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