]> git.saurik.com Git - apple/xnu.git/blame - bsd/hfs/hfs_vfsops.c
xnu-1228.0.2.tar.gz
[apple/xnu.git] / bsd / hfs / hfs_vfsops.c
CommitLineData
1c79356b 1/*
2d21ac55 2 * Copyright (c) 1999-2007 Apple Inc. All rights reserved.
1c79356b 3 *
2d21ac55 4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
1c79356b 5 *
2d21ac55
A
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.
8f6c56a5 14 *
2d21ac55
A
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
17 *
18 * The Original Code and all software distributed under the License are
19 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
8f6c56a5
A
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
2d21ac55
A
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.
8f6c56a5 25 *
2d21ac55 26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
1c79356b
A
27 */
28/*
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.
36 *
37 * Redistribution and use in source and binary forms, with or without
38 * modification, are permitted provided that the following conditions
39 * are met:
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.
52 *
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
63 * SUCH DAMAGE.
64 *
65 * hfs_vfsops.c
66 * derived from @(#)ufs_vfsops.c 8.8 (Berkeley) 5/20/95
67 *
9bccf70c 68 * (c) Copyright 1997-2002 Apple Computer, Inc. All rights reserved.
1c79356b
A
69 *
70 * hfs_vfsops.c -- VFS layer for loadable HFS file system.
71 *
1c79356b
A
72 */
73#include <sys/param.h>
74#include <sys/systm.h>
91447636 75#include <sys/kauth.h>
1c79356b
A
76
77#include <sys/ubc.h>
91447636
A
78#include <sys/vnode_internal.h>
79#include <sys/mount_internal.h>
55e303ae 80#include <sys/sysctl.h>
1c79356b
A
81#include <sys/malloc.h>
82#include <sys/stat.h>
9bccf70c
A
83#include <sys/quota.h>
84#include <sys/disk.h>
55e303ae
A
85#include <sys/paths.h>
86#include <sys/utfconv.h>
91447636 87#include <sys/kdebug.h>
2d21ac55 88#include <sys/fslog.h>
91447636
A
89
90#include <kern/locks.h>
9bccf70c 91
b4c24cb9
A
92#include <vfs/vfs_journal.h>
93
1c79356b
A
94#include <miscfs/specfs/specdev.h>
95#include <hfs/hfs_mount.h>
96
97#include "hfs.h"
9bccf70c
A
98#include "hfs_catalog.h"
99#include "hfs_cnode.h"
1c79356b
A
100#include "hfs_dbg.h"
101#include "hfs_endian.h"
91447636 102#include "hfs_hotfiles.h"
9bccf70c 103#include "hfs_quota.h"
1c79356b
A
104
105#include "hfscommon/headers/FileMgrInternal.h"
106#include "hfscommon/headers/BTreesInternal.h"
107
108#if HFS_DIAGNOSTIC
109int hfs_dbg_all = 0;
1c79356b 110int hfs_dbg_err = 0;
1c79356b
A
111#endif
112
d52fe63f 113
91447636
A
114lck_grp_attr_t * hfs_group_attr;
115lck_attr_t * hfs_lock_attr;
116lck_grp_t * hfs_mutex_group;
117lck_grp_t * hfs_rwlock_group;
118
1c79356b
A
119extern struct vnodeopv_desc hfs_vnodeop_opv_desc;
120
91447636
A
121static int hfs_changefs(struct mount *mp, struct hfs_mount_args *args);
122static int hfs_fhtovp(struct mount *mp, int fhlen, unsigned char *fhp, struct vnode **vpp, vfs_context_t context);
123static int hfs_flushfiles(struct mount *, int, struct proc *);
124static int hfs_flushMDB(struct hfsmount *hfsmp, int waitfor, int altflush);
125static int hfs_getmountpoint(struct vnode *vp, struct hfsmount **hfsmpp);
126static int hfs_init(struct vfsconf *vfsp);
127static int hfs_mount(struct mount *mp, vnode_t devvp, user_addr_t data, vfs_context_t context);
2d21ac55
A
128static int hfs_mountfs(struct vnode *devvp, struct mount *mp, struct hfs_mount_args *args, int journal_replay_only, vfs_context_t context);
129static int hfs_reload(struct mount *mp);
91447636
A
130static int hfs_vfs_root(struct mount *mp, struct vnode **vpp, vfs_context_t context);
131static int hfs_quotactl(struct mount *, int, uid_t, caddr_t, vfs_context_t context);
132static int hfs_start(struct mount *mp, int flags, vfs_context_t context);
133static int hfs_statfs(struct mount *mp, register struct vfsstatfs *sbp, vfs_context_t context);
134static int hfs_sync(struct mount *mp, int waitfor, vfs_context_t context);
135static int hfs_sysctl(int *name, u_int namelen, user_addr_t oldp, size_t *oldlenp,
136 user_addr_t newp, size_t newlen, vfs_context_t context);
137static int hfs_unmount(struct mount *mp, int mntflags, vfs_context_t context);
138static int hfs_vfs_vget(struct mount *mp, ino64_t ino, struct vnode **vpp, vfs_context_t context);
139static int hfs_vptofh(struct vnode *vp, int *fhlenp, unsigned char *fhp, vfs_context_t context);
140
2d21ac55 141static int hfs_reclaimspace(struct hfsmount *hfsmp, u_long startblk, u_long reclaimblks, vfs_context_t context);
0c530ab8
A
142static int hfs_overlapped_overflow_extents(struct hfsmount *hfsmp, u_int32_t startblk,
143 u_int32_t catblks, u_int32_t fileID, int rsrcfork);
2d21ac55 144static int hfs_journal_replay(const char *devnode, vfs_context_t context);
1c79356b
A
145
146
147/*
148 * Called by vfs_mountroot when mounting HFS Plus as root.
149 */
91447636 150
55e303ae 151__private_extern__
1c79356b 152int
91447636 153hfs_mountroot(mount_t mp, vnode_t rvp, vfs_context_t context)
1c79356b 154{
1c79356b 155 struct hfsmount *hfsmp;
9bccf70c 156 ExtendedVCB *vcb;
91447636 157 struct vfsstatfs *vfsp;
1c79356b 158 int error;
2d21ac55
A
159
160 hfs_chashinit_finish();
1c79356b 161
2d21ac55 162 if ((error = hfs_mountfs(rvp, mp, NULL, 0, context)))
1c79356b 163 return (error);
55e303ae 164
1c79356b
A
165 /* Init hfsmp */
166 hfsmp = VFSTOHFS(mp);
167
0b4e3aa0
A
168 hfsmp->hfs_uid = UNKNOWNUID;
169 hfsmp->hfs_gid = UNKNOWNGID;
170 hfsmp->hfs_dir_mask = (S_IRWXU | S_IRGRP|S_IXGRP | S_IROTH|S_IXOTH); /* 0755 */
171 hfsmp->hfs_file_mask = (S_IRWXU | S_IRGRP|S_IXGRP | S_IROTH|S_IXOTH); /* 0755 */
1c79356b 172
9bccf70c
A
173 /* Establish the free block reserve. */
174 vcb = HFSTOVCB(hfsmp);
175 vcb->reserveBlocks = ((u_int64_t)vcb->totalBlocks * HFS_MINFREE) / 100;
176 vcb->reserveBlocks = MIN(vcb->reserveBlocks, HFS_MAXRESERVE / vcb->blockSize);
177
91447636
A
178 vfsp = vfs_statfs(mp);
179 (void)hfs_statfs(mp, vfsp, NULL);
180
1c79356b
A
181 return (0);
182}
183
184
185/*
186 * VFS Operations.
187 *
188 * mount system call
189 */
190
9bccf70c 191static int
91447636 192hfs_mount(struct mount *mp, vnode_t devvp, user_addr_t data, vfs_context_t context)
1c79356b 193{
91447636 194 struct proc *p = vfs_context_proc(context);
1c79356b 195 struct hfsmount *hfsmp = NULL;
1c79356b 196 struct hfs_mount_args args;
1c79356b 197 int retval = E_NONE;
2d21ac55 198 u_int32_t cmdflags;
1c79356b 199
91447636
A
200 if ((retval = copyin(data, (caddr_t)&args, sizeof(args)))) {
201 return (retval);
202 }
2d21ac55 203 cmdflags = (u_int32_t)vfs_flags(mp) & MNT_CMDFLAGS;
91447636 204 if (cmdflags & MNT_UPDATE) {
1c79356b 205 hfsmp = VFSTOHFS(mp);
91447636
A
206
207 /* Reload incore data after an fsck. */
208 if (cmdflags & MNT_RELOAD) {
209 if (vfs_isrdonly(mp))
2d21ac55 210 return hfs_reload(mp);
91447636
A
211 else
212 return (EINVAL);
213 }
214
215 /* Change to a read-only file system. */
55e303ae 216 if (((hfsmp->hfs_flags & HFS_READ_ONLY) == 0) &&
91447636
A
217 vfs_isrdonly(mp)) {
218 int flags;
219
1c79356b 220 /* use VFS_SYNC to push out System (btree) files */
91447636
A
221 retval = VFS_SYNC(mp, MNT_WAIT, context);
222 if (retval && ((cmdflags & MNT_FORCE) == 0))
223 goto out;
1c79356b
A
224
225 flags = WRITECLOSE;
91447636 226 if (cmdflags & MNT_FORCE)
1c79356b
A
227 flags |= FORCECLOSE;
228
9bccf70c 229 if ((retval = hfs_flushfiles(mp, flags, p)))
91447636 230 goto out;
55e303ae 231 hfsmp->hfs_flags |= HFS_READ_ONLY;
9bccf70c 232 retval = hfs_flushvolumeheader(hfsmp, MNT_WAIT, 0);
1c79356b
A
233
234 /* also get the volume bitmap blocks */
91447636
A
235 if (!retval) {
236 if (vnode_mount(hfsmp->hfs_devvp) == mp) {
237 retval = hfs_fsync(hfsmp->hfs_devvp, MNT_WAIT, 0, p);
238 } else {
239 vnode_get(hfsmp->hfs_devvp);
240 retval = VNOP_FSYNC(hfsmp->hfs_devvp, MNT_WAIT, context);
241 vnode_put(hfsmp->hfs_devvp);
242 }
243 }
1c79356b 244 if (retval) {
55e303ae 245 hfsmp->hfs_flags &= ~HFS_READ_ONLY;
91447636 246 goto out;
1c79356b 247 }
55e303ae
A
248 if (hfsmp->jnl) {
249 hfs_global_exclusive_lock_acquire(hfsmp);
250
251 journal_close(hfsmp->jnl);
252 hfsmp->jnl = NULL;
253
254 // Note: we explicitly don't want to shutdown
255 // access to the jvp because we may need
256 // it later if we go back to being read-write.
257
258 hfs_global_exclusive_lock_release(hfsmp);
259 }
1c79356b
A
260 }
261
91447636
A
262 /* Change to a writable file system. */
263 if (vfs_iswriteupgrade(mp)) {
2d21ac55
A
264
265 /*
266 * On inconsistent disks, do not allow read-write mount
267 * unless it is the boot volume being mounted.
268 */
269 if (!(vfs_flags(mp) & MNT_ROOTFS) &&
270 (hfsmp->vcbAtrb & kHFSVolumeInconsistentMask)) {
271 retval = EINVAL;
272 goto out;
273 }
274
275
9bccf70c 276 retval = hfs_flushvolumeheader(hfsmp, MNT_WAIT, 0);
1c79356b 277 if (retval != E_NONE)
91447636 278 goto out;
1c79356b 279
55e303ae
A
280 // If the journal was shut-down previously because we were
281 // asked to be read-only, let's start it back up again now
282
283 if ( (HFSTOVCB(hfsmp)->vcbAtrb & kHFSVolumeJournaledMask)
284 && hfsmp->jnl == NULL
285 && hfsmp->jvp != NULL) {
91447636 286 int jflags;
55e303ae
A
287
288 if (hfsmp->hfs_flags & HFS_NEED_JNL_RESET) {
91447636 289 jflags = JOURNAL_RESET;
55e303ae 290 } else {
91447636 291 jflags = 0;
55e303ae
A
292 }
293
294 hfs_global_exclusive_lock_acquire(hfsmp);
295
296 hfsmp->jnl = journal_open(hfsmp->jvp,
297 (hfsmp->jnl_start * HFSTOVCB(hfsmp)->blockSize) + (off_t)HFSTOVCB(hfsmp)->hfsPlusIOPosOffset,
298 hfsmp->jnl_size,
299 hfsmp->hfs_devvp,
300 hfsmp->hfs_phys_block_size,
91447636 301 jflags,
55e303ae
A
302 0,
303 hfs_sync_metadata, hfsmp->hfs_mp);
304
305 hfs_global_exclusive_lock_release(hfsmp);
306
307 if (hfsmp->jnl == NULL) {
308 retval = EINVAL;
91447636 309 goto out;
55e303ae
A
310 } else {
311 hfsmp->hfs_flags &= ~HFS_NEED_JNL_RESET;
312 }
313
314 }
315
316 /* Only clear HFS_READ_ONLY after a successfull write */
317 hfsmp->hfs_flags &= ~HFS_READ_ONLY;
1c79356b 318
91447636 319 if (!(hfsmp->hfs_flags & (HFS_READ_ONLY & HFS_STANDARD))) {
2d21ac55
A
320 /* Setup private/hidden directories for hardlinks. */
321 hfs_privatedir_init(hfsmp, FILE_HARDLINKS);
322 hfs_privatedir_init(hfsmp, DIR_HARDLINKS);
323
b4c24cb9 324 hfs_remove_orphans(hfsmp);
91447636
A
325
326 /*
327 * Allow hot file clustering if conditions allow.
328 */
329 if (hfsmp->hfs_flags & HFS_METADATA_ZONE) {
330 (void) hfs_recording_init(hfsmp);
331 }
2d21ac55
A
332 /* Force ACLs on HFS+ file systems. */
333 if (vfs_extendedsecurity(HFSTOVFS(hfsmp)) == 0) {
334 vfs_setextendedsecurity(HFSTOVFS(hfsmp));
335 }
55e303ae 336 }
1c79356b
A
337 }
338
91447636
A
339 /* Update file system parameters. */
340 retval = hfs_changefs(mp, &args);
1c79356b 341
91447636 342 } else /* not an update request */ {
1c79356b 343
91447636 344 /* Set the mount flag to indicate that we support volfs */
2d21ac55 345 vfs_setflags(mp, (u_int64_t)((unsigned int)MNT_DOVOLFS));
1c79356b 346
2d21ac55
A
347 hfs_chashinit_finish();
348
349 retval = hfs_mountfs(devvp, mp, &args, 0, context);
1c79356b 350 }
91447636
A
351out:
352 if (retval == 0) {
353 (void)hfs_statfs(mp, vfs_statfs(mp), context);
1c79356b 354 }
91447636
A
355 return (retval);
356}
1c79356b 357
1c79356b 358
91447636
A
359struct hfs_changefs_cargs {
360 struct hfsmount *hfsmp;
361 int namefix;
362 int permfix;
363 int permswitch;
364};
1c79356b 365
91447636
A
366static int
367hfs_changefs_callback(struct vnode *vp, void *cargs)
368{
369 ExtendedVCB *vcb;
370 struct cnode *cp;
371 struct cat_desc cndesc;
372 struct cat_attr cnattr;
373 struct hfs_changefs_cargs *args;
1c79356b 374
91447636 375 args = (struct hfs_changefs_cargs *)cargs;
b4c24cb9 376
91447636
A
377 cp = VTOC(vp);
378 vcb = HFSTOVCB(args->hfsmp);
1c79356b 379
91447636
A
380 if (cat_lookup(args->hfsmp, &cp->c_desc, 0, &cndesc, &cnattr, NULL, NULL)) {
381 /*
382 * If we couldn't find this guy skip to the next one
383 */
384 if (args->namefix)
385 cache_purge(vp);
1c79356b 386
91447636
A
387 return (VNODE_RETURNED);
388 }
389 /*
390 * Get the real uid/gid and perm mask from disk.
391 */
392 if (args->permswitch || args->permfix) {
393 cp->c_uid = cnattr.ca_uid;
394 cp->c_gid = cnattr.ca_gid;
395 cp->c_mode = cnattr.ca_mode;
396 }
397 /*
398 * If we're switching name converters then...
399 * Remove the existing entry from the namei cache.
400 * Update name to one based on new encoder.
401 */
402 if (args->namefix) {
403 cache_purge(vp);
404 replace_desc(cp, &cndesc);
1c79356b 405
91447636 406 if (cndesc.cd_cnid == kHFSRootFolderID) {
2d21ac55 407 strlcpy((char *)vcb->vcbVN, (const char *)cp->c_desc.cd_nameptr, NAME_MAX+1);
91447636
A
408 cp->c_desc.cd_encoding = args->hfsmp->hfs_encoding;
409 }
410 } else {
411 cat_releasedesc(&cndesc);
412 }
413 return (VNODE_RETURNED);
414}
1c79356b 415
9bccf70c
A
416/* Change fs mount parameters */
417static int
91447636 418hfs_changefs(struct mount *mp, struct hfs_mount_args *args)
1c79356b 419{
9bccf70c 420 int retval = 0;
1c79356b
A
421 int namefix, permfix, permswitch;
422 struct hfsmount *hfsmp;
1c79356b 423 ExtendedVCB *vcb;
1c79356b
A
424 hfs_to_unicode_func_t get_unicode_func;
425 unicode_to_hfs_func_t get_hfsname_func;
91447636
A
426 u_long old_encoding = 0;
427 struct hfs_changefs_cargs cargs;
2d21ac55 428 u_int32_t mount_flags;
1c79356b
A
429
430 hfsmp = VFSTOHFS(mp);
431 vcb = HFSTOVCB(hfsmp);
91447636
A
432 mount_flags = (unsigned int)vfs_flags(mp);
433
55e303ae 434 permswitch = (((hfsmp->hfs_flags & HFS_UNKNOWN_PERMS) &&
91447636 435 ((mount_flags & MNT_UNKNOWNPERMISSIONS) == 0)) ||
55e303ae 436 (((hfsmp->hfs_flags & HFS_UNKNOWN_PERMS) == 0) &&
91447636 437 (mount_flags & MNT_UNKNOWNPERMISSIONS)));
55e303ae 438
0b4e3aa0 439 /* The root filesystem must operate with actual permissions: */
91447636 440 if (permswitch && (mount_flags & MNT_ROOTFS) && (mount_flags & MNT_UNKNOWNPERMISSIONS)) {
2d21ac55 441 vfs_clearflags(mp, (u_int64_t)((unsigned int)MNT_UNKNOWNPERMISSIONS)); /* Just say "No". */
0b4e3aa0 442 return EINVAL;
55e303ae 443 }
91447636 444 if (mount_flags & MNT_UNKNOWNPERMISSIONS)
55e303ae
A
445 hfsmp->hfs_flags |= HFS_UNKNOWN_PERMS;
446 else
447 hfsmp->hfs_flags &= ~HFS_UNKNOWN_PERMS;
448
449 namefix = permfix = 0;
1c79356b 450
2d21ac55
A
451 /*
452 * Tracking of hot files requires up-to-date access times. So if
453 * access time updates are disabled, we must also disable hot files.
454 */
455 if (mount_flags & MNT_NOATIME) {
456 (void) hfs_recording_suspend(hfsmp);
457 }
458
9bccf70c 459 /* Change the timezone (Note: this affects all hfs volumes and hfs+ volume create dates) */
1c79356b
A
460 if (args->hfs_timezone.tz_minuteswest != VNOVAL) {
461 gTimeZone = args->hfs_timezone;
462 }
463
9bccf70c 464 /* Change the default uid, gid and/or mask */
1c79356b
A
465 if ((args->hfs_uid != (uid_t)VNOVAL) && (hfsmp->hfs_uid != args->hfs_uid)) {
466 hfsmp->hfs_uid = args->hfs_uid;
91447636 467 if (vcb->vcbSigWord == kHFSPlusSigWord)
9bccf70c 468 ++permfix;
1c79356b
A
469 }
470 if ((args->hfs_gid != (gid_t)VNOVAL) && (hfsmp->hfs_gid != args->hfs_gid)) {
471 hfsmp->hfs_gid = args->hfs_gid;
91447636 472 if (vcb->vcbSigWord == kHFSPlusSigWord)
9bccf70c 473 ++permfix;
1c79356b
A
474 }
475 if (args->hfs_mask != (mode_t)VNOVAL) {
476 if (hfsmp->hfs_dir_mask != (args->hfs_mask & ALLPERMS)) {
477 hfsmp->hfs_dir_mask = args->hfs_mask & ALLPERMS;
478 hfsmp->hfs_file_mask = args->hfs_mask & ALLPERMS;
479 if ((args->flags != VNOVAL) && (args->flags & HFSFSMNT_NOXONFILES))
480 hfsmp->hfs_file_mask = (args->hfs_mask & DEFFILEMODE);
91447636 481 if (vcb->vcbSigWord == kHFSPlusSigWord)
9bccf70c 482 ++permfix;
1c79356b
A
483 }
484 }
485
9bccf70c 486 /* Change the hfs encoding value (hfs only) */
91447636 487 if ((vcb->vcbSigWord == kHFSSigWord) &&
55e303ae 488 (args->hfs_encoding != (u_long)VNOVAL) &&
1c79356b
A
489 (hfsmp->hfs_encoding != args->hfs_encoding)) {
490
491 retval = hfs_getconverter(args->hfs_encoding, &get_unicode_func, &get_hfsname_func);
9bccf70c
A
492 if (retval)
493 goto exit;
1c79356b
A
494
495 /*
496 * Connect the new hfs_get_unicode converter but leave
497 * the old hfs_get_hfsname converter in place so that
498 * we can lookup existing vnodes to get their correctly
499 * encoded names.
500 *
501 * When we're all finished, we can then connect the new
502 * hfs_get_hfsname converter and release our interest
503 * in the old converters.
504 */
505 hfsmp->hfs_get_unicode = get_unicode_func;
9bccf70c
A
506 old_encoding = hfsmp->hfs_encoding;
507 hfsmp->hfs_encoding = args->hfs_encoding;
1c79356b
A
508 ++namefix;
509 }
510
9bccf70c
A
511 if (!(namefix || permfix || permswitch))
512 goto exit;
1c79356b 513
91447636
A
514 /* XXX 3762912 hack to support HFS filesystem 'owner' */
515 if (permfix)
516 vfs_setowner(mp,
517 hfsmp->hfs_uid == UNKNOWNUID ? KAUTH_UID_NONE : hfsmp->hfs_uid,
518 hfsmp->hfs_gid == UNKNOWNGID ? KAUTH_GID_NONE : hfsmp->hfs_gid);
519
1c79356b
A
520 /*
521 * For each active vnode fix things that changed
522 *
523 * Note that we can visit a vnode more than once
524 * and we can race with fsync.
91447636
A
525 *
526 * hfs_changefs_callback will be called for each vnode
527 * hung off of this mount point
528 * the vnode will be
529 * properly referenced and unreferenced around the callback
1c79356b 530 */
91447636
A
531 cargs.hfsmp = hfsmp;
532 cargs.namefix = namefix;
533 cargs.permfix = permfix;
534 cargs.permswitch = permswitch;
1c79356b 535
91447636 536 vnode_iterate(mp, 0, hfs_changefs_callback, (void *)&cargs);
1c79356b 537
1c79356b
A
538 /*
539 * If we're switching name converters we can now
540 * connect the new hfs_get_hfsname converter and
541 * release our interest in the old converters.
542 */
543 if (namefix) {
1c79356b 544 hfsmp->hfs_get_hfsname = get_hfsname_func;
1c79356b 545 vcb->volumeNameEncodingHint = args->hfs_encoding;
1c79356b
A
546 (void) hfs_relconverter(old_encoding);
547 }
9bccf70c 548exit:
1c79356b
A
549 return (retval);
550}
551
552
91447636
A
553struct hfs_reload_cargs {
554 struct hfsmount *hfsmp;
91447636
A
555 int error;
556};
557
558static int
559hfs_reload_callback(struct vnode *vp, void *cargs)
560{
561 struct cnode *cp;
562 struct hfs_reload_cargs *args;
563
564 args = (struct hfs_reload_cargs *)cargs;
565 /*
566 * flush all the buffers associated with this node
567 */
568 (void) buf_invalidateblks(vp, 0, 0, 0);
569
570 cp = VTOC(vp);
571 /*
572 * Remove any directory hints
573 */
574 if (vnode_isdir(vp))
575 hfs_reldirhints(cp, 0);
576
577 /*
578 * Re-read cnode data for all active vnodes (non-metadata files).
579 */
743b1565 580 if (!vnode_issystem(vp) && !VNODE_IS_RSRC(vp)) {
91447636
A
581 struct cat_fork *datafork;
582 struct cat_desc desc;
583
584 datafork = cp->c_datafork ? &cp->c_datafork->ff_data : NULL;
585
586 /* lookup by fileID since name could have changed */
2d21ac55 587 if ((args->error = cat_idlookup(args->hfsmp, cp->c_fileid, 0, &desc, &cp->c_attr, datafork)))
91447636
A
588 return (VNODE_RETURNED_DONE);
589
590 /* update cnode's catalog descriptor */
591 (void) replace_desc(cp, &desc);
592 }
593 return (VNODE_RETURNED);
594}
595
1c79356b
A
596/*
597 * Reload all incore data for a filesystem (used after running fsck on
598 * the root filesystem and finding things to fix). The filesystem must
599 * be mounted read-only.
600 *
601 * Things to do to update the mount:
9bccf70c
A
602 * invalidate all cached meta-data.
603 * invalidate all inactive vnodes.
604 * invalidate all cached file data.
605 * re-read volume header from disk.
606 * re-load meta-file info (extents, file size).
607 * re-load B-tree header data.
608 * re-read cnode data for all active vnodes.
1c79356b 609 */
9bccf70c 610static int
2d21ac55 611hfs_reload(struct mount *mountp)
1c79356b 612{
91447636 613 register struct vnode *devvp;
1c79356b 614 struct buf *bp;
d52fe63f
A
615 int sectorsize;
616 int error, i;
1c79356b
A
617 struct hfsmount *hfsmp;
618 struct HFSPlusVolumeHeader *vhp;
619 ExtendedVCB *vcb;
9bccf70c
A
620 struct filefork *forkp;
621 struct cat_desc cndesc;
91447636 622 struct hfs_reload_cargs args;
1c79356b
A
623
624 hfsmp = VFSTOHFS(mountp);
625 vcb = HFSTOVCB(hfsmp);
626
627 if (vcb->vcbSigWord == kHFSSigWord)
628 return (EINVAL); /* rooting from HFS is not supported! */
629
630 /*
631 * Invalidate all cached meta-data.
632 */
633 devvp = hfsmp->hfs_devvp;
91447636 634 if (buf_invalidateblks(devvp, 0, 0, 0))
1c79356b 635 panic("hfs_reload: dirty1");
9bccf70c 636
91447636 637 args.hfsmp = hfsmp;
91447636
A
638 args.error = 0;
639 /*
640 * hfs_reload_callback will be called for each vnode
641 * hung off of this mount point that can't be recycled...
642 * vnode_iterate will recycle those that it can (the VNODE_RELOAD option)
643 * the vnode will be in an 'unbusy' state (VNODE_WAIT) and
644 * properly referenced and unreferenced around the callback
645 */
91447636 646 vnode_iterate(mountp, VNODE_RELOAD | VNODE_WAIT, hfs_reload_callback, (void *)&args);
9bccf70c 647
91447636
A
648 if (args.error)
649 return (args.error);
9bccf70c 650
1c79356b
A
651 /*
652 * Re-read VolumeHeader from disk.
653 */
d52fe63f
A
654 sectorsize = hfsmp->hfs_phys_block_size;
655
91447636
A
656 error = (int)buf_meta_bread(hfsmp->hfs_devvp,
657 (daddr64_t)((vcb->hfsPlusIOPosOffset / sectorsize) + HFS_PRI_SECTOR(sectorsize)),
d52fe63f 658 sectorsize, NOCRED, &bp);
1c79356b
A
659 if (error) {
660 if (bp != NULL)
91447636 661 buf_brelse(bp);
1c79356b
A
662 return (error);
663 }
664
91447636 665 vhp = (HFSPlusVolumeHeader *) (buf_dataptr(bp) + HFS_PRI_OFFSET(sectorsize));
1c79356b 666
9bccf70c 667 /* Do a quick sanity check */
55e303ae
A
668 if ((SWAP_BE16(vhp->signature) != kHFSPlusSigWord &&
669 SWAP_BE16(vhp->signature) != kHFSXSigWord) ||
670 (SWAP_BE16(vhp->version) != kHFSPlusVersion &&
671 SWAP_BE16(vhp->version) != kHFSXVersion) ||
9bccf70c 672 SWAP_BE32(vhp->blockSize) != vcb->blockSize) {
91447636 673 buf_brelse(bp);
9bccf70c 674 return (EIO);
1c79356b
A
675 }
676
9bccf70c 677 vcb->vcbLsMod = to_bsd_time(SWAP_BE32(vhp->modifyDate));
91447636 678 vcb->vcbAtrb = SWAP_BE32 (vhp->attributes);
b4c24cb9 679 vcb->vcbJinfoBlock = SWAP_BE32(vhp->journalInfoBlock);
9bccf70c
A
680 vcb->vcbClpSiz = SWAP_BE32 (vhp->rsrcClumpSize);
681 vcb->vcbNxtCNID = SWAP_BE32 (vhp->nextCatalogID);
682 vcb->vcbVolBkUp = to_bsd_time(SWAP_BE32(vhp->backupDate));
683 vcb->vcbWrCnt = SWAP_BE32 (vhp->writeCount);
684 vcb->vcbFilCnt = SWAP_BE32 (vhp->fileCount);
685 vcb->vcbDirCnt = SWAP_BE32 (vhp->folderCount);
2d21ac55 686 HFS_UPDATE_NEXT_ALLOCATION(vcb, SWAP_BE32 (vhp->nextAllocation));
9bccf70c
A
687 vcb->totalBlocks = SWAP_BE32 (vhp->totalBlocks);
688 vcb->freeBlocks = SWAP_BE32 (vhp->freeBlocks);
1c79356b
A
689 vcb->encodingsBitmap = SWAP_BE64 (vhp->encodingsBitmap);
690 bcopy(vhp->finderInfo, vcb->vcbFndrInfo, sizeof(vhp->finderInfo));
691 vcb->localCreateDate = SWAP_BE32 (vhp->createDate); /* hfs+ create date is in local time */
692
693 /*
694 * Re-load meta-file vnode data (extent info, file size, etc).
695 */
9bccf70c
A
696 forkp = VTOF((struct vnode *)vcb->extentsRefNum);
697 for (i = 0; i < kHFSPlusExtentDensity; i++) {
698 forkp->ff_extents[i].startBlock =
699 SWAP_BE32 (vhp->extentsFile.extents[i].startBlock);
700 forkp->ff_extents[i].blockCount =
701 SWAP_BE32 (vhp->extentsFile.extents[i].blockCount);
702 }
703 forkp->ff_size = SWAP_BE64 (vhp->extentsFile.logicalSize);
704 forkp->ff_blocks = SWAP_BE32 (vhp->extentsFile.totalBlocks);
705 forkp->ff_clumpsize = SWAP_BE32 (vhp->extentsFile.clumpSize);
706
707
708 forkp = VTOF((struct vnode *)vcb->catalogRefNum);
709 for (i = 0; i < kHFSPlusExtentDensity; i++) {
710 forkp->ff_extents[i].startBlock =
711 SWAP_BE32 (vhp->catalogFile.extents[i].startBlock);
712 forkp->ff_extents[i].blockCount =
713 SWAP_BE32 (vhp->catalogFile.extents[i].blockCount);
714 }
715 forkp->ff_size = SWAP_BE64 (vhp->catalogFile.logicalSize);
716 forkp->ff_blocks = SWAP_BE32 (vhp->catalogFile.totalBlocks);
717 forkp->ff_clumpsize = SWAP_BE32 (vhp->catalogFile.clumpSize);
718
91447636
A
719 if (hfsmp->hfs_attribute_vp) {
720 forkp = VTOF(hfsmp->hfs_attribute_vp);
721 for (i = 0; i < kHFSPlusExtentDensity; i++) {
722 forkp->ff_extents[i].startBlock =
723 SWAP_BE32 (vhp->attributesFile.extents[i].startBlock);
724 forkp->ff_extents[i].blockCount =
725 SWAP_BE32 (vhp->attributesFile.extents[i].blockCount);
726 }
727 forkp->ff_size = SWAP_BE64 (vhp->attributesFile.logicalSize);
728 forkp->ff_blocks = SWAP_BE32 (vhp->attributesFile.totalBlocks);
729 forkp->ff_clumpsize = SWAP_BE32 (vhp->attributesFile.clumpSize);
730 }
9bccf70c
A
731
732 forkp = VTOF((struct vnode *)vcb->allocationsRefNum);
733 for (i = 0; i < kHFSPlusExtentDensity; i++) {
734 forkp->ff_extents[i].startBlock =
735 SWAP_BE32 (vhp->allocationFile.extents[i].startBlock);
736 forkp->ff_extents[i].blockCount =
737 SWAP_BE32 (vhp->allocationFile.extents[i].blockCount);
738 }
739 forkp->ff_size = SWAP_BE64 (vhp->allocationFile.logicalSize);
740 forkp->ff_blocks = SWAP_BE32 (vhp->allocationFile.totalBlocks);
741 forkp->ff_clumpsize = SWAP_BE32 (vhp->allocationFile.clumpSize);
1c79356b 742
91447636 743 buf_brelse(bp);
1c79356b
A
744 vhp = NULL;
745
746 /*
747 * Re-load B-tree header data
748 */
9bccf70c 749 forkp = VTOF((struct vnode *)vcb->extentsRefNum);
91447636 750 if ( (error = MacToVFSError( BTReloadData((FCB*)forkp) )) )
1c79356b
A
751 return (error);
752
9bccf70c 753 forkp = VTOF((struct vnode *)vcb->catalogRefNum);
91447636 754 if ( (error = MacToVFSError( BTReloadData((FCB*)forkp) )) )
1c79356b
A
755 return (error);
756
91447636
A
757 if (hfsmp->hfs_attribute_vp) {
758 forkp = VTOF(hfsmp->hfs_attribute_vp);
759 if ( (error = MacToVFSError( BTReloadData((FCB*)forkp) )) )
760 return (error);
761 }
762
9bccf70c 763 /* Reload the volume name */
2d21ac55 764 if ((error = cat_idlookup(hfsmp, kHFSRootFolderID, 0, &cndesc, NULL, NULL)))
1c79356b 765 return (error);
9bccf70c
A
766 vcb->volumeNameEncodingHint = cndesc.cd_encoding;
767 bcopy(cndesc.cd_nameptr, vcb->vcbVN, min(255, cndesc.cd_namelen));
768 cat_releasedesc(&cndesc);
1c79356b 769
2d21ac55
A
770 /* Re-establish private/hidden directories. */
771 hfs_privatedir_init(hfsmp, FILE_HARDLINKS);
772 hfs_privatedir_init(hfsmp, DIR_HARDLINKS);
1c79356b 773
55e303ae
A
774 /* In case any volume information changed to trigger a notification */
775 hfs_generate_volume_notifications(hfsmp);
776
1c79356b
A
777 return (0);
778}
779
780
781/*
782 * Common code for mount and mountroot
783 */
9bccf70c 784static int
91447636 785hfs_mountfs(struct vnode *devvp, struct mount *mp, struct hfs_mount_args *args,
2d21ac55 786 int journal_replay_only, vfs_context_t context)
1c79356b 787{
91447636 788 struct proc *p = vfs_context_proc(context);
9bccf70c
A
789 int retval = E_NONE;
790 struct hfsmount *hfsmp;
791 struct buf *bp;
792 dev_t dev;
793 HFSMasterDirectoryBlock *mdbp;
794 int ronly;
2d21ac55 795#if QUOTA
9bccf70c 796 int i;
2d21ac55 797#endif
9bccf70c 798 int mntwrapper;
91447636 799 kauth_cred_t cred;
d52fe63f 800 u_int64_t disksize;
91447636 801 daddr64_t blkcnt;
d52fe63f
A
802 u_int32_t blksize;
803 u_int32_t minblksize;
9bccf70c 804 u_int32_t iswritable;
91447636 805 daddr64_t mdb_offset;
2d21ac55 806 int isvirtual = 0;
1c79356b 807
91447636
A
808 ronly = vfs_isrdonly(mp);
809 dev = vnode_specrdev(devvp);
810 cred = p ? vfs_context_ucred(context) : NOCRED;
9bccf70c 811 mntwrapper = 0;
1c79356b 812
d52fe63f
A
813 bp = NULL;
814 hfsmp = NULL;
9bccf70c 815 mdbp = NULL;
d52fe63f 816 minblksize = kHFSBlockSize;
1c79356b 817
91447636
A
818 /* Advisory locking should be handled at the VFS layer */
819 vfs_setlocklocal(mp);
820
d52fe63f 821 /* Get the real physical block size. */
91447636 822 if (VNOP_IOCTL(devvp, DKIOCGETBLOCKSIZE, (caddr_t)&blksize, 0, context)) {
d52fe63f
A
823 retval = ENXIO;
824 goto error_exit;
825 }
826 /* Switch to 512 byte sectors (temporarily) */
827 if (blksize > 512) {
828 u_int32_t size512 = 512;
829
91447636 830 if (VNOP_IOCTL(devvp, DKIOCSETBLOCKSIZE, (caddr_t)&size512, FWRITE, context)) {
d52fe63f
A
831 retval = ENXIO;
832 goto error_exit;
833 }
834 }
835 /* Get the number of 512 byte physical blocks. */
91447636 836 if (VNOP_IOCTL(devvp, DKIOCGETBLOCKCOUNT, (caddr_t)&blkcnt, 0, context)) {
2d21ac55
A
837 /* resetting block size may fail if getting block count did */
838 (void)VNOP_IOCTL(devvp, DKIOCSETBLOCKSIZE, (caddr_t)&blksize, FWRITE, context);
839
d52fe63f
A
840 retval = ENXIO;
841 goto error_exit;
842 }
843 /* Compute an accurate disk size (i.e. within 512 bytes) */
91447636 844 disksize = (u_int64_t)blkcnt * (u_int64_t)512;
1c79356b 845
d52fe63f 846 /*
91447636
A
847 * On Tiger it is not necessary to switch the device
848 * block size to be 4k if there are more than 31-bits
849 * worth of blocks but to insure compatibility with
850 * pre-Tiger systems we have to do it.
1c79356b 851 */
2d21ac55 852 if (blkcnt > 0x000000007fffffff) {
d52fe63f
A
853 minblksize = blksize = 4096;
854 }
91447636 855
2d21ac55 856 /* Now switch to our preferred physical block size. */
d52fe63f 857 if (blksize > 512) {
91447636 858 if (VNOP_IOCTL(devvp, DKIOCSETBLOCKSIZE, (caddr_t)&blksize, FWRITE, context)) {
d52fe63f
A
859 retval = ENXIO;
860 goto error_exit;
861 }
862 /* Get the count of physical blocks. */
91447636 863 if (VNOP_IOCTL(devvp, DKIOCGETBLOCKCOUNT, (caddr_t)&blkcnt, 0, context)) {
d52fe63f
A
864 retval = ENXIO;
865 goto error_exit;
866 }
867 }
d52fe63f
A
868 /*
869 * At this point:
870 * minblksize is the minimum physical block size
2d21ac55 871 * blksize has our preferred physical block size
d52fe63f 872 * blkcnt has the total number of physical blocks
1c79356b 873 */
0b4e3aa0 874
91447636
A
875 mdb_offset = (daddr64_t)HFS_PRI_SECTOR(blksize);
876 if ((retval = (int)buf_meta_bread(devvp, mdb_offset, blksize, cred, &bp))) {
d52fe63f
A
877 goto error_exit;
878 }
9bccf70c 879 MALLOC(mdbp, HFSMasterDirectoryBlock *, kMDBSize, M_TEMP, M_WAITOK);
91447636
A
880 bcopy((char *)buf_dataptr(bp) + HFS_PRI_OFFSET(blksize), mdbp, kMDBSize);
881 buf_brelse(bp);
9bccf70c 882 bp = NULL;
1c79356b 883
d52fe63f
A
884 MALLOC(hfsmp, struct hfsmount *, sizeof(struct hfsmount), M_HFSMNT, M_WAITOK);
885 bzero(hfsmp, sizeof(struct hfsmount));
b4c24cb9 886
9bccf70c 887 /*
91447636
A
888 * Init the volume information structure
889 */
890
891 lck_mtx_init(&hfsmp->hfs_mutex, hfs_mutex_group, hfs_lock_attr);
892 lck_mtx_init(&hfsmp->hfc_mutex, hfs_mutex_group, hfs_lock_attr);
893 lck_rw_init(&hfsmp->hfs_global_lock, hfs_rwlock_group, hfs_lock_attr);
3a60a9f5 894 lck_rw_init(&hfsmp->hfs_insync, hfs_rwlock_group, hfs_lock_attr);
91447636
A
895
896 vfs_setfsprivate(mp, hfsmp);
9bccf70c 897 hfsmp->hfs_mp = mp; /* Make VFSTOHFS work */
91447636 898 hfsmp->hfs_raw_dev = vnode_specrdev(devvp);
9bccf70c 899 hfsmp->hfs_devvp = devvp;
2d21ac55 900 vnode_ref(devvp); /* Hold a ref on the device, dropped when hfsmp is freed. */
9bccf70c
A
901 hfsmp->hfs_phys_block_size = blksize;
902 hfsmp->hfs_phys_block_count = blkcnt;
55e303ae
A
903 hfsmp->hfs_flags |= HFS_WRITEABLE_MEDIA;
904 if (ronly)
905 hfsmp->hfs_flags |= HFS_READ_ONLY;
91447636 906 if (((unsigned int)vfs_flags(mp)) & MNT_UNKNOWNPERMISSIONS)
55e303ae 907 hfsmp->hfs_flags |= HFS_UNKNOWN_PERMS;
2d21ac55
A
908
909#if QUOTA
9bccf70c 910 for (i = 0; i < MAXQUOTAS; i++)
91447636 911 dqfileinit(&hfsmp->hfs_qfiles[i]);
2d21ac55 912#endif
9bccf70c 913
1c79356b
A
914 if (args) {
915 hfsmp->hfs_uid = (args->hfs_uid == (uid_t)VNOVAL) ? UNKNOWNUID : args->hfs_uid;
916 if (hfsmp->hfs_uid == 0xfffffffd) hfsmp->hfs_uid = UNKNOWNUID;
917 hfsmp->hfs_gid = (args->hfs_gid == (gid_t)VNOVAL) ? UNKNOWNGID : args->hfs_gid;
918 if (hfsmp->hfs_gid == 0xfffffffd) hfsmp->hfs_gid = UNKNOWNGID;
91447636 919 vfs_setowner(mp, hfsmp->hfs_uid, hfsmp->hfs_gid); /* tell the VFS */
1c79356b
A
920 if (args->hfs_mask != (mode_t)VNOVAL) {
921 hfsmp->hfs_dir_mask = args->hfs_mask & ALLPERMS;
922 if (args->flags & HFSFSMNT_NOXONFILES) {
923 hfsmp->hfs_file_mask = (args->hfs_mask & DEFFILEMODE);
924 } else {
925 hfsmp->hfs_file_mask = args->hfs_mask & ALLPERMS;
926 }
927 } else {
928 hfsmp->hfs_dir_mask = UNKNOWNPERMISSIONS & ALLPERMS; /* 0777: rwx---rwx */
929 hfsmp->hfs_file_mask = UNKNOWNPERMISSIONS & DEFFILEMODE; /* 0666: no --x by default? */
9bccf70c
A
930 }
931 if ((args->flags != (int)VNOVAL) && (args->flags & HFSFSMNT_WRAPPER))
932 mntwrapper = 1;
1c79356b
A
933 } else {
934 /* Even w/o explicit mount arguments, MNT_UNKNOWNPERMISSIONS requires setting up uid, gid, and mask: */
91447636 935 if (((unsigned int)vfs_flags(mp)) & MNT_UNKNOWNPERMISSIONS) {
1c79356b
A
936 hfsmp->hfs_uid = UNKNOWNUID;
937 hfsmp->hfs_gid = UNKNOWNGID;
91447636 938 vfs_setowner(mp, hfsmp->hfs_uid, hfsmp->hfs_gid); /* tell the VFS */
1c79356b
A
939 hfsmp->hfs_dir_mask = UNKNOWNPERMISSIONS & ALLPERMS; /* 0777: rwx---rwx */
940 hfsmp->hfs_file_mask = UNKNOWNPERMISSIONS & DEFFILEMODE; /* 0666: no --x by default? */
9bccf70c
A
941 }
942 }
943
944 /* Find out if disk media is writable. */
91447636 945 if (VNOP_IOCTL(devvp, DKIOCISWRITABLE, (caddr_t)&iswritable, 0, context) == 0) {
9bccf70c 946 if (iswritable)
55e303ae 947 hfsmp->hfs_flags |= HFS_WRITEABLE_MEDIA;
9bccf70c 948 else
55e303ae 949 hfsmp->hfs_flags &= ~HFS_WRITEABLE_MEDIA;
9bccf70c 950 }
1c79356b 951
91447636 952 // record the current time at which we're mounting this volume
2d21ac55
A
953 struct timeval tv;
954 microtime(&tv);
955 hfsmp->hfs_mount_time = tv.tv_sec;
91447636 956
d52fe63f
A
957 /* Mount a standard HFS disk */
958 if ((SWAP_BE16(mdbp->drSigWord) == kHFSSigWord) &&
9bccf70c 959 (mntwrapper || (SWAP_BE16(mdbp->drEmbedSigWord) != kHFSPlusSigWord))) {
2d21ac55
A
960
961 /* If only journal replay is requested, exit immediately */
962 if (journal_replay_only) {
963 retval = 0;
964 goto error_exit;
965 }
966
91447636 967 if ((vfs_flags(mp) & MNT_ROOTFS)) {
d52fe63f 968 retval = EINVAL; /* Cannot root from HFS standard disks */
1c79356b 969 goto error_exit;
d52fe63f
A
970 }
971 /* HFS disks can only use 512 byte physical blocks */
972 if (blksize > kHFSBlockSize) {
973 blksize = kHFSBlockSize;
91447636 974 if (VNOP_IOCTL(devvp, DKIOCSETBLOCKSIZE, (caddr_t)&blksize, FWRITE, context)) {
d52fe63f
A
975 retval = ENXIO;
976 goto error_exit;
977 }
91447636 978 if (VNOP_IOCTL(devvp, DKIOCGETBLOCKCOUNT, (caddr_t)&blkcnt, 0, context)) {
d52fe63f
A
979 retval = ENXIO;
980 goto error_exit;
981 }
d52fe63f
A
982 hfsmp->hfs_phys_block_size = blksize;
983 hfsmp->hfs_phys_block_count = blkcnt;
984 }
1c79356b
A
985 if (args) {
986 hfsmp->hfs_encoding = args->hfs_encoding;
987 HFSTOVCB(hfsmp)->volumeNameEncodingHint = args->hfs_encoding;
988
1c79356b
A
989 /* establish the timezone */
990 gTimeZone = args->hfs_timezone;
991 }
992
9bccf70c
A
993 retval = hfs_getconverter(hfsmp->hfs_encoding, &hfsmp->hfs_get_unicode,
994 &hfsmp->hfs_get_hfsname);
d52fe63f
A
995 if (retval)
996 goto error_exit;
1c79356b 997
d52fe63f 998 retval = hfs_MountHFSVolume(hfsmp, mdbp, p);
1c79356b
A
999 if (retval)
1000 (void) hfs_relconverter(hfsmp->hfs_encoding);
1001
d52fe63f
A
1002 } else /* Mount an HFS Plus disk */ {
1003 HFSPlusVolumeHeader *vhp;
1004 off_t embeddedOffset;
b4c24cb9 1005 int jnl_disable = 0;
d52fe63f
A
1006
1007 /* Get the embedded Volume Header */
1008 if (SWAP_BE16(mdbp->drEmbedSigWord) == kHFSPlusSigWord) {
1009 embeddedOffset = SWAP_BE16(mdbp->drAlBlSt) * kHFSBlockSize;
1010 embeddedOffset += (u_int64_t)SWAP_BE16(mdbp->drEmbedExtent.startBlock) *
1011 (u_int64_t)SWAP_BE32(mdbp->drAlBlkSiz);
1012
d52fe63f
A
1013 /*
1014 * If the embedded volume doesn't start on a block
1015 * boundary, then switch the device to a 512-byte
1016 * block size so everything will line up on a block
1017 * boundary.
1018 */
1019 if ((embeddedOffset % blksize) != 0) {
1020 printf("HFS Mount: embedded volume offset not"
1021 " a multiple of physical block size (%d);"
1022 " switching to 512\n", blksize);
1023 blksize = 512;
91447636
A
1024 if (VNOP_IOCTL(devvp, DKIOCSETBLOCKSIZE,
1025 (caddr_t)&blksize, FWRITE, context)) {
d52fe63f
A
1026 retval = ENXIO;
1027 goto error_exit;
1028 }
91447636
A
1029 if (VNOP_IOCTL(devvp, DKIOCGETBLOCKCOUNT,
1030 (caddr_t)&blkcnt, 0, context)) {
d52fe63f
A
1031 retval = ENXIO;
1032 goto error_exit;
1033 }
d52fe63f
A
1034 /* Note: relative block count adjustment */
1035 hfsmp->hfs_phys_block_count *=
1036 hfsmp->hfs_phys_block_size / blksize;
1037 hfsmp->hfs_phys_block_size = blksize;
1038 }
1039
9bccf70c
A
1040 disksize = (u_int64_t)SWAP_BE16(mdbp->drEmbedExtent.blockCount) *
1041 (u_int64_t)SWAP_BE32(mdbp->drAlBlkSiz);
1042
1043 hfsmp->hfs_phys_block_count = disksize / blksize;
1044
91447636
A
1045 mdb_offset = (daddr64_t)((embeddedOffset / blksize) + HFS_PRI_SECTOR(blksize));
1046 retval = (int)buf_meta_bread(devvp, mdb_offset, blksize, cred, &bp);
d52fe63f
A
1047 if (retval)
1048 goto error_exit;
91447636
A
1049 bcopy((char *)buf_dataptr(bp) + HFS_PRI_OFFSET(blksize), mdbp, 512);
1050 buf_brelse(bp);
9bccf70c
A
1051 bp = NULL;
1052 vhp = (HFSPlusVolumeHeader*) mdbp;
d52fe63f
A
1053
1054 } else /* pure HFS+ */ {
1055 embeddedOffset = 0;
1056 vhp = (HFSPlusVolumeHeader*) mdbp;
1057 }
1058
2d21ac55
A
1059 /*
1060 * On inconsistent disks, do not allow read-write mount
1061 * unless it is the boot volume being mounted.
1062 */
1063 if (!(vfs_flags(mp) & MNT_ROOTFS) &&
1064 (SWAP_BE32(vhp->attributes) & kHFSVolumeInconsistentMask) &&
1065 !(hfsmp->hfs_flags & HFS_READ_ONLY)) {
1066 retval = EINVAL;
1067 goto error_exit;
1068 }
1069
1070
b4c24cb9
A
1071 // XXXdbg
1072 //
1073 hfsmp->jnl = NULL;
1074 hfsmp->jvp = NULL;
2d21ac55
A
1075 if (args != NULL && (args->flags & HFSFSMNT_EXTENDED_ARGS) &&
1076 args->journal_disable) {
b4c24cb9
A
1077 jnl_disable = 1;
1078 }
1079
1080 //
1081 // We only initialize the journal here if the last person
1082 // to mount this volume was journaling aware. Otherwise
1083 // we delay journal initialization until later at the end
1084 // of hfs_MountHFSPlusVolume() because the last person who
1085 // mounted it could have messed things up behind our back
1086 // (so we need to go find the .journal file, make sure it's
1087 // the right size, re-sync up if it was moved, etc).
1088 //
1089 if ( (SWAP_BE32(vhp->lastMountedVersion) == kHFSJMountVersion)
1090 && (SWAP_BE32(vhp->attributes) & kHFSVolumeJournaledMask)
1091 && !jnl_disable) {
1092
1093 // if we're able to init the journal, mark the mount
1094 // point as journaled.
1095 //
1096 if (hfs_early_journal_init(hfsmp, vhp, args, embeddedOffset, mdb_offset, mdbp, cred) == 0) {
2d21ac55 1097 vfs_setflags(mp, (u_int64_t)((unsigned int)MNT_JOURNALED));
b4c24cb9 1098 } else {
55e303ae
A
1099 // if the journal failed to open, then set the lastMountedVersion
1100 // to be "FSK!" which fsck_hfs will see and force the fsck instead
1101 // of just bailing out because the volume is journaled.
91447636
A
1102 if (!ronly) {
1103 HFSPlusVolumeHeader *jvhp;
55e303ae
A
1104
1105 hfsmp->hfs_flags |= HFS_NEED_JNL_RESET;
1106
1107 if (mdb_offset == 0) {
91447636 1108 mdb_offset = (daddr64_t)((embeddedOffset / blksize) + HFS_PRI_SECTOR(blksize));
55e303ae
A
1109 }
1110
1111 bp = NULL;
91447636 1112 retval = (int)buf_meta_bread(devvp, mdb_offset, blksize, cred, &bp);
55e303ae 1113 if (retval == 0) {
91447636 1114 jvhp = (HFSPlusVolumeHeader *)(buf_dataptr(bp) + HFS_PRI_OFFSET(blksize));
55e303ae 1115
91447636
A
1116 if (SWAP_BE16(jvhp->signature) == kHFSPlusSigWord || SWAP_BE16(jvhp->signature) == kHFSXSigWord) {
1117 printf ("hfs(1): Journal replay fail. Writing lastMountVersion as FSK!\n");
1118 jvhp->lastMountedVersion = SWAP_BE32(kFSKMountVersion);
1119 buf_bwrite(bp);
55e303ae 1120 } else {
91447636 1121 buf_brelse(bp);
55e303ae
A
1122 }
1123 bp = NULL;
1124 } else if (bp) {
91447636
A
1125 buf_brelse(bp);
1126 // clear this so the error exit path won't try to use it
1127 bp = NULL;
55e303ae
A
1128 }
1129 }
1130
1131 // if this isn't the root device just bail out.
91447636 1132 // If it is the root device we just continue on
55e303ae
A
1133 // in the hopes that fsck_hfs will be able to
1134 // fix any damage that exists on the volume.
91447636 1135 if ( !(vfs_flags(mp) & MNT_ROOTFS)) {
55e303ae
A
1136 retval = EINVAL;
1137 goto error_exit;
1138 }
b4c24cb9
A
1139 }
1140 }
1141 // XXXdbg
1142
2d21ac55
A
1143 /* Either the journal is replayed successfully, or there
1144 * was nothing to replay, or no journal exists. In any case,
1145 * return success.
1146 */
1147 if (journal_replay_only) {
1148 retval = 0;
1149 goto error_exit;
1150 }
1151
d52fe63f
A
1152 (void) hfs_getconverter(0, &hfsmp->hfs_get_unicode, &hfsmp->hfs_get_hfsname);
1153
91447636 1154 retval = hfs_MountHFSPlusVolume(hfsmp, vhp, embeddedOffset, disksize, p, args, cred);
d52fe63f
A
1155 /*
1156 * If the backend didn't like our physical blocksize
1157 * then retry with physical blocksize of 512.
1158 */
1159 if ((retval == ENXIO) && (blksize > 512) && (blksize != minblksize)) {
1160 printf("HFS Mount: could not use physical block size "
1161 "(%d) switching to 512\n", blksize);
1162 blksize = 512;
91447636 1163 if (VNOP_IOCTL(devvp, DKIOCSETBLOCKSIZE, (caddr_t)&blksize, FWRITE, context)) {
d52fe63f
A
1164 retval = ENXIO;
1165 goto error_exit;
1166 }
91447636 1167 if (VNOP_IOCTL(devvp, DKIOCGETBLOCKCOUNT, (caddr_t)&blkcnt, 0, context)) {
d52fe63f
A
1168 retval = ENXIO;
1169 goto error_exit;
1170 }
d52fe63f
A
1171 devvp->v_specsize = blksize;
1172 /* Note: relative block count adjustment (in case this is an embedded volume). */
1173 hfsmp->hfs_phys_block_count *= hfsmp->hfs_phys_block_size / blksize;
1174 hfsmp->hfs_phys_block_size = blksize;
1175
55e303ae
A
1176 if (hfsmp->jnl) {
1177 // close and re-open this with the new block size
1178 journal_close(hfsmp->jnl);
1179 hfsmp->jnl = NULL;
1180 if (hfs_early_journal_init(hfsmp, vhp, args, embeddedOffset, mdb_offset, mdbp, cred) == 0) {
2d21ac55 1181 vfs_setflags(mp, (u_int64_t)((unsigned int)MNT_JOURNALED));
91447636
A
1182 } else {
1183 // if the journal failed to open, then set the lastMountedVersion
1184 // to be "FSK!" which fsck_hfs will see and force the fsck instead
1185 // of just bailing out because the volume is journaled.
1186 if (!ronly) {
1187 HFSPlusVolumeHeader *jvhp;
1188
1189 hfsmp->hfs_flags |= HFS_NEED_JNL_RESET;
1190
1191 if (mdb_offset == 0) {
1192 mdb_offset = (daddr64_t)((embeddedOffset / blksize) + HFS_PRI_SECTOR(blksize));
1193 }
1194
1195 bp = NULL;
1196 retval = (int)buf_meta_bread(devvp, mdb_offset, blksize, cred, &bp);
1197 if (retval == 0) {
1198 jvhp = (HFSPlusVolumeHeader *)(buf_dataptr(bp) + HFS_PRI_OFFSET(blksize));
1199
1200 if (SWAP_BE16(jvhp->signature) == kHFSPlusSigWord || SWAP_BE16(jvhp->signature) == kHFSXSigWord) {
1201 printf ("hfs(2): Journal replay fail. Writing lastMountVersion as FSK!\n");
1202 jvhp->lastMountedVersion = SWAP_BE32(kFSKMountVersion);
1203 buf_bwrite(bp);
1204 } else {
1205 buf_brelse(bp);
1206 }
1207 bp = NULL;
1208 } else if (bp) {
1209 buf_brelse(bp);
1210 // clear this so the error exit path won't try to use it
1211 bp = NULL;
1212 }
1213 }
1214
1215 // if this isn't the root device just bail out.
1216 // If it is the root device we just continue on
1217 // in the hopes that fsck_hfs will be able to
1218 // fix any damage that exists on the volume.
1219 if ( !(vfs_flags(mp) & MNT_ROOTFS)) {
1220 retval = EINVAL;
1221 goto error_exit;
1222 }
1223 }
55e303ae
A
1224 }
1225
d52fe63f 1226 /* Try again with a smaller block size... */
91447636 1227 retval = hfs_MountHFSPlusVolume(hfsmp, vhp, embeddedOffset, disksize, p, args, cred);
d52fe63f
A
1228 }
1229 if (retval)
1230 (void) hfs_relconverter(0);
1231 }
1c79356b 1232
91447636
A
1233 // save off a snapshot of the mtime from the previous mount
1234 // (for matador).
1235 hfsmp->hfs_last_mounted_mtime = hfsmp->hfs_mtime;
1236
1c79356b
A
1237 if ( retval ) {
1238 goto error_exit;
1239 }
1240
91447636
A
1241 mp->mnt_vfsstat.f_fsid.val[0] = (long)dev;
1242 mp->mnt_vfsstat.f_fsid.val[1] = vfs_typenum(mp);
1243 vfs_setmaxsymlen(mp, 0);
1244 mp->mnt_vtable->vfc_threadsafe = TRUE;
1245 mp->mnt_vtable->vfc_vfsflags |= VFC_VFSNATIVEXATTR;
2d21ac55
A
1246#if NAMEDSTREAMS
1247 mp->mnt_kern_flag |= MNTK_NAMED_STREAMS;
1248#endif
1249 if (!(hfsmp->hfs_flags & HFS_STANDARD)) {
1250 /* Tell VFS that we support directory hard links. */
1251 mp->mnt_vtable->vfc_vfsflags |= VFC_VFSDIRLINKS;
1252 } else {
1253 /* HFS standard doesn't support extended readdir! */
1254 mp->mnt_vtable->vfc_vfsflags &= ~VFC_VFSREADDIR_EXTENDED;
1255 }
1c79356b 1256
55e303ae
A
1257 if (args) {
1258 /*
1259 * Set the free space warning levels for a non-root volume:
1260 *
1261 * Set the lower freespace limit (the level that will trigger a warning)
1262 * to 5% of the volume size or 250MB, whichever is less, and the desired
1263 * level (which will cancel the alert request) to 1/2 above that limit.
1264 * Start looking for free space to drop below this level and generate a
1265 * warning immediately if needed:
1266 */
1267 hfsmp->hfs_freespace_notify_warninglimit =
1268 MIN(HFS_LOWDISKTRIGGERLEVEL / HFSTOVCB(hfsmp)->blockSize,
1269 (HFSTOVCB(hfsmp)->totalBlocks / 100) * HFS_LOWDISKTRIGGERFRACTION);
1270 hfsmp->hfs_freespace_notify_desiredlevel =
1271 MIN(HFS_LOWDISKSHUTOFFLEVEL / HFSTOVCB(hfsmp)->blockSize,
1272 (HFSTOVCB(hfsmp)->totalBlocks / 100) * HFS_LOWDISKSHUTOFFFRACTION);
1273 } else {
1274 /*
1275 * Set the free space warning levels for the root volume:
1276 *
1277 * Set the lower freespace limit (the level that will trigger a warning)
1278 * to 1% of the volume size or 50MB, whichever is less, and the desired
1279 * level (which will cancel the alert request) to 2% or 75MB, whichever is less.
1280 */
1281 hfsmp->hfs_freespace_notify_warninglimit =
1282 MIN(HFS_ROOTLOWDISKTRIGGERLEVEL / HFSTOVCB(hfsmp)->blockSize,
1283 (HFSTOVCB(hfsmp)->totalBlocks / 100) * HFS_ROOTLOWDISKTRIGGERFRACTION);
1284 hfsmp->hfs_freespace_notify_desiredlevel =
1285 MIN(HFS_ROOTLOWDISKSHUTOFFLEVEL / HFSTOVCB(hfsmp)->blockSize,
1286 (HFSTOVCB(hfsmp)->totalBlocks / 100) * HFS_ROOTLOWDISKSHUTOFFFRACTION);
1287 };
1288
2d21ac55
A
1289 /* Check if the file system exists on virtual device, like disk image */
1290 if (VNOP_IOCTL(devvp, DKIOCISVIRTUAL, (caddr_t)&isvirtual, 0, context) == 0) {
1291 if (isvirtual) {
1292 hfsmp->hfs_flags |= HFS_VIRTUAL_DEVICE;
1293 }
1294 }
1295
55e303ae
A
1296 /*
1297 * Start looking for free space to drop below this level and generate a
1298 * warning immediately if needed:
1299 */
1300 hfsmp->hfs_notification_conditions = 0;
1301 hfs_generate_volume_notifications(hfsmp);
2d21ac55 1302
9bccf70c
A
1303 if (ronly == 0) {
1304 (void) hfs_flushvolumeheader(hfsmp, MNT_WAIT, 0);
1305 }
1306 FREE(mdbp, M_TEMP);
1307 return (0);
1c79356b 1308
9bccf70c
A
1309error_exit:
1310 if (bp)
91447636 1311 buf_brelse(bp);
9bccf70c
A
1312 if (mdbp)
1313 FREE(mdbp, M_TEMP);
91447636 1314
b4c24cb9 1315 if (hfsmp && hfsmp->jvp && hfsmp->jvp != hfsmp->hfs_devvp) {
91447636 1316 (void)VNOP_CLOSE(hfsmp->jvp, ronly ? FREAD : FREAD|FWRITE, context);
b4c24cb9
A
1317 hfsmp->jvp = NULL;
1318 }
9bccf70c 1319 if (hfsmp) {
2d21ac55
A
1320 if (hfsmp->hfs_devvp) {
1321 vnode_rele(hfsmp->hfs_devvp);
1322 }
9bccf70c 1323 FREE(hfsmp, M_HFSMNT);
91447636 1324 vfs_setfsprivate(mp, NULL);
9bccf70c 1325 }
1c79356b
A
1326 return (retval);
1327}
1328
1329
1330/*
1331 * Make a filesystem operational.
1332 * Nothing to do at the moment.
1333 */
1334/* ARGSUSED */
9bccf70c 1335static int
91447636 1336hfs_start(__unused struct mount *mp, __unused int flags, __unused vfs_context_t context)
1c79356b 1337{
9bccf70c 1338 return (0);
1c79356b
A
1339}
1340
1341
1342/*
1343 * unmount system call
1344 */
9bccf70c 1345static int
91447636 1346hfs_unmount(struct mount *mp, int mntflags, vfs_context_t context)
1c79356b 1347{
91447636 1348 struct proc *p = vfs_context_proc(context);
1c79356b
A
1349 struct hfsmount *hfsmp = VFSTOHFS(mp);
1350 int retval = E_NONE;
1351 int flags;
9bccf70c 1352 int force;
91447636 1353 int started_tr = 0;
1c79356b
A
1354
1355 flags = 0;
9bccf70c
A
1356 force = 0;
1357 if (mntflags & MNT_FORCE) {
1c79356b 1358 flags |= FORCECLOSE;
9bccf70c
A
1359 force = 1;
1360 }
1c79356b 1361
9bccf70c 1362 if ((retval = hfs_flushfiles(mp, flags, p)) && !force)
1c79356b
A
1363 return (retval);
1364
55e303ae 1365 if (hfsmp->hfs_flags & HFS_METADATA_ZONE)
91447636 1366 (void) hfs_recording_suspend(hfsmp);
55e303ae 1367
1c79356b
A
1368 /*
1369 * Flush out the b-trees, volume bitmap and Volume Header
1370 */
55e303ae 1371 if ((hfsmp->hfs_flags & HFS_READ_ONLY) == 0) {
2d21ac55
A
1372 retval = hfs_start_transaction(hfsmp);
1373 if (retval == 0) {
1374 started_tr = 1;
1375 } else if (!force) {
1376 goto err_exit;
1377 }
1378
1379 if (hfsmp->hfs_startup_vp) {
1380 (void) hfs_lock(VTOC(hfsmp->hfs_startup_vp), HFS_EXCLUSIVE_LOCK);
1381 retval = hfs_fsync(hfsmp->hfs_startup_vp, MNT_WAIT, 0, p);
1382 hfs_unlock(VTOC(hfsmp->hfs_startup_vp));
1383 if (retval && !force)
1384 goto err_exit;
1385 }
91447636
A
1386
1387 if (hfsmp->hfs_attribute_vp) {
1388 (void) hfs_lock(VTOC(hfsmp->hfs_attribute_vp), HFS_EXCLUSIVE_LOCK);
1389 retval = hfs_fsync(hfsmp->hfs_attribute_vp, MNT_WAIT, 0, p);
1390 hfs_unlock(VTOC(hfsmp->hfs_attribute_vp));
1391 if (retval && !force)
1392 goto err_exit;
b4c24cb9 1393 }
91447636
A
1394
1395 (void) hfs_lock(VTOC(hfsmp->hfs_catalog_vp), HFS_EXCLUSIVE_LOCK);
1396 retval = hfs_fsync(hfsmp->hfs_catalog_vp, MNT_WAIT, 0, p);
1397 hfs_unlock(VTOC(hfsmp->hfs_catalog_vp));
9bccf70c 1398 if (retval && !force)
b4c24cb9
A
1399 goto err_exit;
1400
91447636
A
1401 (void) hfs_lock(VTOC(hfsmp->hfs_extents_vp), HFS_EXCLUSIVE_LOCK);
1402 retval = hfs_fsync(hfsmp->hfs_extents_vp, MNT_WAIT, 0, p);
1403 hfs_unlock(VTOC(hfsmp->hfs_extents_vp));
9bccf70c 1404 if (retval && !force)
b4c24cb9
A
1405 goto err_exit;
1406
91447636
A
1407 if (hfsmp->hfs_allocation_vp) {
1408 (void) hfs_lock(VTOC(hfsmp->hfs_allocation_vp), HFS_EXCLUSIVE_LOCK);
1409 retval = hfs_fsync(hfsmp->hfs_allocation_vp, MNT_WAIT, 0, p);
1410 hfs_unlock(VTOC(hfsmp->hfs_allocation_vp));
55e303ae
A
1411 if (retval && !force)
1412 goto err_exit;
1413 }
1414
91447636
A
1415 if (hfsmp->hfc_filevp && vnode_issystem(hfsmp->hfc_filevp)) {
1416 retval = hfs_fsync(hfsmp->hfc_filevp, MNT_WAIT, 0, p);
1417 if (retval && !force)
b4c24cb9 1418 goto err_exit;
1c79356b 1419 }
2d21ac55
A
1420
1421 /* If runtime corruption was detected, indicate that the volume
1422 * was not unmounted cleanly.
1423 */
1424 if (hfsmp->vcbAtrb & kHFSVolumeInconsistentMask) {
1c79356b
A
1425 HFSTOVCB(hfsmp)->vcbAtrb &= ~kHFSVolumeUnmountedMask;
1426 } else {
9bccf70c 1427 HFSTOVCB(hfsmp)->vcbAtrb |= kHFSVolumeUnmountedMask;
1c79356b 1428 }
2d21ac55 1429
91447636 1430 retval = hfs_flushvolumeheader(hfsmp, MNT_WAIT, 0);
1c79356b 1431 if (retval) {
1c79356b 1432 HFSTOVCB(hfsmp)->vcbAtrb &= ~kHFSVolumeUnmountedMask;
9bccf70c 1433 if (!force)
b4c24cb9
A
1434 goto err_exit; /* could not flush everything */
1435 }
1436
2d21ac55
A
1437 if (started_tr) {
1438 hfs_end_transaction(hfsmp);
1439 started_tr = 0;
1440 }
1c79356b
A
1441 }
1442
b4c24cb9
A
1443 if (hfsmp->jnl) {
1444 journal_flush(hfsmp->jnl);
1445 }
1446
1c79356b
A
1447 /*
1448 * Invalidate our caches and release metadata vnodes
1449 */
1450 (void) hfsUnmount(hfsmp, p);
1451
55e303ae
A
1452 /*
1453 * Last chance to dump unreferenced system files.
1454 */
1455 (void) vflush(mp, NULLVP, FORCECLOSE);
1456
1c79356b
A
1457 if (HFSTOVCB(hfsmp)->vcbSigWord == kHFSSigWord)
1458 (void) hfs_relconverter(hfsmp->hfs_encoding);
1459
b4c24cb9
A
1460 // XXXdbg
1461 if (hfsmp->jnl) {
1462 journal_close(hfsmp->jnl);
55e303ae 1463 hfsmp->jnl = NULL;
b4c24cb9
A
1464 }
1465
91447636
A
1466 VNOP_FSYNC(hfsmp->hfs_devvp, MNT_WAIT, context);
1467
b4c24cb9 1468 if (hfsmp->jvp && hfsmp->jvp != hfsmp->hfs_devvp) {
91447636 1469 retval = VNOP_CLOSE(hfsmp->jvp,
55e303ae 1470 hfsmp->hfs_flags & HFS_READ_ONLY ? FREAD : FREAD|FWRITE,
91447636
A
1471 context);
1472 vnode_put(hfsmp->jvp);
55e303ae 1473 hfsmp->jvp = NULL;
b4c24cb9
A
1474 }
1475 // XXXdbg
1476
55e303ae
A
1477#ifdef HFS_SPARSE_DEV
1478 /* Drop our reference on the backing fs (if any). */
1479 if ((hfsmp->hfs_flags & HFS_HAS_SPARSE_DEVICE) && hfsmp->hfs_backingfs_rootvp) {
1480 struct vnode * tmpvp;
1481
1482 hfsmp->hfs_flags &= ~HFS_HAS_SPARSE_DEVICE;
1483 tmpvp = hfsmp->hfs_backingfs_rootvp;
1484 hfsmp->hfs_backingfs_rootvp = NULLVP;
91447636 1485 vnode_rele(tmpvp);
55e303ae
A
1486 }
1487#endif /* HFS_SPARSE_DEV */
91447636 1488 lck_mtx_destroy(&hfsmp->hfc_mutex, hfs_mutex_group);
2d21ac55 1489 vnode_rele(hfsmp->hfs_devvp);
1c79356b 1490 FREE(hfsmp, M_HFSMNT);
91447636 1491
9bccf70c 1492 return (0);
b4c24cb9
A
1493
1494 err_exit:
91447636
A
1495 if (started_tr) {
1496 hfs_end_transaction(hfsmp);
b4c24cb9
A
1497 }
1498 return retval;
1c79356b
A
1499}
1500
1501
1502/*
1503 * Return the root of a filesystem.
1c79356b 1504 */
9bccf70c 1505static int
91447636 1506hfs_vfs_root(struct mount *mp, struct vnode **vpp, __unused vfs_context_t context)
1c79356b 1507{
91447636 1508 return hfs_vget(VFSTOHFS(mp), (cnid_t)kHFSRootFolderID, vpp, 1);
1c79356b
A
1509}
1510
1511
1512/*
1513 * Do operations associated with quotas
1514 */
2d21ac55
A
1515#if !QUOTA
1516static int
1517hfs_quotactl(__unused struct mount *mp, __unused int cmds, __unused uid_t uid, __unused caddr_t datap, __unused vfs_context_t context)
1518{
1519 return (ENOTSUP);
1520}
1521#else
91447636
A
1522static int
1523hfs_quotactl(struct mount *mp, int cmds, uid_t uid, caddr_t datap, vfs_context_t context)
1c79356b 1524{
91447636 1525 struct proc *p = vfs_context_proc(context);
9bccf70c
A
1526 int cmd, type, error;
1527
2d21ac55 1528 if (uid == ~0U)
91447636 1529 uid = vfs_context_ucred(context)->cr_ruid;
9bccf70c
A
1530 cmd = cmds >> SUBCMDSHIFT;
1531
1532 switch (cmd) {
1533 case Q_SYNC:
1534 case Q_QUOTASTAT:
1535 break;
1536 case Q_GETQUOTA:
91447636 1537 if (uid == vfs_context_ucred(context)->cr_ruid)
9bccf70c
A
1538 break;
1539 /* fall through */
1540 default:
91447636 1541 if ( (error = vfs_context_suser(context)) )
9bccf70c
A
1542 return (error);
1543 }
1544
1545 type = cmds & SUBCMDMASK;
1546 if ((u_int)type >= MAXQUOTAS)
1547 return (EINVAL);
91447636 1548 if (vfs_busy(mp, LK_NOWAIT))
9bccf70c
A
1549 return (0);
1550
1551 switch (cmd) {
1c79356b 1552
9bccf70c 1553 case Q_QUOTAON:
91447636 1554 error = hfs_quotaon(p, mp, type, datap);
9bccf70c
A
1555 break;
1556
1557 case Q_QUOTAOFF:
1558 error = hfs_quotaoff(p, mp, type);
1559 break;
1560
1561 case Q_SETQUOTA:
91447636 1562 error = hfs_setquota(mp, uid, type, datap);
9bccf70c
A
1563 break;
1564
1565 case Q_SETUSE:
91447636 1566 error = hfs_setuse(mp, uid, type, datap);
9bccf70c
A
1567 break;
1568
1569 case Q_GETQUOTA:
91447636 1570 error = hfs_getquota(mp, uid, type, datap);
9bccf70c
A
1571 break;
1572
1573 case Q_SYNC:
1574 error = hfs_qsync(mp);
1575 break;
1576
1577 case Q_QUOTASTAT:
91447636 1578 error = hfs_quotastat(mp, type, datap);
9bccf70c
A
1579 break;
1580
1581 default:
1582 error = EINVAL;
1583 break;
1584 }
91447636
A
1585 vfs_unbusy(mp);
1586
9bccf70c 1587 return (error);
1c79356b 1588}
2d21ac55 1589#endif /* QUOTA */
1c79356b 1590
91447636
A
1591/* Subtype is composite of bits */
1592#define HFS_SUBTYPE_JOURNALED 0x01
1593#define HFS_SUBTYPE_CASESENSITIVE 0x02
1594/* bits 2 - 6 reserved */
1595#define HFS_SUBTYPE_STANDARDHFS 0x80
b4c24cb9 1596
1c79356b
A
1597/*
1598 * Get file system statistics.
1599 */
1600static int
91447636 1601hfs_statfs(struct mount *mp, register struct vfsstatfs *sbp, __unused vfs_context_t context)
1c79356b
A
1602{
1603 ExtendedVCB *vcb = VFSTOVCB(mp);
1604 struct hfsmount *hfsmp = VFSTOHFS(mp);
1605 u_long freeCNIDs;
2d21ac55 1606 u_int16_t subtype = 0;
1c79356b 1607
1c79356b
A
1608 freeCNIDs = (u_long)0xFFFFFFFF - (u_long)vcb->vcbNxtCNID;
1609
2d21ac55 1610 sbp->f_bsize = (u_int32_t)vcb->blockSize;
91447636 1611 sbp->f_iosize = (size_t)(MAX_UPL_TRANSFER * PAGE_SIZE);
2d21ac55
A
1612 sbp->f_blocks = (u_int64_t)((unsigned long)vcb->totalBlocks);
1613 sbp->f_bfree = (u_int64_t)((unsigned long )hfs_freeblks(hfsmp, 0));
1614 sbp->f_bavail = (u_int64_t)((unsigned long )hfs_freeblks(hfsmp, 1));
1615 sbp->f_files = (u_int64_t)((unsigned long )(vcb->totalBlocks - 2)); /* max files is constrained by total blocks */
1616 sbp->f_ffree = (u_int64_t)((unsigned long )(MIN(freeCNIDs, sbp->f_bavail)));
91447636
A
1617
1618 /*
1619 * Subtypes (flavors) for HFS
1620 * 0: Mac OS Extended
1621 * 1: Mac OS Extended (Journaled)
1622 * 2: Mac OS Extended (Case Sensitive)
1623 * 3: Mac OS Extended (Case Sensitive, Journaled)
1624 * 4 - 127: Reserved
1625 * 128: Mac OS Standard
1626 *
1627 */
1628 if (hfsmp->hfs_flags & HFS_STANDARD) {
1629 subtype = HFS_SUBTYPE_STANDARDHFS;
1630 } else /* HFS Plus */ {
1631 if (hfsmp->jnl)
1632 subtype |= HFS_SUBTYPE_JOURNALED;
1633 if (hfsmp->hfs_flags & HFS_CASE_SENSITIVE)
1634 subtype |= HFS_SUBTYPE_CASESENSITIVE;
1c79356b 1635 }
91447636
A
1636 sbp->f_fssubtype = subtype;
1637
1c79356b
A
1638 return (0);
1639}
1640
1641
b4c24cb9
A
1642//
1643// XXXdbg -- this is a callback to be used by the journal to
1644// get meta data blocks flushed out to disk.
1645//
1646// XXXdbg -- be smarter and don't flush *every* block on each
1647// call. try to only flush some so we don't wind up
1648// being too synchronous.
1649//
1650__private_extern__
1651void
1652hfs_sync_metadata(void *arg)
1653{
1654 struct mount *mp = (struct mount *)arg;
b4c24cb9
A
1655 struct hfsmount *hfsmp;
1656 ExtendedVCB *vcb;
91447636
A
1657 buf_t bp;
1658 int sectorsize, retval;
1659 daddr64_t priIDSector;
b4c24cb9
A
1660 hfsmp = VFSTOHFS(mp);
1661 vcb = HFSTOVCB(hfsmp);
1662
b4c24cb9
A
1663 // now make sure the super block is flushed
1664 sectorsize = hfsmp->hfs_phys_block_size;
91447636
A
1665 priIDSector = (daddr64_t)((vcb->hfsPlusIOPosOffset / sectorsize) +
1666 HFS_PRI_SECTOR(sectorsize));
1667 retval = (int)buf_meta_bread(hfsmp->hfs_devvp, priIDSector, sectorsize, NOCRED, &bp);
2d21ac55 1668 if ((retval != 0 ) && (retval != ENXIO)) {
0c530ab8 1669 printf("hfs_sync_metadata: can't read volume header at %d! (retval 0x%x)\n",
2d21ac55 1670 (int)priIDSector, retval);
b4c24cb9
A
1671 }
1672
91447636
A
1673 if (retval == 0 && ((buf_flags(bp) & (B_DELWRI | B_LOCKED)) == B_DELWRI)) {
1674 buf_bwrite(bp);
b4c24cb9 1675 } else if (bp) {
91447636 1676 buf_brelse(bp);
b4c24cb9
A
1677 }
1678
1679 // the alternate super block...
1680 // XXXdbg - we probably don't need to do this each and every time.
1681 // hfs_btreeio.c:FlushAlternate() should flag when it was
1682 // written...
91447636
A
1683 if (hfsmp->hfs_alt_id_sector) {
1684 retval = (int)buf_meta_bread(hfsmp->hfs_devvp, hfsmp->hfs_alt_id_sector, sectorsize, NOCRED, &bp);
1685 if (retval == 0 && ((buf_flags(bp) & (B_DELWRI | B_LOCKED)) == B_DELWRI)) {
1686 buf_bwrite(bp);
1687 } else if (bp) {
1688 buf_brelse(bp);
1689 }
b4c24cb9 1690 }
b4c24cb9
A
1691}
1692
91447636
A
1693
1694struct hfs_sync_cargs {
1695 kauth_cred_t cred;
1696 struct proc *p;
1697 int waitfor;
1698 int error;
1699};
1700
1701
1702static int
1703hfs_sync_callback(struct vnode *vp, void *cargs)
1704{
1705 struct cnode *cp;
1706 struct hfs_sync_cargs *args;
1707 int error;
1708
1709 args = (struct hfs_sync_cargs *)cargs;
1710
1711 if (hfs_lock(VTOC(vp), HFS_EXCLUSIVE_LOCK) != 0) {
1712 return (VNODE_RETURNED);
1713 }
1714 cp = VTOC(vp);
1715
1716 if ((cp->c_flag & C_MODIFIED) ||
1717 (cp->c_touch_acctime | cp->c_touch_chgtime | cp->c_touch_modtime) ||
1718 vnode_hasdirtyblks(vp)) {
1719 error = hfs_fsync(vp, args->waitfor, 0, args->p);
1720
1721 if (error)
1722 args->error = error;
1723 }
1724 hfs_unlock(cp);
1725 return (VNODE_RETURNED);
1726}
1727
1728
1729
1c79356b
A
1730/*
1731 * Go through the disk queues to initiate sandbagged IO;
1732 * go through the inodes to write those that have been modified;
1733 * initiate the writing of the super block if it has been modified.
1734 *
1735 * Note: we are always called with the filesystem marked `MPBUSY'.
1736 */
9bccf70c 1737static int
91447636 1738hfs_sync(struct mount *mp, int waitfor, vfs_context_t context)
1c79356b 1739{
91447636 1740 struct proc *p = vfs_context_proc(context);
9bccf70c
A
1741 struct cnode *cp;
1742 struct hfsmount *hfsmp;
1743 ExtendedVCB *vcb;
91447636 1744 struct vnode *meta_vp[4];
9bccf70c
A
1745 int i;
1746 int error, allerror = 0;
91447636 1747 struct hfs_sync_cargs args;
1c79356b
A
1748
1749 /*
1750 * During MNT_UPDATE hfs_changefs might be manipulating
1751 * vnodes so back off
1752 */
2d21ac55 1753 if (((u_int32_t)vfs_flags(mp)) & MNT_UPDATE) /* XXX MNT_UPDATE may not be visible here */
1c79356b
A
1754 return (0);
1755
9bccf70c 1756 hfsmp = VFSTOHFS(mp);
55e303ae
A
1757 if (hfsmp->hfs_flags & HFS_READ_ONLY)
1758 return (EROFS);
1c79356b 1759
3a60a9f5
A
1760 /* skip over frozen volumes */
1761 if (!lck_rw_try_lock_shared(&hfsmp->hfs_insync))
1762 return 0;
1763
2d21ac55 1764 args.cred = kauth_cred_get();
91447636
A
1765 args.waitfor = waitfor;
1766 args.p = p;
1767 args.error = 0;
9bccf70c 1768 /*
91447636
A
1769 * hfs_sync_callback will be called for each vnode
1770 * hung off of this mount point... the vnode will be
1771 * properly referenced and unreferenced around the callback
9bccf70c 1772 */
91447636 1773 vnode_iterate(mp, 0, hfs_sync_callback, (void *)&args);
1c79356b 1774
91447636
A
1775 if (args.error)
1776 allerror = args.error;
1c79356b 1777
9bccf70c
A
1778 vcb = HFSTOVCB(hfsmp);
1779
1780 meta_vp[0] = vcb->extentsRefNum;
1781 meta_vp[1] = vcb->catalogRefNum;
1782 meta_vp[2] = vcb->allocationsRefNum; /* This is NULL for standard HFS */
91447636 1783 meta_vp[3] = hfsmp->hfs_attribute_vp; /* Optional file */
9bccf70c
A
1784
1785 /* Now sync our three metadata files */
91447636 1786 for (i = 0; i < 4; ++i) {
9bccf70c
A
1787 struct vnode *btvp;
1788
91447636
A
1789 btvp = meta_vp[i];;
1790 if ((btvp==0) || (vnode_mount(btvp) != mp))
9bccf70c 1791 continue;
b4c24cb9 1792
91447636
A
1793 /* XXX use hfs_systemfile_lock instead ? */
1794 (void) hfs_lock(VTOC(btvp), HFS_EXCLUSIVE_LOCK);
9bccf70c 1795 cp = VTOC(btvp);
91447636
A
1796
1797 if (((cp->c_flag & C_MODIFIED) == 0) &&
1798 (cp->c_touch_acctime == 0) &&
1799 (cp->c_touch_chgtime == 0) &&
1800 (cp->c_touch_modtime == 0) &&
1801 vnode_hasdirtyblks(btvp) == 0) {
1802 hfs_unlock(VTOC(btvp));
9bccf70c
A
1803 continue;
1804 }
91447636 1805 error = vnode_get(btvp);
9bccf70c 1806 if (error) {
91447636 1807 hfs_unlock(VTOC(btvp));
9bccf70c
A
1808 continue;
1809 }
91447636 1810 if ((error = hfs_fsync(btvp, waitfor, 0, p)))
9bccf70c 1811 allerror = error;
9bccf70c 1812
91447636
A
1813 hfs_unlock(cp);
1814 vnode_put(btvp);
1815 };
9bccf70c
A
1816
1817 /*
1818 * Force stale file system control information to be flushed.
1819 */
1820 if (vcb->vcbSigWord == kHFSSigWord) {
91447636 1821 if ((error = VNOP_FSYNC(hfsmp->hfs_devvp, waitfor, context))) {
9bccf70c 1822 allerror = error;
91447636 1823 }
9bccf70c
A
1824 }
1825#if QUOTA
1826 hfs_qsync(mp);
1827#endif /* QUOTA */
55e303ae 1828
2d21ac55
A
1829 hfs_hotfilesync(hfsmp, vfs_context_kernel());
1830
9bccf70c
A
1831 /*
1832 * Write back modified superblock.
1833 */
9bccf70c
A
1834 if (IsVCBDirty(vcb)) {
1835 error = hfs_flushvolumeheader(hfsmp, waitfor, 0);
b4c24cb9
A
1836 if (error)
1837 allerror = error;
9bccf70c 1838 }
1c79356b 1839
b4c24cb9
A
1840 if (hfsmp->jnl) {
1841 journal_flush(hfsmp->jnl);
1842 }
3a60a9f5
A
1843
1844 lck_rw_unlock_shared(&hfsmp->hfs_insync);
9bccf70c 1845 return (allerror);
1c79356b
A
1846}
1847
1848
1849/*
1850 * File handle to vnode
1851 *
1852 * Have to be really careful about stale file handles:
9bccf70c
A
1853 * - check that the cnode id is valid
1854 * - call hfs_vget() to get the locked cnode
1855 * - check for an unallocated cnode (i_mode == 0)
1c79356b
A
1856 * - check that the given client host has export rights and return
1857 * those rights via. exflagsp and credanonp
1858 */
9bccf70c 1859static int
2d21ac55 1860hfs_fhtovp(struct mount *mp, int fhlen, unsigned char *fhp, struct vnode **vpp, __unused vfs_context_t context)
1c79356b
A
1861{
1862 struct hfsfid *hfsfhp;
1863 struct vnode *nvp;
1864 int result;
1c79356b
A
1865
1866 *vpp = NULL;
1867 hfsfhp = (struct hfsfid *)fhp;
1868
2d21ac55 1869 if (fhlen < (int)sizeof(struct hfsfid))
91447636 1870 return (EINVAL);
1c79356b 1871
0c530ab8 1872 result = hfs_vget(VFSTOHFS(mp), ntohl(hfsfhp->hfsfid_cnid), &nvp, 0);
91447636
A
1873 if (result) {
1874 if (result == ENOENT)
1875 result = ESTALE;
1876 return result;
1877 }
1c79356b 1878
0b4e3aa0
A
1879 /* The createtime can be changed by hfs_setattr or hfs_setattrlist.
1880 * For NFS, we are assuming that only if the createtime was moved
1881 * forward would it mean the fileID got reused in that session by
1882 * wrapping. We don't have a volume ID or other unique identifier to
1883 * to use here for a generation ID across reboots, crashes where
1884 * metadata noting lastFileID didn't make it to disk but client has
1885 * it, or volume erasures where fileIDs start over again. Lastly,
1886 * with HFS allowing "wraps" of fileIDs now, this becomes more
1887 * error prone. Future, would be change the "wrap bit" to a unique
1888 * wrap number and use that for generation number. For now do this.
1889 */
2d21ac55 1890 if (((time_t)(ntohl(hfsfhp->hfsfid_gen)) < VTOC(nvp)->c_itime)) {
91447636
A
1891 hfs_unlock(VTOC(nvp));
1892 vnode_put(nvp);
9bccf70c 1893 return (ESTALE);
55e303ae 1894 }
1c79356b 1895 *vpp = nvp;
91447636
A
1896
1897 hfs_unlock(VTOC(nvp));
9bccf70c 1898 return (0);
1c79356b
A
1899}
1900
1901
1902/*
1903 * Vnode pointer to File handle
1904 */
1905/* ARGSUSED */
9bccf70c 1906static int
2d21ac55 1907hfs_vptofh(struct vnode *vp, int *fhlenp, unsigned char *fhp, __unused vfs_context_t context)
1c79356b 1908{
9bccf70c 1909 struct cnode *cp;
1c79356b 1910 struct hfsfid *hfsfhp;
1c79356b 1911
9bccf70c 1912 if (ISHFS(VTOVCB(vp)))
91447636
A
1913 return (ENOTSUP); /* hfs standard is not exportable */
1914
1915 if (*fhlenp < (int)sizeof(struct hfsfid))
1916 return (EOVERFLOW);
1c79356b 1917
9bccf70c
A
1918 cp = VTOC(vp);
1919 hfsfhp = (struct hfsfid *)fhp;
0c530ab8
A
1920 hfsfhp->hfsfid_cnid = htonl(cp->c_fileid);
1921 hfsfhp->hfsfid_gen = htonl(cp->c_itime);
91447636 1922 *fhlenp = sizeof(struct hfsfid);
1c79356b 1923
9bccf70c 1924 return (0);
1c79356b
A
1925}
1926
1927
1928/*
1929 * Initial HFS filesystems, done only once.
1930 */
9bccf70c 1931static int
91447636 1932hfs_init(__unused struct vfsconf *vfsp)
1c79356b 1933{
9bccf70c 1934 static int done = 0;
1c79356b 1935
9bccf70c
A
1936 if (done)
1937 return (0);
1938 done = 1;
1939 hfs_chashinit();
1940 hfs_converterinit();
1c79356b 1941
55e303ae 1942 BTReserveSetup();
91447636
A
1943
1944
1945 hfs_lock_attr = lck_attr_alloc_init();
1946 hfs_group_attr = lck_grp_attr_alloc_init();
1947 hfs_mutex_group = lck_grp_alloc_init("hfs-mutex", hfs_group_attr);
1948 hfs_rwlock_group = lck_grp_alloc_init("hfs-rwlock", hfs_group_attr);
0c530ab8 1949
1c79356b 1950
9bccf70c 1951 return (0);
1c79356b
A
1952}
1953
55e303ae 1954static int
2d21ac55 1955hfs_getmountpoint(struct vnode *vp, struct hfsmount **hfsmpp)
55e303ae
A
1956{
1957 struct hfsmount * hfsmp;
91447636 1958 char fstypename[MFSNAMELEN];
55e303ae
A
1959
1960 if (vp == NULL)
1961 return (EINVAL);
1962
91447636 1963 if (!vnode_isvroot(vp))
55e303ae
A
1964 return (EINVAL);
1965
91447636 1966 vnode_vfsname(vp, fstypename);
2d21ac55 1967 if (strncmp(fstypename, "hfs", sizeof(fstypename)) != 0)
55e303ae
A
1968 return (EINVAL);
1969
1970 hfsmp = VTOHFS(vp);
1971
1972 if (HFSTOVCB(hfsmp)->vcbSigWord == kHFSSigWord)
1973 return (EINVAL);
1974
1975 *hfsmpp = hfsmp;
1976
1977 return (0);
1978}
1c79356b 1979
b4c24cb9
A
1980// XXXdbg
1981#include <sys/filedesc.h>
1982
1c79356b 1983/*
9bccf70c 1984 * HFS filesystem related variables.
1c79356b 1985 */
9bccf70c 1986static int
91447636
A
1987hfs_sysctl(int *name, __unused u_int namelen, user_addr_t oldp, size_t *oldlenp,
1988 user_addr_t newp, size_t newlen, vfs_context_t context)
1c79356b 1989{
91447636 1990 struct proc *p = vfs_context_proc(context);
55e303ae 1991 int error;
55e303ae 1992 struct hfsmount *hfsmp;
9bccf70c
A
1993
1994 /* all sysctl names at this level are terminal */
1c79356b 1995
55e303ae 1996 if (name[0] == HFS_ENCODINGBIAS) {
2d21ac55 1997 int bias;
55e303ae
A
1998
1999 bias = hfs_getencodingbias();
2000 error = sysctl_int(oldp, oldlenp, newp, newlen, &bias);
2001 if (error == 0 && newp)
2002 hfs_setencodingbias(bias);
2003 return (error);
2004
2005 } else if (name[0] == HFS_EXTEND_FS) {
91447636 2006 u_int64_t newsize;
2d21ac55 2007 vnode_t vp = vfs_context_cwd(context);
91447636 2008
2d21ac55 2009 if (newp == USER_ADDR_NULL || vp == NULLVP)
55e303ae 2010 return (EINVAL);
91447636 2011 if ((error = hfs_getmountpoint(vp, &hfsmp)))
55e303ae 2012 return (error);
2d21ac55 2013 error = sysctl_quad(oldp, oldlenp, newp, newlen, (quad_t *)&newsize);
55e303ae
A
2014 if (error)
2015 return (error);
2016
91447636 2017 error = hfs_extendfs(hfsmp, newsize, context);
55e303ae
A
2018 return (error);
2019
2020 } else if (name[0] == HFS_ENCODINGHINT) {
2021 size_t bufsize;
2022 size_t bytes;
2023 u_int32_t hint;
2024 u_int16_t *unicode_name;
2025 char *filename;
2026
2d21ac55
A
2027 if ((newlen <= 0) || (newlen > MAXPATHLEN))
2028 return (EINVAL);
2029
55e303ae
A
2030 bufsize = MAX(newlen * 3, MAXPATHLEN);
2031 MALLOC(filename, char *, newlen, M_TEMP, M_WAITOK);
2032 MALLOC(unicode_name, u_int16_t *, bufsize, M_TEMP, M_WAITOK);
2033
2034 error = copyin(newp, (caddr_t)filename, newlen);
2035 if (error == 0) {
2d21ac55 2036 error = utf8_decodestr((u_int8_t *)filename, newlen - 1, unicode_name,
55e303ae
A
2037 &bytes, bufsize, 0, UTF_DECOMPOSED);
2038 if (error == 0) {
2039 hint = hfs_pickencoding(unicode_name, bytes / 2);
2d21ac55 2040 error = sysctl_int(oldp, oldlenp, USER_ADDR_NULL, 0, (int32_t *)&hint);
55e303ae
A
2041 }
2042 }
2043 FREE(unicode_name, M_TEMP);
2044 FREE(filename, M_TEMP);
2045 return (error);
2046
2047 } else if (name[0] == HFS_ENABLE_JOURNALING) {
b4c24cb9 2048 // make the file system journaled...
2d21ac55
A
2049 vnode_t vp = vfs_context_cwd(context);
2050 vnode_t jvp;
b4c24cb9 2051 ExtendedVCB *vcb;
b4c24cb9
A
2052 struct cat_attr jnl_attr, jinfo_attr;
2053 struct cat_fork jnl_fork, jinfo_fork;
2054 void *jnl = NULL;
91447636 2055 int lockflags;
d7e50217
A
2056
2057 /* Only root can enable journaling */
91447636 2058 if (!is_suser()) {
d7e50217
A
2059 return (EPERM);
2060 }
2d21ac55 2061 if (vp == NULLVP)
91447636 2062 return EINVAL;
55e303ae 2063
b4c24cb9 2064 hfsmp = VTOHFS(vp);
55e303ae 2065 if (hfsmp->hfs_flags & HFS_READ_ONLY) {
b4c24cb9
A
2066 return EROFS;
2067 }
2068 if (HFSTOVCB(hfsmp)->vcbSigWord == kHFSSigWord) {
2069 printf("hfs: can't make a plain hfs volume journaled.\n");
2070 return EINVAL;
2071 }
2072
2073 if (hfsmp->jnl) {
2d21ac55 2074 printf("hfs: volume @ mp %p is already journaled!\n", vnode_mount(vp));
b4c24cb9
A
2075 return EAGAIN;
2076 }
2077
2078 vcb = HFSTOVCB(hfsmp);
91447636 2079 lockflags = hfs_systemfile_lock(hfsmp, SFL_CATALOG | SFL_EXTENTS, HFS_EXCLUSIVE_LOCK);
b4c24cb9
A
2080 if (BTHasContiguousNodes(VTOF(vcb->catalogRefNum)) == 0 ||
2081 BTHasContiguousNodes(VTOF(vcb->extentsRefNum)) == 0) {
2082
2083 printf("hfs: volume has a btree w/non-contiguous nodes. can not enable journaling.\n");
91447636 2084 hfs_systemfile_unlock(hfsmp, lockflags);
b4c24cb9
A
2085 return EINVAL;
2086 }
91447636 2087 hfs_systemfile_unlock(hfsmp, lockflags);
b4c24cb9
A
2088
2089 // make sure these both exist!
91447636
A
2090 if ( GetFileInfo(vcb, kHFSRootFolderID, ".journal_info_block", &jinfo_attr, &jinfo_fork) == 0
2091 || GetFileInfo(vcb, kHFSRootFolderID, ".journal", &jnl_attr, &jnl_fork) == 0) {
b4c24cb9
A
2092
2093 return EINVAL;
2094 }
2095
91447636 2096 hfs_sync(hfsmp->hfs_mp, MNT_WAIT, context);
b4c24cb9
A
2097
2098 printf("hfs: Initializing the journal (joffset 0x%llx sz 0x%llx)...\n",
2099 (off_t)name[2], (off_t)name[3]);
2100
2101 jvp = hfsmp->hfs_devvp;
2102 jnl = journal_create(jvp,
2103 (off_t)name[2] * (off_t)HFSTOVCB(hfsmp)->blockSize
2104 + HFSTOVCB(hfsmp)->hfsPlusIOPosOffset,
55e303ae 2105 (off_t)((unsigned)name[3]),
b4c24cb9
A
2106 hfsmp->hfs_devvp,
2107 hfsmp->hfs_phys_block_size,
2108 0,
2109 0,
2110 hfs_sync_metadata, hfsmp->hfs_mp);
2111
2112 if (jnl == NULL) {
2113 printf("hfs: FAILED to create the journal!\n");
2114 if (jvp && jvp != hfsmp->hfs_devvp) {
91447636 2115 VNOP_CLOSE(jvp, hfsmp->hfs_flags & HFS_READ_ONLY ? FREAD : FREAD|FWRITE, context);
b4c24cb9
A
2116 }
2117 jvp = NULL;
2118
2119 return EINVAL;
2120 }
2121
2122 hfs_global_exclusive_lock_acquire(hfsmp);
2123
4452a7af
A
2124 /*
2125 * Flush all dirty metadata buffers.
2126 */
2127 buf_flushdirtyblks(hfsmp->hfs_devvp, MNT_WAIT, 0, "hfs_sysctl");
2128 buf_flushdirtyblks(hfsmp->hfs_extents_vp, MNT_WAIT, 0, "hfs_sysctl");
2129 buf_flushdirtyblks(hfsmp->hfs_catalog_vp, MNT_WAIT, 0, "hfs_sysctl");
2130 buf_flushdirtyblks(hfsmp->hfs_allocation_vp, MNT_WAIT, 0, "hfs_sysctl");
2131 if (hfsmp->hfs_attribute_vp)
2132 buf_flushdirtyblks(hfsmp->hfs_attribute_vp, MNT_WAIT, 0, "hfs_sysctl");
2133
b4c24cb9
A
2134 HFSTOVCB(hfsmp)->vcbJinfoBlock = name[1];
2135 HFSTOVCB(hfsmp)->vcbAtrb |= kHFSVolumeJournaledMask;
2136 hfsmp->jvp = jvp;
2137 hfsmp->jnl = jnl;
2138
2139 // save this off for the hack-y check in hfs_remove()
2140 hfsmp->jnl_start = (u_int32_t)name[2];
55e303ae 2141 hfsmp->jnl_size = (off_t)((unsigned)name[3]);
b4c24cb9
A
2142 hfsmp->hfs_jnlinfoblkid = jinfo_attr.ca_fileid;
2143 hfsmp->hfs_jnlfileid = jnl_attr.ca_fileid;
2144
2d21ac55 2145 vfs_setflags(hfsmp->hfs_mp, (u_int64_t)((unsigned int)MNT_JOURNALED));
b4c24cb9
A
2146
2147 hfs_global_exclusive_lock_release(hfsmp);
2148 hfs_flushvolumeheader(hfsmp, MNT_WAIT, 1);
2149
2150 return 0;
55e303ae 2151 } else if (name[0] == HFS_DISABLE_JOURNALING) {
b4c24cb9 2152 // clear the journaling bit
2d21ac55 2153 vnode_t vp = vfs_context_cwd(context);
b4c24cb9 2154
d7e50217 2155 /* Only root can disable journaling */
91447636 2156 if (!is_suser()) {
d7e50217
A
2157 return (EPERM);
2158 }
2d21ac55 2159 if (vp == NULLVP)
91447636 2160 return EINVAL;
55e303ae 2161
b4c24cb9 2162 hfsmp = VTOHFS(vp);
b4c24cb9 2163
2d21ac55
A
2164 /*
2165 * Disabling journaling is disallowed on volumes with directory hard links
2166 * because we have not tested the relevant code path.
2167 */
2168 if (hfsmp->hfs_private_attr[DIR_HARDLINKS].ca_entries != 0){
2169 printf("hfs: cannot disable journaling on volumes with directory hardlinks\n");
2170 return EPERM;
2171 }
2172
2173 printf("hfs: disabling journaling for mount @ %p\n", vnode_mount(vp));
b4c24cb9 2174
b4c24cb9
A
2175 hfs_global_exclusive_lock_acquire(hfsmp);
2176
2177 // Lights out for you buddy!
91447636 2178 journal_close(hfsmp->jnl);
b4c24cb9 2179 hfsmp->jnl = NULL;
b4c24cb9
A
2180
2181 if (hfsmp->jvp && hfsmp->jvp != hfsmp->hfs_devvp) {
91447636 2182 VNOP_CLOSE(hfsmp->jvp, hfsmp->hfs_flags & HFS_READ_ONLY ? FREAD : FREAD|FWRITE, context);
b4c24cb9 2183 }
b4c24cb9 2184 hfsmp->jvp = NULL;
2d21ac55 2185 vfs_clearflags(hfsmp->hfs_mp, (u_int64_t)((unsigned int)MNT_JOURNALED));
b4c24cb9
A
2186 hfsmp->jnl_start = 0;
2187 hfsmp->hfs_jnlinfoblkid = 0;
2188 hfsmp->hfs_jnlfileid = 0;
2189
2190 HFSTOVCB(hfsmp)->vcbAtrb &= ~kHFSVolumeJournaledMask;
2191
2192 hfs_global_exclusive_lock_release(hfsmp);
2193 hfs_flushvolumeheader(hfsmp, MNT_WAIT, 1);
2194
2195 return 0;
55e303ae 2196 } else if (name[0] == HFS_GET_JOURNAL_INFO) {
2d21ac55 2197 vnode_t vp = vfs_context_cwd(context);
55e303ae
A
2198 off_t jnl_start, jnl_size;
2199
2d21ac55 2200 if (vp == NULLVP)
91447636
A
2201 return EINVAL;
2202
55e303ae
A
2203 hfsmp = VTOHFS(vp);
2204 if (hfsmp->jnl == NULL) {
2205 jnl_start = 0;
2206 jnl_size = 0;
2207 } else {
2208 jnl_start = (off_t)(hfsmp->jnl_start * HFSTOVCB(hfsmp)->blockSize) + (off_t)HFSTOVCB(hfsmp)->hfsPlusIOPosOffset;
2209 jnl_size = (off_t)hfsmp->jnl_size;
2210 }
2211
91447636 2212 if ((error = copyout((caddr_t)&jnl_start, CAST_USER_ADDR_T(name[1]), sizeof(off_t))) != 0) {
55e303ae
A
2213 return error;
2214 }
91447636 2215 if ((error = copyout((caddr_t)&jnl_size, CAST_USER_ADDR_T(name[2]), sizeof(off_t))) != 0) {
55e303ae
A
2216 return error;
2217 }
2218
2219 return 0;
2220 } else if (name[0] == HFS_SET_PKG_EXTENSIONS) {
2221
2222 return set_package_extensions_table((void *)name[1], name[2], name[3]);
2223
2224 } else if (name[0] == VFS_CTL_QUERY) {
91447636
A
2225 struct sysctl_req *req;
2226 struct vfsidctl vc;
2227 struct user_vfsidctl user_vc;
2228 struct mount *mp;
2229 struct vfsquery vq;
2230 boolean_t is_64_bit;
2231
2232 is_64_bit = proc_is64bit(p);
2233 req = CAST_DOWN(struct sysctl_req *, oldp); /* we're new style vfs sysctl. */
55e303ae 2234
91447636
A
2235 if (is_64_bit) {
2236 error = SYSCTL_IN(req, &user_vc, sizeof(user_vc));
2237 if (error) return (error);
2238
2239 mp = vfs_getvfs(&user_vc.vc_fsid);
2240 }
2241 else {
2242 error = SYSCTL_IN(req, &vc, sizeof(vc));
2243 if (error) return (error);
2244
2245 mp = vfs_getvfs(&vc.vc_fsid);
2246 }
2247 if (mp == NULL) return (ENOENT);
55e303ae
A
2248
2249 hfsmp = VFSTOHFS(mp);
2250 bzero(&vq, sizeof(vq));
2251 vq.vq_flags = hfsmp->hfs_notification_conditions;
2252 return SYSCTL_OUT(req, &vq, sizeof(vq));;
2d21ac55
A
2253 } else if (name[0] == HFS_REPLAY_JOURNAL) {
2254 char *devnode = NULL;
2255 size_t devnode_len;
2256
2257 devnode_len = *oldlenp;
2258 MALLOC(devnode, char *, devnode_len + 1, M_TEMP, M_WAITOK);
2259 if (devnode == NULL) {
2260 return ENOMEM;
2261 }
2262
2263 error = copyin(oldp, (caddr_t)devnode, devnode_len);
2264 if (error) {
2265 FREE(devnode, M_TEMP);
2266 return error;
2267 }
2268 devnode[devnode_len] = 0;
2269
2270 error = hfs_journal_replay(devnode, context);
2271 FREE(devnode, M_TEMP);
2272 return error;
2273 }
9bccf70c 2274
91447636 2275 return (ENOTSUP);
1c79356b
A
2276}
2277
2278
9bccf70c 2279static int
91447636
A
2280hfs_vfs_vget(struct mount *mp, ino64_t ino, struct vnode **vpp, __unused vfs_context_t context)
2281{
2d21ac55
A
2282 int error;
2283
2284 error = hfs_vget(VFSTOHFS(mp), (cnid_t)ino, vpp, 1);
2285 if (error)
2286 return (error);
2287
2288 /*
2289 * ADLs may need to have their origin state updated
2290 * since build_path needs a valid parent.
2291 */
2292 if (vnode_isdir(*vpp) &&
2293 (VTOC(*vpp)->c_flag & C_HARDLINK) &&
2294 (hfs_lock(VTOC(*vpp), HFS_EXCLUSIVE_LOCK) == 0)) {
2295 cnode_t *cp = VTOC(*vpp);
2296 struct cat_desc cdesc;
2297
2298 if (!hfs_haslinkorigin(cp) &&
2299 (cat_findname(VFSTOHFS(mp), (cnid_t)ino, &cdesc) == 0)) {
2300 if (cdesc.cd_parentcnid !=
2301 VFSTOHFS(mp)->hfs_private_desc[DIR_HARDLINKS].cd_cnid) {
2302 hfs_savelinkorigin(cp, cdesc.cd_parentcnid);
2303 }
2304 cat_releasedesc(&cdesc);
2305 }
2306 hfs_unlock(cp);
2307 }
2308 return (0);
91447636
A
2309}
2310
2311
2312/*
2313 * Look up an HFS object by ID.
2314 *
2315 * The object is returned with an iocount reference and the cnode locked.
2316 *
2317 * If the object is a file then it will represent the data fork.
2318 */
2319__private_extern__
2320int
2321hfs_vget(struct hfsmount *hfsmp, cnid_t cnid, struct vnode **vpp, int skiplock)
9bccf70c 2322{
2d21ac55 2323 struct vnode *vp = NULLVP;
91447636
A
2324 struct cat_desc cndesc;
2325 struct cat_attr cnattr;
2326 struct cat_fork cnfork;
743b1565 2327 u_int32_t linkref = 0;
91447636 2328 int error;
9bccf70c
A
2329
2330 /* Check for cnids that should't be exported. */
2d21ac55
A
2331 if ((cnid < kHFSFirstUserCatalogNodeID) &&
2332 (cnid != kHFSRootFolderID && cnid != kHFSRootParentID)) {
9bccf70c 2333 return (ENOENT);
2d21ac55
A
2334 }
2335 /* Don't export our private directories. */
2336 if (cnid == hfsmp->hfs_private_desc[FILE_HARDLINKS].cd_cnid ||
2337 cnid == hfsmp->hfs_private_desc[DIR_HARDLINKS].cd_cnid) {
9bccf70c 2338 return (ENOENT);
2d21ac55 2339 }
91447636
A
2340 /*
2341 * Check the hash first
2342 */
2343 vp = hfs_chash_getvnode(hfsmp->hfs_raw_dev, cnid, 0, skiplock);
2344 if (vp) {
2345 *vpp = vp;
2346 return(0);
2347 }
9bccf70c 2348
91447636
A
2349 bzero(&cndesc, sizeof(cndesc));
2350 bzero(&cnattr, sizeof(cnattr));
2351 bzero(&cnfork, sizeof(cnfork));
55e303ae 2352
91447636
A
2353 /*
2354 * Not in hash, lookup in catalog
2355 */
2356 if (cnid == kHFSRootParentID) {
2357 static char hfs_rootname[] = "/";
2358
2d21ac55 2359 cndesc.cd_nameptr = (const u_int8_t *)&hfs_rootname[0];
91447636
A
2360 cndesc.cd_namelen = 1;
2361 cndesc.cd_parentcnid = kHFSRootParentID;
2362 cndesc.cd_cnid = kHFSRootFolderID;
2363 cndesc.cd_flags = CD_ISDIR;
2364
2365 cnattr.ca_fileid = kHFSRootFolderID;
2d21ac55 2366 cnattr.ca_linkcount = 1;
91447636 2367 cnattr.ca_entries = 1;
2d21ac55 2368 cnattr.ca_dircount = 1;
91447636
A
2369 cnattr.ca_mode = (S_IFDIR | S_IRWXU | S_IRWXG | S_IRWXO);
2370 } else {
2371 int lockflags;
2d21ac55
A
2372 cnid_t pid;
2373 const char *nameptr;
55e303ae 2374
91447636 2375 lockflags = hfs_systemfile_lock(hfsmp, SFL_CATALOG, HFS_SHARED_LOCK);
2d21ac55 2376 error = cat_idlookup(hfsmp, cnid, 0, &cndesc, &cnattr, &cnfork);
91447636
A
2377 hfs_systemfile_unlock(hfsmp, lockflags);
2378
2379 if (error) {
2380 *vpp = NULL;
2381 return (error);
55e303ae 2382 }
91447636 2383
743b1565 2384 /*
2d21ac55 2385 * Check for a raw hardlink inode and save its linkref.
743b1565 2386 */
2d21ac55
A
2387 pid = cndesc.cd_parentcnid;
2388 nameptr = (const char *)cndesc.cd_nameptr;
2389
2390 if ((pid == hfsmp->hfs_private_desc[FILE_HARDLINKS].cd_cnid) &&
2391 (bcmp(nameptr, HFS_INODE_PREFIX, HFS_INODE_PREFIX_LEN) == 0)) {
2392 linkref = strtoul(&nameptr[HFS_INODE_PREFIX_LEN], NULL, 10);
2393
2394 } else if ((pid == hfsmp->hfs_private_desc[DIR_HARDLINKS].cd_cnid) &&
2395 (bcmp(nameptr, HFS_DIRINODE_PREFIX, HFS_DIRINODE_PREFIX_LEN) == 0)) {
2396 linkref = strtoul(&nameptr[HFS_DIRINODE_PREFIX_LEN], NULL, 10);
2397
2398 } else if ((pid == hfsmp->hfs_private_desc[FILE_HARDLINKS].cd_cnid) &&
2399 (bcmp(nameptr, HFS_DELETE_PREFIX, HFS_DELETE_PREFIX_LEN) == 0)) {
2400 *vpp = NULL;
2401 return (ENOENT); /* open unlinked file */
91447636
A
2402 }
2403 }
2404
2405 /*
2d21ac55
A
2406 * Finish initializing cnode descriptor for hardlinks.
2407 *
2408 * We need a valid name and parent for reverse lookups.
91447636 2409 */
2d21ac55
A
2410 if (linkref) {
2411 cnid_t nextlinkid;
2412 cnid_t prevlinkid;
2413 struct cat_desc linkdesc;
2414
2415 cnattr.ca_linkref = linkref;
91447636 2416
2d21ac55
A
2417 /*
2418 * Pick up the first link in the chain and get a descriptor for it.
2419 * This allows blind volfs paths to work for hardlinks.
2420 */
2421 if ((hfs_lookuplink(hfsmp, linkref, &prevlinkid, &nextlinkid) == 0) &&
2422 (nextlinkid != 0)) {
2423 if (cat_findname(hfsmp, nextlinkid, &linkdesc) == 0) {
2424 cat_releasedesc(&cndesc);
2425 bcopy(&linkdesc, &cndesc, sizeof(linkdesc));
2426 }
2427 }
743b1565
A
2428 }
2429
2d21ac55
A
2430 if (linkref) {
2431 error = hfs_getnewvnode(hfsmp, NULL, NULL, &cndesc, 0, &cnattr, &cnfork, &vp);
2432 if (error == 0) {
2433 VTOC(vp)->c_flag |= C_HARDLINK;
2434 vnode_setmultipath(vp);
2435 }
2436 } else {
2437 struct componentname cn;
2438
2439 /* Supply hfs_getnewvnode with a component name. */
2440 MALLOC_ZONE(cn.cn_pnbuf, caddr_t, MAXPATHLEN, M_NAMEI, M_WAITOK);
2441 cn.cn_nameiop = LOOKUP;
2442 cn.cn_flags = ISLASTCN | HASBUF;
2443 cn.cn_context = NULL;
2444 cn.cn_pnlen = MAXPATHLEN;
2445 cn.cn_nameptr = cn.cn_pnbuf;
2446 cn.cn_namelen = cndesc.cd_namelen;
2447 cn.cn_hash = 0;
2448 cn.cn_consume = 0;
2449 bcopy(cndesc.cd_nameptr, cn.cn_nameptr, cndesc.cd_namelen + 1);
2450
2451 error = hfs_getnewvnode(hfsmp, NULLVP, &cn, &cndesc, 0, &cnattr, &cnfork, &vp);
91447636 2452
2d21ac55
A
2453 if (error == 0 && (VTOC(vp)->c_flag & C_HARDLINK) && vnode_isdir(vp)) {
2454 hfs_savelinkorigin(VTOC(vp), cndesc.cd_parentcnid);
2455 }
2456 FREE_ZONE(cn.cn_pnbuf, cn.cn_pnlen, M_NAMEI);
2457 }
91447636 2458 cat_releasedesc(&cndesc);
2d21ac55 2459
91447636 2460 *vpp = vp;
2d21ac55 2461 if (vp && skiplock) {
91447636 2462 hfs_unlock(VTOC(vp));
2d21ac55 2463 }
91447636 2464 return (error);
55e303ae
A
2465}
2466
91447636 2467
9bccf70c
A
2468/*
2469 * Flush out all the files in a filesystem.
2470 */
55e303ae 2471static int
2d21ac55 2472#if QUOTA
9bccf70c 2473hfs_flushfiles(struct mount *mp, int flags, struct proc *p)
2d21ac55
A
2474#else
2475hfs_flushfiles(struct mount *mp, int flags, __unused struct proc *p)
2476#endif /* QUOTA */
1c79356b 2477{
55e303ae
A
2478 struct hfsmount *hfsmp;
2479 struct vnode *skipvp = NULLVP;
2d21ac55
A
2480 int error;
2481#if QUOTA
55e303ae 2482 int quotafilecnt;
9bccf70c 2483 int i;
2d21ac55 2484#endif
1c79356b 2485
9bccf70c 2486 hfsmp = VFSTOHFS(mp);
1c79356b 2487
55e303ae
A
2488#if QUOTA
2489 /*
2490 * The open quota files have an indirect reference on
2491 * the root directory vnode. We must account for this
2492 * extra reference when doing the intial vflush.
2493 */
2494 quotafilecnt = 0;
91447636 2495 if (((unsigned int)vfs_flags(mp)) & MNT_QUOTA) {
55e303ae
A
2496
2497 /* Find out how many quota files we have open. */
2498 for (i = 0; i < MAXQUOTAS; i++) {
2499 if (hfsmp->hfs_qfiles[i].qf_vp != NULLVP)
2500 ++quotafilecnt;
2501 }
2502
2503 /* Obtain the root vnode so we can skip over it. */
91447636 2504 skipvp = hfs_chash_getvnode(hfsmp->hfs_raw_dev, kHFSRootFolderID, 0, 0);
55e303ae
A
2505 }
2506#endif /* QUOTA */
2507
2508 error = vflush(mp, skipvp, SKIPSYSTEM | SKIPSWAP | flags);
91447636
A
2509 if (error != 0)
2510 return(error);
2511
55e303ae
A
2512 error = vflush(mp, skipvp, SKIPSYSTEM | flags);
2513
2514#if QUOTA
91447636 2515 if (((unsigned int)vfs_flags(mp)) & MNT_QUOTA) {
55e303ae
A
2516 if (skipvp) {
2517 /*
2518 * See if there are additional references on the
2519 * root vp besides the ones obtained from the open
91447636 2520 * quota files and the hfs_chash_getvnode call above.
55e303ae
A
2521 */
2522 if ((error == 0) &&
91447636 2523 (vnode_isinuse(skipvp, quotafilecnt))) {
55e303ae
A
2524 error = EBUSY; /* root directory is still open */
2525 }
91447636
A
2526 hfs_unlock(VTOC(skipvp));
2527 vnode_put(skipvp);
55e303ae
A
2528 }
2529 if (error && (flags & FORCECLOSE) == 0)
9bccf70c 2530 return (error);
55e303ae 2531
9bccf70c
A
2532 for (i = 0; i < MAXQUOTAS; i++) {
2533 if (hfsmp->hfs_qfiles[i].qf_vp == NULLVP)
2534 continue;
2535 hfs_quotaoff(p, mp, i);
2536 }
55e303ae 2537 error = vflush(mp, NULLVP, SKIPSYSTEM | flags);
1c79356b 2538 }
9bccf70c 2539#endif /* QUOTA */
1c79356b 2540
9bccf70c
A
2541 return (error);
2542}
1c79356b 2543
9bccf70c
A
2544/*
2545 * Update volume encoding bitmap (HFS Plus only)
2546 */
2547__private_extern__
2548void
2549hfs_setencodingbits(struct hfsmount *hfsmp, u_int32_t encoding)
2550{
2551#define kIndexMacUkrainian 48 /* MacUkrainian encoding is 152 */
2552#define kIndexMacFarsi 49 /* MacFarsi encoding is 140 */
2553
2d21ac55 2554 u_int32_t index;
9bccf70c
A
2555
2556 switch (encoding) {
2557 case kTextEncodingMacUkrainian:
2558 index = kIndexMacUkrainian;
2559 break;
2560 case kTextEncodingMacFarsi:
2561 index = kIndexMacFarsi;
2562 break;
2563 default:
2564 index = encoding;
2565 break;
2566 }
1c79356b 2567
2d21ac55 2568 if (index < 64 && (hfsmp->encodingsBitmap & (u_int64_t)(1ULL << index)) == 0) {
91447636
A
2569 HFS_MOUNT_LOCK(hfsmp, TRUE)
2570 hfsmp->encodingsBitmap |= (u_int64_t)(1ULL << index);
2d21ac55 2571 MarkVCBDirty(hfsmp);
91447636 2572 HFS_MOUNT_UNLOCK(hfsmp, TRUE);
9bccf70c 2573 }
1c79356b
A
2574}
2575
2576/*
9bccf70c 2577 * Update volume stats
91447636
A
2578 *
2579 * On journal volumes this will cause a volume header flush
1c79356b 2580 */
9bccf70c 2581__private_extern__
1c79356b 2582int
9bccf70c 2583hfs_volupdate(struct hfsmount *hfsmp, enum volop op, int inroot)
1c79356b 2584{
91447636 2585 struct timeval tv;
1c79356b 2586
91447636
A
2587 microtime(&tv);
2588
2589 lck_mtx_lock(&hfsmp->hfs_mutex);
2590
2d21ac55 2591 MarkVCBDirty(hfsmp);
91447636 2592 hfsmp->hfs_mtime = tv.tv_sec;
9bccf70c
A
2593
2594 switch (op) {
2595 case VOL_UPDATE:
2596 break;
2597 case VOL_MKDIR:
91447636
A
2598 if (hfsmp->hfs_dircount != 0xFFFFFFFF)
2599 ++hfsmp->hfs_dircount;
2600 if (inroot && hfsmp->vcbNmRtDirs != 0xFFFF)
2601 ++hfsmp->vcbNmRtDirs;
9bccf70c
A
2602 break;
2603 case VOL_RMDIR:
91447636
A
2604 if (hfsmp->hfs_dircount != 0)
2605 --hfsmp->hfs_dircount;
2606 if (inroot && hfsmp->vcbNmRtDirs != 0xFFFF)
2607 --hfsmp->vcbNmRtDirs;
9bccf70c
A
2608 break;
2609 case VOL_MKFILE:
91447636
A
2610 if (hfsmp->hfs_filecount != 0xFFFFFFFF)
2611 ++hfsmp->hfs_filecount;
2612 if (inroot && hfsmp->vcbNmFls != 0xFFFF)
2613 ++hfsmp->vcbNmFls;
9bccf70c
A
2614 break;
2615 case VOL_RMFILE:
91447636
A
2616 if (hfsmp->hfs_filecount != 0)
2617 --hfsmp->hfs_filecount;
2618 if (inroot && hfsmp->vcbNmFls != 0xFFFF)
2619 --hfsmp->vcbNmFls;
9bccf70c
A
2620 break;
2621 }
b4c24cb9 2622
91447636
A
2623 lck_mtx_unlock(&hfsmp->hfs_mutex);
2624
b4c24cb9
A
2625 if (hfsmp->jnl) {
2626 hfs_flushvolumeheader(hfsmp, 0, 0);
2627 }
2628
9bccf70c 2629 return (0);
1c79356b
A
2630}
2631
9bccf70c
A
2632
2633static int
2634hfs_flushMDB(struct hfsmount *hfsmp, int waitfor, int altflush)
1c79356b 2635{
9bccf70c
A
2636 ExtendedVCB *vcb = HFSTOVCB(hfsmp);
2637 struct filefork *fp;
1c79356b 2638 HFSMasterDirectoryBlock *mdb;
9bccf70c
A
2639 struct buf *bp = NULL;
2640 int retval;
2641 int sectorsize;
2642 ByteCount namelen;
1c79356b 2643
9bccf70c 2644 sectorsize = hfsmp->hfs_phys_block_size;
91447636 2645 retval = (int)buf_bread(hfsmp->hfs_devvp, (daddr64_t)HFS_PRI_SECTOR(sectorsize), sectorsize, NOCRED, &bp);
1c79356b 2646 if (retval) {
9bccf70c 2647 if (bp)
91447636 2648 buf_brelse(bp);
1c79356b
A
2649 return retval;
2650 }
2651
91447636 2652 lck_mtx_lock(&hfsmp->hfs_mutex);
b4c24cb9 2653
91447636 2654 mdb = (HFSMasterDirectoryBlock *)(buf_dataptr(bp) + HFS_PRI_OFFSET(sectorsize));
1c79356b 2655
9bccf70c
A
2656 mdb->drCrDate = SWAP_BE32 (UTCToLocal(to_hfs_time(vcb->vcbCrDate)));
2657 mdb->drLsMod = SWAP_BE32 (UTCToLocal(to_hfs_time(vcb->vcbLsMod)));
2658 mdb->drAtrb = SWAP_BE16 (vcb->vcbAtrb);
1c79356b
A
2659 mdb->drNmFls = SWAP_BE16 (vcb->vcbNmFls);
2660 mdb->drAllocPtr = SWAP_BE16 (vcb->nextAllocation);
2661 mdb->drClpSiz = SWAP_BE32 (vcb->vcbClpSiz);
2662 mdb->drNxtCNID = SWAP_BE32 (vcb->vcbNxtCNID);
2663 mdb->drFreeBks = SWAP_BE16 (vcb->freeBlocks);
2664
2d21ac55 2665 namelen = strlen((char *)vcb->vcbVN);
1c79356b
A
2666 retval = utf8_to_hfs(vcb, namelen, vcb->vcbVN, mdb->drVN);
2667 /* Retry with MacRoman in case that's how it was exported. */
2668 if (retval)
2669 retval = utf8_to_mac_roman(namelen, vcb->vcbVN, mdb->drVN);
2670
9bccf70c 2671 mdb->drVolBkUp = SWAP_BE32 (UTCToLocal(to_hfs_time(vcb->vcbVolBkUp)));
1c79356b
A
2672 mdb->drWrCnt = SWAP_BE32 (vcb->vcbWrCnt);
2673 mdb->drNmRtDirs = SWAP_BE16 (vcb->vcbNmRtDirs);
2674 mdb->drFilCnt = SWAP_BE32 (vcb->vcbFilCnt);
2675 mdb->drDirCnt = SWAP_BE32 (vcb->vcbDirCnt);
2676
2677 bcopy(vcb->vcbFndrInfo, mdb->drFndrInfo, sizeof(mdb->drFndrInfo));
2678
9bccf70c
A
2679 fp = VTOF(vcb->extentsRefNum);
2680 mdb->drXTExtRec[0].startBlock = SWAP_BE16 (fp->ff_extents[0].startBlock);
2681 mdb->drXTExtRec[0].blockCount = SWAP_BE16 (fp->ff_extents[0].blockCount);
2682 mdb->drXTExtRec[1].startBlock = SWAP_BE16 (fp->ff_extents[1].startBlock);
2683 mdb->drXTExtRec[1].blockCount = SWAP_BE16 (fp->ff_extents[1].blockCount);
2684 mdb->drXTExtRec[2].startBlock = SWAP_BE16 (fp->ff_extents[2].startBlock);
2685 mdb->drXTExtRec[2].blockCount = SWAP_BE16 (fp->ff_extents[2].blockCount);
2686 mdb->drXTFlSize = SWAP_BE32 (fp->ff_blocks * vcb->blockSize);
2687 mdb->drXTClpSiz = SWAP_BE32 (fp->ff_clumpsize);
91447636 2688 FTOC(fp)->c_flag &= ~C_MODIFIED;
1c79356b 2689
9bccf70c
A
2690 fp = VTOF(vcb->catalogRefNum);
2691 mdb->drCTExtRec[0].startBlock = SWAP_BE16 (fp->ff_extents[0].startBlock);
2692 mdb->drCTExtRec[0].blockCount = SWAP_BE16 (fp->ff_extents[0].blockCount);
2693 mdb->drCTExtRec[1].startBlock = SWAP_BE16 (fp->ff_extents[1].startBlock);
2694 mdb->drCTExtRec[1].blockCount = SWAP_BE16 (fp->ff_extents[1].blockCount);
2695 mdb->drCTExtRec[2].startBlock = SWAP_BE16 (fp->ff_extents[2].startBlock);
2696 mdb->drCTExtRec[2].blockCount = SWAP_BE16 (fp->ff_extents[2].blockCount);
2697 mdb->drCTFlSize = SWAP_BE32 (fp->ff_blocks * vcb->blockSize);
2698 mdb->drCTClpSiz = SWAP_BE32 (fp->ff_clumpsize);
91447636
A
2699 FTOC(fp)->c_flag &= ~C_MODIFIED;
2700
2701 MarkVCBClean( vcb );
2702
2703 lck_mtx_unlock(&hfsmp->hfs_mutex);
9bccf70c
A
2704
2705 /* If requested, flush out the alternate MDB */
2706 if (altflush) {
2707 struct buf *alt_bp = NULL;
9bccf70c 2708
91447636
A
2709 if (buf_meta_bread(hfsmp->hfs_devvp, hfsmp->hfs_alt_id_sector, sectorsize, NOCRED, &alt_bp) == 0) {
2710 bcopy(mdb, (char *)buf_dataptr(alt_bp) + HFS_ALT_OFFSET(sectorsize), kMDBSize);
b4c24cb9 2711
91447636 2712 (void) VNOP_BWRITE(alt_bp);
9bccf70c 2713 } else if (alt_bp)
91447636 2714 buf_brelse(alt_bp);
9bccf70c 2715 }
1c79356b 2716
9bccf70c 2717 if (waitfor != MNT_WAIT)
91447636 2718 buf_bawrite(bp);
b4c24cb9 2719 else
91447636 2720 retval = VNOP_BWRITE(bp);
1c79356b
A
2721
2722 return (retval);
2723}
2724
55e303ae
A
2725/*
2726 * Flush any dirty in-memory mount data to the on-disk
2727 * volume header.
2728 *
2729 * Note: the on-disk volume signature is intentionally
2730 * not flushed since the on-disk "H+" and "HX" signatures
2731 * are always stored in-memory as "H+".
2732 */
9bccf70c
A
2733__private_extern__
2734int
2735hfs_flushvolumeheader(struct hfsmount *hfsmp, int waitfor, int altflush)
1c79356b 2736{
9bccf70c
A
2737 ExtendedVCB *vcb = HFSTOVCB(hfsmp);
2738 struct filefork *fp;
2739 HFSPlusVolumeHeader *volumeHeader;
2740 int retval;
2741 struct buf *bp;
2742 int i;
d52fe63f 2743 int sectorsize;
91447636 2744 daddr64_t priIDSector;
2d21ac55 2745 int critical;
55e303ae 2746 u_int16_t signature;
91447636 2747 u_int16_t hfsversion;
1c79356b 2748
55e303ae
A
2749 if (hfsmp->hfs_flags & HFS_READ_ONLY) {
2750 return(0);
2751 }
2d21ac55 2752 if (hfsmp->hfs_flags & HFS_STANDARD) {
9bccf70c 2753 return hfs_flushMDB(hfsmp, waitfor, altflush);
2d21ac55
A
2754 }
2755 critical = altflush;
d52fe63f 2756 sectorsize = hfsmp->hfs_phys_block_size;
91447636
A
2757 priIDSector = (daddr64_t)((vcb->hfsPlusIOPosOffset / sectorsize) +
2758 HFS_PRI_SECTOR(sectorsize));
d52fe63f 2759
91447636
A
2760 if (hfs_start_transaction(hfsmp) != 0) {
2761 return EINVAL;
b4c24cb9
A
2762 }
2763
91447636 2764 retval = (int)buf_meta_bread(hfsmp->hfs_devvp, priIDSector, sectorsize, NOCRED, &bp);
1c79356b 2765 if (retval) {
9bccf70c 2766 if (bp)
91447636 2767 buf_brelse(bp);
b4c24cb9 2768
91447636 2769 hfs_end_transaction(hfsmp);
b4c24cb9 2770
55e303ae 2771 printf("HFS: err %d reading VH blk (%s)\n", retval, vcb->vcbVN);
9bccf70c 2772 return (retval);
1c79356b
A
2773 }
2774
b4c24cb9
A
2775 if (hfsmp->jnl) {
2776 journal_modify_block_start(hfsmp->jnl, bp);
2777 }
2778
91447636 2779 volumeHeader = (HFSPlusVolumeHeader *)((char *)buf_dataptr(bp) + HFS_PRI_OFFSET(sectorsize));
1c79356b 2780
55e303ae
A
2781 /*
2782 * Sanity check what we just read.
2783 */
2784 signature = SWAP_BE16 (volumeHeader->signature);
91447636 2785 hfsversion = SWAP_BE16 (volumeHeader->version);
55e303ae 2786 if ((signature != kHFSPlusSigWord && signature != kHFSXSigWord) ||
91447636 2787 (hfsversion < kHFSPlusVersion) || (hfsversion > 100) ||
55e303ae
A
2788 (SWAP_BE32 (volumeHeader->blockSize) != vcb->blockSize)) {
2789#if 1
2790 panic("HFS: corrupt VH on %s, sig 0x%04x, ver %d, blksize %d",
91447636 2791 vcb->vcbVN, signature, hfsversion,
55e303ae
A
2792 SWAP_BE32 (volumeHeader->blockSize));
2793#endif
2794 printf("HFS: corrupt VH blk (%s)\n", vcb->vcbVN);
91447636 2795 buf_brelse(bp);
55e303ae
A
2796 return (EIO);
2797 }
2798
1c79356b
A
2799 /*
2800 * For embedded HFS+ volumes, update create date if it changed
2801 * (ie from a setattrlist call)
2802 */
9bccf70c
A
2803 if ((vcb->hfsPlusIOPosOffset != 0) &&
2804 (SWAP_BE32 (volumeHeader->createDate) != vcb->localCreateDate)) {
2805 struct buf *bp2;
1c79356b
A
2806 HFSMasterDirectoryBlock *mdb;
2807
91447636 2808 retval = (int)buf_meta_bread(hfsmp->hfs_devvp, (daddr64_t)HFS_PRI_SECTOR(sectorsize),
9bccf70c
A
2809 sectorsize, NOCRED, &bp2);
2810 if (retval) {
2811 if (bp2)
91447636 2812 buf_brelse(bp2);
9bccf70c 2813 retval = 0;
1c79356b 2814 } else {
91447636 2815 mdb = (HFSMasterDirectoryBlock *)(buf_dataptr(bp2) +
9bccf70c 2816 HFS_PRI_OFFSET(sectorsize));
1c79356b
A
2817
2818 if ( SWAP_BE32 (mdb->drCrDate) != vcb->localCreateDate )
2819 {
b4c24cb9
A
2820 if (hfsmp->jnl) {
2821 journal_modify_block_start(hfsmp->jnl, bp2);
2822 }
2823
1c79356b
A
2824 mdb->drCrDate = SWAP_BE32 (vcb->localCreateDate); /* pick up the new create date */
2825
b4c24cb9 2826 if (hfsmp->jnl) {
2d21ac55 2827 journal_modify_block_end(hfsmp->jnl, bp2, NULL, NULL);
b4c24cb9 2828 } else {
91447636 2829 (void) VNOP_BWRITE(bp2); /* write out the changes */
b4c24cb9 2830 }
1c79356b
A
2831 }
2832 else
2833 {
91447636 2834 buf_brelse(bp2); /* just release it */
1c79356b
A
2835 }
2836 }
9bccf70c 2837 }
1c79356b 2838
2d21ac55 2839 lck_mtx_lock(&hfsmp->hfs_mutex);
91447636 2840
1c79356b 2841 /* Note: only update the lower 16 bits worth of attributes */
91447636
A
2842 volumeHeader->attributes = SWAP_BE32 (vcb->vcbAtrb);
2843 volumeHeader->journalInfoBlock = SWAP_BE32 (vcb->vcbJinfoBlock);
b4c24cb9
A
2844 if (hfsmp->jnl) {
2845 volumeHeader->lastMountedVersion = SWAP_BE32 (kHFSJMountVersion);
2846 } else {
2847 volumeHeader->lastMountedVersion = SWAP_BE32 (kHFSPlusMountVersion);
2848 }
9bccf70c
A
2849 volumeHeader->createDate = SWAP_BE32 (vcb->localCreateDate); /* volume create date is in local time */
2850 volumeHeader->modifyDate = SWAP_BE32 (to_hfs_time(vcb->vcbLsMod));
2851 volumeHeader->backupDate = SWAP_BE32 (to_hfs_time(vcb->vcbVolBkUp));
2852 volumeHeader->fileCount = SWAP_BE32 (vcb->vcbFilCnt);
2853 volumeHeader->folderCount = SWAP_BE32 (vcb->vcbDirCnt);
91447636 2854 volumeHeader->totalBlocks = SWAP_BE32 (vcb->totalBlocks);
9bccf70c
A
2855 volumeHeader->freeBlocks = SWAP_BE32 (vcb->freeBlocks);
2856 volumeHeader->nextAllocation = SWAP_BE32 (vcb->nextAllocation);
2857 volumeHeader->rsrcClumpSize = SWAP_BE32 (vcb->vcbClpSiz);
2858 volumeHeader->dataClumpSize = SWAP_BE32 (vcb->vcbClpSiz);
2859 volumeHeader->nextCatalogID = SWAP_BE32 (vcb->vcbNxtCNID);
2860 volumeHeader->writeCount = SWAP_BE32 (vcb->vcbWrCnt);
2861 volumeHeader->encodingsBitmap = SWAP_BE64 (vcb->encodingsBitmap);
2862
91447636
A
2863 if (bcmp(vcb->vcbFndrInfo, volumeHeader->finderInfo, sizeof(volumeHeader->finderInfo)) != 0) {
2864 bcopy(vcb->vcbFndrInfo, volumeHeader->finderInfo, sizeof(volumeHeader->finderInfo));
9bccf70c 2865 critical = 1;
91447636 2866 }
9bccf70c 2867
2d21ac55
A
2868 /*
2869 * System files are only dirty when altflush is set.
2870 */
2871 if (altflush == 0) {
2872 goto done;
2873 }
2874
9bccf70c
A
2875 /* Sync Extents over-flow file meta data */
2876 fp = VTOF(vcb->extentsRefNum);
91447636
A
2877 if (FTOC(fp)->c_flag & C_MODIFIED) {
2878 for (i = 0; i < kHFSPlusExtentDensity; i++) {
2879 volumeHeader->extentsFile.extents[i].startBlock =
2880 SWAP_BE32 (fp->ff_extents[i].startBlock);
2881 volumeHeader->extentsFile.extents[i].blockCount =
2882 SWAP_BE32 (fp->ff_extents[i].blockCount);
2883 }
2884 volumeHeader->extentsFile.logicalSize = SWAP_BE64 (fp->ff_size);
2885 volumeHeader->extentsFile.totalBlocks = SWAP_BE32 (fp->ff_blocks);
2886 volumeHeader->extentsFile.clumpSize = SWAP_BE32 (fp->ff_clumpsize);
2887 FTOC(fp)->c_flag &= ~C_MODIFIED;
9bccf70c 2888 }
9bccf70c
A
2889
2890 /* Sync Catalog file meta data */
2891 fp = VTOF(vcb->catalogRefNum);
91447636
A
2892 if (FTOC(fp)->c_flag & C_MODIFIED) {
2893 for (i = 0; i < kHFSPlusExtentDensity; i++) {
2894 volumeHeader->catalogFile.extents[i].startBlock =
2895 SWAP_BE32 (fp->ff_extents[i].startBlock);
2896 volumeHeader->catalogFile.extents[i].blockCount =
2897 SWAP_BE32 (fp->ff_extents[i].blockCount);
2898 }
2899 volumeHeader->catalogFile.logicalSize = SWAP_BE64 (fp->ff_size);
2900 volumeHeader->catalogFile.totalBlocks = SWAP_BE32 (fp->ff_blocks);
2901 volumeHeader->catalogFile.clumpSize = SWAP_BE32 (fp->ff_clumpsize);
2902 FTOC(fp)->c_flag &= ~C_MODIFIED;
9bccf70c 2903 }
9bccf70c
A
2904
2905 /* Sync Allocation file meta data */
2906 fp = VTOF(vcb->allocationsRefNum);
91447636
A
2907 if (FTOC(fp)->c_flag & C_MODIFIED) {
2908 for (i = 0; i < kHFSPlusExtentDensity; i++) {
2909 volumeHeader->allocationFile.extents[i].startBlock =
2910 SWAP_BE32 (fp->ff_extents[i].startBlock);
2911 volumeHeader->allocationFile.extents[i].blockCount =
2912 SWAP_BE32 (fp->ff_extents[i].blockCount);
2913 }
2914 volumeHeader->allocationFile.logicalSize = SWAP_BE64 (fp->ff_size);
2915 volumeHeader->allocationFile.totalBlocks = SWAP_BE32 (fp->ff_blocks);
2916 volumeHeader->allocationFile.clumpSize = SWAP_BE32 (fp->ff_clumpsize);
2917 FTOC(fp)->c_flag &= ~C_MODIFIED;
2918 }
2919
2920 /* Sync Attribute file meta data */
2921 if (hfsmp->hfs_attribute_vp) {
2922 fp = VTOF(hfsmp->hfs_attribute_vp);
2923 for (i = 0; i < kHFSPlusExtentDensity; i++) {
2924 volumeHeader->attributesFile.extents[i].startBlock =
2925 SWAP_BE32 (fp->ff_extents[i].startBlock);
2926 volumeHeader->attributesFile.extents[i].blockCount =
2927 SWAP_BE32 (fp->ff_extents[i].blockCount);
2928 }
2929 FTOC(fp)->c_flag &= ~C_MODIFIED;
2930 volumeHeader->attributesFile.logicalSize = SWAP_BE64 (fp->ff_size);
2931 volumeHeader->attributesFile.totalBlocks = SWAP_BE32 (fp->ff_blocks);
2932 volumeHeader->attributesFile.clumpSize = SWAP_BE32 (fp->ff_clumpsize);
2933 }
2934
2d21ac55
A
2935 /* Sync Startup file meta data */
2936 if (hfsmp->hfs_startup_vp) {
2937 fp = VTOF(hfsmp->hfs_startup_vp);
2938 if (FTOC(fp)->c_flag & C_MODIFIED) {
2939 for (i = 0; i < kHFSPlusExtentDensity; i++) {
2940 volumeHeader->startupFile.extents[i].startBlock =
2941 SWAP_BE32 (fp->ff_extents[i].startBlock);
2942 volumeHeader->startupFile.extents[i].blockCount =
2943 SWAP_BE32 (fp->ff_extents[i].blockCount);
2944 }
2945 volumeHeader->startupFile.logicalSize = SWAP_BE64 (fp->ff_size);
2946 volumeHeader->startupFile.totalBlocks = SWAP_BE32 (fp->ff_blocks);
2947 volumeHeader->startupFile.clumpSize = SWAP_BE32 (fp->ff_clumpsize);
2948 FTOC(fp)->c_flag &= ~C_MODIFIED;
2949 }
9bccf70c 2950 }
9bccf70c 2951
2d21ac55
A
2952done:
2953 MarkVCBClean(hfsmp);
2954 lck_mtx_unlock(&hfsmp->hfs_mutex);
2955
9bccf70c 2956 /* If requested, flush out the alternate volume header */
91447636 2957 if (altflush && hfsmp->hfs_alt_id_sector) {
9bccf70c 2958 struct buf *alt_bp = NULL;
9bccf70c 2959
91447636 2960 if (buf_meta_bread(hfsmp->hfs_devvp, hfsmp->hfs_alt_id_sector, sectorsize, NOCRED, &alt_bp) == 0) {
b4c24cb9
A
2961 if (hfsmp->jnl) {
2962 journal_modify_block_start(hfsmp->jnl, alt_bp);
2963 }
2964
91447636 2965 bcopy(volumeHeader, (char *)buf_dataptr(alt_bp) + HFS_ALT_OFFSET(sectorsize), kMDBSize);
b4c24cb9
A
2966
2967 if (hfsmp->jnl) {
2d21ac55 2968 journal_modify_block_end(hfsmp->jnl, alt_bp, NULL, NULL);
b4c24cb9 2969 } else {
91447636 2970 (void) VNOP_BWRITE(alt_bp);
b4c24cb9 2971 }
9bccf70c 2972 } else if (alt_bp)
91447636 2973 buf_brelse(alt_bp);
9bccf70c
A
2974 }
2975
b4c24cb9 2976 if (hfsmp->jnl) {
2d21ac55 2977 journal_modify_block_end(hfsmp->jnl, bp, NULL, NULL);
b4c24cb9
A
2978 } else {
2979 if (waitfor != MNT_WAIT)
91447636 2980 buf_bawrite(bp);
b4c24cb9 2981 else {
91447636 2982 retval = VNOP_BWRITE(bp);
b4c24cb9
A
2983 /* When critical data changes, flush the device cache */
2984 if (critical && (retval == 0)) {
91447636
A
2985 (void) VNOP_IOCTL(hfsmp->hfs_devvp, DKIOCSYNCHRONIZECACHE,
2986 NULL, FWRITE, NULL);
b4c24cb9 2987 }
9bccf70c
A
2988 }
2989 }
91447636 2990 hfs_end_transaction(hfsmp);
1c79356b 2991
1c79356b
A
2992 return (retval);
2993}
2994
2995
55e303ae
A
2996/*
2997 * Extend a file system.
2998 */
91447636
A
2999__private_extern__
3000int
3001hfs_extendfs(struct hfsmount *hfsmp, u_int64_t newsize, vfs_context_t context)
55e303ae 3002{
91447636
A
3003 struct proc *p = vfs_context_proc(context);
3004 kauth_cred_t cred = vfs_context_ucred(context);
55e303ae
A
3005 struct vnode *vp;
3006 struct vnode *devvp;
3007 struct buf *bp;
55e303ae
A
3008 struct filefork *fp = NULL;
3009 ExtendedVCB *vcb;
3010 struct cat_fork forkdata;
3011 u_int64_t oldsize;
3012 u_int64_t newblkcnt;
91447636 3013 u_int64_t prev_phys_block_count;
55e303ae
A
3014 u_int32_t addblks;
3015 u_int64_t sectorcnt;
3016 u_int32_t sectorsize;
91447636
A
3017 daddr64_t prev_alt_sector;
3018 daddr_t bitmapblks;
3019 int lockflags;
55e303ae 3020 int error;
2d21ac55
A
3021 int64_t oldBitmapSize;
3022 Boolean usedExtendFileC = false;
3023
55e303ae
A
3024 devvp = hfsmp->hfs_devvp;
3025 vcb = HFSTOVCB(hfsmp);
3026
3027 /*
3028 * - HFS Plus file systems only.
3029 * - Journaling must be enabled.
3030 * - No embedded volumes.
3031 */
3032 if ((vcb->vcbSigWord == kHFSSigWord) ||
3033 (hfsmp->jnl == NULL) ||
3034 (vcb->hfsPlusIOPosOffset != 0)) {
3035 return (EPERM);
3036 }
3037 /*
3038 * If extending file system by non-root, then verify
3039 * ownership and check permissions.
3040 */
91447636
A
3041 if (suser(cred, NULL)) {
3042 error = hfs_vget(hfsmp, kHFSRootFolderID, &vp, 0);
3043
55e303ae
A
3044 if (error)
3045 return (error);
91447636 3046 error = hfs_owner_rights(hfsmp, VTOC(vp)->c_uid, cred, p, 0);
55e303ae 3047 if (error == 0) {
91447636 3048 error = hfs_write_access(vp, cred, p, false);
55e303ae 3049 }
91447636
A
3050 hfs_unlock(VTOC(vp));
3051 vnode_put(vp);
55e303ae
A
3052 if (error)
3053 return (error);
3054
91447636 3055 error = vnode_authorize(devvp, NULL, KAUTH_VNODE_READ_DATA | KAUTH_VNODE_WRITE_DATA, context);
55e303ae
A
3056 if (error)
3057 return (error);
3058 }
91447636 3059 if (VNOP_IOCTL(devvp, DKIOCGETBLOCKSIZE, (caddr_t)&sectorsize, 0, context)) {
55e303ae
A
3060 return (ENXIO);
3061 }
3062 if (sectorsize != hfsmp->hfs_phys_block_size) {
3063 return (ENXIO);
3064 }
91447636 3065 if (VNOP_IOCTL(devvp, DKIOCGETBLOCKCOUNT, (caddr_t)&sectorcnt, 0, context)) {
55e303ae
A
3066 return (ENXIO);
3067 }
3068 if ((sectorsize * sectorcnt) < newsize) {
3069 printf("hfs_extendfs: not enough space on device\n");
3070 return (ENOSPC);
3071 }
91447636 3072 oldsize = (u_int64_t)hfsmp->totalBlocks * (u_int64_t)hfsmp->blockSize;
55e303ae
A
3073
3074 /*
3075 * Validate new size.
3076 */
91447636 3077 if ((newsize <= oldsize) || (newsize % sectorsize)) {
55e303ae
A
3078 printf("hfs_extendfs: invalid size\n");
3079 return (EINVAL);
3080 }
3081 newblkcnt = newsize / vcb->blockSize;
3082 if (newblkcnt > (u_int64_t)0xFFFFFFFF)
3083 return (EOVERFLOW);
3084
3085 addblks = newblkcnt - vcb->totalBlocks;
3086
3087 printf("hfs_extendfs: growing %s by %d blocks\n", vcb->vcbVN, addblks);
3088 /*
3089 * Enclose changes inside a transaction.
3090 */
91447636 3091 if (hfs_start_transaction(hfsmp) != 0) {
55e303ae
A
3092 return (EINVAL);
3093 }
3094
2d21ac55
A
3095 /*
3096 * Note: we take the attributes lock in case we have an attribute data vnode
3097 * which needs to change size.
3098 */
3099 lockflags = hfs_systemfile_lock(hfsmp, SFL_ATTRIBUTE | SFL_EXTENTS | SFL_BITMAP, HFS_EXCLUSIVE_LOCK);
55e303ae 3100 vp = vcb->allocationsRefNum;
55e303ae
A
3101 fp = VTOF(vp);
3102 bcopy(&fp->ff_data, &forkdata, sizeof(forkdata));
3103
3104 /*
3105 * Calculate additional space required (if any) by allocation bitmap.
3106 */
2d21ac55
A
3107 oldBitmapSize = fp->ff_size;
3108 bitmapblks = roundup((newblkcnt+7) / 8, vcb->vcbVBMIOSize) / vcb->blockSize;
91447636 3109 if (bitmapblks > (daddr_t)fp->ff_blocks)
55e303ae
A
3110 bitmapblks -= fp->ff_blocks;
3111 else
3112 bitmapblks = 0;
3113
3114 if (bitmapblks > 0) {
91447636 3115 daddr64_t blkno;
55e303ae 3116 daddr_t blkcnt;
2d21ac55 3117 off_t bytesAdded;
55e303ae
A
3118
3119 /*
2d21ac55
A
3120 * Get the bitmap's current size (in allocation blocks) so we know
3121 * where to start zero filling once the new space is added. We've
3122 * got to do this before the bitmap is grown.
55e303ae 3123 */
91447636 3124 blkno = (daddr64_t)fp->ff_blocks;
2d21ac55
A
3125
3126 /*
3127 * Try to grow the allocation file in the normal way, using allocation
3128 * blocks already existing in the file system. This way, we might be
3129 * able to grow the bitmap contiguously, or at least in the metadata
3130 * zone.
3131 */
3132 error = ExtendFileC(vcb, fp, bitmapblks * vcb->blockSize, 0,
3133 kEFAllMask | kEFNoClumpMask | kEFReserveMask | kEFMetadataMask,
3134 &bytesAdded);
3135
3136 if (error == 0) {
3137 usedExtendFileC = true;
3138 } else {
3139 /*
3140 * If the above allocation failed, fall back to allocating the new
3141 * extent of the bitmap from the space we're going to add. Since those
3142 * blocks don't yet belong to the file system, we have to update the
3143 * extent list directly, and manually adjust the file size.
3144 */
3145 bytesAdded = 0;
3146 error = AddFileExtent(vcb, fp, vcb->totalBlocks, bitmapblks);
3147 if (error) {
3148 printf("hfs_extendfs: error %d adding extents\n", error);
3149 goto out;
3150 }
3151 fp->ff_blocks += bitmapblks;
3152 VTOC(vp)->c_blocks = fp->ff_blocks;
3153 VTOC(vp)->c_flag |= C_MODIFIED;
3154 }
3155
3156 /*
3157 * Update the allocation file's size to include the newly allocated
3158 * blocks. Note that ExtendFileC doesn't do this, which is why this
3159 * statement is outside the above "if" statement.
3160 */
55e303ae 3161 fp->ff_size += (u_int64_t)bitmapblks * (u_int64_t)vcb->blockSize;
2d21ac55 3162
55e303ae
A
3163 /*
3164 * Zero out the new bitmap blocks.
3165 */
3166 {
3167
3168 bp = NULL;
2d21ac55 3169 blkcnt = bitmapblks;
55e303ae 3170 while (blkcnt > 0) {
91447636 3171 error = (int)buf_meta_bread(vp, blkno, vcb->blockSize, NOCRED, &bp);
55e303ae
A
3172 if (error) {
3173 if (bp) {
91447636 3174 buf_brelse(bp);
55e303ae
A
3175 }
3176 break;
3177 }
91447636
A
3178 bzero((char *)buf_dataptr(bp), vcb->blockSize);
3179 buf_markaged(bp);
3180 error = (int)buf_bwrite(bp);
55e303ae
A
3181 if (error)
3182 break;
3183 --blkcnt;
3184 ++blkno;
3185 }
3186 }
3187 if (error) {
3188 printf("hfs_extendfs: error %d clearing blocks\n", error);
3189 goto out;
3190 }
3191 /*
3192 * Mark the new bitmap space as allocated.
2d21ac55
A
3193 *
3194 * Note that ExtendFileC will have marked any blocks it allocated, so
3195 * this is only needed if we used AddFileExtent. Also note that this
3196 * has to come *after* the zero filling of new blocks in the case where
3197 * we used AddFileExtent (since the part of the bitmap we're touching
3198 * is in those newly allocated blocks).
55e303ae 3199 */
2d21ac55
A
3200 if (!usedExtendFileC) {
3201 error = BlockMarkAllocated(vcb, vcb->totalBlocks, bitmapblks);
3202 if (error) {
3203 printf("hfs_extendfs: error %d setting bitmap\n", error);
3204 goto out;
3205 }
3206 vcb->freeBlocks -= bitmapblks;
55e303ae
A
3207 }
3208 }
3209 /*
3210 * Mark the new alternate VH as allocated.
3211 */
3212 if (vcb->blockSize == 512)
3213 error = BlockMarkAllocated(vcb, vcb->totalBlocks + addblks - 2, 2);
3214 else
3215 error = BlockMarkAllocated(vcb, vcb->totalBlocks + addblks - 1, 1);
3216 if (error) {
3217 printf("hfs_extendfs: error %d setting bitmap (VH)\n", error);
3218 goto out;
3219 }
3220 /*
3221 * Mark the old alternate VH as free.
3222 */
3223 if (vcb->blockSize == 512)
3224 (void) BlockMarkFree(vcb, vcb->totalBlocks - 2, 2);
3225 else
3226 (void) BlockMarkFree(vcb, vcb->totalBlocks - 1, 1);
55e303ae
A
3227 /*
3228 * Adjust file system variables for new space.
3229 */
91447636
A
3230 prev_phys_block_count = hfsmp->hfs_phys_block_count;
3231 prev_alt_sector = hfsmp->hfs_alt_id_sector;
3232
55e303ae 3233 vcb->totalBlocks += addblks;
2d21ac55 3234 vcb->freeBlocks += addblks;
55e303ae 3235 hfsmp->hfs_phys_block_count = newsize / sectorsize;
91447636
A
3236 hfsmp->hfs_alt_id_sector = (hfsmp->hfsPlusIOPosOffset / sectorsize) +
3237 HFS_ALT_SECTOR(sectorsize, hfsmp->hfs_phys_block_count);
55e303ae
A
3238 MarkVCBDirty(vcb);
3239 error = hfs_flushvolumeheader(hfsmp, MNT_WAIT, HFS_ALTFLUSH);
3240 if (error) {
3241 printf("hfs_extendfs: couldn't flush volume headers (%d)", error);
3242 /*
3243 * Restore to old state.
3244 */
2d21ac55
A
3245 if (usedExtendFileC) {
3246 (void) TruncateFileC(vcb, fp, oldBitmapSize, false);
3247 } else {
3248 fp->ff_blocks -= bitmapblks;
3249 fp->ff_size -= (u_int64_t)bitmapblks * (u_int64_t)vcb->blockSize;
3250 /*
3251 * No need to mark the excess blocks free since those bitmap blocks
3252 * are no longer part of the bitmap. But we do need to undo the
3253 * effect of the "vcb->freeBlocks -= bitmapblks" above.
3254 */
3255 vcb->freeBlocks += bitmapblks;
3256 }
55e303ae 3257 vcb->totalBlocks -= addblks;
2d21ac55 3258 vcb->freeBlocks -= addblks;
91447636
A
3259 hfsmp->hfs_phys_block_count = prev_phys_block_count;
3260 hfsmp->hfs_alt_id_sector = prev_alt_sector;
55e303ae
A
3261 MarkVCBDirty(vcb);
3262 if (vcb->blockSize == 512)
3263 (void) BlockMarkAllocated(vcb, vcb->totalBlocks - 2, 2);
3264 else
3265 (void) BlockMarkAllocated(vcb, vcb->totalBlocks - 1, 1);
3266 goto out;
3267 }
3268 /*
3269 * Invalidate the old alternate volume header.
3270 */
3271 bp = NULL;
91447636
A
3272 if (prev_alt_sector) {
3273 if (buf_meta_bread(hfsmp->hfs_devvp, prev_alt_sector, sectorsize,
3274 NOCRED, &bp) == 0) {
3275 journal_modify_block_start(hfsmp->jnl, bp);
3276
3277 bzero((char *)buf_dataptr(bp) + HFS_ALT_OFFSET(sectorsize), kMDBSize);
3278
2d21ac55 3279 journal_modify_block_end(hfsmp->jnl, bp, NULL, NULL);
91447636
A
3280 } else if (bp) {
3281 buf_brelse(bp);
3282 }
55e303ae 3283 }
2d21ac55
A
3284
3285 /*
3286 * TODO: Adjust the size of the metadata zone based on new volume size?
3287 */
3288
3289 /*
3290 * Adjust the size of hfsmp->hfs_attrdata_vp
3291 */
3292 if (hfsmp->hfs_attrdata_vp) {
3293 struct cnode *attr_cp;
3294 struct filefork *attr_fp;
3295
3296 if (vnode_get(hfsmp->hfs_attrdata_vp) == 0) {
3297 attr_cp = VTOC(hfsmp->hfs_attrdata_vp);
3298 attr_fp = VTOF(hfsmp->hfs_attrdata_vp);
3299
3300 attr_cp->c_blocks = newblkcnt;
3301 attr_fp->ff_blocks = newblkcnt;
3302 attr_fp->ff_extents[0].blockCount = newblkcnt;
3303 attr_fp->ff_size = (off_t) newblkcnt * hfsmp->blockSize;
3304 ubc_setsize(hfsmp->hfs_attrdata_vp, attr_fp->ff_size);
3305 vnode_put(hfsmp->hfs_attrdata_vp);
3306 }
3307 }
3308
55e303ae
A
3309out:
3310 if (error && fp) {
3311 /* Restore allocation fork. */
3312 bcopy(&forkdata, &fp->ff_data, sizeof(forkdata));
3313 VTOC(vp)->c_blocks = fp->ff_blocks;
3314
3315 }
91447636
A
3316 hfs_systemfile_unlock(hfsmp, lockflags);
3317 hfs_end_transaction(hfsmp);
3318
3319 return (error);
3320}
3321
3322#define HFS_MIN_SIZE (32LL * 1024LL * 1024LL)
3323
3324/*
3325 * Truncate a file system (while still mounted).
3326 */
3327__private_extern__
3328int
2d21ac55 3329hfs_truncatefs(struct hfsmount *hfsmp, u_int64_t newsize, vfs_context_t context)
91447636 3330{
91447636
A
3331 struct buf *bp = NULL;
3332 u_int64_t oldsize;
3333 u_int32_t newblkcnt;
2d21ac55 3334 u_int32_t reclaimblks = 0;
91447636
A
3335 int lockflags = 0;
3336 int transaction_begun = 0;
3337 int error;
3338
0c530ab8
A
3339 lck_mtx_lock(&hfsmp->hfs_mutex);
3340 if (hfsmp->hfs_flags & HFS_RESIZE_IN_PROGRESS) {
3341 lck_mtx_unlock(&hfsmp->hfs_mutex);
3342 return (EALREADY);
91447636 3343 }
0c530ab8
A
3344 hfsmp->hfs_flags |= HFS_RESIZE_IN_PROGRESS;
3345 hfsmp->hfs_resize_filesmoved = 0;
3346 hfsmp->hfs_resize_totalfiles = 0;
3347 lck_mtx_unlock(&hfsmp->hfs_mutex);
3348
91447636 3349 /*
0c530ab8 3350 * - Journaled HFS Plus volumes only.
91447636
A
3351 * - No embedded volumes.
3352 */
0c530ab8 3353 if ((hfsmp->jnl == NULL) ||
91447636
A
3354 (hfsmp->hfsPlusIOPosOffset != 0)) {
3355 error = EPERM;
3356 goto out;
3357 }
3358 oldsize = (u_int64_t)hfsmp->totalBlocks * (u_int64_t)hfsmp->blockSize;
3359 newblkcnt = newsize / hfsmp->blockSize;
3360 reclaimblks = hfsmp->totalBlocks - newblkcnt;
3361
3362 /* Make sure new size is valid. */
3363 if ((newsize < HFS_MIN_SIZE) ||
3364 (newsize >= oldsize) ||
3365 (newsize % hfsmp->hfs_phys_block_size)) {
3366 error = EINVAL;
3367 goto out;
3368 }
3369 /* Make sure there's enough space to work with. */
0c530ab8 3370 if (reclaimblks >= hfs_freeblks(hfsmp, 1)) {
2d21ac55 3371 printf("hfs_truncatefs: insufficient space (need %u blocks; have %u blocks)\n", reclaimblks, hfs_freeblks(hfsmp, 1));
91447636
A
3372 error = ENOSPC;
3373 goto out;
3374 }
2d21ac55 3375
0c530ab8
A
3376 /* Start with a clean journal. */
3377 journal_flush(hfsmp->jnl);
2d21ac55 3378
91447636
A
3379 if (hfs_start_transaction(hfsmp) != 0) {
3380 error = EINVAL;
3381 goto out;
3382 }
3383 transaction_begun = 1;
3384
3385 /*
2d21ac55
A
3386 * Prevent new allocations from using the part we're trying to truncate.
3387 *
3388 * NOTE: allocLimit is set to the allocation block number where the new
3389 * alternate volume header will be. That way there will be no files to
3390 * interfere with allocating the new alternate volume header, and no files
3391 * in the allocation blocks beyond (i.e. the blocks we're trying to
3392 * truncate away.
3393 */
3394 lck_mtx_lock(&hfsmp->hfs_mutex);
3395 if (hfsmp->blockSize == 512)
3396 hfsmp->allocLimit = newblkcnt - 2;
3397 else
3398 hfsmp->allocLimit = newblkcnt - 1;
3399 hfsmp->freeBlocks -= reclaimblks;
3400 lck_mtx_unlock(&hfsmp->hfs_mutex);
3401
3402 /*
3403 * Look for files that have blocks at or beyond the location of the
3404 * new alternate volume header.
91447636 3405 */
2d21ac55 3406 if (hfs_isallocated(hfsmp, hfsmp->allocLimit, reclaimblks)) {
91447636
A
3407 /*
3408 * hfs_reclaimspace will use separate transactions when
3409 * relocating files (so we don't overwhelm the journal).
3410 */
3411 hfs_end_transaction(hfsmp);
3412 transaction_begun = 0;
3413
3414 /* Attempt to reclaim some space. */
2d21ac55 3415 if (hfs_reclaimspace(hfsmp, hfsmp->allocLimit, reclaimblks, context) != 0) {
91447636
A
3416 printf("hfs_truncatefs: couldn't reclaim space on %s\n", hfsmp->vcbVN);
3417 error = ENOSPC;
3418 goto out;
3419 }
3420 if (hfs_start_transaction(hfsmp) != 0) {
3421 error = EINVAL;
3422 goto out;
3423 }
3424 transaction_begun = 1;
3425
3426 /* Check if we're clear now. */
2d21ac55 3427 if (hfs_isallocated(hfsmp, hfsmp->allocLimit, reclaimblks)) {
91447636 3428 printf("hfs_truncatefs: didn't reclaim enough space on %s\n", hfsmp->vcbVN);
0c530ab8 3429 error = EAGAIN; /* tell client to try again */
91447636
A
3430 goto out;
3431 }
3432 }
2d21ac55
A
3433
3434 /*
3435 * Note: we take the attributes lock in case we have an attribute data vnode
3436 * which needs to change size.
3437 */
3438 lockflags = hfs_systemfile_lock(hfsmp, SFL_ATTRIBUTE | SFL_EXTENTS | SFL_BITMAP, HFS_EXCLUSIVE_LOCK);
91447636
A
3439
3440 /*
3441 * Mark the old alternate volume header as free.
3442 * We don't bother shrinking allocation bitmap file.
3443 */
2d21ac55 3444 if (hfsmp->blockSize == 512)
91447636
A
3445 (void) BlockMarkFree(hfsmp, hfsmp->totalBlocks - 2, 2);
3446 else
3447 (void) BlockMarkFree(hfsmp, hfsmp->totalBlocks - 1, 1);
3448
3449 /*
2d21ac55 3450 * Allocate last 1KB for alternate volume header.
91447636 3451 */
2d21ac55 3452 error = BlockMarkAllocated(hfsmp, hfsmp->allocLimit, (hfsmp->blockSize == 512) ? 2 : 1);
91447636 3453 if (error) {
2d21ac55 3454 printf("hfs_truncatefs: Error %d allocating new alternate volume header\n", error);
91447636
A
3455 goto out;
3456 }
55e303ae 3457
91447636
A
3458 /*
3459 * Invalidate the existing alternate volume header.
0c530ab8 3460 *
2d21ac55 3461 * Don't include this in a transaction (don't call journal_modify_block)
0c530ab8 3462 * since this block will be outside of the truncated file system!
91447636
A
3463 */
3464 if (hfsmp->hfs_alt_id_sector) {
3465 if (buf_meta_bread(hfsmp->hfs_devvp, hfsmp->hfs_alt_id_sector,
3466 hfsmp->hfs_phys_block_size, NOCRED, &bp) == 0) {
91447636
A
3467
3468 bzero((void*)((char *)buf_dataptr(bp) + HFS_ALT_OFFSET(hfsmp->hfs_phys_block_size)), kMDBSize);
0c530ab8 3469 (void) VNOP_BWRITE(bp);
91447636
A
3470 } else if (bp) {
3471 buf_brelse(bp);
3472 }
3473 bp = NULL;
3474 }
3475
0c530ab8
A
3476 /* Log successful shrinking. */
3477 printf("hfs_truncatefs: shrank \"%s\" to %d blocks (was %d blocks)\n",
3478 hfsmp->vcbVN, newblkcnt, hfsmp->totalBlocks);
3479
91447636
A
3480 /*
3481 * Adjust file system variables and flush them to disk.
3482 */
91447636
A
3483 hfsmp->totalBlocks = newblkcnt;
3484 hfsmp->hfs_phys_block_count = newsize / hfsmp->hfs_phys_block_size;
3485 hfsmp->hfs_alt_id_sector = HFS_ALT_SECTOR(hfsmp->hfs_phys_block_size, hfsmp->hfs_phys_block_count);
3486 MarkVCBDirty(hfsmp);
3487 error = hfs_flushvolumeheader(hfsmp, MNT_WAIT, HFS_ALTFLUSH);
3488 if (error)
3489 panic("hfs_truncatefs: unexpected error flushing volume header (%d)\n", error);
2d21ac55
A
3490
3491 /*
3492 * TODO: Adjust the size of the metadata zone based on new volume size?
3493 */
3494
3495 /*
3496 * Adjust the size of hfsmp->hfs_attrdata_vp
3497 */
3498 if (hfsmp->hfs_attrdata_vp) {
3499 struct cnode *cp;
3500 struct filefork *fp;
3501
3502 if (vnode_get(hfsmp->hfs_attrdata_vp) == 0) {
3503 cp = VTOC(hfsmp->hfs_attrdata_vp);
3504 fp = VTOF(hfsmp->hfs_attrdata_vp);
3505
3506 cp->c_blocks = newblkcnt;
3507 fp->ff_blocks = newblkcnt;
3508 fp->ff_extents[0].blockCount = newblkcnt;
3509 fp->ff_size = (off_t) newblkcnt * hfsmp->blockSize;
3510 ubc_setsize(hfsmp->hfs_attrdata_vp, fp->ff_size);
3511 vnode_put(hfsmp->hfs_attrdata_vp);
3512 }
3513 }
3514
91447636 3515out:
2d21ac55
A
3516 if (error)
3517 hfsmp->freeBlocks += reclaimblks;
3518
3519 lck_mtx_lock(&hfsmp->hfs_mutex);
3520 hfsmp->allocLimit = hfsmp->totalBlocks;
3521 if (hfsmp->nextAllocation >= hfsmp->allocLimit)
3522 hfsmp->nextAllocation = hfsmp->hfs_metazone_end + 1;
3523 hfsmp->hfs_flags &= ~HFS_RESIZE_IN_PROGRESS;
3524 lck_mtx_unlock(&hfsmp->hfs_mutex);
3525
91447636
A
3526 if (lockflags) {
3527 hfs_systemfile_unlock(hfsmp, lockflags);
3528 }
3529 if (transaction_begun) {
3530 hfs_end_transaction(hfsmp);
0c530ab8 3531 journal_flush(hfsmp->jnl);
91447636 3532 }
0c530ab8 3533
55e303ae
A
3534 return (error);
3535}
3536
0c530ab8 3537
91447636 3538/*
2d21ac55
A
3539 * Invalidate the physical block numbers associated with buffer cache blocks
3540 * in the given extent of the given vnode.
91447636 3541 */
2d21ac55
A
3542struct hfs_inval_blk_no {
3543 daddr64_t sectorStart;
3544 daddr64_t sectorCount;
3545};
91447636 3546static int
2d21ac55 3547hfs_invalidate_block_numbers_callback(buf_t bp, void *args_in)
91447636 3548{
2d21ac55
A
3549 daddr64_t blkno;
3550 struct hfs_inval_blk_no *args;
3551
3552 blkno = buf_blkno(bp);
3553 args = args_in;
3554
3555 if (blkno >= args->sectorStart && blkno < args->sectorStart+args->sectorCount)
3556 buf_setblkno(bp, buf_lblkno(bp));
89b3af67 3557
2d21ac55
A
3558 return BUF_RETURNED;
3559}
3560static void
3561hfs_invalidate_sectors(struct vnode *vp, daddr64_t sectorStart, daddr64_t sectorCount)
3562{
3563 struct hfs_inval_blk_no args;
3564 args.sectorStart = sectorStart;
3565 args.sectorCount = sectorCount;
3566
3567 buf_iterate(vp, hfs_invalidate_block_numbers_callback, BUF_SCAN_DIRTY|BUF_SCAN_CLEAN, &args);
3568}
0c530ab8 3569
2d21ac55
A
3570
3571/*
3572 * Copy the contents of an extent to a new location. Also invalidates the
3573 * physical block number of any buffer cache block in the copied extent
3574 * (so that if the block is written, it will go through VNOP_BLOCKMAP to
3575 * determine the new physical block number).
3576 */
3577static int
3578hfs_copy_extent(
3579 struct hfsmount *hfsmp,
3580 struct vnode *vp, /* The file whose extent is being copied. */
3581 u_int32_t oldStart, /* The start of the source extent. */
3582 u_int32_t newStart, /* The start of the destination extent. */
3583 u_int32_t blockCount, /* The number of allocation blocks to copy. */
3584 vfs_context_t context)
3585{
3586 int err = 0;
3587 size_t bufferSize;
3588 void *buffer = NULL;
3589 struct vfsioattr ioattr;
3590 buf_t bp = NULL;
3591 off_t resid;
3592 size_t ioSize;
3593 u_int32_t ioSizeSectors; /* Device sectors in this I/O */
3594 daddr64_t srcSector, destSector;
3595 u_int32_t sectorsPerBlock = hfsmp->blockSize / hfsmp->hfs_phys_block_size;
3596
3597 /*
3598 * Sanity check that we have locked the vnode of the file we're copying.
3599 *
3600 * But since hfs_systemfile_lock() doesn't actually take the lock on
3601 * the allocation file if a journal is active, ignore the check if the
3602 * file being copied is the allocation file.
3603 */
3604 struct cnode *cp = VTOC(vp);
3605 if (cp != hfsmp->hfs_allocation_cp && cp->c_lockowner != current_thread())
3606 panic("hfs_copy_extent: vp=%p (cp=%p) not owned?\n", vp, cp);
3607
3608 /*
3609 * Wait for any in-progress writes to this vnode to complete, so that we'll
3610 * be copying consistent bits. (Otherwise, it's possible that an async
3611 * write will complete to the old extent after we read from it. That
3612 * could lead to corruption.)
3613 */
3614 err = vnode_waitforwrites(vp, 0, 0, 0, "hfs_copy_extent");
3615 if (err) {
3616 printf("hfs_copy_extent: Error %d from vnode_waitforwrites\n", err);
3617 return err;
3618 }
3619
3620 /*
3621 * Determine the I/O size to use
3622 *
3623 * NOTE: Many external drives will result in an ioSize of 128KB.
3624 * TODO: Should we use a larger buffer, doing several consecutive
3625 * reads, then several consecutive writes?
3626 */
3627 vfs_ioattr(hfsmp->hfs_mp, &ioattr);
3628 bufferSize = MIN(ioattr.io_maxreadcnt, ioattr.io_maxwritecnt);
3629 if (kmem_alloc(kernel_map, (vm_offset_t*) &buffer, bufferSize))
3630 return ENOMEM;
3631
3632 /* Get a buffer for doing the I/O */
3633 bp = buf_alloc(hfsmp->hfs_devvp);
3634 buf_setdataptr(bp, (uintptr_t)buffer);
3635
3636 resid = (off_t) blockCount * (off_t) hfsmp->blockSize;
3637 srcSector = (daddr64_t) oldStart * hfsmp->blockSize / hfsmp->hfs_phys_block_size;
3638 destSector = (daddr64_t) newStart * hfsmp->blockSize / hfsmp->hfs_phys_block_size;
3639 while (resid > 0) {
3640 ioSize = MIN(bufferSize, resid);
3641 ioSizeSectors = ioSize / hfsmp->hfs_phys_block_size;
3642
3643 /* Prepare the buffer for reading */
3644 buf_reset(bp, B_READ);
3645 buf_setsize(bp, ioSize);
3646 buf_setcount(bp, ioSize);
3647 buf_setblkno(bp, srcSector);
3648 buf_setlblkno(bp, srcSector);
3649
3650 /* Do the read */
3651 err = VNOP_STRATEGY(bp);
3652 if (!err)
3653 err = buf_biowait(bp);
3654 if (err) {
3655 printf("hfs_copy_extent: Error %d from VNOP_STRATEGY (read)\n", err);
3656 break;
91447636 3657 }
2d21ac55
A
3658
3659 /* Prepare the buffer for writing */
3660 buf_reset(bp, B_WRITE);
3661 buf_setsize(bp, ioSize);
3662 buf_setcount(bp, ioSize);
3663 buf_setblkno(bp, destSector);
3664 buf_setlblkno(bp, destSector);
3665 if (journal_uses_fua(hfsmp->jnl))
3666 buf_markfua(bp);
3667
3668 /* Do the write */
3669 vnode_startwrite(hfsmp->hfs_devvp);
3670 err = VNOP_STRATEGY(bp);
3671 if (!err)
3672 err = buf_biowait(bp);
3673 if (err) {
3674 printf("hfs_copy_extent: Error %d from VNOP_STRATEGY (write)\n", err);
3675 break;
0c530ab8 3676 }
2d21ac55
A
3677
3678 resid -= ioSize;
3679 srcSector += ioSizeSectors;
3680 destSector += ioSizeSectors;
3681 }
3682 if (bp)
3683 buf_free(bp);
3684 if (buffer)
3685 kmem_free(kernel_map, (vm_offset_t)buffer, bufferSize);
3686
3687 /* Make sure all writes have been flushed to disk. */
3688 if (!journal_uses_fua(hfsmp->jnl)) {
3689 err = VNOP_IOCTL(hfsmp->hfs_devvp, DKIOCSYNCHRONIZECACHE, NULL, FWRITE, context);
3690 if (err) {
3691 printf("hfs_copy_extent: DKIOCSYNCHRONIZECACHE failed (%d)\n", err);
3692 err = 0; /* Don't fail the copy. */
3693 }
3694 }
3695
3696 if (!err)
3697 hfs_invalidate_sectors(vp, (daddr64_t)oldStart*sectorsPerBlock, (daddr64_t)blockCount*sectorsPerBlock);
3698
3699 return err;
3700}
3701
3702
3703/*
3704 * Reclaim space at the end of a volume, used by a given system file.
3705 *
3706 * This routine attempts to move any extent which contains allocation blocks
3707 * at or after "startblk." A separate transaction is used to do the move.
3708 * The contents of any moved extents are read and written via the volume's
3709 * device vnode -- NOT via "vp." During the move, moved blocks which are part
3710 * of a transaction have their physical block numbers invalidated so they will
3711 * eventually be written to their new locations.
3712 *
3713 * This routine can be used to move overflow extents for the allocation file.
3714 *
3715 * Inputs:
3716 * hfsmp The volume being resized.
3717 * startblk Blocks >= this allocation block need to be moved.
3718 * locks Which locks need to be taken for the given system file.
3719 * vp The vnode for the system file.
3720 *
3721 * Outputs:
3722 * moved Set to true if any extents were moved.
3723 */
3724static int
3725hfs_relocate_callback(__unused HFSPlusExtentKey *key, HFSPlusExtentRecord *record, HFSPlusExtentRecord *state)
3726{
3727 bcopy(state, record, sizeof(HFSPlusExtentRecord));
3728 return 0;
3729}
3730static int
3731hfs_reclaim_sys_file(struct hfsmount *hfsmp, struct vnode *vp, u_long startblk, int locks, Boolean *moved, vfs_context_t context)
3732{
3733 int error;
3734 int lockflags;
3735 int i;
3736 u_long datablks;
3737 u_long block;
3738 u_int32_t oldStartBlock;
3739 u_int32_t newStartBlock;
3740 u_int32_t blockCount;
3741 struct filefork *fp;
3742
3743 /* If there is no vnode for this file, then there's nothing to do. */
3744 if (vp == NULL)
3745 return 0;
3746
3747 /* printf("hfs_reclaim_sys_file: %.*s\n", VTOC(vp)->c_desc.cd_namelen, VTOC(vp)->c_desc.cd_nameptr); */
3748
3749 /* We always need the allocation bitmap and extents B-tree */
3750 locks |= SFL_BITMAP | SFL_EXTENTS;
3751
3752 error = hfs_start_transaction(hfsmp);
3753 if (error) {
3754 printf("hfs_reclaim_sys_file: hfs_start_transaction returned %d\n", error);
3755 return error;
0c530ab8 3756 }
2d21ac55
A
3757 lockflags = hfs_systemfile_lock(hfsmp, locks, HFS_EXCLUSIVE_LOCK);
3758 fp = VTOF(vp);
0c530ab8 3759 datablks = 0;
2d21ac55
A
3760
3761 /* Relocate non-overflow extents */
0c530ab8 3762 for (i = 0; i < kHFSPlusExtentDensity; ++i) {
2d21ac55 3763 if (fp->ff_extents[i].blockCount == 0)
0c530ab8 3764 break;
2d21ac55
A
3765 oldStartBlock = fp->ff_extents[i].startBlock;
3766 blockCount = fp->ff_extents[i].blockCount;
3767 datablks += blockCount;
3768 block = oldStartBlock + blockCount;
3769 if (block > startblk) {
3770 error = BlockAllocate(hfsmp, 1, blockCount, blockCount, true, true, &newStartBlock, &blockCount);
3771 if (error) {
3772 printf("hfs_reclaim_sys_file: BlockAllocate returned %d\n", error);
3773 goto fail;
3774 }
3775 if (blockCount != fp->ff_extents[i].blockCount) {
3776 printf("hfs_reclaim_sys_file: new blockCount=%u, original blockCount=%u", blockCount, fp->ff_extents[i].blockCount);
3777 goto free_fail;
3778 }
3779 error = hfs_copy_extent(hfsmp, vp, oldStartBlock, newStartBlock, blockCount, context);
3780 if (error) {
3781 printf("hfs_reclaim_sys_file: hfs_copy_extent returned %d\n", error);
3782 goto free_fail;
3783 }
3784 fp->ff_extents[i].startBlock = newStartBlock;
3785 VTOC(vp)->c_flag |= C_MODIFIED;
3786 *moved = true;
3787 error = BlockDeallocate(hfsmp, oldStartBlock, blockCount);
3788 if (error) {
3789 /* TODO: Mark volume inconsistent? */
3790 printf("hfs_reclaim_sys_file: BlockDeallocate returned %d\n", error);
3791 goto fail;
3792 }
3793 error = hfs_flushvolumeheader(hfsmp, MNT_WAIT, HFS_ALTFLUSH);
3794 if (error) {
3795 /* TODO: Mark volume inconsistent? */
3796 printf("hfs_reclaim_sys_file: hfs_flushvolumeheader returned %d\n", error);
3797 goto fail;
3798 }
0c530ab8 3799 }
2d21ac55
A
3800 }
3801
3802 /* Relocate overflow extents (if any) */
3803 if (i == kHFSPlusExtentDensity && fp->ff_blocks > datablks) {
3804 struct BTreeIterator *iterator = NULL;
3805 struct FSBufferDescriptor btdata;
3806 HFSPlusExtentRecord record;
3807 HFSPlusExtentKey *key;
3808 FCB *fcb;
3809 u_int32_t fileID;
3810 u_int8_t forktype;
3811
3812 forktype = VNODE_IS_RSRC(vp) ? 0xFF : 0;
3813 fileID = VTOC(vp)->c_cnid;
3814 if (kmem_alloc(kernel_map, (vm_offset_t*) &iterator, sizeof(*iterator))) {
3815 printf("hfs_reclaim_sys_file: kmem_alloc failed!\n");
3816 error = ENOMEM;
3817 goto fail;
3818 }
3819
3820 bzero(iterator, sizeof(*iterator));
3821 key = (HFSPlusExtentKey *) &iterator->key;
3822 key->keyLength = kHFSPlusExtentKeyMaximumLength;
3823 key->forkType = forktype;
3824 key->fileID = fileID;
3825 key->startBlock = datablks;
3826
3827 btdata.bufferAddress = &record;
3828 btdata.itemSize = sizeof(record);
3829 btdata.itemCount = 1;
3830
3831 fcb = VTOF(hfsmp->hfs_extents_vp);
3832
3833 error = BTSearchRecord(fcb, iterator, &btdata, NULL, iterator);
3834 while (error == 0) {
3835 /* Stop when we encounter a different file or fork. */
3836 if ((key->fileID != fileID) ||
3837 (key->forkType != forktype)) {
3838 break;
3839 }
3840 /*
3841 * Check if the file overlaps target space.
3842 */
3843 for (i = 0; i < kHFSPlusExtentDensity; ++i) {
3844 if (record[i].blockCount == 0) {
3845 goto overflow_done;
3846 }
3847 oldStartBlock = record[i].startBlock;
3848 blockCount = record[i].blockCount;
3849 block = oldStartBlock + blockCount;
3850 if (block > startblk) {
3851 error = BlockAllocate(hfsmp, 1, blockCount, blockCount, true, true, &newStartBlock, &blockCount);
3852 if (error) {
3853 printf("hfs_reclaim_sys_file: BlockAllocate returned %d\n", error);
3854 goto overflow_done;
3855 }
3856 if (blockCount != record[i].blockCount) {
3857 printf("hfs_reclaim_sys_file: new blockCount=%u, original blockCount=%u", blockCount, fp->ff_extents[i].blockCount);
3858 kmem_free(kernel_map, (vm_offset_t)iterator, sizeof(*iterator));
3859 goto free_fail;
3860 }
3861 error = hfs_copy_extent(hfsmp, vp, oldStartBlock, newStartBlock, blockCount, context);
3862 if (error) {
3863 printf("hfs_reclaim_sys_file: hfs_copy_extent returned %d\n", error);
3864 kmem_free(kernel_map, (vm_offset_t)iterator, sizeof(*iterator));
3865 goto free_fail;
3866 }
3867 record[i].startBlock = newStartBlock;
3868 VTOC(vp)->c_flag |= C_MODIFIED;
3869 *moved = true;
3870 /*
3871 * NOTE: To support relocating overflow extents of the
3872 * allocation file, we must update the BTree record BEFORE
3873 * deallocating the old extent so that BlockDeallocate will
3874 * use the extent's new location to calculate physical block
3875 * numbers. (This is for the case where the old extent's
3876 * bitmap bits actually reside in the extent being moved.)
3877 */
3878 error = BTUpdateRecord(fcb, iterator, (IterateCallBackProcPtr) hfs_relocate_callback, &record);
3879 if (error) {
3880 /* TODO: Mark volume inconsistent? */
3881 printf("hfs_reclaim_sys_file: BTUpdateRecord returned %d\n", error);
3882 goto overflow_done;
3883 }
3884 error = BlockDeallocate(hfsmp, oldStartBlock, blockCount);
3885 if (error) {
3886 /* TODO: Mark volume inconsistent? */
3887 printf("hfs_reclaim_sys_file: BlockDeallocate returned %d\n", error);
3888 goto overflow_done;
3889 }
3890 }
3891 }
3892 /* Look for more records. */
3893 error = BTIterateRecord(fcb, kBTreeNextRecord, iterator, &btdata, NULL);
3894 if (error == btNotFound) {
3895 error = 0;
3896 break;
3897 }
3898 }
3899overflow_done:
3900 kmem_free(kernel_map, (vm_offset_t)iterator, sizeof(*iterator));
3901 if (error) {
3902 goto fail;
0c530ab8
A
3903 }
3904 }
2d21ac55
A
3905
3906 hfs_systemfile_unlock(hfsmp, lockflags);
3907 error = hfs_end_transaction(hfsmp);
3908 if (error) {
3909 printf("hfs_reclaim_sys_file: hfs_end_transaction returned %d\n", error);
3910 }
3911
3912 return error;
3913
3914free_fail:
3915 (void) BlockDeallocate(hfsmp, newStartBlock, blockCount);
3916fail:
3917 (void) hfs_systemfile_unlock(hfsmp, lockflags);
3918 (void) hfs_end_transaction(hfsmp);
3919 return error;
3920}
3921
3922
3923/*
3924 * This journal_relocate callback updates the journal info block to point
3925 * at the new journal location. This write must NOT be done using the
3926 * transaction. We must write the block immediately. We must also force
3927 * it to get to the media so that the new journal location will be seen by
3928 * the replay code before we can safely let journaled blocks be written
3929 * to their normal locations.
3930 *
3931 * The tests for journal_uses_fua below are mildly hacky. Since the journal
3932 * and the file system are both on the same device, I'm leveraging what
3933 * the journal has decided about FUA.
3934 */
3935struct hfs_journal_relocate_args {
3936 struct hfsmount *hfsmp;
3937 vfs_context_t context;
3938 u_int32_t newStartBlock;
3939};
3940
3941static errno_t
3942hfs_journal_relocate_callback(void *_args)
3943{
3944 int error;
3945 struct hfs_journal_relocate_args *args = _args;
3946 struct hfsmount *hfsmp = args->hfsmp;
3947 buf_t bp;
3948 JournalInfoBlock *jibp;
3949
3950 error = buf_meta_bread(hfsmp->hfs_devvp,
3951 hfsmp->vcbJinfoBlock * (hfsmp->blockSize/hfsmp->hfs_phys_block_size),
3952 hfsmp->blockSize, vfs_context_ucred(args->context), &bp);
3953 if (error) {
3954 printf("hfs_reclaim_journal_file: failed to read JIB (%d)\n", error);
3955 return error;
3956 }
3957 jibp = (JournalInfoBlock*) buf_dataptr(bp);
3958 jibp->offset = SWAP_BE64((u_int64_t)args->newStartBlock * hfsmp->blockSize);
3959 jibp->size = SWAP_BE64(hfsmp->jnl_size);
3960 if (journal_uses_fua(hfsmp->jnl))
3961 buf_markfua(bp);
3962 error = buf_bwrite(bp);
3963 if (error) {
3964 printf("hfs_reclaim_journal_file: failed to write JIB (%d)\n", error);
3965 return error;
3966 }
3967 if (!journal_uses_fua(hfsmp->jnl)) {
3968 error = VNOP_IOCTL(hfsmp->hfs_devvp, DKIOCSYNCHRONIZECACHE, NULL, FWRITE, args->context);
3969 if (error) {
3970 printf("hfs_reclaim_journal_file: DKIOCSYNCHRONIZECACHE failed (%d)\n", error);
3971 error = 0; /* Don't fail the operation. */
0c530ab8 3972 }
91447636
A
3973 }
3974
2d21ac55
A
3975 return error;
3976}
3977
3978
3979static int
3980hfs_reclaim_journal_file(struct hfsmount *hfsmp, vfs_context_t context)
3981{
3982 int error;
3983 int lockflags;
3984 u_int32_t newStartBlock;
3985 u_int32_t oldBlockCount;
3986 u_int32_t newBlockCount;
3987 struct cat_desc journal_desc;
3988 struct cat_attr journal_attr;
3989 struct cat_fork journal_fork;
3990 struct hfs_journal_relocate_args callback_args;
3991
3992 error = hfs_start_transaction(hfsmp);
3993 if (error) {
3994 printf("hfs_reclaim_journal_file: hfs_start_transaction returned %d\n", error);
3995 return error;
3996 }
3997 lockflags = hfs_systemfile_lock(hfsmp, SFL_CATALOG | SFL_BITMAP, HFS_EXCLUSIVE_LOCK);
3998
3999 oldBlockCount = hfsmp->jnl_size / hfsmp->blockSize;
4000
4001 /* TODO: Allow the journal to change size based on the new volume size. */
4002 error = BlockAllocate(hfsmp, 1, oldBlockCount, oldBlockCount, true, true, &newStartBlock, &newBlockCount);
4003 if (error) {
4004 printf("hfs_reclaim_journal_file: BlockAllocate returned %d\n", error);
4005 goto fail;
4006 }
4007 if (newBlockCount != oldBlockCount) {
4008 printf("hfs_reclaim_journal_file: newBlockCount != oldBlockCount (%u, %u)\n", newBlockCount, oldBlockCount);
4009 goto free_fail;
4010 }
4011
4012 error = BlockDeallocate(hfsmp, hfsmp->jnl_start, oldBlockCount);
4013 if (error) {
4014 printf("hfs_reclaim_journal_file: BlockDeallocate returned %d\n", error);
4015 goto free_fail;
4016 }
4017
4018 /* Update the catalog record for .journal */
4019 error = cat_idlookup(hfsmp, hfsmp->hfs_jnlfileid, 1, &journal_desc, &journal_attr, &journal_fork);
4020 if (error) {
4021 printf("hfs_reclaim_journal_file: cat_idlookup returned %d\n", error);
4022 goto free_fail;
4023 }
4024 journal_fork.cf_size = newBlockCount * hfsmp->blockSize;
4025 journal_fork.cf_extents[0].startBlock = newStartBlock;
4026 journal_fork.cf_extents[0].blockCount = newBlockCount;
4027 journal_fork.cf_blocks = newBlockCount;
4028 error = cat_update(hfsmp, &journal_desc, &journal_attr, &journal_fork, NULL);
4029 if (error) {
4030 printf("hfs_reclaim_journal_file: cat_update returned %d\n", error);
4031 goto free_fail;
4032 }
4033 callback_args.hfsmp = hfsmp;
4034 callback_args.context = context;
4035 callback_args.newStartBlock = newStartBlock;
4036
4037 error = journal_relocate(hfsmp->jnl, (off_t)newStartBlock*hfsmp->blockSize,
4038 (off_t)newBlockCount*hfsmp->blockSize, 0,
4039 hfs_journal_relocate_callback, &callback_args);
4040 if (error) {
4041 /* NOTE: journal_relocate will mark the journal invalid. */
4042 printf("hfs_reclaim_journal_file: journal_relocate returned %d\n", error);
4043 goto fail;
4044 }
4045 hfsmp->jnl_start = newStartBlock;
4046 hfsmp->jnl_size = (off_t)newBlockCount * hfsmp->blockSize;
4047
4048 hfs_systemfile_unlock(hfsmp, lockflags);
4049 error = hfs_end_transaction(hfsmp);
4050 if (error) {
4051 printf("hfs_reclaim_journal_file: hfs_end_transaction returned %d\n", error);
4052 }
4053
4054 return error;
4055
4056free_fail:
4057 (void) BlockDeallocate(hfsmp, newStartBlock, newBlockCount);
4058fail:
4059 hfs_systemfile_unlock(hfsmp, lockflags);
4060 (void) hfs_end_transaction(hfsmp);
4061 return error;
4062}
4063
4064
4065/*
4066 * Move the journal info block to a new location. We have to make sure the
4067 * new copy of the journal info block gets to the media first, then change
4068 * the field in the volume header and the catalog record.
4069 */
4070static int
4071hfs_reclaim_journal_info_block(struct hfsmount *hfsmp, vfs_context_t context)
4072{
4073 int error;
4074 int lockflags;
4075 u_int32_t newBlock;
4076 u_int32_t blockCount;
4077 struct cat_desc jib_desc;
4078 struct cat_attr jib_attr;
4079 struct cat_fork jib_fork;
4080 buf_t old_bp, new_bp;
4081
4082 error = hfs_start_transaction(hfsmp);
4083 if (error) {
4084 printf("hfs_reclaim_journal_info_block: hfs_start_transaction returned %d\n", error);
4085 return error;
4086 }
4087 lockflags = hfs_systemfile_lock(hfsmp, SFL_CATALOG | SFL_BITMAP, HFS_EXCLUSIVE_LOCK);
4088
4089 error = BlockAllocate(hfsmp, 1, 1, 1, true, true, &newBlock, &blockCount);
4090 if (error) {
4091 printf("hfs_reclaim_journal_info_block: BlockAllocate returned %d\n", error);
4092 goto fail;
4093 }
4094 if (blockCount != 1) {
4095 printf("hfs_reclaim_journal_info_block: blockCount != 1 (%u)\n", blockCount);
4096 goto free_fail;
4097 }
4098 error = BlockDeallocate(hfsmp, hfsmp->vcbJinfoBlock, 1);
4099 if (error) {
4100 printf("hfs_reclaim_journal_info_block: BlockDeallocate returned %d\n", error);
4101 goto free_fail;
4102 }
4103
4104 /* Copy the old journal info block content to the new location */
4105 error = buf_meta_bread(hfsmp->hfs_devvp,
4106 hfsmp->vcbJinfoBlock * (hfsmp->blockSize/hfsmp->hfs_phys_block_size),
4107 hfsmp->blockSize, vfs_context_ucred(context), &old_bp);
4108 if (error) {
4109 printf("hfs_reclaim_journal_info_block: failed to read JIB (%d)\n", error);
4110 goto free_fail;
4111 }
4112 new_bp = buf_getblk(hfsmp->hfs_devvp,
4113 newBlock * (hfsmp->blockSize/hfsmp->hfs_phys_block_size),
4114 hfsmp->blockSize, 0, 0, BLK_META);
4115 bcopy((char*)buf_dataptr(old_bp), (char*)buf_dataptr(new_bp), hfsmp->blockSize);
4116 buf_brelse(old_bp);
4117 if (journal_uses_fua(hfsmp->jnl))
4118 buf_markfua(new_bp);
4119 error = buf_bwrite(new_bp);
4120 if (error) {
4121 printf("hfs_reclaim_journal_info_block: failed to write new JIB (%d)\n", error);
4122 goto free_fail;
4123 }
4124 if (!journal_uses_fua(hfsmp->jnl)) {
4125 error = VNOP_IOCTL(hfsmp->hfs_devvp, DKIOCSYNCHRONIZECACHE, NULL, FWRITE, context);
4126 if (error) {
4127 printf("hfs_reclaim_journal_info_block: DKIOCSYNCHRONIZECACHE failed (%d)\n", error);
4128 /* Don't fail the operation. */
4129 }
4130 }
4131
4132 /* Update the catalog record for .journal_info_block */
4133 error = cat_idlookup(hfsmp, hfsmp->hfs_jnlinfoblkid, 1, &jib_desc, &jib_attr, &jib_fork);
4134 if (error) {
4135 printf("hfs_reclaim_journal_file: cat_idlookup returned %d\n", error);
4136 goto fail;
4137 }
4138 jib_fork.cf_size = hfsmp->blockSize;
4139 jib_fork.cf_extents[0].startBlock = newBlock;
4140 jib_fork.cf_extents[0].blockCount = 1;
4141 jib_fork.cf_blocks = 1;
4142 error = cat_update(hfsmp, &jib_desc, &jib_attr, &jib_fork, NULL);
4143 if (error) {
4144 printf("hfs_reclaim_journal_info_block: cat_update returned %d\n", error);
4145 goto fail;
4146 }
4147
4148 /* Update the pointer to the journal info block in the volume header. */
4149 hfsmp->vcbJinfoBlock = newBlock;
4150 error = hfs_flushvolumeheader(hfsmp, MNT_WAIT, HFS_ALTFLUSH);
4151 if (error) {
4152 printf("hfs_reclaim_journal_info_block: hfs_flushvolumeheader returned %d\n", error);
4153 goto fail;
4154 }
4155 hfs_systemfile_unlock(hfsmp, lockflags);
4156 error = hfs_end_transaction(hfsmp);
4157 if (error) {
4158 printf("hfs_reclaim_journal_info_block: hfs_end_transaction returned %d\n", error);
4159 }
4160 error = journal_flush(hfsmp->jnl);
4161 if (error) {
4162 printf("hfs_reclaim_journal_info_block: journal_flush returned %d\n", error);
4163 }
4164 return error;
4165
4166free_fail:
4167 (void) BlockDeallocate(hfsmp, newBlock, blockCount);
4168fail:
4169 hfs_systemfile_unlock(hfsmp, lockflags);
4170 (void) hfs_end_transaction(hfsmp);
4171 return error;
4172}
4173
4174
4175/*
4176 * Reclaim space at the end of a file system.
4177 */
4178static int
4179hfs_reclaimspace(struct hfsmount *hfsmp, u_long startblk, u_long reclaimblks, vfs_context_t context)
4180{
4181 struct vnode *vp = NULL;
4182 FCB *fcb;
4183 struct BTreeIterator * iterator = NULL;
4184 struct FSBufferDescriptor btdata;
4185 struct HFSPlusCatalogFile filerec;
4186 u_int32_t saved_next_allocation;
4187 cnid_t * cnidbufp;
4188 size_t cnidbufsize;
4189 int filecnt = 0;
4190 int maxfilecnt;
4191 u_long block;
4192 u_long datablks;
4193 u_long rsrcblks;
4194 u_long blkstomove = 0;
4195 int lockflags;
4196 int i;
4197 int error;
4198 int lastprogress = 0;
4199 Boolean system_file_moved = false;
4200
4201 /* Relocate extents of the Allocation file if they're in the way. */
4202 error = hfs_reclaim_sys_file(hfsmp, hfsmp->hfs_allocation_vp, startblk, SFL_BITMAP, &system_file_moved, context);
4203 if (error) {
4204 printf("hfs_reclaimspace: reclaim allocation file returned %d\n", error);
4205 return error;
4206 }
4207 /* Relocate extents of the Extents B-tree if they're in the way. */
4208 error = hfs_reclaim_sys_file(hfsmp, hfsmp->hfs_extents_vp, startblk, SFL_EXTENTS, &system_file_moved, context);
4209 if (error) {
4210 printf("hfs_reclaimspace: reclaim extents b-tree returned %d\n", error);
4211 return error;
4212 }
4213 /* Relocate extents of the Catalog B-tree if they're in the way. */
4214 error = hfs_reclaim_sys_file(hfsmp, hfsmp->hfs_catalog_vp, startblk, SFL_CATALOG, &system_file_moved, context);
4215 if (error) {
4216 printf("hfs_reclaimspace: reclaim catalog b-tree returned %d\n", error);
4217 return error;
4218 }
4219 /* Relocate extents of the Attributes B-tree if they're in the way. */
4220 error = hfs_reclaim_sys_file(hfsmp, hfsmp->hfs_attribute_vp, startblk, SFL_ATTRIBUTE, &system_file_moved, context);
4221 if (error) {
4222 printf("hfs_reclaimspace: reclaim attribute b-tree returned %d\n", error);
4223 return error;
4224 }
4225 /* Relocate extents of the Startup File if there is one and they're in the way. */
4226 error = hfs_reclaim_sys_file(hfsmp, hfsmp->hfs_startup_vp, startblk, SFL_STARTUP, &system_file_moved, context);
4227 if (error) {
4228 printf("hfs_reclaimspace: reclaim startup file returned %d\n", error);
4229 return error;
4230 }
4231
4232 /*
4233 * We need to make sure the alternate volume header gets flushed if we moved
4234 * any extents in the volume header. But we need to do that before
4235 * shrinking the size of the volume, or else the journal code will panic
4236 * with an invalid (too large) block number.
4237 *
4238 * Note that system_file_moved will be set if ANY extent was moved, even
4239 * if it was just an overflow extent. In this case, the journal_flush isn't
4240 * strictly required, but shouldn't hurt.
4241 */
4242 if (system_file_moved)
4243 journal_flush(hfsmp->jnl);
4244
4245 if (hfsmp->jnl_start + (hfsmp->jnl_size / hfsmp->blockSize) > startblk) {
4246 error = hfs_reclaim_journal_file(hfsmp, context);
4247 if (error) {
4248 printf("hfs_reclaimspace: hfs_reclaim_journal_file failed (%d)\n", error);
4249 return error;
4250 }
4251 }
4252
4253 if (hfsmp->vcbJinfoBlock >= startblk) {
4254 error = hfs_reclaim_journal_info_block(hfsmp, context);
4255 if (error) {
4256 printf("hfs_reclaimspace: hfs_reclaim_journal_info_block failed (%d)\n", error);
4257 return error;
4258 }
4259 }
4260
0c530ab8
A
4261 /* For now move a maximum of 250,000 files. */
4262 maxfilecnt = MIN(hfsmp->hfs_filecount, 250000);
4263 maxfilecnt = MIN((u_long)maxfilecnt, reclaimblks);
91447636
A
4264 cnidbufsize = maxfilecnt * sizeof(cnid_t);
4265 if (kmem_alloc(kernel_map, (vm_offset_t *)&cnidbufp, cnidbufsize)) {
4266 return (ENOMEM);
4267 }
4268 if (kmem_alloc(kernel_map, (vm_offset_t *)&iterator, sizeof(*iterator))) {
4269 kmem_free(kernel_map, (vm_offset_t)cnidbufp, cnidbufsize);
4270 return (ENOMEM);
4271 }
4272
4273 saved_next_allocation = hfsmp->nextAllocation;
2d21ac55 4274 HFS_UPDATE_NEXT_ALLOCATION(hfsmp, hfsmp->hfs_metazone_start);
91447636
A
4275
4276 fcb = VTOF(hfsmp->hfs_catalog_vp);
4277 bzero(iterator, sizeof(*iterator));
4278
4279 btdata.bufferAddress = &filerec;
4280 btdata.itemSize = sizeof(filerec);
4281 btdata.itemCount = 1;
4282
0c530ab8
A
4283 /* Keep the Catalog and extents files locked during iteration. */
4284 lockflags = hfs_systemfile_lock(hfsmp, SFL_CATALOG | SFL_EXTENTS, HFS_SHARED_LOCK);
4285
91447636
A
4286 error = BTIterateRecord(fcb, kBTreeFirstRecord, iterator, NULL, NULL);
4287 if (error) {
0c530ab8 4288 goto end_iteration;
91447636 4289 }
91447636
A
4290 /*
4291 * Iterate over all the catalog records looking for files
4292 * that overlap into the space we're trying to free up.
4293 */
4294 for (filecnt = 0; filecnt < maxfilecnt; ) {
4295 error = BTIterateRecord(fcb, kBTreeNextRecord, iterator, &btdata, NULL);
4296 if (error) {
0c530ab8
A
4297 if (error == fsBTRecordNotFoundErr || error == fsBTEndOfIterationErr) {
4298 error = 0;
4299 }
91447636
A
4300 break;
4301 }
0c530ab8 4302 if (filerec.recordType != kHFSPlusFileRecord) {
91447636 4303 continue;
0c530ab8
A
4304 }
4305 datablks = rsrcblks = 0;
91447636
A
4306 /*
4307 * Check if either fork overlaps target space.
4308 */
4309 for (i = 0; i < kHFSPlusExtentDensity; ++i) {
0c530ab8
A
4310 if (filerec.dataFork.extents[i].blockCount != 0) {
4311 datablks += filerec.dataFork.extents[i].blockCount;
4312 block = filerec.dataFork.extents[i].startBlock +
4313 filerec.dataFork.extents[i].blockCount;
4314 if (block >= startblk) {
4315 if ((filerec.fileID == hfsmp->hfs_jnlfileid) ||
4316 (filerec.fileID == hfsmp->hfs_jnlinfoblkid)) {
4317 printf("hfs_reclaimspace: cannot move active journal\n");
4318 error = EPERM;
4319 goto end_iteration;
4320 }
4321 cnidbufp[filecnt++] = filerec.fileID;
4322 blkstomove += filerec.dataFork.totalBlocks;
4452a7af
A
4323 break;
4324 }
4325 }
0c530ab8
A
4326 if (filerec.resourceFork.extents[i].blockCount != 0) {
4327 rsrcblks += filerec.resourceFork.extents[i].blockCount;
4328 block = filerec.resourceFork.extents[i].startBlock +
4329 filerec.resourceFork.extents[i].blockCount;
4330 if (block >= startblk) {
4331 cnidbufp[filecnt++] = filerec.fileID;
4332 blkstomove += filerec.resourceFork.totalBlocks;
4333 break;
4334 }
91447636
A
4335 }
4336 }
0c530ab8
A
4337 /*
4338 * Check for any overflow extents that overlap.
4339 */
4340 if (i == kHFSPlusExtentDensity) {
4341 if (filerec.dataFork.totalBlocks > datablks) {
4342 if (hfs_overlapped_overflow_extents(hfsmp, startblk, datablks, filerec.fileID, 0)) {
4343 cnidbufp[filecnt++] = filerec.fileID;
4344 blkstomove += filerec.dataFork.totalBlocks;
4345 }
4346 } else if (filerec.resourceFork.totalBlocks > rsrcblks) {
4347 if (hfs_overlapped_overflow_extents(hfsmp, startblk, rsrcblks, filerec.fileID, 1)) {
4348 cnidbufp[filecnt++] = filerec.fileID;
4349 blkstomove += filerec.resourceFork.totalBlocks;
4350 }
4351 }
4352 }
4353 }
4354
4355end_iteration:
2d21ac55
A
4356 if (filecnt == 0 && !system_file_moved) {
4357 printf("hfs_reclaimspace: no files moved\n");
0c530ab8 4358 error = ENOSPC;
91447636
A
4359 }
4360 /* All done with catalog. */
4361 hfs_systemfile_unlock(hfsmp, lockflags);
2d21ac55 4362 if (error || filecnt == 0)
91447636
A
4363 goto out;
4364
0c530ab8
A
4365 /*
4366 * Double check space requirements to make sure
4367 * there is enough space to relocate any files
4368 * that reside in the reclaim area.
4369 *
4370 * Blocks To Move --------------
4371 * | | |
4372 * V V V
4373 * ------------------------------------------------------------------------
4374 * | | / /// // |
4375 * | | / /// // |
4376 * | | / /// // |
4377 * ------------------------------------------------------------------------
4378 *
4379 * <------------------- New Total Blocks ------------------><-- Reclaim -->
4380 *
4381 * <------------------------ Original Total Blocks ----------------------->
4382 *
4383 */
2d21ac55
A
4384 if (blkstomove >= hfs_freeblks(hfsmp, 1)) {
4385 printf("hfs_truncatefs: insufficient space (need %lu blocks; have %u blocks)\n", blkstomove, hfs_freeblks(hfsmp, 1));
0c530ab8
A
4386 error = ENOSPC;
4387 goto out;
4388 }
4389 hfsmp->hfs_resize_filesmoved = 0;
4390 hfsmp->hfs_resize_totalfiles = filecnt;
4391
91447636
A
4392 /* Now move any files that are in the way. */
4393 for (i = 0; i < filecnt; ++i) {
4394 struct vnode * rvp;
4395
4396 if (hfs_vget(hfsmp, cnidbufp[i], &vp, 0) != 0)
4397 continue;
4398
4399 /* Relocate any data fork blocks. */
4400 if (VTOF(vp)->ff_blocks > 0) {
4401 error = hfs_relocate(vp, hfsmp->hfs_metazone_end + 1, kauth_cred_get(), current_proc());
4402 }
91447636
A
4403 if (error)
4404 break;
4405
4406 /* Relocate any resource fork blocks. */
4407 if ((VTOC((vp))->c_blocks - VTOF((vp))->ff_blocks) > 0) {
2d21ac55 4408 error = hfs_vgetrsrc(hfsmp, vp, &rvp, TRUE);
91447636
A
4409 if (error)
4410 break;
91447636 4411 error = hfs_relocate(rvp, hfsmp->hfs_metazone_end + 1, kauth_cred_get(), current_proc());
91447636
A
4412 vnode_put(rvp);
4413 if (error)
4414 break;
4415 }
743b1565 4416 hfs_unlock(VTOC(vp));
91447636
A
4417 vnode_put(vp);
4418 vp = NULL;
0c530ab8
A
4419
4420 ++hfsmp->hfs_resize_filesmoved;
4421
4422 /* Report intermediate progress. */
4423 if (filecnt > 100) {
4424 int progress;
4425
4426 progress = (i * 100) / filecnt;
4427 if (progress > (lastprogress + 9)) {
4428 printf("hfs_reclaimspace: %d%% done...\n", progress);
4429 lastprogress = progress;
4430 }
4431 }
91447636
A
4432 }
4433 if (vp) {
743b1565 4434 hfs_unlock(VTOC(vp));
91447636
A
4435 vnode_put(vp);
4436 vp = NULL;
4437 }
0c530ab8
A
4438 if (hfsmp->hfs_resize_filesmoved != 0) {
4439 printf("hfs_reclaimspace: relocated %d files on \"%s\"\n",
4440 (int)hfsmp->hfs_resize_filesmoved, hfsmp->vcbVN);
4441 }
91447636
A
4442out:
4443 kmem_free(kernel_map, (vm_offset_t)iterator, sizeof(*iterator));
4444 kmem_free(kernel_map, (vm_offset_t)cnidbufp, cnidbufsize);
4445
0c530ab8
A
4446 /*
4447 * Restore the roving allocation pointer on errors.
4448 * (but only if we didn't move any files)
4449 */
4450 if (error && hfsmp->hfs_resize_filesmoved == 0) {
2d21ac55 4451 HFS_UPDATE_NEXT_ALLOCATION(hfsmp, saved_next_allocation);
91447636
A
4452 }
4453 return (error);
4454}
4455
4456
0c530ab8
A
4457/*
4458 * Check if there are any overflow extents that overlap.
4459 */
4460static int
4461hfs_overlapped_overflow_extents(struct hfsmount *hfsmp, u_int32_t startblk, u_int32_t catblks, u_int32_t fileID, int rsrcfork)
4462{
4463 struct BTreeIterator * iterator = NULL;
4464 struct FSBufferDescriptor btdata;
4465 HFSPlusExtentRecord extrec;
4466 HFSPlusExtentKey *extkeyptr;
4467 FCB *fcb;
4468 u_int32_t block;
4469 u_int8_t forktype;
4470 int overlapped = 0;
4471 int i;
4472 int error;
4473
4474 forktype = rsrcfork ? 0xFF : 0;
4475 if (kmem_alloc(kernel_map, (vm_offset_t *)&iterator, sizeof(*iterator))) {
4476 return (0);
4477 }
4478 bzero(iterator, sizeof(*iterator));
4479 extkeyptr = (HFSPlusExtentKey *)&iterator->key;
4480 extkeyptr->keyLength = kHFSPlusExtentKeyMaximumLength;
4481 extkeyptr->forkType = forktype;
4482 extkeyptr->fileID = fileID;
4483 extkeyptr->startBlock = catblks;
4484
4485 btdata.bufferAddress = &extrec;
4486 btdata.itemSize = sizeof(extrec);
4487 btdata.itemCount = 1;
4488
4489 fcb = VTOF(hfsmp->hfs_extents_vp);
4490
4491 error = BTSearchRecord(fcb, iterator, &btdata, NULL, iterator);
4492 while (error == 0) {
4493 /* Stop when we encounter a different file. */
4494 if ((extkeyptr->fileID != fileID) ||
4495 (extkeyptr->forkType != forktype)) {
4496 break;
4497 }
4498 /*
4499 * Check if the file overlaps target space.
4500 */
4501 for (i = 0; i < kHFSPlusExtentDensity; ++i) {
4502 if (extrec[i].blockCount == 0) {
4503 break;
4504 }
4505 block = extrec[i].startBlock + extrec[i].blockCount;
4506 if (block >= startblk) {
4507 overlapped = 1;
4508 break;
4509 }
4510 }
4511 /* Look for more records. */
4512 error = BTIterateRecord(fcb, kBTreeNextRecord, iterator, &btdata, NULL);
4513 }
4514
4515 kmem_free(kernel_map, (vm_offset_t)iterator, sizeof(*iterator));
4516 return (overlapped);
4517}
4518
4519
4520/*
4521 * Calculate the progress of a file system resize operation.
4522 */
4523__private_extern__
4524int
4525hfs_resize_progress(struct hfsmount *hfsmp, u_int32_t *progress)
4526{
4527 if ((hfsmp->hfs_flags & HFS_RESIZE_IN_PROGRESS) == 0) {
4528 return (ENXIO);
4529 }
4530
4531 if (hfsmp->hfs_resize_totalfiles > 0)
4532 *progress = (hfsmp->hfs_resize_filesmoved * 100) / hfsmp->hfs_resize_totalfiles;
4533 else
4534 *progress = 0;
4535
4536 return (0);
4537}
4538
4539
91447636
A
4540/*
4541 * Get file system attributes.
4542 */
4543static int
4544hfs_vfs_getattr(struct mount *mp, struct vfs_attr *fsap, __unused vfs_context_t context)
4545{
2d21ac55
A
4546#define HFS_ATTR_CMN_VALIDMASK (ATTR_CMN_VALIDMASK & ~(ATTR_CMN_NAMEDATTRCOUNT | ATTR_CMN_NAMEDATTRLIST))
4547#define HFS_ATTR_FILE_VALIDMASK (ATTR_FILE_VALIDMASK & ~(ATTR_FILE_FILETYPE | ATTR_FILE_FORKCOUNT | ATTR_FILE_FORKLIST))
4548
91447636
A
4549 ExtendedVCB *vcb = VFSTOVCB(mp);
4550 struct hfsmount *hfsmp = VFSTOHFS(mp);
4551 u_long freeCNIDs;
4552
4553 freeCNIDs = (u_long)0xFFFFFFFF - (u_long)hfsmp->vcbNxtCNID;
4554
2d21ac55
A
4555 VFSATTR_RETURN(fsap, f_objcount, (u_int64_t)hfsmp->vcbFilCnt + (u_int64_t)hfsmp->vcbDirCnt);
4556 VFSATTR_RETURN(fsap, f_filecount, (u_int64_t)hfsmp->vcbFilCnt);
4557 VFSATTR_RETURN(fsap, f_dircount, (u_int64_t)hfsmp->vcbDirCnt);
4558 VFSATTR_RETURN(fsap, f_maxobjcount, (u_int64_t)0xFFFFFFFF);
91447636 4559 VFSATTR_RETURN(fsap, f_iosize, (size_t)(MAX_UPL_TRANSFER * PAGE_SIZE));
2d21ac55
A
4560 VFSATTR_RETURN(fsap, f_blocks, (u_int64_t)hfsmp->totalBlocks);
4561 VFSATTR_RETURN(fsap, f_bfree, (u_int64_t)hfs_freeblks(hfsmp, 0));
4562 VFSATTR_RETURN(fsap, f_bavail, (u_int64_t)hfs_freeblks(hfsmp, 1));
4563 VFSATTR_RETURN(fsap, f_bsize, (u_int32_t)vcb->blockSize);
91447636
A
4564 /* XXX needs clarification */
4565 VFSATTR_RETURN(fsap, f_bused, hfsmp->totalBlocks - hfs_freeblks(hfsmp, 1));
4566 /* Maximum files is constrained by total blocks. */
2d21ac55
A
4567 VFSATTR_RETURN(fsap, f_files, (u_int64_t)(hfsmp->totalBlocks - 2));
4568 VFSATTR_RETURN(fsap, f_ffree, MIN((u_int64_t)freeCNIDs, (u_int64_t)hfs_freeblks(hfsmp, 1)));
91447636
A
4569
4570 fsap->f_fsid.val[0] = hfsmp->hfs_raw_dev;
4571 fsap->f_fsid.val[1] = vfs_typenum(mp);
4572 VFSATTR_SET_SUPPORTED(fsap, f_fsid);
4573
4574 VFSATTR_RETURN(fsap, f_signature, vcb->vcbSigWord);
4575 VFSATTR_RETURN(fsap, f_carbon_fsid, 0);
4576
4577 if (VFSATTR_IS_ACTIVE(fsap, f_capabilities)) {
4578 vol_capabilities_attr_t *cap;
4579
4580 cap = &fsap->f_capabilities;
4581
4582 if (hfsmp->hfs_flags & HFS_STANDARD) {
4583 cap->capabilities[VOL_CAPABILITIES_FORMAT] =
4584 VOL_CAP_FMT_PERSISTENTOBJECTIDS |
4585 VOL_CAP_FMT_CASE_PRESERVING |
2d21ac55
A
4586 VOL_CAP_FMT_FAST_STATFS |
4587 VOL_CAP_FMT_HIDDEN_FILES |
4588 VOL_CAP_FMT_PATH_FROM_ID;
91447636
A
4589 } else {
4590 cap->capabilities[VOL_CAPABILITIES_FORMAT] =
4591 VOL_CAP_FMT_PERSISTENTOBJECTIDS |
4592 VOL_CAP_FMT_SYMBOLICLINKS |
4593 VOL_CAP_FMT_HARDLINKS |
4594 VOL_CAP_FMT_JOURNAL |
2d21ac55 4595 VOL_CAP_FMT_ZERO_RUNS |
91447636
A
4596 (hfsmp->jnl ? VOL_CAP_FMT_JOURNAL_ACTIVE : 0) |
4597 (hfsmp->hfs_flags & HFS_CASE_SENSITIVE ? VOL_CAP_FMT_CASE_SENSITIVE : 0) |
4598 VOL_CAP_FMT_CASE_PRESERVING |
4599 VOL_CAP_FMT_FAST_STATFS |
2d21ac55
A
4600 VOL_CAP_FMT_2TB_FILESIZE |
4601 VOL_CAP_FMT_HIDDEN_FILES |
4602 VOL_CAP_FMT_PATH_FROM_ID;
91447636
A
4603 }
4604 cap->capabilities[VOL_CAPABILITIES_INTERFACES] =
4605 VOL_CAP_INT_SEARCHFS |
4606 VOL_CAP_INT_ATTRLIST |
4607 VOL_CAP_INT_NFSEXPORT |
4608 VOL_CAP_INT_READDIRATTR |
4609 VOL_CAP_INT_EXCHANGEDATA |
4610 VOL_CAP_INT_ALLOCATE |
4611 VOL_CAP_INT_VOL_RENAME |
4612 VOL_CAP_INT_ADVLOCK |
2d21ac55
A
4613 VOL_CAP_INT_FLOCK |
4614#if NAMEDSTREAMS
4615 VOL_CAP_INT_EXTENDED_ATTR |
4616 VOL_CAP_INT_NAMEDSTREAMS;
4617#else
4618 VOL_CAP_INT_EXTENDED_ATTR;
4619#endif
91447636
A
4620 cap->capabilities[VOL_CAPABILITIES_RESERVED1] = 0;
4621 cap->capabilities[VOL_CAPABILITIES_RESERVED2] = 0;
4622
4623 cap->valid[VOL_CAPABILITIES_FORMAT] =
4624 VOL_CAP_FMT_PERSISTENTOBJECTIDS |
4625 VOL_CAP_FMT_SYMBOLICLINKS |
4626 VOL_CAP_FMT_HARDLINKS |
4627 VOL_CAP_FMT_JOURNAL |
4628 VOL_CAP_FMT_JOURNAL_ACTIVE |
4629 VOL_CAP_FMT_NO_ROOT_TIMES |
4630 VOL_CAP_FMT_SPARSE_FILES |
4631 VOL_CAP_FMT_ZERO_RUNS |
4632 VOL_CAP_FMT_CASE_SENSITIVE |
4633 VOL_CAP_FMT_CASE_PRESERVING |
4634 VOL_CAP_FMT_FAST_STATFS |
2d21ac55
A
4635 VOL_CAP_FMT_2TB_FILESIZE |
4636 VOL_CAP_FMT_OPENDENYMODES |
4637 VOL_CAP_FMT_HIDDEN_FILES |
4638 VOL_CAP_FMT_PATH_FROM_ID;
91447636
A
4639 cap->valid[VOL_CAPABILITIES_INTERFACES] =
4640 VOL_CAP_INT_SEARCHFS |
4641 VOL_CAP_INT_ATTRLIST |
4642 VOL_CAP_INT_NFSEXPORT |
4643 VOL_CAP_INT_READDIRATTR |
4644 VOL_CAP_INT_EXCHANGEDATA |
4645 VOL_CAP_INT_COPYFILE |
4646 VOL_CAP_INT_ALLOCATE |
4647 VOL_CAP_INT_VOL_RENAME |
4648 VOL_CAP_INT_ADVLOCK |
2d21ac55
A
4649 VOL_CAP_INT_FLOCK |
4650 VOL_CAP_INT_MANLOCK |
4651#if NAMEDSTREAMS
4652 VOL_CAP_INT_EXTENDED_ATTR |
4653 VOL_CAP_INT_NAMEDSTREAMS;
4654#else
4655 VOL_CAP_INT_EXTENDED_ATTR;
4656#endif
91447636
A
4657 cap->valid[VOL_CAPABILITIES_RESERVED1] = 0;
4658 cap->valid[VOL_CAPABILITIES_RESERVED2] = 0;
4659 VFSATTR_SET_SUPPORTED(fsap, f_capabilities);
4660 }
4661 if (VFSATTR_IS_ACTIVE(fsap, f_attributes)) {
4662 vol_attributes_attr_t *attrp = &fsap->f_attributes;
4663
2d21ac55 4664 attrp->validattr.commonattr = HFS_ATTR_CMN_VALIDMASK;
91447636
A
4665 attrp->validattr.volattr = ATTR_VOL_VALIDMASK & ~ATTR_VOL_INFO;
4666 attrp->validattr.dirattr = ATTR_DIR_VALIDMASK;
2d21ac55 4667 attrp->validattr.fileattr = HFS_ATTR_FILE_VALIDMASK;
91447636
A
4668 attrp->validattr.forkattr = 0;
4669
2d21ac55 4670 attrp->nativeattr.commonattr = HFS_ATTR_CMN_VALIDMASK;
91447636
A
4671 attrp->nativeattr.volattr = ATTR_VOL_VALIDMASK & ~ATTR_VOL_INFO;
4672 attrp->nativeattr.dirattr = ATTR_DIR_VALIDMASK;
2d21ac55 4673 attrp->nativeattr.fileattr = HFS_ATTR_FILE_VALIDMASK;
91447636
A
4674 attrp->nativeattr.forkattr = 0;
4675 VFSATTR_SET_SUPPORTED(fsap, f_attributes);
4676 }
4677 fsap->f_create_time.tv_sec = hfsmp->vcbCrDate;
4678 fsap->f_create_time.tv_nsec = 0;
4679 VFSATTR_SET_SUPPORTED(fsap, f_create_time);
4680 fsap->f_modify_time.tv_sec = hfsmp->vcbLsMod;
4681 fsap->f_modify_time.tv_nsec = 0;
4682 VFSATTR_SET_SUPPORTED(fsap, f_modify_time);
4683
4684 fsap->f_backup_time.tv_sec = hfsmp->vcbVolBkUp;
4685 fsap->f_backup_time.tv_nsec = 0;
4686 VFSATTR_SET_SUPPORTED(fsap, f_backup_time);
4687 if (VFSATTR_IS_ACTIVE(fsap, f_fssubtype)) {
2d21ac55 4688 u_int16_t subtype = 0;
91447636
A
4689
4690 /*
4691 * Subtypes (flavors) for HFS
4692 * 0: Mac OS Extended
4693 * 1: Mac OS Extended (Journaled)
4694 * 2: Mac OS Extended (Case Sensitive)
4695 * 3: Mac OS Extended (Case Sensitive, Journaled)
4696 * 4 - 127: Reserved
4697 * 128: Mac OS Standard
4698 *
4699 */
4700 if (hfsmp->hfs_flags & HFS_STANDARD) {
4701 subtype = HFS_SUBTYPE_STANDARDHFS;
4702 } else /* HFS Plus */ {
4703 if (hfsmp->jnl)
4704 subtype |= HFS_SUBTYPE_JOURNALED;
4705 if (hfsmp->hfs_flags & HFS_CASE_SENSITIVE)
4706 subtype |= HFS_SUBTYPE_CASESENSITIVE;
4707 }
4708 fsap->f_fssubtype = subtype;
4709 VFSATTR_SET_SUPPORTED(fsap, f_fssubtype);
4710 }
4711
4712 if (VFSATTR_IS_ACTIVE(fsap, f_vol_name)) {
2d21ac55 4713 strlcpy(fsap->f_vol_name, (char *) hfsmp->vcbVN, MAXPATHLEN);
91447636
A
4714 VFSATTR_SET_SUPPORTED(fsap, f_vol_name);
4715 }
4716 return (0);
4717}
4718
4719/*
4720 * Perform a volume rename. Requires the FS' root vp.
4721 */
4722static int
4723hfs_rename_volume(struct vnode *vp, const char *name, proc_t p)
4724{
4725 ExtendedVCB *vcb = VTOVCB(vp);
4726 struct cnode *cp = VTOC(vp);
4727 struct hfsmount *hfsmp = VTOHFS(vp);
4728 struct cat_desc to_desc;
4729 struct cat_desc todir_desc;
4730 struct cat_desc new_desc;
4731 cat_cookie_t cookie;
4732 int lockflags;
4733 int error = 0;
4734
4735 /*
4736 * Ignore attempts to rename a volume to a zero-length name.
4737 */
4738 if (name[0] == 0)
4739 return(0);
4740
4741 bzero(&to_desc, sizeof(to_desc));
4742 bzero(&todir_desc, sizeof(todir_desc));
4743 bzero(&new_desc, sizeof(new_desc));
4744 bzero(&cookie, sizeof(cookie));
4745
4746 todir_desc.cd_parentcnid = kHFSRootParentID;
4747 todir_desc.cd_cnid = kHFSRootFolderID;
4748 todir_desc.cd_flags = CD_ISDIR;
4749
2d21ac55 4750 to_desc.cd_nameptr = (const u_int8_t *)name;
91447636
A
4751 to_desc.cd_namelen = strlen(name);
4752 to_desc.cd_parentcnid = kHFSRootParentID;
4753 to_desc.cd_cnid = cp->c_cnid;
4754 to_desc.cd_flags = CD_ISDIR;
4755
4756 if ((error = hfs_lock(cp, HFS_EXCLUSIVE_LOCK)) == 0) {
4757 if ((error = hfs_start_transaction(hfsmp)) == 0) {
4758 if ((error = cat_preflight(hfsmp, CAT_RENAME, &cookie, p)) == 0) {
4759 lockflags = hfs_systemfile_lock(hfsmp, SFL_CATALOG, HFS_EXCLUSIVE_LOCK);
4760
4761 error = cat_rename(hfsmp, &cp->c_desc, &todir_desc, &to_desc, &new_desc);
4762
4763 /*
4764 * If successful, update the name in the VCB, ensure it's terminated.
4765 */
4766 if (!error) {
2d21ac55 4767 strlcpy((char *)vcb->vcbVN, name, sizeof(vcb->vcbVN));
91447636
A
4768 }
4769
4770 hfs_systemfile_unlock(hfsmp, lockflags);
4771 cat_postflight(hfsmp, &cookie, p);
4772
4773 if (error)
2d21ac55 4774 MarkVCBDirty(vcb);
91447636
A
4775 (void) hfs_flushvolumeheader(hfsmp, MNT_WAIT, 0);
4776 }
4777 hfs_end_transaction(hfsmp);
4778 }
4779 if (!error) {
4780 /* Release old allocated name buffer */
4781 if (cp->c_desc.cd_flags & CD_HASBUF) {
2d21ac55 4782 const char *tmp_name = (const char *)cp->c_desc.cd_nameptr;
91447636
A
4783
4784 cp->c_desc.cd_nameptr = 0;
4785 cp->c_desc.cd_namelen = 0;
4786 cp->c_desc.cd_flags &= ~CD_HASBUF;
2d21ac55 4787 vfs_removename(tmp_name);
91447636
A
4788 }
4789 /* Update cnode's catalog descriptor */
4790 replace_desc(cp, &new_desc);
4791 vcb->volumeNameEncodingHint = new_desc.cd_encoding;
4792 cp->c_touch_chgtime = TRUE;
4793 }
4794
4795 hfs_unlock(cp);
4796 }
4797
4798 return(error);
4799}
4800
4801/*
4802 * Get file system attributes.
4803 */
4804static int
4805hfs_vfs_setattr(struct mount *mp, struct vfs_attr *fsap, __unused vfs_context_t context)
4806{
4807 kauth_cred_t cred = vfs_context_ucred(context);
4808 int error = 0;
4809
4810 /*
4811 * Must be superuser or owner of filesystem to change volume attributes
4812 */
4813 if (!kauth_cred_issuser(cred) && (kauth_cred_getuid(cred) != vfs_statfs(mp)->f_owner))
4814 return(EACCES);
4815
4816 if (VFSATTR_IS_ACTIVE(fsap, f_vol_name)) {
4817 vnode_t root_vp;
4818
4819 error = hfs_vfs_root(mp, &root_vp, context);
4820 if (error)
4821 goto out;
4822
4823 error = hfs_rename_volume(root_vp, fsap->f_vol_name, vfs_context_proc(context));
4824 (void) vnode_put(root_vp);
4825 if (error)
4826 goto out;
4827
4828 VFSATTR_SET_SUPPORTED(fsap, f_vol_name);
4829 }
4830
4831out:
4832 return error;
4833}
4834
2d21ac55
A
4835/* If a runtime corruption is detected, set the volume inconsistent
4836 * bit in the volume attributes. The volume inconsistent bit is a persistent
4837 * bit which represents that the volume is corrupt and needs repair.
4838 * The volume inconsistent bit can be set from the kernel when it detects
4839 * runtime corruption or from file system repair utilities like fsck_hfs when
4840 * a repair operation fails. The bit should be cleared only from file system
4841 * verify/repair utility like fsck_hfs when a verify/repair succeeds.
4842 */
4843void hfs_mark_volume_inconsistent(struct hfsmount *hfsmp)
4844{
4845 HFS_MOUNT_LOCK(hfsmp, TRUE);
4846 if ((hfsmp->vcbAtrb & kHFSVolumeInconsistentMask) == 0) {
4847 hfsmp->vcbAtrb |= kHFSVolumeInconsistentMask;
4848 MarkVCBDirty(hfsmp);
4849 }
4850 /* Log information to ASL log */
4851 fslog_fs_corrupt(hfsmp->hfs_mp);
4852 printf("HFS: Runtime corruption detected on %s, fsck will be forced on next mount.\n", hfsmp->vcbVN);
4853 HFS_MOUNT_UNLOCK(hfsmp, TRUE);
4854}
4855
4856/* Replay the journal on the device node provided. Returns zero if
4857 * journal replay succeeded or no journal was supposed to be replayed.
4858 */
4859static int hfs_journal_replay(const char *devnode, vfs_context_t context)
4860{
4861 int retval = 0;
4862 struct vnode *devvp = NULL;
4863 struct mount *mp = NULL;
4864 struct hfs_mount_args *args = NULL;
4865
4866 /* Lookup vnode for given raw device path */
4867 retval = vnode_open(devnode, FREAD|FWRITE, 0, 0, &devvp, NULL);
4868 if (retval) {
4869 goto out;
4870 }
4871
4872 /* Replay allowed only on raw devices */
4873 if (!vnode_ischr(devvp)) {
4874 retval = EINVAL;
4875 goto out;
4876 }
4877
4878 /* Create dummy mount structures */
4879 MALLOC(mp, struct mount *, sizeof(struct mount), M_TEMP, M_WAITOK);
4880 bzero(mp, sizeof(struct mount));
4881 mount_lock_init(mp);
4882
4883 MALLOC(args, struct hfs_mount_args *, sizeof(struct hfs_mount_args), M_TEMP, M_WAITOK);
4884 bzero(args, sizeof(struct hfs_mount_args));
4885
4886 retval = hfs_mountfs(devvp, mp, args, 1, context);
4887 buf_flushdirtyblks(devvp, MNT_WAIT, 0, "hfs_journal_replay");
4888
4889out:
4890 if (mp) {
4891 mount_lock_destroy(mp);
4892 FREE(mp, M_TEMP);
4893 }
4894 if (args) {
4895 FREE(args, M_TEMP);
4896 }
4897 if (devvp) {
4898 vnode_close(devvp, FREAD|FWRITE, NULL);
4899 }
4900 return retval;
4901}
55e303ae 4902
1c79356b
A
4903/*
4904 * hfs vfs operations.
4905 */
4906struct vfsops hfs_vfsops = {
9bccf70c
A
4907 hfs_mount,
4908 hfs_start,
4909 hfs_unmount,
91447636 4910 hfs_vfs_root,
9bccf70c 4911 hfs_quotactl,
91447636 4912 hfs_vfs_getattr, /* was hfs_statfs */
9bccf70c 4913 hfs_sync,
91447636 4914 hfs_vfs_vget,
9bccf70c
A
4915 hfs_fhtovp,
4916 hfs_vptofh,
4917 hfs_init,
91447636 4918 hfs_sysctl,
2d21ac55
A
4919 hfs_vfs_setattr,
4920 {NULL}
1c79356b 4921};