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