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