2 * Copyright (c) 2000-2019 Apple Inc. All rights reserved.
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. The rights granted to you under the License
10 * may not be used to create, or enable the creation or redistribution of,
11 * unlawful or unlicensed copies of an Apple operating system, or to
12 * circumvent, violate, or enable the circumvention or violation of, any
13 * terms of an Apple operating system software license agreement.
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
18 * The Original Code and all software distributed under the License are
19 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23 * Please see the License for the specific language governing rights and
24 * limitations under the License.
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
28 /* Copyright (c) 1995 NeXT Computer, Inc. All Rights Reserved */
30 * Copyright (c) 1989, 1993
31 * The Regents of the University of California. All rights reserved.
32 * (c) UNIX System Laboratories, Inc.
33 * All or some portions of this file are derived from material licensed
34 * to the University of California by American Telephone and Telegraph
35 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
36 * the permission of UNIX System Laboratories, Inc.
38 * Redistribution and use in source and binary forms, with or without
39 * modification, are permitted provided that the following conditions
41 * 1. Redistributions of source code must retain the above copyright
42 * notice, this list of conditions and the following disclaimer.
43 * 2. Redistributions in binary form must reproduce the above copyright
44 * notice, this list of conditions and the following disclaimer in the
45 * documentation and/or other materials provided with the distribution.
46 * 3. All advertising materials mentioning features or use of this software
47 * must display the following acknowledgement:
48 * This product includes software developed by the University of
49 * California, Berkeley and its contributors.
50 * 4. Neither the name of the University nor the names of its contributors
51 * may be used to endorse or promote products derived from this software
52 * without specific prior written permission.
54 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
55 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
56 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
57 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
58 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
59 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
60 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
61 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
62 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
63 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
66 * @(#)vfs_subr.c 8.31 (Berkeley) 5/26/95
69 * NOTICE: This file was modified by SPARTA, Inc. in 2005 to introduce
70 * support for mandatory and extensible security protections. This notice
71 * is included in support of clause 2.2 (b) of the Apple Public License,
76 * External virtual filesystem routines
79 #include <sys/param.h>
80 #include <sys/systm.h>
81 #include <sys/proc_internal.h>
82 #include <sys/kauth.h>
83 #include <sys/mount_internal.h>
86 #include <sys/vnode.h>
87 #include <sys/vnode_internal.h>
89 #include <sys/namei.h>
90 #include <sys/ucred.h>
91 #include <sys/buf_internal.h>
92 #include <sys/errno.h>
93 #include <kern/kalloc.h>
94 #include <sys/uio_internal.h>
96 #include <sys/domain.h>
98 #include <sys/syslog.h>
99 #include <sys/ubc_internal.h>
101 #include <sys/sysctl.h>
102 #include <sys/filedesc.h>
103 #include <sys/event.h>
104 #include <sys/kdebug.h>
105 #include <sys/kauth.h>
106 #include <sys/user.h>
107 #include <sys/systm.h>
108 #include <sys/kern_memorystatus.h>
109 #include <sys/lockf.h>
110 #include <sys/reboot.h>
111 #include <miscfs/fifofs/fifo.h>
113 #include <nfs/nfs_conf.h>
116 #include <machine/machine_routines.h>
118 #include <kern/assert.h>
119 #include <mach/kern_return.h>
120 #include <kern/thread.h>
121 #include <kern/sched_prim.h>
123 #include <miscfs/specfs/specdev.h>
125 #include <mach/mach_types.h>
126 #include <mach/memory_object_types.h>
127 #include <mach/memory_object_control.h>
129 #include <kern/kalloc.h> /* kalloc()/kfree() */
130 #include <kern/clock.h> /* delay_for_interval() */
131 #include <libkern/OSAtomic.h> /* OSAddAtomic() */
132 #include <os/atomic_private.h>
133 #if defined(XNU_TARGET_OS_OSX)
134 #include <console/video_console.h>
138 #include <libkern/OSDebug.h>
141 #include <vm/vm_protos.h> /* vnode_pager_vrele() */
144 #include <security/mac_framework.h>
147 #include <vfs/vfs_disk_conditioner.h>
148 #include <libkern/section_keywords.h>
150 static LCK_GRP_DECLARE(vnode_lck_grp
, "vnode");
151 static LCK_ATTR_DECLARE(vnode_lck_attr
, 0, 0);
154 static LCK_GRP_DECLARE(trigger_vnode_lck_grp
, "trigger_vnode");
155 static LCK_ATTR_DECLARE(trigger_vnode_lck_attr
, 0, 0);
158 extern lck_mtx_t mnt_list_mtx_lock
;
160 ZONE_DECLARE(specinfo_zone
, "specinfo",
161 sizeof(struct specinfo
), ZC_NOENCRYPT
| ZC_ZFREE_CLEARMEM
);
163 ZONE_DECLARE(vnode_zone
, "vnodes",
164 sizeof(struct vnode
), ZC_NOENCRYPT
| ZC_NOGC
| ZC_ZFREE_CLEARMEM
);
166 enum vtype iftovt_tab
[16] = {
167 VNON
, VFIFO
, VCHR
, VNON
, VDIR
, VNON
, VBLK
, VNON
,
168 VREG
, VNON
, VLNK
, VNON
, VSOCK
, VNON
, VNON
, VBAD
,
170 int vttoif_tab
[9] = {
171 0, S_IFREG
, S_IFDIR
, S_IFBLK
, S_IFCHR
, S_IFLNK
,
172 S_IFSOCK
, S_IFIFO
, S_IFMT
,
175 /* XXX These should be in a BSD accessible Mach header, but aren't. */
176 extern void memory_object_mark_used(
177 memory_object_control_t control
);
179 extern void memory_object_mark_unused(
180 memory_object_control_t control
,
183 extern void memory_object_mark_io_tracking(
184 memory_object_control_t control
);
186 /* XXX next protptype should be from <nfs/nfs.h> */
187 extern int nfs_vinvalbuf(vnode_t
, int, vfs_context_t
, int);
189 extern int paniclog_append_noflush(const char *format
, ...);
191 /* XXX next prototytype should be from libsa/stdlib.h> but conflicts libkern */
192 __private_extern__
void qsort(
196 int (*)(const void *, const void *));
198 __private_extern__
void vntblinit(void);
199 __private_extern__
int unlink1(vfs_context_t
, vnode_t
, user_addr_t
,
202 static void vnode_list_add(vnode_t
);
203 static void vnode_async_list_add(vnode_t
);
204 static void vnode_list_remove(vnode_t
);
205 static void vnode_list_remove_locked(vnode_t
);
207 static void vnode_abort_advlocks(vnode_t
);
208 static errno_t
vnode_drain(vnode_t
);
209 static void vgone(vnode_t
, int flags
);
210 static void vclean(vnode_t vp
, int flag
);
211 static void vnode_reclaim_internal(vnode_t
, int, int, int);
213 static void vnode_dropiocount(vnode_t
);
215 static vnode_t
checkalias(vnode_t vp
, dev_t nvp_rdev
);
216 static int vnode_reload(vnode_t
);
218 static int unmount_callback(mount_t
, __unused
void *);
220 static void insmntque(vnode_t vp
, mount_t mp
);
221 static int mount_getvfscnt(void);
222 static int mount_fillfsids(fsid_t
*, int );
223 static void vnode_iterate_setup(mount_t
);
224 int vnode_umount_preflight(mount_t
, vnode_t
, int);
225 static int vnode_iterate_prepare(mount_t
);
226 static int vnode_iterate_reloadq(mount_t
);
227 static void vnode_iterate_clear(mount_t
);
228 static mount_t
vfs_getvfs_locked(fsid_t
*);
229 static int vn_create_reg(vnode_t dvp
, vnode_t
*vpp
, struct nameidata
*ndp
,
230 struct vnode_attr
*vap
, uint32_t flags
, int fmode
, uint32_t *statusp
, vfs_context_t ctx
);
231 static int vnode_authattr_new_internal(vnode_t dvp
, struct vnode_attr
*vap
, int noauth
, uint32_t *defaulted_fieldsp
, vfs_context_t ctx
);
233 errno_t
rmdir_remove_orphaned_appleDouble(vnode_t
, vfs_context_t
, int *);
236 static void record_vp(vnode_t vp
, int count
);
239 #if CONFIG_JETSAM && (DEVELOPMENT || DEBUG)
240 extern int bootarg_no_vnode_jetsam
; /* from bsd_init.c default value is 0 */
241 #endif /* CONFIG_JETSAM && (DEVELOPMENT || DEBUG) */
243 extern int bootarg_no_vnode_drain
; /* from bsd_init.c default value is 0 */
245 boolean_t root_is_CF_drive
= FALSE
;
248 static int vnode_resolver_create(mount_t
, vnode_t
, struct vnode_trigger_param
*, boolean_t external
);
249 static void vnode_resolver_detach(vnode_t
);
252 TAILQ_HEAD(freelst
, vnode
) vnode_free_list
; /* vnode free list */
253 TAILQ_HEAD(deadlst
, vnode
) vnode_dead_list
; /* vnode dead list */
254 TAILQ_HEAD(async_work_lst
, vnode
) vnode_async_work_list
;
257 TAILQ_HEAD(ragelst
, vnode
) vnode_rage_list
; /* vnode rapid age list */
258 struct timeval rage_tv
;
262 int deadvnodes_low
= 0;
263 int deadvnodes_high
= 0;
265 uint64_t newvnode
= 0;
266 uint64_t newvnode_nodead
= 0;
268 static int vfs_unmountall_started
= 0;
270 #define RAGE_LIMIT_MIN 100
271 #define RAGE_TIME_LIMIT 5
275 * NOTE: These are shadowed from PlatformSupport definitions, but XNU
278 #define PLATFORM_DATA_VOLUME_MOUNT_POINT "/System/Volumes/Data"
281 * These could be in PlatformSupport but aren't yet
283 #define PLATFORM_PREBOOT_VOLUME_MOUNT_POINT "/System/Volumes/Preboot"
284 #define PLATFORM_RECOVERY_VOLUME_MOUNT_POINT "/System/Volumes/Recovery"
287 #define PLATFORM_VM_VOLUME_MOUNT_POINT "/System/Volumes/VM"
290 struct mntlist mountlist
; /* mounted filesystem list */
291 static int nummounts
= 0;
293 static int print_busy_vnodes
= 0; /* print out busy vnodes */
296 #define VLISTCHECK(fun, vp, list) \
297 if ((vp)->v_freelist.tqe_prev == (struct vnode **)0xdeadb) \
298 panic("%s: %s vnode not on %slist", (fun), (list), (list));
300 #define VLISTCHECK(fun, vp, list)
301 #endif /* DIAGNOSTIC */
303 #define VLISTNONE(vp) \
305 (vp)->v_freelist.tqe_next = (struct vnode *)0; \
306 (vp)->v_freelist.tqe_prev = (struct vnode **)0xdeadb; \
309 #define VONLIST(vp) \
310 ((vp)->v_freelist.tqe_prev != (struct vnode **)0xdeadb)
312 /* remove a vnode from free vnode list */
313 #define VREMFREE(fun, vp) \
315 VLISTCHECK((fun), (vp), "free"); \
316 TAILQ_REMOVE(&vnode_free_list, (vp), v_freelist); \
322 /* remove a vnode from dead vnode list */
323 #define VREMDEAD(fun, vp) \
325 VLISTCHECK((fun), (vp), "dead"); \
326 TAILQ_REMOVE(&vnode_dead_list, (vp), v_freelist); \
328 vp->v_listflag &= ~VLIST_DEAD; \
333 /* remove a vnode from async work vnode list */
334 #define VREMASYNC_WORK(fun, vp) \
336 VLISTCHECK((fun), (vp), "async_work"); \
337 TAILQ_REMOVE(&vnode_async_work_list, (vp), v_freelist); \
339 vp->v_listflag &= ~VLIST_ASYNC_WORK; \
340 async_work_vnodes--; \
344 /* remove a vnode from rage vnode list */
345 #define VREMRAGE(fun, vp) \
347 if ( !(vp->v_listflag & VLIST_RAGE)) \
348 panic("VREMRAGE: vp not on rage list"); \
349 VLISTCHECK((fun), (vp), "rage"); \
350 TAILQ_REMOVE(&vnode_rage_list, (vp), v_freelist); \
352 vp->v_listflag &= ~VLIST_RAGE; \
356 static void async_work_continue(void);
357 static void vn_laundry_continue(void);
360 * Initialize the vnode management data structures.
362 __private_extern__
void
365 thread_t thread
= THREAD_NULL
;
367 TAILQ_INIT(&vnode_free_list
);
368 TAILQ_INIT(&vnode_rage_list
);
369 TAILQ_INIT(&vnode_dead_list
);
370 TAILQ_INIT(&vnode_async_work_list
);
371 TAILQ_INIT(&mountlist
);
373 microuptime(&rage_tv
);
374 rage_limit
= desiredvnodes
/ 100;
376 if (rage_limit
< RAGE_LIMIT_MIN
) {
377 rage_limit
= RAGE_LIMIT_MIN
;
380 deadvnodes_low
= (desiredvnodes
) / 100;
381 if (deadvnodes_low
> 300) {
382 deadvnodes_low
= 300;
384 deadvnodes_high
= deadvnodes_low
* 2;
387 * create worker threads
389 kernel_thread_start((thread_continue_t
)async_work_continue
, NULL
, &thread
);
390 thread_deallocate(thread
);
391 kernel_thread_start((thread_continue_t
)vn_laundry_continue
, NULL
, &thread
);
392 thread_deallocate(thread
);
395 /* the timeout is in 10 msecs */
397 vnode_waitforwrites(vnode_t vp
, int output_target
, int slpflag
, int slptimeout
, const char *msg
)
402 if (output_target
< 0) {
406 KERNEL_DEBUG(0x3010280 | DBG_FUNC_START
, (int)vp
, output_target
, vp
->v_numoutput
, 0, 0);
408 if (vp
->v_numoutput
> output_target
) {
413 while ((vp
->v_numoutput
> output_target
) && error
== 0) {
415 vp
->v_flag
|= VTHROTTLED
;
417 vp
->v_flag
|= VBWAIT
;
420 ts
.tv_sec
= (slptimeout
/ 100);
421 ts
.tv_nsec
= (slptimeout
% 1000) * 10 * NSEC_PER_USEC
* 1000;
422 error
= msleep((caddr_t
)&vp
->v_numoutput
, &vp
->v_lock
, (slpflag
| (PRIBIO
+ 1)), msg
, &ts
);
428 KERNEL_DEBUG(0x3010280 | DBG_FUNC_END
, (int)vp
, output_target
, vp
->v_numoutput
, error
, 0);
435 vnode_startwrite(vnode_t vp
)
437 OSAddAtomic(1, &vp
->v_numoutput
);
442 vnode_writedone(vnode_t vp
)
447 OSAddAtomic(-1, &vp
->v_numoutput
);
451 if (vp
->v_numoutput
< 0) {
452 panic("vnode_writedone: numoutput < 0");
455 if ((vp
->v_flag
& VTHROTTLED
)) {
456 vp
->v_flag
&= ~VTHROTTLED
;
459 if ((vp
->v_flag
& VBWAIT
) && (vp
->v_numoutput
== 0)) {
460 vp
->v_flag
&= ~VBWAIT
;
466 wakeup((caddr_t
)&vp
->v_numoutput
);
474 vnode_hasdirtyblks(vnode_t vp
)
476 struct cl_writebehind
*wbp
;
479 * Not taking the buf_mtx as there is little
480 * point doing it. Even if the lock is taken the
481 * state can change right after that. If their
482 * needs to be a synchronization, it must be driven
485 if (vp
->v_dirtyblkhd
.lh_first
) {
489 if (!UBCINFOEXISTS(vp
)) {
493 wbp
= vp
->v_ubcinfo
->cl_wbehind
;
495 if (wbp
&& (wbp
->cl_number
|| wbp
->cl_scmap
)) {
503 vnode_hascleanblks(vnode_t vp
)
506 * Not taking the buf_mtx as there is little
507 * point doing it. Even if the lock is taken the
508 * state can change right after that. If their
509 * needs to be a synchronization, it must be driven
512 if (vp
->v_cleanblkhd
.lh_first
) {
519 vnode_iterate_setup(mount_t mp
)
521 mp
->mnt_lflag
|= MNT_LITER
;
525 vnode_umount_preflight(mount_t mp
, vnode_t skipvp
, int flags
)
530 TAILQ_FOREACH(vp
, &mp
->mnt_vnodelist
, v_mntvnodes
) {
531 if (vp
->v_type
== VDIR
) {
537 if ((flags
& SKIPSYSTEM
) && ((vp
->v_flag
& VSYSTEM
) || (vp
->v_flag
& VNOFLUSH
))) {
540 if ((flags
& SKIPSWAP
) && (vp
->v_flag
& VSWAP
)) {
543 if ((flags
& WRITECLOSE
) && (vp
->v_writecount
== 0 || vp
->v_type
!= VREG
)) {
547 /* Look for busy vnode */
548 if ((vp
->v_usecount
!= 0) && ((vp
->v_usecount
- vp
->v_kusecount
) != 0)) {
550 if (print_busy_vnodes
&& ((flags
& FORCECLOSE
) == 0)) {
551 vprint("vnode_umount_preflight - busy vnode", vp
);
555 } else if (vp
->v_iocount
> 0) {
556 /* Busy if iocount is > 0 for more than 3 seconds */
557 tsleep(&vp
->v_iocount
, PVFS
, "vnode_drain_network", 3 * hz
);
558 if (vp
->v_iocount
> 0) {
560 if (print_busy_vnodes
&& ((flags
& FORCECLOSE
) == 0)) {
561 vprint("vnode_umount_preflight - busy vnode", vp
);
574 * This routine prepares iteration by moving all the vnodes to worker queue
575 * called with mount lock held
578 vnode_iterate_prepare(mount_t mp
)
582 if (TAILQ_EMPTY(&mp
->mnt_vnodelist
)) {
587 vp
= TAILQ_FIRST(&mp
->mnt_vnodelist
);
588 vp
->v_mntvnodes
.tqe_prev
= &(mp
->mnt_workerqueue
.tqh_first
);
589 mp
->mnt_workerqueue
.tqh_first
= mp
->mnt_vnodelist
.tqh_first
;
590 mp
->mnt_workerqueue
.tqh_last
= mp
->mnt_vnodelist
.tqh_last
;
592 TAILQ_INIT(&mp
->mnt_vnodelist
);
593 if (mp
->mnt_newvnodes
.tqh_first
!= NULL
) {
594 panic("vnode_iterate_prepare: newvnode when entering vnode");
596 TAILQ_INIT(&mp
->mnt_newvnodes
);
602 /* called with mount lock held */
604 vnode_iterate_reloadq(mount_t mp
)
608 /* add the remaining entries in workerq to the end of mount vnode list */
609 if (!TAILQ_EMPTY(&mp
->mnt_workerqueue
)) {
611 mvp
= TAILQ_LAST(&mp
->mnt_vnodelist
, vnodelst
);
613 /* Joining the workerque entities to mount vnode list */
615 mvp
->v_mntvnodes
.tqe_next
= mp
->mnt_workerqueue
.tqh_first
;
617 mp
->mnt_vnodelist
.tqh_first
= mp
->mnt_workerqueue
.tqh_first
;
619 mp
->mnt_workerqueue
.tqh_first
->v_mntvnodes
.tqe_prev
= mp
->mnt_vnodelist
.tqh_last
;
620 mp
->mnt_vnodelist
.tqh_last
= mp
->mnt_workerqueue
.tqh_last
;
621 TAILQ_INIT(&mp
->mnt_workerqueue
);
624 /* add the newvnodes to the head of mount vnode list */
625 if (!TAILQ_EMPTY(&mp
->mnt_newvnodes
)) {
627 nlvp
= TAILQ_LAST(&mp
->mnt_newvnodes
, vnodelst
);
629 mp
->mnt_newvnodes
.tqh_first
->v_mntvnodes
.tqe_prev
= &mp
->mnt_vnodelist
.tqh_first
;
630 nlvp
->v_mntvnodes
.tqe_next
= mp
->mnt_vnodelist
.tqh_first
;
631 if (mp
->mnt_vnodelist
.tqh_first
) {
632 mp
->mnt_vnodelist
.tqh_first
->v_mntvnodes
.tqe_prev
= &nlvp
->v_mntvnodes
.tqe_next
;
634 mp
->mnt_vnodelist
.tqh_last
= mp
->mnt_newvnodes
.tqh_last
;
636 mp
->mnt_vnodelist
.tqh_first
= mp
->mnt_newvnodes
.tqh_first
;
637 TAILQ_INIT(&mp
->mnt_newvnodes
);
646 vnode_iterate_clear(mount_t mp
)
648 mp
->mnt_lflag
&= ~MNT_LITER
;
651 #if defined(__x86_64__)
653 #include <i386/panic_hooks.h>
655 struct vnode_iterate_panic_hook
{
662 vnode_iterate_panic_hook(panic_hook_t
*hook_
)
664 struct vnode_iterate_panic_hook
*hook
= (struct vnode_iterate_panic_hook
*)hook_
;
665 panic_phys_range_t range
;
668 if (panic_phys_range_before(hook
->mp
, &phys
, &range
)) {
669 paniclog_append_noflush("mp = %p, phys = %p, prev (%p: %p-%p)\n",
670 hook
->mp
, phys
, range
.type
, range
.phys_start
,
671 range
.phys_start
+ range
.len
);
673 paniclog_append_noflush("mp = %p, phys = %p, prev (!)\n", hook
->mp
, phys
);
676 if (panic_phys_range_before(hook
->vp
, &phys
, &range
)) {
677 paniclog_append_noflush("vp = %p, phys = %p, prev (%p: %p-%p)\n",
678 hook
->vp
, phys
, range
.type
, range
.phys_start
,
679 range
.phys_start
+ range
.len
);
681 paniclog_append_noflush("vp = %p, phys = %p, prev (!)\n", hook
->vp
, phys
);
683 panic_dump_mem((void *)(((vm_offset_t
)hook
->mp
- 4096) & ~4095), 12288);
685 #endif /* defined(__x86_64__) */
688 vnode_iterate(mount_t mp
, int flags
, int (*callout
)(struct vnode
*, void *),
696 * The mount iterate mutex is held for the duration of the iteration.
697 * This can be done by a state flag on the mount structure but we can
698 * run into priority inversion issues sometimes.
699 * Using a mutex allows us to benefit from the priority donation
700 * mechanisms in the kernel for locks. This mutex should never be
701 * acquired in spin mode and it should be acquired before attempting to
702 * acquire the mount lock.
704 mount_iterate_lock(mp
);
708 vnode_iterate_setup(mp
);
710 /* If it returns 0 then there is nothing to do */
711 retval
= vnode_iterate_prepare(mp
);
714 vnode_iterate_clear(mp
);
716 mount_iterate_unlock(mp
);
720 #if defined(__x86_64__)
721 struct vnode_iterate_panic_hook hook
;
724 panic_hook(&hook
.hook
, vnode_iterate_panic_hook
);
726 /* iterate over all the vnodes */
727 while (!TAILQ_EMPTY(&mp
->mnt_workerqueue
)) {
728 vp
= TAILQ_FIRST(&mp
->mnt_workerqueue
);
729 #if defined(__x86_64__)
732 TAILQ_REMOVE(&mp
->mnt_workerqueue
, vp
, v_mntvnodes
);
733 TAILQ_INSERT_TAIL(&mp
->mnt_vnodelist
, vp
, v_mntvnodes
);
735 if ((vp
->v_data
== NULL
) || (vp
->v_type
== VNON
) || (vp
->v_mount
!= mp
)) {
740 if (vget_internal(vp
, vid
, (flags
| VNODE_NODEAD
| VNODE_WITHID
| VNODE_NOSUSPEND
))) {
744 if (flags
& VNODE_RELOAD
) {
746 * we're reloading the filesystem
747 * cast out any inactive vnodes...
749 if (vnode_reload(vp
)) {
750 /* vnode will be recycled on the refcount drop */
757 retval
= callout(vp
, arg
);
761 case VNODE_RETURNED_DONE
:
763 if (retval
== VNODE_RETURNED_DONE
) {
770 case VNODE_CLAIMED_DONE
:
782 #if defined(__x86_64__)
783 panic_unhook(&hook
.hook
);
785 (void)vnode_iterate_reloadq(mp
);
786 vnode_iterate_clear(mp
);
788 mount_iterate_unlock(mp
);
793 mount_lock_renames(mount_t mp
)
795 lck_mtx_lock(&mp
->mnt_renamelock
);
799 mount_unlock_renames(mount_t mp
)
801 lck_mtx_unlock(&mp
->mnt_renamelock
);
805 mount_iterate_lock(mount_t mp
)
807 lck_mtx_lock(&mp
->mnt_iter_lock
);
811 mount_iterate_unlock(mount_t mp
)
813 lck_mtx_unlock(&mp
->mnt_iter_lock
);
817 mount_lock(mount_t mp
)
819 lck_mtx_lock(&mp
->mnt_mlock
);
823 mount_lock_spin(mount_t mp
)
825 lck_mtx_lock_spin(&mp
->mnt_mlock
);
829 mount_unlock(mount_t mp
)
831 lck_mtx_unlock(&mp
->mnt_mlock
);
836 mount_ref(mount_t mp
, int locked
)
851 mount_drop(mount_t mp
, int locked
)
859 if (mp
->mnt_count
== 0 && (mp
->mnt_lflag
& MNT_LDRAIN
)) {
860 wakeup(&mp
->mnt_lflag
);
870 mount_iterref(mount_t mp
, int locked
)
877 if (mp
->mnt_iterref
< 0) {
889 mount_isdrained(mount_t mp
, int locked
)
896 if (mp
->mnt_iterref
< 0) {
908 mount_iterdrop(mount_t mp
)
912 wakeup(&mp
->mnt_iterref
);
917 mount_iterdrain(mount_t mp
)
920 while (mp
->mnt_iterref
) {
921 msleep((caddr_t
)&mp
->mnt_iterref
, &mnt_list_mtx_lock
, PVFS
, "mount_iterdrain", NULL
);
923 /* mount iterations drained */
924 mp
->mnt_iterref
= -1;
928 mount_iterreset(mount_t mp
)
931 if (mp
->mnt_iterref
== -1) {
937 /* always called with mount lock held */
939 mount_refdrain(mount_t mp
)
941 if (mp
->mnt_lflag
& MNT_LDRAIN
) {
942 panic("already in drain");
944 mp
->mnt_lflag
|= MNT_LDRAIN
;
946 while (mp
->mnt_count
) {
947 msleep((caddr_t
)&mp
->mnt_lflag
, &mp
->mnt_mlock
, PVFS
, "mount_drain", NULL
);
950 if (mp
->mnt_vnodelist
.tqh_first
!= NULL
) {
951 panic("mount_refdrain: dangling vnode");
954 mp
->mnt_lflag
&= ~MNT_LDRAIN
;
959 /* Tags the mount point as not supportine extended readdir for NFS exports */
961 mount_set_noreaddirext(mount_t mp
)
964 mp
->mnt_kern_flag
|= MNTK_DENY_READDIREXT
;
969 * Mark a mount point as busy. Used to synchronize access and to delay
973 vfs_busy(mount_t mp
, int flags
)
976 if (mp
->mnt_lflag
& MNT_LDEAD
) {
982 if (mp
->mnt_lflag
& MNT_LUNMOUNT
) {
983 if (flags
& LK_NOWAIT
|| mp
->mnt_lflag
& MNT_LDEAD
) {
989 * Since all busy locks are shared except the exclusive
990 * lock granted when unmounting, the only place that a
991 * wakeup needs to be done is at the release of the
992 * exclusive lock at the end of dounmount.
994 mp
->mnt_lflag
|= MNT_LWAIT
;
995 msleep((caddr_t
)mp
, &mp
->mnt_mlock
, (PVFS
| PDROP
), "vfsbusy", NULL
);
1001 lck_rw_lock_shared(&mp
->mnt_rwlock
);
1004 * Until we are granted the rwlock, it's possible for the mount point to
1005 * change state, so re-evaluate before granting the vfs_busy.
1007 if (mp
->mnt_lflag
& (MNT_LDEAD
| MNT_LUNMOUNT
)) {
1008 lck_rw_done(&mp
->mnt_rwlock
);
1015 * Free a busy filesystem.
1018 vfs_unbusy(mount_t mp
)
1020 lck_rw_done(&mp
->mnt_rwlock
);
1026 vfs_rootmountfailed(mount_t mp
)
1029 mp
->mnt_vtable
->vfc_refcount
--;
1030 mount_list_unlock();
1034 mount_lock_destroy(mp
);
1037 mac_mount_label_destroy(mp
);
1040 zfree(mount_zone
, mp
);
1044 * Lookup a filesystem type, and if found allocate and initialize
1045 * a mount structure for it.
1047 * Devname is usually updated by mount(8) after booting.
1050 vfs_rootmountalloc_internal(struct vfstable
*vfsp
, const char *devname
)
1054 mp
= zalloc_flags(mount_zone
, Z_WAITOK
| Z_ZERO
);
1055 /* Initialize the default IO constraints */
1056 mp
->mnt_maxreadcnt
= mp
->mnt_maxwritecnt
= MAXPHYS
;
1057 mp
->mnt_segreadcnt
= mp
->mnt_segwritecnt
= 32;
1058 mp
->mnt_maxsegreadsize
= mp
->mnt_maxreadcnt
;
1059 mp
->mnt_maxsegwritesize
= mp
->mnt_maxwritecnt
;
1060 mp
->mnt_devblocksize
= DEV_BSIZE
;
1061 mp
->mnt_alignmentmask
= PAGE_MASK
;
1062 mp
->mnt_ioqueue_depth
= MNT_DEFAULT_IOQUEUE_DEPTH
;
1063 mp
->mnt_ioscale
= 1;
1064 mp
->mnt_ioflags
= 0;
1065 mp
->mnt_realrootvp
= NULLVP
;
1066 mp
->mnt_authcache_ttl
= CACHED_LOOKUP_RIGHT_TTL
;
1067 mp
->mnt_throttle_mask
= LOWPRI_MAX_NUM_DEV
- 1;
1068 mp
->mnt_devbsdunit
= 0;
1070 mount_lock_init(mp
);
1071 (void)vfs_busy(mp
, LK_NOWAIT
);
1073 TAILQ_INIT(&mp
->mnt_vnodelist
);
1074 TAILQ_INIT(&mp
->mnt_workerqueue
);
1075 TAILQ_INIT(&mp
->mnt_newvnodes
);
1077 mp
->mnt_vtable
= vfsp
;
1078 mp
->mnt_op
= vfsp
->vfc_vfsops
;
1079 mp
->mnt_flag
= MNT_RDONLY
| MNT_ROOTFS
;
1080 mp
->mnt_vnodecovered
= NULLVP
;
1081 //mp->mnt_stat.f_type = vfsp->vfc_typenum;
1082 mp
->mnt_flag
|= vfsp
->vfc_flags
& MNT_VISFLAGMASK
;
1085 vfsp
->vfc_refcount
++;
1086 mount_list_unlock();
1088 strlcpy(mp
->mnt_vfsstat
.f_fstypename
, vfsp
->vfc_name
, MFSTYPENAMELEN
);
1089 mp
->mnt_vfsstat
.f_mntonname
[0] = '/';
1090 /* XXX const poisoning layering violation */
1091 (void) copystr((const void *)devname
, mp
->mnt_vfsstat
.f_mntfromname
, MAXPATHLEN
- 1, NULL
);
1094 mac_mount_label_init(mp
);
1095 mac_mount_label_associate(vfs_context_kernel(), mp
);
1101 vfs_rootmountalloc(const char *fstypename
, const char *devname
, mount_t
*mpp
)
1103 struct vfstable
*vfsp
;
1105 for (vfsp
= vfsconf
; vfsp
; vfsp
= vfsp
->vfc_next
) {
1106 if (!strncmp(vfsp
->vfc_name
, fstypename
,
1107 sizeof(vfsp
->vfc_name
))) {
1115 *mpp
= vfs_rootmountalloc_internal(vfsp
, devname
);
1124 #define DBG_MOUNTROOT (FSDBG_CODE(DBG_MOUNT, 0))
1127 * Find an appropriate filesystem to use for the root. If a filesystem
1128 * has not been preselected, walk through the list of known filesystems
1129 * trying those that have mountroot routines, and try them until one
1130 * works or we have tried them all.
1132 extern int (*mountroot
)(void);
1140 struct vfstable
*vfsp
;
1141 vfs_context_t ctx
= vfs_context_kernel();
1142 struct vfs_attr vfsattr
;
1145 vnode_t bdevvp_rootvp
;
1147 KDBG_RELEASE(DBG_MOUNTROOT
| DBG_FUNC_START
);
1148 if (mountroot
!= NULL
) {
1150 * used for netboot which follows a different set of rules
1152 error
= (*mountroot
)();
1154 KDBG_RELEASE(DBG_MOUNTROOT
| DBG_FUNC_END
, error
, 0);
1157 if ((error
= bdevvp(rootdev
, &rootvp
))) {
1158 printf("vfs_mountroot: can't setup bdevvp\n");
1160 KDBG_RELEASE(DBG_MOUNTROOT
| DBG_FUNC_END
, error
, 1);
1164 * 4951998 - code we call in vfc_mountroot may replace rootvp
1165 * so keep a local copy for some house keeping.
1167 bdevvp_rootvp
= rootvp
;
1169 for (vfsp
= vfsconf
; vfsp
; vfsp
= vfsp
->vfc_next
) {
1170 if (vfsp
->vfc_mountroot
== NULL
1171 && !ISSET(vfsp
->vfc_vfsflags
, VFC_VFSCANMOUNTROOT
)) {
1175 mp
= vfs_rootmountalloc_internal(vfsp
, "root_device");
1176 mp
->mnt_devvp
= rootvp
;
1178 if (vfsp
->vfc_mountroot
) {
1179 error
= (*vfsp
->vfc_mountroot
)(mp
, rootvp
, ctx
);
1181 error
= VFS_MOUNT(mp
, rootvp
, 0, ctx
);
1185 if (bdevvp_rootvp
!= rootvp
) {
1188 * bump the iocount and fix up mnt_devvp for the
1189 * new rootvp (it will already have a usecount taken)...
1190 * drop the iocount and the usecount on the orignal
1191 * since we are no longer going to use it...
1193 vnode_getwithref(rootvp
);
1194 mp
->mnt_devvp
= rootvp
;
1196 vnode_rele(bdevvp_rootvp
);
1197 vnode_put(bdevvp_rootvp
);
1199 mp
->mnt_devvp
->v_specflags
|= SI_MOUNTEDON
;
1206 * cache the IO attributes for the underlying physical media...
1207 * an error return indicates the underlying driver doesn't
1208 * support all the queries necessary... however, reasonable
1209 * defaults will have been set, so no reason to bail or care
1211 vfs_init_io_attributes(rootvp
, mp
);
1213 if (mp
->mnt_ioflags
& MNT_IOFLAGS_FUSION_DRIVE
) {
1214 root_is_CF_drive
= TRUE
;
1218 * Shadow the VFC_VFSNATIVEXATTR flag to MNTK_EXTENDED_ATTRS.
1220 if (mp
->mnt_vtable
->vfc_vfsflags
& VFC_VFSNATIVEXATTR
) {
1221 mp
->mnt_kern_flag
|= MNTK_EXTENDED_ATTRS
;
1223 if (mp
->mnt_vtable
->vfc_vfsflags
& VFC_VFSPREFLIGHT
) {
1224 mp
->mnt_kern_flag
|= MNTK_UNMOUNT_PREFLIGHT
;
1227 #if defined(XNU_TARGET_OS_OSX)
1230 if (MNTK_VIRTUALDEV
& mp
->mnt_kern_flag
) {
1232 } else if (disk_conditioner_mount_is_ssd(mp
)) {
1237 vc_progress_setdiskspeed(speed
);
1238 #endif /* XNU_TARGET_OS_OSX */
1240 * Probe root file system for additional features.
1242 (void)VFS_START(mp
, 0, ctx
);
1244 VFSATTR_INIT(&vfsattr
);
1245 VFSATTR_WANTED(&vfsattr
, f_capabilities
);
1246 if (vfs_getattr(mp
, &vfsattr
, ctx
) == 0 &&
1247 VFSATTR_IS_SUPPORTED(&vfsattr
, f_capabilities
)) {
1248 if ((vfsattr
.f_capabilities
.capabilities
[VOL_CAPABILITIES_INTERFACES
] & VOL_CAP_INT_EXTENDED_ATTR
) &&
1249 (vfsattr
.f_capabilities
.valid
[VOL_CAPABILITIES_INTERFACES
] & VOL_CAP_INT_EXTENDED_ATTR
)) {
1250 mp
->mnt_kern_flag
|= MNTK_EXTENDED_ATTRS
;
1253 if ((vfsattr
.f_capabilities
.capabilities
[VOL_CAPABILITIES_INTERFACES
] & VOL_CAP_INT_NAMEDSTREAMS
) &&
1254 (vfsattr
.f_capabilities
.valid
[VOL_CAPABILITIES_INTERFACES
] & VOL_CAP_INT_NAMEDSTREAMS
)) {
1255 mp
->mnt_kern_flag
|= MNTK_NAMED_STREAMS
;
1258 if ((vfsattr
.f_capabilities
.capabilities
[VOL_CAPABILITIES_FORMAT
] & VOL_CAP_FMT_PATH_FROM_ID
) &&
1259 (vfsattr
.f_capabilities
.valid
[VOL_CAPABILITIES_FORMAT
] & VOL_CAP_FMT_PATH_FROM_ID
)) {
1260 mp
->mnt_kern_flag
|= MNTK_PATH_FROM_ID
;
1263 if ((vfsattr
.f_capabilities
.capabilities
[VOL_CAPABILITIES_FORMAT
] & VOL_CAP_FMT_DIR_HARDLINKS
) &&
1264 (vfsattr
.f_capabilities
.valid
[VOL_CAPABILITIES_FORMAT
] & VOL_CAP_FMT_DIR_HARDLINKS
)) {
1265 mp
->mnt_kern_flag
|= MNTK_DIR_HARDLINKS
;
1270 * get rid of iocount reference returned
1271 * by bdevvp (or picked up by us on the substitued
1272 * rootvp)... it (or we) will have also taken
1273 * a usecount reference which we want to keep
1278 if ((vfs_flags(mp
) & MNT_MULTILABEL
) == 0) {
1279 KDBG_RELEASE(DBG_MOUNTROOT
| DBG_FUNC_END
, 0, 2);
1283 error
= VFS_ROOT(mp
, &vp
, ctx
);
1285 printf("%s() VFS_ROOT() returned %d\n",
1287 dounmount(mp
, MNT_FORCE
, 0, ctx
);
1290 error
= vnode_label(mp
, NULL
, vp
, NULL
, 0, ctx
);
1292 * get rid of reference provided by VFS_ROOT
1297 printf("%s() vnode_label() returned %d\n",
1299 dounmount(mp
, MNT_FORCE
, 0, ctx
);
1303 KDBG_RELEASE(DBG_MOUNTROOT
| DBG_FUNC_END
, 0, 3);
1309 vfs_rootmountfailed(mp
);
1311 if (error
!= EINVAL
) {
1312 printf("%s_mountroot failed: %d\n", vfsp
->vfc_name
, error
);
1315 KDBG_RELEASE(DBG_MOUNTROOT
| DBG_FUNC_END
, error
? error
: ENODEV
, 4);
1320 cache_purge_callback(mount_t mp
, __unused
void * arg
)
1323 return VFS_RETURNED
;
1326 extern lck_rw_t rootvnode_rw_lock
;
1327 extern void set_rootvnode(vnode_t
);
1331 mntonname_fixup_callback(mount_t mp
, __unused
void *arg
)
1335 if ((strncmp(&mp
->mnt_vfsstat
.f_mntonname
[0], "/", sizeof("/")) == 0) ||
1336 (strncmp(&mp
->mnt_vfsstat
.f_mntonname
[0], "/dev", sizeof("/dev")) == 0)) {
1340 if ((error
= vfs_busy(mp
, LK_NOWAIT
))) {
1341 printf("vfs_busy failed with %d for %s\n", error
, mp
->mnt_vfsstat
.f_mntonname
);
1345 int pathlen
= MAXPATHLEN
;
1346 if ((error
= vn_getpath_ext(mp
->mnt_vnodecovered
, NULL
, mp
->mnt_vfsstat
.f_mntonname
, &pathlen
, VN_GETPATH_FSENTER
))) {
1347 printf("vn_getpath_ext failed with %d for mnt_vnodecovered of %s\n", error
, mp
->mnt_vfsstat
.f_mntonname
);
1356 clear_mntk_backs_root_callback(mount_t mp
, __unused
void *arg
)
1358 lck_rw_lock_exclusive(&mp
->mnt_rwlock
);
1359 mp
->mnt_kern_flag
&= ~MNTK_BACKS_ROOT
;
1360 lck_rw_done(&mp
->mnt_rwlock
);
1361 return VFS_RETURNED
;
1365 verify_incoming_rootfs(vnode_t
*incoming_rootvnodep
, vfs_context_t ctx
,
1366 vfs_switch_root_flags_t flags
)
1370 vnode_t incoming_rootvnode_with_iocount
= *incoming_rootvnodep
;
1371 vnode_t incoming_rootvnode_with_usecount
= NULLVP
;
1374 if (vnode_vtype(incoming_rootvnode_with_iocount
) != VDIR
) {
1375 printf("Incoming rootfs path not a directory\n");
1381 * Before we call VFS_ROOT, we have to let go of the iocount already
1382 * acquired, but before doing that get a usecount.
1384 vnode_ref_ext(incoming_rootvnode_with_iocount
, 0, VNODE_REF_FORCE
);
1385 incoming_rootvnode_with_usecount
= incoming_rootvnode_with_iocount
;
1386 vnode_lock_spin(incoming_rootvnode_with_usecount
);
1387 if ((mp
= incoming_rootvnode_with_usecount
->v_mount
)) {
1389 vnode_unlock(incoming_rootvnode_with_usecount
);
1391 vnode_unlock(incoming_rootvnode_with_usecount
);
1392 printf("Incoming rootfs root vnode does not have associated mount\n");
1397 if (vfs_busy(mp
, LK_NOWAIT
)) {
1398 printf("Incoming rootfs root vnode mount is busy\n");
1403 vnode_put(incoming_rootvnode_with_iocount
);
1404 incoming_rootvnode_with_iocount
= NULLVP
;
1406 error
= VFS_ROOT(mp
, &tdp
, ctx
);
1409 printf("Could not get rootvnode of incoming rootfs\n");
1410 } else if (tdp
!= incoming_rootvnode_with_usecount
) {
1413 printf("Incoming rootfs root vnode mount is is not a mountpoint\n");
1417 incoming_rootvnode_with_iocount
= tdp
;
1421 if ((flags
& VFSSR_VIRTUALDEV_PROHIBITED
) != 0) {
1422 lck_rw_lock_shared(&mp
->mnt_rwlock
);
1423 if (mp
->mnt_flag
& MNTK_VIRTUALDEV
) {
1426 lck_rw_done(&mp
->mnt_rwlock
);
1428 printf("Incoming rootfs is backed by a virtual device; cannot switch to it");
1437 vnode_lock(incoming_rootvnode_with_usecount
);
1439 if (mp
->mnt_crossref
< 0) {
1440 panic("mount cross refs -ve");
1442 vnode_unlock(incoming_rootvnode_with_usecount
);
1445 if (incoming_rootvnode_with_usecount
) {
1446 vnode_rele(incoming_rootvnode_with_usecount
);
1447 incoming_rootvnode_with_usecount
= NULLVP
;
1450 if (error
&& incoming_rootvnode_with_iocount
) {
1451 vnode_put(incoming_rootvnode_with_iocount
);
1452 incoming_rootvnode_with_iocount
= NULLVP
;
1455 *incoming_rootvnodep
= incoming_rootvnode_with_iocount
;
1462 * Move the current root volume, and put a different volume at the root.
1464 * incoming_vol_old_path: This is the path where the incoming root volume
1465 * is mounted when this function begins.
1466 * outgoing_vol_new_path: This is the path where the outgoing root volume
1467 * will be mounted when this function (successfully) ends.
1468 * Note: Do not use a leading slash.
1470 * Volumes mounted at several fixed points (including /dev) will be preserved
1471 * at the same absolute path. That means they will move within the folder
1472 * hierarchy during the pivot operation. For example, /dev before the pivot
1473 * will be at /dev after the pivot.
1475 * If any filesystem has MNTK_BACKS_ROOT set, it will be cleared. If the
1476 * incoming root volume is actually a disk image backed by some other
1477 * filesystem, it is the caller's responsibility to re-set MNTK_BACKS_ROOT
1481 vfs_switch_root(const char *incoming_vol_old_path
,
1482 const char *outgoing_vol_new_path
,
1483 vfs_switch_root_flags_t flags
)
1486 #define countof(x) (sizeof(x) / sizeof(x[0]))
1488 struct preserved_mount
{
1489 vnode_t pm_rootvnode
;
1491 vnode_t pm_new_covered_vp
;
1492 vnode_t pm_old_covered_vp
;
1493 const char *pm_path
;
1496 vfs_context_t ctx
= vfs_context_kernel();
1497 vnode_t incoming_rootvnode
= NULLVP
;
1498 vnode_t outgoing_vol_new_covered_vp
= NULLVP
;
1499 vnode_t incoming_vol_old_covered_vp
= NULLVP
;
1500 mount_t outgoing
= NULL
;
1501 mount_t incoming
= NULL
;
1503 struct preserved_mount devfs
= { NULLVP
, NULL
, NULLVP
, NULLVP
, "dev" };
1504 struct preserved_mount preboot
= { NULLVP
, NULL
, NULLVP
, NULLVP
, "System/Volumes/Preboot" };
1505 struct preserved_mount recovery
= { NULLVP
, NULL
, NULLVP
, NULLVP
, "System/Volumes/Recovery" };
1506 struct preserved_mount vm
= { NULLVP
, NULL
, NULLVP
, NULLVP
, "System/Volumes/VM" };
1507 struct preserved_mount update
= { NULLVP
, NULL
, NULLVP
, NULLVP
, "System/Volumes/Update" };
1508 struct preserved_mount iscPreboot
= { NULLVP
, NULL
, NULLVP
, NULLVP
, "System/Volumes/iSCPreboot" };
1509 struct preserved_mount hardware
= { NULLVP
, NULL
, NULLVP
, NULLVP
, "System/Volumes/Hardware" };
1510 struct preserved_mount xarts
= { NULLVP
, NULL
, NULLVP
, NULLVP
, "System/Volumes/xarts" };
1511 struct preserved_mount factorylogs
= { NULLVP
, NULL
, NULLVP
, NULLVP
, "FactoryLogs" };
1512 struct preserved_mount idiags
= { NULLVP
, NULL
, NULLVP
, NULLVP
, "System/Volumes/Diags" };
1514 struct preserved_mount
*preserved
[10];
1515 preserved
[0] = &devfs
;
1516 preserved
[1] = &preboot
;
1517 preserved
[2] = &recovery
;
1519 preserved
[4] = &update
;
1520 preserved
[5] = &iscPreboot
;
1521 preserved
[6] = &hardware
;
1522 preserved
[7] = &xarts
;
1523 preserved
[8] = &factorylogs
;
1524 preserved
[9] = &idiags
;
1528 printf("%s : shuffling mount points : %s <-> / <-> %s\n", __FUNCTION__
, incoming_vol_old_path
, outgoing_vol_new_path
);
1530 if (outgoing_vol_new_path
[0] == '/') {
1531 // I should have written this to be more helpful and just advance the pointer forward past the slash
1532 printf("Do not use a leading slash in outgoing_vol_new_path\n");
1536 // Set incoming_rootvnode.
1537 // Find the vnode representing the mountpoint of the new root
1538 // filesystem. That will be the new root directory.
1539 error
= vnode_lookup(incoming_vol_old_path
, 0, &incoming_rootvnode
, ctx
);
1541 printf("Incoming rootfs root vnode not found\n");
1547 * This function drops the icoount and sets the vnode to NULL on error.
1549 error
= verify_incoming_rootfs(&incoming_rootvnode
, ctx
, flags
);
1555 * Set outgoing_vol_new_covered_vp.
1556 * Find the vnode representing the future mountpoint of the old
1557 * root filesystem, inside the directory incoming_rootvnode.
1558 * Right now it's at "/incoming_vol_old_path/outgoing_vol_new_path".
1559 * soon it will become "/oldrootfs_path_after", which will be covered.
1561 error
= vnode_lookupat(outgoing_vol_new_path
, 0, &outgoing_vol_new_covered_vp
, ctx
, incoming_rootvnode
);
1563 printf("Outgoing rootfs path not found, abandoning / switch, error = %d\n", error
);
1567 if (vnode_vtype(outgoing_vol_new_covered_vp
) != VDIR
) {
1568 printf("Outgoing rootfs path is not a directory, abandoning / switch\n");
1574 * Find the preserved mounts - see if they are mounted. Get their root
1575 * vnode if they are. If they aren't, leave rootvnode NULL which will
1576 * be the signal to ignore this mount later on.
1578 * Also get preserved mounts' new_covered_vp.
1579 * Find the node representing the folder "dev" inside the directory newrootvnode.
1580 * Right now it's at "/incoming_vol_old_path/dev".
1581 * Soon it will become /dev, which will be covered by the devfs mountpoint.
1583 for (size_t i
= 0; i
< countof(preserved
); i
++) {
1584 struct preserved_mount
*pmi
= preserved
[i
];
1586 error
= vnode_lookupat(pmi
->pm_path
, 0, &pmi
->pm_rootvnode
, ctx
, rootvnode
);
1588 printf("skipping preserved mountpoint because not found or error: %d: %s\n", error
, pmi
->pm_path
);
1589 // not fatal. try the next one in the list.
1592 bool is_mountpoint
= false;
1593 vnode_lock_spin(pmi
->pm_rootvnode
);
1594 if ((pmi
->pm_rootvnode
->v_flag
& VROOT
) != 0) {
1595 is_mountpoint
= true;
1597 vnode_unlock(pmi
->pm_rootvnode
);
1598 if (!is_mountpoint
) {
1599 printf("skipping preserved mountpoint because not a mountpoint: %s\n", pmi
->pm_path
);
1600 vnode_put(pmi
->pm_rootvnode
);
1601 pmi
->pm_rootvnode
= NULLVP
;
1602 // not fatal. try the next one in the list.
1606 error
= vnode_lookupat(pmi
->pm_path
, 0, &pmi
->pm_new_covered_vp
, ctx
, incoming_rootvnode
);
1608 printf("preserved new mount directory not found or error: %d: %s\n", error
, pmi
->pm_path
);
1612 if (vnode_vtype(pmi
->pm_new_covered_vp
) != VDIR
) {
1613 printf("preserved new mount directory not directory: %s\n", pmi
->pm_path
);
1618 printf("will preserve mountpoint across pivot: /%s\n", pmi
->pm_path
);
1623 * At this point, everything has been prepared and all error conditions
1624 * have been checked. We check everything we can before this point;
1625 * from now on we start making destructive changes, and we can't stop
1626 * until we reach the end.
1630 /* this usecount is transferred to the mnt_vnodecovered */
1631 vnode_ref_ext(outgoing_vol_new_covered_vp
, 0, VNODE_REF_FORCE
);
1632 /* this usecount is transferred to set_rootvnode */
1633 vnode_ref_ext(incoming_rootvnode
, 0, VNODE_REF_FORCE
);
1636 for (size_t i
= 0; i
< countof(preserved
); i
++) {
1637 struct preserved_mount
*pmi
= preserved
[i
];
1638 if (pmi
->pm_rootvnode
== NULLVP
) {
1642 /* this usecount is transferred to the mnt_vnodecovered */
1643 vnode_ref_ext(pmi
->pm_new_covered_vp
, 0, VNODE_REF_FORCE
);
1645 /* The new_covered_vp is a mountpoint from now on. */
1646 vnode_lock_spin(pmi
->pm_new_covered_vp
);
1647 pmi
->pm_new_covered_vp
->v_flag
|= VMOUNT
;
1648 vnode_unlock(pmi
->pm_new_covered_vp
);
1651 /* The outgoing_vol_new_covered_vp is a mountpoint from now on. */
1652 vnode_lock_spin(outgoing_vol_new_covered_vp
);
1653 outgoing_vol_new_covered_vp
->v_flag
|= VMOUNT
;
1654 vnode_unlock(outgoing_vol_new_covered_vp
);
1658 * Identify the mount_ts of the mounted filesystems that are being
1659 * manipulated: outgoing rootfs, incoming rootfs, and the preserved
1662 outgoing
= rootvnode
->v_mount
;
1663 incoming
= incoming_rootvnode
->v_mount
;
1664 for (size_t i
= 0; i
< countof(preserved
); i
++) {
1665 struct preserved_mount
*pmi
= preserved
[i
];
1666 if (pmi
->pm_rootvnode
== NULLVP
) {
1670 pmi
->pm_mount
= pmi
->pm_rootvnode
->v_mount
;
1673 lck_rw_lock_exclusive(&rootvnode_rw_lock
);
1675 /* Setup incoming as the new rootfs */
1676 lck_rw_lock_exclusive(&incoming
->mnt_rwlock
);
1677 incoming_vol_old_covered_vp
= incoming
->mnt_vnodecovered
;
1678 incoming
->mnt_vnodecovered
= NULLVP
;
1679 strlcpy(incoming
->mnt_vfsstat
.f_mntonname
, "/", MAXPATHLEN
);
1680 incoming
->mnt_flag
|= MNT_ROOTFS
;
1681 lck_rw_done(&incoming
->mnt_rwlock
);
1684 * The preserved mountpoints will now be moved to
1685 * incoming_rootnode/pm_path, and then by the end of the function,
1686 * since incoming_rootnode is going to /, the preserved mounts
1687 * will be end up back at /pm_path
1689 for (size_t i
= 0; i
< countof(preserved
); i
++) {
1690 struct preserved_mount
*pmi
= preserved
[i
];
1691 if (pmi
->pm_rootvnode
== NULLVP
) {
1695 lck_rw_lock_exclusive(&pmi
->pm_mount
->mnt_rwlock
);
1696 pmi
->pm_old_covered_vp
= pmi
->pm_mount
->mnt_vnodecovered
;
1697 pmi
->pm_mount
->mnt_vnodecovered
= pmi
->pm_new_covered_vp
;
1698 vnode_lock_spin(pmi
->pm_new_covered_vp
);
1699 pmi
->pm_new_covered_vp
->v_mountedhere
= pmi
->pm_mount
;
1700 vnode_unlock(pmi
->pm_new_covered_vp
);
1701 lck_rw_done(&pmi
->pm_mount
->mnt_rwlock
);
1705 * The old root volume now covers outgoing_vol_new_covered_vp
1706 * on the new root volume. Remove the ROOTFS marker.
1707 * Now it is to be found at outgoing_vol_new_path
1709 lck_rw_lock_exclusive(&outgoing
->mnt_rwlock
);
1710 outgoing
->mnt_vnodecovered
= outgoing_vol_new_covered_vp
;
1711 strlcpy(outgoing
->mnt_vfsstat
.f_mntonname
, "/", MAXPATHLEN
);
1712 strlcat(outgoing
->mnt_vfsstat
.f_mntonname
, outgoing_vol_new_path
, MAXPATHLEN
);
1713 outgoing
->mnt_flag
&= ~MNT_ROOTFS
;
1714 vnode_lock_spin(outgoing_vol_new_covered_vp
);
1715 outgoing_vol_new_covered_vp
->v_mountedhere
= outgoing
;
1716 vnode_unlock(outgoing_vol_new_covered_vp
);
1717 lck_rw_done(&outgoing
->mnt_rwlock
);
1719 if (!(outgoing
->mnt_kern_flag
& MNTK_VIRTUALDEV
) &&
1720 (TAILQ_FIRST(&mountlist
) == outgoing
)) {
1721 vfs_setmntsystem(outgoing
);
1725 * Finally, remove the mount_t linkage from the previously covered
1726 * vnodes on the old root volume. These were incoming_vol_old_path,
1727 * and each preserved mounts's "/pm_path". The filesystems previously
1728 * mounted there have already been moved away.
1730 vnode_lock_spin(incoming_vol_old_covered_vp
);
1731 incoming_vol_old_covered_vp
->v_flag
&= ~VMOUNT
;
1732 incoming_vol_old_covered_vp
->v_mountedhere
= NULL
;
1733 vnode_unlock(incoming_vol_old_covered_vp
);
1735 for (size_t i
= 0; i
< countof(preserved
); i
++) {
1736 struct preserved_mount
*pmi
= preserved
[i
];
1737 if (pmi
->pm_rootvnode
== NULLVP
) {
1741 vnode_lock_spin(pmi
->pm_old_covered_vp
);
1742 pmi
->pm_old_covered_vp
->v_flag
&= ~VMOUNT
;
1743 pmi
->pm_old_covered_vp
->v_mountedhere
= NULL
;
1744 vnode_unlock(pmi
->pm_old_covered_vp
);
1748 * Clear the name cache since many cached names are now invalid.
1750 vfs_iterate(0 /* flags */, cache_purge_callback
, NULL
);
1753 * Actually change the rootvnode! And finally drop the lock that
1754 * prevents concurrent vnode_lookups.
1756 set_rootvnode(incoming_rootvnode
);
1757 lck_rw_unlock_exclusive(&rootvnode_rw_lock
);
1759 if (!(incoming
->mnt_kern_flag
& MNTK_VIRTUALDEV
) &&
1760 !(outgoing
->mnt_kern_flag
& MNTK_VIRTUALDEV
)) {
1762 * Switch the order of mount structures in the mountlist, new root
1763 * mount moves to the head of the list followed by /dev and the other
1764 * preserved mounts then all the preexisting mounts (old rootfs + any
1768 for (size_t i
= 0; i
< countof(preserved
); i
++) {
1769 struct preserved_mount
*pmi
= preserved
[i
];
1770 if (pmi
->pm_rootvnode
== NULLVP
) {
1774 TAILQ_REMOVE(&mountlist
, pmi
->pm_mount
, mnt_list
);
1775 TAILQ_INSERT_HEAD(&mountlist
, pmi
->pm_mount
, mnt_list
);
1777 TAILQ_REMOVE(&mountlist
, incoming
, mnt_list
);
1778 TAILQ_INSERT_HEAD(&mountlist
, incoming
, mnt_list
);
1779 mount_list_unlock();
1783 * Fixups across all volumes
1785 vfs_iterate(0 /* flags */, mntonname_fixup_callback
, NULL
);
1786 vfs_iterate(0 /* flags */, clear_mntk_backs_root_callback
, NULL
);
1791 for (size_t i
= 0; i
< countof(preserved
); i
++) {
1792 struct preserved_mount
*pmi
= preserved
[i
];
1794 if (pmi
->pm_rootvnode
) {
1795 vnode_put(pmi
->pm_rootvnode
);
1797 if (pmi
->pm_new_covered_vp
) {
1798 vnode_put(pmi
->pm_new_covered_vp
);
1800 if (pmi
->pm_old_covered_vp
) {
1801 vnode_rele(pmi
->pm_old_covered_vp
);
1805 if (outgoing_vol_new_covered_vp
) {
1806 vnode_put(outgoing_vol_new_covered_vp
);
1809 if (incoming_vol_old_covered_vp
) {
1810 vnode_rele(incoming_vol_old_covered_vp
);
1813 if (incoming_rootvnode
) {
1814 vnode_put(incoming_rootvnode
);
1817 printf("%s : done shuffling mount points with error: %d\n", __FUNCTION__
, error
);
1822 * Mount the Recovery volume of a container
1825 vfs_mount_recovery(void)
1827 #if CONFIG_MOUNT_PREBOOTRECOVERY
1830 error
= vnode_get(rootvnode
);
1832 /* root must be mounted first */
1833 printf("vnode_get(rootvnode) failed with error %d\n", error
);
1837 char recoverypath
[] = PLATFORM_RECOVERY_VOLUME_MOUNT_POINT
; /* !const because of internal casting */
1839 /* Mount the recovery volume */
1840 printf("attempting kernel mount for recovery volume... \n");
1841 error
= kernel_mount(rootvnode
->v_mount
->mnt_vfsstat
.f_fstypename
, NULLVP
, NULLVP
,
1842 recoverypath
, (rootvnode
->v_mount
), 0, 0, (KERNEL_MOUNT_RECOVERYVOL
), vfs_context_kernel());
1845 printf("Failed to mount recovery volume (%d)\n", error
);
1847 printf("mounted recovery volume\n");
1850 vnode_put(rootvnode
);
1858 * Lookup a mount point by filesystem identifier.
1862 vfs_getvfs(fsid_t
*fsid
)
1864 return mount_list_lookupby_fsid(fsid
, 0, 0);
1867 static struct mount
*
1868 vfs_getvfs_locked(fsid_t
*fsid
)
1870 return mount_list_lookupby_fsid(fsid
, 1, 0);
1874 vfs_getvfs_by_mntonname(char *path
)
1876 mount_t retmp
= (mount_t
)0;
1880 TAILQ_FOREACH(mp
, &mountlist
, mnt_list
) {
1881 if (!strncmp(mp
->mnt_vfsstat
.f_mntonname
, path
,
1882 sizeof(mp
->mnt_vfsstat
.f_mntonname
))) {
1884 if (mount_iterref(retmp
, 1)) {
1891 mount_list_unlock();
1895 /* generation number for creation of new fsids */
1896 u_short mntid_gen
= 0;
1898 * Get a new unique fsid
1901 vfs_getnewfsid(struct mount
*mp
)
1908 /* generate a new fsid */
1909 mtype
= mp
->mnt_vtable
->vfc_typenum
;
1910 if (++mntid_gen
== 0) {
1913 tfsid
.val
[0] = makedev(nblkdev
+ mtype
, mntid_gen
);
1914 tfsid
.val
[1] = mtype
;
1916 while (vfs_getvfs_locked(&tfsid
)) {
1917 if (++mntid_gen
== 0) {
1920 tfsid
.val
[0] = makedev(nblkdev
+ mtype
, mntid_gen
);
1923 mp
->mnt_vfsstat
.f_fsid
.val
[0] = tfsid
.val
[0];
1924 mp
->mnt_vfsstat
.f_fsid
.val
[1] = tfsid
.val
[1];
1925 mount_list_unlock();
1929 * Routines having to do with the management of the vnode table.
1931 extern int(**dead_vnodeop_p
)(void *);
1932 long numvnodes
, freevnodes
, deadvnodes
, async_work_vnodes
;
1935 int async_work_timed_out
= 0;
1936 int async_work_handled
= 0;
1937 int dead_vnode_wanted
= 0;
1938 int dead_vnode_waited
= 0;
1941 * Move a vnode from one mount queue to another.
1944 insmntque(vnode_t vp
, mount_t mp
)
1948 * Delete from old mount point vnode list, if on one.
1950 if ((lmp
= vp
->v_mount
) != NULL
&& lmp
!= dead_mountp
) {
1951 if ((vp
->v_lflag
& VNAMED_MOUNT
) == 0) {
1952 panic("insmntque: vp not in mount vnode list");
1954 vp
->v_lflag
&= ~VNAMED_MOUNT
;
1956 mount_lock_spin(lmp
);
1960 if (vp
->v_mntvnodes
.tqe_next
== NULL
) {
1961 if (TAILQ_LAST(&lmp
->mnt_vnodelist
, vnodelst
) == vp
) {
1962 TAILQ_REMOVE(&lmp
->mnt_vnodelist
, vp
, v_mntvnodes
);
1963 } else if (TAILQ_LAST(&lmp
->mnt_newvnodes
, vnodelst
) == vp
) {
1964 TAILQ_REMOVE(&lmp
->mnt_newvnodes
, vp
, v_mntvnodes
);
1965 } else if (TAILQ_LAST(&lmp
->mnt_workerqueue
, vnodelst
) == vp
) {
1966 TAILQ_REMOVE(&lmp
->mnt_workerqueue
, vp
, v_mntvnodes
);
1969 vp
->v_mntvnodes
.tqe_next
->v_mntvnodes
.tqe_prev
= vp
->v_mntvnodes
.tqe_prev
;
1970 *vp
->v_mntvnodes
.tqe_prev
= vp
->v_mntvnodes
.tqe_next
;
1972 vp
->v_mntvnodes
.tqe_next
= NULL
;
1973 vp
->v_mntvnodes
.tqe_prev
= NULL
;
1979 * Insert into list of vnodes for the new mount point, if available.
1981 if ((vp
->v_mount
= mp
) != NULL
) {
1982 mount_lock_spin(mp
);
1983 if ((vp
->v_mntvnodes
.tqe_next
!= 0) && (vp
->v_mntvnodes
.tqe_prev
!= 0)) {
1984 panic("vp already in mount list");
1986 if (mp
->mnt_lflag
& MNT_LITER
) {
1987 TAILQ_INSERT_HEAD(&mp
->mnt_newvnodes
, vp
, v_mntvnodes
);
1989 TAILQ_INSERT_HEAD(&mp
->mnt_vnodelist
, vp
, v_mntvnodes
);
1991 if (vp
->v_lflag
& VNAMED_MOUNT
) {
1992 panic("insmntque: vp already in mount vnode list");
1994 vp
->v_lflag
|= VNAMED_MOUNT
;
2002 * Create a vnode for a block device.
2003 * Used for root filesystem, argdev, and swap areas.
2004 * Also used for memory file system special devices.
2007 bdevvp(dev_t dev
, vnode_t
*vpp
)
2011 struct vnode_fsparam vfsp
;
2012 struct vfs_context context
;
2019 context
.vc_thread
= current_thread();
2020 context
.vc_ucred
= FSCRED
;
2022 vfsp
.vnfs_mp
= (struct mount
*)0;
2023 vfsp
.vnfs_vtype
= VBLK
;
2024 vfsp
.vnfs_str
= "bdevvp";
2025 vfsp
.vnfs_dvp
= NULL
;
2026 vfsp
.vnfs_fsnode
= NULL
;
2027 vfsp
.vnfs_cnp
= NULL
;
2028 vfsp
.vnfs_vops
= spec_vnodeop_p
;
2029 vfsp
.vnfs_rdev
= dev
;
2030 vfsp
.vnfs_filesize
= 0;
2032 vfsp
.vnfs_flags
= VNFS_NOCACHE
| VNFS_CANTCACHE
;
2034 vfsp
.vnfs_marksystem
= 0;
2035 vfsp
.vnfs_markroot
= 0;
2037 if ((error
= vnode_create(VNCREATE_FLAVOR
, VCREATESIZE
, &vfsp
, &nvp
))) {
2041 vnode_lock_spin(nvp
);
2042 nvp
->v_flag
|= VBDEVVP
;
2043 nvp
->v_tag
= VT_NON
; /* set this to VT_NON so during aliasing it can be replaced */
2045 if ((error
= vnode_ref(nvp
))) {
2046 panic("bdevvp failed: vnode_ref");
2049 if ((error
= VNOP_FSYNC(nvp
, MNT_WAIT
, &context
))) {
2050 panic("bdevvp failed: fsync");
2053 if ((error
= buf_invalidateblks(nvp
, BUF_WRITE_DATA
, 0, 0))) {
2054 panic("bdevvp failed: invalidateblks");
2060 * XXXMAC: We can't put a MAC check here, the system will
2061 * panic without this vnode.
2065 if ((error
= VNOP_OPEN(nvp
, FREAD
, &context
))) {
2066 panic("bdevvp failed: open");
2075 * Check to see if the new vnode represents a special device
2076 * for which we already have a vnode (either because of
2077 * bdevvp() or because of a different vnode representing
2078 * the same block device). If such an alias exists, deallocate
2079 * the existing contents and return the aliased vnode. The
2080 * caller is responsible for filling it with its new contents.
2083 checkalias(struct vnode
*nvp
, dev_t nvp_rdev
)
2087 struct specinfo
*sin
= NULL
;
2090 vpp
= &speclisth
[SPECHASH(nvp_rdev
)];
2094 for (vp
= *vpp
; vp
; vp
= vp
->v_specnext
) {
2095 if (nvp_rdev
== vp
->v_rdev
&& nvp
->v_type
== vp
->v_type
) {
2104 if (vnode_getwithvid(vp
, vid
)) {
2108 * Termination state is checked in vnode_getwithvid
2113 * Alias, but not in use, so flush it out.
2115 if ((vp
->v_iocount
== 1) && (vp
->v_usecount
== 0)) {
2116 vnode_reclaim_internal(vp
, 1, 1, 0);
2117 vnode_put_locked(vp
);
2122 if (vp
== NULL
|| vp
->v_tag
!= VT_NON
) {
2124 sin
= zalloc_flags(specinfo_zone
, Z_WAITOK
| Z_ZERO
);
2126 bzero(sin
, sizeof(struct specinfo
));
2129 nvp
->v_specinfo
= sin
;
2130 nvp
->v_rdev
= nvp_rdev
;
2131 nvp
->v_specflags
= 0;
2132 nvp
->v_speclastr
= -1;
2133 nvp
->v_specinfo
->si_opencount
= 0;
2134 nvp
->v_specinfo
->si_initted
= 0;
2135 nvp
->v_specinfo
->si_throttleable
= 0;
2139 /* We dropped the lock, someone could have added */
2141 for (vp
= *vpp
; vp
; vp
= vp
->v_specnext
) {
2142 if (nvp_rdev
== vp
->v_rdev
&& nvp
->v_type
== vp
->v_type
) {
2150 nvp
->v_hashchain
= vpp
;
2151 nvp
->v_specnext
= *vpp
;
2155 nvp
->v_specflags
|= SI_ALIASED
;
2156 vp
->v_specflags
|= SI_ALIASED
;
2158 vnode_put_locked(vp
);
2168 zfree(specinfo_zone
, sin
);
2171 if ((vp
->v_flag
& (VBDEVVP
| VDEVFLUSH
)) != 0) {
2175 panic("checkalias with VT_NON vp that shouldn't: %p", vp
);
2182 * Get a reference on a particular vnode and lock it if requested.
2183 * If the vnode was on the inactive list, remove it from the list.
2184 * If the vnode was on the free list, remove it from the list and
2185 * move it to inactive list as needed.
2186 * The vnode lock bit is set if the vnode is being eliminated in
2187 * vgone. The process is awakened when the transition is completed,
2188 * and an error returned to indicate that the vnode is no longer
2189 * usable (possibly having been changed to a new file system type).
2192 vget_internal(vnode_t vp
, int vid
, int vflags
)
2196 vnode_lock_spin(vp
);
2198 if ((vflags
& VNODE_WRITEABLE
) && (vp
->v_writecount
== 0)) {
2200 * vnode to be returned only if it has writers opened
2204 error
= vnode_getiocount(vp
, vid
, vflags
);
2213 * Returns: 0 Success
2214 * ENOENT No such file or directory [terminating]
2217 vnode_ref(vnode_t vp
)
2219 return vnode_ref_ext(vp
, 0, 0);
2223 * Returns: 0 Success
2224 * ENOENT No such file or directory [terminating]
2227 vnode_ref_ext(vnode_t vp
, int fmode
, int flags
)
2231 vnode_lock_spin(vp
);
2234 * once all the current call sites have been fixed to insure they have
2235 * taken an iocount, we can toughen this assert up and insist that the
2236 * iocount is non-zero... a non-zero usecount doesn't insure correctness
2238 if (vp
->v_iocount
<= 0 && vp
->v_usecount
<= 0) {
2239 panic("vnode_ref_ext: vp %p has no valid reference %d, %d", vp
, vp
->v_iocount
, vp
->v_usecount
);
2243 * if you are the owner of drain/termination, can acquire usecount
2245 if ((flags
& VNODE_REF_FORCE
) == 0) {
2246 if ((vp
->v_lflag
& (VL_DRAIN
| VL_TERMINATE
| VL_DEAD
))) {
2247 if (vp
->v_owner
!= current_thread()) {
2254 /* Enable atomic ops on v_usecount without the vnode lock */
2255 os_atomic_inc(&vp
->v_usecount
, relaxed
);
2257 if (fmode
& FWRITE
) {
2258 if (++vp
->v_writecount
<= 0) {
2259 panic("vnode_ref_ext: v_writecount");
2262 if (fmode
& O_EVTONLY
) {
2263 if (++vp
->v_kusecount
<= 0) {
2264 panic("vnode_ref_ext: v_kusecount");
2267 if (vp
->v_flag
& VRAGE
) {
2270 ut
= get_bsdthread_info(current_thread());
2272 if (!(current_proc()->p_lflag
& P_LRAGE_VNODES
) &&
2273 !(ut
->uu_flag
& UT_RAGE_VNODES
)) {
2275 * a 'normal' process accessed this vnode
2276 * so make sure its no longer marked
2277 * for rapid aging... also, make sure
2278 * it gets removed from the rage list...
2279 * when v_usecount drops back to 0, it
2280 * will be put back on the real free list
2282 vp
->v_flag
&= ~VRAGE
;
2283 vp
->v_references
= 0;
2284 vnode_list_remove(vp
);
2287 if (vp
->v_usecount
== 1 && vp
->v_type
== VREG
&& !(vp
->v_flag
& VSYSTEM
)) {
2288 if (vp
->v_ubcinfo
) {
2289 vnode_lock_convert(vp
);
2290 memory_object_mark_used(vp
->v_ubcinfo
->ui_control
);
2301 vnode_on_reliable_media(vnode_t vp
)
2303 mount_t mp
= vp
->v_mount
;
2306 * A NULL mountpoint would imply it's not attached to a any filesystem.
2307 * This can only happen with a vnode created by bdevvp(). We'll consider
2308 * those as not unreliable as the primary use of this function is determine
2309 * which vnodes are to be handed off to the async cleaner thread for
2312 if (!mp
|| (!(mp
->mnt_kern_flag
& MNTK_VIRTUALDEV
) && (mp
->mnt_flag
& MNT_LOCAL
))) {
2320 vnode_async_list_add_locked(vnode_t vp
)
2322 if (VONLIST(vp
) || (vp
->v_lflag
& (VL_TERMINATE
| VL_DEAD
))) {
2323 panic("vnode_async_list_add: %p is in wrong state", vp
);
2326 TAILQ_INSERT_HEAD(&vnode_async_work_list
, vp
, v_freelist
);
2327 vp
->v_listflag
|= VLIST_ASYNC_WORK
;
2329 async_work_vnodes
++;
2333 vnode_async_list_add(vnode_t vp
)
2337 vnode_async_list_add_locked(vp
);
2339 vnode_list_unlock();
2341 wakeup(&vnode_async_work_list
);
2346 * put the vnode on appropriate free list.
2347 * called with vnode LOCKED
2350 vnode_list_add(vnode_t vp
)
2352 boolean_t need_dead_wakeup
= FALSE
;
2355 lck_mtx_assert(&vp
->v_lock
, LCK_MTX_ASSERT_OWNED
);
2361 * if it is already on a list or non zero references return
2363 if (VONLIST(vp
) || (vp
->v_usecount
!= 0) || (vp
->v_iocount
!= 0) || (vp
->v_lflag
& VL_TERMINATE
)) {
2368 * In vclean, we might have deferred ditching locked buffers
2369 * because something was still referencing them (indicated by
2370 * usecount). We can ditch them now.
2372 if (ISSET(vp
->v_lflag
, VL_DEAD
)
2373 && (!LIST_EMPTY(&vp
->v_cleanblkhd
) || !LIST_EMPTY(&vp
->v_dirtyblkhd
))) {
2374 ++vp
->v_iocount
; // Probably not necessary, but harmless
2379 buf_invalidateblks(vp
, BUF_INVALIDATE_LOCKED
, 0, 0);
2381 vnode_dropiocount(vp
);
2387 if ((vp
->v_flag
& VRAGE
) && !(vp
->v_lflag
& VL_DEAD
)) {
2389 * add the new guy to the appropriate end of the RAGE list
2391 if ((vp
->v_flag
& VAGE
)) {
2392 TAILQ_INSERT_HEAD(&vnode_rage_list
, vp
, v_freelist
);
2394 TAILQ_INSERT_TAIL(&vnode_rage_list
, vp
, v_freelist
);
2397 vp
->v_listflag
|= VLIST_RAGE
;
2401 * reset the timestamp for the last inserted vp on the RAGE
2402 * queue to let new_vnode know that its not ok to start stealing
2403 * from this list... as long as we're actively adding to this list
2404 * we'll push out the vnodes we want to donate to the real free list
2405 * once we stop pushing, we'll let some time elapse before we start
2406 * stealing them in the new_vnode routine
2408 microuptime(&rage_tv
);
2411 * if VL_DEAD, insert it at head of the dead list
2412 * else insert at tail of LRU list or at head if VAGE is set
2414 if ((vp
->v_lflag
& VL_DEAD
)) {
2415 TAILQ_INSERT_HEAD(&vnode_dead_list
, vp
, v_freelist
);
2416 vp
->v_listflag
|= VLIST_DEAD
;
2419 if (dead_vnode_wanted
) {
2420 dead_vnode_wanted
--;
2421 need_dead_wakeup
= TRUE
;
2423 } else if ((vp
->v_flag
& VAGE
)) {
2424 TAILQ_INSERT_HEAD(&vnode_free_list
, vp
, v_freelist
);
2425 vp
->v_flag
&= ~VAGE
;
2428 TAILQ_INSERT_TAIL(&vnode_free_list
, vp
, v_freelist
);
2432 vnode_list_unlock();
2434 if (need_dead_wakeup
== TRUE
) {
2435 wakeup_one((caddr_t
)&dead_vnode_wanted
);
2441 * remove the vnode from appropriate free list.
2442 * called with vnode LOCKED and
2443 * the list lock held
2446 vnode_list_remove_locked(vnode_t vp
)
2450 * the v_listflag field is
2451 * protected by the vnode_list_lock
2453 if (vp
->v_listflag
& VLIST_RAGE
) {
2454 VREMRAGE("vnode_list_remove", vp
);
2455 } else if (vp
->v_listflag
& VLIST_DEAD
) {
2456 VREMDEAD("vnode_list_remove", vp
);
2457 } else if (vp
->v_listflag
& VLIST_ASYNC_WORK
) {
2458 VREMASYNC_WORK("vnode_list_remove", vp
);
2460 VREMFREE("vnode_list_remove", vp
);
2467 * remove the vnode from appropriate free list.
2468 * called with vnode LOCKED
2471 vnode_list_remove(vnode_t vp
)
2474 lck_mtx_assert(&vp
->v_lock
, LCK_MTX_ASSERT_OWNED
);
2477 * we want to avoid taking the list lock
2478 * in the case where we're not on the free
2479 * list... this will be true for most
2480 * directories and any currently in use files
2482 * we're guaranteed that we can't go from
2483 * the not-on-list state to the on-list
2484 * state since we hold the vnode lock...
2485 * all calls to vnode_list_add are done
2486 * under the vnode lock... so we can
2487 * check for that condition (the prevelant one)
2488 * without taking the list lock
2493 * however, we're not guaranteed that
2494 * we won't go from the on-list state
2495 * to the not-on-list state until we
2496 * hold the vnode_list_lock... this
2497 * is due to "new_vnode" removing vnodes
2498 * from the free list uder the list_lock
2499 * w/o the vnode lock... so we need to
2500 * check again whether we're currently
2503 vnode_list_remove_locked(vp
);
2505 vnode_list_unlock();
2511 vnode_rele(vnode_t vp
)
2513 vnode_rele_internal(vp
, 0, 0, 0);
2518 vnode_rele_ext(vnode_t vp
, int fmode
, int dont_reenter
)
2520 vnode_rele_internal(vp
, fmode
, dont_reenter
, 0);
2525 vnode_rele_internal(vnode_t vp
, int fmode
, int dont_reenter
, int locked
)
2527 int32_t old_usecount
;
2530 vnode_lock_spin(vp
);
2534 lck_mtx_assert(&vp
->v_lock
, LCK_MTX_ASSERT_OWNED
);
2537 /* Enable atomic ops on v_usecount without the vnode lock */
2538 old_usecount
= os_atomic_dec_orig(&vp
->v_usecount
, relaxed
);
2539 if (old_usecount
< 1) {
2541 * Because we allow atomic ops on usecount (in lookup only, under
2542 * specific conditions of already having a usecount) it is
2543 * possible that when the vnode is examined, its usecount is
2544 * different than what will be printed in this panic message.
2546 panic("vnode_rele_ext: vp %p usecount -ve : %d. v_tag = %d, v_type = %d, v_flag = %x.",
2547 vp
, old_usecount
- 1, vp
->v_tag
, vp
->v_type
, vp
->v_flag
);
2550 if (fmode
& FWRITE
) {
2551 if (--vp
->v_writecount
< 0) {
2552 panic("vnode_rele_ext: vp %p writecount -ve : %d. v_tag = %d, v_type = %d, v_flag = %x.", vp
, vp
->v_writecount
, vp
->v_tag
, vp
->v_type
, vp
->v_flag
);
2555 if (fmode
& O_EVTONLY
) {
2556 if (--vp
->v_kusecount
< 0) {
2557 panic("vnode_rele_ext: vp %p kusecount -ve : %d. v_tag = %d, v_type = %d, v_flag = %x.", vp
, vp
->v_kusecount
, vp
->v_tag
, vp
->v_type
, vp
->v_flag
);
2560 if (vp
->v_kusecount
> vp
->v_usecount
) {
2561 panic("vnode_rele_ext: vp %p kusecount(%d) out of balance with usecount(%d). v_tag = %d, v_type = %d, v_flag = %x.", vp
, vp
->v_kusecount
, vp
->v_usecount
, vp
->v_tag
, vp
->v_type
, vp
->v_flag
);
2564 if ((vp
->v_iocount
> 0) || (vp
->v_usecount
> 0)) {
2566 * vnode is still busy... if we're the last
2567 * usecount, mark for a future call to VNOP_INACTIVE
2568 * when the iocount finally drops to 0
2570 if (vp
->v_usecount
== 0) {
2571 vp
->v_lflag
|= VL_NEEDINACTIVE
;
2572 vp
->v_flag
&= ~(VNOCACHE_DATA
| VRAOFF
| VOPENEVT
);
2576 vp
->v_flag
&= ~(VNOCACHE_DATA
| VRAOFF
| VOPENEVT
);
2578 if (ISSET(vp
->v_lflag
, VL_TERMINATE
| VL_DEAD
) || dont_reenter
) {
2580 * vnode is being cleaned, or
2581 * we've requested that we don't reenter
2582 * the filesystem on this release...in
2583 * the latter case, we'll mark the vnode aged
2586 if (!(vp
->v_lflag
& (VL_TERMINATE
| VL_DEAD
| VL_MARKTERM
))) {
2587 vp
->v_lflag
|= VL_NEEDINACTIVE
;
2589 if (vnode_on_reliable_media(vp
) == FALSE
|| vp
->v_flag
& VISDIRTY
) {
2590 vnode_async_list_add(vp
);
2601 * at this point both the iocount and usecount
2603 * pick up an iocount so that we can call
2604 * VNOP_INACTIVE with the vnode lock unheld
2610 vp
->v_lflag
&= ~VL_NEEDINACTIVE
;
2613 VNOP_INACTIVE(vp
, vfs_context_current());
2615 vnode_lock_spin(vp
);
2617 * because we dropped the vnode lock to call VNOP_INACTIVE
2618 * the state of the vnode may have changed... we may have
2619 * picked up an iocount, usecount or the MARKTERM may have
2620 * been set... we need to reevaluate the reference counts
2621 * to determine if we can call vnode_reclaim_internal at
2622 * this point... if the reference counts are up, we'll pick
2623 * up the MARKTERM state when they get subsequently dropped
2625 if ((vp
->v_iocount
== 1) && (vp
->v_usecount
== 0) &&
2626 ((vp
->v_lflag
& (VL_MARKTERM
| VL_TERMINATE
| VL_DEAD
)) == VL_MARKTERM
)) {
2629 ut
= get_bsdthread_info(current_thread());
2631 if (ut
->uu_defer_reclaims
) {
2632 vp
->v_defer_reclaimlist
= ut
->uu_vreclaims
;
2633 ut
->uu_vreclaims
= vp
;
2636 vnode_lock_convert(vp
);
2637 vnode_reclaim_internal(vp
, 1, 1, 0);
2639 vnode_dropiocount(vp
);
2642 if (vp
->v_usecount
== 0 && vp
->v_type
== VREG
&& !(vp
->v_flag
& VSYSTEM
)) {
2643 if (vp
->v_ubcinfo
) {
2644 vnode_lock_convert(vp
);
2645 memory_object_mark_unused(vp
->v_ubcinfo
->ui_control
, (vp
->v_flag
& VRAGE
) == VRAGE
);
2655 * Remove any vnodes in the vnode table belonging to mount point mp.
2657 * If MNT_NOFORCE is specified, there should not be any active ones,
2658 * return error if any are found (nb: this is a user error, not a
2659 * system error). If MNT_FORCE is specified, detach any active vnodes
2664 vflush(struct mount
*mp
, struct vnode
*skipvp
, int flags
)
2671 bool first_try
= true;
2674 * See comments in vnode_iterate() for the rationale for this lock
2676 mount_iterate_lock(mp
);
2679 vnode_iterate_setup(mp
);
2681 * On regular unmounts(not forced) do a
2682 * quick check for vnodes to be in use. This
2683 * preserves the caching of vnodes. automounter
2684 * tries unmounting every so often to see whether
2685 * it is still busy or not.
2687 if (((flags
& FORCECLOSE
) == 0) && ((mp
->mnt_kern_flag
& MNTK_UNMOUNT_PREFLIGHT
) != 0)) {
2688 if (vnode_umount_preflight(mp
, skipvp
, flags
)) {
2689 vnode_iterate_clear(mp
);
2691 mount_iterate_unlock(mp
);
2696 /* If it returns 0 then there is nothing to do */
2697 retval
= vnode_iterate_prepare(mp
);
2700 vnode_iterate_clear(mp
);
2702 mount_iterate_unlock(mp
);
2706 /* iterate over all the vnodes */
2707 while (!TAILQ_EMPTY(&mp
->mnt_workerqueue
)) {
2708 vp
= TAILQ_FIRST(&mp
->mnt_workerqueue
);
2709 TAILQ_REMOVE(&mp
->mnt_workerqueue
, vp
, v_mntvnodes
);
2710 TAILQ_INSERT_TAIL(&mp
->mnt_vnodelist
, vp
, v_mntvnodes
);
2712 if ((vp
->v_mount
!= mp
) || (vp
== skipvp
)) {
2718 vnode_lock_spin(vp
);
2720 // If vnode is already terminating, wait for it...
2721 while (vp
->v_id
== vid
&& ISSET(vp
->v_lflag
, VL_TERMINATE
)) {
2722 vp
->v_lflag
|= VL_TERMWANT
;
2723 msleep(&vp
->v_lflag
, &vp
->v_lock
, PVFS
, "vflush", NULL
);
2726 if ((vp
->v_id
!= vid
) || ISSET(vp
->v_lflag
, VL_DEAD
)) {
2733 * If requested, skip over vnodes marked VSYSTEM.
2734 * Skip over all vnodes marked VNOFLUSH.
2736 if ((flags
& SKIPSYSTEM
) && ((vp
->v_flag
& VSYSTEM
) ||
2737 (vp
->v_flag
& VNOFLUSH
))) {
2743 * If requested, skip over vnodes marked VSWAP.
2745 if ((flags
& SKIPSWAP
) && (vp
->v_flag
& VSWAP
)) {
2751 * If requested, skip over vnodes marked VROOT.
2753 if ((flags
& SKIPROOT
) && (vp
->v_flag
& VROOT
)) {
2759 * If WRITECLOSE is set, only flush out regular file
2760 * vnodes open for writing.
2762 if ((flags
& WRITECLOSE
) &&
2763 (vp
->v_writecount
== 0 || vp
->v_type
!= VREG
)) {
2769 * If the real usecount is 0, all we need to do is clear
2770 * out the vnode data structures and we are done.
2772 if (((vp
->v_usecount
== 0) ||
2773 ((vp
->v_usecount
- vp
->v_kusecount
) == 0))) {
2774 vnode_lock_convert(vp
);
2775 vp
->v_iocount
++; /* so that drain waits for * other iocounts */
2779 vnode_reclaim_internal(vp
, 1, 1, 0);
2780 vnode_dropiocount(vp
);
2789 * If FORCECLOSE is set, forcibly close the vnode.
2790 * For block or character devices, revert to an
2791 * anonymous device. For all other files, just kill them.
2793 if (flags
& FORCECLOSE
) {
2794 vnode_lock_convert(vp
);
2796 if (vp
->v_type
!= VBLK
&& vp
->v_type
!= VCHR
) {
2797 vp
->v_iocount
++; /* so that drain waits * for other iocounts */
2801 vnode_abort_advlocks(vp
);
2802 vnode_reclaim_internal(vp
, 1, 1, 0);
2803 vnode_dropiocount(vp
);
2808 vp
->v_lflag
&= ~VL_DEAD
;
2809 vp
->v_op
= spec_vnodeop_p
;
2810 vp
->v_flag
|= VDEVFLUSH
;
2817 /* log vnodes blocking unforced unmounts */
2818 if (print_busy_vnodes
&& first_try
&& ((flags
& FORCECLOSE
) == 0)) {
2819 vprint("vflush - busy vnode", vp
);
2827 /* At this point the worker queue is completed */
2828 if (busy
&& ((flags
& FORCECLOSE
) == 0) && reclaimed
) {
2831 (void)vnode_iterate_reloadq(mp
);
2833 /* returned with mount lock held */
2837 /* if new vnodes were created in between retry the reclaim */
2838 if (vnode_iterate_reloadq(mp
) != 0) {
2839 if (!(busy
&& ((flags
& FORCECLOSE
) == 0))) {
2844 vnode_iterate_clear(mp
);
2846 mount_iterate_unlock(mp
);
2848 if (busy
&& ((flags
& FORCECLOSE
) == 0)) {
2854 long num_recycledvnodes
= 0;
2856 * Disassociate the underlying file system from a vnode.
2857 * The vnode lock is held on entry.
2860 vclean(vnode_t vp
, int flags
)
2862 vfs_context_t ctx
= vfs_context_current();
2865 int already_terminating
;
2872 * Check to see if the vnode is in use.
2873 * If so we have to reference it before we clean it out
2874 * so that its count cannot fall to zero and generate a
2875 * race against ourselves to recycle it.
2877 active
= vp
->v_usecount
;
2880 * just in case we missed sending a needed
2881 * VNOP_INACTIVE, we'll do it now
2883 need_inactive
= (vp
->v_lflag
& VL_NEEDINACTIVE
);
2885 vp
->v_lflag
&= ~VL_NEEDINACTIVE
;
2888 * Prevent the vnode from being recycled or
2889 * brought into use while we clean it out.
2891 already_terminating
= (vp
->v_lflag
& VL_TERMINATE
);
2893 vp
->v_lflag
|= VL_TERMINATE
;
2896 is_namedstream
= vnode_isnamedstream(vp
);
2901 OSAddAtomicLong(1, &num_recycledvnodes
);
2903 if (flags
& DOCLOSE
) {
2904 clflags
|= IO_NDELAY
;
2906 if (flags
& REVOKEALL
) {
2907 clflags
|= IO_REVOKE
;
2913 * It is possible for bdevvp vnodes to not have a mount
2914 * pointer. It's fine to let it get reclaimed without
2917 mac_vnode_notify_reclaim(vp
);
2921 if (active
&& (flags
& DOCLOSE
)) {
2922 VNOP_CLOSE(vp
, clflags
, ctx
);
2926 * Clean out any buffers associated with the vnode.
2928 if (flags
& DOCLOSE
) {
2929 #if CONFIG_NFS_CLIENT
2930 if (vp
->v_tag
== VT_NFS
) {
2931 nfs_vinvalbuf(vp
, V_SAVE
, ctx
, 0);
2933 #endif /* CONFIG_NFS_CLIENT */
2935 VNOP_FSYNC(vp
, MNT_WAIT
, ctx
);
2938 * If the vnode is still in use (by the journal for
2939 * example) we don't want to invalidate locked buffers
2940 * here. In that case, either the journal will tidy them
2941 * up, or we will deal with it when the usecount is
2942 * finally released in vnode_rele_internal.
2944 buf_invalidateblks(vp
, BUF_WRITE_DATA
| (active
? 0 : BUF_INVALIDATE_LOCKED
), 0, 0);
2946 if (UBCINFOEXISTS(vp
)) {
2948 * Clean the pages in VM.
2950 (void)ubc_msync(vp
, (off_t
)0, ubc_getsize(vp
), NULL
, UBC_PUSHALL
| UBC_INVALIDATE
| UBC_SYNC
);
2953 if (active
|| need_inactive
) {
2954 VNOP_INACTIVE(vp
, ctx
);
2958 if ((is_namedstream
!= 0) && (vp
->v_parent
!= NULLVP
)) {
2959 vnode_t pvp
= vp
->v_parent
;
2961 /* Delete the shadow stream file before we reclaim its vnode */
2962 if (vnode_isshadow(vp
)) {
2963 vnode_relenamedstream(pvp
, vp
);
2967 * No more streams associated with the parent. We
2968 * have a ref on it, so its identity is stable.
2969 * If the parent is on an opaque volume, then we need to know
2970 * whether it has associated named streams.
2972 if (vfs_authopaque(pvp
->v_mount
)) {
2973 vnode_lock_spin(pvp
);
2974 pvp
->v_lflag
&= ~VL_HASSTREAMS
;
2981 * Destroy ubc named reference
2982 * cluster_release is done on this path
2983 * along with dropping the reference on the ucred
2984 * (and in the case of forced unmount of an mmap-ed file,
2985 * the ubc reference on the vnode is dropped here too).
2987 ubc_destroy_named(vp
);
2991 * cleanup trigger info from vnode (if any)
2993 if (vp
->v_resolve
) {
2994 vnode_resolver_detach(vp
);
2998 #if CONFIG_IO_COMPRESSION_STATS
2999 if ((vp
->io_compression_stats
)) {
3000 vnode_iocs_record_and_free(vp
);
3002 #endif /* CONFIG_IO_COMPRESSION_STATS */
3005 * Reclaim the vnode.
3007 if (VNOP_RECLAIM(vp
, ctx
)) {
3008 panic("vclean: cannot reclaim");
3011 // make sure the name & parent ptrs get cleaned out!
3012 vnode_update_identity(vp
, NULLVP
, NULL
, 0, 0, VNODE_UPDATE_PARENT
| VNODE_UPDATE_NAME
| VNODE_UPDATE_PURGE
| VNODE_UPDATE_PURGEFIRMLINK
);
3017 * Remove the vnode from any mount list it might be on. It is not
3018 * safe to do this any earlier because unmount needs to wait for
3019 * any vnodes to terminate and it cannot do that if it cannot find
3022 insmntque(vp
, (struct mount
*)0);
3024 vp
->v_mount
= dead_mountp
;
3025 vp
->v_op
= dead_vnodeop_p
;
3029 vp
->v_lflag
|= VL_DEAD
;
3030 vp
->v_flag
&= ~VISDIRTY
;
3032 if (already_terminating
== 0) {
3033 vp
->v_lflag
&= ~VL_TERMINATE
;
3035 * Done with purge, notify sleepers of the grim news.
3037 if (vp
->v_lflag
& VL_TERMWANT
) {
3038 vp
->v_lflag
&= ~VL_TERMWANT
;
3039 wakeup(&vp
->v_lflag
);
3045 * Eliminate all activity associated with the requested vnode
3046 * and with all vnodes aliased to the requested vnode.
3050 vn_revoke(vnode_t vp
, int flags
, __unused vfs_context_t a_context
)
3052 vn_revoke(vnode_t vp
, __unused
int flags
, __unused vfs_context_t a_context
)
3059 if ((flags
& REVOKEALL
) == 0) {
3060 panic("vnop_revoke");
3064 if (vnode_isaliased(vp
)) {
3066 * If a vgone (or vclean) is already in progress,
3067 * return an immediate error
3069 if (vp
->v_lflag
& VL_TERMINATE
) {
3074 * Ensure that vp will not be vgone'd while we
3075 * are eliminating its aliases.
3078 while ((vp
->v_specflags
& SI_ALIASED
)) {
3079 for (vq
= *vp
->v_hashchain
; vq
; vq
= vq
->v_specnext
) {
3080 if (vq
->v_rdev
!= vp
->v_rdev
||
3081 vq
->v_type
!= vp
->v_type
|| vp
== vq
) {
3086 if (vnode_getwithvid(vq
, vid
)) {
3091 if (!(vq
->v_lflag
& VL_TERMINATE
)) {
3092 vnode_reclaim_internal(vq
, 1, 1, 0);
3094 vnode_put_locked(vq
);
3103 if (vp
->v_lflag
& VL_TERMINATE
) {
3107 vnode_reclaim_internal(vp
, 1, 0, REVOKEALL
);
3114 * Recycle an unused vnode to the front of the free list.
3115 * Release the passed interlock if the vnode will be recycled.
3118 vnode_recycle(struct vnode
*vp
)
3120 vnode_lock_spin(vp
);
3122 if (vp
->v_iocount
|| vp
->v_usecount
) {
3123 vp
->v_lflag
|= VL_MARKTERM
;
3127 vnode_lock_convert(vp
);
3128 vnode_reclaim_internal(vp
, 1, 0, 0);
3136 vnode_reload(vnode_t vp
)
3138 vnode_lock_spin(vp
);
3140 if ((vp
->v_iocount
> 1) || vp
->v_usecount
) {
3144 if (vp
->v_iocount
<= 0) {
3145 panic("vnode_reload with no iocount %d", vp
->v_iocount
);
3148 /* mark for release when iocount is dopped */
3149 vp
->v_lflag
|= VL_MARKTERM
;
3157 vgone(vnode_t vp
, int flags
)
3163 * Clean out the filesystem specific data.
3164 * vclean also takes care of removing the
3165 * vnode from any mount list it might be on
3167 vclean(vp
, flags
| DOCLOSE
);
3170 * If special device, remove it from special device alias list
3173 if ((vp
->v_type
== VBLK
|| vp
->v_type
== VCHR
) && vp
->v_specinfo
!= 0) {
3175 if (*vp
->v_hashchain
== vp
) {
3176 *vp
->v_hashchain
= vp
->v_specnext
;
3178 for (vq
= *vp
->v_hashchain
; vq
; vq
= vq
->v_specnext
) {
3179 if (vq
->v_specnext
!= vp
) {
3182 vq
->v_specnext
= vp
->v_specnext
;
3186 panic("missing bdev");
3189 if (vp
->v_specflags
& SI_ALIASED
) {
3191 for (vq
= *vp
->v_hashchain
; vq
; vq
= vq
->v_specnext
) {
3192 if (vq
->v_rdev
!= vp
->v_rdev
||
3193 vq
->v_type
!= vp
->v_type
) {
3202 panic("missing alias");
3205 vx
->v_specflags
&= ~SI_ALIASED
;
3207 vp
->v_specflags
&= ~SI_ALIASED
;
3211 struct specinfo
*tmp
= vp
->v_specinfo
;
3212 vp
->v_specinfo
= NULL
;
3213 zfree(specinfo_zone
, tmp
);
3219 * Lookup a vnode by device number.
3222 check_mountedon(dev_t dev
, enum vtype type
, int *errorp
)
3230 for (vp
= speclisth
[SPECHASH(dev
)]; vp
; vp
= vp
->v_specnext
) {
3231 if (dev
!= vp
->v_rdev
|| type
!= vp
->v_type
) {
3236 if (vnode_getwithvid(vp
, vid
)) {
3239 vnode_lock_spin(vp
);
3240 if ((vp
->v_usecount
> 0) || (vp
->v_iocount
> 1)) {
3242 if ((*errorp
= vfs_mountedon(vp
)) != 0) {
3256 * Calculate the total number of references to a special device.
3265 if (!vnode_isspec(vp
)) {
3266 return vp
->v_usecount
- vp
->v_kusecount
;
3270 if (!vnode_isaliased(vp
)) {
3271 return vp
->v_specinfo
->si_opencount
;
3277 * Grab first vnode and its vid.
3279 vq
= *vp
->v_hashchain
;
3280 vid
= vq
? vq
->v_id
: 0;
3286 * Attempt to get the vnode outside the SPECHASH lock.
3288 if (vnode_getwithvid(vq
, vid
)) {
3293 if (vq
->v_rdev
== vp
->v_rdev
&& vq
->v_type
== vp
->v_type
) {
3294 if ((vq
->v_usecount
== 0) && (vq
->v_iocount
== 1) && vq
!= vp
) {
3296 * Alias, but not in use, so flush it out.
3298 vnode_reclaim_internal(vq
, 1, 1, 0);
3299 vnode_put_locked(vq
);
3303 count
+= vq
->v_specinfo
->si_opencount
;
3309 * must do this with the reference still held on 'vq'
3310 * so that it can't be destroyed while we're poking
3311 * through v_specnext
3313 vnext
= vq
->v_specnext
;
3314 vid
= vnext
? vnext
->v_id
: 0;
3326 int prtactive
= 0; /* 1 => print out reclaim of active vnodes */
3329 * Print out a description of a vnode.
3331 static const char *typename
[] =
3332 { "VNON", "VREG", "VDIR", "VBLK", "VCHR", "VLNK", "VSOCK", "VFIFO", "VBAD" };
3335 vprint(const char *label
, struct vnode
*vp
)
3339 if (label
!= NULL
) {
3340 printf("%s: ", label
);
3342 printf("name %s type %s, usecount %d, writecount %d\n",
3343 vp
->v_name
, typename
[vp
->v_type
],
3344 vp
->v_usecount
, vp
->v_writecount
);
3346 if (vp
->v_flag
& VROOT
) {
3347 strlcat(sbuf
, "|VROOT", sizeof(sbuf
));
3349 if (vp
->v_flag
& VTEXT
) {
3350 strlcat(sbuf
, "|VTEXT", sizeof(sbuf
));
3352 if (vp
->v_flag
& VSYSTEM
) {
3353 strlcat(sbuf
, "|VSYSTEM", sizeof(sbuf
));
3355 if (vp
->v_flag
& VNOFLUSH
) {
3356 strlcat(sbuf
, "|VNOFLUSH", sizeof(sbuf
));
3358 if (vp
->v_flag
& VBWAIT
) {
3359 strlcat(sbuf
, "|VBWAIT", sizeof(sbuf
));
3361 if (vnode_isaliased(vp
)) {
3362 strlcat(sbuf
, "|VALIASED", sizeof(sbuf
));
3364 if (sbuf
[0] != '\0') {
3365 printf("vnode flags (%s\n", &sbuf
[1]);
3371 vn_getpath(struct vnode
*vp
, char *pathbuf
, int *len
)
3373 return build_path(vp
, pathbuf
, *len
, len
, BUILDPATH_NO_FS_ENTER
, vfs_context_current());
3377 vn_getpath_fsenter(struct vnode
*vp
, char *pathbuf
, int *len
)
3379 return build_path(vp
, pathbuf
, *len
, len
, 0, vfs_context_current());
3383 * vn_getpath_fsenter_with_parent will reenter the file system to fine the path of the
3384 * vnode. It requires that there are IO counts on both the vnode and the directory vnode.
3386 * vn_getpath_fsenter is called by MAC hooks to authorize operations for every thing, but
3387 * unlink, rmdir and rename. For these operation the MAC hook calls vn_getpath. This presents
3388 * problems where if the path can not be found from the name cache, those operations can
3389 * erroneously fail with EPERM even though the call should succeed. When removing or moving
3390 * file system objects with operations such as unlink or rename, those operations need to
3391 * take IO counts on the target and containing directory. Calling vn_getpath_fsenter from a
3392 * MAC hook from these operations during forced unmount operations can lead to dead
3393 * lock. This happens when the operation starts, IO counts are taken on the containing
3394 * directories and targets. Before the MAC hook is called a forced unmount from another
3395 * thread takes place and blocks on the on going operation's directory vnode in vdrain.
3396 * After which, the MAC hook gets called and calls vn_getpath_fsenter. vn_getpath_fsenter
3397 * is called with the understanding that there is an IO count on the target. If in
3398 * build_path the directory vnode is no longer in the cache, then the parent object id via
3399 * vnode_getattr from the target is obtain and used to call VFS_VGET to get the parent
3400 * vnode. The file system's VFS_VGET then looks up by inode in its hash and tries to get
3401 * an IO count. But VFS_VGET "sees" the directory vnode is in vdrain and can block
3402 * depending on which version and how it calls the vnode_get family of interfaces.
3404 * N.B. A reasonable interface to use is vnode_getwithvid. This interface was modified to
3405 * call vnode_getiocount with VNODE_DRAINO, so it will happily get an IO count and not
3406 * cause issues, but there is no guarantee that all or any file systems are doing that.
3408 * vn_getpath_fsenter_with_parent can enter the file system safely since there is a known
3409 * IO count on the directory vnode by calling build_path_with_parent.
3413 vn_getpath_fsenter_with_parent(struct vnode
*dvp
, struct vnode
*vp
, char *pathbuf
, int *len
)
3415 return build_path_with_parent(vp
, dvp
, pathbuf
, *len
, len
, NULL
, 0, vfs_context_current());
3419 vn_getpath_ext(struct vnode
*vp
, struct vnode
*dvp
, char *pathbuf
, int *len
, int flags
)
3421 int bpflags
= (flags
& VN_GETPATH_FSENTER
) ? 0 : BUILDPATH_NO_FS_ENTER
;
3423 if (flags
&& (flags
!= VN_GETPATH_FSENTER
)) {
3424 if (flags
& VN_GETPATH_NO_FIRMLINK
) {
3425 bpflags
|= BUILDPATH_NO_FIRMLINK
;;
3427 if (flags
& VN_GETPATH_VOLUME_RELATIVE
) {
3428 bpflags
|= (BUILDPATH_VOLUME_RELATIVE
| BUILDPATH_NO_FIRMLINK
);
3430 if (flags
& VN_GETPATH_NO_PROCROOT
) {
3431 bpflags
|= BUILDPATH_NO_PROCROOT
;
3435 return build_path_with_parent(vp
, dvp
, pathbuf
, *len
, len
, NULL
, bpflags
, vfs_context_current());
3439 vn_getpath_no_firmlink(struct vnode
*vp
, char *pathbuf
, int *len
)
3441 return vn_getpath_ext(vp
, NULLVP
, pathbuf
, len
, VN_GETPATH_NO_FIRMLINK
);
3445 vn_getpath_ext_with_mntlen(struct vnode
*vp
, struct vnode
*dvp
, char *pathbuf
, size_t *len
, size_t *mntlen
, int flags
)
3447 int bpflags
= (flags
& VN_GETPATH_FSENTER
) ? 0 : BUILDPATH_NO_FS_ENTER
;
3451 if (*len
> INT_MAX
) {
3457 if (flags
&& (flags
!= VN_GETPATH_FSENTER
)) {
3458 if (flags
& VN_GETPATH_NO_FIRMLINK
) {
3459 bpflags
|= BUILDPATH_NO_FIRMLINK
;;
3461 if (flags
& VN_GETPATH_VOLUME_RELATIVE
) {
3462 bpflags
|= (BUILDPATH_VOLUME_RELATIVE
| BUILDPATH_NO_FIRMLINK
);
3464 if (flags
& VN_GETPATH_NO_PROCROOT
) {
3465 bpflags
|= BUILDPATH_NO_PROCROOT
;
3469 error
= build_path_with_parent(vp
, dvp
, pathbuf
, local_len
, &local_len
, mntlen
, bpflags
, vfs_context_current());
3471 if (local_len
>= 0 && local_len
<= (int)*len
) {
3472 *len
= (size_t)local_len
;
3479 vn_getcdhash(struct vnode
*vp
, off_t offset
, unsigned char *cdhash
)
3481 return ubc_cs_getcdhash(vp
, offset
, cdhash
);
3485 static char *extension_table
= NULL
;
3487 static int max_ext_width
;
3490 extension_cmp(const void *a
, const void *b
)
3492 return (int)(strlen((const char *)a
) - strlen((const char *)b
));
3497 // This is the api LaunchServices uses to inform the kernel
3498 // the list of package extensions to ignore.
3500 // Internally we keep the list sorted by the length of the
3501 // the extension (from longest to shortest). We sort the
3502 // list of extensions so that we can speed up our searches
3503 // when comparing file names -- we only compare extensions
3504 // that could possibly fit into the file name, not all of
3505 // them (i.e. a short 8 character name can't have an 8
3506 // character extension).
3508 extern lck_mtx_t pkg_extensions_lck
;
3510 __private_extern__
int
3511 set_package_extensions_table(user_addr_t data
, int nentries
, int maxwidth
)
3513 char *new_exts
, *old_exts
;
3514 int old_nentries
= 0, old_maxwidth
= 0;
3517 if (nentries
<= 0 || nentries
> 1024 || maxwidth
<= 0 || maxwidth
> 255) {
3522 // allocate one byte extra so we can guarantee null termination
3523 new_exts
= kheap_alloc(KHEAP_DATA_BUFFERS
, (nentries
* maxwidth
) + 1,
3525 if (new_exts
== NULL
) {
3529 error
= copyin(data
, new_exts
, nentries
* maxwidth
);
3531 kheap_free(KHEAP_DATA_BUFFERS
, new_exts
, (nentries
* maxwidth
) + 1);
3535 new_exts
[(nentries
* maxwidth
)] = '\0'; // guarantee null termination of the block
3537 qsort(new_exts
, nentries
, maxwidth
, extension_cmp
);
3539 lck_mtx_lock(&pkg_extensions_lck
);
3541 old_exts
= extension_table
;
3542 old_nentries
= nexts
;
3543 old_maxwidth
= max_ext_width
;
3544 extension_table
= new_exts
;
3546 max_ext_width
= maxwidth
;
3548 lck_mtx_unlock(&pkg_extensions_lck
);
3550 kheap_free(KHEAP_DATA_BUFFERS
, old_exts
,
3551 (old_nentries
* old_maxwidth
) + 1);
3558 is_package_name(const char *name
, int len
)
3562 const char *ptr
, *name_ext
;
3564 // if the name is less than 3 bytes it can't be of the
3565 // form A.B and if it begins with a "." then it is also
3567 if (len
<= 3 || name
[0] == '.') {
3572 for (ptr
= name
; *ptr
!= '\0'; ptr
++) {
3578 // if there is no "." extension, it can't match
3579 if (name_ext
== NULL
) {
3583 // advance over the "."
3586 lck_mtx_lock(&pkg_extensions_lck
);
3588 // now iterate over all the extensions to see if any match
3589 ptr
= &extension_table
[0];
3590 for (i
= 0; i
< nexts
; i
++, ptr
+= max_ext_width
) {
3591 extlen
= strlen(ptr
);
3592 if (strncasecmp(name_ext
, ptr
, extlen
) == 0 && name_ext
[extlen
] == '\0') {
3594 lck_mtx_unlock(&pkg_extensions_lck
);
3599 lck_mtx_unlock(&pkg_extensions_lck
);
3601 // if we get here, no extension matched
3606 vn_path_package_check(__unused vnode_t vp
, char *path
, int pathlen
, int *component
)
3621 while (end
< path
+ pathlen
&& *end
!= '\0') {
3622 while (end
< path
+ pathlen
&& *end
== '/' && *end
!= '\0') {
3628 while (end
< path
+ pathlen
&& *end
!= '/' && *end
!= '\0') {
3632 if (end
> path
+ pathlen
) {
3633 // hmm, string wasn't null terminated
3638 if (is_package_name(ptr
, (int)(end
- ptr
))) {
3651 * Determine if a name is inappropriate for a searchfs query.
3652 * This list consists of /System currently.
3656 vn_searchfs_inappropriate_name(const char *name
, int len
)
3658 const char *bad_names
[] = { "System" };
3659 int bad_len
[] = { 6 };
3666 for (i
= 0; i
< (int) (sizeof(bad_names
) / sizeof(bad_names
[0])); i
++) {
3667 if (len
== bad_len
[i
] && strncmp(name
, bad_names
[i
], strlen(bad_names
[i
]) + 1) == 0) {
3672 // if we get here, no name matched
3677 * Top level filesystem related information gathering.
3679 extern unsigned int vfs_nummntops
;
3682 * The VFS_NUMMNTOPS shouldn't be at name[1] since
3683 * is a VFS generic variable. Since we no longer support
3684 * VT_UFS, we reserve its value to support this sysctl node.
3686 * It should have been:
3687 * name[0]: VFS_GENERIC
3688 * name[1]: VFS_NUMMNTOPS
3690 SYSCTL_INT(_vfs
, VFS_NUMMNTOPS
, nummntops
,
3691 CTLFLAG_RD
| CTLFLAG_KERN
| CTLFLAG_LOCKED
,
3692 &vfs_nummntops
, 0, "");
3695 vfs_sysctl(int *name __unused
, u_int namelen __unused
,
3696 user_addr_t oldp __unused
, size_t *oldlenp __unused
,
3697 user_addr_t newp __unused
, size_t newlen __unused
, proc_t p __unused
);
3700 vfs_sysctl(int *name __unused
, u_int namelen __unused
,
3701 user_addr_t oldp __unused
, size_t *oldlenp __unused
,
3702 user_addr_t newp __unused
, size_t newlen __unused
, proc_t p __unused
)
3709 // The following code disallows specific sysctl's that came through
3710 // the direct sysctl interface (vfs_sysctl_node) instead of the newer
3711 // sysctl_vfs_ctlbyfsid() interface. We can not allow these selectors
3712 // through vfs_sysctl_node() because it passes the user's oldp pointer
3713 // directly to the file system which (for these selectors) casts it
3714 // back to a struct sysctl_req and then proceed to use SYSCTL_IN()
3715 // which jumps through an arbitrary function pointer. When called
3716 // through the sysctl_vfs_ctlbyfsid() interface this does not happen
3717 // and so it's safe.
3719 // Unfortunately we have to pull in definitions from AFP and SMB and
3720 // perform explicit name checks on the file system to determine if
3721 // these selectors are being used.
3724 #define AFPFS_VFS_CTL_GETID 0x00020001
3725 #define AFPFS_VFS_CTL_NETCHANGE 0x00020002
3726 #define AFPFS_VFS_CTL_VOLCHANGE 0x00020003
3728 #define SMBFS_SYSCTL_REMOUNT 1
3729 #define SMBFS_SYSCTL_REMOUNT_INFO 2
3730 #define SMBFS_SYSCTL_GET_SERVER_SHARE 3
3734 is_bad_sysctl_name(struct vfstable
*vfsp
, int selector_name
)
3736 switch (selector_name
) {
3739 case VFS_CTL_NOLOCKS
:
3740 case VFS_CTL_NSTATUS
:
3743 case VFS_CTL_SERVERINFO
:
3750 // the more complicated check for some of SMB's special values
3751 if (strcmp(vfsp
->vfc_name
, "smbfs") == 0) {
3752 switch (selector_name
) {
3753 case SMBFS_SYSCTL_REMOUNT
:
3754 case SMBFS_SYSCTL_REMOUNT_INFO
:
3755 case SMBFS_SYSCTL_GET_SERVER_SHARE
:
3758 } else if (strcmp(vfsp
->vfc_name
, "afpfs") == 0) {
3759 switch (selector_name
) {
3760 case AFPFS_VFS_CTL_GETID
:
3761 case AFPFS_VFS_CTL_NETCHANGE
:
3762 case AFPFS_VFS_CTL_VOLCHANGE
:
3768 // If we get here we passed all the checks so the selector is ok
3774 int vfs_sysctl_node SYSCTL_HANDLER_ARGS
3777 struct vfstable
*vfsp
;
3781 fstypenum
= oidp
->oid_number
;
3785 /* all sysctl names at this level should have at least one name slot for the FS */
3787 return EISDIR
; /* overloaded */
3790 for (vfsp
= vfsconf
; vfsp
; vfsp
= vfsp
->vfc_next
) {
3791 if (vfsp
->vfc_typenum
== fstypenum
) {
3792 vfsp
->vfc_refcount
++;
3796 mount_list_unlock();
3802 if (is_bad_sysctl_name(vfsp
, name
[0])) {
3803 printf("vfs: bad selector 0x%.8x for old-style sysctl(). use the sysctl-by-fsid interface instead\n", name
[0]);
3807 error
= (vfsp
->vfc_vfsops
->vfs_sysctl
)(name
, namelen
, req
->oldptr
, &req
->oldlen
, req
->newptr
, req
->newlen
, vfs_context_current());
3810 vfsp
->vfc_refcount
--;
3811 mount_list_unlock();
3817 * Check to see if a filesystem is mounted on a block device.
3820 vfs_mountedon(struct vnode
*vp
)
3826 if (vp
->v_specflags
& SI_MOUNTEDON
) {
3830 if (vp
->v_specflags
& SI_ALIASED
) {
3831 for (vq
= *vp
->v_hashchain
; vq
; vq
= vq
->v_specnext
) {
3832 if (vq
->v_rdev
!= vp
->v_rdev
||
3833 vq
->v_type
!= vp
->v_type
) {
3836 if (vq
->v_specflags
& SI_MOUNTEDON
) {
3847 struct unmount_info
{
3848 int u_errs
; // Total failed unmounts
3849 int u_busy
; // EBUSY failed unmounts
3850 int u_count
; // Total volumes iterated
3851 int u_only_non_system
;
3855 unmount_callback(mount_t mp
, void *arg
)
3859 struct unmount_info
*uip
= arg
;
3863 mntname
= zalloc(ZV_NAMEI
);
3864 strlcpy(mntname
, mp
->mnt_vfsstat
.f_mntonname
, MAXPATHLEN
);
3866 if (uip
->u_only_non_system
3867 && ((mp
->mnt_flag
& MNT_ROOTFS
) || (mp
->mnt_kern_flag
& MNTK_SYSTEM
))) { //MNTK_BACKS_ROOT
3868 printf("unmount(%d) %s skipped\n", uip
->u_only_non_system
, mntname
);
3869 mount_iterdrop(mp
); // VFS_ITERATE_CB_DROPREF
3871 printf("unmount(%d) %s\n", uip
->u_only_non_system
, mntname
);
3874 mount_iterdrop(mp
); // VFS_ITERATE_CB_DROPREF
3875 error
= dounmount(mp
, MNT_FORCE
, 1, vfs_context_current());
3878 printf("Unmount of %s failed (%d)\n", mntname
? mntname
:"?", error
);
3879 if (error
== EBUSY
) {
3885 zfree(ZV_NAMEI
, mntname
);
3888 return VFS_RETURNED
;
3892 * Unmount all filesystems. The list is traversed in reverse order
3893 * of mounting to avoid dependencies.
3894 * Busy mounts are retried.
3896 __private_extern__
void
3897 vfs_unmountall(int only_non_system
)
3899 int mounts
, sec
= 1;
3900 struct unmount_info ui
;
3902 vfs_unmountall_started
= 1;
3903 printf("vfs_unmountall(%ssystem) start\n", only_non_system
? "non" : "");
3906 ui
.u_errs
= ui
.u_busy
= ui
.u_count
= 0;
3907 ui
.u_only_non_system
= only_non_system
;
3908 // avoid vfs_iterate deadlock in dounmount(), use VFS_ITERATE_CB_DROPREF
3909 vfs_iterate(VFS_ITERATE_CB_DROPREF
| VFS_ITERATE_TAIL_FIRST
, unmount_callback
, &ui
);
3910 mounts
= mount_getvfscnt();
3914 if (ui
.u_busy
> 0) { // Busy mounts - wait & retry
3915 tsleep(&nummounts
, PVFS
, "busy mount", sec
* hz
);
3920 printf("Unmounting timed out\n");
3921 } else if (ui
.u_count
< mounts
) {
3922 // If the vfs_iterate missed mounts in progress - wait a bit
3923 tsleep(&nummounts
, PVFS
, "missed mount", 2 * hz
);
3926 printf("vfs_unmountall(%ssystem) end\n", only_non_system
? "non" : "");
3930 * This routine is called from vnode_pager_deallocate out of the VM
3931 * The path to vnode_pager_deallocate can only be initiated by ubc_destroy_named
3932 * on a vnode that has a UBCINFO
3934 __private_extern__
void
3935 vnode_pager_vrele(vnode_t vp
)
3937 struct ubc_info
*uip
;
3939 vnode_lock_spin(vp
);
3941 vp
->v_lflag
&= ~VNAMED_UBC
;
3942 if (vp
->v_usecount
!= 0) {
3944 * At the eleventh hour, just before the ubcinfo is
3945 * destroyed, ensure the ubc-specific v_usecount
3946 * reference has gone. We use v_usecount != 0 as a hint;
3947 * ubc_unmap() does nothing if there's no mapping.
3949 * This case is caused by coming here via forced unmount,
3950 * versus the usual vm_object_deallocate() path.
3951 * In the forced unmount case, ubc_destroy_named()
3952 * releases the pager before memory_object_last_unmap()
3957 vnode_lock_spin(vp
);
3960 uip
= vp
->v_ubcinfo
;
3961 vp
->v_ubcinfo
= UBC_INFO_NULL
;
3965 ubc_info_deallocate(uip
);
3969 #include <sys/disk.h>
3971 u_int32_t rootunit
= (u_int32_t
)-1;
3974 extern int lowpri_throttle_enabled
;
3975 extern int iosched_enabled
;
3979 vfs_init_io_attributes(vnode_t devvp
, mount_t mp
)
3982 off_t readblockcnt
= 0;
3983 off_t writeblockcnt
= 0;
3984 off_t readmaxcnt
= 0;
3985 off_t writemaxcnt
= 0;
3986 off_t readsegcnt
= 0;
3987 off_t writesegcnt
= 0;
3988 off_t readsegsize
= 0;
3989 off_t writesegsize
= 0;
3990 off_t alignment
= 0;
3991 u_int32_t minsaturationbytecount
= 0;
3992 u_int32_t ioqueue_depth
= 0;
3996 u_int64_t location
= 0;
3997 vfs_context_t ctx
= vfs_context_current();
3998 dk_corestorage_info_t cs_info
;
3999 boolean_t cs_present
= FALSE
;;
4004 VNOP_IOCTL(devvp
, DKIOCGETTHROTTLEMASK
, (caddr_t
)&mp
->mnt_throttle_mask
, 0, NULL
);
4006 * as a reasonable approximation, only use the lowest bit of the mask
4007 * to generate a disk unit number
4009 mp
->mnt_devbsdunit
= num_trailing_0(mp
->mnt_throttle_mask
);
4011 if (devvp
== rootvp
) {
4012 rootunit
= mp
->mnt_devbsdunit
;
4015 if (mp
->mnt_devbsdunit
== rootunit
) {
4017 * this mount point exists on the same device as the root
4018 * partition, so it comes under the hard throttle control...
4019 * this is true even for the root mount point itself
4021 mp
->mnt_kern_flag
|= MNTK_ROOTDEV
;
4024 * force the spec device to re-cache
4025 * the underlying block size in case
4026 * the filesystem overrode the initial value
4028 set_fsblocksize(devvp
);
4031 if ((error
= VNOP_IOCTL(devvp
, DKIOCGETBLOCKSIZE
,
4032 (caddr_t
)&blksize
, 0, ctx
))) {
4036 mp
->mnt_devblocksize
= blksize
;
4039 * set the maximum possible I/O size
4040 * this may get clipped to a smaller value
4041 * based on which constraints are being advertised
4042 * and if those advertised constraints result in a smaller
4043 * limit for a given I/O
4045 mp
->mnt_maxreadcnt
= MAX_UPL_SIZE_BYTES
;
4046 mp
->mnt_maxwritecnt
= MAX_UPL_SIZE_BYTES
;
4048 if (VNOP_IOCTL(devvp
, DKIOCISVIRTUAL
, (caddr_t
)&isvirtual
, 0, ctx
) == 0) {
4050 mp
->mnt_kern_flag
|= MNTK_VIRTUALDEV
;
4051 mp
->mnt_flag
|= MNT_REMOVABLE
;
4054 if (VNOP_IOCTL(devvp
, DKIOCISSOLIDSTATE
, (caddr_t
)&isssd
, 0, ctx
) == 0) {
4056 mp
->mnt_kern_flag
|= MNTK_SSD
;
4059 if ((error
= VNOP_IOCTL(devvp
, DKIOCGETFEATURES
,
4060 (caddr_t
)&features
, 0, ctx
))) {
4064 if ((error
= VNOP_IOCTL(devvp
, DKIOCGETMAXBLOCKCOUNTREAD
,
4065 (caddr_t
)&readblockcnt
, 0, ctx
))) {
4069 if ((error
= VNOP_IOCTL(devvp
, DKIOCGETMAXBLOCKCOUNTWRITE
,
4070 (caddr_t
)&writeblockcnt
, 0, ctx
))) {
4074 if ((error
= VNOP_IOCTL(devvp
, DKIOCGETMAXBYTECOUNTREAD
,
4075 (caddr_t
)&readmaxcnt
, 0, ctx
))) {
4079 if ((error
= VNOP_IOCTL(devvp
, DKIOCGETMAXBYTECOUNTWRITE
,
4080 (caddr_t
)&writemaxcnt
, 0, ctx
))) {
4084 if ((error
= VNOP_IOCTL(devvp
, DKIOCGETMAXSEGMENTCOUNTREAD
,
4085 (caddr_t
)&readsegcnt
, 0, ctx
))) {
4089 if ((error
= VNOP_IOCTL(devvp
, DKIOCGETMAXSEGMENTCOUNTWRITE
,
4090 (caddr_t
)&writesegcnt
, 0, ctx
))) {
4094 if ((error
= VNOP_IOCTL(devvp
, DKIOCGETMAXSEGMENTBYTECOUNTREAD
,
4095 (caddr_t
)&readsegsize
, 0, ctx
))) {
4099 if ((error
= VNOP_IOCTL(devvp
, DKIOCGETMAXSEGMENTBYTECOUNTWRITE
,
4100 (caddr_t
)&writesegsize
, 0, ctx
))) {
4104 if ((error
= VNOP_IOCTL(devvp
, DKIOCGETMINSEGMENTALIGNMENTBYTECOUNT
,
4105 (caddr_t
)&alignment
, 0, ctx
))) {
4109 if ((error
= VNOP_IOCTL(devvp
, DKIOCGETCOMMANDPOOLSIZE
,
4110 (caddr_t
)&ioqueue_depth
, 0, ctx
))) {
4115 mp
->mnt_maxreadcnt
= (readmaxcnt
> UINT32_MAX
) ? UINT32_MAX
:(uint32_t) readmaxcnt
;
4119 temp
= readblockcnt
* blksize
;
4120 temp
= (temp
> UINT32_MAX
) ? UINT32_MAX
: temp
;
4122 if (temp
< mp
->mnt_maxreadcnt
) {
4123 mp
->mnt_maxreadcnt
= (u_int32_t
)temp
;
4128 mp
->mnt_maxwritecnt
= (writemaxcnt
> UINT32_MAX
) ? UINT32_MAX
: (uint32_t)writemaxcnt
;
4131 if (writeblockcnt
) {
4132 temp
= writeblockcnt
* blksize
;
4133 temp
= (temp
> UINT32_MAX
) ? UINT32_MAX
: temp
;
4135 if (temp
< mp
->mnt_maxwritecnt
) {
4136 mp
->mnt_maxwritecnt
= (u_int32_t
)temp
;
4141 temp
= (readsegcnt
> UINT16_MAX
) ? UINT16_MAX
: readsegcnt
;
4143 temp
= mp
->mnt_maxreadcnt
/ PAGE_SIZE
;
4145 if (temp
> UINT16_MAX
) {
4149 mp
->mnt_segreadcnt
= (u_int16_t
)temp
;
4152 temp
= (writesegcnt
> UINT16_MAX
) ? UINT16_MAX
: writesegcnt
;
4154 temp
= mp
->mnt_maxwritecnt
/ PAGE_SIZE
;
4156 if (temp
> UINT16_MAX
) {
4160 mp
->mnt_segwritecnt
= (u_int16_t
)temp
;
4163 temp
= (readsegsize
> UINT32_MAX
) ? UINT32_MAX
: readsegsize
;
4165 temp
= mp
->mnt_maxreadcnt
;
4167 mp
->mnt_maxsegreadsize
= (u_int32_t
)temp
;
4170 temp
= (writesegsize
> UINT32_MAX
) ? UINT32_MAX
: writesegsize
;
4172 temp
= mp
->mnt_maxwritecnt
;
4174 mp
->mnt_maxsegwritesize
= (u_int32_t
)temp
;
4177 temp
= (alignment
> PAGE_SIZE
) ? PAGE_MASK
: alignment
- 1;
4181 mp
->mnt_alignmentmask
= (uint32_t)temp
;
4184 if (ioqueue_depth
> MNT_DEFAULT_IOQUEUE_DEPTH
) {
4185 temp
= ioqueue_depth
;
4187 temp
= MNT_DEFAULT_IOQUEUE_DEPTH
;
4190 mp
->mnt_ioqueue_depth
= (uint32_t)temp
;
4191 mp
->mnt_ioscale
= MNT_IOSCALE(mp
->mnt_ioqueue_depth
);
4193 if (mp
->mnt_ioscale
> 1) {
4194 printf("ioqueue_depth = %d, ioscale = %d\n", (int)mp
->mnt_ioqueue_depth
, (int)mp
->mnt_ioscale
);
4197 if (features
& DK_FEATURE_FORCE_UNIT_ACCESS
) {
4198 mp
->mnt_ioflags
|= MNT_IOFLAGS_FUA_SUPPORTED
;
4201 if (VNOP_IOCTL(devvp
, DKIOCGETIOMINSATURATIONBYTECOUNT
, (caddr_t
)&minsaturationbytecount
, 0, ctx
) == 0) {
4202 mp
->mnt_minsaturationbytecount
= minsaturationbytecount
;
4204 mp
->mnt_minsaturationbytecount
= 0;
4207 if (VNOP_IOCTL(devvp
, DKIOCCORESTORAGE
, (caddr_t
)&cs_info
, 0, ctx
) == 0) {
4211 if (features
& DK_FEATURE_UNMAP
) {
4212 mp
->mnt_ioflags
|= MNT_IOFLAGS_UNMAP_SUPPORTED
;
4214 if (cs_present
== TRUE
) {
4215 mp
->mnt_ioflags
|= MNT_IOFLAGS_CSUNMAP_SUPPORTED
;
4218 if (cs_present
== TRUE
) {
4220 * for now we'll use the following test as a proxy for
4221 * the underlying drive being FUSION in nature
4223 if ((cs_info
.flags
& DK_CORESTORAGE_PIN_YOUR_METADATA
)) {
4224 mp
->mnt_ioflags
|= MNT_IOFLAGS_FUSION_DRIVE
;
4227 /* Check for APFS Fusion */
4228 dk_apfs_flavour_t flavour
;
4229 if ((VNOP_IOCTL(devvp
, DKIOCGETAPFSFLAVOUR
, (caddr_t
)&flavour
, 0, ctx
) == 0) &&
4230 (flavour
== DK_APFS_FUSION
)) {
4231 mp
->mnt_ioflags
|= MNT_IOFLAGS_FUSION_DRIVE
;
4235 if (VNOP_IOCTL(devvp
, DKIOCGETLOCATION
, (caddr_t
)&location
, 0, ctx
) == 0) {
4236 if (location
& DK_LOCATION_EXTERNAL
) {
4237 mp
->mnt_ioflags
|= MNT_IOFLAGS_PERIPHERAL_DRIVE
;
4238 mp
->mnt_flag
|= MNT_REMOVABLE
;
4243 if (iosched_enabled
&& (features
& DK_FEATURE_PRIORITY
)) {
4244 mp
->mnt_ioflags
|= MNT_IOFLAGS_IOSCHED_SUPPORTED
;
4245 throttle_info_disable_throttle(mp
->mnt_devbsdunit
, (mp
->mnt_ioflags
& MNT_IOFLAGS_FUSION_DRIVE
) != 0);
4247 #endif /* CONFIG_IOSCHED */
4251 static struct klist fs_klist
;
4252 static LCK_GRP_DECLARE(fs_klist_lck_grp
, "fs_klist");
4253 static LCK_MTX_DECLARE(fs_klist_lock
, &fs_klist_lck_grp
);
4256 vfs_event_init(void)
4258 klist_init(&fs_klist
);
4262 vfs_event_signal(fsid_t
*fsid
, u_int32_t event
, intptr_t data
)
4264 if (event
== VQ_DEAD
|| event
== VQ_NOTRESP
) {
4265 struct mount
*mp
= vfs_getvfs(fsid
);
4267 mount_lock_spin(mp
);
4269 mp
->mnt_kern_flag
&= ~MNT_LNOTRESP
; // Now responding
4271 mp
->mnt_kern_flag
|= MNT_LNOTRESP
; // Not responding
4277 lck_mtx_lock(&fs_klist_lock
);
4278 KNOTE(&fs_klist
, event
);
4279 lck_mtx_unlock(&fs_klist_lock
);
4283 * return the number of mounted filesystems.
4286 sysctl_vfs_getvfscnt(void)
4288 return mount_getvfscnt();
4293 mount_getvfscnt(void)
4299 mount_list_unlock();
4306 mount_fillfsids(fsid_t
*fsidlst
, int count
)
4313 TAILQ_FOREACH(mp
, &mountlist
, mnt_list
) {
4314 if (actual
< count
) {
4315 fsidlst
[actual
] = mp
->mnt_vfsstat
.f_fsid
;
4319 mount_list_unlock();
4324 * fill in the array of fsid_t's up to a max of 'count', the actual
4325 * number filled in will be set in '*actual'. If there are more fsid_t's
4326 * than room in fsidlst then ENOMEM will be returned and '*actual' will
4327 * have the actual count.
4328 * having *actual filled out even in the error case is depended upon.
4331 sysctl_vfs_getvfslist(fsid_t
*fsidlst
, unsigned long count
, unsigned long *actual
)
4337 TAILQ_FOREACH(mp
, &mountlist
, mnt_list
) {
4339 if (*actual
<= count
) {
4340 fsidlst
[(*actual
) - 1] = mp
->mnt_vfsstat
.f_fsid
;
4343 mount_list_unlock();
4344 return *actual
<= count
? 0 : ENOMEM
;
4348 sysctl_vfs_vfslist(__unused
struct sysctl_oid
*oidp
, __unused
void *arg1
,
4349 __unused
int arg2
, struct sysctl_req
*req
)
4351 unsigned long actual
;
4356 /* This is a readonly node. */
4357 if (req
->newptr
!= USER_ADDR_NULL
) {
4361 /* they are querying us so just return the space required. */
4362 if (req
->oldptr
== USER_ADDR_NULL
) {
4363 req
->oldidx
= sysctl_vfs_getvfscnt() * sizeof(fsid_t
);
4368 * Retrieve an accurate count of the amount of space required to copy
4369 * out all the fsids in the system.
4371 space
= req
->oldlen
;
4372 req
->oldlen
= sysctl_vfs_getvfscnt() * sizeof(fsid_t
);
4374 /* they didn't give us enough space. */
4375 if (space
< req
->oldlen
) {
4379 fsidlst
= kheap_alloc(KHEAP_TEMP
, req
->oldlen
, Z_WAITOK
| Z_ZERO
);
4380 if (fsidlst
== NULL
) {
4384 error
= sysctl_vfs_getvfslist(fsidlst
, req
->oldlen
/ sizeof(fsid_t
),
4387 * If we get back ENOMEM, then another mount has been added while we
4388 * slept in malloc above. If this is the case then try again.
4390 if (error
== ENOMEM
) {
4391 kheap_free(KHEAP_TEMP
, fsidlst
, req
->oldlen
);
4392 req
->oldlen
= space
;
4396 error
= SYSCTL_OUT(req
, fsidlst
, actual
* sizeof(fsid_t
));
4398 kheap_free(KHEAP_TEMP
, fsidlst
, req
->oldlen
);
4403 * Do a sysctl by fsid.
4406 sysctl_vfs_ctlbyfsid(__unused
struct sysctl_oid
*oidp
, void *arg1
, int arg2
,
4407 struct sysctl_req
*req
)
4409 union union_vfsidctl vc
;
4411 struct vfsstatfs
*sp
;
4414 int error
= 0, gotref
= 0;
4415 vfs_context_t ctx
= vfs_context_current();
4416 proc_t p
= req
->p
; /* XXX req->p != current_proc()? */
4417 boolean_t is_64_bit
;
4419 struct statfs64 sfs64
;
4420 struct user64_statfs osfs64
;
4421 struct user32_statfs osfs32
;
4424 if (req
->newptr
== USER_ADDR_NULL
) {
4431 is_64_bit
= proc_is64bit(p
);
4433 error
= SYSCTL_IN(req
, &vc
, is_64_bit
? sizeof(vc
.vc64
):sizeof(vc
.vc32
));
4437 if (vc
.vc32
.vc_vers
!= VFS_CTL_VERS1
) { /* works for 32 and 64 */
4441 mp
= mount_list_lookupby_fsid(&vc
.vc32
.vc_fsid
, 0, 1); /* works for 32 and 64 */
4447 /* reset so that the fs specific code can fetch it. */
4450 * Note if this is a VFS_CTL then we pass the actual sysctl req
4451 * in for "oldp" so that the lower layer can DTRT and use the
4452 * SYSCTL_IN/OUT routines.
4454 if (mp
->mnt_op
->vfs_sysctl
!= NULL
) {
4456 if (vfs_64bitready(mp
)) {
4457 error
= mp
->mnt_op
->vfs_sysctl(name
, namelen
,
4458 CAST_USER_ADDR_T(req
),
4459 NULL
, USER_ADDR_NULL
, 0,
4465 error
= mp
->mnt_op
->vfs_sysctl(name
, namelen
,
4466 CAST_USER_ADDR_T(req
),
4467 NULL
, USER_ADDR_NULL
, 0,
4470 if (error
!= ENOTSUP
) {
4475 case VFS_CTL_UMOUNT
:
4477 error
= mac_mount_check_umount(ctx
, mp
);
4484 req
->newptr
= vc
.vc64
.vc_ptr
;
4485 req
->newlen
= (size_t)vc
.vc64
.vc_len
;
4487 req
->newptr
= CAST_USER_ADDR_T(vc
.vc32
.vc_ptr
);
4488 req
->newlen
= vc
.vc32
.vc_len
;
4490 error
= SYSCTL_IN(req
, &flags
, sizeof(flags
));
4498 /* safedounmount consumes a ref */
4499 error
= safedounmount(mp
, flags
, ctx
);
4501 case VFS_CTL_OSTATFS
:
4502 case VFS_CTL_STATFS64
:
4504 error
= mac_mount_check_stat(ctx
, mp
);
4511 req
->newptr
= vc
.vc64
.vc_ptr
;
4512 req
->newlen
= (size_t)vc
.vc64
.vc_len
;
4514 req
->newptr
= CAST_USER_ADDR_T(vc
.vc32
.vc_ptr
);
4515 req
->newlen
= vc
.vc32
.vc_len
;
4517 error
= SYSCTL_IN(req
, &flags
, sizeof(flags
));
4521 sp
= &mp
->mnt_vfsstat
;
4522 if (((flags
& MNT_NOWAIT
) == 0 || (flags
& (MNT_WAIT
| MNT_DWAIT
))) &&
4523 (error
= vfs_update_vfsstat(mp
, ctx
, VFS_USER_EVENT
))) {
4527 sfsbuf
= kheap_alloc(KHEAP_TEMP
, sizeof(*sfsbuf
), Z_WAITOK
);
4529 if (name
[0] == VFS_CTL_STATFS64
) {
4530 struct statfs64
*sfs
= &sfsbuf
->sfs64
;
4532 vfs_get_statfs64(mp
, sfs
);
4533 error
= SYSCTL_OUT(req
, sfs
, sizeof(*sfs
));
4534 } else if (is_64_bit
) {
4535 struct user64_statfs
*sfs
= &sfsbuf
->osfs64
;
4537 bzero(sfs
, sizeof(*sfs
));
4538 sfs
->f_flags
= mp
->mnt_flag
& MNT_VISFLAGMASK
;
4539 sfs
->f_type
= (short)mp
->mnt_vtable
->vfc_typenum
;
4540 sfs
->f_bsize
= (user64_long_t
)sp
->f_bsize
;
4541 sfs
->f_iosize
= (user64_long_t
)sp
->f_iosize
;
4542 sfs
->f_blocks
= (user64_long_t
)sp
->f_blocks
;
4543 sfs
->f_bfree
= (user64_long_t
)sp
->f_bfree
;
4544 sfs
->f_bavail
= (user64_long_t
)sp
->f_bavail
;
4545 sfs
->f_files
= (user64_long_t
)sp
->f_files
;
4546 sfs
->f_ffree
= (user64_long_t
)sp
->f_ffree
;
4547 sfs
->f_fsid
= sp
->f_fsid
;
4548 sfs
->f_owner
= sp
->f_owner
;
4549 #ifdef CONFIG_NFS_CLIENT
4550 if (mp
->mnt_kern_flag
& MNTK_TYPENAME_OVERRIDE
) {
4551 strlcpy(&sfs
->f_fstypename
[0], &mp
->fstypename_override
[0], MFSNAMELEN
);
4553 #endif /* CONFIG_NFS_CLIENT */
4555 strlcpy(sfs
->f_fstypename
, sp
->f_fstypename
, MFSNAMELEN
);
4557 strlcpy(sfs
->f_mntonname
, sp
->f_mntonname
, MNAMELEN
);
4558 strlcpy(sfs
->f_mntfromname
, sp
->f_mntfromname
, MNAMELEN
);
4560 error
= SYSCTL_OUT(req
, sfs
, sizeof(*sfs
));
4562 struct user32_statfs
*sfs
= &sfsbuf
->osfs32
;
4565 bzero(sfs
, sizeof(*sfs
));
4566 sfs
->f_flags
= mp
->mnt_flag
& MNT_VISFLAGMASK
;
4567 sfs
->f_type
= (short)mp
->mnt_vtable
->vfc_typenum
;
4570 * It's possible for there to be more than 2^^31 blocks in the filesystem, so we
4571 * have to fudge the numbers here in that case. We inflate the blocksize in order
4572 * to reflect the filesystem size as best we can.
4574 if (sp
->f_blocks
> INT_MAX
) {
4578 * Work out how far we have to shift the block count down to make it fit.
4579 * Note that it's possible to have to shift so far that the resulting
4580 * blocksize would be unreportably large. At that point, we will clip
4581 * any values that don't fit.
4583 * For safety's sake, we also ensure that f_iosize is never reported as
4584 * being smaller than f_bsize.
4586 for (shift
= 0; shift
< 32; shift
++) {
4587 if ((sp
->f_blocks
>> shift
) <= INT_MAX
) {
4590 if ((((long long)sp
->f_bsize
) << (shift
+ 1)) > INT_MAX
) {
4594 #define __SHIFT_OR_CLIP(x, s) ((((x) >> (s)) > INT_MAX) ? INT_MAX : ((x) >> (s)))
4595 sfs
->f_blocks
= (user32_long_t
)__SHIFT_OR_CLIP(sp
->f_blocks
, shift
);
4596 sfs
->f_bfree
= (user32_long_t
)__SHIFT_OR_CLIP(sp
->f_bfree
, shift
);
4597 sfs
->f_bavail
= (user32_long_t
)__SHIFT_OR_CLIP(sp
->f_bavail
, shift
);
4598 #undef __SHIFT_OR_CLIP
4599 sfs
->f_bsize
= (user32_long_t
)(sp
->f_bsize
<< shift
);
4600 temp
= lmax(sp
->f_iosize
, sp
->f_bsize
);
4601 if (temp
> INT32_MAX
) {
4603 kheap_free(KHEAP_TEMP
, sfsbuf
, sizeof(*sfsbuf
));
4606 sfs
->f_iosize
= (user32_long_t
)temp
;
4608 sfs
->f_bsize
= (user32_long_t
)sp
->f_bsize
;
4609 sfs
->f_iosize
= (user32_long_t
)sp
->f_iosize
;
4610 sfs
->f_blocks
= (user32_long_t
)sp
->f_blocks
;
4611 sfs
->f_bfree
= (user32_long_t
)sp
->f_bfree
;
4612 sfs
->f_bavail
= (user32_long_t
)sp
->f_bavail
;
4614 sfs
->f_files
= (user32_long_t
)sp
->f_files
;
4615 sfs
->f_ffree
= (user32_long_t
)sp
->f_ffree
;
4616 sfs
->f_fsid
= sp
->f_fsid
;
4617 sfs
->f_owner
= sp
->f_owner
;
4619 #ifdef CONFIG_NFS_CLIENT
4620 if (mp
->mnt_kern_flag
& MNTK_TYPENAME_OVERRIDE
) {
4621 strlcpy(&sfs
->f_fstypename
[0], &mp
->fstypename_override
[0], MFSNAMELEN
);
4623 #endif /* CONFIG_NFS_CLIENT */
4625 strlcpy(sfs
->f_fstypename
, sp
->f_fstypename
, MFSNAMELEN
);
4627 strlcpy(sfs
->f_mntonname
, sp
->f_mntonname
, MNAMELEN
);
4628 strlcpy(sfs
->f_mntfromname
, sp
->f_mntfromname
, MNAMELEN
);
4630 error
= SYSCTL_OUT(req
, sfs
, sizeof(*sfs
));
4632 kheap_free(KHEAP_TEMP
, sfsbuf
, sizeof(*sfsbuf
));
4645 static int filt_fsattach(struct knote
*kn
, struct kevent_qos_s
*kev
);
4646 static void filt_fsdetach(struct knote
*kn
);
4647 static int filt_fsevent(struct knote
*kn
, long hint
);
4648 static int filt_fstouch(struct knote
*kn
, struct kevent_qos_s
*kev
);
4649 static int filt_fsprocess(struct knote
*kn
, struct kevent_qos_s
*kev
);
4650 SECURITY_READ_ONLY_EARLY(struct filterops
) fs_filtops
= {
4651 .f_attach
= filt_fsattach
,
4652 .f_detach
= filt_fsdetach
,
4653 .f_event
= filt_fsevent
,
4654 .f_touch
= filt_fstouch
,
4655 .f_process
= filt_fsprocess
,
4659 filt_fsattach(struct knote
*kn
, __unused
struct kevent_qos_s
*kev
)
4661 kn
->kn_flags
|= EV_CLEAR
; /* automatic */
4662 kn
->kn_sdata
= 0; /* incoming data is ignored */
4664 lck_mtx_lock(&fs_klist_lock
);
4665 KNOTE_ATTACH(&fs_klist
, kn
);
4666 lck_mtx_unlock(&fs_klist_lock
);
4669 * filter only sees future events,
4670 * so it can't be fired already.
4676 filt_fsdetach(struct knote
*kn
)
4678 lck_mtx_lock(&fs_klist_lock
);
4679 KNOTE_DETACH(&fs_klist
, kn
);
4680 lck_mtx_unlock(&fs_klist_lock
);
4684 filt_fsevent(struct knote
*kn
, long hint
)
4687 * Backwards compatibility:
4688 * Other filters would do nothing if kn->kn_sfflags == 0
4691 if ((kn
->kn_sfflags
== 0) || (kn
->kn_sfflags
& hint
)) {
4692 kn
->kn_fflags
|= hint
;
4695 return kn
->kn_fflags
!= 0;
4699 filt_fstouch(struct knote
*kn
, struct kevent_qos_s
*kev
)
4703 lck_mtx_lock(&fs_klist_lock
);
4705 kn
->kn_sfflags
= kev
->fflags
;
4708 * the above filter function sets bits even if nobody is looking for them.
4709 * Just preserve those bits even in the new mask is more selective
4712 * For compatibility with previous implementations, we leave kn_fflags
4713 * as they were before.
4715 //if (kn->kn_sfflags)
4716 // kn->kn_fflags &= kn->kn_sfflags;
4717 res
= (kn
->kn_fflags
!= 0);
4719 lck_mtx_unlock(&fs_klist_lock
);
4725 filt_fsprocess(struct knote
*kn
, struct kevent_qos_s
*kev
)
4729 lck_mtx_lock(&fs_klist_lock
);
4730 if (kn
->kn_fflags
) {
4731 knote_fill_kevent(kn
, kev
, 0);
4734 lck_mtx_unlock(&fs_klist_lock
);
4739 sysctl_vfs_noremotehang(__unused
struct sysctl_oid
*oidp
,
4740 __unused
void *arg1
, __unused
int arg2
, struct sysctl_req
*req
)
4746 /* We need a pid. */
4747 if (req
->newptr
== USER_ADDR_NULL
) {
4751 error
= SYSCTL_IN(req
, &pid
, sizeof(pid
));
4756 p
= proc_find(pid
< 0 ? -pid
: pid
);
4762 * Fetching the value is ok, but we only fetch if the old
4765 if (req
->oldptr
!= USER_ADDR_NULL
) {
4766 out
= !((p
->p_flag
& P_NOREMOTEHANG
) == 0);
4768 error
= SYSCTL_OUT(req
, &out
, sizeof(out
));
4772 /* cansignal offers us enough security. */
4773 if (p
!= req
->p
&& proc_suser(req
->p
) != 0) {
4779 OSBitAndAtomic(~((uint32_t)P_NOREMOTEHANG
), &p
->p_flag
);
4781 OSBitOrAtomic(P_NOREMOTEHANG
, &p
->p_flag
);
4789 sysctl_vfs_generic_conf SYSCTL_HANDLER_ARGS
4792 struct vfstable
*vfsp
;
4793 struct vfsconf vfsc
= {};
4801 } else if (namelen
> 1) {
4806 for (vfsp
= vfsconf
; vfsp
; vfsp
= vfsp
->vfc_next
) {
4807 if (vfsp
->vfc_typenum
== name
[0]) {
4813 mount_list_unlock();
4817 vfsc
.vfc_reserved1
= 0;
4818 bcopy(vfsp
->vfc_name
, vfsc
.vfc_name
, sizeof(vfsc
.vfc_name
));
4819 vfsc
.vfc_typenum
= vfsp
->vfc_typenum
;
4820 vfsc
.vfc_refcount
= vfsp
->vfc_refcount
;
4821 vfsc
.vfc_flags
= vfsp
->vfc_flags
;
4822 vfsc
.vfc_reserved2
= 0;
4823 vfsc
.vfc_reserved3
= 0;
4825 mount_list_unlock();
4826 return SYSCTL_OUT(req
, &vfsc
, sizeof(struct vfsconf
));
4829 /* the vfs.generic. branch. */
4830 SYSCTL_EXTENSIBLE_NODE(_vfs
, VFS_GENERIC
, generic
,
4831 CTLFLAG_RW
| CTLFLAG_LOCKED
, NULL
, "vfs generic hinge");
4832 /* retreive a list of mounted filesystem fsid_t */
4833 SYSCTL_PROC(_vfs_generic
, OID_AUTO
, vfsidlist
,
4834 CTLTYPE_STRUCT
| CTLFLAG_RD
| CTLFLAG_LOCKED
,
4835 NULL
, 0, sysctl_vfs_vfslist
, "S,fsid", "List of mounted filesystem ids");
4836 /* perform operations on filesystem via fsid_t */
4837 SYSCTL_NODE(_vfs_generic
, OID_AUTO
, ctlbyfsid
, CTLFLAG_RW
| CTLFLAG_LOCKED
,
4838 sysctl_vfs_ctlbyfsid
, "ctlbyfsid");
4839 SYSCTL_PROC(_vfs_generic
, OID_AUTO
, noremotehang
, CTLFLAG_RW
| CTLFLAG_ANYBODY
,
4840 NULL
, 0, sysctl_vfs_noremotehang
, "I", "noremotehang");
4841 SYSCTL_INT(_vfs_generic
, VFS_MAXTYPENUM
, maxtypenum
,
4842 CTLFLAG_RD
| CTLFLAG_KERN
| CTLFLAG_LOCKED
,
4843 &maxvfstypenum
, 0, "");
4844 SYSCTL_INT(_vfs_generic
, OID_AUTO
, sync_timeout
, CTLFLAG_RW
| CTLFLAG_LOCKED
, &sync_timeout_seconds
, 0, "");
4845 SYSCTL_NODE(_vfs_generic
, VFS_CONF
, conf
,
4846 CTLFLAG_RD
| CTLFLAG_LOCKED
,
4847 sysctl_vfs_generic_conf
, "");
4848 #if DEVELOPMENT || DEBUG
4849 SYSCTL_INT(_vfs_generic
, OID_AUTO
, print_busy_vnodes
,
4850 CTLTYPE_INT
| CTLFLAG_RW
,
4851 &print_busy_vnodes
, 0,
4852 "VFS log busy vnodes blocking unmount");
4855 /* Indicate that the root file system unmounted cleanly */
4856 static int vfs_root_unmounted_cleanly
= 0;
4857 SYSCTL_INT(_vfs_generic
, OID_AUTO
, root_unmounted_cleanly
, CTLFLAG_RD
, &vfs_root_unmounted_cleanly
, 0, "Root filesystem was unmounted cleanly");
4860 vfs_set_root_unmounted_cleanly(void)
4862 vfs_root_unmounted_cleanly
= 1;
4866 * Print vnode state.
4869 vn_print_state(struct vnode
*vp
, const char *fmt
, ...)
4872 char perm_str
[] = "(VM_KERNEL_ADDRPERM pointer)";
4873 char fs_name
[MFSNAMELEN
];
4878 printf("vp 0x%0llx %s: ", (uint64_t)VM_KERNEL_ADDRPERM(vp
), perm_str
);
4879 printf("tag %d, type %d\n", vp
->v_tag
, vp
->v_type
);
4881 printf(" iocount %d, usecount %d, kusecount %d references %d\n",
4882 vp
->v_iocount
, vp
->v_usecount
, vp
->v_kusecount
, vp
->v_references
);
4883 printf(" writecount %d, numoutput %d\n", vp
->v_writecount
,
4886 printf(" flag 0x%x, lflag 0x%x, listflag 0x%x\n", vp
->v_flag
,
4887 vp
->v_lflag
, vp
->v_listflag
);
4889 if (vp
->v_mount
== NULL
|| vp
->v_mount
== dead_mountp
) {
4890 strlcpy(fs_name
, "deadfs", MFSNAMELEN
);
4892 vfs_name(vp
->v_mount
, fs_name
);
4895 printf(" v_data 0x%0llx %s\n",
4896 (vp
->v_data
? (uint64_t)VM_KERNEL_ADDRPERM(vp
->v_data
) : 0),
4898 printf(" v_mount 0x%0llx %s vfs_name %s\n",
4899 (vp
->v_mount
? (uint64_t)VM_KERNEL_ADDRPERM(vp
->v_mount
) : 0),
4903 long num_reusedvnodes
= 0;
4907 process_vp(vnode_t vp
, int want_vp
, bool can_defer
, int *deferred
)
4915 vnode_list_remove_locked(vp
);
4917 vnode_list_unlock();
4919 vnode_lock_spin(vp
);
4922 * We could wait for the vnode_lock after removing the vp from the freelist
4923 * and the vid is bumped only at the very end of reclaim. So it is possible
4924 * that we are looking at a vnode that is being terminated. If so skip it.
4926 if ((vpid
!= vp
->v_id
) || (vp
->v_usecount
!= 0) || (vp
->v_iocount
!= 0) ||
4927 VONLIST(vp
) || (vp
->v_lflag
& VL_TERMINATE
)) {
4929 * we lost the race between dropping the list lock
4930 * and picking up the vnode_lock... someone else
4931 * used this vnode and it is now in a new state
4937 if ((vp
->v_lflag
& (VL_NEEDINACTIVE
| VL_MARKTERM
)) == VL_NEEDINACTIVE
) {
4939 * we did a vnode_rele_ext that asked for
4940 * us not to reenter the filesystem during
4941 * the release even though VL_NEEDINACTIVE was
4942 * set... we'll do it here by doing a
4943 * vnode_get/vnode_put
4945 * pick up an iocount so that we can call
4946 * vnode_put and drive the VNOP_INACTIVE...
4947 * vnode_put will either leave us off
4948 * the freelist if a new ref comes in,
4949 * or put us back on the end of the freelist
4950 * or recycle us if we were marked for termination...
4951 * so we'll just go grab a new candidate
4957 vnode_put_locked(vp
);
4963 * Checks for anyone racing us for recycle
4965 if (vp
->v_type
!= VBAD
) {
4966 if ((want_vp
|| can_defer
) && (vnode_on_reliable_media(vp
) == FALSE
|| (vp
->v_flag
& VISDIRTY
))) {
4967 vnode_async_list_add(vp
);
4974 if (vp
->v_lflag
& VL_DEAD
) {
4975 panic("new_vnode(%p): the vnode is VL_DEAD but not VBAD", vp
);
4978 vnode_lock_convert(vp
);
4979 (void)vnode_reclaim_internal(vp
, 1, want_vp
, 0);
4982 if ((VONLIST(vp
))) {
4983 panic("new_vnode(%p): vp on list", vp
);
4985 if (vp
->v_usecount
|| vp
->v_iocount
|| vp
->v_kusecount
||
4986 (vp
->v_lflag
& (VNAMED_UBC
| VNAMED_MOUNT
| VNAMED_FSHASH
))) {
4987 panic("new_vnode(%p): free vnode still referenced", vp
);
4989 if ((vp
->v_mntvnodes
.tqe_prev
!= 0) && (vp
->v_mntvnodes
.tqe_next
!= 0)) {
4990 panic("new_vnode(%p): vnode seems to be on mount list", vp
);
4992 if (!LIST_EMPTY(&vp
->v_nclinks
) || !TAILQ_EMPTY(&vp
->v_ncchildren
)) {
4993 panic("new_vnode(%p): vnode still hooked into the name cache", vp
);
5003 __attribute__((noreturn
))
5005 async_work_continue(void)
5007 struct async_work_lst
*q
;
5011 q
= &vnode_async_work_list
;
5016 if (TAILQ_EMPTY(q
)) {
5017 assert_wait(q
, (THREAD_UNINT
));
5019 vnode_list_unlock();
5021 thread_block((thread_continue_t
)async_work_continue
);
5025 async_work_handled
++;
5027 vp
= TAILQ_FIRST(q
);
5029 vp
= process_vp(vp
, 0, false, &deferred
);
5032 panic("found VBAD vp (%p) on async queue", vp
);
5037 __attribute__((noreturn
))
5039 vn_laundry_continue(void)
5041 struct freelst
*free_q
;
5042 struct ragelst
*rage_q
;
5049 free_q
= &vnode_free_list
;
5050 rage_q
= &vnode_rage_list
;
5055 free_q_empty
= TAILQ_EMPTY(free_q
);
5056 rage_q_empty
= TAILQ_EMPTY(rage_q
);
5058 if (!rage_q_empty
&& !free_q_empty
) {
5059 struct timeval current_tv
;
5061 microuptime(¤t_tv
);
5062 if (ragevnodes
< rage_limit
&&
5063 ((current_tv
.tv_sec
- rage_tv
.tv_sec
) < RAGE_TIME_LIMIT
)) {
5064 rage_q_empty
= true;
5068 if (deadvnodes
>= deadvnodes_high
||
5069 (rage_q_empty
&& free_q_empty
) ||
5070 numvnodes
< desiredvnodes
) {
5071 assert_wait(free_q
, (THREAD_UNINT
));
5073 vnode_list_unlock();
5075 thread_block((thread_continue_t
)vn_laundry_continue
);
5080 if (!rage_q_empty
) {
5081 vp
= TAILQ_FIRST(rage_q
);
5083 vp
= TAILQ_FIRST(free_q
);
5086 vp
= process_vp(vp
, 0, true, &deferred
);
5091 wakeup_laundry_thread()
5093 if ((deadvnodes
< deadvnodes_low
) &&
5094 /* Minimum number of free vnodes the thread should act on */
5095 ((freevnodes
+ ragevnodes
) > 10)) {
5096 wakeup(&vnode_free_list
);
5101 new_vnode(vnode_t
*vpp
)
5104 uint32_t retries
= 0, max_retries
= 100; /* retry incase of tablefull */
5105 uint32_t bdevvp_vnodes
= 0;
5106 int force_alloc
= 0, walk_count
= 0;
5107 boolean_t need_reliable_vp
= FALSE
;
5109 struct timeval initial_tv
;
5110 struct timeval current_tv
;
5111 proc_t curproc
= current_proc();
5113 initial_tv
.tv_sec
= 0;
5120 if (need_reliable_vp
== TRUE
) {
5121 async_work_timed_out
++;
5124 if ((numvnodes
- deadvnodes
) < desiredvnodes
|| force_alloc
) {
5127 if (!TAILQ_EMPTY(&vnode_dead_list
)) {
5129 * Can always reuse a dead one
5131 vp
= TAILQ_FIRST(&vnode_dead_list
);
5132 if (numvnodes
>= desiredvnodes
) {
5133 wakeup_laundry_thread();
5138 * no dead vnodes available... if we're under
5139 * the limit, we'll create a new vnode
5142 if (numvnodes
>= desiredvnodes
) {
5143 wakeup_laundry_thread();
5145 vnode_list_unlock();
5147 vp
= zalloc_flags(vnode_zone
, Z_WAITOK
| Z_ZERO
);
5148 VLISTNONE(vp
); /* avoid double queue removal */
5149 lck_mtx_init(&vp
->v_lock
, &vnode_lck_grp
, &vnode_lck_attr
);
5151 TAILQ_INIT(&vp
->v_ncchildren
);
5153 klist_init(&vp
->v_knotes
);
5155 vp
->v_id
= (uint32_t)ts
.tv_nsec
;
5156 vp
->v_flag
= VSTANDARD
;
5159 if (mac_vnode_label_init_needed(vp
)) {
5160 mac_vnode_label_init(vp
);
5168 wakeup_laundry_thread();
5170 microuptime(¤t_tv
);
5172 #define MAX_WALK_COUNT 1000
5174 if (!TAILQ_EMPTY(&vnode_rage_list
) &&
5175 (ragevnodes
>= rage_limit
||
5176 (current_tv
.tv_sec
- rage_tv
.tv_sec
) >= RAGE_TIME_LIMIT
)) {
5177 TAILQ_FOREACH(vp
, &vnode_rage_list
, v_freelist
) {
5178 if (!(vp
->v_listflag
& VLIST_RAGE
)) {
5179 panic("new_vnode: vp (%p) on RAGE list not marked VLIST_RAGE", vp
);
5182 // if we're a dependency-capable process, skip vnodes that can
5183 // cause recycling deadlocks. (i.e. this process is diskimages
5184 // helper and the vnode is in a disk image). Querying the
5185 // mnt_kern_flag for the mount's virtual device status
5186 // is safer than checking the mnt_dependent_process, which
5187 // may not be updated if there are multiple devnode layers
5188 // in between the disk image and the final consumer.
5190 if ((curproc
->p_flag
& P_DEPENDENCY_CAPABLE
) == 0 || vp
->v_mount
== NULL
||
5191 (vp
->v_mount
->mnt_kern_flag
& MNTK_VIRTUALDEV
) == 0) {
5193 * if need_reliable_vp == TRUE, then we've already sent one or more
5194 * non-reliable vnodes to the async thread for processing and timed
5195 * out waiting for a dead vnode to show up. Use the MAX_WALK_COUNT
5196 * mechanism to first scan for a reliable vnode before forcing
5197 * a new vnode to be created
5199 if (need_reliable_vp
== FALSE
|| vnode_on_reliable_media(vp
) == TRUE
) {
5204 // don't iterate more than MAX_WALK_COUNT vnodes to
5205 // avoid keeping the vnode list lock held for too long.
5207 if (walk_count
++ > MAX_WALK_COUNT
) {
5214 if (vp
== NULL
&& !TAILQ_EMPTY(&vnode_free_list
)) {
5216 * Pick the first vp for possible reuse
5219 TAILQ_FOREACH(vp
, &vnode_free_list
, v_freelist
) {
5220 // if we're a dependency-capable process, skip vnodes that can
5221 // cause recycling deadlocks. (i.e. this process is diskimages
5222 // helper and the vnode is in a disk image). Querying the
5223 // mnt_kern_flag for the mount's virtual device status
5224 // is safer than checking the mnt_dependent_process, which
5225 // may not be updated if there are multiple devnode layers
5226 // in between the disk image and the final consumer.
5228 if ((curproc
->p_flag
& P_DEPENDENCY_CAPABLE
) == 0 || vp
->v_mount
== NULL
||
5229 (vp
->v_mount
->mnt_kern_flag
& MNTK_VIRTUALDEV
) == 0) {
5231 * if need_reliable_vp == TRUE, then we've already sent one or more
5232 * non-reliable vnodes to the async thread for processing and timed
5233 * out waiting for a dead vnode to show up. Use the MAX_WALK_COUNT
5234 * mechanism to first scan for a reliable vnode before forcing
5235 * a new vnode to be created
5237 if (need_reliable_vp
== FALSE
|| vnode_on_reliable_media(vp
) == TRUE
) {
5242 // don't iterate more than MAX_WALK_COUNT vnodes to
5243 // avoid keeping the vnode list lock held for too long.
5245 if (walk_count
++ > MAX_WALK_COUNT
) {
5253 // if we don't have a vnode and the walk_count is >= MAX_WALK_COUNT
5254 // then we're trying to create a vnode on behalf of a
5255 // process like diskimages-helper that has file systems
5256 // mounted on top of itself (and thus we can't reclaim
5257 // vnodes in the file systems on top of us). if we can't
5258 // find a vnode to reclaim then we'll just have to force
5261 if (vp
== NULL
&& walk_count
>= MAX_WALK_COUNT
) {
5263 vnode_list_unlock();
5269 * we've reached the system imposed maximum number of vnodes
5270 * but there isn't a single one available
5271 * wait a bit and then retry... if we can't get a vnode
5272 * after our target number of retries, than log a complaint
5274 if (++retries
<= max_retries
) {
5275 vnode_list_unlock();
5276 delay_for_interval(1, 1000 * 1000);
5280 vnode_list_unlock();
5282 log(LOG_EMERG
, "%d desired, %ld numvnodes, "
5283 "%ld free, %ld dead, %ld async, %d rage %d bdevvp\n",
5284 desiredvnodes
, numvnodes
, freevnodes
, deadvnodes
, async_work_vnodes
, ragevnodes
, bdevvp_vnodes
);
5287 #if DEVELOPMENT || DEBUG
5288 if (bootarg_no_vnode_jetsam
) {
5289 panic("vnode table is full\n");
5291 #endif /* DEVELOPMENT || DEBUG */
5294 * Running out of vnodes tends to make a system unusable. Start killing
5295 * processes that jetsam knows are killable.
5297 if (memorystatus_kill_on_vnode_limit() == FALSE
) {
5299 * If jetsam can't find any more processes to kill and there
5300 * still aren't any free vnodes, panic. Hopefully we'll get a
5301 * panic log to tell us why we ran out.
5303 panic("vnode table is full\n");
5307 * Now that we've killed someone, wait a bit and continue looking
5308 * (with fewer retries before trying another kill).
5310 delay_for_interval(3, 1000 * 1000);
5321 if ((vp
= process_vp(vp
, 1, true, &deferred
)) == NULLVP
) {
5324 struct timeval elapsed_tv
;
5326 if (initial_tv
.tv_sec
== 0) {
5327 microuptime(&initial_tv
);
5332 dead_vnode_waited
++;
5333 dead_vnode_wanted
++;
5336 * note that we're only going to explicitly wait 10ms
5337 * for a dead vnode to become available, since even if one
5338 * isn't available, a reliable vnode might now be available
5339 * at the head of the VRAGE or free lists... if so, we
5340 * can satisfy the new_vnode request with less latency then waiting
5341 * for the full 100ms duration we're ultimately willing to tolerate
5343 assert_wait_timeout((caddr_t
)&dead_vnode_wanted
, (THREAD_INTERRUPTIBLE
), 10000, NSEC_PER_USEC
);
5345 vnode_list_unlock();
5347 thread_block(THREAD_CONTINUE_NULL
);
5349 microuptime(&elapsed_tv
);
5351 timevalsub(&elapsed_tv
, &initial_tv
);
5352 elapsed_msecs
= (int)(elapsed_tv
.tv_sec
* 1000 + elapsed_tv
.tv_usec
/ 1000);
5354 if (elapsed_msecs
>= 100) {
5356 * we've waited long enough... 100ms is
5357 * somewhat arbitrary for this case, but the
5358 * normal worst case latency used for UI
5359 * interaction is 100ms, so I've chosen to
5362 * setting need_reliable_vp to TRUE
5363 * forces us to find a reliable vnode
5364 * that we can process synchronously, or
5365 * to create a new one if the scan for
5366 * a reliable one hits the scan limit
5368 need_reliable_vp
= TRUE
;
5373 OSAddAtomicLong(1, &num_reusedvnodes
);
5378 * We should never see VL_LABELWAIT or VL_LABEL here.
5379 * as those operations hold a reference.
5381 assert((vp
->v_lflag
& VL_LABELWAIT
) != VL_LABELWAIT
);
5382 assert((vp
->v_lflag
& VL_LABEL
) != VL_LABEL
);
5383 if (vp
->v_lflag
& VL_LABELED
|| vp
->v_label
!= NULL
) {
5384 vnode_lock_convert(vp
);
5385 mac_vnode_label_recycle(vp
);
5386 } else if (mac_vnode_label_init_needed(vp
)) {
5387 vnode_lock_convert(vp
);
5388 mac_vnode_label_init(vp
);
5395 vp
->v_writecount
= 0;
5396 vp
->v_references
= 0;
5397 vp
->v_iterblkflags
= 0;
5398 vp
->v_flag
= VSTANDARD
;
5399 /* vbad vnodes can point to dead_mountp */
5401 vp
->v_defer_reclaimlist
= (vnode_t
)0;
5412 vnode_lock(vnode_t vp
)
5414 lck_mtx_lock(&vp
->v_lock
);
5418 vnode_lock_spin(vnode_t vp
)
5420 lck_mtx_lock_spin(&vp
->v_lock
);
5424 vnode_unlock(vnode_t vp
)
5426 lck_mtx_unlock(&vp
->v_lock
);
5432 vnode_get(struct vnode
*vp
)
5436 vnode_lock_spin(vp
);
5437 retval
= vnode_get_locked(vp
);
5444 vnode_get_locked(struct vnode
*vp
)
5447 lck_mtx_assert(&vp
->v_lock
, LCK_MTX_ASSERT_OWNED
);
5449 if ((vp
->v_iocount
== 0) && (vp
->v_lflag
& (VL_TERMINATE
| VL_DEAD
))) {
5453 if (os_add_overflow(vp
->v_iocount
, 1, &vp
->v_iocount
)) {
5454 panic("v_iocount overflow");
5464 * vnode_getwithvid() cuts in line in front of a vnode drain (that is,
5465 * while the vnode is draining, but at no point after that) to prevent
5466 * deadlocks when getting vnodes from filesystem hashes while holding
5467 * resources that may prevent other iocounts from being released.
5470 vnode_getwithvid(vnode_t vp
, uint32_t vid
)
5472 return vget_internal(vp
, vid
, (VNODE_NODEAD
| VNODE_WITHID
| VNODE_DRAINO
));
5476 * vnode_getwithvid_drainok() is like vnode_getwithvid(), but *does* block behind a vnode
5477 * drain; it exists for use in the VFS name cache, where we really do want to block behind
5478 * vnode drain to prevent holding off an unmount.
5481 vnode_getwithvid_drainok(vnode_t vp
, uint32_t vid
)
5483 return vget_internal(vp
, vid
, (VNODE_NODEAD
| VNODE_WITHID
));
5487 vnode_getwithref(vnode_t vp
)
5489 return vget_internal(vp
, 0, 0);
5493 __private_extern__
int
5494 vnode_getalways(vnode_t vp
)
5496 return vget_internal(vp
, 0, VNODE_ALWAYS
);
5499 __private_extern__
int
5500 vnode_getalways_from_pager(vnode_t vp
)
5502 return vget_internal(vp
, 0, VNODE_ALWAYS
| VNODE_PAGER
);
5506 vn_set_dead(vnode_t vp
)
5509 vp
->v_op
= dead_vnodeop_p
;
5513 vp
->v_lflag
|= VL_DEAD
;
5517 vnode_put_internal_locked(vnode_t vp
, bool from_pager
)
5519 vfs_context_t ctx
= vfs_context_current(); /* hoist outside loop */
5522 lck_mtx_assert(&vp
->v_lock
, LCK_MTX_ASSERT_OWNED
);
5525 if (vp
->v_iocount
< 1) {
5526 panic("vnode_put(%p): iocount < 1", vp
);
5529 if ((vp
->v_usecount
> 0) || (vp
->v_iocount
> 1)) {
5530 vnode_dropiocount(vp
);
5534 if (((vp
->v_lflag
& (VL_DEAD
| VL_NEEDINACTIVE
)) == VL_NEEDINACTIVE
)) {
5535 vp
->v_lflag
&= ~VL_NEEDINACTIVE
;
5538 VNOP_INACTIVE(vp
, ctx
);
5540 vnode_lock_spin(vp
);
5542 * because we had to drop the vnode lock before calling
5543 * VNOP_INACTIVE, the state of this vnode may have changed...
5544 * we may pick up both VL_MARTERM and either
5545 * an iocount or a usecount while in the VNOP_INACTIVE call
5546 * we don't want to call vnode_reclaim_internal on a vnode
5547 * that has active references on it... so loop back around
5548 * and reevaluate the state
5552 vp
->v_lflag
&= ~VL_NEEDINACTIVE
;
5554 if ((vp
->v_lflag
& (VL_MARKTERM
| VL_TERMINATE
| VL_DEAD
)) == VL_MARKTERM
) {
5557 * We can't initiate reclaim when called from the pager
5558 * because it will deadlock with itself so we hand it
5559 * off to the async cleaner thread.
5562 if (!(vp
->v_listflag
& VLIST_ASYNC_WORK
)) {
5564 vnode_list_remove_locked(vp
);
5565 vnode_async_list_add_locked(vp
);
5566 vnode_list_unlock();
5568 wakeup(&vnode_async_work_list
);
5570 vnode_async_list_add(vp
);
5573 vnode_lock_convert(vp
);
5574 vnode_reclaim_internal(vp
, 1, 1, 0);
5577 vnode_dropiocount(vp
);
5584 vnode_put_locked(vnode_t vp
)
5586 return vnode_put_internal_locked(vp
, false);
5590 vnode_put(vnode_t vp
)
5594 vnode_lock_spin(vp
);
5595 retval
= vnode_put_internal_locked(vp
, false);
5602 vnode_put_from_pager(vnode_t vp
)
5606 vnode_lock_spin(vp
);
5607 /* Cannot initiate reclaim while paging */
5608 retval
= vnode_put_internal_locked(vp
, true);
5614 /* is vnode_t in use by others? */
5616 vnode_isinuse(vnode_t vp
, int refcnt
)
5618 return vnode_isinuse_locked(vp
, refcnt
, 0);
5622 vnode_usecount(vnode_t vp
)
5624 return vp
->v_usecount
;
5628 vnode_iocount(vnode_t vp
)
5630 return vp
->v_iocount
;
5634 vnode_isinuse_locked(vnode_t vp
, int refcnt
, int locked
)
5639 vnode_lock_spin(vp
);
5641 if ((vp
->v_type
!= VREG
) && ((vp
->v_usecount
- vp
->v_kusecount
) > refcnt
)) {
5645 if (vp
->v_type
== VREG
) {
5646 retval
= ubc_isinuse_locked(vp
, refcnt
, 1);
5657 /* resume vnode_t */
5659 vnode_resume(vnode_t vp
)
5661 if ((vp
->v_lflag
& VL_SUSPENDED
) && vp
->v_owner
== current_thread()) {
5662 vnode_lock_spin(vp
);
5663 vp
->v_lflag
&= ~VL_SUSPENDED
;
5667 wakeup(&vp
->v_iocount
);
5673 * Please do not use on more than one vnode at a time as it may
5675 * xxx should we explicity prevent this from happening?
5679 vnode_suspend(vnode_t vp
)
5681 if (vp
->v_lflag
& VL_SUSPENDED
) {
5685 vnode_lock_spin(vp
);
5688 * xxx is this sufficient to check if a vnode_drain is
5692 if (vp
->v_owner
== NULL
) {
5693 vp
->v_lflag
|= VL_SUSPENDED
;
5694 vp
->v_owner
= current_thread();
5702 * Release any blocked locking requests on the vnode.
5703 * Used for forced-unmounts.
5705 * XXX What about network filesystems?
5708 vnode_abort_advlocks(vnode_t vp
)
5710 if (vp
->v_flag
& VLOCKLOCAL
) {
5711 lf_abort_advlocks(vp
);
5717 vnode_drain(vnode_t vp
)
5719 if (vp
->v_lflag
& VL_DRAIN
) {
5720 panic("vnode_drain: recursive drain");
5723 vp
->v_lflag
|= VL_DRAIN
;
5724 vp
->v_owner
= current_thread();
5726 while (vp
->v_iocount
> 1) {
5727 if (bootarg_no_vnode_drain
) {
5728 struct timespec ts
= {.tv_sec
= 10, .tv_nsec
= 0};
5731 if (vfs_unmountall_started
) {
5735 error
= msleep(&vp
->v_iocount
, &vp
->v_lock
, PVFS
, "vnode_drain_with_timeout", &ts
);
5737 /* Try to deal with leaked iocounts under bootarg and shutting down */
5738 if (vp
->v_iocount
> 1 && error
== EWOULDBLOCK
&&
5739 ts
.tv_sec
== 1 && vp
->v_numoutput
== 0) {
5744 msleep(&vp
->v_iocount
, &vp
->v_lock
, PVFS
, "vnode_drain", NULL
);
5748 vp
->v_lflag
&= ~VL_DRAIN
;
5755 * if the number of recent references via vnode_getwithvid or vnode_getwithref
5756 * exceeds this threshold, than 'UN-AGE' the vnode by removing it from
5757 * the LRU list if it's currently on it... once the iocount and usecount both drop
5758 * to 0, it will get put back on the end of the list, effectively making it younger
5759 * this allows us to keep actively referenced vnodes in the list without having
5760 * to constantly remove and add to the list each time a vnode w/o a usecount is
5761 * referenced which costs us taking and dropping a global lock twice.
5762 * However, if the vnode is marked DIRTY, we want to pull it out much earlier
5764 #define UNAGE_THRESHHOLD 25
5765 #define UNAGE_DIRTYTHRESHHOLD 6
5768 vnode_getiocount(vnode_t vp
, unsigned int vid
, int vflags
)
5770 int nodead
= vflags
& VNODE_NODEAD
;
5771 int nosusp
= vflags
& VNODE_NOSUSPEND
;
5772 int always
= vflags
& VNODE_ALWAYS
;
5773 int beatdrain
= vflags
& VNODE_DRAINO
;
5774 int withvid
= vflags
& VNODE_WITHID
;
5775 int forpager
= vflags
& VNODE_PAGER
;
5781 * if it is a dead vnode with deadfs
5783 if (nodead
&& (vp
->v_lflag
& VL_DEAD
) && ((vp
->v_type
== VBAD
) || (vp
->v_data
== 0))) {
5787 * will return VL_DEAD ones
5789 if ((vp
->v_lflag
& (VL_SUSPENDED
| VL_DRAIN
| VL_TERMINATE
)) == 0) {
5793 * if suspended vnodes are to be failed
5795 if (nosusp
&& (vp
->v_lflag
& VL_SUSPENDED
)) {
5799 * if you are the owner of drain/suspend/termination , can acquire iocount
5800 * check for VL_TERMINATE; it does not set owner
5802 if ((vp
->v_lflag
& (VL_DRAIN
| VL_SUSPENDED
| VL_TERMINATE
)) &&
5803 (vp
->v_owner
== current_thread())) {
5812 * If this vnode is getting drained, there are some cases where
5813 * we can't block or, in case of tty vnodes, want to be
5816 if (vp
->v_lflag
& VL_DRAIN
) {
5818 * In some situations, we want to get an iocount
5819 * even if the vnode is draining to prevent deadlock,
5820 * e.g. if we're in the filesystem, potentially holding
5821 * resources that could prevent other iocounts from
5828 * Don't block if the vnode's mount point is unmounting as
5829 * we may be the thread the unmount is itself waiting on
5830 * Only callers who pass in vids (at this point, we've already
5831 * handled nosusp and nodead) are expecting error returns
5832 * from this function, so only we can only return errors for
5833 * those. ENODEV is intended to inform callers that the call
5834 * failed because an unmount is in progress.
5836 if (withvid
&& (vp
->v_mount
) && vfs_isunmount(vp
->v_mount
)) {
5840 if (vnode_istty(vp
)) {
5845 vnode_lock_convert(vp
);
5847 if (vp
->v_lflag
& VL_TERMINATE
) {
5850 vp
->v_lflag
|= VL_TERMWANT
;
5852 error
= msleep(&vp
->v_lflag
, &vp
->v_lock
,
5853 (PVFS
| sleepflg
), "vnode getiocount", NULL
);
5858 msleep(&vp
->v_iocount
, &vp
->v_lock
, PVFS
, "vnode_getiocount", NULL
);
5861 if (withvid
&& vid
!= vp
->v_id
) {
5864 if (!forpager
&& (++vp
->v_references
>= UNAGE_THRESHHOLD
||
5865 (vp
->v_flag
& VISDIRTY
&& vp
->v_references
>= UNAGE_DIRTYTHRESHHOLD
))) {
5866 vp
->v_references
= 0;
5867 vnode_list_remove(vp
);
5877 vnode_dropiocount(vnode_t vp
)
5879 if (vp
->v_iocount
< 1) {
5880 panic("vnode_dropiocount(%p): v_iocount < 1", vp
);
5887 if ((vp
->v_lflag
& (VL_DRAIN
| VL_SUSPENDED
)) && (vp
->v_iocount
<= 1)) {
5888 wakeup(&vp
->v_iocount
);
5894 vnode_reclaim(struct vnode
* vp
)
5896 vnode_reclaim_internal(vp
, 0, 0, 0);
5901 vnode_reclaim_internal(struct vnode
* vp
, int locked
, int reuse
, int flags
)
5904 bool clear_tty_revoke
= false;
5910 if (vp
->v_lflag
& VL_TERMINATE
) {
5911 panic("vnode reclaim in progress");
5913 vp
->v_lflag
|= VL_TERMINATE
;
5915 vn_clearunionwait(vp
, 1);
5918 * We have to force any terminals in reads to return and give up
5919 * their iocounts. It's important to do this after VL_TERMINATE
5920 * has been set to ensure new reads are blocked while the
5921 * revoke is in progress.
5923 if (vnode_istty(vp
) && (flags
& REVOKEALL
) && (vp
->v_iocount
> 1)) {
5925 VNOP_IOCTL(vp
, TIOCREVOKE
, (caddr_t
)NULL
, 0, vfs_context_kernel());
5926 clear_tty_revoke
= true;
5932 if (clear_tty_revoke
) {
5934 VNOP_IOCTL(vp
, TIOCREVOKECLEAR
, (caddr_t
)NULL
, 0, vfs_context_kernel());
5938 isfifo
= (vp
->v_type
== VFIFO
);
5940 if (vp
->v_type
!= VBAD
) {
5941 vgone(vp
, flags
); /* clean and reclaim the vnode */
5944 * give the vnode a new identity so that vnode_getwithvid will fail
5945 * on any stale cache accesses...
5946 * grab the list_lock so that if we're in "new_vnode"
5947 * behind the list_lock trying to steal this vnode, the v_id is stable...
5948 * once new_vnode drops the list_lock, it will block trying to take
5949 * the vnode lock until we release it... at that point it will evaluate
5950 * whether the v_vid has changed
5951 * also need to make sure that the vnode isn't on a list where "new_vnode"
5952 * can find it after the v_id has been bumped until we are completely done
5953 * with the vnode (i.e. putting it back on a list has to be the very last
5954 * thing we do to this vnode... many of the callers of vnode_reclaim_internal
5955 * are holding an io_count on the vnode... they need to drop the io_count
5956 * BEFORE doing a vnode_list_add or make sure to hold the vnode lock until
5957 * they are completely done with the vnode
5961 vnode_list_remove_locked(vp
);
5964 vnode_list_unlock();
5967 struct fifoinfo
* fip
;
5969 fip
= vp
->v_fifoinfo
;
5970 vp
->v_fifoinfo
= NULL
;
5971 kheap_free(KHEAP_DEFAULT
, fip
, sizeof(struct fifoinfo
));
5976 panic("vnode_reclaim_internal: cleaned vnode isn't");
5978 if (vp
->v_numoutput
) {
5979 panic("vnode_reclaim_internal: clean vnode has pending I/O's");
5981 if (UBCINFOEXISTS(vp
)) {
5982 panic("vnode_reclaim_internal: ubcinfo not cleaned");
5985 panic("vnode_reclaim_internal: vparent not removed");
5988 panic("vnode_reclaim_internal: vname not removed");
5991 vp
->v_socket
= NULL
;
5993 vp
->v_lflag
&= ~VL_TERMINATE
;
5996 KNOTE(&vp
->v_knotes
, NOTE_REVOKE
);
5998 /* Make sure that when we reuse the vnode, no knotes left over */
5999 klist_init(&vp
->v_knotes
);
6001 if (vp
->v_lflag
& VL_TERMWANT
) {
6002 vp
->v_lflag
&= ~VL_TERMWANT
;
6003 wakeup(&vp
->v_lflag
);
6007 * make sure we get on the
6008 * dead list if appropriate
6018 vnode_create_internal(uint32_t flavor
, uint32_t size
, void *data
, vnode_t
*vpp
,
6028 struct componentname
*cnp
;
6029 struct vnode_fsparam
*param
= (struct vnode_fsparam
*)data
;
6031 struct vnode_trigger_param
*tinfo
= NULL
;
6042 /* Do quick sanity check on the parameters. */
6043 if ((param
== NULL
) || (param
->vnfs_vtype
== VBAD
)) {
6049 if ((flavor
== VNCREATE_TRIGGER
) && (size
== VNCREATE_TRIGGER_SIZE
)) {
6050 tinfo
= (struct vnode_trigger_param
*)data
;
6052 /* Validate trigger vnode input */
6053 if ((param
->vnfs_vtype
!= VDIR
) ||
6054 (tinfo
->vnt_resolve_func
== NULL
) ||
6055 (tinfo
->vnt_flags
& ~VNT_VALID_MASK
)) {
6059 /* Fall through a normal create (params will be the same) */
6060 flavor
= VNCREATE_FLAVOR
;
6064 if ((flavor
!= VNCREATE_FLAVOR
) || (size
!= VCREATESIZE
)) {
6070 if (!existing_vnode
) {
6071 if ((error
= new_vnode(&vp
))) {
6075 /* Make it so that it can be released by a vnode_put) */
6082 * A vnode obtained by vnode_create_empty has been passed to
6083 * vnode_initialize - Unset VL_DEAD set by vn_set_dead. After
6084 * this point, it is set back on any error.
6086 * N.B. vnode locking - We make the same assumptions as the
6087 * "unsplit" vnode_create did - i.e. it is safe to update the
6088 * vnode's fields without the vnode lock. This vnode has been
6089 * out and about with the filesystem and hopefully nothing
6090 * was done to the vnode between the vnode_create_empty and
6091 * now when it has come in through vnode_initialize.
6093 vp
->v_lflag
&= ~VL_DEAD
;
6096 dvp
= param
->vnfs_dvp
;
6097 cnp
= param
->vnfs_cnp
;
6099 vp
->v_op
= param
->vnfs_vops
;
6100 vp
->v_type
= (uint16_t)param
->vnfs_vtype
;
6101 vp
->v_data
= param
->vnfs_fsnode
;
6103 if (param
->vnfs_markroot
) {
6104 vp
->v_flag
|= VROOT
;
6106 if (param
->vnfs_marksystem
) {
6107 vp
->v_flag
|= VSYSTEM
;
6109 if (vp
->v_type
== VREG
) {
6110 error
= ubc_info_init_withsize(vp
, param
->vnfs_filesize
);
6120 if (param
->vnfs_mp
->mnt_ioflags
& MNT_IOFLAGS_IOSCHED_SUPPORTED
) {
6121 memory_object_mark_io_tracking(vp
->v_ubcinfo
->ui_control
);
6128 #if CONFIG_FIRMLINKS
6129 vp
->v_fmlink
= NULLVP
;
6131 vp
->v_flag
&= ~VFMLINKTARGET
;
6135 * For trigger vnodes, attach trigger info to vnode
6137 if ((vp
->v_type
== VDIR
) && (tinfo
!= NULL
)) {
6139 * Note: has a side effect of incrementing trigger count on the
6140 * mount if successful, which we would need to undo on a
6141 * subsequent failure.
6146 error
= vnode_resolver_create(param
->vnfs_mp
, vp
, tinfo
, FALSE
);
6148 printf("vnode_create: vnode_resolver_create() err %d\n", error
);
6158 if (vp
->v_type
== VCHR
|| vp
->v_type
== VBLK
) {
6159 vp
->v_tag
= VT_DEVFS
; /* callers will reset if needed (bdevvp) */
6161 if ((nvp
= checkalias(vp
, param
->vnfs_rdev
))) {
6163 * if checkalias returns a vnode, it will be locked
6165 * first get rid of the unneeded vnode we acquired
6168 vp
->v_op
= spec_vnodeop_p
;
6170 vp
->v_lflag
= VL_DEAD
;
6176 * switch to aliased vnode and finish
6182 vp
->v_op
= param
->vnfs_vops
;
6183 vp
->v_type
= (uint16_t)param
->vnfs_vtype
;
6184 vp
->v_data
= param
->vnfs_fsnode
;
6187 insmntque(vp
, param
->vnfs_mp
);
6192 if (VCHR
== vp
->v_type
) {
6193 u_int maj
= major(vp
->v_rdev
);
6195 if (maj
< (u_int
)nchrdev
&& cdevsw
[maj
].d_type
== D_TTY
) {
6196 vp
->v_flag
|= VISTTY
;
6201 if (vp
->v_type
== VFIFO
) {
6202 struct fifoinfo
*fip
;
6204 fip
= kheap_alloc(KHEAP_DEFAULT
, sizeof(struct fifoinfo
),
6206 vp
->v_fifoinfo
= fip
;
6208 /* The file systems must pass the address of the location where
6209 * they store the vnode pointer. When we add the vnode into the mount
6210 * list and name cache they become discoverable. So the file system node
6211 * must have the connection to vnode setup by then
6215 /* Add fs named reference. */
6216 if (param
->vnfs_flags
& VNFS_ADDFSREF
) {
6217 vp
->v_lflag
|= VNAMED_FSHASH
;
6219 if (param
->vnfs_mp
) {
6220 if (param
->vnfs_mp
->mnt_kern_flag
& MNTK_LOCK_LOCAL
) {
6221 vp
->v_flag
|= VLOCKLOCAL
;
6224 if ((vp
->v_freelist
.tqe_prev
!= (struct vnode
**)0xdeadb)) {
6225 panic("insmntque: vp on the free list\n");
6229 * enter in mount vnode list
6231 insmntque(vp
, param
->vnfs_mp
);
6234 if (dvp
&& vnode_ref(dvp
) == 0) {
6238 if (dvp
&& ((param
->vnfs_flags
& (VNFS_NOCACHE
| VNFS_CANTCACHE
)) == 0)) {
6240 * enter into name cache
6241 * we've got the info to enter it into the name cache now
6242 * cache_enter_create will pick up an extra reference on
6243 * the name entered into the string cache
6245 vp
->v_name
= cache_enter_create(dvp
, vp
, cnp
);
6247 vp
->v_name
= vfs_addname(cnp
->cn_nameptr
, cnp
->cn_namelen
, cnp
->cn_hash
, 0);
6250 if ((cnp
->cn_flags
& UNIONCREATED
) == UNIONCREATED
) {
6251 vp
->v_flag
|= VISUNION
;
6254 if ((param
->vnfs_flags
& VNFS_CANTCACHE
) == 0) {
6256 * this vnode is being created as cacheable in the name cache
6257 * this allows us to re-enter it in the cache
6259 vp
->v_flag
|= VNCACHEABLE
;
6261 ut
= get_bsdthread_info(current_thread());
6263 if ((current_proc()->p_lflag
& P_LRAGE_VNODES
) ||
6264 (ut
->uu_flag
& (UT_RAGE_VNODES
| UT_KERN_RAGE_VNODES
))) {
6266 * process has indicated that it wants any
6267 * vnodes created on its behalf to be rapidly
6268 * aged to reduce the impact on the cached set
6271 * if UT_KERN_RAGE_VNODES is set, then the
6272 * kernel internally wants vnodes to be rapidly
6273 * aged, even if the process hasn't requested
6276 vp
->v_flag
|= VRAGE
;
6279 #if CONFIG_SECLUDED_MEMORY
6280 switch (secluded_for_filecache
) {
6283 * secluded_for_filecache == 0:
6284 * + no file contents in secluded pool
6289 * secluded_for_filecache == 1:
6291 * + files from /Applications/ are OK
6292 * + files from /Applications/Camera are not OK
6293 * + no files that are open for write
6295 if (vnode_vtype(vp
) == VREG
&&
6296 vnode_mount(vp
) != NULL
&&
6297 (!(vfs_flags(vnode_mount(vp
)) & MNT_ROOTFS
))) {
6298 /* not from root filesystem: eligible for secluded pages */
6299 memory_object_mark_eligible_for_secluded(
6300 ubc_getobject(vp
, UBC_FLAGS_NONE
),
6306 * secluded_for_filecache == 2:
6307 * + all read-only files OK, except:
6308 * + dyld_shared_cache_arm64*
6312 if (vnode_vtype(vp
) == VREG
) {
6313 memory_object_mark_eligible_for_secluded(
6314 ubc_getobject(vp
, UBC_FLAGS_NONE
),
6321 #endif /* CONFIG_SECLUDED_MEMORY */
6326 if (existing_vnode
) {
6333 * The following api creates a vnode and associates all the parameter specified in vnode_fsparam
6334 * structure and returns a vnode handle with a reference. device aliasing is handled here so checkalias
6335 * is obsoleted by this.
6338 vnode_create(uint32_t flavor
, uint32_t size
, void *data
, vnode_t
*vpp
)
6341 return vnode_create_internal(flavor
, size
, data
, vpp
, 1);
6345 vnode_create_empty(vnode_t
*vpp
)
6348 return vnode_create_internal(VNCREATE_FLAVOR
, VCREATESIZE
, NULL
,
6353 vnode_initialize(uint32_t flavor
, uint32_t size
, void *data
, vnode_t
*vpp
)
6355 if (*vpp
== NULLVP
) {
6356 panic("NULL vnode passed to vnode_initialize");
6358 #if DEVELOPMENT || DEBUG
6360 * We lock to check that vnode is fit for unlocked use in
6361 * vnode_create_internal.
6363 vnode_lock_spin(*vpp
);
6364 VNASSERT(((*vpp
)->v_iocount
== 1), *vpp
,
6365 ("vnode_initialize : iocount not 1, is %d", (*vpp
)->v_iocount
));
6366 VNASSERT(((*vpp
)->v_usecount
== 0), *vpp
,
6367 ("vnode_initialize : usecount not 0, is %d", (*vpp
)->v_usecount
));
6368 VNASSERT(((*vpp
)->v_lflag
& VL_DEAD
), *vpp
,
6369 ("vnode_initialize : v_lflag does not have VL_DEAD, is 0x%x",
6371 VNASSERT(((*vpp
)->v_data
== NULL
), *vpp
,
6372 ("vnode_initialize : v_data not NULL"));
6375 return vnode_create_internal(flavor
, size
, data
, vpp
, 1);
6379 vnode_addfsref(vnode_t vp
)
6381 vnode_lock_spin(vp
);
6382 if (vp
->v_lflag
& VNAMED_FSHASH
) {
6383 panic("add_fsref: vp already has named reference");
6385 if ((vp
->v_freelist
.tqe_prev
!= (struct vnode
**)0xdeadb)) {
6386 panic("addfsref: vp on the free list\n");
6388 vp
->v_lflag
|= VNAMED_FSHASH
;
6393 vnode_removefsref(vnode_t vp
)
6395 vnode_lock_spin(vp
);
6396 if ((vp
->v_lflag
& VNAMED_FSHASH
) == 0) {
6397 panic("remove_fsref: no named reference");
6399 vp
->v_lflag
&= ~VNAMED_FSHASH
;
6406 vfs_iterate(int flags
, int (*callout
)(mount_t
, void *), void *arg
)
6411 int count
, actualcount
, i
;
6413 int indx_start
, indx_stop
, indx_incr
;
6414 int cb_dropref
= (flags
& VFS_ITERATE_CB_DROPREF
);
6415 int noskip_unmount
= (flags
& VFS_ITERATE_NOSKIP_UNMOUNT
);
6417 count
= mount_getvfscnt();
6420 fsid_list
= kheap_alloc(KHEAP_TEMP
, count
* sizeof(fsid_t
), Z_WAITOK
);
6421 allocmem
= (void *)fsid_list
;
6423 actualcount
= mount_fillfsids(fsid_list
, count
);
6426 * Establish the iteration direction
6427 * VFS_ITERATE_TAIL_FIRST overrides default head first order (oldest first)
6429 if (flags
& VFS_ITERATE_TAIL_FIRST
) {
6430 indx_start
= actualcount
- 1;
6433 } else { /* Head first by default */
6435 indx_stop
= actualcount
;
6439 for (i
= indx_start
; i
!= indx_stop
; i
+= indx_incr
) {
6440 /* obtain the mount point with iteration reference */
6441 mp
= mount_list_lookupby_fsid(&fsid_list
[i
], 0, 1);
6443 if (mp
== (struct mount
*)0) {
6447 if ((mp
->mnt_lflag
& MNT_LDEAD
) ||
6448 (!noskip_unmount
&& (mp
->mnt_lflag
& MNT_LUNMOUNT
))) {
6455 /* iterate over all the vnodes */
6456 ret
= callout(mp
, arg
);
6459 * Drop the iterref here if the callback didn't do it.
6460 * Note: If cb_dropref is set the mp may no longer exist.
6468 case VFS_RETURNED_DONE
:
6469 if (ret
== VFS_RETURNED_DONE
) {
6475 case VFS_CLAIMED_DONE
:
6486 kheap_free(KHEAP_TEMP
, allocmem
, (count
* sizeof(fsid_t
)));
6491 * Update the vfsstatfs structure in the mountpoint.
6492 * MAC: Parameter eventtype added, indicating whether the event that
6493 * triggered this update came from user space, via a system call
6494 * (VFS_USER_EVENT) or an internal kernel call (VFS_KERNEL_EVENT).
6497 vfs_update_vfsstat(mount_t mp
, vfs_context_t ctx
, __unused
int eventtype
)
6503 * Request the attributes we want to propagate into
6504 * the per-mount vfsstat structure.
6507 VFSATTR_WANTED(&va
, f_iosize
);
6508 VFSATTR_WANTED(&va
, f_blocks
);
6509 VFSATTR_WANTED(&va
, f_bfree
);
6510 VFSATTR_WANTED(&va
, f_bavail
);
6511 VFSATTR_WANTED(&va
, f_bused
);
6512 VFSATTR_WANTED(&va
, f_files
);
6513 VFSATTR_WANTED(&va
, f_ffree
);
6514 VFSATTR_WANTED(&va
, f_bsize
);
6515 VFSATTR_WANTED(&va
, f_fssubtype
);
6517 if ((error
= vfs_getattr(mp
, &va
, ctx
)) != 0) {
6518 KAUTH_DEBUG("STAT - filesystem returned error %d", error
);
6522 if (eventtype
== VFS_USER_EVENT
) {
6523 error
= mac_mount_check_getattr(ctx
, mp
, &va
);
6530 * Unpack into the per-mount structure.
6532 * We only overwrite these fields, which are likely to change:
6540 * And these which are not, but which the FS has no other way
6541 * of providing to us:
6547 if (VFSATTR_IS_SUPPORTED(&va
, f_bsize
)) {
6548 /* 4822056 - protect against malformed server mount */
6549 mp
->mnt_vfsstat
.f_bsize
= (va
.f_bsize
> 0 ? va
.f_bsize
: 512);
6551 mp
->mnt_vfsstat
.f_bsize
= mp
->mnt_devblocksize
; /* default from the device block size */
6553 if (VFSATTR_IS_SUPPORTED(&va
, f_iosize
)) {
6554 mp
->mnt_vfsstat
.f_iosize
= va
.f_iosize
;
6556 mp
->mnt_vfsstat
.f_iosize
= 1024 * 1024; /* 1MB sensible I/O size */
6558 if (VFSATTR_IS_SUPPORTED(&va
, f_blocks
)) {
6559 mp
->mnt_vfsstat
.f_blocks
= va
.f_blocks
;
6561 if (VFSATTR_IS_SUPPORTED(&va
, f_bfree
)) {
6562 mp
->mnt_vfsstat
.f_bfree
= va
.f_bfree
;
6564 if (VFSATTR_IS_SUPPORTED(&va
, f_bavail
)) {
6565 mp
->mnt_vfsstat
.f_bavail
= va
.f_bavail
;
6567 if (VFSATTR_IS_SUPPORTED(&va
, f_bused
)) {
6568 mp
->mnt_vfsstat
.f_bused
= va
.f_bused
;
6570 if (VFSATTR_IS_SUPPORTED(&va
, f_files
)) {
6571 mp
->mnt_vfsstat
.f_files
= va
.f_files
;
6573 if (VFSATTR_IS_SUPPORTED(&va
, f_ffree
)) {
6574 mp
->mnt_vfsstat
.f_ffree
= va
.f_ffree
;
6577 /* this is unlikely to change, but has to be queried for */
6578 if (VFSATTR_IS_SUPPORTED(&va
, f_fssubtype
)) {
6579 mp
->mnt_vfsstat
.f_fssubtype
= va
.f_fssubtype
;
6586 mount_list_add(mount_t mp
)
6591 if (get_system_inshutdown() != 0) {
6594 TAILQ_INSERT_TAIL(&mountlist
, mp
, mnt_list
);
6598 mount_list_unlock();
6604 mount_list_remove(mount_t mp
)
6607 TAILQ_REMOVE(&mountlist
, mp
, mnt_list
);
6609 mp
->mnt_list
.tqe_next
= NULL
;
6610 mp
->mnt_list
.tqe_prev
= NULL
;
6611 mount_list_unlock();
6615 mount_lookupby_volfsid(int volfs_id
, int withref
)
6617 mount_t cur_mount
= (mount_t
)0;
6621 TAILQ_FOREACH(mp
, &mountlist
, mnt_list
) {
6622 if (!(mp
->mnt_kern_flag
& MNTK_UNMOUNT
) &&
6623 (mp
->mnt_kern_flag
& MNTK_PATH_FROM_ID
) &&
6624 (mp
->mnt_vfsstat
.f_fsid
.val
[0] == volfs_id
)) {
6627 if (mount_iterref(cur_mount
, 1)) {
6628 cur_mount
= (mount_t
)0;
6629 mount_list_unlock();
6636 mount_list_unlock();
6637 if (withref
&& (cur_mount
!= (mount_t
)0)) {
6639 if (vfs_busy(mp
, LK_NOWAIT
) != 0) {
6640 cur_mount
= (mount_t
)0;
6649 mount_list_lookupby_fsid(fsid_t
*fsid
, int locked
, int withref
)
6651 mount_t retmp
= (mount_t
)0;
6657 TAILQ_FOREACH(mp
, &mountlist
, mnt_list
)
6658 if (mp
->mnt_vfsstat
.f_fsid
.val
[0] == fsid
->val
[0] &&
6659 mp
->mnt_vfsstat
.f_fsid
.val
[1] == fsid
->val
[1]) {
6662 if (mount_iterref(retmp
, 1)) {
6670 mount_list_unlock();
6676 vnode_lookupat(const char *path
, int flags
, vnode_t
*vpp
, vfs_context_t ctx
,
6679 struct nameidata
*ndp
;
6681 u_int32_t ndflags
= 0;
6687 ndp
= kheap_alloc(KHEAP_TEMP
, sizeof(struct nameidata
), Z_WAITOK
);
6692 if (flags
& VNODE_LOOKUP_NOFOLLOW
) {
6698 if (flags
& VNODE_LOOKUP_NOCROSSMOUNT
) {
6699 ndflags
|= NOCROSSMOUNT
;
6702 if (flags
& VNODE_LOOKUP_CROSSMOUNTNOWAIT
) {
6703 ndflags
|= CN_NBMOUNTLOOK
;
6706 /* XXX AUDITVNPATH1 needed ? */
6707 NDINIT(ndp
, LOOKUP
, OP_LOOKUP
, ndflags
, UIO_SYSSPACE
,
6708 CAST_USER_ADDR_T(path
), ctx
);
6710 if (start_dvp
&& (path
[0] != '/')) {
6711 ndp
->ni_dvp
= start_dvp
;
6712 ndp
->ni_cnd
.cn_flags
|= USEDVP
;
6715 if ((error
= namei(ndp
))) {
6719 ndp
->ni_cnd
.cn_flags
&= ~USEDVP
;
6725 kheap_free(KHEAP_TEMP
, ndp
, sizeof(struct nameidata
));
6730 vnode_lookup(const char *path
, int flags
, vnode_t
*vpp
, vfs_context_t ctx
)
6732 return vnode_lookupat(path
, flags
, vpp
, ctx
, NULLVP
);
6736 vnode_open(const char *path
, int fmode
, int cmode
, int flags
, vnode_t
*vpp
, vfs_context_t ctx
)
6738 struct nameidata
*ndp
= NULL
;
6740 u_int32_t ndflags
= 0;
6743 if (ctx
== NULL
) { /* XXX technically an error */
6744 ctx
= vfs_context_current();
6747 ndp
= kheap_alloc(KHEAP_TEMP
, sizeof(struct nameidata
), Z_WAITOK
);
6752 if (fmode
& O_NOFOLLOW
) {
6753 lflags
|= VNODE_LOOKUP_NOFOLLOW
;
6756 if (lflags
& VNODE_LOOKUP_NOFOLLOW
) {
6762 if (lflags
& VNODE_LOOKUP_NOCROSSMOUNT
) {
6763 ndflags
|= NOCROSSMOUNT
;
6766 if (lflags
& VNODE_LOOKUP_CROSSMOUNTNOWAIT
) {
6767 ndflags
|= CN_NBMOUNTLOOK
;
6770 /* XXX AUDITVNPATH1 needed ? */
6771 NDINIT(ndp
, LOOKUP
, OP_OPEN
, ndflags
, UIO_SYSSPACE
,
6772 CAST_USER_ADDR_T(path
), ctx
);
6774 if ((error
= vn_open(ndp
, fmode
, cmode
))) {
6780 kheap_free(KHEAP_TEMP
, ndp
, sizeof(struct nameidata
));
6785 vnode_close(vnode_t vp
, int flags
, vfs_context_t ctx
)
6790 ctx
= vfs_context_current();
6793 error
= vn_close(vp
, flags
, ctx
);
6799 vnode_mtime(vnode_t vp
, struct timespec
*mtime
, vfs_context_t ctx
)
6801 struct vnode_attr va
;
6805 VATTR_WANTED(&va
, va_modify_time
);
6806 error
= vnode_getattr(vp
, &va
, ctx
);
6808 *mtime
= va
.va_modify_time
;
6814 vnode_flags(vnode_t vp
, uint32_t *flags
, vfs_context_t ctx
)
6816 struct vnode_attr va
;
6820 VATTR_WANTED(&va
, va_flags
);
6821 error
= vnode_getattr(vp
, &va
, ctx
);
6823 *flags
= va
.va_flags
;
6829 * Returns: 0 Success
6833 vnode_size(vnode_t vp
, off_t
*sizep
, vfs_context_t ctx
)
6835 struct vnode_attr va
;
6839 VATTR_WANTED(&va
, va_data_size
);
6840 error
= vnode_getattr(vp
, &va
, ctx
);
6842 *sizep
= va
.va_data_size
;
6848 vnode_setsize(vnode_t vp
, off_t size
, int ioflag
, vfs_context_t ctx
)
6850 struct vnode_attr va
;
6853 VATTR_SET(&va
, va_data_size
, size
);
6854 va
.va_vaflags
= ioflag
& 0xffff;
6855 return vnode_setattr(vp
, &va
, ctx
);
6859 vnode_setdirty(vnode_t vp
)
6861 vnode_lock_spin(vp
);
6862 vp
->v_flag
|= VISDIRTY
;
6868 vnode_cleardirty(vnode_t vp
)
6870 vnode_lock_spin(vp
);
6871 vp
->v_flag
&= ~VISDIRTY
;
6877 vnode_isdirty(vnode_t vp
)
6881 vnode_lock_spin(vp
);
6882 dirty
= (vp
->v_flag
& VISDIRTY
) ? 1 : 0;
6889 vn_create_reg(vnode_t dvp
, vnode_t
*vpp
, struct nameidata
*ndp
, struct vnode_attr
*vap
, uint32_t flags
, int fmode
, uint32_t *statusp
, vfs_context_t ctx
)
6891 /* Only use compound VNOP for compound operation */
6892 if (vnode_compound_open_available(dvp
) && ((flags
& VN_CREATE_DOOPEN
) != 0)) {
6894 return VNOP_COMPOUND_OPEN(dvp
, vpp
, ndp
, O_CREAT
, fmode
, statusp
, vap
, ctx
);
6896 return VNOP_CREATE(dvp
, vpp
, &ndp
->ni_cnd
, vap
, ctx
);
6901 * Create a filesystem object of arbitrary type with arbitrary attributes in
6902 * the spevied directory with the specified name.
6904 * Parameters: dvp Pointer to the vnode of the directory
6905 * in which to create the object.
6906 * vpp Pointer to the area into which to
6907 * return the vnode of the created object.
6908 * cnp Component name pointer from the namei
6909 * data structure, containing the name to
6910 * use for the create object.
6911 * vap Pointer to the vnode_attr structure
6912 * describing the object to be created,
6913 * including the type of object.
6914 * flags VN_* flags controlling ACL inheritance
6915 * and whether or not authorization is to
6916 * be required for the operation.
6918 * Returns: 0 Success
6921 * Implicit: *vpp Contains the vnode of the object that
6922 * was created, if successful.
6923 * *cnp May be modified by the underlying VFS.
6924 * *vap May be modified by the underlying VFS.
6925 * modified by either ACL inheritance or
6928 * be modified, even if the operation is
6931 * Notes: The kauth_filesec_t in 'vap', if any, is in host byte order.
6933 * Modification of '*cnp' and '*vap' by the underlying VFS is
6934 * strongly discouraged.
6936 * XXX: This function is a 'vn_*' function; it belongs in vfs_vnops.c
6938 * XXX: We should enummerate the possible errno values here, and where
6939 * in the code they originated.
6942 vn_create(vnode_t dvp
, vnode_t
*vpp
, struct nameidata
*ndp
, struct vnode_attr
*vap
, uint32_t flags
, int fmode
, uint32_t *statusp
, vfs_context_t ctx
)
6944 errno_t error
, old_error
;
6945 vnode_t vp
= (vnode_t
)0;
6947 struct componentname
*cnp
;
6952 batched
= namei_compound_available(dvp
, ndp
) ? TRUE
: FALSE
;
6954 KAUTH_DEBUG("%p CREATE - '%s'", dvp
, cnp
->cn_nameptr
);
6956 if (flags
& VN_CREATE_NOINHERIT
) {
6957 vap
->va_vaflags
|= VA_NOINHERIT
;
6959 if (flags
& VN_CREATE_NOAUTH
) {
6960 vap
->va_vaflags
|= VA_NOAUTH
;
6963 * Handle ACL inheritance, initialize vap.
6965 error
= vn_attribute_prepare(dvp
, vap
, &defaulted
, ctx
);
6970 if (vap
->va_type
!= VREG
&& (fmode
!= 0 || (flags
& VN_CREATE_DOOPEN
) || statusp
)) {
6971 panic("Open parameters, but not a regular file.");
6973 if ((fmode
!= 0) && ((flags
& VN_CREATE_DOOPEN
) == 0)) {
6974 panic("Mode for open, but not trying to open...");
6979 * Create the requested node.
6981 switch (vap
->va_type
) {
6983 error
= vn_create_reg(dvp
, vpp
, ndp
, vap
, flags
, fmode
, statusp
, ctx
);
6986 error
= vn_mkdir(dvp
, vpp
, ndp
, vap
, ctx
);
6992 error
= VNOP_MKNOD(dvp
, vpp
, cnp
, vap
, ctx
);
6995 panic("vnode_create: unknown vtype %d", vap
->va_type
);
6998 KAUTH_DEBUG("%p CREATE - error %d returned by filesystem", dvp
, error
);
7006 * If some of the requested attributes weren't handled by the VNOP,
7007 * use our fallback code.
7009 if ((error
== 0) && !VATTR_ALL_SUPPORTED(vap
) && *vpp
) {
7010 KAUTH_DEBUG(" CREATE - doing fallback with ACL %p", vap
->va_acl
);
7011 error
= vnode_setattr_fallback(*vpp
, vap
, ctx
);
7015 if ((error
== 0) && !(flags
& VN_CREATE_NOLABEL
)) {
7016 error
= vnode_label(vnode_mount(vp
), dvp
, vp
, cnp
, VNODE_LABEL_CREATE
, ctx
);
7020 if ((error
!= 0) && (vp
!= (vnode_t
)0)) {
7021 /* If we've done a compound open, close */
7022 if (batched
&& (old_error
== 0) && (vap
->va_type
== VREG
)) {
7023 VNOP_CLOSE(vp
, fmode
, ctx
);
7026 /* Need to provide notifications if a create succeeded */
7035 * For creation VNOPs, this is the equivalent of
7036 * lookup_handle_found_vnode.
7038 if (kdebug_enable
&& *vpp
) {
7039 kdebug_lookup(*vpp
, cnp
);
7043 vn_attribute_cleanup(vap
, defaulted
);
7048 static kauth_scope_t vnode_scope
;
7049 static int vnode_authorize_callback(kauth_cred_t credential
, void *idata
, kauth_action_t action
,
7050 uintptr_t arg0
, uintptr_t arg1
, uintptr_t arg2
, uintptr_t arg3
);
7051 static int vnode_authorize_callback_int(kauth_action_t action
, vfs_context_t ctx
,
7052 vnode_t vp
, vnode_t dvp
, int *errorp
);
7054 typedef struct _vnode_authorize_context
{
7056 struct vnode_attr
*vap
;
7058 struct vnode_attr
*dvap
;
7062 #define _VAC_IS_OWNER (1<<0)
7063 #define _VAC_IN_GROUP (1<<1)
7064 #define _VAC_IS_DIR_OWNER (1<<2)
7065 #define _VAC_IN_DIR_GROUP (1<<3)
7066 #define _VAC_NO_VNODE_POINTERS (1<<4)
7070 vnode_authorize_init(void)
7072 vnode_scope
= kauth_register_scope(KAUTH_SCOPE_VNODE
, vnode_authorize_callback
, NULL
);
7075 #define VATTR_PREPARE_DEFAULTED_UID 0x1
7076 #define VATTR_PREPARE_DEFAULTED_GID 0x2
7077 #define VATTR_PREPARE_DEFAULTED_MODE 0x4
7080 vn_attribute_prepare(vnode_t dvp
, struct vnode_attr
*vap
, uint32_t *defaulted_fieldsp
, vfs_context_t ctx
)
7082 kauth_acl_t nacl
= NULL
, oacl
= NULL
;
7086 * Handle ACL inheritance.
7088 if (!(vap
->va_vaflags
& VA_NOINHERIT
) && vfs_extendedsecurity(dvp
->v_mount
)) {
7089 /* save the original filesec */
7090 if (VATTR_IS_ACTIVE(vap
, va_acl
)) {
7095 if ((error
= kauth_acl_inherit(dvp
,
7098 vap
->va_type
== VDIR
,
7100 KAUTH_DEBUG("%p CREATE - error %d processing inheritance", dvp
, error
);
7105 * If the generated ACL is NULL, then we can save ourselves some effort
7106 * by clearing the active bit.
7109 VATTR_CLEAR_ACTIVE(vap
, va_acl
);
7111 vap
->va_base_acl
= oacl
;
7112 VATTR_SET(vap
, va_acl
, nacl
);
7116 error
= vnode_authattr_new_internal(dvp
, vap
, (vap
->va_vaflags
& VA_NOAUTH
), defaulted_fieldsp
, ctx
);
7118 vn_attribute_cleanup(vap
, *defaulted_fieldsp
);
7125 vn_attribute_cleanup(struct vnode_attr
*vap
, uint32_t defaulted_fields
)
7128 * If the caller supplied a filesec in vap, it has been replaced
7129 * now by the post-inheritance copy. We need to put the original back
7130 * and free the inherited product.
7132 kauth_acl_t nacl
, oacl
;
7134 if (VATTR_IS_ACTIVE(vap
, va_acl
)) {
7136 oacl
= vap
->va_base_acl
;
7139 VATTR_SET(vap
, va_acl
, oacl
);
7140 vap
->va_base_acl
= NULL
;
7142 VATTR_CLEAR_ACTIVE(vap
, va_acl
);
7146 kauth_acl_free(nacl
);
7150 if ((defaulted_fields
& VATTR_PREPARE_DEFAULTED_MODE
) != 0) {
7151 VATTR_CLEAR_ACTIVE(vap
, va_mode
);
7153 if ((defaulted_fields
& VATTR_PREPARE_DEFAULTED_GID
) != 0) {
7154 VATTR_CLEAR_ACTIVE(vap
, va_gid
);
7156 if ((defaulted_fields
& VATTR_PREPARE_DEFAULTED_UID
) != 0) {
7157 VATTR_CLEAR_ACTIVE(vap
, va_uid
);
7164 vn_authorize_unlink(vnode_t dvp
, vnode_t vp
, struct componentname
*cnp
, vfs_context_t ctx
, __unused
void *reserved
)
7172 * Normally, unlinking of directories is not supported.
7173 * However, some file systems may have limited support.
7175 if ((vp
->v_type
== VDIR
) &&
7176 !(vp
->v_mount
->mnt_kern_flag
& MNTK_DIR_HARDLINKS
)) {
7177 return EPERM
; /* POSIX */
7180 /* authorize the delete operation */
7183 error
= mac_vnode_check_unlink(ctx
, dvp
, vp
, cnp
);
7187 error
= vnode_authorize(vp
, dvp
, KAUTH_VNODE_DELETE
, ctx
);
7194 vn_authorize_open_existing(vnode_t vp
, struct componentname
*cnp
, int fmode
, vfs_context_t ctx
, void *reserved
)
7196 /* Open of existing case */
7197 kauth_action_t action
;
7199 if (cnp
->cn_ndp
== NULL
) {
7202 if (reserved
!= NULL
) {
7203 panic("reserved not NULL.");
7207 /* XXX may do duplicate work here, but ignore that for now (idempotent) */
7208 if (vfs_flags(vnode_mount(vp
)) & MNT_MULTILABEL
) {
7209 error
= vnode_label(vnode_mount(vp
), NULL
, vp
, NULL
, 0, ctx
);
7216 if ((fmode
& O_DIRECTORY
) && vp
->v_type
!= VDIR
) {
7220 if (vp
->v_type
== VSOCK
&& vp
->v_tag
!= VT_FDESC
) {
7221 return EOPNOTSUPP
; /* Operation not supported on socket */
7224 if (vp
->v_type
== VLNK
&& (fmode
& O_NOFOLLOW
) != 0) {
7225 return ELOOP
; /* O_NOFOLLOW was specified and the target is a symbolic link */
7228 /* disallow write operations on directories */
7229 if (vnode_isdir(vp
) && (fmode
& (FWRITE
| O_TRUNC
))) {
7233 if ((cnp
->cn_ndp
->ni_flag
& NAMEI_TRAILINGSLASH
)) {
7234 if (vp
->v_type
!= VDIR
) {
7240 /* If a file being opened is a shadow file containing
7241 * namedstream data, ignore the macf checks because it
7242 * is a kernel internal file and access should always
7245 if (!(vnode_isshadow(vp
) && vnode_isnamedstream(vp
))) {
7246 error
= mac_vnode_check_open(ctx
, vp
, fmode
);
7253 /* compute action to be authorized */
7255 if (fmode
& FREAD
) {
7256 action
|= KAUTH_VNODE_READ_DATA
;
7258 if (fmode
& (FWRITE
| O_TRUNC
)) {
7260 * If we are writing, appending, and not truncating,
7261 * indicate that we are appending so that if the
7262 * UF_APPEND or SF_APPEND bits are set, we do not deny
7265 if ((fmode
& O_APPEND
) && !(fmode
& O_TRUNC
)) {
7266 action
|= KAUTH_VNODE_APPEND_DATA
;
7268 action
|= KAUTH_VNODE_WRITE_DATA
;
7271 error
= vnode_authorize(vp
, NULL
, action
, ctx
);
7273 if (error
== EACCES
) {
7275 * Shadow files may exist on-disk with a different UID/GID
7276 * than that of the current context. Verify that this file
7277 * is really a shadow file. If it was created successfully
7278 * then it should be authorized.
7280 if (vnode_isshadow(vp
) && vnode_isnamedstream(vp
)) {
7281 error
= vnode_verifynamedstream(vp
);
7290 vn_authorize_create(vnode_t dvp
, struct componentname
*cnp
, struct vnode_attr
*vap
, vfs_context_t ctx
, void *reserved
)
7298 if (cnp
->cn_ndp
== NULL
) {
7299 panic("NULL cn_ndp");
7301 if (reserved
!= NULL
) {
7302 panic("reserved not NULL.");
7305 /* Only validate path for creation if we didn't do a complete lookup */
7306 if (cnp
->cn_ndp
->ni_flag
& NAMEI_UNFINISHED
) {
7307 error
= lookup_validate_creation_path(cnp
->cn_ndp
);
7314 error
= mac_vnode_check_create(ctx
, dvp
, cnp
, vap
);
7318 #endif /* CONFIG_MACF */
7320 return vnode_authorize(dvp
, NULL
, KAUTH_VNODE_ADD_FILE
, ctx
);
7324 vn_authorize_rename(struct vnode
*fdvp
, struct vnode
*fvp
, struct componentname
*fcnp
,
7325 struct vnode
*tdvp
, struct vnode
*tvp
, struct componentname
*tcnp
,
7326 vfs_context_t ctx
, void *reserved
)
7328 return vn_authorize_renamex(fdvp
, fvp
, fcnp
, tdvp
, tvp
, tcnp
, ctx
, 0, reserved
);
7332 vn_authorize_renamex(struct vnode
*fdvp
, struct vnode
*fvp
, struct componentname
*fcnp
,
7333 struct vnode
*tdvp
, struct vnode
*tvp
, struct componentname
*tcnp
,
7334 vfs_context_t ctx
, vfs_rename_flags_t flags
, void *reserved
)
7336 return vn_authorize_renamex_with_paths(fdvp
, fvp
, fcnp
, NULL
, tdvp
, tvp
, tcnp
, NULL
, ctx
, flags
, reserved
);
7340 vn_authorize_renamex_with_paths(struct vnode
*fdvp
, struct vnode
*fvp
, struct componentname
*fcnp
, const char *from_path
,
7341 struct vnode
*tdvp
, struct vnode
*tvp
, struct componentname
*tcnp
, const char *to_path
,
7342 vfs_context_t ctx
, vfs_rename_flags_t flags
, void *reserved
)
7346 bool swap
= flags
& VFS_RENAME_SWAP
;
7348 if (reserved
!= NULL
) {
7349 panic("Passed something other than NULL as reserved field!");
7353 * Avoid renaming "." and "..".
7355 * XXX No need to check for this in the FS. We should always have the leaves
7356 * in VFS in this case.
7358 if (fvp
->v_type
== VDIR
&&
7360 (fcnp
->cn_namelen
== 1 && fcnp
->cn_nameptr
[0] == '.') ||
7361 ((fcnp
->cn_flags
| tcnp
->cn_flags
) & ISDOTDOT
))) {
7366 if (tvp
== NULLVP
&& vnode_compound_rename_available(tdvp
)) {
7367 error
= lookup_validate_creation_path(tcnp
->cn_ndp
);
7373 /***** <MACF> *****/
7375 error
= mac_vnode_check_rename(ctx
, fdvp
, fvp
, fcnp
, tdvp
, tvp
, tcnp
);
7380 error
= mac_vnode_check_rename(ctx
, tdvp
, tvp
, tcnp
, fdvp
, fvp
, fcnp
);
7386 /***** </MACF> *****/
7388 /***** <MiscChecks> *****/
7391 if (fvp
->v_type
== VDIR
&& tvp
->v_type
!= VDIR
) {
7394 } else if (fvp
->v_type
!= VDIR
&& tvp
->v_type
== VDIR
) {
7401 * Caller should have already checked this and returned
7402 * ENOENT. If we send back ENOENT here, caller will retry
7403 * which isn't what we want so we send back EINVAL here
7416 * The following edge case is caught here:
7417 * (to cannot be a descendent of from)
7430 if (tdvp
->v_parent
== fvp
) {
7435 if (swap
&& fdvp
->v_parent
== tvp
) {
7439 /***** </MiscChecks> *****/
7441 /***** <Kauth> *****/
7444 * As part of the Kauth step, we call out to allow 3rd-party
7445 * fileop notification of "about to rename". This is needed
7446 * in the event that 3rd-parties need to know that the DELETE
7447 * authorization is actually part of a rename. It's important
7448 * that we guarantee that the DELETE call-out will always be
7449 * made if the WILL_RENAME call-out is made. Another fileop
7450 * call-out will be performed once the operation is completed.
7451 * We can ignore the result of kauth_authorize_fileop().
7453 * N.B. We are passing the vnode and *both* paths to each
7454 * call; kauth_authorize_fileop() extracts the "from" path
7455 * when posting a KAUTH_FILEOP_WILL_RENAME notification.
7456 * As such, we only post these notifications if all of the
7457 * information we need is provided.
7461 kauth_action_t f
= 0, t
= 0;
7464 * Directories changing parents need ...ADD_SUBDIR... to
7465 * permit changing ".."
7468 if (vnode_isdir(fvp
)) {
7469 f
= KAUTH_VNODE_ADD_SUBDIRECTORY
;
7471 if (vnode_isdir(tvp
)) {
7472 t
= KAUTH_VNODE_ADD_SUBDIRECTORY
;
7475 if (to_path
!= NULL
) {
7476 kauth_authorize_fileop(vfs_context_ucred(ctx
),
7477 KAUTH_FILEOP_WILL_RENAME
,
7479 (uintptr_t)to_path
);
7481 error
= vnode_authorize(fvp
, fdvp
, KAUTH_VNODE_DELETE
| f
, ctx
);
7485 if (from_path
!= NULL
) {
7486 kauth_authorize_fileop(vfs_context_ucred(ctx
),
7487 KAUTH_FILEOP_WILL_RENAME
,
7489 (uintptr_t)from_path
);
7491 error
= vnode_authorize(tvp
, tdvp
, KAUTH_VNODE_DELETE
| t
, ctx
);
7495 f
= vnode_isdir(fvp
) ? KAUTH_VNODE_ADD_SUBDIRECTORY
: KAUTH_VNODE_ADD_FILE
;
7496 t
= vnode_isdir(tvp
) ? KAUTH_VNODE_ADD_SUBDIRECTORY
: KAUTH_VNODE_ADD_FILE
;
7498 error
= vnode_authorize(fdvp
, NULL
, f
| t
, ctx
);
7500 error
= vnode_authorize(fdvp
, NULL
, t
, ctx
);
7504 error
= vnode_authorize(tdvp
, NULL
, f
, ctx
);
7511 if ((tvp
!= NULL
) && vnode_isdir(tvp
)) {
7515 } else if (tdvp
!= fdvp
) {
7520 * must have delete rights to remove the old name even in
7521 * the simple case of fdvp == tdvp.
7523 * If fvp is a directory, and we are changing it's parent,
7524 * then we also need rights to rewrite its ".." entry as well.
7526 if (to_path
!= NULL
) {
7527 kauth_authorize_fileop(vfs_context_ucred(ctx
),
7528 KAUTH_FILEOP_WILL_RENAME
,
7530 (uintptr_t)to_path
);
7532 if (vnode_isdir(fvp
)) {
7533 if ((error
= vnode_authorize(fvp
, fdvp
, KAUTH_VNODE_DELETE
| KAUTH_VNODE_ADD_SUBDIRECTORY
, ctx
)) != 0) {
7537 if ((error
= vnode_authorize(fvp
, fdvp
, KAUTH_VNODE_DELETE
, ctx
)) != 0) {
7542 /* moving into tdvp or tvp, must have rights to add */
7543 if ((error
= vnode_authorize(((tvp
!= NULL
) && vnode_isdir(tvp
)) ? tvp
: tdvp
,
7545 vnode_isdir(fvp
) ? KAUTH_VNODE_ADD_SUBDIRECTORY
: KAUTH_VNODE_ADD_FILE
,
7550 /* node staying in same directory, must be allowed to add new name */
7551 if ((error
= vnode_authorize(fdvp
, NULL
,
7552 vnode_isdir(fvp
) ? KAUTH_VNODE_ADD_SUBDIRECTORY
: KAUTH_VNODE_ADD_FILE
, ctx
)) != 0) {
7556 /* overwriting tvp */
7557 if ((tvp
!= NULL
) && !vnode_isdir(tvp
) &&
7558 ((error
= vnode_authorize(tvp
, tdvp
, KAUTH_VNODE_DELETE
, ctx
)) != 0)) {
7563 /***** </Kauth> *****/
7565 /* XXX more checks? */
7571 vn_authorize_mkdir(vnode_t dvp
, struct componentname
*cnp
, struct vnode_attr
*vap
, vfs_context_t ctx
, void *reserved
)
7578 if (reserved
!= NULL
) {
7579 panic("reserved not NULL in vn_authorize_mkdir()");
7582 /* XXX A hack for now, to make shadow files work */
7583 if (cnp
->cn_ndp
== NULL
) {
7587 if (vnode_compound_mkdir_available(dvp
)) {
7588 error
= lookup_validate_creation_path(cnp
->cn_ndp
);
7595 error
= mac_vnode_check_create(ctx
,
7602 /* authorize addition of a directory to the parent */
7603 if ((error
= vnode_authorize(dvp
, NULL
, KAUTH_VNODE_ADD_SUBDIRECTORY
, ctx
)) != 0) {
7612 vn_authorize_rmdir(vnode_t dvp
, vnode_t vp
, struct componentname
*cnp
, vfs_context_t ctx
, void *reserved
)
7619 if (reserved
!= NULL
) {
7620 panic("Non-NULL reserved argument to vn_authorize_rmdir()");
7623 if (vp
->v_type
!= VDIR
) {
7625 * rmdir only deals with directories
7632 * No rmdir "." please.
7638 error
= mac_vnode_check_unlink(ctx
, dvp
,
7645 return vnode_authorize(vp
, dvp
, KAUTH_VNODE_DELETE
, ctx
);
7649 * Authorizer for directory cloning. This does not use vnodes but instead
7650 * uses prefilled vnode attributes from the filesystem.
7652 * The same function is called to set up the attributes required, perform the
7653 * authorization and cleanup (if required)
7656 vnode_attr_authorize_dir_clone(struct vnode_attr
*vap
, kauth_action_t action
,
7657 struct vnode_attr
*dvap
, __unused vnode_t sdvp
, mount_t mp
,
7658 dir_clone_authorizer_op_t vattr_op
, uint32_t flags
, vfs_context_t ctx
,
7659 __unused
void *reserved
)
7662 int is_suser
= vfs_context_issuser(ctx
);
7664 if (vattr_op
== OP_VATTR_SETUP
) {
7668 * When ACL inheritence is implemented, both vap->va_acl and
7669 * dvap->va_acl will be required (even as superuser).
7671 VATTR_WANTED(vap
, va_type
);
7672 VATTR_WANTED(vap
, va_mode
);
7673 VATTR_WANTED(vap
, va_flags
);
7674 VATTR_WANTED(vap
, va_uid
);
7675 VATTR_WANTED(vap
, va_gid
);
7678 VATTR_WANTED(dvap
, va_flags
);
7683 * If not superuser, we have to evaluate ACLs and
7684 * need the target directory gid to set the initial
7685 * gid of the new object.
7687 VATTR_WANTED(vap
, va_acl
);
7689 VATTR_WANTED(dvap
, va_gid
);
7691 } else if (dvap
&& (flags
& VNODE_CLONEFILE_NOOWNERCOPY
)) {
7692 VATTR_WANTED(dvap
, va_gid
);
7695 } else if (vattr_op
== OP_VATTR_CLEANUP
) {
7696 return 0; /* Nothing to do for now */
7699 /* dvap isn't used for authorization */
7700 error
= vnode_attr_authorize(vap
, NULL
, mp
, action
, ctx
);
7707 * vn_attribute_prepare should be able to accept attributes as well as
7708 * vnodes but for now we do this inline.
7710 if (!is_suser
|| (flags
& VNODE_CLONEFILE_NOOWNERCOPY
)) {
7712 * If the filesystem is mounted IGNORE_OWNERSHIP and an explicit
7713 * owner is set, that owner takes ownership of all new files.
7715 if ((mp
->mnt_flag
& MNT_IGNORE_OWNERSHIP
) &&
7716 (mp
->mnt_fsowner
!= KAUTH_UID_NONE
)) {
7717 VATTR_SET(vap
, va_uid
, mp
->mnt_fsowner
);
7719 /* default owner is current user */
7720 VATTR_SET(vap
, va_uid
,
7721 kauth_cred_getuid(vfs_context_ucred(ctx
)));
7724 if ((mp
->mnt_flag
& MNT_IGNORE_OWNERSHIP
) &&
7725 (mp
->mnt_fsgroup
!= KAUTH_GID_NONE
)) {
7726 VATTR_SET(vap
, va_gid
, mp
->mnt_fsgroup
);
7729 * default group comes from parent object,
7730 * fallback to current user
7732 if (VATTR_IS_SUPPORTED(dvap
, va_gid
)) {
7733 VATTR_SET(vap
, va_gid
, dvap
->va_gid
);
7735 VATTR_SET(vap
, va_gid
,
7736 kauth_cred_getgid(vfs_context_ucred(ctx
)));
7741 /* Inherit SF_RESTRICTED bit from destination directory only */
7742 if (VATTR_IS_ACTIVE(vap
, va_flags
)) {
7743 VATTR_SET(vap
, va_flags
,
7744 ((vap
->va_flags
& ~(UF_DATAVAULT
| SF_RESTRICTED
)))); /* Turn off from source */
7745 if (VATTR_IS_ACTIVE(dvap
, va_flags
)) {
7746 VATTR_SET(vap
, va_flags
,
7747 vap
->va_flags
| (dvap
->va_flags
& (UF_DATAVAULT
| SF_RESTRICTED
)));
7749 } else if (VATTR_IS_ACTIVE(dvap
, va_flags
)) {
7750 VATTR_SET(vap
, va_flags
, (dvap
->va_flags
& (UF_DATAVAULT
| SF_RESTRICTED
)));
7758 * Authorize an operation on a vnode.
7760 * This is KPI, but here because it needs vnode_scope.
7762 * Returns: 0 Success
7763 * kauth_authorize_action:EPERM ...
7764 * xlate => EACCES Permission denied
7765 * kauth_authorize_action:0 Success
7766 * kauth_authorize_action: Depends on callback return; this is
7767 * usually only vnode_authorize_callback(),
7768 * but may include other listerners, if any
7776 vnode_authorize(vnode_t vp
, vnode_t dvp
, kauth_action_t action
, vfs_context_t ctx
)
7781 * We can't authorize against a dead vnode; allow all operations through so that
7782 * the correct error can be returned.
7784 if (vp
->v_type
== VBAD
) {
7789 result
= kauth_authorize_action(vnode_scope
, vfs_context_ucred(ctx
), action
,
7790 (uintptr_t)ctx
, (uintptr_t)vp
, (uintptr_t)dvp
, (uintptr_t)&error
);
7791 if (result
== EPERM
) { /* traditional behaviour */
7794 /* did the lower layers give a better error return? */
7795 if ((result
!= 0) && (error
!= 0)) {
7802 * Test for vnode immutability.
7804 * The 'append' flag is set when the authorization request is constrained
7805 * to operations which only request the right to append to a file.
7807 * The 'ignore' flag is set when an operation modifying the immutability flags
7808 * is being authorized. We check the system securelevel to determine which
7809 * immutability flags we can ignore.
7812 vnode_immutable(struct vnode_attr
*vap
, int append
, int ignore
)
7816 /* start with all bits precluding the operation */
7817 mask
= IMMUTABLE
| APPEND
;
7819 /* if appending only, remove the append-only bits */
7824 /* ignore only set when authorizing flags changes */
7826 if (securelevel
<= 0) {
7827 /* in insecure state, flags do not inhibit changes */
7830 /* in secure state, user flags don't inhibit */
7831 mask
&= ~(UF_IMMUTABLE
| UF_APPEND
);
7834 KAUTH_DEBUG("IMMUTABLE - file flags 0x%x mask 0x%x append = %d ignore = %d", vap
->va_flags
, mask
, append
, ignore
);
7835 if ((vap
->va_flags
& mask
) != 0) {
7842 vauth_node_owner(struct vnode_attr
*vap
, kauth_cred_t cred
)
7846 /* default assumption is not-owner */
7850 * If the filesystem has given us a UID, we treat this as authoritative.
7852 if (vap
&& VATTR_IS_SUPPORTED(vap
, va_uid
)) {
7853 result
= (vap
->va_uid
== kauth_cred_getuid(cred
)) ? 1 : 0;
7855 /* we could test the owner UUID here if we had a policy for it */
7863 * Description: Ask if a cred is a member of the group owning the vnode object
7865 * Parameters: vap vnode attribute
7866 * vap->va_gid group owner of vnode object
7867 * cred credential to check
7868 * ismember pointer to where to put the answer
7869 * idontknow Return this if we can't get an answer
7871 * Returns: 0 Success
7872 * idontknow Can't get information
7873 * kauth_cred_ismember_gid:? Error from kauth subsystem
7874 * kauth_cred_ismember_gid:? Error from kauth subsystem
7877 vauth_node_group(struct vnode_attr
*vap
, kauth_cred_t cred
, int *ismember
, int idontknow
)
7886 * The caller is expected to have asked the filesystem for a group
7887 * at some point prior to calling this function. The answer may
7888 * have been that there is no group ownership supported for the
7889 * vnode object, in which case we return
7891 if (vap
&& VATTR_IS_SUPPORTED(vap
, va_gid
)) {
7892 error
= kauth_cred_ismember_gid(cred
, vap
->va_gid
, &result
);
7894 * Credentials which are opted into external group membership
7895 * resolution which are not known to the external resolver
7896 * will result in an ENOENT error. We translate this into
7897 * the appropriate 'idontknow' response for our caller.
7899 * XXX We do not make a distinction here between an ENOENT
7900 * XXX arising from a response from the external resolver,
7901 * XXX and an ENOENT which is internally generated. This is
7902 * XXX a deficiency of the published kauth_cred_ismember_gid()
7903 * XXX KPI which can not be overcome without new KPI. For
7904 * XXX all currently known cases, however, this wil result
7905 * XXX in correct behaviour.
7907 if (error
== ENOENT
) {
7912 * XXX We could test the group UUID here if we had a policy for it,
7913 * XXX but this is problematic from the perspective of synchronizing
7914 * XXX group UUID and POSIX GID ownership of a file and keeping the
7915 * XXX values coherent over time. The problem is that the local
7916 * XXX system will vend transient group UUIDs for unknown POSIX GID
7917 * XXX values, and these are not persistent, whereas storage of values
7918 * XXX is persistent. One potential solution to this is a local
7919 * XXX (persistent) replica of remote directory entries and vended
7920 * XXX local ids in a local directory server (think in terms of a
7921 * XXX caching DNS server).
7931 vauth_file_owner(vauth_ctx vcp
)
7935 if (vcp
->flags_valid
& _VAC_IS_OWNER
) {
7936 result
= (vcp
->flags
& _VAC_IS_OWNER
) ? 1 : 0;
7938 result
= vauth_node_owner(vcp
->vap
, vcp
->ctx
->vc_ucred
);
7940 /* cache our result */
7941 vcp
->flags_valid
|= _VAC_IS_OWNER
;
7943 vcp
->flags
|= _VAC_IS_OWNER
;
7945 vcp
->flags
&= ~_VAC_IS_OWNER
;
7953 * vauth_file_ingroup
7955 * Description: Ask if a user is a member of the group owning the directory
7957 * Parameters: vcp The vnode authorization context that
7958 * contains the user and directory info
7959 * vcp->flags_valid Valid flags
7960 * vcp->flags Flags values
7961 * vcp->vap File vnode attributes
7962 * vcp->ctx VFS Context (for user)
7963 * ismember pointer to where to put the answer
7964 * idontknow Return this if we can't get an answer
7966 * Returns: 0 Success
7967 * vauth_node_group:? Error from vauth_node_group()
7969 * Implicit returns: *ismember 0 The user is not a group member
7970 * 1 The user is a group member
7973 vauth_file_ingroup(vauth_ctx vcp
, int *ismember
, int idontknow
)
7977 /* Check for a cached answer first, to avoid the check if possible */
7978 if (vcp
->flags_valid
& _VAC_IN_GROUP
) {
7979 *ismember
= (vcp
->flags
& _VAC_IN_GROUP
) ? 1 : 0;
7982 /* Otherwise, go look for it */
7983 error
= vauth_node_group(vcp
->vap
, vcp
->ctx
->vc_ucred
, ismember
, idontknow
);
7986 /* cache our result */
7987 vcp
->flags_valid
|= _VAC_IN_GROUP
;
7989 vcp
->flags
|= _VAC_IN_GROUP
;
7991 vcp
->flags
&= ~_VAC_IN_GROUP
;
7999 vauth_dir_owner(vauth_ctx vcp
)
8003 if (vcp
->flags_valid
& _VAC_IS_DIR_OWNER
) {
8004 result
= (vcp
->flags
& _VAC_IS_DIR_OWNER
) ? 1 : 0;
8006 result
= vauth_node_owner(vcp
->dvap
, vcp
->ctx
->vc_ucred
);
8008 /* cache our result */
8009 vcp
->flags_valid
|= _VAC_IS_DIR_OWNER
;
8011 vcp
->flags
|= _VAC_IS_DIR_OWNER
;
8013 vcp
->flags
&= ~_VAC_IS_DIR_OWNER
;
8022 * Description: Ask if a user is a member of the group owning the directory
8024 * Parameters: vcp The vnode authorization context that
8025 * contains the user and directory info
8026 * vcp->flags_valid Valid flags
8027 * vcp->flags Flags values
8028 * vcp->dvap Dir vnode attributes
8029 * vcp->ctx VFS Context (for user)
8030 * ismember pointer to where to put the answer
8031 * idontknow Return this if we can't get an answer
8033 * Returns: 0 Success
8034 * vauth_node_group:? Error from vauth_node_group()
8036 * Implicit returns: *ismember 0 The user is not a group member
8037 * 1 The user is a group member
8040 vauth_dir_ingroup(vauth_ctx vcp
, int *ismember
, int idontknow
)
8044 /* Check for a cached answer first, to avoid the check if possible */
8045 if (vcp
->flags_valid
& _VAC_IN_DIR_GROUP
) {
8046 *ismember
= (vcp
->flags
& _VAC_IN_DIR_GROUP
) ? 1 : 0;
8049 /* Otherwise, go look for it */
8050 error
= vauth_node_group(vcp
->dvap
, vcp
->ctx
->vc_ucred
, ismember
, idontknow
);
8053 /* cache our result */
8054 vcp
->flags_valid
|= _VAC_IN_DIR_GROUP
;
8056 vcp
->flags
|= _VAC_IN_DIR_GROUP
;
8058 vcp
->flags
&= ~_VAC_IN_DIR_GROUP
;
8066 * Test the posix permissions in (vap) to determine whether (credential)
8067 * may perform (action)
8070 vnode_authorize_posix(vauth_ctx vcp
, int action
, int on_dir
)
8072 struct vnode_attr
*vap
;
8073 int needed
, error
, owner_ok
, group_ok
, world_ok
, ismember
;
8074 #ifdef KAUTH_DEBUG_ENABLE
8075 const char *where
= "uninitialized";
8076 # define _SETWHERE(c) where = c;
8078 # define _SETWHERE(c)
8081 /* checking file or directory? */
8091 * We want to do as little work here as possible. So first we check
8092 * which sets of permissions grant us the access we need, and avoid checking
8093 * whether specific permissions grant access when more generic ones would.
8096 /* owner permissions */
8098 if (action
& VREAD
) {
8101 if (action
& VWRITE
) {
8104 if (action
& VEXEC
) {
8107 owner_ok
= (needed
& vap
->va_mode
) == needed
;
8110 * Processes with the appropriate entitlement can marked themselves as
8111 * ignoring file/directory permissions if they own it.
8113 if (!owner_ok
&& proc_ignores_node_permissions(vfs_context_proc(vcp
->ctx
))) {
8117 /* group permissions */
8119 if (action
& VREAD
) {
8122 if (action
& VWRITE
) {
8125 if (action
& VEXEC
) {
8128 group_ok
= (needed
& vap
->va_mode
) == needed
;
8130 /* world permissions */
8132 if (action
& VREAD
) {
8135 if (action
& VWRITE
) {
8138 if (action
& VEXEC
) {
8141 world_ok
= (needed
& vap
->va_mode
) == needed
;
8143 /* If granted/denied by all three, we're done */
8144 if (owner_ok
&& group_ok
&& world_ok
) {
8149 if (!owner_ok
&& !group_ok
&& !world_ok
) {
8155 /* Check ownership (relatively cheap) */
8156 if ((on_dir
&& vauth_dir_owner(vcp
)) ||
8157 (!on_dir
&& vauth_file_owner(vcp
))) {
8165 /* Not owner; if group and world both grant it we're done */
8166 if (group_ok
&& world_ok
) {
8167 _SETWHERE("group/world");
8170 if (!group_ok
&& !world_ok
) {
8171 _SETWHERE("group/world");
8176 /* Check group membership (most expensive) */
8177 ismember
= 0; /* Default to allow, if the target has no group owner */
8180 * In the case we can't get an answer about the user from the call to
8181 * vauth_dir_ingroup() or vauth_file_ingroup(), we want to fail on
8182 * the side of caution, rather than simply granting access, or we will
8183 * fail to correctly implement exclusion groups, so we set the third
8184 * parameter on the basis of the state of 'group_ok'.
8187 error
= vauth_dir_ingroup(vcp
, &ismember
, (!group_ok
? EACCES
: 0));
8189 error
= vauth_file_ingroup(vcp
, &ismember
, (!group_ok
? EACCES
: 0));
8205 /* Not owner, not in group, use world result */
8214 KAUTH_DEBUG("%p %s - posix %s permissions : need %s%s%s %x have %s%s%s%s%s%s%s%s%s UID = %d file = %d,%d",
8215 vcp
->vp
, (error
== 0) ? "ALLOWED" : "DENIED", where
,
8216 (action
& VREAD
) ? "r" : "-",
8217 (action
& VWRITE
) ? "w" : "-",
8218 (action
& VEXEC
) ? "x" : "-",
8220 (vap
->va_mode
& S_IRUSR
) ? "r" : "-",
8221 (vap
->va_mode
& S_IWUSR
) ? "w" : "-",
8222 (vap
->va_mode
& S_IXUSR
) ? "x" : "-",
8223 (vap
->va_mode
& S_IRGRP
) ? "r" : "-",
8224 (vap
->va_mode
& S_IWGRP
) ? "w" : "-",
8225 (vap
->va_mode
& S_IXGRP
) ? "x" : "-",
8226 (vap
->va_mode
& S_IROTH
) ? "r" : "-",
8227 (vap
->va_mode
& S_IWOTH
) ? "w" : "-",
8228 (vap
->va_mode
& S_IXOTH
) ? "x" : "-",
8229 kauth_cred_getuid(vcp
->ctx
->vc_ucred
),
8230 on_dir
? vcp
->dvap
->va_uid
: vcp
->vap
->va_uid
,
8231 on_dir
? vcp
->dvap
->va_gid
: vcp
->vap
->va_gid
);
8236 * Authorize the deletion of the node vp from the directory dvp.
8239 * - Neither the node nor the directory are immutable.
8240 * - The user is not the superuser.
8242 * The precedence of factors for authorizing or denying delete for a credential
8244 * 1) Explicit ACE on the node. (allow or deny DELETE)
8245 * 2) Explicit ACE on the directory (allow or deny DELETE_CHILD).
8247 * If there are conflicting ACEs on the node and the directory, the node
8250 * 3) Sticky bit on the directory.
8251 * Deletion is not permitted if the directory is sticky and the caller is
8252 * not owner of the node or directory. The sticky bit rules are like a deny
8253 * delete ACE except lower in priority than ACL's either allowing or denying
8256 * 4) POSIX permisions on the directory.
8258 * As an optimization, we cache whether or not delete child is permitted
8259 * on directories. This enables us to skip directory ACL and POSIX checks
8260 * as we already have the result from those checks. However, we always check the
8261 * node ACL and, if the directory has the sticky bit set, we always check its
8262 * ACL (even for a directory with an authorized delete child). Furthermore,
8263 * caching the delete child authorization is independent of the sticky bit
8264 * being set as it is only applicable in determining whether the node can be
8268 vnode_authorize_delete(vauth_ctx vcp
, boolean_t cached_delete_child
)
8270 struct vnode_attr
*vap
= vcp
->vap
;
8271 struct vnode_attr
*dvap
= vcp
->dvap
;
8272 kauth_cred_t cred
= vcp
->ctx
->vc_ucred
;
8273 struct kauth_acl_eval eval
;
8274 int error
, ismember
;
8276 /* Check the ACL on the node first */
8277 if (VATTR_IS_NOT(vap
, va_acl
, NULL
)) {
8278 eval
.ae_requested
= KAUTH_VNODE_DELETE
;
8279 eval
.ae_acl
= &vap
->va_acl
->acl_ace
[0];
8280 eval
.ae_count
= vap
->va_acl
->acl_entrycount
;
8281 eval
.ae_options
= 0;
8282 if (vauth_file_owner(vcp
)) {
8283 eval
.ae_options
|= KAUTH_AEVAL_IS_OWNER
;
8286 * We use ENOENT as a marker to indicate we could not get
8287 * information in order to delay evaluation until after we
8288 * have the ACL evaluation answer. Previously, we would
8289 * always deny the operation at this point.
8291 if ((error
= vauth_file_ingroup(vcp
, &ismember
, ENOENT
)) != 0 && error
!= ENOENT
) {
8294 if (error
== ENOENT
) {
8295 eval
.ae_options
|= KAUTH_AEVAL_IN_GROUP_UNKNOWN
;
8296 } else if (ismember
) {
8297 eval
.ae_options
|= KAUTH_AEVAL_IN_GROUP
;
8299 eval
.ae_exp_gall
= KAUTH_VNODE_GENERIC_ALL_BITS
;
8300 eval
.ae_exp_gread
= KAUTH_VNODE_GENERIC_READ_BITS
;
8301 eval
.ae_exp_gwrite
= KAUTH_VNODE_GENERIC_WRITE_BITS
;
8302 eval
.ae_exp_gexec
= KAUTH_VNODE_GENERIC_EXECUTE_BITS
;
8304 if ((error
= kauth_acl_evaluate(cred
, &eval
)) != 0) {
8305 KAUTH_DEBUG("%p ERROR during ACL processing - %d", vcp
->vp
, error
);
8309 switch (eval
.ae_result
) {
8310 case KAUTH_RESULT_DENY
:
8311 if (vauth_file_owner(vcp
) && proc_ignores_node_permissions(vfs_context_proc(vcp
->ctx
))) {
8312 KAUTH_DEBUG("%p Override DENY due to entitlement", vcp
->vp
);
8315 KAUTH_DEBUG("%p DENIED - denied by ACL", vcp
->vp
);
8317 case KAUTH_RESULT_ALLOW
:
8318 KAUTH_DEBUG("%p ALLOWED - granted by ACL", vcp
->vp
);
8320 case KAUTH_RESULT_DEFER
:
8322 /* Defer to directory */
8323 KAUTH_DEBUG("%p DEFERRED - by file ACL", vcp
->vp
);
8329 * Without a sticky bit, a previously authorized delete child is
8330 * sufficient to authorize this delete.
8332 * If the sticky bit is set, a directory ACL which allows delete child
8333 * overrides a (potential) sticky bit deny. The authorized delete child
8334 * cannot tell us if it was authorized because of an explicit delete
8335 * child allow ACE or because of POSIX permisions so we have to check
8336 * the directory ACL everytime if the directory has a sticky bit.
8338 if (!(dvap
->va_mode
& S_ISTXT
) && cached_delete_child
) {
8339 KAUTH_DEBUG("%p ALLOWED - granted by directory ACL or POSIX permissions and no sticky bit on directory", vcp
->vp
);
8343 /* check the ACL on the directory */
8344 if (VATTR_IS_NOT(dvap
, va_acl
, NULL
)) {
8345 eval
.ae_requested
= KAUTH_VNODE_DELETE_CHILD
;
8346 eval
.ae_acl
= &dvap
->va_acl
->acl_ace
[0];
8347 eval
.ae_count
= dvap
->va_acl
->acl_entrycount
;
8348 eval
.ae_options
= 0;
8349 if (vauth_dir_owner(vcp
)) {
8350 eval
.ae_options
|= KAUTH_AEVAL_IS_OWNER
;
8353 * We use ENOENT as a marker to indicate we could not get
8354 * information in order to delay evaluation until after we
8355 * have the ACL evaluation answer. Previously, we would
8356 * always deny the operation at this point.
8358 if ((error
= vauth_dir_ingroup(vcp
, &ismember
, ENOENT
)) != 0 && error
!= ENOENT
) {
8361 if (error
== ENOENT
) {
8362 eval
.ae_options
|= KAUTH_AEVAL_IN_GROUP_UNKNOWN
;
8363 } else if (ismember
) {
8364 eval
.ae_options
|= KAUTH_AEVAL_IN_GROUP
;
8366 eval
.ae_exp_gall
= KAUTH_VNODE_GENERIC_ALL_BITS
;
8367 eval
.ae_exp_gread
= KAUTH_VNODE_GENERIC_READ_BITS
;
8368 eval
.ae_exp_gwrite
= KAUTH_VNODE_GENERIC_WRITE_BITS
;
8369 eval
.ae_exp_gexec
= KAUTH_VNODE_GENERIC_EXECUTE_BITS
;
8372 * If there is no entry, we are going to defer to other
8373 * authorization mechanisms.
8375 error
= kauth_acl_evaluate(cred
, &eval
);
8378 KAUTH_DEBUG("%p ERROR during ACL processing - %d", vcp
->vp
, error
);
8381 switch (eval
.ae_result
) {
8382 case KAUTH_RESULT_DENY
:
8383 if (vauth_dir_owner(vcp
) && proc_ignores_node_permissions(vfs_context_proc(vcp
->ctx
))) {
8384 KAUTH_DEBUG("%p Override DENY due to entitlement", vcp
->vp
);
8387 KAUTH_DEBUG("%p DENIED - denied by directory ACL", vcp
->vp
);
8389 case KAUTH_RESULT_ALLOW
:
8390 KAUTH_DEBUG("%p ALLOWED - granted by directory ACL", vcp
->vp
);
8391 if (!cached_delete_child
&& vcp
->dvp
) {
8392 vnode_cache_authorized_action(vcp
->dvp
,
8393 vcp
->ctx
, KAUTH_VNODE_DELETE_CHILD
);
8396 case KAUTH_RESULT_DEFER
:
8398 /* Deferred by directory ACL */
8399 KAUTH_DEBUG("%p DEFERRED - directory ACL", vcp
->vp
);
8405 * From this point, we can't explicitly allow and if we reach the end
8406 * of the function without a denial, then the delete is authorized.
8408 if (!cached_delete_child
) {
8409 if (vnode_authorize_posix(vcp
, VWRITE
, 1 /* on_dir */) != 0) {
8410 KAUTH_DEBUG("%p DENIED - denied by posix permisssions", vcp
->vp
);
8414 * Cache the authorized action on the vnode if allowed by the
8415 * directory ACL or POSIX permissions. It is correct to cache
8416 * this action even if sticky bit would deny deleting the node.
8419 vnode_cache_authorized_action(vcp
->dvp
, vcp
->ctx
,
8420 KAUTH_VNODE_DELETE_CHILD
);
8424 /* enforce sticky bit behaviour */
8425 if ((dvap
->va_mode
& S_ISTXT
) && !vauth_file_owner(vcp
) && !vauth_dir_owner(vcp
)) {
8426 KAUTH_DEBUG("%p DENIED - sticky bit rules (user %d file %d dir %d)",
8427 vcp
->vp
, cred
->cr_posix
.cr_uid
, vap
->va_uid
, dvap
->va_uid
);
8431 /* not denied, must be OK */
8437 * Authorize an operation based on the node's attributes.
8440 vnode_authorize_simple(vauth_ctx vcp
, kauth_ace_rights_t acl_rights
, kauth_ace_rights_t preauth_rights
, boolean_t
*found_deny
)
8442 struct vnode_attr
*vap
= vcp
->vap
;
8443 kauth_cred_t cred
= vcp
->ctx
->vc_ucred
;
8444 struct kauth_acl_eval eval
;
8445 int error
, ismember
;
8446 mode_t posix_action
;
8449 * If we are the file owner, we automatically have some rights.
8451 * Do we need to expand this to support group ownership?
8453 if (vauth_file_owner(vcp
)) {
8454 acl_rights
&= ~(KAUTH_VNODE_WRITE_SECURITY
);
8458 * If we are checking both TAKE_OWNERSHIP and WRITE_SECURITY, we can
8459 * mask the latter. If TAKE_OWNERSHIP is requested the caller is about to
8460 * change ownership to themselves, and WRITE_SECURITY is implicitly
8461 * granted to the owner. We need to do this because at this point
8462 * WRITE_SECURITY may not be granted as the caller is not currently
8465 if ((acl_rights
& KAUTH_VNODE_TAKE_OWNERSHIP
) &&
8466 (acl_rights
& KAUTH_VNODE_WRITE_SECURITY
)) {
8467 acl_rights
&= ~KAUTH_VNODE_WRITE_SECURITY
;
8470 if (acl_rights
== 0) {
8471 KAUTH_DEBUG("%p ALLOWED - implicit or no rights required", vcp
->vp
);
8475 /* if we have an ACL, evaluate it */
8476 if (VATTR_IS_NOT(vap
, va_acl
, NULL
)) {
8477 eval
.ae_requested
= acl_rights
;
8478 eval
.ae_acl
= &vap
->va_acl
->acl_ace
[0];
8479 eval
.ae_count
= vap
->va_acl
->acl_entrycount
;
8480 eval
.ae_options
= 0;
8481 if (vauth_file_owner(vcp
)) {
8482 eval
.ae_options
|= KAUTH_AEVAL_IS_OWNER
;
8485 * We use ENOENT as a marker to indicate we could not get
8486 * information in order to delay evaluation until after we
8487 * have the ACL evaluation answer. Previously, we would
8488 * always deny the operation at this point.
8490 if ((error
= vauth_file_ingroup(vcp
, &ismember
, ENOENT
)) != 0 && error
!= ENOENT
) {
8493 if (error
== ENOENT
) {
8494 eval
.ae_options
|= KAUTH_AEVAL_IN_GROUP_UNKNOWN
;
8495 } else if (ismember
) {
8496 eval
.ae_options
|= KAUTH_AEVAL_IN_GROUP
;
8498 eval
.ae_exp_gall
= KAUTH_VNODE_GENERIC_ALL_BITS
;
8499 eval
.ae_exp_gread
= KAUTH_VNODE_GENERIC_READ_BITS
;
8500 eval
.ae_exp_gwrite
= KAUTH_VNODE_GENERIC_WRITE_BITS
;
8501 eval
.ae_exp_gexec
= KAUTH_VNODE_GENERIC_EXECUTE_BITS
;
8503 if ((error
= kauth_acl_evaluate(cred
, &eval
)) != 0) {
8504 KAUTH_DEBUG("%p ERROR during ACL processing - %d", vcp
->vp
, error
);
8508 switch (eval
.ae_result
) {
8509 case KAUTH_RESULT_DENY
:
8510 if (vauth_file_owner(vcp
) && proc_ignores_node_permissions(vfs_context_proc(vcp
->ctx
))) {
8511 KAUTH_DEBUG("%p Override DENY due to entitlement", vcp
->vp
);
8514 KAUTH_DEBUG("%p DENIED - by ACL", vcp
->vp
);
8515 return EACCES
; /* deny, deny, counter-allege */
8516 case KAUTH_RESULT_ALLOW
:
8517 KAUTH_DEBUG("%p ALLOWED - all rights granted by ACL", vcp
->vp
);
8519 case KAUTH_RESULT_DEFER
:
8521 /* Effectively the same as !delete_child_denied */
8522 KAUTH_DEBUG("%p DEFERRED - directory ACL", vcp
->vp
);
8526 *found_deny
= eval
.ae_found_deny
;
8528 /* fall through and evaluate residual rights */
8530 /* no ACL, everything is residual */
8531 eval
.ae_residual
= acl_rights
;
8535 * Grant residual rights that have been pre-authorized.
8537 eval
.ae_residual
&= ~preauth_rights
;
8540 * We grant WRITE_ATTRIBUTES to the owner if it hasn't been denied.
8542 if (vauth_file_owner(vcp
)) {
8543 eval
.ae_residual
&= ~KAUTH_VNODE_WRITE_ATTRIBUTES
;
8546 if (eval
.ae_residual
== 0) {
8547 KAUTH_DEBUG("%p ALLOWED - rights already authorized", vcp
->vp
);
8552 * Bail if we have residual rights that can't be granted by posix permissions,
8553 * or aren't presumed granted at this point.
8555 * XXX these can be collapsed for performance
8557 if (eval
.ae_residual
& KAUTH_VNODE_CHANGE_OWNER
) {
8558 KAUTH_DEBUG("%p DENIED - CHANGE_OWNER not permitted", vcp
->vp
);
8561 if (eval
.ae_residual
& KAUTH_VNODE_WRITE_SECURITY
) {
8562 KAUTH_DEBUG("%p DENIED - WRITE_SECURITY not permitted", vcp
->vp
);
8567 if (eval
.ae_residual
& KAUTH_VNODE_DELETE
) {
8568 panic("vnode_authorize: can't be checking delete permission here");
8573 * Compute the fallback posix permissions that will satisfy the remaining
8577 if (eval
.ae_residual
& (KAUTH_VNODE_READ_DATA
|
8578 KAUTH_VNODE_LIST_DIRECTORY
|
8579 KAUTH_VNODE_READ_EXTATTRIBUTES
)) {
8580 posix_action
|= VREAD
;
8582 if (eval
.ae_residual
& (KAUTH_VNODE_WRITE_DATA
|
8583 KAUTH_VNODE_ADD_FILE
|
8584 KAUTH_VNODE_ADD_SUBDIRECTORY
|
8585 KAUTH_VNODE_DELETE_CHILD
|
8586 KAUTH_VNODE_WRITE_ATTRIBUTES
|
8587 KAUTH_VNODE_WRITE_EXTATTRIBUTES
)) {
8588 posix_action
|= VWRITE
;
8590 if (eval
.ae_residual
& (KAUTH_VNODE_EXECUTE
|
8591 KAUTH_VNODE_SEARCH
)) {
8592 posix_action
|= VEXEC
;
8595 if (posix_action
!= 0) {
8596 return vnode_authorize_posix(vcp
, posix_action
, 0 /* !on_dir */);
8598 KAUTH_DEBUG("%p ALLOWED - residual rights %s%s%s%s%s%s%s%s%s%s%s%s%s%s granted due to no posix mapping",
8600 (eval
.ae_residual
& KAUTH_VNODE_READ_DATA
)
8601 ? vnode_isdir(vcp
->vp
) ? " LIST_DIRECTORY" : " READ_DATA" : "",
8602 (eval
.ae_residual
& KAUTH_VNODE_WRITE_DATA
)
8603 ? vnode_isdir(vcp
->vp
) ? " ADD_FILE" : " WRITE_DATA" : "",
8604 (eval
.ae_residual
& KAUTH_VNODE_EXECUTE
)
8605 ? vnode_isdir(vcp
->vp
) ? " SEARCH" : " EXECUTE" : "",
8606 (eval
.ae_residual
& KAUTH_VNODE_DELETE
)
8608 (eval
.ae_residual
& KAUTH_VNODE_APPEND_DATA
)
8609 ? vnode_isdir(vcp
->vp
) ? " ADD_SUBDIRECTORY" : " APPEND_DATA" : "",
8610 (eval
.ae_residual
& KAUTH_VNODE_DELETE_CHILD
)
8611 ? " DELETE_CHILD" : "",
8612 (eval
.ae_residual
& KAUTH_VNODE_READ_ATTRIBUTES
)
8613 ? " READ_ATTRIBUTES" : "",
8614 (eval
.ae_residual
& KAUTH_VNODE_WRITE_ATTRIBUTES
)
8615 ? " WRITE_ATTRIBUTES" : "",
8616 (eval
.ae_residual
& KAUTH_VNODE_READ_EXTATTRIBUTES
)
8617 ? " READ_EXTATTRIBUTES" : "",
8618 (eval
.ae_residual
& KAUTH_VNODE_WRITE_EXTATTRIBUTES
)
8619 ? " WRITE_EXTATTRIBUTES" : "",
8620 (eval
.ae_residual
& KAUTH_VNODE_READ_SECURITY
)
8621 ? " READ_SECURITY" : "",
8622 (eval
.ae_residual
& KAUTH_VNODE_WRITE_SECURITY
)
8623 ? " WRITE_SECURITY" : "",
8624 (eval
.ae_residual
& KAUTH_VNODE_CHECKIMMUTABLE
)
8625 ? " CHECKIMMUTABLE" : "",
8626 (eval
.ae_residual
& KAUTH_VNODE_CHANGE_OWNER
)
8627 ? " CHANGE_OWNER" : "");
8631 * Lack of required Posix permissions implies no reason to deny access.
8637 * Check for file immutability.
8640 vnode_authorize_checkimmutable(mount_t mp
, vauth_ctx vcp
,
8641 struct vnode_attr
*vap
, int rights
, int ignore
)
8647 * Perform immutability checks for operations that change data.
8649 * Sockets, fifos and devices require special handling.
8651 switch (vap
->va_type
) {
8657 * Writing to these nodes does not change the filesystem data,
8658 * so forget that it's being tried.
8660 rights
&= ~KAUTH_VNODE_WRITE_DATA
;
8667 if (rights
& KAUTH_VNODE_WRITE_RIGHTS
) {
8668 /* check per-filesystem options if possible */
8670 /* check for no-EA filesystems */
8671 if ((rights
& KAUTH_VNODE_WRITE_EXTATTRIBUTES
) &&
8672 (vfs_flags(mp
) & MNT_NOUSERXATTR
)) {
8673 KAUTH_DEBUG("%p DENIED - filesystem disallowed extended attributes", vap
);
8674 error
= EACCES
; /* User attributes disabled */
8680 * check for file immutability. first, check if the requested rights are
8681 * allowable for a UF_APPEND file.
8684 if (vap
->va_type
== VDIR
) {
8685 if ((rights
& (KAUTH_VNODE_ADD_FILE
| KAUTH_VNODE_ADD_SUBDIRECTORY
| KAUTH_VNODE_WRITE_EXTATTRIBUTES
)) == rights
) {
8689 if ((rights
& (KAUTH_VNODE_APPEND_DATA
| KAUTH_VNODE_WRITE_EXTATTRIBUTES
)) == rights
) {
8693 if ((error
= vnode_immutable(vap
, append
, ignore
)) != 0) {
8694 if (error
&& !ignore
) {
8696 * In case of a rename, we want to check ownership for dvp as well.
8699 if (rights
& KAUTH_VNODE_DELETE_CHILD
&& vcp
->dvp
!= NULL
) {
8700 owner
= vauth_file_owner(vcp
) && vauth_dir_owner(vcp
);
8702 owner
= vauth_file_owner(vcp
);
8704 if (owner
&& proc_ignores_node_permissions(vfs_context_proc(vcp
->ctx
))) {
8705 error
= vnode_immutable(vap
, append
, 1);
8710 KAUTH_DEBUG("%p DENIED - file is immutable", vap
);
8719 * Handle authorization actions for filesystems that advertise that the
8720 * server will be enforcing.
8722 * Returns: 0 Authorization should be handled locally
8723 * 1 Authorization was handled by the FS
8725 * Note: Imputed returns will only occur if the authorization request
8726 * was handled by the FS.
8728 * Imputed: *resultp, modified Return code from FS when the request is
8729 * handled by the FS.
8734 vnode_authorize_opaque(vnode_t vp
, int *resultp
, kauth_action_t action
, vfs_context_t ctx
)
8739 * If the vp is a device node, socket or FIFO it actually represents a local
8740 * endpoint, so we need to handle it locally.
8742 switch (vp
->v_type
) {
8753 * In the advisory request case, if the filesystem doesn't think it's reliable
8754 * we will attempt to formulate a result ourselves based on VNOP_GETATTR data.
8756 if ((action
& KAUTH_VNODE_ACCESS
) && !vfs_authopaqueaccess(vp
->v_mount
)) {
8761 * Let the filesystem have a say in the matter. It's OK for it to not implemnent
8762 * VNOP_ACCESS, as most will authorise inline with the actual request.
8764 if ((error
= VNOP_ACCESS(vp
, action
, ctx
)) != ENOTSUP
) {
8766 KAUTH_DEBUG("%p DENIED - opaque filesystem VNOP_ACCESS denied access", vp
);
8771 * Typically opaque filesystems do authorisation in-line, but exec is a special case. In
8772 * order to be reasonably sure that exec will be permitted, we try a bit harder here.
8774 if ((action
& KAUTH_VNODE_EXECUTE
) && (vp
->v_type
== VREG
)) {
8775 /* try a VNOP_OPEN for readonly access */
8776 if ((error
= VNOP_OPEN(vp
, FREAD
, ctx
)) != 0) {
8778 KAUTH_DEBUG("%p DENIED - EXECUTE denied because file could not be opened readonly", vp
);
8781 VNOP_CLOSE(vp
, FREAD
, ctx
);
8785 * We don't have any reason to believe that the request has to be denied at this point,
8786 * so go ahead and allow it.
8789 KAUTH_DEBUG("%p ALLOWED - bypassing access check for non-local filesystem", vp
);
8797 * Returns: KAUTH_RESULT_ALLOW
8800 * Imputed: *arg3, modified Error code in the deny case
8801 * EROFS Read-only file system
8802 * EACCES Permission denied
8803 * EPERM Operation not permitted [no execute]
8804 * vnode_getattr:ENOMEM Not enough space [only if has filesec]
8806 * vnode_authorize_opaque:*arg2 ???
8807 * vnode_authorize_checkimmutable:???
8808 * vnode_authorize_delete:???
8809 * vnode_authorize_simple:???
8814 vnode_authorize_callback(__unused kauth_cred_t cred
, __unused
void *idata
,
8815 kauth_action_t action
, uintptr_t arg0
, uintptr_t arg1
, uintptr_t arg2
,
8819 vnode_t cvp
= NULLVP
;
8821 int result
= KAUTH_RESULT_DENY
;
8822 int parent_iocount
= 0;
8823 int parent_action
; /* In case we need to use namedstream's data fork for cached rights*/
8825 ctx
= (vfs_context_t
)arg0
;
8827 dvp
= (vnode_t
)arg2
;
8830 * if there are 2 vnodes passed in, we don't know at
8831 * this point which rights to look at based on the
8832 * combined action being passed in... defer until later...
8833 * otherwise check the kauth 'rights' cache hung
8834 * off of the vnode we're interested in... if we've already
8835 * been granted the right we're currently interested in,
8836 * we can just return success... otherwise we'll go through
8837 * the process of authorizing the requested right(s)... if that
8838 * succeeds, we'll add the right(s) to the cache.
8839 * VNOP_SETATTR and VNOP_SETXATTR will invalidate this cache
8848 * For named streams on local-authorization volumes, rights are cached on the parent;
8849 * authorization is determined by looking at the parent's properties anyway, so storing
8850 * on the parent means that we don't recompute for the named stream and that if
8851 * we need to flush rights (e.g. on VNOP_SETATTR()) we don't need to track down the
8852 * stream to flush its cache separately. If we miss in the cache, then we authorize
8853 * as if there were no cached rights (passing the named stream vnode and desired rights to
8854 * vnode_authorize_callback_int()).
8856 * On an opaquely authorized volume, we don't know the relationship between the
8857 * data fork's properties and the rights granted on a stream. Thus, named stream vnodes
8858 * on such a volume are authorized directly (rather than using the parent) and have their
8859 * own caches. When a named stream vnode is created, we mark the parent as having a named
8860 * stream. On a VNOP_SETATTR() for the parent that may invalidate cached authorization, we
8861 * find the stream and flush its cache.
8863 if (vnode_isnamedstream(vp
) && (!vfs_authopaque(vp
->v_mount
))) {
8864 cvp
= vnode_getparent(vp
);
8865 if (cvp
!= NULLVP
) {
8869 goto defer
; /* If we can't use the parent, take the slow path */
8872 /* Have to translate some actions */
8873 parent_action
= action
;
8874 if (parent_action
& KAUTH_VNODE_READ_DATA
) {
8875 parent_action
&= ~KAUTH_VNODE_READ_DATA
;
8876 parent_action
|= KAUTH_VNODE_READ_EXTATTRIBUTES
;
8878 if (parent_action
& KAUTH_VNODE_WRITE_DATA
) {
8879 parent_action
&= ~KAUTH_VNODE_WRITE_DATA
;
8880 parent_action
|= KAUTH_VNODE_WRITE_EXTATTRIBUTES
;
8887 if (vnode_cache_is_authorized(cvp
, ctx
, parent_iocount
? parent_action
: action
) == TRUE
) {
8888 result
= KAUTH_RESULT_ALLOW
;
8892 result
= vnode_authorize_callback_int(action
, ctx
, vp
, dvp
, (int *)arg3
);
8894 if (result
== KAUTH_RESULT_ALLOW
&& cvp
!= NULLVP
) {
8895 KAUTH_DEBUG("%p - caching action = %x", cvp
, action
);
8896 vnode_cache_authorized_action(cvp
, ctx
, action
);
8900 if (parent_iocount
) {
8908 vnode_attr_authorize_internal(vauth_ctx vcp
, mount_t mp
,
8909 kauth_ace_rights_t rights
, int is_suser
, boolean_t
*found_deny
,
8910 int noimmutable
, int parent_authorized_for_delete_child
)
8915 * Check for immutability.
8917 * In the deletion case, parent directory immutability vetoes specific
8920 if ((result
= vnode_authorize_checkimmutable(mp
, vcp
, vcp
->vap
, rights
,
8921 noimmutable
)) != 0) {
8925 if ((rights
& KAUTH_VNODE_DELETE
) &&
8926 !parent_authorized_for_delete_child
) {
8927 result
= vnode_authorize_checkimmutable(mp
, vcp
, vcp
->dvap
,
8928 KAUTH_VNODE_DELETE_CHILD
, 0);
8935 * Clear rights that have been authorized by reaching this point, bail if nothing left to
8938 rights
&= ~(KAUTH_VNODE_LINKTARGET
| KAUTH_VNODE_CHECKIMMUTABLE
);
8944 * If we're not the superuser, authorize based on file properties;
8945 * note that even if parent_authorized_for_delete_child is TRUE, we
8946 * need to check on the node itself.
8949 /* process delete rights */
8950 if ((rights
& KAUTH_VNODE_DELETE
) &&
8951 ((result
= vnode_authorize_delete(vcp
, parent_authorized_for_delete_child
)) != 0)) {
8955 /* process remaining rights */
8956 if ((rights
& ~KAUTH_VNODE_DELETE
) &&
8957 (result
= vnode_authorize_simple(vcp
, rights
, rights
& KAUTH_VNODE_DELETE
, found_deny
)) != 0) {
8962 * Execute is only granted to root if one of the x bits is set. This check only
8963 * makes sense if the posix mode bits are actually supported.
8965 if ((rights
& KAUTH_VNODE_EXECUTE
) &&
8966 (vcp
->vap
->va_type
== VREG
) &&
8967 VATTR_IS_SUPPORTED(vcp
->vap
, va_mode
) &&
8968 !(vcp
->vap
->va_mode
& (S_IXUSR
| S_IXGRP
| S_IXOTH
))) {
8970 KAUTH_DEBUG("%p DENIED - root execute requires at least one x bit in 0x%x", vcp
, vcp
->vap
->va_mode
);
8974 /* Assume that there were DENYs so we don't wrongly cache KAUTH_VNODE_SEARCHBYANYONE */
8977 KAUTH_DEBUG("%p ALLOWED - caller is superuser", vcp
);
8984 vnode_authorize_callback_int(kauth_action_t action
, vfs_context_t ctx
,
8985 vnode_t vp
, vnode_t dvp
, int *errorp
)
8987 struct _vnode_authorize_context auth_context
;
8990 kauth_ace_rights_t rights
;
8991 struct vnode_attr va
, dva
;
8994 boolean_t parent_authorized_for_delete_child
= FALSE
;
8995 boolean_t found_deny
= FALSE
;
8996 boolean_t parent_ref
= FALSE
;
8997 boolean_t is_suser
= FALSE
;
8999 vcp
= &auth_context
;
9004 * Note that we authorize against the context, not the passed cred
9005 * (the same thing anyway)
9007 cred
= ctx
->vc_ucred
;
9014 vcp
->flags
= vcp
->flags_valid
= 0;
9017 if ((ctx
== NULL
) || (vp
== NULL
) || (cred
== NULL
)) {
9018 panic("vnode_authorize: bad arguments (context %p vp %p cred %p)", ctx
, vp
, cred
);
9022 KAUTH_DEBUG("%p AUTH - %s %s%s%s%s%s%s%s%s%s%s%s%s%s%s%s on %s '%s' (0x%x:%p/%p)",
9023 vp
, vfs_context_proc(ctx
)->p_comm
,
9024 (action
& KAUTH_VNODE_ACCESS
) ? "access" : "auth",
9025 (action
& KAUTH_VNODE_READ_DATA
) ? vnode_isdir(vp
) ? " LIST_DIRECTORY" : " READ_DATA" : "",
9026 (action
& KAUTH_VNODE_WRITE_DATA
) ? vnode_isdir(vp
) ? " ADD_FILE" : " WRITE_DATA" : "",
9027 (action
& KAUTH_VNODE_EXECUTE
) ? vnode_isdir(vp
) ? " SEARCH" : " EXECUTE" : "",
9028 (action
& KAUTH_VNODE_DELETE
) ? " DELETE" : "",
9029 (action
& KAUTH_VNODE_APPEND_DATA
) ? vnode_isdir(vp
) ? " ADD_SUBDIRECTORY" : " APPEND_DATA" : "",
9030 (action
& KAUTH_VNODE_DELETE_CHILD
) ? " DELETE_CHILD" : "",
9031 (action
& KAUTH_VNODE_READ_ATTRIBUTES
) ? " READ_ATTRIBUTES" : "",
9032 (action
& KAUTH_VNODE_WRITE_ATTRIBUTES
) ? " WRITE_ATTRIBUTES" : "",
9033 (action
& KAUTH_VNODE_READ_EXTATTRIBUTES
) ? " READ_EXTATTRIBUTES" : "",
9034 (action
& KAUTH_VNODE_WRITE_EXTATTRIBUTES
) ? " WRITE_EXTATTRIBUTES" : "",
9035 (action
& KAUTH_VNODE_READ_SECURITY
) ? " READ_SECURITY" : "",
9036 (action
& KAUTH_VNODE_WRITE_SECURITY
) ? " WRITE_SECURITY" : "",
9037 (action
& KAUTH_VNODE_CHANGE_OWNER
) ? " CHANGE_OWNER" : "",
9038 (action
& KAUTH_VNODE_NOIMMUTABLE
) ? " (noimmutable)" : "",
9039 vnode_isdir(vp
) ? "directory" : "file",
9040 vp
->v_name
? vp
->v_name
: "<NULL>", action
, vp
, dvp
);
9043 * Extract the control bits from the action, everything else is
9046 noimmutable
= (action
& KAUTH_VNODE_NOIMMUTABLE
) ? 1 : 0;
9047 rights
= action
& ~(KAUTH_VNODE_ACCESS
| KAUTH_VNODE_NOIMMUTABLE
);
9049 if (rights
& KAUTH_VNODE_DELETE
) {
9052 panic("vnode_authorize: KAUTH_VNODE_DELETE test requires a directory");
9056 * check to see if we've already authorized the parent
9057 * directory for deletion of its children... if so, we
9058 * can skip a whole bunch of work... we will still have to
9059 * authorize that this specific child can be removed
9061 if (vnode_cache_is_authorized(dvp
, ctx
, KAUTH_VNODE_DELETE_CHILD
) == TRUE
) {
9062 parent_authorized_for_delete_child
= TRUE
;
9070 * Check for read-only filesystems.
9072 if ((rights
& KAUTH_VNODE_WRITE_RIGHTS
) &&
9073 (vp
->v_mount
->mnt_flag
& MNT_RDONLY
) &&
9074 ((vp
->v_type
== VREG
) || (vp
->v_type
== VDIR
) ||
9075 (vp
->v_type
== VLNK
) || (vp
->v_type
== VCPLX
) ||
9076 (rights
& KAUTH_VNODE_DELETE
) || (rights
& KAUTH_VNODE_DELETE_CHILD
))) {
9082 * Check for noexec filesystems.
9084 if ((rights
& KAUTH_VNODE_EXECUTE
) && (vp
->v_type
== VREG
) && (vp
->v_mount
->mnt_flag
& MNT_NOEXEC
)) {
9090 * Handle cases related to filesystems with non-local enforcement.
9091 * This call can return 0, in which case we will fall through to perform a
9092 * check based on VNOP_GETATTR data. Otherwise it returns 1 and sets
9093 * an appropriate result, at which point we can return immediately.
9095 if ((vp
->v_mount
->mnt_kern_flag
& MNTK_AUTH_OPAQUE
) && vnode_authorize_opaque(vp
, &result
, action
, ctx
)) {
9100 * If the vnode is a namedstream (extended attribute) data vnode (eg.
9101 * a resource fork), *_DATA becomes *_EXTATTRIBUTES.
9103 if (vnode_isnamedstream(vp
)) {
9104 if (rights
& KAUTH_VNODE_READ_DATA
) {
9105 rights
&= ~KAUTH_VNODE_READ_DATA
;
9106 rights
|= KAUTH_VNODE_READ_EXTATTRIBUTES
;
9108 if (rights
& KAUTH_VNODE_WRITE_DATA
) {
9109 rights
&= ~KAUTH_VNODE_WRITE_DATA
;
9110 rights
|= KAUTH_VNODE_WRITE_EXTATTRIBUTES
;
9114 * Point 'vp' to the namedstream's parent for ACL checking
9116 if ((vp
->v_parent
!= NULL
) &&
9117 (vget_internal(vp
->v_parent
, 0, VNODE_NODEAD
| VNODE_DRAINO
) == 0)) {
9119 vcp
->vp
= vp
= vp
->v_parent
;
9123 if (vfs_context_issuser(ctx
)) {
9125 * if we're not asking for execute permissions or modifications,
9126 * then we're done, this action is authorized.
9128 if (!(rights
& (KAUTH_VNODE_EXECUTE
| KAUTH_VNODE_WRITE_RIGHTS
))) {
9136 * Get vnode attributes and extended security information for the vnode
9137 * and directory if required.
9139 * If we're root we only want mode bits and flags for checking
9140 * execute and immutability.
9142 VATTR_WANTED(&va
, va_mode
);
9143 VATTR_WANTED(&va
, va_flags
);
9145 VATTR_WANTED(&va
, va_uid
);
9146 VATTR_WANTED(&va
, va_gid
);
9147 VATTR_WANTED(&va
, va_acl
);
9149 if ((result
= vnode_getattr(vp
, &va
, ctx
)) != 0) {
9150 KAUTH_DEBUG("%p ERROR - failed to get vnode attributes - %d", vp
, result
);
9153 VATTR_WANTED(&va
, va_type
);
9154 VATTR_RETURN(&va
, va_type
, vnode_vtype(vp
));
9157 VATTR_WANTED(&dva
, va_mode
);
9158 VATTR_WANTED(&dva
, va_flags
);
9160 VATTR_WANTED(&dva
, va_uid
);
9161 VATTR_WANTED(&dva
, va_gid
);
9162 VATTR_WANTED(&dva
, va_acl
);
9164 if ((result
= vnode_getattr(vcp
->dvp
, &dva
, ctx
)) != 0) {
9165 KAUTH_DEBUG("%p ERROR - failed to get directory vnode attributes - %d", vp
, result
);
9168 VATTR_WANTED(&dva
, va_type
);
9169 VATTR_RETURN(&dva
, va_type
, vnode_vtype(vcp
->dvp
));
9172 result
= vnode_attr_authorize_internal(vcp
, vp
->v_mount
, rights
, is_suser
,
9173 &found_deny
, noimmutable
, parent_authorized_for_delete_child
);
9175 if (VATTR_IS_SUPPORTED(&va
, va_acl
) && (va
.va_acl
!= NULL
)) {
9176 kauth_acl_free(va
.va_acl
);
9178 if (VATTR_IS_SUPPORTED(&dva
, va_acl
) && (dva
.va_acl
!= NULL
)) {
9179 kauth_acl_free(dva
.va_acl
);
9187 KAUTH_DEBUG("%p DENIED - auth denied", vp
);
9188 return KAUTH_RESULT_DENY
;
9190 if ((rights
& KAUTH_VNODE_SEARCH
) && found_deny
== FALSE
&& vp
->v_type
== VDIR
) {
9192 * if we were successfully granted the right to search this directory
9193 * and there were NO ACL DENYs for search and the posix permissions also don't
9194 * deny execute, we can synthesize a global right that allows anyone to
9195 * traverse this directory during a pathname lookup without having to
9196 * match the credential associated with this cache of rights.
9198 * Note that we can correctly cache KAUTH_VNODE_SEARCHBYANYONE
9199 * only if we actually check ACLs which we don't for root. As
9200 * a workaround, the lookup fast path checks for root.
9202 if (!VATTR_IS_SUPPORTED(&va
, va_mode
) ||
9203 ((va
.va_mode
& (S_IXUSR
| S_IXGRP
| S_IXOTH
)) ==
9204 (S_IXUSR
| S_IXGRP
| S_IXOTH
))) {
9205 vnode_cache_authorized_action(vp
, ctx
, KAUTH_VNODE_SEARCHBYANYONE
);
9214 * Note that this implies that we will allow requests for no rights, as well as
9215 * for rights that we do not recognise. There should be none of these.
9217 KAUTH_DEBUG("%p ALLOWED - auth granted", vp
);
9218 return KAUTH_RESULT_ALLOW
;
9222 vnode_attr_authorize_init(struct vnode_attr
*vap
, struct vnode_attr
*dvap
,
9223 kauth_action_t action
, vfs_context_t ctx
)
9226 VATTR_WANTED(vap
, va_type
);
9227 VATTR_WANTED(vap
, va_mode
);
9228 VATTR_WANTED(vap
, va_flags
);
9231 if (action
& KAUTH_VNODE_DELETE
) {
9232 VATTR_WANTED(dvap
, va_type
);
9233 VATTR_WANTED(dvap
, va_mode
);
9234 VATTR_WANTED(dvap
, va_flags
);
9236 } else if (action
& KAUTH_VNODE_DELETE
) {
9240 if (!vfs_context_issuser(ctx
)) {
9241 VATTR_WANTED(vap
, va_uid
);
9242 VATTR_WANTED(vap
, va_gid
);
9243 VATTR_WANTED(vap
, va_acl
);
9244 if (dvap
&& (action
& KAUTH_VNODE_DELETE
)) {
9245 VATTR_WANTED(dvap
, va_uid
);
9246 VATTR_WANTED(dvap
, va_gid
);
9247 VATTR_WANTED(dvap
, va_acl
);
9255 vnode_attr_authorize(struct vnode_attr
*vap
, struct vnode_attr
*dvap
, mount_t mp
,
9256 kauth_action_t action
, vfs_context_t ctx
)
9258 struct _vnode_authorize_context auth_context
;
9260 kauth_ace_rights_t rights
;
9262 boolean_t found_deny
;
9263 boolean_t is_suser
= FALSE
;
9266 vcp
= &auth_context
;
9272 vcp
->flags
= vcp
->flags_valid
= 0;
9274 noimmutable
= (action
& KAUTH_VNODE_NOIMMUTABLE
) ? 1 : 0;
9275 rights
= action
& ~(KAUTH_VNODE_ACCESS
| KAUTH_VNODE_NOIMMUTABLE
);
9278 * Check for read-only filesystems.
9280 if ((rights
& KAUTH_VNODE_WRITE_RIGHTS
) &&
9281 mp
&& (mp
->mnt_flag
& MNT_RDONLY
) &&
9282 ((vap
->va_type
== VREG
) || (vap
->va_type
== VDIR
) ||
9283 (vap
->va_type
== VLNK
) || (rights
& KAUTH_VNODE_DELETE
) ||
9284 (rights
& KAUTH_VNODE_DELETE_CHILD
))) {
9290 * Check for noexec filesystems.
9292 if ((rights
& KAUTH_VNODE_EXECUTE
) &&
9293 (vap
->va_type
== VREG
) && mp
&& (mp
->mnt_flag
& MNT_NOEXEC
)) {
9298 if (vfs_context_issuser(ctx
)) {
9300 * if we're not asking for execute permissions or modifications,
9301 * then we're done, this action is authorized.
9303 if (!(rights
& (KAUTH_VNODE_EXECUTE
| KAUTH_VNODE_WRITE_RIGHTS
))) {
9308 if (!VATTR_IS_SUPPORTED(vap
, va_uid
) ||
9309 !VATTR_IS_SUPPORTED(vap
, va_gid
) ||
9310 (mp
&& vfs_extendedsecurity(mp
) && !VATTR_IS_SUPPORTED(vap
, va_acl
))) {
9311 panic("vnode attrs not complete for vnode_attr_authorize\n");
9316 vnode_attr_handle_mnt_ignore_ownership(vap
, mp
, ctx
);
9319 result
= vnode_attr_authorize_internal(vcp
, mp
, rights
, is_suser
,
9320 &found_deny
, noimmutable
, FALSE
);
9322 if (result
== EPERM
) {
9331 vnode_authattr_new(vnode_t dvp
, struct vnode_attr
*vap
, int noauth
, vfs_context_t ctx
)
9333 return vnode_authattr_new_internal(dvp
, vap
, noauth
, NULL
, ctx
);
9337 * Check that the attribute information in vattr can be legally applied to
9338 * a new file by the context.
9341 vnode_authattr_new_internal(vnode_t dvp
, struct vnode_attr
*vap
, int noauth
, uint32_t *defaulted_fieldsp
, vfs_context_t ctx
)
9344 int has_priv_suser
, ismember
, defaulted_owner
, defaulted_group
, defaulted_mode
;
9345 uint32_t inherit_flags
;
9349 struct vnode_attr dva
;
9353 if (defaulted_fieldsp
) {
9354 *defaulted_fieldsp
= 0;
9357 defaulted_owner
= defaulted_group
= defaulted_mode
= 0;
9362 * Require that the filesystem support extended security to apply any.
9364 if (!vfs_extendedsecurity(dvp
->v_mount
) &&
9365 (VATTR_IS_ACTIVE(vap
, va_acl
) || VATTR_IS_ACTIVE(vap
, va_uuuid
) || VATTR_IS_ACTIVE(vap
, va_guuid
))) {
9371 * Default some fields.
9376 * If the filesystem is mounted IGNORE_OWNERSHIP and an explicit owner is set, that
9377 * owner takes ownership of all new files.
9379 if ((dmp
->mnt_flag
& MNT_IGNORE_OWNERSHIP
) && (dmp
->mnt_fsowner
!= KAUTH_UID_NONE
)) {
9380 VATTR_SET(vap
, va_uid
, dmp
->mnt_fsowner
);
9381 defaulted_owner
= 1;
9383 if (!VATTR_IS_ACTIVE(vap
, va_uid
)) {
9384 /* default owner is current user */
9385 VATTR_SET(vap
, va_uid
, kauth_cred_getuid(vfs_context_ucred(ctx
)));
9386 defaulted_owner
= 1;
9391 * We need the dvp's va_flags and *may* need the gid of the directory,
9392 * we ask for both here.
9395 VATTR_WANTED(&dva
, va_gid
);
9396 VATTR_WANTED(&dva
, va_flags
);
9397 if ((error
= vnode_getattr(dvp
, &dva
, ctx
)) != 0) {
9402 * If the filesystem is mounted IGNORE_OWNERSHIP and an explicit grouo is set, that
9403 * group takes ownership of all new files.
9405 if ((dmp
->mnt_flag
& MNT_IGNORE_OWNERSHIP
) && (dmp
->mnt_fsgroup
!= KAUTH_GID_NONE
)) {
9406 VATTR_SET(vap
, va_gid
, dmp
->mnt_fsgroup
);
9407 defaulted_group
= 1;
9409 if (!VATTR_IS_ACTIVE(vap
, va_gid
)) {
9410 /* default group comes from parent object, fallback to current user */
9411 if (VATTR_IS_SUPPORTED(&dva
, va_gid
)) {
9412 VATTR_SET(vap
, va_gid
, dva
.va_gid
);
9414 VATTR_SET(vap
, va_gid
, kauth_cred_getgid(vfs_context_ucred(ctx
)));
9416 defaulted_group
= 1;
9420 if (!VATTR_IS_ACTIVE(vap
, va_flags
)) {
9421 VATTR_SET(vap
, va_flags
, 0);
9424 /* Determine if SF_RESTRICTED should be inherited from the parent
9426 if (VATTR_IS_SUPPORTED(&dva
, va_flags
)) {
9427 inherit_flags
= dva
.va_flags
& (UF_DATAVAULT
| SF_RESTRICTED
);
9430 /* default mode is everything, masked with current umask */
9431 if (!VATTR_IS_ACTIVE(vap
, va_mode
)) {
9432 VATTR_SET(vap
, va_mode
, ACCESSPERMS
& ~vfs_context_proc(ctx
)->p_fd
->fd_cmask
);
9433 KAUTH_DEBUG("ATTR - defaulting new file mode to %o from umask %o", vap
->va_mode
, vfs_context_proc(ctx
)->p_fd
->fd_cmask
);
9436 /* set timestamps to now */
9437 if (!VATTR_IS_ACTIVE(vap
, va_create_time
)) {
9438 nanotime(&vap
->va_create_time
);
9439 VATTR_SET_ACTIVE(vap
, va_create_time
);
9443 * Check for attempts to set nonsensical fields.
9445 if (vap
->va_active
& ~VNODE_ATTR_NEWOBJ
) {
9447 KAUTH_DEBUG("ATTR - ERROR - attempt to set unsupported new-file attributes %llx",
9448 vap
->va_active
& ~VNODE_ATTR_NEWOBJ
);
9453 * Quickly check for the applicability of any enforcement here.
9454 * Tests below maintain the integrity of the local security model.
9456 if (vfs_authopaque(dvp
->v_mount
)) {
9461 * We need to know if the caller is the superuser, or if the work is
9462 * otherwise already authorised.
9464 cred
= vfs_context_ucred(ctx
);
9466 /* doing work for the kernel */
9469 has_priv_suser
= vfs_context_issuser(ctx
);
9473 if (VATTR_IS_ACTIVE(vap
, va_flags
)) {
9474 vap
->va_flags
&= ~SF_SYNTHETIC
;
9475 if (has_priv_suser
) {
9476 if ((vap
->va_flags
& (UF_SETTABLE
| SF_SETTABLE
)) != vap
->va_flags
) {
9478 KAUTH_DEBUG(" DENIED - superuser attempt to set illegal flag(s)");
9482 if ((vap
->va_flags
& UF_SETTABLE
) != vap
->va_flags
) {
9484 KAUTH_DEBUG(" DENIED - user attempt to set illegal flag(s)");
9490 /* if not superuser, validate legality of new-item attributes */
9491 if (!has_priv_suser
) {
9492 if (!defaulted_mode
&& VATTR_IS_ACTIVE(vap
, va_mode
)) {
9494 if (vap
->va_mode
& S_ISGID
) {
9495 if ((error
= kauth_cred_ismember_gid(cred
, vap
->va_gid
, &ismember
)) != 0) {
9496 KAUTH_DEBUG("ATTR - ERROR: got %d checking for membership in %d", error
, vap
->va_gid
);
9500 KAUTH_DEBUG(" DENIED - can't set SGID bit, not a member of %d", vap
->va_gid
);
9507 if ((vap
->va_mode
& S_ISUID
) && (vap
->va_uid
!= kauth_cred_getuid(cred
))) {
9508 KAUTH_DEBUG("ATTR - ERROR: illegal attempt to set the setuid bit");
9513 if (!defaulted_owner
&& (vap
->va_uid
!= kauth_cred_getuid(cred
))) {
9514 KAUTH_DEBUG(" DENIED - cannot create new item owned by %d", vap
->va_uid
);
9518 if (!defaulted_group
) {
9519 if ((error
= kauth_cred_ismember_gid(cred
, vap
->va_gid
, &ismember
)) != 0) {
9520 KAUTH_DEBUG(" ERROR - got %d checking for membership in %d", error
, vap
->va_gid
);
9524 KAUTH_DEBUG(" DENIED - cannot create new item with group %d - not a member", vap
->va_gid
);
9530 /* initialising owner/group UUID */
9531 if (VATTR_IS_ACTIVE(vap
, va_uuuid
)) {
9532 if ((error
= kauth_cred_getguid(cred
, &changer
)) != 0) {
9533 KAUTH_DEBUG(" ERROR - got %d trying to get caller UUID", error
);
9534 /* XXX ENOENT here - no GUID - should perhaps become EPERM */
9537 if (!kauth_guid_equal(&vap
->va_uuuid
, &changer
)) {
9538 KAUTH_DEBUG(" ERROR - cannot create item with supplied owner UUID - not us");
9543 if (VATTR_IS_ACTIVE(vap
, va_guuid
)) {
9544 if ((error
= kauth_cred_ismember_guid(cred
, &vap
->va_guuid
, &ismember
)) != 0) {
9545 KAUTH_DEBUG(" ERROR - got %d trying to check group membership", error
);
9549 KAUTH_DEBUG(" ERROR - cannot create item with supplied group UUID - not a member");
9556 if (inherit_flags
) {
9557 /* Apply SF_RESTRICTED to the file if its parent directory was
9558 * restricted. This is done at the end so that root is not
9559 * required if this flag is only set due to inheritance. */
9560 VATTR_SET(vap
, va_flags
, (vap
->va_flags
| inherit_flags
));
9562 if (defaulted_fieldsp
) {
9563 if (defaulted_mode
) {
9564 *defaulted_fieldsp
|= VATTR_PREPARE_DEFAULTED_MODE
;
9566 if (defaulted_group
) {
9567 *defaulted_fieldsp
|= VATTR_PREPARE_DEFAULTED_GID
;
9569 if (defaulted_owner
) {
9570 *defaulted_fieldsp
|= VATTR_PREPARE_DEFAULTED_UID
;
9577 * Check that the attribute information in vap can be legally written by the
9580 * Call this when you're not sure about the vnode_attr; either its contents
9581 * have come from an unknown source, or when they are variable.
9583 * Returns errno, or zero and sets *actionp to the KAUTH_VNODE_* actions that
9584 * must be authorized to be permitted to write the vattr.
9587 vnode_authattr(vnode_t vp
, struct vnode_attr
*vap
, kauth_action_t
*actionp
, vfs_context_t ctx
)
9589 struct vnode_attr ova
;
9590 kauth_action_t required_action
;
9591 int error
, has_priv_suser
, ismember
, chowner
, chgroup
, clear_suid
, clear_sgid
;
9600 required_action
= 0;
9604 * Quickly check for enforcement applicability.
9606 if (vfs_authopaque(vp
->v_mount
)) {
9611 * Check for attempts to set nonsensical fields.
9613 if (vap
->va_active
& VNODE_ATTR_RDONLY
) {
9614 KAUTH_DEBUG("ATTR - ERROR: attempt to set readonly attribute(s)");
9620 * We need to know if the caller is the superuser.
9622 cred
= vfs_context_ucred(ctx
);
9623 has_priv_suser
= kauth_cred_issuser(cred
);
9626 * If any of the following are changing, we need information from the old file:
9633 if (VATTR_IS_ACTIVE(vap
, va_uid
) ||
9634 VATTR_IS_ACTIVE(vap
, va_gid
) ||
9635 VATTR_IS_ACTIVE(vap
, va_mode
) ||
9636 VATTR_IS_ACTIVE(vap
, va_uuuid
) ||
9637 VATTR_IS_ACTIVE(vap
, va_guuid
)) {
9638 VATTR_WANTED(&ova
, va_mode
);
9639 VATTR_WANTED(&ova
, va_uid
);
9640 VATTR_WANTED(&ova
, va_gid
);
9641 VATTR_WANTED(&ova
, va_uuuid
);
9642 VATTR_WANTED(&ova
, va_guuid
);
9643 KAUTH_DEBUG("ATTR - security information changing, fetching existing attributes");
9647 * If timestamps are being changed, we need to know who the file is owned
9650 if (VATTR_IS_ACTIVE(vap
, va_create_time
) ||
9651 VATTR_IS_ACTIVE(vap
, va_change_time
) ||
9652 VATTR_IS_ACTIVE(vap
, va_modify_time
) ||
9653 VATTR_IS_ACTIVE(vap
, va_access_time
) ||
9654 VATTR_IS_ACTIVE(vap
, va_backup_time
) ||
9655 VATTR_IS_ACTIVE(vap
, va_addedtime
)) {
9656 VATTR_WANTED(&ova
, va_uid
);
9657 #if 0 /* enable this when we support UUIDs as official owners */
9658 VATTR_WANTED(&ova
, va_uuuid
);
9660 KAUTH_DEBUG("ATTR - timestamps changing, fetching uid and GUID");
9664 * If flags are being changed, we need the old flags.
9666 if (VATTR_IS_ACTIVE(vap
, va_flags
)) {
9667 KAUTH_DEBUG("ATTR - flags changing, fetching old flags");
9668 VATTR_WANTED(&ova
, va_flags
);
9672 * If ACLs are being changed, we need the old ACLs.
9674 if (VATTR_IS_ACTIVE(vap
, va_acl
)) {
9675 KAUTH_DEBUG("ATTR - acl changing, fetching old flags");
9676 VATTR_WANTED(&ova
, va_acl
);
9680 * If the size is being set, make sure it's not a directory.
9682 if (VATTR_IS_ACTIVE(vap
, va_data_size
)) {
9683 /* size is only meaningful on regular files, don't permit otherwise */
9684 if (!vnode_isreg(vp
)) {
9685 KAUTH_DEBUG("ATTR - ERROR: size change requested on non-file");
9686 error
= vnode_isdir(vp
) ? EISDIR
: EINVAL
;
9694 KAUTH_DEBUG("ATTR - fetching old attributes %016llx", ova
.va_active
);
9695 if ((error
= vnode_getattr(vp
, &ova
, ctx
)) != 0) {
9696 KAUTH_DEBUG(" ERROR - got %d trying to get attributes", error
);
9701 * Size changes require write access to the file data.
9703 if (VATTR_IS_ACTIVE(vap
, va_data_size
)) {
9704 /* if we can't get the size, or it's different, we need write access */
9705 KAUTH_DEBUG("ATTR - size change, requiring WRITE_DATA");
9706 required_action
|= KAUTH_VNODE_WRITE_DATA
;
9710 * Changing timestamps?
9712 * Note that we are only called to authorize user-requested time changes;
9713 * side-effect time changes are not authorized. Authorisation is only
9714 * required for existing files.
9716 * Non-owners are not permitted to change the time on an existing
9717 * file to anything other than the current time.
9719 if (VATTR_IS_ACTIVE(vap
, va_create_time
) ||
9720 VATTR_IS_ACTIVE(vap
, va_change_time
) ||
9721 VATTR_IS_ACTIVE(vap
, va_modify_time
) ||
9722 VATTR_IS_ACTIVE(vap
, va_access_time
) ||
9723 VATTR_IS_ACTIVE(vap
, va_backup_time
) ||
9724 VATTR_IS_ACTIVE(vap
, va_addedtime
)) {
9726 * The owner and root may set any timestamps they like,
9727 * provided that the file is not immutable. The owner still needs
9728 * WRITE_ATTRIBUTES (implied by ownership but still deniable).
9730 if (has_priv_suser
|| vauth_node_owner(&ova
, cred
)) {
9731 KAUTH_DEBUG("ATTR - root or owner changing timestamps");
9732 required_action
|= KAUTH_VNODE_CHECKIMMUTABLE
| KAUTH_VNODE_WRITE_ATTRIBUTES
;
9734 /* just setting the current time? */
9735 if (vap
->va_vaflags
& VA_UTIMES_NULL
) {
9736 KAUTH_DEBUG("ATTR - non-root/owner changing timestamps, requiring WRITE_ATTRIBUTES");
9737 required_action
|= KAUTH_VNODE_WRITE_ATTRIBUTES
;
9739 KAUTH_DEBUG("ATTR - ERROR: illegal timestamp modification attempted");
9747 * Changing file mode?
9749 if (VATTR_IS_ACTIVE(vap
, va_mode
) && VATTR_IS_SUPPORTED(&ova
, va_mode
) && (ova
.va_mode
!= vap
->va_mode
)) {
9750 KAUTH_DEBUG("ATTR - mode change from %06o to %06o", ova
.va_mode
, vap
->va_mode
);
9753 * Mode changes always have the same basic auth requirements.
9755 if (has_priv_suser
) {
9756 KAUTH_DEBUG("ATTR - superuser mode change, requiring immutability check");
9757 required_action
|= KAUTH_VNODE_CHECKIMMUTABLE
;
9759 /* need WRITE_SECURITY */
9760 KAUTH_DEBUG("ATTR - non-superuser mode change, requiring WRITE_SECURITY");
9761 required_action
|= KAUTH_VNODE_WRITE_SECURITY
;
9765 * Can't set the setgid bit if you're not in the group and not root. Have to have
9766 * existing group information in the case we're not setting it right now.
9768 if (vap
->va_mode
& S_ISGID
) {
9769 required_action
|= KAUTH_VNODE_CHECKIMMUTABLE
; /* always required */
9770 if (!has_priv_suser
) {
9771 if (VATTR_IS_ACTIVE(vap
, va_gid
)) {
9772 group
= vap
->va_gid
;
9773 } else if (VATTR_IS_SUPPORTED(&ova
, va_gid
)) {
9776 KAUTH_DEBUG("ATTR - ERROR: setgid but no gid available");
9781 * This might be too restrictive; WRITE_SECURITY might be implied by
9782 * membership in this case, rather than being an additional requirement.
9784 if ((error
= kauth_cred_ismember_gid(cred
, group
, &ismember
)) != 0) {
9785 KAUTH_DEBUG("ATTR - ERROR: got %d checking for membership in %d", error
, vap
->va_gid
);
9789 KAUTH_DEBUG(" DENIED - can't set SGID bit, not a member of %d", group
);
9797 * Can't set the setuid bit unless you're root or the file's owner.
9799 if (vap
->va_mode
& S_ISUID
) {
9800 required_action
|= KAUTH_VNODE_CHECKIMMUTABLE
; /* always required */
9801 if (!has_priv_suser
) {
9802 if (VATTR_IS_ACTIVE(vap
, va_uid
)) {
9803 owner
= vap
->va_uid
;
9804 } else if (VATTR_IS_SUPPORTED(&ova
, va_uid
)) {
9807 KAUTH_DEBUG("ATTR - ERROR: setuid but no uid available");
9811 if (owner
!= kauth_cred_getuid(cred
)) {
9813 * We could allow this if WRITE_SECURITY is permitted, perhaps.
9815 KAUTH_DEBUG("ATTR - ERROR: illegal attempt to set the setuid bit");
9824 * Validate/mask flags changes. This checks that only the flags in
9825 * the UF_SETTABLE mask are being set, and preserves the flags in
9826 * the SF_SETTABLE case.
9828 * Since flags changes may be made in conjunction with other changes,
9829 * we will ask the auth code to ignore immutability in the case that
9830 * the SF_* flags are not set and we are only manipulating the file flags.
9833 if (VATTR_IS_ACTIVE(vap
, va_flags
)) {
9834 /* compute changing flags bits */
9835 vap
->va_flags
&= ~SF_SYNTHETIC
;
9836 ova
.va_flags
&= ~SF_SYNTHETIC
;
9837 if (VATTR_IS_SUPPORTED(&ova
, va_flags
)) {
9838 fdelta
= vap
->va_flags
^ ova
.va_flags
;
9840 fdelta
= vap
->va_flags
;
9844 KAUTH_DEBUG("ATTR - flags changing, requiring WRITE_SECURITY");
9845 required_action
|= KAUTH_VNODE_WRITE_SECURITY
;
9847 /* check that changing bits are legal */
9848 if (has_priv_suser
) {
9850 * The immutability check will prevent us from clearing the SF_*
9851 * flags unless the system securelevel permits it, so just check
9852 * for legal flags here.
9854 if (fdelta
& ~(UF_SETTABLE
| SF_SETTABLE
)) {
9856 KAUTH_DEBUG(" DENIED - superuser attempt to set illegal flag(s)");
9860 if (fdelta
& ~UF_SETTABLE
) {
9862 KAUTH_DEBUG(" DENIED - user attempt to set illegal flag(s)");
9867 * If the caller has the ability to manipulate file flags,
9868 * security is not reduced by ignoring them for this operation.
9870 * A more complete test here would consider the 'after' states of the flags
9871 * to determine whether it would permit the operation, but this becomes
9874 * Ignoring immutability is conditional on securelevel; this does not bypass
9875 * the SF_* flags if securelevel > 0.
9877 required_action
|= KAUTH_VNODE_NOIMMUTABLE
;
9882 * Validate ownership information.
9891 * Note that if the filesystem didn't give us a UID, we expect that it doesn't
9892 * support them in general, and will ignore it if/when we try to set it.
9893 * We might want to clear the uid out of vap completely here.
9895 if (VATTR_IS_ACTIVE(vap
, va_uid
)) {
9896 if (VATTR_IS_SUPPORTED(&ova
, va_uid
) && (vap
->va_uid
!= ova
.va_uid
)) {
9897 if (!has_priv_suser
&& (kauth_cred_getuid(cred
) != vap
->va_uid
)) {
9898 KAUTH_DEBUG(" DENIED - non-superuser cannot change ownershipt to a third party");
9909 * Note that if the filesystem didn't give us a GID, we expect that it doesn't
9910 * support them in general, and will ignore it if/when we try to set it.
9911 * We might want to clear the gid out of vap completely here.
9913 if (VATTR_IS_ACTIVE(vap
, va_gid
)) {
9914 if (VATTR_IS_SUPPORTED(&ova
, va_gid
) && (vap
->va_gid
!= ova
.va_gid
)) {
9915 if (!has_priv_suser
) {
9916 if ((error
= kauth_cred_ismember_gid(cred
, vap
->va_gid
, &ismember
)) != 0) {
9917 KAUTH_DEBUG(" ERROR - got %d checking for membership in %d", error
, vap
->va_gid
);
9921 KAUTH_DEBUG(" DENIED - group change from %d to %d but not a member of target group",
9922 ova
.va_gid
, vap
->va_gid
);
9933 * Owner UUID being set or changed.
9935 if (VATTR_IS_ACTIVE(vap
, va_uuuid
)) {
9936 /* if the owner UUID is not actually changing ... */
9937 if (VATTR_IS_SUPPORTED(&ova
, va_uuuid
)) {
9938 if (kauth_guid_equal(&vap
->va_uuuid
, &ova
.va_uuuid
)) {
9939 goto no_uuuid_change
;
9943 * If the current owner UUID is a null GUID, check
9944 * it against the UUID corresponding to the owner UID.
9946 if (kauth_guid_equal(&ova
.va_uuuid
, &kauth_null_guid
) &&
9947 VATTR_IS_SUPPORTED(&ova
, va_uid
)) {
9950 if (kauth_cred_uid2guid(ova
.va_uid
, &uid_guid
) == 0 &&
9951 kauth_guid_equal(&vap
->va_uuuid
, &uid_guid
)) {
9952 goto no_uuuid_change
;
9958 * The owner UUID cannot be set by a non-superuser to anything other than
9959 * their own or a null GUID (to "unset" the owner UUID).
9960 * Note that file systems must be prepared to handle the
9961 * null UUID case in a manner appropriate for that file
9964 if (!has_priv_suser
) {
9965 if ((error
= kauth_cred_getguid(cred
, &changer
)) != 0) {
9966 KAUTH_DEBUG(" ERROR - got %d trying to get caller UUID", error
);
9967 /* XXX ENOENT here - no UUID - should perhaps become EPERM */
9970 if (!kauth_guid_equal(&vap
->va_uuuid
, &changer
) &&
9971 !kauth_guid_equal(&vap
->va_uuuid
, &kauth_null_guid
)) {
9972 KAUTH_DEBUG(" ERROR - cannot set supplied owner UUID - not us / null");
9982 * Group UUID being set or changed.
9984 if (VATTR_IS_ACTIVE(vap
, va_guuid
)) {
9985 /* if the group UUID is not actually changing ... */
9986 if (VATTR_IS_SUPPORTED(&ova
, va_guuid
)) {
9987 if (kauth_guid_equal(&vap
->va_guuid
, &ova
.va_guuid
)) {
9988 goto no_guuid_change
;
9992 * If the current group UUID is a null UUID, check
9993 * it against the UUID corresponding to the group GID.
9995 if (kauth_guid_equal(&ova
.va_guuid
, &kauth_null_guid
) &&
9996 VATTR_IS_SUPPORTED(&ova
, va_gid
)) {
9999 if (kauth_cred_gid2guid(ova
.va_gid
, &gid_guid
) == 0 &&
10000 kauth_guid_equal(&vap
->va_guuid
, &gid_guid
)) {
10001 goto no_guuid_change
;
10007 * The group UUID cannot be set by a non-superuser to anything other than
10008 * one of which they are a member or a null GUID (to "unset"
10010 * Note that file systems must be prepared to handle the
10011 * null UUID case in a manner appropriate for that file
10014 if (!has_priv_suser
) {
10015 if (kauth_guid_equal(&vap
->va_guuid
, &kauth_null_guid
)) {
10017 } else if ((error
= kauth_cred_ismember_guid(cred
, &vap
->va_guuid
, &ismember
)) != 0) {
10018 KAUTH_DEBUG(" ERROR - got %d trying to check group membership", error
);
10022 KAUTH_DEBUG(" ERROR - cannot set supplied group UUID - not a member / null");
10032 * Compute authorisation for group/ownership changes.
10034 if (chowner
|| chgroup
|| clear_suid
|| clear_sgid
) {
10035 if (has_priv_suser
) {
10036 KAUTH_DEBUG("ATTR - superuser changing file owner/group, requiring immutability check");
10037 required_action
|= KAUTH_VNODE_CHECKIMMUTABLE
;
10040 KAUTH_DEBUG("ATTR - ownership change, requiring TAKE_OWNERSHIP");
10041 required_action
|= KAUTH_VNODE_TAKE_OWNERSHIP
;
10043 if (chgroup
&& !chowner
) {
10044 KAUTH_DEBUG("ATTR - group change, requiring WRITE_SECURITY");
10045 required_action
|= KAUTH_VNODE_WRITE_SECURITY
;
10050 * clear set-uid and set-gid bits. POSIX only requires this for
10051 * non-privileged processes but we do it even for root.
10053 if (VATTR_IS_ACTIVE(vap
, va_mode
)) {
10054 newmode
= vap
->va_mode
;
10055 } else if (VATTR_IS_SUPPORTED(&ova
, va_mode
)) {
10056 newmode
= ova
.va_mode
;
10058 KAUTH_DEBUG("CHOWN - trying to change owner but cannot get mode from filesystem to mask setugid bits");
10062 /* chown always clears setuid/gid bits. An exception is made for
10063 * setattrlist which can set both at the same time: <uid, gid, mode> on a file:
10064 * setattrlist is allowed to set the new mode on the file and change (chown)
10067 if (newmode
& (S_ISUID
| S_ISGID
)) {
10068 if (!VATTR_IS_ACTIVE(vap
, va_mode
)) {
10069 KAUTH_DEBUG("CHOWN - masking setugid bits from mode %o to %o",
10070 newmode
, newmode
& ~(S_ISUID
| S_ISGID
));
10071 newmode
&= ~(S_ISUID
| S_ISGID
);
10073 VATTR_SET(vap
, va_mode
, newmode
);
10078 * Authorise changes in the ACL.
10080 if (VATTR_IS_ACTIVE(vap
, va_acl
)) {
10081 /* no existing ACL */
10082 if (!VATTR_IS_ACTIVE(&ova
, va_acl
) || (ova
.va_acl
== NULL
)) {
10083 /* adding an ACL */
10084 if (vap
->va_acl
!= NULL
) {
10085 required_action
|= KAUTH_VNODE_WRITE_SECURITY
;
10086 KAUTH_DEBUG("CHMOD - adding ACL");
10089 /* removing an existing ACL */
10090 } else if (vap
->va_acl
== NULL
) {
10091 required_action
|= KAUTH_VNODE_WRITE_SECURITY
;
10092 KAUTH_DEBUG("CHMOD - removing ACL");
10094 /* updating an existing ACL */
10096 if (vap
->va_acl
->acl_entrycount
!= ova
.va_acl
->acl_entrycount
) {
10097 /* entry count changed, must be different */
10098 required_action
|= KAUTH_VNODE_WRITE_SECURITY
;
10099 KAUTH_DEBUG("CHMOD - adding/removing ACL entries");
10100 } else if (vap
->va_acl
->acl_entrycount
> 0) {
10101 /* both ACLs have the same ACE count, said count is 1 or more, bitwise compare ACLs */
10102 if (memcmp(&vap
->va_acl
->acl_ace
[0], &ova
.va_acl
->acl_ace
[0],
10103 sizeof(struct kauth_ace
) * vap
->va_acl
->acl_entrycount
)) {
10104 required_action
|= KAUTH_VNODE_WRITE_SECURITY
;
10105 KAUTH_DEBUG("CHMOD - changing ACL entries");
10112 * Other attributes that require authorisation.
10114 if (VATTR_IS_ACTIVE(vap
, va_encoding
)) {
10115 required_action
|= KAUTH_VNODE_WRITE_ATTRIBUTES
;
10119 if (VATTR_IS_SUPPORTED(&ova
, va_acl
) && (ova
.va_acl
!= NULL
)) {
10120 kauth_acl_free(ova
.va_acl
);
10123 *actionp
= required_action
;
10129 setlocklocal_callback(struct vnode
*vp
, __unused
void *cargs
)
10131 vnode_lock_spin(vp
);
10132 vp
->v_flag
|= VLOCKLOCAL
;
10135 return VNODE_RETURNED
;
10139 vfs_setlocklocal(mount_t mp
)
10141 mount_lock_spin(mp
);
10142 mp
->mnt_kern_flag
|= MNTK_LOCK_LOCAL
;
10146 * The number of active vnodes is expected to be
10147 * very small when vfs_setlocklocal is invoked.
10149 vnode_iterate(mp
, 0, setlocklocal_callback
, NULL
);
10153 vfs_setcompoundopen(mount_t mp
)
10155 mount_lock_spin(mp
);
10156 mp
->mnt_compound_ops
|= COMPOUND_VNOP_OPEN
;
10161 vnode_setswapmount(vnode_t vp
)
10163 mount_lock(vp
->v_mount
);
10164 vp
->v_mount
->mnt_kern_flag
|= MNTK_SWAP_MOUNT
;
10165 mount_unlock(vp
->v_mount
);
10170 vnode_getswappin_avail(vnode_t vp
)
10172 int64_t max_swappin_avail
= 0;
10174 mount_lock(vp
->v_mount
);
10175 if (vp
->v_mount
->mnt_ioflags
& MNT_IOFLAGS_SWAPPIN_SUPPORTED
) {
10176 max_swappin_avail
= vp
->v_mount
->mnt_max_swappin_available
;
10178 mount_unlock(vp
->v_mount
);
10180 return max_swappin_avail
;
10185 vn_setunionwait(vnode_t vp
)
10187 vnode_lock_spin(vp
);
10188 vp
->v_flag
|= VISUNION
;
10194 vn_checkunionwait(vnode_t vp
)
10196 vnode_lock_spin(vp
);
10197 while ((vp
->v_flag
& VISUNION
) == VISUNION
) {
10198 msleep((caddr_t
)&vp
->v_flag
, &vp
->v_lock
, 0, 0, 0);
10204 vn_clearunionwait(vnode_t vp
, int locked
)
10207 vnode_lock_spin(vp
);
10209 if ((vp
->v_flag
& VISUNION
) == VISUNION
) {
10210 vp
->v_flag
&= ~VISUNION
;
10211 wakeup((caddr_t
)&vp
->v_flag
);
10219 vnode_materialize_dataless_file(vnode_t vp
, uint64_t op_type
)
10223 /* Swap files are special; ignore them */
10224 if (vnode_isswap(vp
)) {
10228 error
= resolve_nspace_item(vp
,
10229 op_type
| NAMESPACE_HANDLER_NSPACE_EVENT
);
10232 * The file resolver owns the logic about what error to return
10233 * to the caller. We only need to handle a couple of special
10236 if (error
== EJUSTRETURN
) {
10238 * The requesting process is allowed to interact with
10239 * dataless objects. Make a couple of sanity-checks
10240 * here to ensure the action makes sense.
10243 case NAMESPACE_HANDLER_WRITE_OP
:
10244 case NAMESPACE_HANDLER_TRUNCATE_OP
:
10245 case NAMESPACE_HANDLER_RENAME_OP
:
10247 * This handles the case of the resolver itself
10248 * writing data to the file (or throwing it
10253 case NAMESPACE_HANDLER_READ_OP
:
10255 * This handles the case of the resolver needing
10256 * to look up inside of a dataless directory while
10257 * it's in the process of materializing it (for
10258 * example, creating files or directories).
10260 error
= (vnode_vtype(vp
) == VDIR
) ? 0 : EBADF
;
10272 * Removes orphaned apple double files during a rmdir
10274 * 1. vnode_suspend().
10275 * 2. Call VNOP_READDIR() till the end of directory is reached.
10276 * 3. Check if the directory entries returned are regular files with name starting with "._". If not, return ENOTEMPTY.
10277 * 4. Continue (2) and (3) till end of directory is reached.
10278 * 5. If all the entries in the directory were files with "._" name, delete all the files.
10279 * 6. vnode_resume()
10280 * 7. If deletion of all files succeeded, call VNOP_RMDIR() again.
10284 rmdir_remove_orphaned_appleDouble(vnode_t vp
, vfs_context_t ctx
, int * restart_flag
)
10286 #define UIO_BUFF_SIZE 2048
10288 int eofflag
, siz
= UIO_BUFF_SIZE
, alloc_size
= 0, nentries
= 0;
10289 int open_flag
= 0, full_erase_flag
= 0;
10290 char uio_buf
[UIO_SIZEOF(1)];
10297 error
= vnode_suspend(vp
);
10300 * restart_flag is set so that the calling rmdir sleeps and resets
10302 if (error
== EBUSY
) {
10310 * Prevent dataless fault materialization while we have
10311 * a suspended vnode.
10313 uthread_t ut
= get_bsdthread_info(current_thread());
10314 bool saved_nodatalessfaults
=
10315 (ut
->uu_flag
& UT_NSPACE_NODATALESSFAULTS
) ? true : false;
10316 ut
->uu_flag
|= UT_NSPACE_NODATALESSFAULTS
;
10321 rbuf
= kheap_alloc(KHEAP_DATA_BUFFERS
, siz
, Z_WAITOK
);
10324 auio
= uio_createwithbuffer(1, 0, UIO_SYSSPACE
, UIO_READ
,
10325 &uio_buf
[0], sizeof(uio_buf
));
10327 if (!rbuf
|| !auio
) {
10332 uio_setoffset(auio
, 0);
10336 if ((error
= VNOP_OPEN(vp
, FREAD
, ctx
))) {
10343 * First pass checks if all files are appleDouble files.
10347 siz
= UIO_BUFF_SIZE
;
10348 uio_reset(auio
, uio_offset(auio
), UIO_SYSSPACE
, UIO_READ
);
10349 uio_addiov(auio
, CAST_USER_ADDR_T(rbuf
), UIO_BUFF_SIZE
);
10351 if ((error
= VNOP_READDIR(vp
, auio
, 0, &eofflag
, &nentries
, ctx
))) {
10355 if (uio_resid(auio
) != 0) {
10356 siz
-= uio_resid(auio
);
10360 * Iterate through directory
10362 dir_pos
= (void*) rbuf
;
10363 dir_end
= (void*) (rbuf
+ siz
);
10364 dp
= (struct dirent
*) (dir_pos
);
10366 if (dir_pos
== dir_end
) {
10370 while (dir_pos
< dir_end
) {
10372 * Check for . and .. as well as directories
10374 if (dp
->d_ino
!= 0 &&
10375 !((dp
->d_namlen
== 1 && dp
->d_name
[0] == '.') ||
10376 (dp
->d_namlen
== 2 && dp
->d_name
[0] == '.' && dp
->d_name
[1] == '.'))) {
10378 * Check for irregular files and ._ files
10379 * If there is a ._._ file abort the op
10381 if (dp
->d_namlen
< 2 ||
10382 strncmp(dp
->d_name
, "._", 2) ||
10383 (dp
->d_namlen
>= 4 && !strncmp(&(dp
->d_name
[2]), "._", 2))) {
10388 dir_pos
= (void*) ((uint8_t*)dir_pos
+ dp
->d_reclen
);
10389 dp
= (struct dirent
*)dir_pos
;
10393 * workaround for HFS/NFS setting eofflag before end of file
10395 if (vp
->v_tag
== VT_HFS
&& nentries
> 2) {
10399 if (vp
->v_tag
== VT_NFS
) {
10400 if (eofflag
&& !full_erase_flag
) {
10401 full_erase_flag
= 1;
10403 uio_reset(auio
, 0, UIO_SYSSPACE
, UIO_READ
);
10404 } else if (!eofflag
&& full_erase_flag
) {
10405 full_erase_flag
= 0;
10408 } while (!eofflag
);
10410 * If we've made it here all the files in the dir are ._ files.
10411 * We can delete the files even though the node is suspended
10412 * because we are the owner of the file.
10415 uio_reset(auio
, 0, UIO_SYSSPACE
, UIO_READ
);
10417 full_erase_flag
= 0;
10420 siz
= UIO_BUFF_SIZE
;
10421 uio_reset(auio
, uio_offset(auio
), UIO_SYSSPACE
, UIO_READ
);
10422 uio_addiov(auio
, CAST_USER_ADDR_T(rbuf
), UIO_BUFF_SIZE
);
10424 error
= VNOP_READDIR(vp
, auio
, 0, &eofflag
, &nentries
, ctx
);
10430 if (uio_resid(auio
) != 0) {
10431 siz
-= uio_resid(auio
);
10435 * Iterate through directory
10437 dir_pos
= (void*) rbuf
;
10438 dir_end
= (void*) (rbuf
+ siz
);
10439 dp
= (struct dirent
*) dir_pos
;
10441 if (dir_pos
== dir_end
) {
10445 while (dir_pos
< dir_end
) {
10447 * Check for . and .. as well as directories
10449 if (dp
->d_ino
!= 0 &&
10450 !((dp
->d_namlen
== 1 && dp
->d_name
[0] == '.') ||
10451 (dp
->d_namlen
== 2 && dp
->d_name
[0] == '.' && dp
->d_name
[1] == '.'))
10453 error
= unlink1(ctx
, vp
,
10454 CAST_USER_ADDR_T(dp
->d_name
), UIO_SYSSPACE
,
10455 VNODE_REMOVE_SKIP_NAMESPACE_EVENT
|
10456 VNODE_REMOVE_NO_AUDIT_PATH
);
10458 if (error
&& error
!= ENOENT
) {
10462 dir_pos
= (void*) ((uint8_t*)dir_pos
+ dp
->d_reclen
);
10463 dp
= (struct dirent
*)dir_pos
;
10467 * workaround for HFS/NFS setting eofflag before end of file
10469 if (vp
->v_tag
== VT_HFS
&& nentries
> 2) {
10473 if (vp
->v_tag
== VT_NFS
) {
10474 if (eofflag
&& !full_erase_flag
) {
10475 full_erase_flag
= 1;
10477 uio_reset(auio
, 0, UIO_SYSSPACE
, UIO_READ
);
10478 } else if (!eofflag
&& full_erase_flag
) {
10479 full_erase_flag
= 0;
10482 } while (!eofflag
);
10489 VNOP_CLOSE(vp
, FREAD
, ctx
);
10495 kheap_free(KHEAP_DATA_BUFFERS
, rbuf
, alloc_size
);
10497 if (saved_nodatalessfaults
== false) {
10498 ut
->uu_flag
&= ~UT_NSPACE_NODATALESSFAULTS
;
10508 lock_vnode_and_post(vnode_t vp
, int kevent_num
)
10510 /* Only take the lock if there's something there! */
10511 if (vp
->v_knotes
.slh_first
!= NULL
) {
10513 KNOTE(&vp
->v_knotes
, kevent_num
);
10518 void panic_print_vnodes(void);
10520 /* define PANIC_PRINTS_VNODES only if investigation is required. */
10521 #ifdef PANIC_PRINTS_VNODES
10523 static const char *
10524 __vtype(uint16_t vtype
)
10553 * build a path from the bottom up
10554 * NOTE: called from the panic path - no alloc'ing of memory and no locks!
10557 __vpath(vnode_t vp
, char *str
, int len
, int depth
)
10566 /* str + len is the start of the string we created */
10571 /* follow mount vnodes to get the full path */
10572 if ((vp
->v_flag
& VROOT
)) {
10573 if (vp
->v_mount
!= NULL
&& vp
->v_mount
->mnt_vnodecovered
) {
10574 return __vpath(vp
->v_mount
->mnt_vnodecovered
,
10575 str
, len
, depth
+ 1);
10581 vnm_len
= strlen(src
);
10582 if (vnm_len
> len
) {
10583 /* truncate the name to fit in the string */
10584 src
+= (vnm_len
- len
);
10588 /* start from the back and copy just characters (no NULLs) */
10590 /* this will chop off leaf path (file) names */
10592 dst
= str
+ len
- vnm_len
;
10593 memcpy(dst
, src
, vnm_len
);
10599 if (vp
->v_parent
&& len
> 1) {
10600 /* follow parents up the chain */
10603 return __vpath(vp
->v_parent
, str
, len
, depth
+ 1);
10609 #define SANE_VNODE_PRINT_LIMIT 5000
10611 panic_print_vnodes(void)
10620 paniclog_append_noflush("\n***** VNODES *****\n"
10621 "TYPE UREF ICNT PATH\n");
10623 /* NULL-terminate the path name */
10624 vname
[sizeof(vname
) - 1] = '\0';
10627 * iterate all vnodelist items in all mounts (mntlist) -> mnt_vnodelist
10629 TAILQ_FOREACH(mnt
, &mountlist
, mnt_list
) {
10630 if (!ml_validate_nofault((vm_offset_t
)mnt
, sizeof(mount_t
))) {
10631 paniclog_append_noflush("Unable to iterate the mount list %p - encountered an invalid mount pointer %p \n",
10636 TAILQ_FOREACH(vp
, &mnt
->mnt_vnodelist
, v_mntvnodes
) {
10637 if (!ml_validate_nofault((vm_offset_t
)vp
, sizeof(vnode_t
))) {
10638 paniclog_append_noflush("Unable to iterate the vnode list %p - encountered an invalid vnode pointer %p \n",
10639 &mnt
->mnt_vnodelist
, vp
);
10643 if (++nvnodes
> SANE_VNODE_PRINT_LIMIT
) {
10646 type
= __vtype(vp
->v_type
);
10647 nm
= __vpath(vp
, vname
, sizeof(vname
) - 1, 0);
10648 paniclog_append_noflush("%s %0d %0d %s\n",
10649 type
, vp
->v_usecount
, vp
->v_iocount
, nm
);
10654 #else /* !PANIC_PRINTS_VNODES */
10656 panic_print_vnodes(void)
10665 record_vp(vnode_t vp
, int count
)
10667 struct uthread
*ut
;
10669 #if CONFIG_TRIGGERS
10670 if (vp
->v_resolve
) {
10674 if ((vp
->v_flag
& VSYSTEM
)) {
10678 ut
= get_bsdthread_info(current_thread());
10679 ut
->uu_iocount
+= count
;
10682 if (ut
->uu_vpindex
< 32) {
10683 OSBacktrace((void **)&ut
->uu_pcs
[ut
->uu_vpindex
][0], 10);
10685 ut
->uu_vps
[ut
->uu_vpindex
] = vp
;
10693 #if CONFIG_TRIGGERS
10695 #define TRIG_DEBUG 0
10698 #define TRIG_LOG(...) do { printf("%s: ", __FUNCTION__); printf(__VA_ARGS__); } while (0)
10700 #define TRIG_LOG(...)
10704 * Resolver result functions
10708 vfs_resolver_result(uint32_t seq
, enum resolver_status stat
, int aux
)
10711 * |<--- 32 --->|<--- 28 --->|<- 4 ->|
10712 * sequence auxiliary status
10714 return (((uint64_t)seq
) << 32) |
10715 (((uint64_t)(aux
& 0x0fffffff)) << 4) |
10716 (uint64_t)(stat
& 0x0000000F);
10719 enum resolver_status
10720 vfs_resolver_status(resolver_result_t result
)
10722 /* lower 4 bits is status */
10723 return result
& 0x0000000F;
10727 vfs_resolver_sequence(resolver_result_t result
)
10729 /* upper 32 bits is sequence */
10730 return (uint32_t)(result
>> 32);
10734 vfs_resolver_auxiliary(resolver_result_t result
)
10736 /* 28 bits of auxiliary */
10737 return (int)(((uint32_t)(result
& 0xFFFFFFF0)) >> 4);
10742 * Call in for resolvers to update vnode trigger state
10745 vnode_trigger_update(vnode_t vp
, resolver_result_t result
)
10747 vnode_resolve_t rp
;
10749 enum resolver_status stat
;
10751 if (vp
->v_resolve
== NULL
) {
10755 stat
= vfs_resolver_status(result
);
10756 seq
= vfs_resolver_sequence(result
);
10758 if ((stat
!= RESOLVER_RESOLVED
) && (stat
!= RESOLVER_UNRESOLVED
)) {
10762 rp
= vp
->v_resolve
;
10763 lck_mtx_lock(&rp
->vr_lock
);
10765 if (seq
> rp
->vr_lastseq
) {
10766 if (stat
== RESOLVER_RESOLVED
) {
10767 rp
->vr_flags
|= VNT_RESOLVED
;
10769 rp
->vr_flags
&= ~VNT_RESOLVED
;
10772 rp
->vr_lastseq
= seq
;
10775 lck_mtx_unlock(&rp
->vr_lock
);
10781 vnode_resolver_attach(vnode_t vp
, vnode_resolve_t rp
, boolean_t ref
)
10785 vnode_lock_spin(vp
);
10786 if (vp
->v_resolve
!= NULL
) {
10790 vp
->v_resolve
= rp
;
10795 error
= vnode_ref_ext(vp
, O_EVTONLY
, VNODE_REF_FORCE
);
10797 panic("VNODE_REF_FORCE didn't help...");
10805 * VFS internal interfaces for vnode triggers
10807 * vnode must already have an io count on entry
10808 * v_resolve is stable when io count is non-zero
10811 vnode_resolver_create(mount_t mp
, vnode_t vp
, struct vnode_trigger_param
*tinfo
, boolean_t external
)
10813 vnode_resolve_t rp
;
10818 /* minimum pointer test (debugging) */
10819 if (tinfo
->vnt_data
) {
10820 byte
= *((char *)tinfo
->vnt_data
);
10823 rp
= kheap_alloc(KHEAP_DEFAULT
, sizeof(struct vnode_resolve
), Z_WAITOK
);
10828 lck_mtx_init(&rp
->vr_lock
, &trigger_vnode_lck_grp
, &trigger_vnode_lck_attr
);
10830 rp
->vr_resolve_func
= tinfo
->vnt_resolve_func
;
10831 rp
->vr_unresolve_func
= tinfo
->vnt_unresolve_func
;
10832 rp
->vr_rearm_func
= tinfo
->vnt_rearm_func
;
10833 rp
->vr_reclaim_func
= tinfo
->vnt_reclaim_func
;
10834 rp
->vr_data
= tinfo
->vnt_data
;
10835 rp
->vr_lastseq
= 0;
10836 rp
->vr_flags
= tinfo
->vnt_flags
& VNT_VALID_MASK
;
10838 rp
->vr_flags
|= VNT_EXTERNAL
;
10841 result
= vnode_resolver_attach(vp
, rp
, external
);
10847 OSAddAtomic(1, &mp
->mnt_numtriggers
);
10853 kheap_free(KHEAP_DEFAULT
, rp
, sizeof(struct vnode_resolve
));
10858 vnode_resolver_release(vnode_resolve_t rp
)
10861 * Give them a chance to free any private data
10863 if (rp
->vr_data
&& rp
->vr_reclaim_func
) {
10864 rp
->vr_reclaim_func(NULLVP
, rp
->vr_data
);
10867 lck_mtx_destroy(&rp
->vr_lock
, &trigger_vnode_lck_grp
);
10868 kheap_free(KHEAP_DEFAULT
, rp
, sizeof(struct vnode_resolve
));
10871 /* Called after the vnode has been drained */
10873 vnode_resolver_detach(vnode_t vp
)
10875 vnode_resolve_t rp
;
10878 mp
= vnode_mount(vp
);
10881 rp
= vp
->v_resolve
;
10882 vp
->v_resolve
= NULL
;
10885 if ((rp
->vr_flags
& VNT_EXTERNAL
) != 0) {
10886 vnode_rele_ext(vp
, O_EVTONLY
, 1);
10889 vnode_resolver_release(rp
);
10891 /* Keep count of active trigger vnodes per mount */
10892 OSAddAtomic(-1, &mp
->mnt_numtriggers
);
10897 vnode_trigger_rearm(vnode_t vp
, vfs_context_t ctx
)
10899 vnode_resolve_t rp
;
10900 resolver_result_t result
;
10901 enum resolver_status status
;
10904 if ((vp
->v_resolve
== NULL
) ||
10905 (vp
->v_resolve
->vr_rearm_func
== NULL
) ||
10906 (vp
->v_resolve
->vr_flags
& VNT_AUTO_REARM
) == 0) {
10910 rp
= vp
->v_resolve
;
10911 lck_mtx_lock(&rp
->vr_lock
);
10914 * Check if VFS initiated this unmount. If so, we'll catch it after the unresolve completes.
10916 if (rp
->vr_flags
& VNT_VFS_UNMOUNTED
) {
10917 lck_mtx_unlock(&rp
->vr_lock
);
10921 /* Check if this vnode is already armed */
10922 if ((rp
->vr_flags
& VNT_RESOLVED
) == 0) {
10923 lck_mtx_unlock(&rp
->vr_lock
);
10927 lck_mtx_unlock(&rp
->vr_lock
);
10929 result
= rp
->vr_rearm_func(vp
, 0, rp
->vr_data
, ctx
);
10930 status
= vfs_resolver_status(result
);
10931 seq
= vfs_resolver_sequence(result
);
10933 lck_mtx_lock(&rp
->vr_lock
);
10934 if (seq
> rp
->vr_lastseq
) {
10935 if (status
== RESOLVER_UNRESOLVED
) {
10936 rp
->vr_flags
&= ~VNT_RESOLVED
;
10938 rp
->vr_lastseq
= seq
;
10940 lck_mtx_unlock(&rp
->vr_lock
);
10945 vnode_trigger_resolve(vnode_t vp
, struct nameidata
*ndp
, vfs_context_t ctx
)
10947 vnode_resolve_t rp
;
10948 enum path_operation op
;
10949 resolver_result_t result
;
10950 enum resolver_status status
;
10954 * N.B. we cannot call vfs_context_can_resolve_triggers()
10955 * here because we really only want to suppress that in
10956 * the event the trigger will be resolved by something in
10957 * user-space. Any triggers that are resolved by the kernel
10958 * do not pose a threat of deadlock.
10961 /* Only trigger on topmost vnodes */
10962 if ((vp
->v_resolve
== NULL
) ||
10963 (vp
->v_resolve
->vr_resolve_func
== NULL
) ||
10964 (vp
->v_mountedhere
!= NULL
)) {
10968 rp
= vp
->v_resolve
;
10969 lck_mtx_lock(&rp
->vr_lock
);
10971 /* Check if this vnode is already resolved */
10972 if (rp
->vr_flags
& VNT_RESOLVED
) {
10973 lck_mtx_unlock(&rp
->vr_lock
);
10977 lck_mtx_unlock(&rp
->vr_lock
);
10980 if ((rp
->vr_flags
& VNT_KERN_RESOLVE
) == 0) {
10982 * VNT_KERN_RESOLVE indicates this trigger has no parameters
10983 * at the discression of the accessing process other than
10984 * the act of access. All other triggers must be checked
10986 int rv
= mac_vnode_check_trigger_resolve(ctx
, vp
, &ndp
->ni_cnd
);
10995 * assumes that resolver will not access this trigger vnode (otherwise the kernel will deadlock)
10996 * is there anyway to know this???
10997 * there can also be other legitimate lookups in parallel
10999 * XXX - should we call this on a separate thread with a timeout?
11001 * XXX - should we use ISLASTCN to pick the op value??? Perhaps only leafs should
11002 * get the richer set and non-leafs should get generic OP_LOOKUP? TBD
11004 op
= (ndp
->ni_op
< OP_MAXOP
) ? ndp
->ni_op
: OP_LOOKUP
;
11006 result
= rp
->vr_resolve_func(vp
, &ndp
->ni_cnd
, op
, 0, rp
->vr_data
, ctx
);
11007 status
= vfs_resolver_status(result
);
11008 seq
= vfs_resolver_sequence(result
);
11010 lck_mtx_lock(&rp
->vr_lock
);
11011 if (seq
> rp
->vr_lastseq
) {
11012 if (status
== RESOLVER_RESOLVED
) {
11013 rp
->vr_flags
|= VNT_RESOLVED
;
11015 rp
->vr_lastseq
= seq
;
11017 lck_mtx_unlock(&rp
->vr_lock
);
11019 /* On resolver errors, propagate the error back up */
11020 return status
== RESOLVER_ERROR
? vfs_resolver_auxiliary(result
) : 0;
11024 vnode_trigger_unresolve(vnode_t vp
, int flags
, vfs_context_t ctx
)
11026 vnode_resolve_t rp
;
11027 resolver_result_t result
;
11028 enum resolver_status status
;
11031 if ((vp
->v_resolve
== NULL
) || (vp
->v_resolve
->vr_unresolve_func
== NULL
)) {
11035 rp
= vp
->v_resolve
;
11036 lck_mtx_lock(&rp
->vr_lock
);
11038 /* Check if this vnode is already resolved */
11039 if ((rp
->vr_flags
& VNT_RESOLVED
) == 0) {
11040 printf("vnode_trigger_unresolve: not currently resolved\n");
11041 lck_mtx_unlock(&rp
->vr_lock
);
11045 rp
->vr_flags
|= VNT_VFS_UNMOUNTED
;
11047 lck_mtx_unlock(&rp
->vr_lock
);
11051 * assumes that resolver will not access this trigger vnode (otherwise the kernel will deadlock)
11052 * there can also be other legitimate lookups in parallel
11054 * XXX - should we call this on a separate thread with a timeout?
11057 result
= rp
->vr_unresolve_func(vp
, flags
, rp
->vr_data
, ctx
);
11058 status
= vfs_resolver_status(result
);
11059 seq
= vfs_resolver_sequence(result
);
11061 lck_mtx_lock(&rp
->vr_lock
);
11062 if (seq
> rp
->vr_lastseq
) {
11063 if (status
== RESOLVER_UNRESOLVED
) {
11064 rp
->vr_flags
&= ~VNT_RESOLVED
;
11066 rp
->vr_lastseq
= seq
;
11068 rp
->vr_flags
&= ~VNT_VFS_UNMOUNTED
;
11069 lck_mtx_unlock(&rp
->vr_lock
);
11071 /* On resolver errors, propagate the error back up */
11072 return status
== RESOLVER_ERROR
? vfs_resolver_auxiliary(result
) : 0;
11076 triggerisdescendant(mount_t mp
, mount_t rmp
)
11081 * walk up vnode covered chain looking for a match
11083 name_cache_lock_shared();
11088 /* did we encounter "/" ? */
11089 if (mp
->mnt_flag
& MNT_ROOTFS
) {
11093 vp
= mp
->mnt_vnodecovered
;
11094 if (vp
== NULLVP
) {
11105 name_cache_unlock();
11110 struct trigger_unmount_info
{
11113 vnode_t trigger_vp
;
11114 mount_t trigger_mp
;
11115 uint32_t trigger_vid
;
11120 trigger_unmount_callback(mount_t mp
, void * arg
)
11122 struct trigger_unmount_info
* infop
= (struct trigger_unmount_info
*)arg
;
11123 boolean_t mountedtrigger
= FALSE
;
11126 * When we encounter the top level mount we're done
11128 if (mp
== infop
->top_mp
) {
11129 return VFS_RETURNED_DONE
;
11132 if ((mp
->mnt_vnodecovered
== NULL
) ||
11133 (vnode_getwithref(mp
->mnt_vnodecovered
) != 0)) {
11134 return VFS_RETURNED
;
11137 if ((mp
->mnt_vnodecovered
->v_mountedhere
== mp
) &&
11138 (mp
->mnt_vnodecovered
->v_resolve
!= NULL
) &&
11139 (mp
->mnt_vnodecovered
->v_resolve
->vr_flags
& VNT_RESOLVED
)) {
11140 mountedtrigger
= TRUE
;
11142 vnode_put(mp
->mnt_vnodecovered
);
11145 * When we encounter a mounted trigger, check if its under the top level mount
11147 if (!mountedtrigger
|| !triggerisdescendant(mp
, infop
->top_mp
)) {
11148 return VFS_RETURNED
;
11152 * Process any pending nested mount (now that its not referenced)
11154 if ((infop
->trigger_vp
!= NULLVP
) &&
11155 (vnode_getwithvid(infop
->trigger_vp
, infop
->trigger_vid
) == 0)) {
11156 vnode_t vp
= infop
->trigger_vp
;
11159 infop
->trigger_vp
= NULLVP
;
11161 if (mp
== vp
->v_mountedhere
) {
11163 printf("trigger_unmount_callback: unexpected match '%s'\n",
11164 mp
->mnt_vfsstat
.f_mntonname
);
11165 return VFS_RETURNED
;
11167 if (infop
->trigger_mp
!= vp
->v_mountedhere
) {
11169 printf("trigger_unmount_callback: trigger mnt changed! (%p != %p)\n",
11170 infop
->trigger_mp
, vp
->v_mountedhere
);
11174 error
= vnode_trigger_unresolve(vp
, infop
->flags
, infop
->ctx
);
11177 printf("unresolving: '%s', err %d\n",
11178 vp
->v_mountedhere
? vp
->v_mountedhere
->mnt_vfsstat
.f_mntonname
:
11180 return VFS_RETURNED_DONE
; /* stop iteration on errors */
11185 * We can't call resolver here since we hold a mount iter
11186 * ref on mp so save its covered vp for later processing
11188 infop
->trigger_vp
= mp
->mnt_vnodecovered
;
11189 if ((infop
->trigger_vp
!= NULLVP
) &&
11190 (vnode_getwithref(infop
->trigger_vp
) == 0)) {
11191 if (infop
->trigger_vp
->v_mountedhere
== mp
) {
11192 infop
->trigger_vid
= infop
->trigger_vp
->v_id
;
11193 infop
->trigger_mp
= mp
;
11195 vnode_put(infop
->trigger_vp
);
11198 return VFS_RETURNED
;
11202 * Attempt to unmount any trigger mounts nested underneath a mount.
11203 * This is a best effort attempt and no retries are performed here.
11205 * Note: mp->mnt_rwlock is held exclusively on entry (so be carefull)
11209 vfs_nested_trigger_unmounts(mount_t mp
, int flags
, vfs_context_t ctx
)
11211 struct trigger_unmount_info info
;
11213 /* Must have trigger vnodes */
11214 if (mp
->mnt_numtriggers
== 0) {
11217 /* Avoid recursive requests (by checking covered vnode) */
11218 if ((mp
->mnt_vnodecovered
!= NULL
) &&
11219 (vnode_getwithref(mp
->mnt_vnodecovered
) == 0)) {
11220 boolean_t recursive
= FALSE
;
11222 if ((mp
->mnt_vnodecovered
->v_mountedhere
== mp
) &&
11223 (mp
->mnt_vnodecovered
->v_resolve
!= NULL
) &&
11224 (mp
->mnt_vnodecovered
->v_resolve
->vr_flags
& VNT_VFS_UNMOUNTED
)) {
11227 vnode_put(mp
->mnt_vnodecovered
);
11234 * Attempt to unmount any nested trigger mounts (best effort)
11238 info
.trigger_vp
= NULLVP
;
11239 info
.trigger_vid
= 0;
11240 info
.trigger_mp
= NULL
;
11241 info
.flags
= flags
;
11243 (void) vfs_iterate(VFS_ITERATE_TAIL_FIRST
, trigger_unmount_callback
, &info
);
11246 * Process remaining nested mount (now that its not referenced)
11248 if ((info
.trigger_vp
!= NULLVP
) &&
11249 (vnode_getwithvid(info
.trigger_vp
, info
.trigger_vid
) == 0)) {
11250 vnode_t vp
= info
.trigger_vp
;
11252 if (info
.trigger_mp
== vp
->v_mountedhere
) {
11253 (void) vnode_trigger_unresolve(vp
, flags
, ctx
);
11260 vfs_addtrigger(mount_t mp
, const char *relpath
, struct vnode_trigger_info
*vtip
, vfs_context_t ctx
)
11262 struct nameidata
*ndp
;
11265 struct vnode_trigger_param vtp
;
11268 * Must be called for trigger callback, wherein rwlock is held
11270 lck_rw_assert(&mp
->mnt_rwlock
, LCK_RW_ASSERT_HELD
);
11272 TRIG_LOG("Adding trigger at %s\n", relpath
);
11273 TRIG_LOG("Trying VFS_ROOT\n");
11275 ndp
= kheap_alloc(KHEAP_TEMP
, sizeof(struct nameidata
), Z_WAITOK
);
11281 * We do a lookup starting at the root of the mountpoint, unwilling
11282 * to cross into other mountpoints.
11284 res
= VFS_ROOT(mp
, &rvp
, ctx
);
11289 TRIG_LOG("Trying namei\n");
11291 NDINIT(ndp
, LOOKUP
, OP_LOOKUP
, USEDVP
| NOCROSSMOUNT
| FOLLOW
, UIO_SYSSPACE
,
11292 CAST_USER_ADDR_T(relpath
), ctx
);
11304 TRIG_LOG("Trying vnode_resolver_create()\n");
11307 * Set up blob. vnode_create() takes a larger structure
11308 * with creation info, and we needed something different
11309 * for this case. One needs to win, or we need to munge both;
11310 * vnode_create() wins.
11312 bzero(&vtp
, sizeof(vtp
));
11313 vtp
.vnt_resolve_func
= vtip
->vti_resolve_func
;
11314 vtp
.vnt_unresolve_func
= vtip
->vti_unresolve_func
;
11315 vtp
.vnt_rearm_func
= vtip
->vti_rearm_func
;
11316 vtp
.vnt_reclaim_func
= vtip
->vti_reclaim_func
;
11317 vtp
.vnt_reclaim_func
= vtip
->vti_reclaim_func
;
11318 vtp
.vnt_data
= vtip
->vti_data
;
11319 vtp
.vnt_flags
= vtip
->vti_flags
;
11321 res
= vnode_resolver_create(mp
, vp
, &vtp
, TRUE
);
11324 kheap_free(KHEAP_TEMP
, ndp
, sizeof(struct nameidata
));
11325 TRIG_LOG("Returning %d\n", res
);
11329 #endif /* CONFIG_TRIGGERS */
11332 kdebug_vnode(vnode_t vp
)
11334 return VM_KERNEL_ADDRPERM(vp
);
11337 static int flush_cache_on_write
= 0;
11338 SYSCTL_INT(_kern
, OID_AUTO
, flush_cache_on_write
,
11339 CTLFLAG_RW
| CTLFLAG_LOCKED
, &flush_cache_on_write
, 0,
11340 "always flush the drive cache on writes to uncached files");
11343 vnode_should_flush_after_write(vnode_t vp
, int ioflag
)
11345 return flush_cache_on_write
11346 && (ISSET(ioflag
, IO_NOCACHE
) || vnode_isnocache(vp
));
11350 * sysctl for use by disk I/O tracing tools to get the list of existing
11354 #define NPATH_WORDS (MAXPATHLEN / sizeof(unsigned long))
11355 struct vnode_trace_paths_context
{
11358 * Must be a multiple of 4, then -1, for tracing!
11360 unsigned long path
[NPATH_WORDS
+ (4 - (NPATH_WORDS
% 4)) - 1];
11364 vnode_trace_path_callback(struct vnode
*vp
, void *vctx
)
11366 struct vnode_trace_paths_context
*ctx
= vctx
;
11367 size_t path_len
= sizeof(ctx
->path
);
11369 int getpath_len
= (int)path_len
;
11370 if (vn_getpath(vp
, (char *)ctx
->path
, &getpath_len
) == 0) {
11371 /* vn_getpath() NUL-terminates, and len includes the NUL. */
11372 assert(getpath_len
>= 0);
11373 path_len
= (size_t)getpath_len
;
11375 assert(path_len
<= sizeof(ctx
->path
));
11376 kdebug_vfs_lookup(ctx
->path
, (int)path_len
, vp
,
11377 KDBG_VFS_LOOKUP_FLAG_LOOKUP
| KDBG_VFS_LOOKUP_FLAG_NOPROCFILT
);
11379 if (++(ctx
->count
) == 1000) {
11380 thread_yield_to_preemption();
11385 return VNODE_RETURNED
;
11389 vfs_trace_paths_callback(mount_t mp
, void *arg
)
11391 if (mp
->mnt_flag
& MNT_LOCAL
) {
11392 vnode_iterate(mp
, VNODE_ITERATE_ALL
, vnode_trace_path_callback
, arg
);
11395 return VFS_RETURNED
;
11398 static int sysctl_vfs_trace_paths SYSCTL_HANDLER_ARGS
{
11399 struct vnode_trace_paths_context ctx
;
11406 if (!kauth_cred_issuser(kauth_cred_get())) {
11410 if (!kdebug_enable
|| !kdebug_debugid_enabled(VFS_LOOKUP
)) {
11414 bzero(&ctx
, sizeof(struct vnode_trace_paths_context
));
11416 vfs_iterate(0, vfs_trace_paths_callback
, &ctx
);
11421 SYSCTL_PROC(_vfs_generic
, OID_AUTO
, trace_paths
, CTLFLAG_RD
| CTLFLAG_LOCKED
| CTLFLAG_MASKED
, NULL
, 0, &sysctl_vfs_trace_paths
, "-", "trace_paths");