xref: /xnu-8792.61.2/bsd/vfs/vfs_subr.c (revision 42e220869062b56f8d7d0726fd4c88954f87902c)
1 /*
2  *
3  * Copyright (c) 2000-2019 Apple Inc. All rights reserved.
4  *
5  * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
6  *
7  * This file contains Original Code and/or Modifications of Original Code
8  * as defined in and that are subject to the Apple Public Source License
9  * Version 2.0 (the 'License'). You may not use this file except in
10  * compliance with the License. The rights granted to you under the License
11  * may not be used to create, or enable the creation or redistribution of,
12  * unlawful or unlicensed copies of an Apple operating system, or to
13  * circumvent, violate, or enable the circumvention or violation of, any
14  * terms of an Apple operating system software license agreement.
15  *
16  * Please obtain a copy of the License at
17  * http://www.opensource.apple.com/apsl/ and read it before using this file.
18  *
19  * The Original Code and all software distributed under the License are
20  * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
21  * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
22  * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
23  * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
24  * Please see the License for the specific language governing rights and
25  * limitations under the License.
26  *
27  * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
28  */
29 /* Copyright (c) 1995 NeXT Computer, Inc. All Rights Reserved */
30 /*
31  * Copyright (c) 1989, 1993
32  *	The Regents of the University of California.  All rights reserved.
33  * (c) UNIX System Laboratories, Inc.
34  * All or some portions of this file are derived from material licensed
35  * to the University of California by American Telephone and Telegraph
36  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
37  * the permission of UNIX System Laboratories, Inc.
38  *
39  * Redistribution and use in source and binary forms, with or without
40  * modification, are permitted provided that the following conditions
41  * are met:
42  * 1. Redistributions of source code must retain the above copyright
43  *    notice, this list of conditions and the following disclaimer.
44  * 2. Redistributions in binary form must reproduce the above copyright
45  *    notice, this list of conditions and the following disclaimer in the
46  *    documentation and/or other materials provided with the distribution.
47  * 3. All advertising materials mentioning features or use of this software
48  *    must display the following acknowledgement:
49  *	This product includes software developed by the University of
50  *	California, Berkeley and its contributors.
51  * 4. Neither the name of the University nor the names of its contributors
52  *    may be used to endorse or promote products derived from this software
53  *    without specific prior written permission.
54  *
55  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
56  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
57  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
58  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
59  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
60  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
61  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
62  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
63  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
64  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
65  * SUCH DAMAGE.
66  *
67  *	@(#)vfs_subr.c	8.31 (Berkeley) 5/26/95
68  */
69 /*
70  * NOTICE: This file was modified by SPARTA, Inc. in 2005 to introduce
71  * support for mandatory and extensible security protections.  This notice
72  * is included in support of clause 2.2 (b) of the Apple Public License,
73  * Version 2.0.
74  */
75 
76 /*
77  * External virtual filesystem routines
78  */
79 
80 #include <sys/param.h>
81 #include <sys/systm.h>
82 #include <sys/proc_internal.h>
83 #include <sys/kauth.h>
84 #include <sys/mount_internal.h>
85 #include <sys/time.h>
86 #include <sys/lock.h>
87 #include <sys/vnode.h>
88 #include <sys/vnode_internal.h>
89 #include <sys/stat.h>
90 #include <sys/namei.h>
91 #include <sys/ucred.h>
92 #include <sys/buf_internal.h>
93 #include <sys/errno.h>
94 #include <kern/kalloc.h>
95 #include <sys/uio_internal.h>
96 #include <sys/uio.h>
97 #include <sys/domain.h>
98 #include <sys/mbuf.h>
99 #include <sys/syslog.h>
100 #include <sys/ubc_internal.h>
101 #include <sys/vm.h>
102 #include <sys/sysctl.h>
103 #include <sys/filedesc.h>
104 #include <sys/event.h>
105 #include <sys/kdebug.h>
106 #include <sys/kauth.h>
107 #include <sys/user.h>
108 #include <sys/systm.h>
109 #include <sys/kern_memorystatus.h>
110 #include <sys/lockf.h>
111 #include <sys/reboot.h>
112 #include <miscfs/fifofs/fifo.h>
113 
114 #include <nfs/nfs.h>
115 
116 #include <string.h>
117 #include <machine/machine_routines.h>
118 
119 #include <kern/assert.h>
120 #include <mach/kern_return.h>
121 #include <kern/thread.h>
122 #include <kern/sched_prim.h>
123 
124 #include <miscfs/specfs/specdev.h>
125 
126 #include <mach/mach_types.h>
127 #include <mach/memory_object_types.h>
128 #include <mach/memory_object_control.h>
129 
130 #include <kern/kalloc.h>        /* kalloc()/kfree() */
131 #include <kern/clock.h>         /* delay_for_interval() */
132 #include <libkern/OSAtomic.h>   /* OSAddAtomic() */
133 #include <os/atomic_private.h>
134 #if defined(XNU_TARGET_OS_OSX)
135 #include <console/video_console.h>
136 #endif
137 
138 #ifdef CONFIG_IOCOUNT_TRACE
139 #include <libkern/OSDebug.h>
140 #endif
141 
142 #include <vm/vm_protos.h>       /* vnode_pager_vrele() */
143 
144 #if CONFIG_MACF
145 #include <security/mac_framework.h>
146 #endif
147 
148 #include <vfs/vfs_disk_conditioner.h>
149 #include <libkern/section_keywords.h>
150 
151 static LCK_GRP_DECLARE(vnode_lck_grp, "vnode");
152 static LCK_ATTR_DECLARE(vnode_lck_attr, 0, 0);
153 
154 #if CONFIG_TRIGGERS
155 static LCK_GRP_DECLARE(trigger_vnode_lck_grp, "trigger_vnode");
156 static LCK_ATTR_DECLARE(trigger_vnode_lck_attr, 0, 0);
157 #endif
158 
159 extern lck_mtx_t mnt_list_mtx_lock;
160 
161 ZONE_DEFINE(specinfo_zone, "specinfo",
162     sizeof(struct specinfo), ZC_ZFREE_CLEARMEM);
163 
164 ZONE_DEFINE(vnode_zone, "vnodes",
165     sizeof(struct vnode), ZC_NOGC | ZC_ZFREE_CLEARMEM);
166 
167 enum vtype iftovt_tab[16] = {
168 	VNON, VFIFO, VCHR, VNON, VDIR, VNON, VBLK, VNON,
169 	VREG, VNON, VLNK, VNON, VSOCK, VNON, VNON, VBAD,
170 };
171 int     vttoif_tab[9] = {
172 	0, S_IFREG, S_IFDIR, S_IFBLK, S_IFCHR, S_IFLNK,
173 	S_IFSOCK, S_IFIFO, S_IFMT,
174 };
175 
176 /* XXX These should be in a BSD accessible Mach header, but aren't. */
177 extern void             memory_object_mark_used(
178 	memory_object_control_t         control);
179 
180 extern void             memory_object_mark_unused(
181 	memory_object_control_t         control,
182 	boolean_t                       rage);
183 
184 extern void             memory_object_mark_io_tracking(
185 	memory_object_control_t         control);
186 
187 extern int paniclog_append_noflush(const char *format, ...);
188 
189 /* XXX next prototytype should be from libsa/stdlib.h> but conflicts libkern */
190 __private_extern__ void qsort(
191 	void * array,
192 	size_t nmembers,
193 	size_t member_size,
194 	int (*)(const void *, const void *));
195 
196 __private_extern__ void vntblinit(void);
197 __private_extern__ int unlink1(vfs_context_t, vnode_t, user_addr_t,
198     enum uio_seg, int);
199 
200 static void vnode_list_add(vnode_t);
201 static void vnode_async_list_add(vnode_t);
202 static void vnode_list_remove(vnode_t);
203 static void vnode_list_remove_locked(vnode_t);
204 
205 static void vnode_abort_advlocks(vnode_t);
206 static errno_t vnode_drain(vnode_t);
207 static void vgone(vnode_t, int flags);
208 static void vclean(vnode_t vp, int flag);
209 static void vnode_reclaim_internal(vnode_t, int, int, int);
210 
211 static void vnode_dropiocount(vnode_t);
212 
213 static vnode_t checkalias(vnode_t vp, dev_t nvp_rdev);
214 static int  vnode_reload(vnode_t);
215 
216 static int unmount_callback(mount_t, __unused void *);
217 
218 static void insmntque(vnode_t vp, mount_t mp);
219 static int mount_getvfscnt(void);
220 static int mount_fillfsids(fsid_t *, int );
221 static void vnode_iterate_setup(mount_t);
222 int vnode_umount_preflight(mount_t, vnode_t, int);
223 static int vnode_iterate_prepare(mount_t);
224 static int vnode_iterate_reloadq(mount_t);
225 static void vnode_iterate_clear(mount_t);
226 static mount_t vfs_getvfs_locked(fsid_t *);
227 static int vn_create_reg(vnode_t dvp, vnode_t *vpp, struct nameidata *ndp,
228     struct vnode_attr *vap, uint32_t flags, int fmode, uint32_t *statusp, vfs_context_t ctx);
229 static int vnode_authattr_new_internal(vnode_t dvp, struct vnode_attr *vap, int noauth, uint32_t *defaulted_fieldsp, vfs_context_t ctx);
230 
231 errno_t rmdir_remove_orphaned_appleDouble(vnode_t, vfs_context_t, int *);
232 
233 #ifdef CONFIG_IOCOUNT_TRACE
234 static void record_vp(vnode_t vp, int count);
235 static TUNABLE(int, bootarg_vnode_iocount_trace, "vnode_iocount_trace", 0);
236 static TUNABLE(int, bootarg_uthread_iocount_trace, "uthread_iocount_trace", 0);
237 #endif /* CONFIG_IOCOUNT_TRACE */
238 
239 #if CONFIG_JETSAM && (DEVELOPMENT || DEBUG)
240 static TUNABLE(bool, bootarg_no_vnode_jetsam, "-no_vnode_jetsam", false);
241 #endif /* CONFIG_JETSAM && (DEVELOPMENT || DEBUG) */
242 
243 static TUNABLE(bool, bootarg_no_vnode_drain, "-no_vnode_drain", false);
244 
245 __options_decl(freeable_vnode_level_t, uint32_t, {
246 	DEALLOC_VNODE_NONE = 0,
247 	DEALLOC_VNODE_ONLY_OVERFLOW = 1,
248 	DEALLOC_VNODE_ALL = 2
249 });
250 
251 #if XNU_TARGET_OS_OSX
252 static TUNABLE(freeable_vnode_level_t, bootarg_vn_dealloc_level, "vn_dealloc_level", DEALLOC_VNODE_NONE);
253 #else
254 static TUNABLE(freeable_vnode_level_t, bootarg_vn_dealloc_level, "vn_dealloc_level", DEALLOC_VNODE_NONE);
255 #endif /* CONFIG_VNDEALLOC */
256 
257 static freeable_vnode_level_t vn_dealloc_level = DEALLOC_VNODE_NONE;
258 
259 boolean_t root_is_CF_drive = FALSE;
260 
261 #if CONFIG_TRIGGERS
262 static int vnode_resolver_create(mount_t, vnode_t, struct vnode_trigger_param *, boolean_t external);
263 static void vnode_resolver_detach(vnode_t);
264 #endif
265 
266 TAILQ_HEAD(freelst, vnode) vnode_free_list;     /* vnode free list */
267 TAILQ_HEAD(deadlst, vnode) vnode_dead_list;     /* vnode dead list */
268 TAILQ_HEAD(async_work_lst, vnode) vnode_async_work_list;
269 
270 
271 TAILQ_HEAD(ragelst, vnode) vnode_rage_list;     /* vnode rapid age list */
272 struct timeval rage_tv;
273 int     rage_limit = 0;
274 int     ragevnodes = 0;
275 
276 long  reusablevnodes_max = LONG_MAX;
277 long  reusablevnodes = 0;
278 int   deadvnodes_low = 0;
279 int   deadvnodes_high = 0;
280 int   numvnodes_min = 0;
281 int   numvnodes_max = 0;
282 
283 uint64_t newvnode = 0;
284 unsigned long newvnode_nodead = 0;
285 
286 static  int vfs_unmountall_started = 0;
287 static  int vfs_unmountall_finished = 0;
288 static  uint64_t vfs_shutdown_last_completion_time;
289 
290 #define RAGE_LIMIT_MIN  100
291 #define RAGE_TIME_LIMIT 5
292 
293 /*
294  * ROSV definitions
295  * NOTE: These are shadowed from PlatformSupport definitions, but XNU
296  * builds standalone.
297  */
298 #define PLATFORM_DATA_VOLUME_MOUNT_POINT "/System/Volumes/Data"
299 
300 /*
301  * These could be in PlatformSupport but aren't yet
302  */
303 #define PLATFORM_PREBOOT_VOLUME_MOUNT_POINT "/System/Volumes/Preboot"
304 #define PLATFORM_RECOVERY_VOLUME_MOUNT_POINT "/System/Volumes/Recovery"
305 
306 #if CONFIG_MOUNT_VM
307 #define PLATFORM_VM_VOLUME_MOUNT_POINT "/System/Volumes/VM"
308 #endif
309 
310 struct mntlist mountlist;                       /* mounted filesystem list */
311 static int nummounts = 0;
312 
313 static int print_busy_vnodes = 0;                               /* print out busy vnodes */
314 
315 #if DIAGNOSTIC
316 #define VLISTCHECK(fun, vp, list)       \
317 	if ((vp)->v_freelist.tqe_prev == (struct vnode **)0xdeadb) \
318 	        panic("%s: %s vnode not on %slist", (fun), (list), (list));
319 #else
320 #define VLISTCHECK(fun, vp, list)
321 #endif /* DIAGNOSTIC */
322 
323 #define VLISTNONE(vp)   \
324 	do {    \
325 	        (vp)->v_freelist.tqe_next = (struct vnode *)0;  \
326 	        (vp)->v_freelist.tqe_prev = (struct vnode **)0xdeadb;   \
327 	} while(0)
328 
329 #define VONLIST(vp)     \
330 	((vp)->v_freelist.tqe_prev != (struct vnode **)0xdeadb)
331 
332 /* remove a vnode from free vnode list */
333 #define VREMFREE(fun, vp)       \
334 	do {    \
335 	        VLISTCHECK((fun), (vp), "free");        \
336 	        TAILQ_REMOVE(&vnode_free_list, (vp), v_freelist);       \
337 	        VLISTNONE((vp));        \
338 	        freevnodes--;   \
339 	        reusablevnodes--;    \
340 	} while(0)
341 
342 
343 /* remove a vnode from dead vnode list */
344 #define VREMDEAD(fun, vp)       \
345 	do {    \
346 	        VLISTCHECK((fun), (vp), "dead");        \
347 	        TAILQ_REMOVE(&vnode_dead_list, (vp), v_freelist);       \
348 	        VLISTNONE((vp));        \
349 	        vp->v_listflag &= ~VLIST_DEAD;  \
350 	        deadvnodes--;   \
351 	        if (vp->v_listflag & VLIST_NO_REUSE) {        \
352 	                deadvnodes_noreuse--;        \
353 	        }        \
354 	} while(0)
355 
356 
357 /* remove a vnode from async work vnode list */
358 #define VREMASYNC_WORK(fun, vp) \
359 	do {    \
360 	        VLISTCHECK((fun), (vp), "async_work");  \
361 	        TAILQ_REMOVE(&vnode_async_work_list, (vp), v_freelist); \
362 	        VLISTNONE((vp));        \
363 	        vp->v_listflag &= ~VLIST_ASYNC_WORK;    \
364 	        async_work_vnodes--;    \
365 	        if (!(vp->v_listflag & VLIST_NO_REUSE)) {        \
366 	                reusablevnodes--;    \
367 	        }        \
368 	} while(0)
369 
370 
371 /* remove a vnode from rage vnode list */
372 #define VREMRAGE(fun, vp)       \
373 	do {    \
374 	        if ( !(vp->v_listflag & VLIST_RAGE))                    \
375 	                panic("VREMRAGE: vp not on rage list");         \
376 	        VLISTCHECK((fun), (vp), "rage");                        \
377 	        TAILQ_REMOVE(&vnode_rage_list, (vp), v_freelist);       \
378 	        VLISTNONE((vp));                \
379 	        vp->v_listflag &= ~VLIST_RAGE;  \
380 	        ragevnodes--;                   \
381 	        reusablevnodes--;    \
382 	} while(0)
383 
384 static void async_work_continue(void);
385 static void vn_laundry_continue(void);
386 static void wakeup_laundry_thread(void);
387 
388 /*
389  * Initialize the vnode management data structures.
390  */
391 __private_extern__ void
vntblinit(void)392 vntblinit(void)
393 {
394 	thread_t        thread = THREAD_NULL;
395 	int desiredvnodes_one_percent = desiredvnodes / 100;
396 
397 	TAILQ_INIT(&vnode_free_list);
398 	TAILQ_INIT(&vnode_rage_list);
399 	TAILQ_INIT(&vnode_dead_list);
400 	TAILQ_INIT(&vnode_async_work_list);
401 	TAILQ_INIT(&mountlist);
402 
403 	microuptime(&rage_tv);
404 	rage_limit = desiredvnodes_one_percent;
405 	if (rage_limit < RAGE_LIMIT_MIN) {
406 		rage_limit = RAGE_LIMIT_MIN;
407 	}
408 
409 	deadvnodes_low = desiredvnodes_one_percent;
410 	if (deadvnodes_low > 300) {
411 		deadvnodes_low = 300;
412 	}
413 	deadvnodes_high = deadvnodes_low * 2;
414 
415 	numvnodes_min = numvnodes_max = desiredvnodes;
416 	if (bootarg_vn_dealloc_level == DEALLOC_VNODE_ONLY_OVERFLOW) {
417 		numvnodes_max = desiredvnodes * 2;
418 		vn_dealloc_level = bootarg_vn_dealloc_level;
419 	} else if (bootarg_vn_dealloc_level == DEALLOC_VNODE_ALL) {
420 		numvnodes_min = desiredvnodes_one_percent * 40;
421 		numvnodes_max = desiredvnodes * 2;
422 		reusablevnodes_max = (desiredvnodes_one_percent * 20) - deadvnodes_low;
423 		vn_dealloc_level = bootarg_vn_dealloc_level;
424 	}
425 
426 	/*
427 	 * create worker threads
428 	 */
429 	kernel_thread_start((thread_continue_t)async_work_continue, NULL, &thread);
430 	thread_deallocate(thread);
431 	kernel_thread_start((thread_continue_t)vn_laundry_continue, NULL, &thread);
432 	thread_deallocate(thread);
433 }
434 
435 /* the timeout is in 10 msecs */
436 int
vnode_waitforwrites(vnode_t vp,int output_target,int slpflag,int slptimeout,const char * msg)437 vnode_waitforwrites(vnode_t vp, int output_target, int slpflag, int slptimeout, const char *msg)
438 {
439 	int error = 0;
440 	struct timespec ts;
441 
442 	if (output_target < 0) {
443 		return EINVAL;
444 	}
445 
446 	KERNEL_DEBUG(0x3010280 | DBG_FUNC_START, (int)vp, output_target, vp->v_numoutput, 0, 0);
447 
448 	if (vp->v_numoutput > output_target) {
449 		slpflag |= PDROP;
450 
451 		vnode_lock_spin(vp);
452 
453 		while ((vp->v_numoutput > output_target) && error == 0) {
454 			if (output_target) {
455 				vp->v_flag |= VTHROTTLED;
456 			} else {
457 				vp->v_flag |= VBWAIT;
458 			}
459 
460 			ts.tv_sec = (slptimeout / 100);
461 			ts.tv_nsec = (slptimeout % 1000)  * 10 * NSEC_PER_USEC * 1000;
462 			error = msleep((caddr_t)&vp->v_numoutput, &vp->v_lock, (slpflag | (PRIBIO + 1)), msg, &ts);
463 
464 			vnode_lock_spin(vp);
465 		}
466 		vnode_unlock(vp);
467 	}
468 	KERNEL_DEBUG(0x3010280 | DBG_FUNC_END, (int)vp, output_target, vp->v_numoutput, error, 0);
469 
470 	return error;
471 }
472 
473 
474 void
vnode_startwrite(vnode_t vp)475 vnode_startwrite(vnode_t vp)
476 {
477 	OSAddAtomic(1, &vp->v_numoutput);
478 }
479 
480 
481 void
vnode_writedone(vnode_t vp)482 vnode_writedone(vnode_t vp)
483 {
484 	if (vp) {
485 		int need_wakeup = 0;
486 
487 		OSAddAtomic(-1, &vp->v_numoutput);
488 
489 		vnode_lock_spin(vp);
490 
491 		if (vp->v_numoutput < 0) {
492 			panic("vnode_writedone: numoutput < 0");
493 		}
494 
495 		if ((vp->v_flag & VTHROTTLED)) {
496 			vp->v_flag &= ~VTHROTTLED;
497 			need_wakeup = 1;
498 		}
499 		if ((vp->v_flag & VBWAIT) && (vp->v_numoutput == 0)) {
500 			vp->v_flag &= ~VBWAIT;
501 			need_wakeup = 1;
502 		}
503 		vnode_unlock(vp);
504 
505 		if (need_wakeup) {
506 			wakeup((caddr_t)&vp->v_numoutput);
507 		}
508 	}
509 }
510 
511 
512 
513 int
vnode_hasdirtyblks(vnode_t vp)514 vnode_hasdirtyblks(vnode_t vp)
515 {
516 	struct cl_writebehind *wbp;
517 
518 	/*
519 	 * Not taking the buf_mtx as there is little
520 	 * point doing it. Even if the lock is taken the
521 	 * state can change right after that. If their
522 	 * needs to be a synchronization, it must be driven
523 	 * by the caller
524 	 */
525 	if (vp->v_dirtyblkhd.lh_first) {
526 		return 1;
527 	}
528 
529 	if (!UBCINFOEXISTS(vp)) {
530 		return 0;
531 	}
532 
533 	wbp = vp->v_ubcinfo->cl_wbehind;
534 
535 	if (wbp && (wbp->cl_number || wbp->cl_scmap)) {
536 		return 1;
537 	}
538 
539 	return 0;
540 }
541 
542 int
vnode_hascleanblks(vnode_t vp)543 vnode_hascleanblks(vnode_t vp)
544 {
545 	/*
546 	 * Not taking the buf_mtx as there is little
547 	 * point doing it. Even if the lock is taken the
548 	 * state can change right after that. If their
549 	 * needs to be a synchronization, it must be driven
550 	 * by the caller
551 	 */
552 	if (vp->v_cleanblkhd.lh_first) {
553 		return 1;
554 	}
555 	return 0;
556 }
557 
558 void
vnode_iterate_setup(mount_t mp)559 vnode_iterate_setup(mount_t mp)
560 {
561 	mp->mnt_lflag |= MNT_LITER;
562 }
563 
564 int
vnode_umount_preflight(mount_t mp,vnode_t skipvp,int flags)565 vnode_umount_preflight(mount_t mp, vnode_t skipvp, int flags)
566 {
567 	vnode_t vp;
568 	int ret = 0;
569 
570 	TAILQ_FOREACH(vp, &mp->mnt_vnodelist, v_mntvnodes) {
571 		if (vp->v_type == VDIR) {
572 			continue;
573 		}
574 		if (vp == skipvp) {
575 			continue;
576 		}
577 		if ((flags & SKIPSYSTEM) && ((vp->v_flag & VSYSTEM) || (vp->v_flag & VNOFLUSH))) {
578 			continue;
579 		}
580 		if ((flags & SKIPSWAP) && (vp->v_flag & VSWAP)) {
581 			continue;
582 		}
583 		if ((flags & WRITECLOSE) && (vp->v_writecount == 0 || vp->v_type != VREG)) {
584 			continue;
585 		}
586 
587 		/* Look for busy vnode */
588 		if ((vp->v_usecount != 0) && ((vp->v_usecount - vp->v_kusecount) != 0)) {
589 			ret = 1;
590 			if (print_busy_vnodes && ((flags & FORCECLOSE) == 0)) {
591 				vprint("vnode_umount_preflight - busy vnode", vp);
592 			} else {
593 				return ret;
594 			}
595 		} else if (vp->v_iocount > 0) {
596 			/* Busy if iocount is > 0 for more than 3 seconds */
597 			tsleep(&vp->v_iocount, PVFS, "vnode_drain_network", 3 * hz);
598 			if (vp->v_iocount > 0) {
599 				ret = 1;
600 				if (print_busy_vnodes && ((flags & FORCECLOSE) == 0)) {
601 					vprint("vnode_umount_preflight - busy vnode", vp);
602 				} else {
603 					return ret;
604 				}
605 			}
606 			continue;
607 		}
608 	}
609 
610 	return ret;
611 }
612 
613 /*
614  * This routine prepares iteration by moving all the vnodes to worker queue
615  * called with mount lock held
616  */
617 int
vnode_iterate_prepare(mount_t mp)618 vnode_iterate_prepare(mount_t mp)
619 {
620 	vnode_t vp;
621 
622 	if (TAILQ_EMPTY(&mp->mnt_vnodelist)) {
623 		/* nothing to do */
624 		return 0;
625 	}
626 
627 	vp = TAILQ_FIRST(&mp->mnt_vnodelist);
628 	vp->v_mntvnodes.tqe_prev = &(mp->mnt_workerqueue.tqh_first);
629 	mp->mnt_workerqueue.tqh_first = mp->mnt_vnodelist.tqh_first;
630 	mp->mnt_workerqueue.tqh_last = mp->mnt_vnodelist.tqh_last;
631 
632 	TAILQ_INIT(&mp->mnt_vnodelist);
633 	if (mp->mnt_newvnodes.tqh_first != NULL) {
634 		panic("vnode_iterate_prepare: newvnode when entering vnode");
635 	}
636 	TAILQ_INIT(&mp->mnt_newvnodes);
637 
638 	return 1;
639 }
640 
641 
642 /* called with mount lock held */
643 int
vnode_iterate_reloadq(mount_t mp)644 vnode_iterate_reloadq(mount_t mp)
645 {
646 	int moved = 0;
647 
648 	/* add the remaining entries in workerq to the end of mount vnode list */
649 	if (!TAILQ_EMPTY(&mp->mnt_workerqueue)) {
650 		struct vnode * mvp;
651 		mvp = TAILQ_LAST(&mp->mnt_vnodelist, vnodelst);
652 
653 		/* Joining the workerque entities to mount vnode list */
654 		if (mvp) {
655 			mvp->v_mntvnodes.tqe_next = mp->mnt_workerqueue.tqh_first;
656 		} else {
657 			mp->mnt_vnodelist.tqh_first = mp->mnt_workerqueue.tqh_first;
658 		}
659 		mp->mnt_workerqueue.tqh_first->v_mntvnodes.tqe_prev = mp->mnt_vnodelist.tqh_last;
660 		mp->mnt_vnodelist.tqh_last = mp->mnt_workerqueue.tqh_last;
661 		TAILQ_INIT(&mp->mnt_workerqueue);
662 	}
663 
664 	/* add the newvnodes to the head of mount vnode list */
665 	if (!TAILQ_EMPTY(&mp->mnt_newvnodes)) {
666 		struct vnode * nlvp;
667 		nlvp = TAILQ_LAST(&mp->mnt_newvnodes, vnodelst);
668 
669 		mp->mnt_newvnodes.tqh_first->v_mntvnodes.tqe_prev = &mp->mnt_vnodelist.tqh_first;
670 		nlvp->v_mntvnodes.tqe_next = mp->mnt_vnodelist.tqh_first;
671 		if (mp->mnt_vnodelist.tqh_first) {
672 			mp->mnt_vnodelist.tqh_first->v_mntvnodes.tqe_prev = &nlvp->v_mntvnodes.tqe_next;
673 		} else {
674 			mp->mnt_vnodelist.tqh_last = mp->mnt_newvnodes.tqh_last;
675 		}
676 		mp->mnt_vnodelist.tqh_first = mp->mnt_newvnodes.tqh_first;
677 		TAILQ_INIT(&mp->mnt_newvnodes);
678 		moved = 1;
679 	}
680 
681 	return moved;
682 }
683 
684 
685 void
vnode_iterate_clear(mount_t mp)686 vnode_iterate_clear(mount_t mp)
687 {
688 	mp->mnt_lflag &= ~MNT_LITER;
689 }
690 
691 #if defined(__x86_64__)
692 
693 #include <i386/panic_hooks.h>
694 
695 struct vnode_iterate_panic_hook {
696 	panic_hook_t hook;
697 	mount_t mp;
698 	struct vnode *vp;
699 };
700 
701 static void
vnode_iterate_panic_hook(panic_hook_t * hook_)702 vnode_iterate_panic_hook(panic_hook_t *hook_)
703 {
704 	struct vnode_iterate_panic_hook *hook = (struct vnode_iterate_panic_hook *)hook_;
705 	panic_phys_range_t range;
706 	uint64_t phys;
707 
708 	if (panic_phys_range_before(hook->mp, &phys, &range)) {
709 		paniclog_append_noflush("mp = %p, phys = %p, prev (%p: %p-%p)\n",
710 		    hook->mp, phys, range.type, range.phys_start,
711 		    range.phys_start + range.len);
712 	} else {
713 		paniclog_append_noflush("mp = %p, phys = %p, prev (!)\n", hook->mp, phys);
714 	}
715 
716 	if (panic_phys_range_before(hook->vp, &phys, &range)) {
717 		paniclog_append_noflush("vp = %p, phys = %p, prev (%p: %p-%p)\n",
718 		    hook->vp, phys, range.type, range.phys_start,
719 		    range.phys_start + range.len);
720 	} else {
721 		paniclog_append_noflush("vp = %p, phys = %p, prev (!)\n", hook->vp, phys);
722 	}
723 	panic_dump_mem((void *)(((vm_offset_t)hook->mp - 4096) & ~4095), 12288);
724 }
725 #endif /* defined(__x86_64__) */
726 
727 int
vnode_iterate(mount_t mp,int flags,int (* callout)(struct vnode *,void *),void * arg)728 vnode_iterate(mount_t mp, int flags, int (*callout)(struct vnode *, void *),
729     void *arg)
730 {
731 	struct vnode *vp;
732 	int vid, retval;
733 	int ret = 0;
734 
735 	/*
736 	 * The mount iterate mutex is held for the duration of the iteration.
737 	 * This can be done by a state flag on the mount structure but we can
738 	 * run into priority inversion issues sometimes.
739 	 * Using a mutex allows us to benefit from the priority donation
740 	 * mechanisms in the kernel for locks. This mutex should never be
741 	 * acquired in spin mode and it should be acquired before attempting to
742 	 * acquire the mount lock.
743 	 */
744 	mount_iterate_lock(mp);
745 
746 	mount_lock(mp);
747 
748 	vnode_iterate_setup(mp);
749 
750 	/* If it returns 0 then there is nothing to do */
751 	retval = vnode_iterate_prepare(mp);
752 
753 	if (retval == 0) {
754 		vnode_iterate_clear(mp);
755 		mount_unlock(mp);
756 		mount_iterate_unlock(mp);
757 		return ret;
758 	}
759 
760 #if defined(__x86_64__)
761 	struct vnode_iterate_panic_hook hook;
762 	hook.mp = mp;
763 	hook.vp = NULL;
764 	panic_hook(&hook.hook, vnode_iterate_panic_hook);
765 #endif
766 	/* iterate over all the vnodes */
767 	while (!TAILQ_EMPTY(&mp->mnt_workerqueue)) {
768 		vp = TAILQ_FIRST(&mp->mnt_workerqueue);
769 #if defined(__x86_64__)
770 		hook.vp = vp;
771 #endif
772 		TAILQ_REMOVE(&mp->mnt_workerqueue, vp, v_mntvnodes);
773 		TAILQ_INSERT_TAIL(&mp->mnt_vnodelist, vp, v_mntvnodes);
774 		vid = vp->v_id;
775 		if ((vp->v_data == NULL) || (vp->v_type == VNON) || (vp->v_mount != mp)) {
776 			continue;
777 		}
778 		vnode_hold(vp);
779 		mount_unlock(mp);
780 
781 		if (vget_internal(vp, vid, (flags | VNODE_NODEAD | VNODE_WITHID | VNODE_NOSUSPEND))) {
782 			mount_lock(mp);
783 			vnode_drop(vp);
784 			continue;
785 		}
786 		vnode_drop(vp);
787 		if (flags & VNODE_RELOAD) {
788 			/*
789 			 * we're reloading the filesystem
790 			 * cast out any inactive vnodes...
791 			 */
792 			if (vnode_reload(vp)) {
793 				/* vnode will be recycled on the refcount drop */
794 				vnode_put(vp);
795 				mount_lock(mp);
796 				continue;
797 			}
798 		}
799 
800 		retval = callout(vp, arg);
801 
802 		switch (retval) {
803 		case VNODE_RETURNED:
804 		case VNODE_RETURNED_DONE:
805 			vnode_put(vp);
806 			if (retval == VNODE_RETURNED_DONE) {
807 				mount_lock(mp);
808 				ret = 0;
809 				goto out;
810 			}
811 			break;
812 
813 		case VNODE_CLAIMED_DONE:
814 			mount_lock(mp);
815 			ret = 0;
816 			goto out;
817 		case VNODE_CLAIMED:
818 		default:
819 			break;
820 		}
821 		mount_lock(mp);
822 	}
823 
824 out:
825 #if defined(__x86_64__)
826 	panic_unhook(&hook.hook);
827 #endif
828 	(void)vnode_iterate_reloadq(mp);
829 	vnode_iterate_clear(mp);
830 	mount_unlock(mp);
831 	mount_iterate_unlock(mp);
832 	return ret;
833 }
834 
835 void
mount_lock_renames(mount_t mp)836 mount_lock_renames(mount_t mp)
837 {
838 	lck_mtx_lock(&mp->mnt_renamelock);
839 }
840 
841 void
mount_unlock_renames(mount_t mp)842 mount_unlock_renames(mount_t mp)
843 {
844 	lck_mtx_unlock(&mp->mnt_renamelock);
845 }
846 
847 void
mount_iterate_lock(mount_t mp)848 mount_iterate_lock(mount_t mp)
849 {
850 	lck_mtx_lock(&mp->mnt_iter_lock);
851 }
852 
853 void
mount_iterate_unlock(mount_t mp)854 mount_iterate_unlock(mount_t mp)
855 {
856 	lck_mtx_unlock(&mp->mnt_iter_lock);
857 }
858 
859 void
mount_lock(mount_t mp)860 mount_lock(mount_t mp)
861 {
862 	lck_mtx_lock(&mp->mnt_mlock);
863 }
864 
865 void
mount_lock_spin(mount_t mp)866 mount_lock_spin(mount_t mp)
867 {
868 	lck_mtx_lock_spin(&mp->mnt_mlock);
869 }
870 
871 void
mount_unlock(mount_t mp)872 mount_unlock(mount_t mp)
873 {
874 	lck_mtx_unlock(&mp->mnt_mlock);
875 }
876 
877 
878 void
mount_ref(mount_t mp,int locked)879 mount_ref(mount_t mp, int locked)
880 {
881 	if (!locked) {
882 		mount_lock_spin(mp);
883 	}
884 
885 	mp->mnt_count++;
886 
887 	if (!locked) {
888 		mount_unlock(mp);
889 	}
890 }
891 
892 
893 void
mount_drop(mount_t mp,int locked)894 mount_drop(mount_t mp, int locked)
895 {
896 	if (!locked) {
897 		mount_lock_spin(mp);
898 	}
899 
900 	mp->mnt_count--;
901 
902 	if (mp->mnt_count == 0 && (mp->mnt_lflag & MNT_LDRAIN)) {
903 		wakeup(&mp->mnt_lflag);
904 	}
905 
906 	if (!locked) {
907 		mount_unlock(mp);
908 	}
909 }
910 
911 
912 int
mount_iterref(mount_t mp,int locked)913 mount_iterref(mount_t mp, int locked)
914 {
915 	int retval = 0;
916 
917 	if (!locked) {
918 		mount_list_lock();
919 	}
920 	if (mp->mnt_iterref < 0) {
921 		retval = 1;
922 	} else {
923 		mp->mnt_iterref++;
924 	}
925 	if (!locked) {
926 		mount_list_unlock();
927 	}
928 	return retval;
929 }
930 
931 int
mount_isdrained(mount_t mp,int locked)932 mount_isdrained(mount_t mp, int locked)
933 {
934 	int retval;
935 
936 	if (!locked) {
937 		mount_list_lock();
938 	}
939 	if (mp->mnt_iterref < 0) {
940 		retval = 1;
941 	} else {
942 		retval = 0;
943 	}
944 	if (!locked) {
945 		mount_list_unlock();
946 	}
947 	return retval;
948 }
949 
950 void
mount_iterdrop(mount_t mp)951 mount_iterdrop(mount_t mp)
952 {
953 	mount_list_lock();
954 	mp->mnt_iterref--;
955 	wakeup(&mp->mnt_iterref);
956 	mount_list_unlock();
957 }
958 
959 void
mount_iterdrain(mount_t mp)960 mount_iterdrain(mount_t mp)
961 {
962 	mount_list_lock();
963 	while (mp->mnt_iterref) {
964 		msleep((caddr_t)&mp->mnt_iterref, &mnt_list_mtx_lock, PVFS, "mount_iterdrain", NULL);
965 	}
966 	/* mount iterations drained */
967 	mp->mnt_iterref = -1;
968 	mount_list_unlock();
969 }
970 void
mount_iterreset(mount_t mp)971 mount_iterreset(mount_t mp)
972 {
973 	mount_list_lock();
974 	if (mp->mnt_iterref == -1) {
975 		mp->mnt_iterref = 0;
976 	}
977 	mount_list_unlock();
978 }
979 
980 /* always called with  mount lock held */
981 int
mount_refdrain(mount_t mp)982 mount_refdrain(mount_t mp)
983 {
984 	if (mp->mnt_lflag & MNT_LDRAIN) {
985 		panic("already in drain");
986 	}
987 	mp->mnt_lflag |= MNT_LDRAIN;
988 
989 	while (mp->mnt_count) {
990 		msleep((caddr_t)&mp->mnt_lflag, &mp->mnt_mlock, PVFS, "mount_drain", NULL);
991 	}
992 
993 	if (mp->mnt_vnodelist.tqh_first != NULL) {
994 		panic("mount_refdrain: dangling vnode");
995 	}
996 
997 	mp->mnt_lflag &= ~MNT_LDRAIN;
998 
999 	return 0;
1000 }
1001 
1002 /* Tags the mount point as not supportine extended readdir for NFS exports */
1003 void
mount_set_noreaddirext(mount_t mp)1004 mount_set_noreaddirext(mount_t mp)
1005 {
1006 	mount_lock(mp);
1007 	mp->mnt_kern_flag |= MNTK_DENY_READDIREXT;
1008 	mount_unlock(mp);
1009 }
1010 
1011 /*
1012  * Mark a mount point as busy. Used to synchronize access and to delay
1013  * unmounting.
1014  */
1015 int
vfs_busy(mount_t mp,int flags)1016 vfs_busy(mount_t mp, int flags)
1017 {
1018 restart:
1019 	if (mp->mnt_lflag & MNT_LDEAD) {
1020 		return ENOENT;
1021 	}
1022 
1023 	mount_lock(mp);
1024 
1025 	if (mp->mnt_lflag & MNT_LUNMOUNT) {
1026 		if (flags & LK_NOWAIT || mp->mnt_lflag & MNT_LDEAD) {
1027 			mount_unlock(mp);
1028 			return ENOENT;
1029 		}
1030 
1031 		/*
1032 		 * Since all busy locks are shared except the exclusive
1033 		 * lock granted when unmounting, the only place that a
1034 		 * wakeup needs to be done is at the release of the
1035 		 * exclusive lock at the end of dounmount.
1036 		 */
1037 		mp->mnt_lflag |= MNT_LWAIT;
1038 		msleep((caddr_t)mp, &mp->mnt_mlock, (PVFS | PDROP), "vfsbusy", NULL);
1039 		return ENOENT;
1040 	}
1041 
1042 	mount_unlock(mp);
1043 
1044 	lck_rw_lock_shared(&mp->mnt_rwlock);
1045 
1046 	/*
1047 	 * Until we are granted the rwlock, it's possible for the mount point to
1048 	 * change state, so re-evaluate before granting the vfs_busy.
1049 	 */
1050 	if (mp->mnt_lflag & (MNT_LDEAD | MNT_LUNMOUNT)) {
1051 		lck_rw_done(&mp->mnt_rwlock);
1052 		goto restart;
1053 	}
1054 	return 0;
1055 }
1056 
1057 /*
1058  * Free a busy filesystem.
1059  */
1060 void
vfs_unbusy(mount_t mp)1061 vfs_unbusy(mount_t mp)
1062 {
1063 	lck_rw_done(&mp->mnt_rwlock);
1064 }
1065 
1066 
1067 
1068 static void
vfs_rootmountfailed(mount_t mp)1069 vfs_rootmountfailed(mount_t mp)
1070 {
1071 	mount_list_lock();
1072 	mp->mnt_vtable->vfc_refcount--;
1073 	mount_list_unlock();
1074 
1075 	vfs_unbusy(mp);
1076 
1077 	mount_lock_destroy(mp);
1078 
1079 #if CONFIG_MACF
1080 	mac_mount_label_destroy(mp);
1081 #endif
1082 
1083 	zfree(mount_zone, mp);
1084 }
1085 
1086 /*
1087  * Lookup a filesystem type, and if found allocate and initialize
1088  * a mount structure for it.
1089  *
1090  * Devname is usually updated by mount(8) after booting.
1091  */
1092 static mount_t
vfs_rootmountalloc_internal(struct vfstable * vfsp,const char * devname)1093 vfs_rootmountalloc_internal(struct vfstable *vfsp, const char *devname)
1094 {
1095 	mount_t mp;
1096 
1097 	mp = zalloc_flags(mount_zone, Z_WAITOK | Z_ZERO);
1098 	/* Initialize the default IO constraints */
1099 	mp->mnt_maxreadcnt = mp->mnt_maxwritecnt = MAXPHYS;
1100 	mp->mnt_segreadcnt = mp->mnt_segwritecnt = 32;
1101 	mp->mnt_maxsegreadsize = mp->mnt_maxreadcnt;
1102 	mp->mnt_maxsegwritesize = mp->mnt_maxwritecnt;
1103 	mp->mnt_devblocksize = DEV_BSIZE;
1104 	mp->mnt_alignmentmask = PAGE_MASK;
1105 	mp->mnt_ioqueue_depth = MNT_DEFAULT_IOQUEUE_DEPTH;
1106 	mp->mnt_ioscale = 1;
1107 	mp->mnt_ioflags = 0;
1108 	mp->mnt_realrootvp = NULLVP;
1109 	mp->mnt_authcache_ttl = CACHED_LOOKUP_RIGHT_TTL;
1110 	mp->mnt_throttle_mask = LOWPRI_MAX_NUM_DEV - 1;
1111 	mp->mnt_devbsdunit = 0;
1112 
1113 	mount_lock_init(mp);
1114 	(void)vfs_busy(mp, LK_NOWAIT);
1115 
1116 	TAILQ_INIT(&mp->mnt_vnodelist);
1117 	TAILQ_INIT(&mp->mnt_workerqueue);
1118 	TAILQ_INIT(&mp->mnt_newvnodes);
1119 
1120 	mp->mnt_vtable = vfsp;
1121 	mp->mnt_op = vfsp->vfc_vfsops;
1122 	mp->mnt_flag = MNT_RDONLY | MNT_ROOTFS;
1123 	mp->mnt_vnodecovered = NULLVP;
1124 	//mp->mnt_stat.f_type = vfsp->vfc_typenum;
1125 	mp->mnt_flag |= vfsp->vfc_flags & MNT_VISFLAGMASK;
1126 
1127 	mount_list_lock();
1128 	vfsp->vfc_refcount++;
1129 	mount_list_unlock();
1130 
1131 	strlcpy(mp->mnt_vfsstat.f_fstypename, vfsp->vfc_name, MFSTYPENAMELEN);
1132 	mp->mnt_vfsstat.f_mntonname[0] = '/';
1133 	/* XXX const poisoning layering violation */
1134 	(void) copystr((const void *)devname, mp->mnt_vfsstat.f_mntfromname, MAXPATHLEN - 1, NULL);
1135 
1136 #if CONFIG_MACF
1137 	mac_mount_label_init(mp);
1138 	mac_mount_label_associate(vfs_context_kernel(), mp);
1139 #endif
1140 	return mp;
1141 }
1142 
1143 errno_t
vfs_rootmountalloc(const char * fstypename,const char * devname,mount_t * mpp)1144 vfs_rootmountalloc(const char *fstypename, const char *devname, mount_t *mpp)
1145 {
1146 	struct vfstable *vfsp;
1147 
1148 	for (vfsp = vfsconf; vfsp; vfsp = vfsp->vfc_next) {
1149 		if (!strncmp(vfsp->vfc_name, fstypename,
1150 		    sizeof(vfsp->vfc_name))) {
1151 			break;
1152 		}
1153 	}
1154 	if (vfsp == NULL) {
1155 		return ENODEV;
1156 	}
1157 
1158 	*mpp = vfs_rootmountalloc_internal(vfsp, devname);
1159 
1160 	if (*mpp) {
1161 		return 0;
1162 	}
1163 
1164 	return ENOMEM;
1165 }
1166 
1167 #define DBG_MOUNTROOT (FSDBG_CODE(DBG_MOUNT, 0))
1168 
1169 /*
1170  * Find an appropriate filesystem to use for the root. If a filesystem
1171  * has not been preselected, walk through the list of known filesystems
1172  * trying those that have mountroot routines, and try them until one
1173  * works or we have tried them all.
1174  */
1175 extern int (*mountroot)(void);
1176 
1177 int
vfs_mountroot(void)1178 vfs_mountroot(void)
1179 {
1180 #if CONFIG_MACF
1181 	struct vnode *vp;
1182 #endif
1183 	struct vfstable *vfsp;
1184 	vfs_context_t ctx = vfs_context_kernel();
1185 	struct vfs_attr vfsattr;
1186 	int     error;
1187 	mount_t mp;
1188 	vnode_t bdevvp_rootvp;
1189 
1190 	/*
1191 	 * Reset any prior "unmounting everything" state.  This handles the
1192 	 * situation where mount root and then unmountall and re-mountroot
1193 	 * a new image (see bsd/kern/imageboot.c).
1194 	 */
1195 	vfs_unmountall_started = vfs_unmountall_finished = 0;
1196 	OSMemoryBarrier();
1197 
1198 	KDBG_RELEASE(DBG_MOUNTROOT | DBG_FUNC_START);
1199 	if (mountroot != NULL) {
1200 		/*
1201 		 * used for netboot which follows a different set of rules
1202 		 */
1203 		error = (*mountroot)();
1204 
1205 		KDBG_RELEASE(DBG_MOUNTROOT | DBG_FUNC_END, error, 0);
1206 		return error;
1207 	}
1208 	if ((error = bdevvp(rootdev, &rootvp))) {
1209 		printf("vfs_mountroot: can't setup bdevvp\n");
1210 
1211 		KDBG_RELEASE(DBG_MOUNTROOT | DBG_FUNC_END, error, 1);
1212 		return error;
1213 	}
1214 	/*
1215 	 * 4951998 - code we call in vfc_mountroot may replace rootvp
1216 	 * so keep a local copy for some house keeping.
1217 	 */
1218 	bdevvp_rootvp = rootvp;
1219 
1220 	for (vfsp = vfsconf; vfsp; vfsp = vfsp->vfc_next) {
1221 		if (vfsp->vfc_mountroot == NULL
1222 		    && !ISSET(vfsp->vfc_vfsflags, VFC_VFSCANMOUNTROOT)) {
1223 			continue;
1224 		}
1225 
1226 		mp = vfs_rootmountalloc_internal(vfsp, "root_device");
1227 		mp->mnt_devvp = rootvp;
1228 
1229 		if (vfsp->vfc_mountroot) {
1230 			error = (*vfsp->vfc_mountroot)(mp, rootvp, ctx);
1231 		} else {
1232 			error = VFS_MOUNT(mp, rootvp, 0, ctx);
1233 		}
1234 
1235 		if (!error) {
1236 			if (bdevvp_rootvp != rootvp) {
1237 				/*
1238 				 * rootvp changed...
1239 				 *   bump the iocount and fix up mnt_devvp for the
1240 				 *   new rootvp (it will already have a usecount taken)...
1241 				 *   drop the iocount and the usecount on the orignal
1242 				 *   since we are no longer going to use it...
1243 				 */
1244 				vnode_getwithref(rootvp);
1245 				mp->mnt_devvp = rootvp;
1246 
1247 				vnode_rele(bdevvp_rootvp);
1248 				vnode_put(bdevvp_rootvp);
1249 			}
1250 			mp->mnt_devvp->v_specflags |= SI_MOUNTEDON;
1251 
1252 			vfs_unbusy(mp);
1253 
1254 			mount_list_add(mp);
1255 
1256 			/*
1257 			 *   cache the IO attributes for the underlying physical media...
1258 			 *   an error return indicates the underlying driver doesn't
1259 			 *   support all the queries necessary... however, reasonable
1260 			 *   defaults will have been set, so no reason to bail or care
1261 			 */
1262 			vfs_init_io_attributes(rootvp, mp);
1263 
1264 			if (mp->mnt_ioflags & MNT_IOFLAGS_FUSION_DRIVE) {
1265 				root_is_CF_drive = TRUE;
1266 			}
1267 
1268 			/*
1269 			 * Shadow the VFC_VFSNATIVEXATTR flag to MNTK_EXTENDED_ATTRS.
1270 			 */
1271 			if (mp->mnt_vtable->vfc_vfsflags & VFC_VFSNATIVEXATTR) {
1272 				mp->mnt_kern_flag |= MNTK_EXTENDED_ATTRS;
1273 			}
1274 			if (mp->mnt_vtable->vfc_vfsflags & VFC_VFSPREFLIGHT) {
1275 				mp->mnt_kern_flag |= MNTK_UNMOUNT_PREFLIGHT;
1276 			}
1277 
1278 #if defined(XNU_TARGET_OS_OSX)
1279 			uint32_t speed;
1280 
1281 			if (MNTK_VIRTUALDEV & mp->mnt_kern_flag) {
1282 				speed = 128;
1283 			} else if (disk_conditioner_mount_is_ssd(mp)) {
1284 				speed = 7 * 256;
1285 			} else {
1286 				speed = 256;
1287 			}
1288 			vc_progress_setdiskspeed(speed);
1289 #endif /* XNU_TARGET_OS_OSX */
1290 			/*
1291 			 * Probe root file system for additional features.
1292 			 */
1293 			(void)VFS_START(mp, 0, ctx);
1294 
1295 			VFSATTR_INIT(&vfsattr);
1296 			VFSATTR_WANTED(&vfsattr, f_capabilities);
1297 			if (vfs_getattr(mp, &vfsattr, ctx) == 0 &&
1298 			    VFSATTR_IS_SUPPORTED(&vfsattr, f_capabilities)) {
1299 				if ((vfsattr.f_capabilities.capabilities[VOL_CAPABILITIES_INTERFACES] & VOL_CAP_INT_EXTENDED_ATTR) &&
1300 				    (vfsattr.f_capabilities.valid[VOL_CAPABILITIES_INTERFACES] & VOL_CAP_INT_EXTENDED_ATTR)) {
1301 					mp->mnt_kern_flag |= MNTK_EXTENDED_ATTRS;
1302 				}
1303 #if NAMEDSTREAMS
1304 				if ((vfsattr.f_capabilities.capabilities[VOL_CAPABILITIES_INTERFACES] & VOL_CAP_INT_NAMEDSTREAMS) &&
1305 				    (vfsattr.f_capabilities.valid[VOL_CAPABILITIES_INTERFACES] & VOL_CAP_INT_NAMEDSTREAMS)) {
1306 					mp->mnt_kern_flag |= MNTK_NAMED_STREAMS;
1307 				}
1308 #endif
1309 				if ((vfsattr.f_capabilities.capabilities[VOL_CAPABILITIES_FORMAT] & VOL_CAP_FMT_PATH_FROM_ID) &&
1310 				    (vfsattr.f_capabilities.valid[VOL_CAPABILITIES_FORMAT] & VOL_CAP_FMT_PATH_FROM_ID)) {
1311 					mp->mnt_kern_flag |= MNTK_PATH_FROM_ID;
1312 				}
1313 
1314 				if ((vfsattr.f_capabilities.capabilities[VOL_CAPABILITIES_FORMAT] & VOL_CAP_FMT_DIR_HARDLINKS) &&
1315 				    (vfsattr.f_capabilities.valid[VOL_CAPABILITIES_FORMAT] & VOL_CAP_FMT_DIR_HARDLINKS)) {
1316 					mp->mnt_kern_flag |= MNTK_DIR_HARDLINKS;
1317 				}
1318 			}
1319 
1320 			/*
1321 			 * get rid of iocount reference returned
1322 			 * by bdevvp (or picked up by us on the substitued
1323 			 * rootvp)... it (or we) will have also taken
1324 			 * a usecount reference which we want to keep
1325 			 */
1326 			vnode_put(rootvp);
1327 
1328 #if CONFIG_MACF
1329 			if ((vfs_flags(mp) & MNT_MULTILABEL) == 0) {
1330 				KDBG_RELEASE(DBG_MOUNTROOT | DBG_FUNC_END, 0, 2);
1331 				return 0;
1332 			}
1333 
1334 			error = VFS_ROOT(mp, &vp, ctx);
1335 			if (error) {
1336 				printf("%s() VFS_ROOT() returned %d\n",
1337 				    __func__, error);
1338 				dounmount(mp, MNT_FORCE, 0, ctx);
1339 				goto fail;
1340 			}
1341 			error = vnode_label(mp, NULL, vp, NULL, 0, ctx);
1342 			/*
1343 			 * get rid of reference provided by VFS_ROOT
1344 			 */
1345 			vnode_put(vp);
1346 
1347 			if (error) {
1348 				printf("%s() vnode_label() returned %d\n",
1349 				    __func__, error);
1350 				dounmount(mp, MNT_FORCE, 0, ctx);
1351 				goto fail;
1352 			}
1353 #endif
1354 			KDBG_RELEASE(DBG_MOUNTROOT | DBG_FUNC_END, 0, 3);
1355 			return 0;
1356 		}
1357 		vfs_rootmountfailed(mp);
1358 #if CONFIG_MACF
1359 fail:
1360 #endif
1361 		if (error != EINVAL) {
1362 			printf("%s_mountroot failed: %d\n", vfsp->vfc_name, error);
1363 		}
1364 	}
1365 	KDBG_RELEASE(DBG_MOUNTROOT | DBG_FUNC_END, error ? error : ENODEV, 4);
1366 	return ENODEV;
1367 }
1368 
1369 static int
cache_purge_callback(mount_t mp,__unused void * arg)1370 cache_purge_callback(mount_t mp, __unused void * arg)
1371 {
1372 	cache_purgevfs(mp);
1373 	return VFS_RETURNED;
1374 }
1375 
1376 extern lck_rw_t rootvnode_rw_lock;
1377 extern void set_rootvnode(vnode_t);
1378 
1379 
1380 static int
mntonname_fixup_callback(mount_t mp,__unused void * arg)1381 mntonname_fixup_callback(mount_t mp, __unused void *arg)
1382 {
1383 	int error = 0;
1384 
1385 	if ((strncmp(&mp->mnt_vfsstat.f_mntonname[0], "/", sizeof("/")) == 0) ||
1386 	    (strncmp(&mp->mnt_vfsstat.f_mntonname[0], "/dev", sizeof("/dev")) == 0)) {
1387 		return 0;
1388 	}
1389 
1390 	if ((error = vfs_busy(mp, LK_NOWAIT))) {
1391 		printf("vfs_busy failed with %d for %s\n", error, mp->mnt_vfsstat.f_mntonname);
1392 		return -1;
1393 	}
1394 
1395 	size_t pathlen = MAXPATHLEN;
1396 	if ((error = vn_getpath_ext(mp->mnt_vnodecovered, NULL, mp->mnt_vfsstat.f_mntonname, &pathlen, VN_GETPATH_FSENTER))) {
1397 		printf("vn_getpath_ext failed with %d for mnt_vnodecovered of %s\n", error, mp->mnt_vfsstat.f_mntonname);
1398 	}
1399 
1400 	vfs_unbusy(mp);
1401 
1402 	return error;
1403 }
1404 
1405 static int
clear_mntk_backs_root_callback(mount_t mp,__unused void * arg)1406 clear_mntk_backs_root_callback(mount_t mp, __unused void *arg)
1407 {
1408 	lck_rw_lock_exclusive(&mp->mnt_rwlock);
1409 	mp->mnt_kern_flag &= ~MNTK_BACKS_ROOT;
1410 	lck_rw_done(&mp->mnt_rwlock);
1411 	return VFS_RETURNED;
1412 }
1413 
1414 static int
verify_incoming_rootfs(vnode_t * incoming_rootvnodep,vfs_context_t ctx,vfs_switch_root_flags_t flags)1415 verify_incoming_rootfs(vnode_t *incoming_rootvnodep, vfs_context_t ctx,
1416     vfs_switch_root_flags_t flags)
1417 {
1418 	mount_t mp;
1419 	vnode_t tdp;
1420 	vnode_t incoming_rootvnode_with_iocount = *incoming_rootvnodep;
1421 	vnode_t incoming_rootvnode_with_usecount = NULLVP;
1422 	int error = 0;
1423 
1424 	if (vnode_vtype(incoming_rootvnode_with_iocount) != VDIR) {
1425 		printf("Incoming rootfs path not a directory\n");
1426 		error = ENOTDIR;
1427 		goto done;
1428 	}
1429 
1430 	/*
1431 	 * Before we call VFS_ROOT, we have to let go of the iocount already
1432 	 * acquired, but before doing that get a usecount.
1433 	 */
1434 	vnode_ref_ext(incoming_rootvnode_with_iocount, 0, VNODE_REF_FORCE);
1435 	incoming_rootvnode_with_usecount = incoming_rootvnode_with_iocount;
1436 	vnode_lock_spin(incoming_rootvnode_with_usecount);
1437 	if ((mp = incoming_rootvnode_with_usecount->v_mount)) {
1438 		mp->mnt_crossref++;
1439 		vnode_unlock(incoming_rootvnode_with_usecount);
1440 	} else {
1441 		vnode_unlock(incoming_rootvnode_with_usecount);
1442 		printf("Incoming rootfs root vnode does not have associated mount\n");
1443 		error = ENOTDIR;
1444 		goto done;
1445 	}
1446 
1447 	if (vfs_busy(mp, LK_NOWAIT)) {
1448 		printf("Incoming rootfs root vnode mount is busy\n");
1449 		error = ENOENT;
1450 		goto out;
1451 	}
1452 
1453 	vnode_put(incoming_rootvnode_with_iocount);
1454 	incoming_rootvnode_with_iocount = NULLVP;
1455 
1456 	error = VFS_ROOT(mp, &tdp, ctx);
1457 
1458 	if (error) {
1459 		printf("Could not get rootvnode of incoming rootfs\n");
1460 	} else if (tdp != incoming_rootvnode_with_usecount) {
1461 		vnode_put(tdp);
1462 		tdp = NULLVP;
1463 		printf("Incoming rootfs root vnode mount is is not a mountpoint\n");
1464 		error = EINVAL;
1465 		goto out_busy;
1466 	} else {
1467 		incoming_rootvnode_with_iocount = tdp;
1468 		tdp = NULLVP;
1469 	}
1470 
1471 	if ((flags & VFSSR_VIRTUALDEV_PROHIBITED) != 0) {
1472 		if (mp->mnt_flag & MNTK_VIRTUALDEV) {
1473 			error = ENODEV;
1474 		}
1475 		if (error) {
1476 			printf("Incoming rootfs is backed by a virtual device; cannot switch to it");
1477 			goto out_busy;
1478 		}
1479 	}
1480 
1481 out_busy:
1482 	vfs_unbusy(mp);
1483 
1484 out:
1485 	vnode_lock(incoming_rootvnode_with_usecount);
1486 	mp->mnt_crossref--;
1487 	if (mp->mnt_crossref < 0) {
1488 		panic("mount cross refs -ve");
1489 	}
1490 	vnode_unlock(incoming_rootvnode_with_usecount);
1491 
1492 done:
1493 	if (incoming_rootvnode_with_usecount) {
1494 		vnode_rele(incoming_rootvnode_with_usecount);
1495 		incoming_rootvnode_with_usecount = NULLVP;
1496 	}
1497 
1498 	if (error && incoming_rootvnode_with_iocount) {
1499 		vnode_put(incoming_rootvnode_with_iocount);
1500 		incoming_rootvnode_with_iocount = NULLVP;
1501 	}
1502 
1503 	*incoming_rootvnodep = incoming_rootvnode_with_iocount;
1504 	return error;
1505 }
1506 
1507 /*
1508  * vfs_switch_root()
1509  *
1510  * Move the current root volume, and put a different volume at the root.
1511  *
1512  * incoming_vol_old_path: This is the path where the incoming root volume
1513  *	is mounted when this function begins.
1514  * outgoing_vol_new_path: This is the path where the outgoing root volume
1515  *	will be mounted when this function (successfully) ends.
1516  *	Note: Do not use a leading slash.
1517  *
1518  * Volumes mounted at several fixed points (including /dev) will be preserved
1519  * at the same absolute path. That means they will move within the folder
1520  * hierarchy during the pivot operation. For example, /dev before the pivot
1521  * will be at /dev after the pivot.
1522  *
1523  * If any filesystem has MNTK_BACKS_ROOT set, it will be cleared. If the
1524  * incoming root volume is actually a disk image backed by some other
1525  * filesystem, it is the caller's responsibility to re-set MNTK_BACKS_ROOT
1526  * as appropriate.
1527  */
1528 int
vfs_switch_root(const char * incoming_vol_old_path,const char * outgoing_vol_new_path,vfs_switch_root_flags_t flags)1529 vfs_switch_root(const char *incoming_vol_old_path,
1530     const char *outgoing_vol_new_path,
1531     vfs_switch_root_flags_t flags)
1532 {
1533 	// grumble grumble
1534 #define countof(x) (sizeof(x) / sizeof(x[0]))
1535 
1536 	struct preserved_mount {
1537 		vnode_t pm_rootvnode;
1538 		mount_t pm_mount;
1539 		vnode_t pm_new_covered_vp;
1540 		vnode_t pm_old_covered_vp;
1541 		const char *pm_path;
1542 	};
1543 
1544 	vfs_context_t ctx = vfs_context_kernel();
1545 	vnode_t incoming_rootvnode = NULLVP;
1546 	vnode_t outgoing_vol_new_covered_vp = NULLVP;
1547 	vnode_t incoming_vol_old_covered_vp = NULLVP;
1548 	mount_t outgoing = NULL;
1549 	mount_t incoming = NULL;
1550 
1551 	struct preserved_mount devfs = { NULLVP, NULL, NULLVP, NULLVP, "dev" };
1552 	struct preserved_mount preboot = { NULLVP, NULL, NULLVP, NULLVP, "System/Volumes/Preboot" };
1553 	struct preserved_mount recovery = { NULLVP, NULL, NULLVP, NULLVP, "System/Volumes/Recovery" };
1554 	struct preserved_mount vm = { NULLVP, NULL, NULLVP, NULLVP, "System/Volumes/VM" };
1555 	struct preserved_mount update = { NULLVP, NULL, NULLVP, NULLVP, "System/Volumes/Update" };
1556 	struct preserved_mount iscPreboot = { NULLVP, NULL, NULLVP, NULLVP, "System/Volumes/iSCPreboot" };
1557 	struct preserved_mount hardware = { NULLVP, NULL, NULLVP, NULLVP, "System/Volumes/Hardware" };
1558 	struct preserved_mount xarts = { NULLVP, NULL, NULLVP, NULLVP, "System/Volumes/xarts" };
1559 	struct preserved_mount factorylogs = { NULLVP, NULL, NULLVP, NULLVP, "FactoryLogs" };
1560 	struct preserved_mount idiags = { NULLVP, NULL, NULLVP, NULLVP, "System/Volumes/Diags" };
1561 
1562 	struct preserved_mount *preserved[10];
1563 	preserved[0] = &devfs;
1564 	preserved[1] = &preboot;
1565 	preserved[2] = &recovery;
1566 	preserved[3] = &vm;
1567 	preserved[4] = &update;
1568 	preserved[5] = &iscPreboot;
1569 	preserved[6] = &hardware;
1570 	preserved[7] = &xarts;
1571 	preserved[8] = &factorylogs;
1572 	preserved[9] = &idiags;
1573 
1574 	int error;
1575 
1576 	printf("%s : shuffling mount points : %s <-> / <-> %s\n", __FUNCTION__, incoming_vol_old_path, outgoing_vol_new_path);
1577 
1578 	if (outgoing_vol_new_path[0] == '/') {
1579 		// I should have written this to be more helpful and just advance the pointer forward past the slash
1580 		printf("Do not use a leading slash in outgoing_vol_new_path\n");
1581 		return EINVAL;
1582 	}
1583 
1584 	// Set incoming_rootvnode.
1585 	// Find the vnode representing the mountpoint of the new root
1586 	// filesystem. That will be the new root directory.
1587 	error = vnode_lookup(incoming_vol_old_path, 0, &incoming_rootvnode, ctx);
1588 	if (error) {
1589 		printf("Incoming rootfs root vnode not found\n");
1590 		error = ENOENT;
1591 		goto done;
1592 	}
1593 
1594 	/*
1595 	 * This function drops the icoount and sets the vnode to NULL on error.
1596 	 */
1597 	error = verify_incoming_rootfs(&incoming_rootvnode, ctx, flags);
1598 	if (error) {
1599 		goto done;
1600 	}
1601 
1602 	/*
1603 	 * Set outgoing_vol_new_covered_vp.
1604 	 * Find the vnode representing the future mountpoint of the old
1605 	 * root filesystem, inside the directory incoming_rootvnode.
1606 	 * Right now it's at "/incoming_vol_old_path/outgoing_vol_new_path".
1607 	 * soon it will become "/oldrootfs_path_after", which will be covered.
1608 	 */
1609 	error = vnode_lookupat(outgoing_vol_new_path, 0, &outgoing_vol_new_covered_vp, ctx, incoming_rootvnode);
1610 	if (error) {
1611 		printf("Outgoing rootfs path not found, abandoning / switch, error = %d\n", error);
1612 		error = ENOENT;
1613 		goto done;
1614 	}
1615 	if (vnode_vtype(outgoing_vol_new_covered_vp) != VDIR) {
1616 		printf("Outgoing rootfs path is not a directory, abandoning / switch\n");
1617 		error = ENOTDIR;
1618 		goto done;
1619 	}
1620 
1621 	/*
1622 	 * Find the preserved mounts - see if they are mounted. Get their root
1623 	 * vnode if they are. If they aren't, leave rootvnode NULL which will
1624 	 * be the signal to ignore this mount later on.
1625 	 *
1626 	 * Also get preserved mounts' new_covered_vp.
1627 	 * Find the node representing the folder "dev" inside the directory newrootvnode.
1628 	 * Right now it's at "/incoming_vol_old_path/dev".
1629 	 * Soon it will become /dev, which will be covered by the devfs mountpoint.
1630 	 */
1631 	for (size_t i = 0; i < countof(preserved); i++) {
1632 		struct preserved_mount *pmi = preserved[i];
1633 
1634 		error = vnode_lookupat(pmi->pm_path, 0, &pmi->pm_rootvnode, ctx, rootvnode);
1635 		if (error) {
1636 			printf("skipping preserved mountpoint because not found or error: %d: %s\n", error, pmi->pm_path);
1637 			// not fatal. try the next one in the list.
1638 			continue;
1639 		}
1640 		bool is_mountpoint = false;
1641 		vnode_lock_spin(pmi->pm_rootvnode);
1642 		if ((pmi->pm_rootvnode->v_flag & VROOT) != 0) {
1643 			is_mountpoint = true;
1644 		}
1645 		vnode_unlock(pmi->pm_rootvnode);
1646 		if (!is_mountpoint) {
1647 			printf("skipping preserved mountpoint because not a mountpoint: %s\n", pmi->pm_path);
1648 			vnode_put(pmi->pm_rootvnode);
1649 			pmi->pm_rootvnode = NULLVP;
1650 			// not fatal. try the next one in the list.
1651 			continue;
1652 		}
1653 
1654 		error = vnode_lookupat(pmi->pm_path, 0, &pmi->pm_new_covered_vp, ctx, incoming_rootvnode);
1655 		if (error) {
1656 			printf("preserved new mount directory not found or error: %d: %s\n", error, pmi->pm_path);
1657 			error = ENOENT;
1658 			goto done;
1659 		}
1660 		if (vnode_vtype(pmi->pm_new_covered_vp) != VDIR) {
1661 			printf("preserved new mount directory not directory: %s\n", pmi->pm_path);
1662 			error = ENOTDIR;
1663 			goto done;
1664 		}
1665 
1666 		printf("will preserve mountpoint across pivot: /%s\n", pmi->pm_path);
1667 	}
1668 
1669 	/*
1670 	 * --
1671 	 * At this point, everything has been prepared and all error conditions
1672 	 * have been checked. We check everything we can before this point;
1673 	 * from now on we start making destructive changes, and we can't stop
1674 	 * until we reach the end.
1675 	 * ----
1676 	 */
1677 
1678 	/* this usecount is transferred to the mnt_vnodecovered */
1679 	vnode_ref_ext(outgoing_vol_new_covered_vp, 0, VNODE_REF_FORCE);
1680 	/* this usecount is transferred to set_rootvnode */
1681 	vnode_ref_ext(incoming_rootvnode, 0, VNODE_REF_FORCE);
1682 
1683 
1684 	for (size_t i = 0; i < countof(preserved); i++) {
1685 		struct preserved_mount *pmi = preserved[i];
1686 		if (pmi->pm_rootvnode == NULLVP) {
1687 			continue;
1688 		}
1689 
1690 		/* this usecount is transferred to the mnt_vnodecovered */
1691 		vnode_ref_ext(pmi->pm_new_covered_vp, 0, VNODE_REF_FORCE);
1692 
1693 		/* The new_covered_vp is a mountpoint from now on. */
1694 		vnode_lock_spin(pmi->pm_new_covered_vp);
1695 		pmi->pm_new_covered_vp->v_flag |= VMOUNT;
1696 		vnode_unlock(pmi->pm_new_covered_vp);
1697 	}
1698 
1699 	/* The outgoing_vol_new_covered_vp is a mountpoint from now on. */
1700 	vnode_lock_spin(outgoing_vol_new_covered_vp);
1701 	outgoing_vol_new_covered_vp->v_flag |= VMOUNT;
1702 	vnode_unlock(outgoing_vol_new_covered_vp);
1703 
1704 
1705 	/*
1706 	 * Identify the mount_ts of the mounted filesystems that are being
1707 	 * manipulated: outgoing rootfs, incoming rootfs, and the preserved
1708 	 * mounts.
1709 	 */
1710 	outgoing = rootvnode->v_mount;
1711 	incoming = incoming_rootvnode->v_mount;
1712 	for (size_t i = 0; i < countof(preserved); i++) {
1713 		struct preserved_mount *pmi = preserved[i];
1714 		if (pmi->pm_rootvnode == NULLVP) {
1715 			continue;
1716 		}
1717 
1718 		pmi->pm_mount = pmi->pm_rootvnode->v_mount;
1719 	}
1720 
1721 	lck_rw_lock_exclusive(&rootvnode_rw_lock);
1722 
1723 	/* Setup incoming as the new rootfs */
1724 	lck_rw_lock_exclusive(&incoming->mnt_rwlock);
1725 	incoming_vol_old_covered_vp = incoming->mnt_vnodecovered;
1726 	incoming->mnt_vnodecovered = NULLVP;
1727 	strlcpy(incoming->mnt_vfsstat.f_mntonname, "/", MAXPATHLEN);
1728 	incoming->mnt_flag |= MNT_ROOTFS;
1729 	lck_rw_done(&incoming->mnt_rwlock);
1730 
1731 	/*
1732 	 * The preserved mountpoints will now be moved to
1733 	 * incoming_rootnode/pm_path, and then by the end of the function,
1734 	 * since incoming_rootnode is going to /, the preserved mounts
1735 	 * will be end up back at /pm_path
1736 	 */
1737 	for (size_t i = 0; i < countof(preserved); i++) {
1738 		struct preserved_mount *pmi = preserved[i];
1739 		if (pmi->pm_rootvnode == NULLVP) {
1740 			continue;
1741 		}
1742 
1743 		lck_rw_lock_exclusive(&pmi->pm_mount->mnt_rwlock);
1744 		pmi->pm_old_covered_vp = pmi->pm_mount->mnt_vnodecovered;
1745 		pmi->pm_mount->mnt_vnodecovered = pmi->pm_new_covered_vp;
1746 		vnode_lock_spin(pmi->pm_new_covered_vp);
1747 		pmi->pm_new_covered_vp->v_mountedhere = pmi->pm_mount;
1748 		vnode_unlock(pmi->pm_new_covered_vp);
1749 		lck_rw_done(&pmi->pm_mount->mnt_rwlock);
1750 	}
1751 
1752 	/*
1753 	 * The old root volume now covers outgoing_vol_new_covered_vp
1754 	 * on the new root volume. Remove the ROOTFS marker.
1755 	 * Now it is to be found at outgoing_vol_new_path
1756 	 */
1757 	lck_rw_lock_exclusive(&outgoing->mnt_rwlock);
1758 	outgoing->mnt_vnodecovered = outgoing_vol_new_covered_vp;
1759 	strlcpy(outgoing->mnt_vfsstat.f_mntonname, "/", MAXPATHLEN);
1760 	strlcat(outgoing->mnt_vfsstat.f_mntonname, outgoing_vol_new_path, MAXPATHLEN);
1761 	outgoing->mnt_flag &= ~MNT_ROOTFS;
1762 	vnode_lock_spin(outgoing_vol_new_covered_vp);
1763 	outgoing_vol_new_covered_vp->v_mountedhere = outgoing;
1764 	vnode_unlock(outgoing_vol_new_covered_vp);
1765 	lck_rw_done(&outgoing->mnt_rwlock);
1766 
1767 	if (!(outgoing->mnt_kern_flag & MNTK_VIRTUALDEV) &&
1768 	    (TAILQ_FIRST(&mountlist) == outgoing)) {
1769 		vfs_setmntsystem(outgoing);
1770 	}
1771 
1772 	/*
1773 	 * Finally, remove the mount_t linkage from the previously covered
1774 	 * vnodes on the old root volume. These were incoming_vol_old_path,
1775 	 * and each preserved mounts's "/pm_path". The filesystems previously
1776 	 * mounted there have already been moved away.
1777 	 */
1778 	vnode_lock_spin(incoming_vol_old_covered_vp);
1779 	incoming_vol_old_covered_vp->v_flag &= ~VMOUNT;
1780 	incoming_vol_old_covered_vp->v_mountedhere = NULL;
1781 	vnode_unlock(incoming_vol_old_covered_vp);
1782 
1783 	for (size_t i = 0; i < countof(preserved); i++) {
1784 		struct preserved_mount *pmi = preserved[i];
1785 		if (pmi->pm_rootvnode == NULLVP) {
1786 			continue;
1787 		}
1788 
1789 		vnode_lock_spin(pmi->pm_old_covered_vp);
1790 		pmi->pm_old_covered_vp->v_flag &= ~VMOUNT;
1791 		pmi->pm_old_covered_vp->v_mountedhere = NULL;
1792 		vnode_unlock(pmi->pm_old_covered_vp);
1793 	}
1794 
1795 	/*
1796 	 * Clear the name cache since many cached names are now invalid.
1797 	 */
1798 	vfs_iterate(0 /* flags */, cache_purge_callback, NULL);
1799 
1800 	/*
1801 	 * Actually change the rootvnode! And finally drop the lock that
1802 	 * prevents concurrent vnode_lookups.
1803 	 */
1804 	set_rootvnode(incoming_rootvnode);
1805 	lck_rw_unlock_exclusive(&rootvnode_rw_lock);
1806 
1807 	if (!(incoming->mnt_kern_flag & MNTK_VIRTUALDEV) &&
1808 	    !(outgoing->mnt_kern_flag & MNTK_VIRTUALDEV)) {
1809 		/*
1810 		 * Switch the order of mount structures in the mountlist, new root
1811 		 * mount moves to the head of the list followed by /dev and the other
1812 		 * preserved mounts then all the preexisting mounts (old rootfs + any
1813 		 * others)
1814 		 */
1815 		mount_list_lock();
1816 		for (size_t i = 0; i < countof(preserved); i++) {
1817 			struct preserved_mount *pmi = preserved[i];
1818 			if (pmi->pm_rootvnode == NULLVP) {
1819 				continue;
1820 			}
1821 
1822 			TAILQ_REMOVE(&mountlist, pmi->pm_mount, mnt_list);
1823 			TAILQ_INSERT_HEAD(&mountlist, pmi->pm_mount, mnt_list);
1824 		}
1825 		TAILQ_REMOVE(&mountlist, incoming, mnt_list);
1826 		TAILQ_INSERT_HEAD(&mountlist, incoming, mnt_list);
1827 		mount_list_unlock();
1828 	}
1829 
1830 	/*
1831 	 * Fixups across all volumes
1832 	 */
1833 	vfs_iterate(0 /* flags */, mntonname_fixup_callback, NULL);
1834 	vfs_iterate(0 /* flags */, clear_mntk_backs_root_callback, NULL);
1835 
1836 	error = 0;
1837 
1838 done:
1839 	for (size_t i = 0; i < countof(preserved); i++) {
1840 		struct preserved_mount *pmi = preserved[i];
1841 
1842 		if (pmi->pm_rootvnode) {
1843 			vnode_put(pmi->pm_rootvnode);
1844 		}
1845 		if (pmi->pm_new_covered_vp) {
1846 			vnode_put(pmi->pm_new_covered_vp);
1847 		}
1848 		if (pmi->pm_old_covered_vp) {
1849 			vnode_rele(pmi->pm_old_covered_vp);
1850 		}
1851 	}
1852 
1853 	if (outgoing_vol_new_covered_vp) {
1854 		vnode_put(outgoing_vol_new_covered_vp);
1855 	}
1856 
1857 	if (incoming_vol_old_covered_vp) {
1858 		vnode_rele(incoming_vol_old_covered_vp);
1859 	}
1860 
1861 	if (incoming_rootvnode) {
1862 		vnode_put(incoming_rootvnode);
1863 	}
1864 
1865 	printf("%s : done shuffling mount points with error: %d\n", __FUNCTION__, error);
1866 	return error;
1867 }
1868 
1869 /*
1870  * Mount the Recovery volume of a container
1871  */
1872 int
vfs_mount_recovery(void)1873 vfs_mount_recovery(void)
1874 {
1875 #if CONFIG_MOUNT_PREBOOTRECOVERY
1876 	int error = 0;
1877 
1878 	error = vnode_get(rootvnode);
1879 	if (error) {
1880 		/* root must be mounted first */
1881 		printf("vnode_get(rootvnode) failed with error %d\n", error);
1882 		return error;
1883 	}
1884 
1885 	char recoverypath[] = PLATFORM_RECOVERY_VOLUME_MOUNT_POINT; /* !const because of internal casting */
1886 
1887 	/* Mount the recovery volume */
1888 	printf("attempting kernel mount for recovery volume... \n");
1889 	error = kernel_mount(rootvnode->v_mount->mnt_vfsstat.f_fstypename, NULLVP, NULLVP,
1890 	    recoverypath, (rootvnode->v_mount), 0, 0, (KERNEL_MOUNT_RECOVERYVOL), vfs_context_kernel());
1891 
1892 	if (error) {
1893 		printf("Failed to mount recovery volume (%d)\n", error);
1894 	} else {
1895 		printf("mounted recovery volume\n");
1896 	}
1897 
1898 	vnode_put(rootvnode);
1899 	return error;
1900 #else
1901 	return 0;
1902 #endif
1903 }
1904 
1905 /*
1906  * Lookup a mount point by filesystem identifier.
1907  */
1908 
1909 struct mount *
vfs_getvfs(fsid_t * fsid)1910 vfs_getvfs(fsid_t *fsid)
1911 {
1912 	return mount_list_lookupby_fsid(fsid, 0, 0);
1913 }
1914 
1915 static struct mount *
vfs_getvfs_locked(fsid_t * fsid)1916 vfs_getvfs_locked(fsid_t *fsid)
1917 {
1918 	return mount_list_lookupby_fsid(fsid, 1, 0);
1919 }
1920 
1921 struct mount *
vfs_getvfs_by_mntonname(char * path)1922 vfs_getvfs_by_mntonname(char *path)
1923 {
1924 	mount_t retmp = (mount_t)0;
1925 	mount_t mp;
1926 
1927 	mount_list_lock();
1928 	TAILQ_FOREACH(mp, &mountlist, mnt_list) {
1929 		if (!strncmp(mp->mnt_vfsstat.f_mntonname, path,
1930 		    sizeof(mp->mnt_vfsstat.f_mntonname))) {
1931 			retmp = mp;
1932 			if (mount_iterref(retmp, 1)) {
1933 				retmp = NULL;
1934 			}
1935 			goto out;
1936 		}
1937 	}
1938 out:
1939 	mount_list_unlock();
1940 	return retmp;
1941 }
1942 
1943 /* generation number for creation of new fsids */
1944 u_short mntid_gen = 0;
1945 /*
1946  * Get a new unique fsid
1947  */
1948 void
vfs_getnewfsid(struct mount * mp)1949 vfs_getnewfsid(struct mount *mp)
1950 {
1951 	fsid_t tfsid;
1952 	int mtype;
1953 
1954 	mount_list_lock();
1955 
1956 	/* generate a new fsid */
1957 	mtype = mp->mnt_vtable->vfc_typenum;
1958 	if (++mntid_gen == 0) {
1959 		mntid_gen++;
1960 	}
1961 	tfsid.val[0] = makedev(nblkdev + mtype, mntid_gen);
1962 	tfsid.val[1] = mtype;
1963 
1964 	while (vfs_getvfs_locked(&tfsid)) {
1965 		if (++mntid_gen == 0) {
1966 			mntid_gen++;
1967 		}
1968 		tfsid.val[0] = makedev(nblkdev + mtype, mntid_gen);
1969 	}
1970 
1971 	mp->mnt_vfsstat.f_fsid.val[0] = tfsid.val[0];
1972 	mp->mnt_vfsstat.f_fsid.val[1] = tfsid.val[1];
1973 	mount_list_unlock();
1974 }
1975 
1976 /*
1977  * Routines having to do with the management of the vnode table.
1978  */
1979 extern int(**dead_vnodeop_p)(void *);
1980 long numvnodes, freevnodes, deadvnodes, async_work_vnodes;
1981 long busyvnodes = 0;
1982 long deadvnodes_noreuse = 0;
1983 int32_t freeablevnodes = 0;
1984 uint64_t allocedvnodes = 0;
1985 uint64_t deallocedvnodes = 0;
1986 
1987 
1988 int async_work_timed_out = 0;
1989 int async_work_handled = 0;
1990 int dead_vnode_wanted = 0;
1991 int dead_vnode_waited = 0;
1992 
1993 /*
1994  * Move a vnode from one mount queue to another.
1995  */
1996 static void
insmntque(vnode_t vp,mount_t mp)1997 insmntque(vnode_t vp, mount_t mp)
1998 {
1999 	mount_t lmp;
2000 	/*
2001 	 * Delete from old mount point vnode list, if on one.
2002 	 */
2003 	if ((lmp = vp->v_mount) != NULL && lmp != dead_mountp) {
2004 		if ((vp->v_lflag & VNAMED_MOUNT) == 0) {
2005 			panic("insmntque: vp not in mount vnode list");
2006 		}
2007 		vp->v_lflag &= ~VNAMED_MOUNT;
2008 
2009 		mount_lock_spin(lmp);
2010 
2011 		mount_drop(lmp, 1);
2012 
2013 		if (vp->v_mntvnodes.tqe_next == NULL) {
2014 			if (TAILQ_LAST(&lmp->mnt_vnodelist, vnodelst) == vp) {
2015 				TAILQ_REMOVE(&lmp->mnt_vnodelist, vp, v_mntvnodes);
2016 			} else if (TAILQ_LAST(&lmp->mnt_newvnodes, vnodelst) == vp) {
2017 				TAILQ_REMOVE(&lmp->mnt_newvnodes, vp, v_mntvnodes);
2018 			} else if (TAILQ_LAST(&lmp->mnt_workerqueue, vnodelst) == vp) {
2019 				TAILQ_REMOVE(&lmp->mnt_workerqueue, vp, v_mntvnodes);
2020 			}
2021 		} else {
2022 			vp->v_mntvnodes.tqe_next->v_mntvnodes.tqe_prev = vp->v_mntvnodes.tqe_prev;
2023 			*vp->v_mntvnodes.tqe_prev = vp->v_mntvnodes.tqe_next;
2024 		}
2025 		vp->v_mntvnodes.tqe_next = NULL;
2026 		vp->v_mntvnodes.tqe_prev = NULL;
2027 		mount_unlock(lmp);
2028 		vnode_drop(vp);
2029 		return;
2030 	}
2031 
2032 	/*
2033 	 * Insert into list of vnodes for the new mount point, if available.
2034 	 */
2035 	if ((vp->v_mount = mp) != NULL) {
2036 		mount_lock_spin(mp);
2037 		if ((vp->v_mntvnodes.tqe_next != 0) && (vp->v_mntvnodes.tqe_prev != 0)) {
2038 			panic("vp already in mount list");
2039 		}
2040 		if (mp->mnt_lflag & MNT_LITER) {
2041 			TAILQ_INSERT_HEAD(&mp->mnt_newvnodes, vp, v_mntvnodes);
2042 		} else {
2043 			TAILQ_INSERT_HEAD(&mp->mnt_vnodelist, vp, v_mntvnodes);
2044 		}
2045 		if (vp->v_lflag & VNAMED_MOUNT) {
2046 			panic("insmntque: vp already in mount vnode list");
2047 		}
2048 		vnode_hold(vp);
2049 		vp->v_lflag |= VNAMED_MOUNT;
2050 		mount_ref(mp, 1);
2051 		mount_unlock(mp);
2052 	}
2053 }
2054 
2055 
2056 /*
2057  * Create a vnode for a block device.
2058  * Used for root filesystem, argdev, and swap areas.
2059  * Also used for memory file system special devices.
2060  */
2061 int
bdevvp(dev_t dev,vnode_t * vpp)2062 bdevvp(dev_t dev, vnode_t *vpp)
2063 {
2064 	vnode_t nvp;
2065 	int     error;
2066 	struct vnode_fsparam vfsp;
2067 	struct vfs_context context;
2068 
2069 	if (dev == NODEV) {
2070 		*vpp = NULLVP;
2071 		return ENODEV;
2072 	}
2073 
2074 	context.vc_thread = current_thread();
2075 	context.vc_ucred = FSCRED;
2076 
2077 	vfsp.vnfs_mp = (struct mount *)0;
2078 	vfsp.vnfs_vtype = VBLK;
2079 	vfsp.vnfs_str = "bdevvp";
2080 	vfsp.vnfs_dvp = NULL;
2081 	vfsp.vnfs_fsnode = NULL;
2082 	vfsp.vnfs_cnp = NULL;
2083 	vfsp.vnfs_vops = spec_vnodeop_p;
2084 	vfsp.vnfs_rdev = dev;
2085 	vfsp.vnfs_filesize = 0;
2086 
2087 	vfsp.vnfs_flags = VNFS_NOCACHE | VNFS_CANTCACHE;
2088 
2089 	vfsp.vnfs_marksystem = 0;
2090 	vfsp.vnfs_markroot = 0;
2091 
2092 	if ((error = vnode_create(VNCREATE_FLAVOR, VCREATESIZE, &vfsp, &nvp))) {
2093 		*vpp = NULLVP;
2094 		return error;
2095 	}
2096 	vnode_lock_spin(nvp);
2097 	nvp->v_flag |= VBDEVVP;
2098 	nvp->v_tag = VT_NON;    /* set this to VT_NON so during aliasing it can be replaced */
2099 	vnode_unlock(nvp);
2100 	if ((error = vnode_ref(nvp))) {
2101 		panic("bdevvp failed: vnode_ref");
2102 		return error;
2103 	}
2104 	if ((error = VNOP_FSYNC(nvp, MNT_WAIT, &context))) {
2105 		panic("bdevvp failed: fsync");
2106 		return error;
2107 	}
2108 	if ((error = buf_invalidateblks(nvp, BUF_WRITE_DATA, 0, 0))) {
2109 		panic("bdevvp failed: invalidateblks");
2110 		return error;
2111 	}
2112 
2113 #if CONFIG_MACF
2114 	/*
2115 	 * XXXMAC: We can't put a MAC check here, the system will
2116 	 * panic without this vnode.
2117 	 */
2118 #endif /* MAC */
2119 
2120 	if ((error = VNOP_OPEN(nvp, FREAD, &context))) {
2121 		panic("bdevvp failed: open");
2122 		return error;
2123 	}
2124 	*vpp = nvp;
2125 
2126 	return 0;
2127 }
2128 
2129 /*
2130  * Check to see if the new vnode represents a special device
2131  * for which we already have a vnode (either because of
2132  * bdevvp() or because of a different vnode representing
2133  * the same block device). If such an alias exists, deallocate
2134  * the existing contents and return the aliased vnode. The
2135  * caller is responsible for filling it with its new contents.
2136  */
2137 static vnode_t
checkalias(struct vnode * nvp,dev_t nvp_rdev)2138 checkalias(struct vnode *nvp, dev_t nvp_rdev)
2139 {
2140 	struct vnode *vp;
2141 	struct vnode **vpp;
2142 	struct specinfo *sin = NULL;
2143 	int vid = 0;
2144 
2145 	vpp = &speclisth[SPECHASH(nvp_rdev)];
2146 loop:
2147 	SPECHASH_LOCK();
2148 
2149 	for (vp = *vpp; vp; vp = vp->v_specnext) {
2150 		if (nvp_rdev == vp->v_rdev && nvp->v_type == vp->v_type) {
2151 			vid = vp->v_id;
2152 			vnode_hold(vp);
2153 			break;
2154 		}
2155 	}
2156 	SPECHASH_UNLOCK();
2157 
2158 	if (vp) {
2159 found_alias:
2160 		if (vnode_getwithvid(vp, vid)) {
2161 			vnode_drop(vp);
2162 			goto loop;
2163 		}
2164 		vnode_drop(vp);
2165 		/*
2166 		 * Termination state is checked in vnode_getwithvid
2167 		 */
2168 		vnode_lock(vp);
2169 
2170 		/*
2171 		 * Alias, but not in use, so flush it out.
2172 		 */
2173 		if ((vp->v_iocount == 1) && (vp->v_usecount == 0)) {
2174 			vnode_hold(vp);
2175 			vnode_reclaim_internal(vp, 1, 1, 0);
2176 			vnode_put_locked(vp);
2177 			vnode_drop_and_unlock(vp);
2178 			goto loop;
2179 		}
2180 	}
2181 	if (vp == NULL || vp->v_tag != VT_NON) {
2182 		if (sin == NULL) {
2183 			sin = zalloc_flags(specinfo_zone, Z_WAITOK | Z_ZERO);
2184 		} else {
2185 			bzero(sin, sizeof(struct specinfo));
2186 		}
2187 
2188 		nvp->v_specinfo = sin;
2189 		nvp->v_rdev = nvp_rdev;
2190 		nvp->v_specflags = 0;
2191 		nvp->v_speclastr = -1;
2192 		nvp->v_specinfo->si_opencount = 0;
2193 		nvp->v_specinfo->si_initted = 0;
2194 		nvp->v_specinfo->si_throttleable = 0;
2195 
2196 		SPECHASH_LOCK();
2197 
2198 		/* We dropped the lock, someone could have added */
2199 		if (vp == NULLVP) {
2200 			for (vp = *vpp; vp; vp = vp->v_specnext) {
2201 				if (nvp_rdev == vp->v_rdev && nvp->v_type == vp->v_type) {
2202 					vid = vp->v_id;
2203 					vnode_hold(vp);
2204 					SPECHASH_UNLOCK();
2205 					goto found_alias;
2206 				}
2207 			}
2208 		}
2209 
2210 		nvp->v_hashchain = vpp;
2211 		nvp->v_specnext = *vpp;
2212 		*vpp = nvp;
2213 
2214 		if (vp != NULLVP) {
2215 			nvp->v_specflags |= SI_ALIASED;
2216 			vp->v_specflags |= SI_ALIASED;
2217 			SPECHASH_UNLOCK();
2218 			vnode_put_locked(vp);
2219 			vnode_unlock(vp);
2220 		} else {
2221 			SPECHASH_UNLOCK();
2222 		}
2223 
2224 		return NULLVP;
2225 	}
2226 
2227 	if (sin) {
2228 		zfree(specinfo_zone, sin);
2229 	}
2230 
2231 	if ((vp->v_flag & (VBDEVVP | VDEVFLUSH)) != 0) {
2232 		return vp;
2233 	}
2234 
2235 	panic("checkalias with VT_NON vp that shouldn't: %p", vp);
2236 
2237 	return vp;
2238 }
2239 
2240 
2241 /*
2242  * Get a reference on a particular vnode and lock it if requested.
2243  * If the vnode was on the inactive list, remove it from the list.
2244  * If the vnode was on the free list, remove it from the list and
2245  * move it to inactive list as needed.
2246  * The vnode lock bit is set if the vnode is being eliminated in
2247  * vgone. The process is awakened when the transition is completed,
2248  * and an error returned to indicate that the vnode is no longer
2249  * usable (possibly having been changed to a new file system type).
2250  */
2251 int
vget_internal(vnode_t vp,int vid,int vflags)2252 vget_internal(vnode_t vp, int vid, int vflags)
2253 {
2254 	int error = 0;
2255 
2256 	vnode_lock_spin(vp);
2257 
2258 	if ((vflags & VNODE_WRITEABLE) && (vp->v_writecount == 0)) {
2259 		/*
2260 		 * vnode to be returned only if it has writers opened
2261 		 */
2262 		error = EINVAL;
2263 	} else {
2264 		error = vnode_getiocount(vp, vid, vflags);
2265 	}
2266 
2267 	vnode_unlock(vp);
2268 
2269 	return error;
2270 }
2271 
2272 /*
2273  * Returns:	0			Success
2274  *		ENOENT			No such file or directory [terminating]
2275  */
2276 int
vnode_ref(vnode_t vp)2277 vnode_ref(vnode_t vp)
2278 {
2279 	return vnode_ref_ext(vp, 0, 0);
2280 }
2281 
2282 /*
2283  * Returns:	0			Success
2284  *		ENOENT			No such file or directory [terminating]
2285  */
2286 int
vnode_ref_ext(vnode_t vp,int fmode,int flags)2287 vnode_ref_ext(vnode_t vp, int fmode, int flags)
2288 {
2289 	int     error = 0;
2290 
2291 	vnode_lock_spin(vp);
2292 
2293 	/*
2294 	 * once all the current call sites have been fixed to insure they have
2295 	 * taken an iocount, we can toughen this assert up and insist that the
2296 	 * iocount is non-zero... a non-zero usecount doesn't insure correctness
2297 	 */
2298 	if (vp->v_iocount <= 0 && vp->v_usecount <= 0) {
2299 		panic("vnode_ref_ext: vp %p has no valid reference %d, %d", vp, vp->v_iocount, vp->v_usecount);
2300 	}
2301 
2302 	/*
2303 	 * if you are the owner of drain/termination, can acquire usecount
2304 	 */
2305 	if ((flags & VNODE_REF_FORCE) == 0) {
2306 		if ((vp->v_lflag & (VL_DRAIN | VL_TERMINATE | VL_DEAD))) {
2307 			if (vp->v_owner != current_thread()) {
2308 				error = ENOENT;
2309 				goto out;
2310 			}
2311 		}
2312 	}
2313 
2314 	/* Enable atomic ops on v_usecount without the vnode lock */
2315 	os_atomic_inc(&vp->v_usecount, relaxed);
2316 
2317 	if (fmode & FWRITE) {
2318 		if (++vp->v_writecount <= 0) {
2319 			panic("vnode_ref_ext: v_writecount");
2320 		}
2321 	}
2322 	if (fmode & O_EVTONLY) {
2323 		if (++vp->v_kusecount <= 0) {
2324 			panic("vnode_ref_ext: v_kusecount");
2325 		}
2326 	}
2327 	if (vp->v_flag & VRAGE) {
2328 		struct  uthread *ut;
2329 
2330 		ut = current_uthread();
2331 
2332 		if (!(current_proc()->p_lflag & P_LRAGE_VNODES) &&
2333 		    !(ut->uu_flag & UT_RAGE_VNODES)) {
2334 			/*
2335 			 * a 'normal' process accessed this vnode
2336 			 * so make sure its no longer marked
2337 			 * for rapid aging...  also, make sure
2338 			 * it gets removed from the rage list...
2339 			 * when v_usecount drops back to 0, it
2340 			 * will be put back on the real free list
2341 			 */
2342 			vp->v_flag &= ~VRAGE;
2343 			vp->v_references = 0;
2344 			vnode_list_remove(vp);
2345 		}
2346 	}
2347 	if (vp->v_usecount == 1 && vp->v_type == VREG && !(vp->v_flag & VSYSTEM)) {
2348 		if (vp->v_ubcinfo) {
2349 			vnode_lock_convert(vp);
2350 			memory_object_mark_used(vp->v_ubcinfo->ui_control);
2351 		}
2352 	}
2353 out:
2354 	vnode_unlock(vp);
2355 
2356 	return error;
2357 }
2358 
2359 
2360 boolean_t
vnode_on_reliable_media(vnode_t vp)2361 vnode_on_reliable_media(vnode_t vp)
2362 {
2363 	mount_t mp = vp->v_mount;
2364 
2365 	/*
2366 	 * A NULL mountpoint would imply it's not attached to a any filesystem.
2367 	 * This can only happen with a vnode created by bdevvp(). We'll consider
2368 	 * those as not unreliable as the primary use of this function is determine
2369 	 * which vnodes are to be handed off to the async cleaner thread for
2370 	 * reclaim.
2371 	 */
2372 	if (!mp || (!(mp->mnt_kern_flag & MNTK_VIRTUALDEV) && (mp->mnt_flag & MNT_LOCAL))) {
2373 		return TRUE;
2374 	}
2375 
2376 	return FALSE;
2377 }
2378 
2379 static void
vnode_async_list_add_locked(vnode_t vp)2380 vnode_async_list_add_locked(vnode_t vp)
2381 {
2382 	if (VONLIST(vp) || (vp->v_lflag & (VL_TERMINATE | VL_DEAD))) {
2383 		panic("vnode_async_list_add: %p is in wrong state", vp);
2384 	}
2385 
2386 	TAILQ_INSERT_HEAD(&vnode_async_work_list, vp, v_freelist);
2387 	vp->v_listflag |= VLIST_ASYNC_WORK;
2388 
2389 	async_work_vnodes++;
2390 	if (!(vp->v_listflag & VLIST_NO_REUSE)) {
2391 		reusablevnodes++;
2392 	}
2393 	if (vp->v_flag & VCANDEALLOC) {
2394 		os_atomic_dec(&busyvnodes, relaxed);
2395 	}
2396 }
2397 
2398 static void
vnode_async_list_add(vnode_t vp)2399 vnode_async_list_add(vnode_t vp)
2400 {
2401 	vnode_list_lock();
2402 
2403 	if (VONLIST(vp)) {
2404 		if (!(vp->v_listflag & VLIST_ASYNC_WORK)) {
2405 			vnode_list_remove_locked(vp);
2406 			vnode_async_list_add_locked(vp);
2407 		}
2408 	} else {
2409 		vnode_async_list_add_locked(vp);
2410 	}
2411 
2412 	vnode_list_unlock();
2413 
2414 	wakeup(&vnode_async_work_list);
2415 }
2416 
2417 
2418 /*
2419  * put the vnode on appropriate free list.
2420  * called with vnode LOCKED
2421  */
2422 static void
vnode_list_add(vnode_t vp)2423 vnode_list_add(vnode_t vp)
2424 {
2425 	boolean_t need_dead_wakeup = FALSE;
2426 	bool no_busy_decrement = false;
2427 
2428 #if DIAGNOSTIC
2429 	lck_mtx_assert(&vp->v_lock, LCK_MTX_ASSERT_OWNED);
2430 #endif
2431 
2432 again:
2433 
2434 	/*
2435 	 * if it is already on a list or non zero references return
2436 	 */
2437 	if (VONLIST(vp) || (vp->v_usecount != 0) || (vp->v_iocount != 0) || (vp->v_lflag & VL_TERMINATE)) {
2438 		return;
2439 	}
2440 
2441 	/*
2442 	 * In vclean, we might have deferred ditching locked buffers
2443 	 * because something was still referencing them (indicated by
2444 	 * usecount).  We can ditch them now.
2445 	 */
2446 	if (ISSET(vp->v_lflag, VL_DEAD)
2447 	    && (!LIST_EMPTY(&vp->v_cleanblkhd) || !LIST_EMPTY(&vp->v_dirtyblkhd))) {
2448 		++vp->v_iocount;        // Probably not necessary, but harmless
2449 #ifdef CONFIG_IOCOUNT_TRACE
2450 		record_vp(vp, 1);
2451 #endif
2452 		vnode_unlock(vp);
2453 		buf_invalidateblks(vp, BUF_INVALIDATE_LOCKED, 0, 0);
2454 		vnode_lock(vp);
2455 		vnode_dropiocount(vp);
2456 		goto again;
2457 	}
2458 
2459 	vnode_list_lock();
2460 
2461 	if (!(vp->v_lflag & VL_DEAD) && (vp->v_listflag & VLIST_NO_REUSE)) {
2462 		if (!(vp->v_listflag & VLIST_ASYNC_WORK)) {
2463 			vnode_async_list_add_locked(vp);
2464 		}
2465 		no_busy_decrement = true;
2466 	} else if ((vp->v_flag & VRAGE) && !(vp->v_lflag & VL_DEAD)) {
2467 		/*
2468 		 * add the new guy to the appropriate end of the RAGE list
2469 		 */
2470 		if ((vp->v_flag & VAGE)) {
2471 			TAILQ_INSERT_HEAD(&vnode_rage_list, vp, v_freelist);
2472 		} else {
2473 			TAILQ_INSERT_TAIL(&vnode_rage_list, vp, v_freelist);
2474 		}
2475 
2476 		vp->v_listflag |= VLIST_RAGE;
2477 		ragevnodes++;
2478 		reusablevnodes++;
2479 		wakeup_laundry_thread();
2480 
2481 		/*
2482 		 * reset the timestamp for the last inserted vp on the RAGE
2483 		 * queue to let new_vnode know that its not ok to start stealing
2484 		 * from this list... as long as we're actively adding to this list
2485 		 * we'll push out the vnodes we want to donate to the real free list
2486 		 * once we stop pushing, we'll let some time elapse before we start
2487 		 * stealing them in the new_vnode routine
2488 		 */
2489 		microuptime(&rage_tv);
2490 	} else {
2491 		/*
2492 		 * if VL_DEAD, insert it at head of the dead list
2493 		 * else insert at tail of LRU list or at head if VAGE is set
2494 		 */
2495 		if ((vp->v_lflag & VL_DEAD)) {
2496 			if (vp->v_flag & VCANDEALLOC) {
2497 				TAILQ_INSERT_TAIL(&vnode_dead_list, vp, v_freelist);
2498 				if (vp->v_listflag & VLIST_NO_REUSE) {
2499 					deadvnodes_noreuse++;
2500 				}
2501 			} else {
2502 				TAILQ_INSERT_HEAD(&vnode_dead_list, vp, v_freelist);
2503 			}
2504 			vp->v_listflag |= VLIST_DEAD;
2505 			deadvnodes++;
2506 
2507 			if (dead_vnode_wanted) {
2508 				dead_vnode_wanted--;
2509 				need_dead_wakeup = TRUE;
2510 			}
2511 		} else if ((vp->v_flag & VAGE)) {
2512 			TAILQ_INSERT_HEAD(&vnode_free_list, vp, v_freelist);
2513 			vp->v_flag &= ~VAGE;
2514 			freevnodes++;
2515 			reusablevnodes++;
2516 			wakeup_laundry_thread();
2517 		} else {
2518 			TAILQ_INSERT_TAIL(&vnode_free_list, vp, v_freelist);
2519 			freevnodes++;
2520 			reusablevnodes++;
2521 			wakeup_laundry_thread();
2522 		}
2523 	}
2524 	if ((vp->v_flag & VCANDEALLOC) && !no_busy_decrement) {
2525 		os_atomic_dec(&busyvnodes, relaxed);
2526 	}
2527 	vnode_list_unlock();
2528 
2529 	if (need_dead_wakeup == TRUE) {
2530 		wakeup_one((caddr_t)&dead_vnode_wanted);
2531 	}
2532 }
2533 
2534 
2535 /*
2536  * remove the vnode from appropriate free list.
2537  * called with vnode LOCKED and
2538  * the list lock held
2539  */
2540 static void
vnode_list_remove_locked(vnode_t vp)2541 vnode_list_remove_locked(vnode_t vp)
2542 {
2543 	if (VONLIST(vp)) {
2544 		/*
2545 		 * the v_listflag field is
2546 		 * protected by the vnode_list_lock
2547 		 */
2548 		if (vp->v_listflag & VLIST_RAGE) {
2549 			VREMRAGE("vnode_list_remove", vp);
2550 		} else if (vp->v_listflag & VLIST_DEAD) {
2551 			VREMDEAD("vnode_list_remove", vp);
2552 			wakeup_laundry_thread();
2553 		} else if (vp->v_listflag & VLIST_ASYNC_WORK) {
2554 			VREMASYNC_WORK("vnode_list_remove", vp);
2555 		} else {
2556 			VREMFREE("vnode_list_remove", vp);
2557 		}
2558 		if (vp->v_flag & VCANDEALLOC) {
2559 			os_atomic_inc(&busyvnodes, relaxed);
2560 		}
2561 	}
2562 }
2563 
2564 
2565 /*
2566  * remove the vnode from appropriate free list.
2567  * called with vnode LOCKED
2568  */
2569 static void
vnode_list_remove(vnode_t vp)2570 vnode_list_remove(vnode_t vp)
2571 {
2572 #if DIAGNOSTIC
2573 	lck_mtx_assert(&vp->v_lock, LCK_MTX_ASSERT_OWNED);
2574 #endif
2575 	/*
2576 	 * we want to avoid taking the list lock
2577 	 * in the case where we're not on the free
2578 	 * list... this will be true for most
2579 	 * directories and any currently in use files
2580 	 *
2581 	 * we're guaranteed that we can't go from
2582 	 * the not-on-list state to the on-list
2583 	 * state since we hold the vnode lock...
2584 	 * all calls to vnode_list_add are done
2585 	 * under the vnode lock... so we can
2586 	 * check for that condition (the prevelant one)
2587 	 * without taking the list lock
2588 	 */
2589 	if (VONLIST(vp)) {
2590 		vnode_list_lock();
2591 		/*
2592 		 * however, we're not guaranteed that
2593 		 * we won't go from the on-list state
2594 		 * to the not-on-list state until we
2595 		 * hold the vnode_list_lock... this
2596 		 * is due to "new_vnode" removing vnodes
2597 		 * from the free list uder the list_lock
2598 		 * w/o the vnode lock... so we need to
2599 		 * check again whether we're currently
2600 		 * on the free list
2601 		 */
2602 		vnode_list_remove_locked(vp);
2603 
2604 		vnode_list_unlock();
2605 	}
2606 }
2607 
2608 
2609 void
vnode_rele(vnode_t vp)2610 vnode_rele(vnode_t vp)
2611 {
2612 	vnode_rele_internal(vp, 0, 0, 0);
2613 }
2614 
2615 
2616 void
vnode_rele_ext(vnode_t vp,int fmode,int dont_reenter)2617 vnode_rele_ext(vnode_t vp, int fmode, int dont_reenter)
2618 {
2619 	vnode_rele_internal(vp, fmode, dont_reenter, 0);
2620 }
2621 
2622 
2623 void
vnode_rele_internal(vnode_t vp,int fmode,int dont_reenter,int locked)2624 vnode_rele_internal(vnode_t vp, int fmode, int dont_reenter, int locked)
2625 {
2626 	int32_t old_usecount;
2627 
2628 	if (!locked) {
2629 		vnode_hold(vp);
2630 		vnode_lock_spin(vp);
2631 	}
2632 #if DIAGNOSTIC
2633 	else {
2634 		lck_mtx_assert(&vp->v_lock, LCK_MTX_ASSERT_OWNED);
2635 	}
2636 #endif
2637 	/* Enable atomic ops on v_usecount without the vnode lock */
2638 	old_usecount = os_atomic_dec_orig(&vp->v_usecount, relaxed);
2639 	if (old_usecount < 1) {
2640 		/*
2641 		 * Because we allow atomic ops on usecount (in lookup only, under
2642 		 * specific conditions of already having a usecount) it is
2643 		 * possible that when the vnode is examined, its usecount is
2644 		 * different than what will be printed in this panic message.
2645 		 */
2646 		panic("vnode_rele_ext: vp %p usecount -ve : %d.  v_tag = %d, v_type = %d, v_flag = %x.",
2647 		    vp, old_usecount - 1, vp->v_tag, vp->v_type, vp->v_flag);
2648 	}
2649 
2650 	if (fmode & FWRITE) {
2651 		if (--vp->v_writecount < 0) {
2652 			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);
2653 		}
2654 	}
2655 	if (fmode & O_EVTONLY) {
2656 		if (--vp->v_kusecount < 0) {
2657 			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);
2658 		}
2659 	}
2660 	if (vp->v_kusecount > vp->v_usecount) {
2661 		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);
2662 	}
2663 
2664 	if ((vp->v_iocount > 0) || (vp->v_usecount > 0)) {
2665 		/*
2666 		 * vnode is still busy... if we're the last
2667 		 * usecount, mark for a future call to VNOP_INACTIVE
2668 		 * when the iocount finally drops to 0
2669 		 */
2670 		if (vp->v_usecount == 0) {
2671 			vp->v_lflag |= VL_NEEDINACTIVE;
2672 			vp->v_flag  &= ~(VNOCACHE_DATA | VRAOFF | VOPENEVT);
2673 		}
2674 		goto done;
2675 	}
2676 	vp->v_flag  &= ~(VNOCACHE_DATA | VRAOFF | VOPENEVT);
2677 
2678 	if (ISSET(vp->v_lflag, VL_TERMINATE | VL_DEAD) || dont_reenter) {
2679 		/*
2680 		 * vnode is being cleaned, or
2681 		 * we've requested that we don't reenter
2682 		 * the filesystem on this release...in
2683 		 * the latter case, we'll mark the vnode aged
2684 		 */
2685 		if (dont_reenter) {
2686 			if (!(vp->v_lflag & (VL_TERMINATE | VL_DEAD | VL_MARKTERM))) {
2687 				vp->v_lflag |= VL_NEEDINACTIVE;
2688 
2689 				if (vnode_on_reliable_media(vp) == FALSE || vp->v_flag & VISDIRTY) {
2690 					vnode_async_list_add(vp);
2691 					goto done;
2692 				}
2693 			}
2694 			vp->v_flag |= VAGE;
2695 		}
2696 		vnode_list_add(vp);
2697 
2698 		goto done;
2699 	}
2700 	/*
2701 	 * at this point both the iocount and usecount
2702 	 * are zero
2703 	 * pick up an iocount so that we can call
2704 	 * VNOP_INACTIVE with the vnode lock unheld
2705 	 */
2706 	vp->v_iocount++;
2707 #ifdef CONFIG_IOCOUNT_TRACE
2708 	record_vp(vp, 1);
2709 #endif
2710 	vp->v_lflag &= ~VL_NEEDINACTIVE;
2711 
2712 	if (UBCINFOEXISTS(vp)) {
2713 		ubc_cs_free_and_vnode_unlock(vp);
2714 	} else {
2715 		vnode_unlock(vp);
2716 	}
2717 
2718 	VNOP_INACTIVE(vp, vfs_context_current());
2719 
2720 	vnode_lock_spin(vp);
2721 
2722 	/*
2723 	 * because we dropped the vnode lock to call VNOP_INACTIVE
2724 	 * the state of the vnode may have changed... we may have
2725 	 * picked up an iocount, usecount or the MARKTERM may have
2726 	 * been set... we need to reevaluate the reference counts
2727 	 * to determine if we can call vnode_reclaim_internal at
2728 	 * this point... if the reference counts are up, we'll pick
2729 	 * up the MARKTERM state when they get subsequently dropped
2730 	 */
2731 	if ((vp->v_iocount == 1) && (vp->v_usecount == 0) &&
2732 	    ((vp->v_lflag & (VL_MARKTERM | VL_TERMINATE | VL_DEAD)) == VL_MARKTERM)) {
2733 		struct  uthread *ut;
2734 
2735 		ut = current_uthread();
2736 
2737 		if (ut->uu_defer_reclaims) {
2738 			vp->v_defer_reclaimlist = ut->uu_vreclaims;
2739 			ut->uu_vreclaims = vp;
2740 			goto done;
2741 		}
2742 		vnode_lock_convert(vp);
2743 		vnode_reclaim_internal(vp, 1, 1, 0);
2744 	}
2745 	vnode_dropiocount(vp);
2746 	vnode_list_add(vp);
2747 done:
2748 	if (vp->v_usecount == 0 && vp->v_type == VREG && !(vp->v_flag & VSYSTEM)) {
2749 		if (vp->v_ubcinfo) {
2750 			vnode_lock_convert(vp);
2751 			memory_object_mark_unused(vp->v_ubcinfo->ui_control, (vp->v_flag & VRAGE) == VRAGE);
2752 		}
2753 	}
2754 	if (!locked) {
2755 		vnode_drop_and_unlock(vp);
2756 	}
2757 	return;
2758 }
2759 
2760 /*
2761  * Remove any vnodes in the vnode table belonging to mount point mp.
2762  *
2763  * If MNT_NOFORCE is specified, there should not be any active ones,
2764  * return error if any are found (nb: this is a user error, not a
2765  * system error). If MNT_FORCE is specified, detach any active vnodes
2766  * that are found.
2767  */
2768 
2769 int
vflush(struct mount * mp,struct vnode * skipvp,int flags)2770 vflush(struct mount *mp, struct vnode *skipvp, int flags)
2771 {
2772 	struct vnode *vp;
2773 	int busy = 0;
2774 	int reclaimed = 0;
2775 	int retval;
2776 	unsigned int vid;
2777 	bool first_try = true;
2778 
2779 	/*
2780 	 * See comments in vnode_iterate() for the rationale for this lock
2781 	 */
2782 	mount_iterate_lock(mp);
2783 
2784 	mount_lock(mp);
2785 	vnode_iterate_setup(mp);
2786 	/*
2787 	 * On regular unmounts(not forced) do a
2788 	 * quick check for vnodes to be in use. This
2789 	 * preserves the caching of vnodes. automounter
2790 	 * tries unmounting every so often to see whether
2791 	 * it is still busy or not.
2792 	 */
2793 	if (((flags & FORCECLOSE) == 0) && ((mp->mnt_kern_flag & MNTK_UNMOUNT_PREFLIGHT) != 0)) {
2794 		if (vnode_umount_preflight(mp, skipvp, flags)) {
2795 			vnode_iterate_clear(mp);
2796 			mount_unlock(mp);
2797 			mount_iterate_unlock(mp);
2798 			return EBUSY;
2799 		}
2800 	}
2801 loop:
2802 	/* If it returns 0 then there is nothing to do */
2803 	retval = vnode_iterate_prepare(mp);
2804 
2805 	if (retval == 0) {
2806 		vnode_iterate_clear(mp);
2807 		mount_unlock(mp);
2808 		mount_iterate_unlock(mp);
2809 		return retval;
2810 	}
2811 
2812 	/* iterate over all the vnodes */
2813 	while (!TAILQ_EMPTY(&mp->mnt_workerqueue)) {
2814 		vp = TAILQ_FIRST(&mp->mnt_workerqueue);
2815 		TAILQ_REMOVE(&mp->mnt_workerqueue, vp, v_mntvnodes);
2816 		TAILQ_INSERT_TAIL(&mp->mnt_vnodelist, vp, v_mntvnodes);
2817 
2818 		if ((vp->v_mount != mp) || (vp == skipvp)) {
2819 			continue;
2820 		}
2821 		vid = vp->v_id;
2822 		mount_unlock(mp);
2823 
2824 		vnode_lock_spin(vp);
2825 
2826 		// If vnode is already terminating, wait for it...
2827 		while (vp->v_id == vid && ISSET(vp->v_lflag, VL_TERMINATE)) {
2828 			vp->v_lflag |= VL_TERMWANT;
2829 			msleep(&vp->v_lflag, &vp->v_lock, PVFS, "vflush", NULL);
2830 		}
2831 
2832 		if ((vp->v_id != vid) || ISSET(vp->v_lflag, VL_DEAD)) {
2833 			vnode_unlock(vp);
2834 			mount_lock(mp);
2835 			continue;
2836 		}
2837 
2838 		/*
2839 		 * If requested, skip over vnodes marked VSYSTEM.
2840 		 * Skip over all vnodes marked VNOFLUSH.
2841 		 */
2842 		if ((flags & SKIPSYSTEM) && ((vp->v_flag & VSYSTEM) ||
2843 		    (vp->v_flag & VNOFLUSH))) {
2844 			vnode_unlock(vp);
2845 			mount_lock(mp);
2846 			continue;
2847 		}
2848 		/*
2849 		 * If requested, skip over vnodes marked VSWAP.
2850 		 */
2851 		if ((flags & SKIPSWAP) && (vp->v_flag & VSWAP)) {
2852 			vnode_unlock(vp);
2853 			mount_lock(mp);
2854 			continue;
2855 		}
2856 		/*
2857 		 * If requested, skip over vnodes marked VROOT.
2858 		 */
2859 		if ((flags & SKIPROOT) && (vp->v_flag & VROOT)) {
2860 			vnode_unlock(vp);
2861 			mount_lock(mp);
2862 			continue;
2863 		}
2864 		/*
2865 		 * If WRITECLOSE is set, only flush out regular file
2866 		 * vnodes open for writing.
2867 		 */
2868 		if ((flags & WRITECLOSE) &&
2869 		    (vp->v_writecount == 0 || vp->v_type != VREG)) {
2870 			vnode_unlock(vp);
2871 			mount_lock(mp);
2872 			continue;
2873 		}
2874 		/*
2875 		 * If the real usecount is 0, all we need to do is clear
2876 		 * out the vnode data structures and we are done.
2877 		 */
2878 		if (((vp->v_usecount == 0) ||
2879 		    ((vp->v_usecount - vp->v_kusecount) == 0))) {
2880 			vnode_lock_convert(vp);
2881 			vnode_hold(vp);
2882 			vp->v_iocount++;        /* so that drain waits for * other iocounts */
2883 #ifdef CONFIG_IOCOUNT_TRACE
2884 			record_vp(vp, 1);
2885 #endif
2886 			vnode_reclaim_internal(vp, 1, 1, 0);
2887 			vnode_dropiocount(vp);
2888 			vnode_list_add(vp);
2889 			vnode_drop_and_unlock(vp);
2890 
2891 			reclaimed++;
2892 			mount_lock(mp);
2893 			continue;
2894 		}
2895 		/*
2896 		 * If FORCECLOSE is set, forcibly close the vnode.
2897 		 * For block or character devices, revert to an
2898 		 * anonymous device. For all other files, just kill them.
2899 		 */
2900 		if (flags & FORCECLOSE) {
2901 			vnode_lock_convert(vp);
2902 
2903 			if (vp->v_type != VBLK && vp->v_type != VCHR) {
2904 				vp->v_iocount++;        /* so that drain waits * for other iocounts */
2905 				vnode_hold(vp);
2906 #ifdef CONFIG_IOCOUNT_TRACE
2907 				record_vp(vp, 1);
2908 #endif
2909 				vnode_abort_advlocks(vp);
2910 				vnode_reclaim_internal(vp, 1, 1, 0);
2911 				vnode_dropiocount(vp);
2912 				vnode_list_add(vp);
2913 				vnode_drop_and_unlock(vp);
2914 			} else {
2915 				vnode_hold(vp);
2916 				vp->v_lflag |= VL_OPSCHANGE;
2917 				vclean(vp, 0);
2918 				vp->v_lflag &= ~VL_DEAD;
2919 				vp->v_op = spec_vnodeop_p;
2920 				vp->v_flag |= VDEVFLUSH;
2921 				vnode_drop_and_unlock(vp);
2922 				wakeup(&vp->v_lflag); /* chkvnlock is waitng for VL_DEAD to get unset */
2923 			}
2924 			mount_lock(mp);
2925 			continue;
2926 		}
2927 
2928 		/* log vnodes blocking unforced unmounts */
2929 		if (print_busy_vnodes && first_try && ((flags & FORCECLOSE) == 0)) {
2930 			vprint("vflush - busy vnode", vp);
2931 		}
2932 
2933 		vnode_unlock(vp);
2934 		mount_lock(mp);
2935 		busy++;
2936 	}
2937 
2938 	/* At this point the worker queue is completed */
2939 	if (busy && ((flags & FORCECLOSE) == 0) && reclaimed) {
2940 		busy = 0;
2941 		reclaimed = 0;
2942 		(void)vnode_iterate_reloadq(mp);
2943 		first_try = false;
2944 		/* returned with mount lock held */
2945 		goto loop;
2946 	}
2947 
2948 	/* if new vnodes were created in between retry the reclaim */
2949 	if (vnode_iterate_reloadq(mp) != 0) {
2950 		if (!(busy && ((flags & FORCECLOSE) == 0))) {
2951 			first_try = false;
2952 			goto loop;
2953 		}
2954 	}
2955 	vnode_iterate_clear(mp);
2956 	mount_unlock(mp);
2957 	mount_iterate_unlock(mp);
2958 
2959 	if (busy && ((flags & FORCECLOSE) == 0)) {
2960 		return EBUSY;
2961 	}
2962 	return 0;
2963 }
2964 
2965 long num_recycledvnodes = 0;
2966 /*
2967  * Disassociate the underlying file system from a vnode.
2968  * The vnode lock is held on entry.
2969  */
2970 static void
vclean(vnode_t vp,int flags)2971 vclean(vnode_t vp, int flags)
2972 {
2973 	vfs_context_t ctx = vfs_context_current();
2974 	int active;
2975 	int need_inactive;
2976 	int already_terminating;
2977 	int clflags = 0;
2978 #if NAMEDSTREAMS
2979 	int is_namedstream;
2980 #endif
2981 
2982 	/*
2983 	 * Check to see if the vnode is in use.
2984 	 * If so we have to reference it before we clean it out
2985 	 * so that its count cannot fall to zero and generate a
2986 	 * race against ourselves to recycle it.
2987 	 */
2988 	active = vp->v_usecount;
2989 
2990 	/*
2991 	 * just in case we missed sending a needed
2992 	 * VNOP_INACTIVE, we'll do it now
2993 	 */
2994 	need_inactive = (vp->v_lflag & VL_NEEDINACTIVE);
2995 
2996 	vp->v_lflag &= ~VL_NEEDINACTIVE;
2997 
2998 	/*
2999 	 * Prevent the vnode from being recycled or
3000 	 * brought into use while we clean it out.
3001 	 */
3002 	already_terminating = (vp->v_lflag & VL_TERMINATE);
3003 
3004 	vp->v_lflag |= VL_TERMINATE;
3005 
3006 #if NAMEDSTREAMS
3007 	is_namedstream = vnode_isnamedstream(vp);
3008 #endif
3009 
3010 	vnode_unlock(vp);
3011 
3012 	OSAddAtomicLong(1, &num_recycledvnodes);
3013 
3014 	if (flags & DOCLOSE) {
3015 		clflags |= IO_NDELAY;
3016 	}
3017 	if (flags & REVOKEALL) {
3018 		clflags |= IO_REVOKE;
3019 	}
3020 
3021 #if CONFIG_MACF
3022 	if (vp->v_mount) {
3023 		/*
3024 		 * It is possible for bdevvp vnodes to not have a mount
3025 		 * pointer. It's fine to let it get reclaimed without
3026 		 * notifying.
3027 		 */
3028 		mac_vnode_notify_reclaim(vp);
3029 	}
3030 #endif
3031 
3032 	if (active && (flags & DOCLOSE)) {
3033 		VNOP_CLOSE(vp, clflags, ctx);
3034 	}
3035 
3036 	/*
3037 	 * Clean out any buffers associated with the vnode.
3038 	 */
3039 	if (flags & DOCLOSE) {
3040 		if (vp->v_tag == VT_NFS) {
3041 			nfs_vinvalbuf(vp, V_SAVE, ctx, 0);
3042 		} else {
3043 			VNOP_FSYNC(vp, MNT_WAIT, ctx);
3044 
3045 			/*
3046 			 * If the vnode is still in use (by the journal for
3047 			 * example) we don't want to invalidate locked buffers
3048 			 * here.  In that case, either the journal will tidy them
3049 			 * up, or we will deal with it when the usecount is
3050 			 * finally released in vnode_rele_internal.
3051 			 */
3052 			buf_invalidateblks(vp, BUF_WRITE_DATA | (active ? 0 : BUF_INVALIDATE_LOCKED), 0, 0);
3053 		}
3054 		if (UBCINFOEXISTS(vp)) {
3055 			/*
3056 			 * Clean the pages in VM.
3057 			 */
3058 			(void)ubc_msync(vp, (off_t)0, ubc_getsize(vp), NULL, UBC_PUSHALL | UBC_INVALIDATE | UBC_SYNC);
3059 		}
3060 	}
3061 	if (active || need_inactive) {
3062 		VNOP_INACTIVE(vp, ctx);
3063 	}
3064 
3065 #if NAMEDSTREAMS
3066 	if ((is_namedstream != 0) && (vp->v_parent != NULLVP)) {
3067 		vnode_t pvp = vp->v_parent;
3068 
3069 		/* Delete the shadow stream file before we reclaim its vnode */
3070 		if (vnode_isshadow(vp)) {
3071 			vnode_relenamedstream(pvp, vp);
3072 		}
3073 
3074 		/*
3075 		 * No more streams associated with the parent.  We
3076 		 * have a ref on it, so its identity is stable.
3077 		 * If the parent is on an opaque volume, then we need to know
3078 		 * whether it has associated named streams.
3079 		 */
3080 		if (vfs_authopaque(pvp->v_mount)) {
3081 			vnode_lock_spin(pvp);
3082 			pvp->v_lflag &= ~VL_HASSTREAMS;
3083 			vnode_unlock(pvp);
3084 		}
3085 	}
3086 #endif
3087 
3088 	/*
3089 	 * Destroy ubc named reference
3090 	 * cluster_release is done on this path
3091 	 * along with dropping the reference on the ucred
3092 	 * (and in the case of forced unmount of an mmap-ed file,
3093 	 * the ubc reference on the vnode is dropped here too).
3094 	 */
3095 	ubc_destroy_named(vp);
3096 
3097 #if CONFIG_TRIGGERS
3098 	/*
3099 	 * cleanup trigger info from vnode (if any)
3100 	 */
3101 	if (vp->v_resolve) {
3102 		vnode_resolver_detach(vp);
3103 	}
3104 #endif
3105 
3106 #if CONFIG_IO_COMPRESSION_STATS
3107 	if ((vp->io_compression_stats)) {
3108 		vnode_iocs_record_and_free(vp);
3109 	}
3110 #endif /* CONFIG_IO_COMPRESSION_STATS */
3111 
3112 	/*
3113 	 * Reclaim the vnode.
3114 	 */
3115 	if (VNOP_RECLAIM(vp, ctx)) {
3116 		panic("vclean: cannot reclaim");
3117 	}
3118 
3119 	// make sure the name & parent ptrs get cleaned out!
3120 	vnode_update_identity(vp, NULLVP, NULL, 0, 0, VNODE_UPDATE_PARENT | VNODE_UPDATE_NAME | VNODE_UPDATE_PURGE | VNODE_UPDATE_PURGEFIRMLINK);
3121 
3122 	vnode_lock(vp);
3123 
3124 	/*
3125 	 * Remove the vnode from any mount list it might be on.  It is not
3126 	 * safe to do this any earlier because unmount needs to wait for
3127 	 * any vnodes to terminate and it cannot do that if it cannot find
3128 	 * them.
3129 	 */
3130 	insmntque(vp, (struct mount *)0);
3131 
3132 	vp->v_lflag |= VL_DEAD;
3133 	vp->v_mount = dead_mountp;
3134 	vp->v_op = dead_vnodeop_p;
3135 	vp->v_tag = VT_NON;
3136 	vp->v_data = NULL;
3137 
3138 	vp->v_flag &= ~VISDIRTY;
3139 
3140 	if (already_terminating == 0) {
3141 		vp->v_lflag &= ~VL_TERMINATE;
3142 		/*
3143 		 * Done with purge, notify sleepers of the grim news.
3144 		 */
3145 		if (vp->v_lflag & VL_TERMWANT) {
3146 			vp->v_lflag &= ~VL_TERMWANT;
3147 			wakeup(&vp->v_lflag);
3148 		}
3149 	}
3150 }
3151 
3152 /*
3153  * Eliminate all activity associated with  the requested vnode
3154  * and with all vnodes aliased to the requested vnode.
3155  */
3156 int
3157 #if DIAGNOSTIC
vn_revoke(vnode_t vp,int flags,__unused vfs_context_t a_context)3158 vn_revoke(vnode_t vp, int flags, __unused vfs_context_t a_context)
3159 #else
3160 vn_revoke(vnode_t vp, __unused int flags, __unused vfs_context_t a_context)
3161 #endif
3162 {
3163 	struct vnode *vq;
3164 	int vid;
3165 
3166 #if DIAGNOSTIC
3167 	if ((flags & REVOKEALL) == 0) {
3168 		panic("vnop_revoke");
3169 	}
3170 #endif
3171 
3172 	if (vnode_isaliased(vp)) {
3173 		/*
3174 		 * If a vgone (or vclean) is already in progress,
3175 		 * return an immediate error
3176 		 */
3177 		if (vp->v_lflag & VL_TERMINATE) {
3178 			return ENOENT;
3179 		}
3180 
3181 		/*
3182 		 * Ensure that vp will not be vgone'd while we
3183 		 * are eliminating its aliases.
3184 		 */
3185 		SPECHASH_LOCK();
3186 		while ((vp->v_specflags & SI_ALIASED)) {
3187 			for (vq = *vp->v_hashchain; vq; vq = vq->v_specnext) {
3188 				if (vq->v_rdev != vp->v_rdev ||
3189 				    vq->v_type != vp->v_type || vp == vq) {
3190 					continue;
3191 				}
3192 				vid = vq->v_id;
3193 				vnode_hold(vq);
3194 				SPECHASH_UNLOCK();
3195 				if (vnode_getwithvid(vq, vid)) {
3196 					vq = vnode_drop(vq);
3197 					SPECHASH_LOCK();
3198 					break;
3199 				}
3200 				vnode_lock(vq);
3201 				if (!(vq->v_lflag & VL_TERMINATE)) {
3202 					vnode_reclaim_internal(vq, 1, 1, 0);
3203 				}
3204 				vnode_put_locked(vq);
3205 				vq = vnode_drop_and_unlock(vq);
3206 				SPECHASH_LOCK();
3207 				break;
3208 			}
3209 		}
3210 		SPECHASH_UNLOCK();
3211 	}
3212 	vnode_lock(vp);
3213 	if (vp->v_lflag & VL_TERMINATE) {
3214 		vnode_unlock(vp);
3215 		return ENOENT;
3216 	}
3217 	vnode_reclaim_internal(vp, 1, 0, REVOKEALL);
3218 	vnode_unlock(vp);
3219 
3220 	return 0;
3221 }
3222 
3223 /*
3224  * Recycle an unused vnode to the front of the free list.
3225  * Release the passed interlock if the vnode will be recycled.
3226  */
3227 int
vnode_recycle(struct vnode * vp)3228 vnode_recycle(struct vnode *vp)
3229 {
3230 	vnode_lock_spin(vp);
3231 
3232 	if (vp->v_iocount || vp->v_usecount) {
3233 		vp->v_lflag |= VL_MARKTERM;
3234 		vnode_unlock(vp);
3235 		return 0;
3236 	}
3237 	vnode_lock_convert(vp);
3238 	vnode_hold(vp);
3239 	vnode_reclaim_internal(vp, 1, 0, 0);
3240 
3241 	vnode_drop_and_unlock(vp);
3242 
3243 	return 1;
3244 }
3245 
3246 static int
vnode_reload(vnode_t vp)3247 vnode_reload(vnode_t vp)
3248 {
3249 	vnode_lock_spin(vp);
3250 
3251 	if ((vp->v_iocount > 1) || vp->v_usecount) {
3252 		vnode_unlock(vp);
3253 		return 0;
3254 	}
3255 	if (vp->v_iocount <= 0) {
3256 		panic("vnode_reload with no iocount %d", vp->v_iocount);
3257 	}
3258 
3259 	/* mark for release when iocount is dopped */
3260 	vp->v_lflag |= VL_MARKTERM;
3261 	vnode_unlock(vp);
3262 
3263 	return 1;
3264 }
3265 
3266 
3267 static void
vgone(vnode_t vp,int flags)3268 vgone(vnode_t vp, int flags)
3269 {
3270 	struct vnode *vq;
3271 	struct vnode *vx;
3272 
3273 	/*
3274 	 * Clean out the filesystem specific data.
3275 	 * vclean also takes care of removing the
3276 	 * vnode from any mount list it might be on
3277 	 */
3278 	vclean(vp, flags | DOCLOSE);
3279 
3280 	/*
3281 	 * If special device, remove it from special device alias list
3282 	 * if it is on one.
3283 	 */
3284 	if ((vp->v_type == VBLK || vp->v_type == VCHR) && vp->v_specinfo != 0) {
3285 		SPECHASH_LOCK();
3286 		if (*vp->v_hashchain == vp) {
3287 			*vp->v_hashchain = vp->v_specnext;
3288 		} else {
3289 			for (vq = *vp->v_hashchain; vq; vq = vq->v_specnext) {
3290 				if (vq->v_specnext != vp) {
3291 					continue;
3292 				}
3293 				vq->v_specnext = vp->v_specnext;
3294 				break;
3295 			}
3296 			if (vq == NULL) {
3297 				panic("missing bdev");
3298 			}
3299 		}
3300 		if (vp->v_specflags & SI_ALIASED) {
3301 			vx = NULL;
3302 			for (vq = *vp->v_hashchain; vq; vq = vq->v_specnext) {
3303 				if (vq->v_rdev != vp->v_rdev ||
3304 				    vq->v_type != vp->v_type) {
3305 					continue;
3306 				}
3307 				if (vx) {
3308 					break;
3309 				}
3310 				vx = vq;
3311 			}
3312 			if (vx == NULL) {
3313 				panic("missing alias");
3314 			}
3315 			if (vq == NULL) {
3316 				vx->v_specflags &= ~SI_ALIASED;
3317 			}
3318 			vp->v_specflags &= ~SI_ALIASED;
3319 		}
3320 		SPECHASH_UNLOCK();
3321 		{
3322 			struct specinfo *tmp = vp->v_specinfo;
3323 			vp->v_specinfo = NULL;
3324 			zfree(specinfo_zone, tmp);
3325 		}
3326 	}
3327 }
3328 
3329 /*
3330  * Lookup a vnode by device number.
3331  */
3332 int
check_mountedon(dev_t dev,enum vtype type,int * errorp)3333 check_mountedon(dev_t dev, enum vtype type, int  *errorp)
3334 {
3335 	vnode_t vp;
3336 	int rc = 0;
3337 	int vid;
3338 
3339 loop:
3340 	SPECHASH_LOCK();
3341 	for (vp = speclisth[SPECHASH(dev)]; vp; vp = vp->v_specnext) {
3342 		if (dev != vp->v_rdev || type != vp->v_type) {
3343 			continue;
3344 		}
3345 		vid = vp->v_id;
3346 		vnode_hold(vp);
3347 		SPECHASH_UNLOCK();
3348 		if (vnode_getwithvid(vp, vid)) {
3349 			vnode_drop(vp);
3350 			goto loop;
3351 		}
3352 		vnode_drop(vp);
3353 		vnode_lock_spin(vp);
3354 		if ((vp->v_usecount > 0) || (vp->v_iocount > 1)) {
3355 			vnode_unlock(vp);
3356 			if ((*errorp = vfs_mountedon(vp)) != 0) {
3357 				rc = 1;
3358 			}
3359 		} else {
3360 			vnode_unlock(vp);
3361 		}
3362 		vnode_put(vp);
3363 		return rc;
3364 	}
3365 	SPECHASH_UNLOCK();
3366 	return 0;
3367 }
3368 
3369 /*
3370  * Calculate the total number of references to a special device.
3371  */
3372 int
vcount(vnode_t vp)3373 vcount(vnode_t vp)
3374 {
3375 	vnode_t vq, vnext;
3376 	int count;
3377 	int vid;
3378 
3379 	if (!vnode_isspec(vp)) {
3380 		return vp->v_usecount - vp->v_kusecount;
3381 	}
3382 
3383 loop:
3384 	if (!vnode_isaliased(vp)) {
3385 		return vp->v_specinfo->si_opencount;
3386 	}
3387 	count = 0;
3388 
3389 	SPECHASH_LOCK();
3390 	/*
3391 	 * Grab first vnode and its vid.
3392 	 */
3393 	vq = *vp->v_hashchain;
3394 	if (vq) {
3395 		vid = vq->v_id;
3396 		vnode_hold(vq);
3397 	} else {
3398 		vid = 0;
3399 	}
3400 	SPECHASH_UNLOCK();
3401 
3402 	while (vq) {
3403 		/*
3404 		 * Attempt to get the vnode outside the SPECHASH lock.
3405 		 */
3406 		if (vnode_getwithvid(vq, vid)) {
3407 			vnode_drop(vq);
3408 			goto loop;
3409 		}
3410 		vnode_drop(vq);
3411 		vnode_lock(vq);
3412 
3413 		if (vq->v_rdev == vp->v_rdev && vq->v_type == vp->v_type) {
3414 			if ((vq->v_usecount == 0) && (vq->v_iocount == 1) && vq != vp) {
3415 				/*
3416 				 * Alias, but not in use, so flush it out.
3417 				 */
3418 				vnode_hold(vq);
3419 				vnode_reclaim_internal(vq, 1, 1, 0);
3420 				vnode_put_locked(vq);
3421 				vnode_drop_and_unlock(vq);
3422 				goto loop;
3423 			}
3424 			count += vq->v_specinfo->si_opencount;
3425 		}
3426 		vnode_unlock(vq);
3427 
3428 		SPECHASH_LOCK();
3429 		/*
3430 		 * must do this with the reference still held on 'vq'
3431 		 * so that it can't be destroyed while we're poking
3432 		 * through v_specnext
3433 		 */
3434 		vnext = vq->v_specnext;
3435 		if (vnext) {
3436 			vid = vnext->v_id;
3437 			vnode_hold(vnext);
3438 		} else {
3439 			vid = 0;
3440 		}
3441 		SPECHASH_UNLOCK();
3442 
3443 		vnode_put(vq);
3444 
3445 		vq = vnext;
3446 	}
3447 
3448 	return count;
3449 }
3450 
3451 int     prtactive = 0;          /* 1 => print out reclaim of active vnodes */
3452 
3453 /*
3454  * Print out a description of a vnode.
3455  */
3456 static const char *typename[] =
3457 { "VNON", "VREG", "VDIR", "VBLK", "VCHR", "VLNK", "VSOCK", "VFIFO", "VBAD" };
3458 
3459 void
vprint(const char * label,struct vnode * vp)3460 vprint(const char *label, struct vnode *vp)
3461 {
3462 	char sbuf[64];
3463 
3464 	if (label != NULL) {
3465 		printf("%s: ", label);
3466 	}
3467 	printf("name %s type %s, usecount %d, writecount %d\n",
3468 	    vp->v_name, typename[vp->v_type],
3469 	    vp->v_usecount, vp->v_writecount);
3470 	sbuf[0] = '\0';
3471 	if (vp->v_flag & VROOT) {
3472 		strlcat(sbuf, "|VROOT", sizeof(sbuf));
3473 	}
3474 	if (vp->v_flag & VTEXT) {
3475 		strlcat(sbuf, "|VTEXT", sizeof(sbuf));
3476 	}
3477 	if (vp->v_flag & VSYSTEM) {
3478 		strlcat(sbuf, "|VSYSTEM", sizeof(sbuf));
3479 	}
3480 	if (vp->v_flag & VNOFLUSH) {
3481 		strlcat(sbuf, "|VNOFLUSH", sizeof(sbuf));
3482 	}
3483 	if (vp->v_flag & VBWAIT) {
3484 		strlcat(sbuf, "|VBWAIT", sizeof(sbuf));
3485 	}
3486 	if (vnode_isaliased(vp)) {
3487 		strlcat(sbuf, "|VALIASED", sizeof(sbuf));
3488 	}
3489 	if (sbuf[0] != '\0') {
3490 		printf("vnode flags (%s\n", &sbuf[1]);
3491 	}
3492 }
3493 
3494 static int
vn_getpath_flags_to_buildpath_flags(int flags)3495 vn_getpath_flags_to_buildpath_flags(int flags)
3496 {
3497 	int bpflags = (flags & VN_GETPATH_FSENTER) ? 0 : BUILDPATH_NO_FS_ENTER;
3498 
3499 	if (flags && (flags != VN_GETPATH_FSENTER)) {
3500 		if (flags & VN_GETPATH_NO_FIRMLINK) {
3501 			bpflags |= BUILDPATH_NO_FIRMLINK;
3502 		}
3503 		if (flags & VN_GETPATH_VOLUME_RELATIVE) {
3504 			bpflags |= (BUILDPATH_VOLUME_RELATIVE |
3505 			    BUILDPATH_NO_FIRMLINK);
3506 		}
3507 		if (flags & VN_GETPATH_NO_PROCROOT) {
3508 			bpflags |= BUILDPATH_NO_PROCROOT;
3509 		}
3510 		if (flags & VN_GETPATH_CHECK_MOVED) {
3511 			bpflags |= BUILDPATH_CHECK_MOVED;
3512 		}
3513 	}
3514 
3515 	return bpflags;
3516 }
3517 
3518 int
vn_getpath_ext_with_mntlen(struct vnode * vp,struct vnode * dvp,char * pathbuf,size_t * len,size_t * mntlen,int flags)3519 vn_getpath_ext_with_mntlen(struct vnode *vp, struct vnode *dvp, char *pathbuf,
3520     size_t *len, size_t *mntlen, int flags)
3521 {
3522 	int bpflags = vn_getpath_flags_to_buildpath_flags(flags);
3523 	int local_len;
3524 	int error;
3525 
3526 	if (*len > INT_MAX) {
3527 		return EINVAL;
3528 	}
3529 
3530 	local_len = *len;
3531 
3532 	error = build_path_with_parent(vp, dvp, pathbuf, local_len, &local_len,
3533 	    mntlen, bpflags, vfs_context_current());
3534 
3535 	if (local_len >= 0 && local_len <= (int)*len) {
3536 		*len = (size_t)local_len;
3537 	}
3538 
3539 	return error;
3540 }
3541 
3542 int
vn_getpath_ext(struct vnode * vp,struct vnode * dvp,char * pathbuf,size_t * len,int flags)3543 vn_getpath_ext(struct vnode *vp, struct vnode *dvp, char *pathbuf, size_t *len,
3544     int flags)
3545 {
3546 	return vn_getpath_ext_with_mntlen(vp, dvp, pathbuf, len, NULL, flags);
3547 }
3548 
3549 /*
3550  * Wrapper around vn_getpath_ext() that takes care of the int * <-> size_t *
3551  * conversion for the legacy KPIs.
3552  */
3553 static int
vn_getpath_ext_int(struct vnode * vp,struct vnode * dvp,char * pathbuf,int * len,int flags)3554 vn_getpath_ext_int(struct vnode *vp, struct vnode *dvp, char *pathbuf,
3555     int *len, int flags)
3556 {
3557 	size_t slen = *len;
3558 	int error;
3559 
3560 	if (*len < 0) {
3561 		return EINVAL;
3562 	}
3563 
3564 	error = vn_getpath_ext(vp, dvp, pathbuf, &slen, flags);
3565 
3566 	if (slen <= INT_MAX) {
3567 		*len = (int)slen;
3568 	}
3569 
3570 	return error;
3571 }
3572 
3573 int
vn_getpath(struct vnode * vp,char * pathbuf,int * len)3574 vn_getpath(struct vnode *vp, char *pathbuf, int *len)
3575 {
3576 	return vn_getpath_ext_int(vp, NULL, pathbuf, len, 0);
3577 }
3578 
3579 int
vn_getpath_fsenter(struct vnode * vp,char * pathbuf,int * len)3580 vn_getpath_fsenter(struct vnode *vp, char *pathbuf, int *len)
3581 {
3582 	return vn_getpath_ext_int(vp, NULL, pathbuf, len, VN_GETPATH_FSENTER);
3583 }
3584 
3585 /*
3586  * vn_getpath_fsenter_with_parent will reenter the file system to fine the path of the
3587  * vnode.  It requires that there are IO counts on both the vnode and the directory vnode.
3588  *
3589  * vn_getpath_fsenter is called by MAC hooks to authorize operations for every thing, but
3590  * unlink, rmdir and rename. For these operation the MAC hook  calls vn_getpath. This presents
3591  * problems where if the path can not be found from the name cache, those operations can
3592  * erroneously fail with EPERM even though the call should succeed. When removing or moving
3593  * file system objects with operations such as unlink or rename, those operations need to
3594  * take IO counts on the target and containing directory. Calling vn_getpath_fsenter from a
3595  * MAC hook from these operations during forced unmount operations can lead to dead
3596  * lock. This happens when the operation starts, IO counts are taken on the containing
3597  * directories and targets. Before the MAC hook is called a forced unmount from another
3598  * thread takes place and blocks on the on going operation's directory vnode in vdrain.
3599  * After which, the MAC hook gets called and calls vn_getpath_fsenter.  vn_getpath_fsenter
3600  * is called with the understanding that there is an IO count on the target. If in
3601  * build_path the directory vnode is no longer in the cache, then the parent object id via
3602  * vnode_getattr from the target is obtain and used to call VFS_VGET to get the parent
3603  * vnode. The file system's VFS_VGET then looks up by inode in its hash and tries to get
3604  * an IO count. But VFS_VGET "sees" the directory vnode is in vdrain and can block
3605  * depending on which version and how it calls the vnode_get family of interfaces.
3606  *
3607  * N.B.  A reasonable interface to use is vnode_getwithvid. This interface was modified to
3608  * call vnode_getiocount with VNODE_DRAINO, so it will happily get an IO count and not
3609  * cause issues, but there is no guarantee that all or any file systems are doing that.
3610  *
3611  * vn_getpath_fsenter_with_parent can enter the file system safely since there is a known
3612  * IO count on the directory vnode by calling build_path_with_parent.
3613  */
3614 
3615 int
vn_getpath_fsenter_with_parent(struct vnode * dvp,struct vnode * vp,char * pathbuf,int * len)3616 vn_getpath_fsenter_with_parent(struct vnode *dvp, struct vnode *vp, char *pathbuf, int *len)
3617 {
3618 	return build_path_with_parent(vp, dvp, pathbuf, *len, len, NULL, 0, vfs_context_current());
3619 }
3620 
3621 int
vn_getpath_no_firmlink(struct vnode * vp,char * pathbuf,int * len)3622 vn_getpath_no_firmlink(struct vnode *vp, char *pathbuf, int *len)
3623 {
3624 	return vn_getpath_ext_int(vp, NULLVP, pathbuf, len,
3625 	           VN_GETPATH_NO_FIRMLINK);
3626 }
3627 
3628 int
vn_getcdhash(struct vnode * vp,off_t offset,unsigned char * cdhash)3629 vn_getcdhash(struct vnode *vp, off_t offset, unsigned char *cdhash)
3630 {
3631 	return ubc_cs_getcdhash(vp, offset, cdhash);
3632 }
3633 
3634 
3635 static char *extension_table = NULL;
3636 static int   nexts;
3637 static int   max_ext_width;
3638 
3639 static int
extension_cmp(const void * a,const void * b)3640 extension_cmp(const void *a, const void *b)
3641 {
3642 	return (int)(strlen((const char *)a) - strlen((const char *)b));
3643 }
3644 
3645 
3646 //
3647 // This is the api LaunchServices uses to inform the kernel
3648 // the list of package extensions to ignore.
3649 //
3650 // Internally we keep the list sorted by the length of the
3651 // the extension (from longest to shortest).  We sort the
3652 // list of extensions so that we can speed up our searches
3653 // when comparing file names -- we only compare extensions
3654 // that could possibly fit into the file name, not all of
3655 // them (i.e. a short 8 character name can't have an 8
3656 // character extension).
3657 //
3658 extern lck_mtx_t pkg_extensions_lck;
3659 
3660 __private_extern__ int
set_package_extensions_table(user_addr_t data,int nentries,int maxwidth)3661 set_package_extensions_table(user_addr_t data, int nentries, int maxwidth)
3662 {
3663 	char *new_exts, *old_exts;
3664 	int old_nentries = 0, old_maxwidth = 0;
3665 	int error;
3666 
3667 	if (nentries <= 0 || nentries > 1024 || maxwidth <= 0 || maxwidth > 255) {
3668 		return EINVAL;
3669 	}
3670 
3671 
3672 	// allocate one byte extra so we can guarantee null termination
3673 	new_exts = kalloc_data((nentries * maxwidth) + 1, Z_WAITOK);
3674 	if (new_exts == NULL) {
3675 		return ENOMEM;
3676 	}
3677 
3678 	error = copyin(data, new_exts, nentries * maxwidth);
3679 	if (error) {
3680 		kfree_data(new_exts, (nentries * maxwidth) + 1);
3681 		return error;
3682 	}
3683 
3684 	new_exts[(nentries * maxwidth)] = '\0'; // guarantee null termination of the block
3685 
3686 	qsort(new_exts, nentries, maxwidth, extension_cmp);
3687 
3688 	lck_mtx_lock(&pkg_extensions_lck);
3689 
3690 	old_exts        = extension_table;
3691 	old_nentries    = nexts;
3692 	old_maxwidth    = max_ext_width;
3693 	extension_table = new_exts;
3694 	nexts           = nentries;
3695 	max_ext_width   = maxwidth;
3696 
3697 	lck_mtx_unlock(&pkg_extensions_lck);
3698 
3699 	kfree_data(old_exts, (old_nentries * old_maxwidth) + 1);
3700 
3701 	return 0;
3702 }
3703 
3704 
3705 int
is_package_name(const char * name,int len)3706 is_package_name(const char *name, int len)
3707 {
3708 	int i;
3709 	size_t extlen;
3710 	const char *ptr, *name_ext;
3711 
3712 	// if the name is less than 3 bytes it can't be of the
3713 	// form A.B and if it begins with a "." then it is also
3714 	// not a package.
3715 	if (len <= 3 || name[0] == '.') {
3716 		return 0;
3717 	}
3718 
3719 	name_ext = NULL;
3720 	for (ptr = name; *ptr != '\0'; ptr++) {
3721 		if (*ptr == '.') {
3722 			name_ext = ptr;
3723 		}
3724 	}
3725 
3726 	// if there is no "." extension, it can't match
3727 	if (name_ext == NULL) {
3728 		return 0;
3729 	}
3730 
3731 	// advance over the "."
3732 	name_ext++;
3733 
3734 	lck_mtx_lock(&pkg_extensions_lck);
3735 
3736 	// now iterate over all the extensions to see if any match
3737 	ptr = &extension_table[0];
3738 	for (i = 0; i < nexts; i++, ptr += max_ext_width) {
3739 		extlen = strlen(ptr);
3740 		if (strncasecmp(name_ext, ptr, extlen) == 0 && name_ext[extlen] == '\0') {
3741 			// aha, a match!
3742 			lck_mtx_unlock(&pkg_extensions_lck);
3743 			return 1;
3744 		}
3745 	}
3746 
3747 	lck_mtx_unlock(&pkg_extensions_lck);
3748 
3749 	// if we get here, no extension matched
3750 	return 0;
3751 }
3752 
3753 int
vn_path_package_check(__unused vnode_t vp,char * path,int pathlen,int * component)3754 vn_path_package_check(__unused vnode_t vp, char *path, int pathlen, int *component)
3755 {
3756 	char *ptr, *end;
3757 	int comp = 0;
3758 
3759 	if (pathlen < 0) {
3760 		return EINVAL;
3761 	}
3762 
3763 	*component = -1;
3764 	if (*path != '/') {
3765 		return EINVAL;
3766 	}
3767 
3768 	end = path + 1;
3769 	while (end < path + pathlen && *end != '\0') {
3770 		while (end < path + pathlen && *end == '/' && *end != '\0') {
3771 			end++;
3772 		}
3773 
3774 		ptr = end;
3775 
3776 		while (end < path + pathlen && *end != '/' && *end != '\0') {
3777 			end++;
3778 		}
3779 
3780 		if (end > path + pathlen) {
3781 			// hmm, string wasn't null terminated
3782 			return EINVAL;
3783 		}
3784 
3785 		*end = '\0';
3786 		if (is_package_name(ptr, (int)(end - ptr))) {
3787 			*component = comp;
3788 			break;
3789 		}
3790 
3791 		end++;
3792 		comp++;
3793 	}
3794 
3795 	return 0;
3796 }
3797 
3798 /*
3799  * Determine if a name is inappropriate for a searchfs query.
3800  * This list consists of /System currently.
3801  */
3802 
3803 int
vn_searchfs_inappropriate_name(const char * name,int len)3804 vn_searchfs_inappropriate_name(const char *name, int len)
3805 {
3806 	const char *bad_names[] = { "System" };
3807 	int   bad_len[]   = { 6 };
3808 	int  i;
3809 
3810 	if (len < 0) {
3811 		return EINVAL;
3812 	}
3813 
3814 	for (i = 0; i < (int) (sizeof(bad_names) / sizeof(bad_names[0])); i++) {
3815 		if (len == bad_len[i] && strncmp(name, bad_names[i], strlen(bad_names[i]) + 1) == 0) {
3816 			return 1;
3817 		}
3818 	}
3819 
3820 	// if we get here, no name matched
3821 	return 0;
3822 }
3823 
3824 /*
3825  * Top level filesystem related information gathering.
3826  */
3827 extern unsigned int vfs_nummntops;
3828 
3829 /*
3830  * The VFS_NUMMNTOPS shouldn't be at name[1] since
3831  * is a VFS generic variable. Since we no longer support
3832  * VT_UFS, we reserve its value to support this sysctl node.
3833  *
3834  * It should have been:
3835  *    name[0]:  VFS_GENERIC
3836  *    name[1]:  VFS_NUMMNTOPS
3837  */
3838 SYSCTL_INT(_vfs, VFS_NUMMNTOPS, nummntops,
3839     CTLFLAG_RD | CTLFLAG_KERN | CTLFLAG_LOCKED,
3840     &vfs_nummntops, 0, "");
3841 
3842 int
3843 vfs_sysctl(int *name __unused, u_int namelen __unused,
3844     user_addr_t oldp __unused, size_t *oldlenp __unused,
3845     user_addr_t newp __unused, size_t newlen __unused, proc_t p __unused);
3846 
3847 int
vfs_sysctl(int * name __unused,u_int namelen __unused,user_addr_t oldp __unused,size_t * oldlenp __unused,user_addr_t newp __unused,size_t newlen __unused,proc_t p __unused)3848 vfs_sysctl(int *name __unused, u_int namelen __unused,
3849     user_addr_t oldp __unused, size_t *oldlenp __unused,
3850     user_addr_t newp __unused, size_t newlen __unused, proc_t p __unused)
3851 {
3852 	return EINVAL;
3853 }
3854 
3855 
3856 //
3857 // The following code disallows specific sysctl's that came through
3858 // the direct sysctl interface (vfs_sysctl_node) instead of the newer
3859 // sysctl_vfs_ctlbyfsid() interface.  We can not allow these selectors
3860 // through vfs_sysctl_node() because it passes the user's oldp pointer
3861 // directly to the file system which (for these selectors) casts it
3862 // back to a struct sysctl_req and then proceed to use SYSCTL_IN()
3863 // which jumps through an arbitrary function pointer.  When called
3864 // through the sysctl_vfs_ctlbyfsid() interface this does not happen
3865 // and so it's safe.
3866 //
3867 // Unfortunately we have to pull in definitions from AFP and SMB and
3868 // perform explicit name checks on the file system to determine if
3869 // these selectors are being used.
3870 //
3871 
3872 #define AFPFS_VFS_CTL_GETID            0x00020001
3873 #define AFPFS_VFS_CTL_NETCHANGE        0x00020002
3874 #define AFPFS_VFS_CTL_VOLCHANGE        0x00020003
3875 
3876 #define SMBFS_SYSCTL_REMOUNT           1
3877 #define SMBFS_SYSCTL_REMOUNT_INFO      2
3878 #define SMBFS_SYSCTL_GET_SERVER_SHARE  3
3879 
3880 
3881 static int
is_bad_sysctl_name(struct vfstable * vfsp,int selector_name)3882 is_bad_sysctl_name(struct vfstable *vfsp, int selector_name)
3883 {
3884 	switch (selector_name) {
3885 	case VFS_CTL_QUERY:
3886 	case VFS_CTL_TIMEO:
3887 	case VFS_CTL_NOLOCKS:
3888 	case VFS_CTL_NSTATUS:
3889 	case VFS_CTL_SADDR:
3890 	case VFS_CTL_DISC:
3891 	case VFS_CTL_SERVERINFO:
3892 		return 1;
3893 
3894 	default:
3895 		break;
3896 	}
3897 
3898 	// the more complicated check for some of SMB's special values
3899 	if (strcmp(vfsp->vfc_name, "smbfs") == 0) {
3900 		switch (selector_name) {
3901 		case SMBFS_SYSCTL_REMOUNT:
3902 		case SMBFS_SYSCTL_REMOUNT_INFO:
3903 		case SMBFS_SYSCTL_GET_SERVER_SHARE:
3904 			return 1;
3905 		}
3906 	} else if (strcmp(vfsp->vfc_name, "afpfs") == 0) {
3907 		switch (selector_name) {
3908 		case AFPFS_VFS_CTL_GETID:
3909 		case AFPFS_VFS_CTL_NETCHANGE:
3910 		case AFPFS_VFS_CTL_VOLCHANGE:
3911 			return 1;
3912 		}
3913 	}
3914 
3915 	//
3916 	// If we get here we passed all the checks so the selector is ok
3917 	//
3918 	return 0;
3919 }
3920 
3921 
3922 int vfs_sysctl_node SYSCTL_HANDLER_ARGS
3923 {
3924 	int *name, namelen;
3925 	struct vfstable *vfsp;
3926 	int error;
3927 	int fstypenum;
3928 
3929 	fstypenum = oidp->oid_number;
3930 	name = arg1;
3931 	namelen = arg2;
3932 
3933 	/* all sysctl names at this level should have at least one name slot for the FS */
3934 	if (namelen < 1) {
3935 		return EISDIR; /* overloaded */
3936 	}
3937 	mount_list_lock();
3938 	for (vfsp = vfsconf; vfsp; vfsp = vfsp->vfc_next) {
3939 		if (vfsp->vfc_typenum == fstypenum) {
3940 			vfsp->vfc_refcount++;
3941 			break;
3942 		}
3943 	}
3944 	mount_list_unlock();
3945 
3946 	if (vfsp == NULL) {
3947 		return ENOTSUP;
3948 	}
3949 
3950 	if (is_bad_sysctl_name(vfsp, name[0])) {
3951 		printf("vfs: bad selector 0x%.8x for old-style sysctl().  use the sysctl-by-fsid interface instead\n", name[0]);
3952 		error = EPERM;
3953 	} else {
3954 		error = (vfsp->vfc_vfsops->vfs_sysctl)(name, namelen,
3955 		    req->oldptr, &req->oldlen, req->newptr, req->newlen,
3956 		    vfs_context_current());
3957 	}
3958 
3959 	mount_list_lock();
3960 	vfsp->vfc_refcount--;
3961 	mount_list_unlock();
3962 
3963 	return error;
3964 }
3965 
3966 /*
3967  * Check to see if a filesystem is mounted on a block device.
3968  */
3969 int
vfs_mountedon(struct vnode * vp)3970 vfs_mountedon(struct vnode *vp)
3971 {
3972 	struct vnode *vq;
3973 	int error = 0;
3974 
3975 	SPECHASH_LOCK();
3976 	if (vp->v_specflags & SI_MOUNTEDON) {
3977 		error = EBUSY;
3978 		goto out;
3979 	}
3980 	if (vp->v_specflags & SI_ALIASED) {
3981 		for (vq = *vp->v_hashchain; vq; vq = vq->v_specnext) {
3982 			if (vq->v_rdev != vp->v_rdev ||
3983 			    vq->v_type != vp->v_type) {
3984 				continue;
3985 			}
3986 			if (vq->v_specflags & SI_MOUNTEDON) {
3987 				error = EBUSY;
3988 				break;
3989 			}
3990 		}
3991 	}
3992 out:
3993 	SPECHASH_UNLOCK();
3994 	return error;
3995 }
3996 
3997 struct unmount_info {
3998 	int     u_errs; // Total failed unmounts
3999 	int     u_busy; // EBUSY failed unmounts
4000 	int     u_count; // Total volumes iterated
4001 	int     u_only_non_system;
4002 };
4003 
4004 static int
unmount_callback(mount_t mp,void * arg)4005 unmount_callback(mount_t mp, void *arg)
4006 {
4007 	int error;
4008 	char *mntname;
4009 	struct unmount_info *uip = arg;
4010 
4011 	uip->u_count++;
4012 
4013 	mntname = zalloc_flags(ZV_NAMEI, Z_WAITOK | Z_NOFAIL);
4014 	strlcpy(mntname, mp->mnt_vfsstat.f_mntonname, MAXPATHLEN);
4015 
4016 	if (uip->u_only_non_system
4017 	    && ((mp->mnt_flag & MNT_ROOTFS) || (mp->mnt_kern_flag & MNTK_SYSTEM))) { //MNTK_BACKS_ROOT
4018 		printf("unmount(%d) %s skipped\n", uip->u_only_non_system, mntname);
4019 		mount_iterdrop(mp);     // VFS_ITERATE_CB_DROPREF
4020 	} else {
4021 		printf("unmount(%d) %s\n", uip->u_only_non_system, mntname);
4022 
4023 		mount_ref(mp, 0);
4024 		mount_iterdrop(mp);     // VFS_ITERATE_CB_DROPREF
4025 		error = dounmount(mp, MNT_FORCE, 1, vfs_context_current());
4026 		if (error) {
4027 			uip->u_errs++;
4028 			printf("Unmount of %s failed (%d)\n", mntname ? mntname:"?", error);
4029 			if (error == EBUSY) {
4030 				uip->u_busy++;
4031 			}
4032 		}
4033 	}
4034 	zfree(ZV_NAMEI, mntname);
4035 
4036 	return VFS_RETURNED;
4037 }
4038 
4039 /*
4040  * Unmount all filesystems. The list is traversed in reverse order
4041  * of mounting to avoid dependencies.
4042  * Busy mounts are retried.
4043  */
4044 __private_extern__ void
vfs_unmountall(int only_non_system)4045 vfs_unmountall(int only_non_system)
4046 {
4047 	int mounts, sec = 1;
4048 	struct unmount_info ui;
4049 
4050 	/*
4051 	 * Ensure last-completion-time is valid before anyone can see that
4052 	 * VFS shutdown has started.
4053 	 */
4054 	vfs_shutdown_last_completion_time = mach_absolute_time();
4055 	OSMemoryBarrier();
4056 	vfs_unmountall_started = 1;
4057 	printf("vfs_unmountall(%ssystem) start\n", only_non_system ? "non" : "");
4058 
4059 retry:
4060 	ui.u_errs = ui.u_busy = ui.u_count = 0;
4061 	ui.u_only_non_system = only_non_system;
4062 	// avoid vfs_iterate deadlock in dounmount(), use VFS_ITERATE_CB_DROPREF
4063 	vfs_iterate(VFS_ITERATE_CB_DROPREF | VFS_ITERATE_TAIL_FIRST, unmount_callback, &ui);
4064 	mounts = mount_getvfscnt();
4065 	if (mounts == 0) {
4066 		goto out;
4067 	}
4068 	if (ui.u_busy > 0) {            // Busy mounts - wait & retry
4069 		tsleep(&nummounts, PVFS, "busy mount", sec * hz);
4070 		sec *= 2;
4071 		if (sec <= 32) {
4072 			goto retry;
4073 		}
4074 		printf("Unmounting timed out\n");
4075 	} else if (ui.u_count < mounts) {
4076 		// If the vfs_iterate missed mounts in progress - wait a bit
4077 		tsleep(&nummounts, PVFS, "missed mount", 2 * hz);
4078 	}
4079 
4080 out:
4081 	printf("vfs_unmountall(%ssystem) end\n", only_non_system ? "non" : "");
4082 
4083 	/*
4084 	 * reboot_kernel() calls us twice; once to deal with non-system
4085 	 * mounts, and again to sweep up anything left after terminating
4086 	 * DEXTs.  We're only finished once we've completed the second pass.
4087 	 */
4088 	if (!only_non_system) {
4089 		vfs_unmountall_finished = 1;
4090 	}
4091 }
4092 
4093 /*
4094  * vfs_shutdown_in_progress --
4095  *
4096  * Returns whether or not the VFS is shutting down the file systems.
4097  */
4098 boolean_t
vfs_shutdown_in_progress(void)4099 vfs_shutdown_in_progress(void)
4100 {
4101 	return vfs_unmountall_started && !vfs_unmountall_finished;
4102 }
4103 
4104 /*
4105  * vfs_shutdown_finished --
4106  *
4107  * Returns whether or not the VFS shutdown has completed.
4108  */
4109 boolean_t
vfs_shutdown_finished(void)4110 vfs_shutdown_finished(void)
4111 {
4112 	return !!vfs_unmountall_finished;
4113 }
4114 
4115 /*
4116  * vfs_update_last_completion_time --
4117  *
4118  * Updates the "last I/O completion time" timestamp used by the watchdog
4119  * to monitor VFS shutdown progress.  Called by various I/O stack layers
4120  * as operations complete and progress moves forward.
4121  */
4122 void
vfs_update_last_completion_time(void)4123 vfs_update_last_completion_time(void)
4124 {
4125 	if (vfs_unmountall_started) {
4126 		vfs_shutdown_last_completion_time = mach_absolute_time();
4127 	}
4128 }
4129 
4130 /*
4131  * vfs_last_completion_time --
4132  *
4133  * Returns the "last I/O completion time" timestamp.  Return
4134  * value is a mach_absolute_time() value, and is not meaningful
4135  * unless vfs_is_shutting_down() also returns true.
4136  */
4137 uint64_t
vfs_last_completion_time(void)4138 vfs_last_completion_time(void)
4139 {
4140 	return vfs_unmountall_started ? vfs_shutdown_last_completion_time : 0;
4141 }
4142 
4143 /*
4144  * This routine is called from vnode_pager_deallocate out of the VM
4145  * The path to vnode_pager_deallocate can only be initiated by ubc_destroy_named
4146  * on a vnode that has a UBCINFO
4147  */
4148 __private_extern__ void
vnode_pager_vrele(vnode_t vp)4149 vnode_pager_vrele(vnode_t vp)
4150 {
4151 	struct ubc_info *uip;
4152 
4153 	vnode_lock_spin(vp);
4154 
4155 	vp->v_lflag &= ~VNAMED_UBC;
4156 	if (vp->v_usecount != 0) {
4157 		/*
4158 		 * At the eleventh hour, just before the ubcinfo is
4159 		 * destroyed, ensure the ubc-specific v_usecount
4160 		 * reference has gone.  We use v_usecount != 0 as a hint;
4161 		 * ubc_unmap() does nothing if there's no mapping.
4162 		 *
4163 		 * This case is caused by coming here via forced unmount,
4164 		 * versus the usual vm_object_deallocate() path.
4165 		 * In the forced unmount case, ubc_destroy_named()
4166 		 * releases the pager before memory_object_last_unmap()
4167 		 * can be called.
4168 		 */
4169 		vnode_unlock(vp);
4170 		ubc_unmap(vp);
4171 		vnode_lock_spin(vp);
4172 	}
4173 
4174 	uip = vp->v_ubcinfo;
4175 	vp->v_ubcinfo = UBC_INFO_NULL;
4176 
4177 	vnode_unlock(vp);
4178 
4179 	ubc_info_deallocate(uip);
4180 }
4181 
4182 
4183 #include <sys/disk.h>
4184 
4185 u_int32_t rootunit = (u_int32_t)-1;
4186 
4187 #if CONFIG_IOSCHED
4188 extern int lowpri_throttle_enabled;
4189 extern int iosched_enabled;
4190 #endif
4191 
4192 errno_t
vfs_init_io_attributes(vnode_t devvp,mount_t mp)4193 vfs_init_io_attributes(vnode_t devvp, mount_t mp)
4194 {
4195 	int     error;
4196 	off_t   readblockcnt = 0;
4197 	off_t   writeblockcnt = 0;
4198 	off_t   readmaxcnt = 0;
4199 	off_t   writemaxcnt = 0;
4200 	off_t   readsegcnt = 0;
4201 	off_t   writesegcnt = 0;
4202 	off_t   readsegsize = 0;
4203 	off_t   writesegsize = 0;
4204 	off_t   alignment = 0;
4205 	u_int32_t minsaturationbytecount = 0;
4206 	u_int32_t ioqueue_depth = 0;
4207 	u_int32_t blksize;
4208 	u_int64_t temp;
4209 	u_int32_t features;
4210 	u_int64_t location = 0;
4211 	vfs_context_t ctx = vfs_context_current();
4212 	dk_corestorage_info_t cs_info;
4213 	boolean_t cs_present = FALSE;
4214 	int isssd = 0;
4215 	int isvirtual = 0;
4216 
4217 
4218 	VNOP_IOCTL(devvp, DKIOCGETTHROTTLEMASK, (caddr_t)&mp->mnt_throttle_mask, 0, NULL);
4219 	/*
4220 	 * as a reasonable approximation, only use the lowest bit of the mask
4221 	 * to generate a disk unit number
4222 	 */
4223 	mp->mnt_devbsdunit = num_trailing_0(mp->mnt_throttle_mask);
4224 
4225 	if (devvp == rootvp) {
4226 		rootunit = mp->mnt_devbsdunit;
4227 	}
4228 
4229 	if (mp->mnt_devbsdunit == rootunit) {
4230 		/*
4231 		 * this mount point exists on the same device as the root
4232 		 * partition, so it comes under the hard throttle control...
4233 		 * this is true even for the root mount point itself
4234 		 */
4235 		mp->mnt_kern_flag |= MNTK_ROOTDEV;
4236 	}
4237 	/*
4238 	 * force the spec device to re-cache
4239 	 * the underlying block size in case
4240 	 * the filesystem overrode the initial value
4241 	 */
4242 	set_fsblocksize(devvp);
4243 
4244 
4245 	if ((error = VNOP_IOCTL(devvp, DKIOCGETBLOCKSIZE,
4246 	    (caddr_t)&blksize, 0, ctx))) {
4247 		return error;
4248 	}
4249 
4250 	mp->mnt_devblocksize = blksize;
4251 
4252 	/*
4253 	 * set the maximum possible I/O size
4254 	 * this may get clipped to a smaller value
4255 	 * based on which constraints are being advertised
4256 	 * and if those advertised constraints result in a smaller
4257 	 * limit for a given I/O
4258 	 */
4259 	mp->mnt_maxreadcnt = MAX_UPL_SIZE_BYTES;
4260 	mp->mnt_maxwritecnt = MAX_UPL_SIZE_BYTES;
4261 
4262 	if (VNOP_IOCTL(devvp, DKIOCISVIRTUAL, (caddr_t)&isvirtual, 0, ctx) == 0) {
4263 		if (isvirtual) {
4264 			mp->mnt_kern_flag |= MNTK_VIRTUALDEV;
4265 			mp->mnt_flag |= MNT_REMOVABLE;
4266 		}
4267 	}
4268 	if (VNOP_IOCTL(devvp, DKIOCISSOLIDSTATE, (caddr_t)&isssd, 0, ctx) == 0) {
4269 		if (isssd) {
4270 			mp->mnt_kern_flag |= MNTK_SSD;
4271 		}
4272 	}
4273 	if ((error = VNOP_IOCTL(devvp, DKIOCGETFEATURES,
4274 	    (caddr_t)&features, 0, ctx))) {
4275 		return error;
4276 	}
4277 
4278 	if ((error = VNOP_IOCTL(devvp, DKIOCGETMAXBLOCKCOUNTREAD,
4279 	    (caddr_t)&readblockcnt, 0, ctx))) {
4280 		return error;
4281 	}
4282 
4283 	if ((error = VNOP_IOCTL(devvp, DKIOCGETMAXBLOCKCOUNTWRITE,
4284 	    (caddr_t)&writeblockcnt, 0, ctx))) {
4285 		return error;
4286 	}
4287 
4288 	if ((error = VNOP_IOCTL(devvp, DKIOCGETMAXBYTECOUNTREAD,
4289 	    (caddr_t)&readmaxcnt, 0, ctx))) {
4290 		return error;
4291 	}
4292 
4293 	if ((error = VNOP_IOCTL(devvp, DKIOCGETMAXBYTECOUNTWRITE,
4294 	    (caddr_t)&writemaxcnt, 0, ctx))) {
4295 		return error;
4296 	}
4297 
4298 	if ((error = VNOP_IOCTL(devvp, DKIOCGETMAXSEGMENTCOUNTREAD,
4299 	    (caddr_t)&readsegcnt, 0, ctx))) {
4300 		return error;
4301 	}
4302 
4303 	if ((error = VNOP_IOCTL(devvp, DKIOCGETMAXSEGMENTCOUNTWRITE,
4304 	    (caddr_t)&writesegcnt, 0, ctx))) {
4305 		return error;
4306 	}
4307 
4308 	if ((error = VNOP_IOCTL(devvp, DKIOCGETMAXSEGMENTBYTECOUNTREAD,
4309 	    (caddr_t)&readsegsize, 0, ctx))) {
4310 		return error;
4311 	}
4312 
4313 	if ((error = VNOP_IOCTL(devvp, DKIOCGETMAXSEGMENTBYTECOUNTWRITE,
4314 	    (caddr_t)&writesegsize, 0, ctx))) {
4315 		return error;
4316 	}
4317 
4318 	if ((error = VNOP_IOCTL(devvp, DKIOCGETMINSEGMENTALIGNMENTBYTECOUNT,
4319 	    (caddr_t)&alignment, 0, ctx))) {
4320 		return error;
4321 	}
4322 
4323 	if ((error = VNOP_IOCTL(devvp, DKIOCGETCOMMANDPOOLSIZE,
4324 	    (caddr_t)&ioqueue_depth, 0, ctx))) {
4325 		return error;
4326 	}
4327 
4328 	if (readmaxcnt) {
4329 		mp->mnt_maxreadcnt = (readmaxcnt > UINT32_MAX) ? UINT32_MAX :(uint32_t) readmaxcnt;
4330 	}
4331 
4332 	if (readblockcnt) {
4333 		temp = readblockcnt * blksize;
4334 		temp = (temp > UINT32_MAX) ? UINT32_MAX : temp;
4335 
4336 		if (temp < mp->mnt_maxreadcnt) {
4337 			mp->mnt_maxreadcnt = (u_int32_t)temp;
4338 		}
4339 	}
4340 
4341 	if (writemaxcnt) {
4342 		mp->mnt_maxwritecnt = (writemaxcnt > UINT32_MAX) ? UINT32_MAX : (uint32_t)writemaxcnt;
4343 	}
4344 
4345 	if (writeblockcnt) {
4346 		temp = writeblockcnt * blksize;
4347 		temp = (temp > UINT32_MAX) ? UINT32_MAX : temp;
4348 
4349 		if (temp < mp->mnt_maxwritecnt) {
4350 			mp->mnt_maxwritecnt = (u_int32_t)temp;
4351 		}
4352 	}
4353 
4354 	if (readsegcnt) {
4355 		temp = (readsegcnt > UINT16_MAX) ? UINT16_MAX : readsegcnt;
4356 	} else {
4357 		temp = mp->mnt_maxreadcnt / PAGE_SIZE;
4358 
4359 		if (temp > UINT16_MAX) {
4360 			temp = UINT16_MAX;
4361 		}
4362 	}
4363 	mp->mnt_segreadcnt = (u_int16_t)temp;
4364 
4365 	if (writesegcnt) {
4366 		temp = (writesegcnt > UINT16_MAX) ? UINT16_MAX : writesegcnt;
4367 	} else {
4368 		temp = mp->mnt_maxwritecnt / PAGE_SIZE;
4369 
4370 		if (temp > UINT16_MAX) {
4371 			temp = UINT16_MAX;
4372 		}
4373 	}
4374 	mp->mnt_segwritecnt = (u_int16_t)temp;
4375 
4376 	if (readsegsize) {
4377 		temp = (readsegsize > UINT32_MAX) ? UINT32_MAX : readsegsize;
4378 	} else {
4379 		temp = mp->mnt_maxreadcnt;
4380 	}
4381 	mp->mnt_maxsegreadsize = (u_int32_t)temp;
4382 
4383 	if (writesegsize) {
4384 		temp = (writesegsize > UINT32_MAX) ? UINT32_MAX : writesegsize;
4385 	} else {
4386 		temp = mp->mnt_maxwritecnt;
4387 	}
4388 	mp->mnt_maxsegwritesize = (u_int32_t)temp;
4389 
4390 	if (alignment) {
4391 		temp = (alignment > PAGE_SIZE) ? PAGE_MASK : alignment - 1;
4392 	} else {
4393 		temp = 0;
4394 	}
4395 	mp->mnt_alignmentmask = (uint32_t)temp;
4396 
4397 
4398 	if (ioqueue_depth > MNT_DEFAULT_IOQUEUE_DEPTH) {
4399 		temp = ioqueue_depth;
4400 	} else {
4401 		temp = MNT_DEFAULT_IOQUEUE_DEPTH;
4402 	}
4403 
4404 	mp->mnt_ioqueue_depth = (uint32_t)temp;
4405 	mp->mnt_ioscale = MNT_IOSCALE(mp->mnt_ioqueue_depth);
4406 
4407 	if (mp->mnt_ioscale > 1) {
4408 		printf("ioqueue_depth = %d,   ioscale = %d\n", (int)mp->mnt_ioqueue_depth, (int)mp->mnt_ioscale);
4409 	}
4410 
4411 	if (features & DK_FEATURE_FORCE_UNIT_ACCESS) {
4412 		mp->mnt_ioflags |= MNT_IOFLAGS_FUA_SUPPORTED;
4413 	}
4414 
4415 	if (VNOP_IOCTL(devvp, DKIOCGETIOMINSATURATIONBYTECOUNT, (caddr_t)&minsaturationbytecount, 0, ctx) == 0) {
4416 		mp->mnt_minsaturationbytecount = minsaturationbytecount;
4417 	} else {
4418 		mp->mnt_minsaturationbytecount = 0;
4419 	}
4420 
4421 	if (VNOP_IOCTL(devvp, DKIOCCORESTORAGE, (caddr_t)&cs_info, 0, ctx) == 0) {
4422 		cs_present = TRUE;
4423 	}
4424 
4425 	if (features & DK_FEATURE_UNMAP) {
4426 		mp->mnt_ioflags |= MNT_IOFLAGS_UNMAP_SUPPORTED;
4427 
4428 		if (cs_present == TRUE) {
4429 			mp->mnt_ioflags |= MNT_IOFLAGS_CSUNMAP_SUPPORTED;
4430 		}
4431 	}
4432 	if (cs_present == TRUE) {
4433 		/*
4434 		 * for now we'll use the following test as a proxy for
4435 		 * the underlying drive being FUSION in nature
4436 		 */
4437 		if ((cs_info.flags & DK_CORESTORAGE_PIN_YOUR_METADATA)) {
4438 			mp->mnt_ioflags |= MNT_IOFLAGS_FUSION_DRIVE;
4439 		}
4440 	} else {
4441 		/* Check for APFS Fusion */
4442 		dk_apfs_flavour_t flavour;
4443 		if ((VNOP_IOCTL(devvp, DKIOCGETAPFSFLAVOUR, (caddr_t)&flavour, 0, ctx) == 0) &&
4444 		    (flavour == DK_APFS_FUSION)) {
4445 			mp->mnt_ioflags |= MNT_IOFLAGS_FUSION_DRIVE;
4446 		}
4447 	}
4448 
4449 	if (VNOP_IOCTL(devvp, DKIOCGETLOCATION, (caddr_t)&location, 0, ctx) == 0) {
4450 		if (location & DK_LOCATION_EXTERNAL) {
4451 			mp->mnt_ioflags |= MNT_IOFLAGS_PERIPHERAL_DRIVE;
4452 			mp->mnt_flag |= MNT_REMOVABLE;
4453 		}
4454 	}
4455 
4456 #if CONFIG_IOSCHED
4457 	if (iosched_enabled && (features & DK_FEATURE_PRIORITY)) {
4458 		mp->mnt_ioflags |= MNT_IOFLAGS_IOSCHED_SUPPORTED;
4459 		throttle_info_disable_throttle(mp->mnt_devbsdunit, (mp->mnt_ioflags & MNT_IOFLAGS_FUSION_DRIVE) != 0);
4460 	}
4461 #endif /* CONFIG_IOSCHED */
4462 	return error;
4463 }
4464 
4465 static struct klist fs_klist;
4466 static LCK_GRP_DECLARE(fs_klist_lck_grp, "fs_klist");
4467 static LCK_MTX_DECLARE(fs_klist_lock, &fs_klist_lck_grp);
4468 
4469 void
vfs_event_init(void)4470 vfs_event_init(void)
4471 {
4472 	klist_init(&fs_klist);
4473 }
4474 
4475 void
vfs_event_signal(fsid_t * fsid,u_int32_t event,intptr_t data)4476 vfs_event_signal(fsid_t *fsid, u_int32_t event, intptr_t data)
4477 {
4478 	if (event == VQ_DEAD || event == VQ_NOTRESP) {
4479 		struct mount *mp = vfs_getvfs(fsid);
4480 		if (mp) {
4481 			mount_lock_spin(mp);
4482 			if (data) {
4483 				mp->mnt_kern_flag &= ~MNT_LNOTRESP;     // Now responding
4484 			} else {
4485 				mp->mnt_kern_flag |= MNT_LNOTRESP;      // Not responding
4486 			}
4487 			mount_unlock(mp);
4488 		}
4489 	}
4490 
4491 	lck_mtx_lock(&fs_klist_lock);
4492 	KNOTE(&fs_klist, event);
4493 	lck_mtx_unlock(&fs_klist_lock);
4494 }
4495 
4496 /*
4497  * return the number of mounted filesystems.
4498  */
4499 static int
sysctl_vfs_getvfscnt(void)4500 sysctl_vfs_getvfscnt(void)
4501 {
4502 	return mount_getvfscnt();
4503 }
4504 
4505 
4506 static int
mount_getvfscnt(void)4507 mount_getvfscnt(void)
4508 {
4509 	int ret;
4510 
4511 	mount_list_lock();
4512 	ret = nummounts;
4513 	mount_list_unlock();
4514 	return ret;
4515 }
4516 
4517 
4518 
4519 static int
mount_fillfsids(fsid_t * fsidlst,int count)4520 mount_fillfsids(fsid_t *fsidlst, int count)
4521 {
4522 	struct mount *mp;
4523 	int actual = 0;
4524 
4525 	actual = 0;
4526 	mount_list_lock();
4527 	TAILQ_FOREACH(mp, &mountlist, mnt_list) {
4528 		if (actual < count) {
4529 			fsidlst[actual] = mp->mnt_vfsstat.f_fsid;
4530 			actual++;
4531 		}
4532 	}
4533 	mount_list_unlock();
4534 	return actual;
4535 }
4536 
4537 /*
4538  * fill in the array of fsid_t's up to a max of 'count', the actual
4539  * number filled in will be set in '*actual'.  If there are more fsid_t's
4540  * than room in fsidlst then ENOMEM will be returned and '*actual' will
4541  * have the actual count.
4542  * having *actual filled out even in the error case is depended upon.
4543  */
4544 static int
sysctl_vfs_getvfslist(fsid_t * fsidlst,unsigned long count,unsigned long * actual)4545 sysctl_vfs_getvfslist(fsid_t *fsidlst, unsigned long count, unsigned long *actual)
4546 {
4547 	struct mount *mp;
4548 
4549 	*actual = 0;
4550 	mount_list_lock();
4551 	TAILQ_FOREACH(mp, &mountlist, mnt_list) {
4552 		(*actual)++;
4553 		if (*actual <= count) {
4554 			fsidlst[(*actual) - 1] = mp->mnt_vfsstat.f_fsid;
4555 		}
4556 	}
4557 	mount_list_unlock();
4558 	return *actual <= count ? 0 : ENOMEM;
4559 }
4560 
4561 static int
sysctl_vfs_vfslist(__unused struct sysctl_oid * oidp,__unused void * arg1,__unused int arg2,struct sysctl_req * req)4562 sysctl_vfs_vfslist(__unused struct sysctl_oid *oidp, __unused void *arg1,
4563     __unused int arg2, struct sysctl_req *req)
4564 {
4565 	unsigned long actual;
4566 	int error;
4567 	size_t space;
4568 	fsid_t *fsidlst;
4569 
4570 	/* This is a readonly node. */
4571 	if (req->newptr != USER_ADDR_NULL) {
4572 		return EPERM;
4573 	}
4574 
4575 	/* they are querying us so just return the space required. */
4576 	if (req->oldptr == USER_ADDR_NULL) {
4577 		req->oldidx = sysctl_vfs_getvfscnt() * sizeof(fsid_t);
4578 		return 0;
4579 	}
4580 again:
4581 	/*
4582 	 * Retrieve an accurate count of the amount of space required to copy
4583 	 * out all the fsids in the system.
4584 	 */
4585 	space = req->oldlen;
4586 	req->oldlen = sysctl_vfs_getvfscnt() * sizeof(fsid_t);
4587 
4588 	/* they didn't give us enough space. */
4589 	if (space < req->oldlen) {
4590 		return ENOMEM;
4591 	}
4592 
4593 	fsidlst = kalloc_data(req->oldlen, Z_WAITOK | Z_ZERO);
4594 	if (fsidlst == NULL) {
4595 		return ENOMEM;
4596 	}
4597 
4598 	error = sysctl_vfs_getvfslist(fsidlst, req->oldlen / sizeof(fsid_t),
4599 	    &actual);
4600 	/*
4601 	 * If we get back ENOMEM, then another mount has been added while we
4602 	 * slept in malloc above.  If this is the case then try again.
4603 	 */
4604 	if (error == ENOMEM) {
4605 		kfree_data(fsidlst, req->oldlen);
4606 		req->oldlen = space;
4607 		goto again;
4608 	}
4609 	if (error == 0) {
4610 		error = SYSCTL_OUT(req, fsidlst, actual * sizeof(fsid_t));
4611 	}
4612 	kfree_data(fsidlst, req->oldlen);
4613 	return error;
4614 }
4615 
4616 /*
4617  * Do a sysctl by fsid.
4618  */
4619 static int
sysctl_vfs_ctlbyfsid(__unused struct sysctl_oid * oidp,void * arg1,int arg2,struct sysctl_req * req)4620 sysctl_vfs_ctlbyfsid(__unused struct sysctl_oid *oidp, void *arg1, int arg2,
4621     struct sysctl_req *req)
4622 {
4623 	union union_vfsidctl vc;
4624 	struct mount *mp = NULL;
4625 	struct vfsstatfs *sp;
4626 	int *name, namelen;
4627 	int flags = 0;
4628 	int error = 0, gotref = 0;
4629 	vfs_context_t ctx = vfs_context_current();
4630 	proc_t p = req->p;      /* XXX req->p != current_proc()? */
4631 	boolean_t is_64_bit;
4632 	union {
4633 		struct statfs64 sfs64;
4634 		struct user64_statfs osfs64;
4635 		struct user32_statfs osfs32;
4636 	} *sfsbuf;
4637 
4638 	if (req->newptr == USER_ADDR_NULL) {
4639 		error = EINVAL;
4640 		goto out;
4641 	}
4642 
4643 	name = arg1;
4644 	namelen = arg2;
4645 	is_64_bit = proc_is64bit(p);
4646 
4647 	error = SYSCTL_IN(req, &vc, is_64_bit? sizeof(vc.vc64):sizeof(vc.vc32));
4648 	if (error) {
4649 		goto out;
4650 	}
4651 	if (vc.vc32.vc_vers != VFS_CTL_VERS1) { /* works for 32 and 64 */
4652 		error = EINVAL;
4653 		goto out;
4654 	}
4655 	mp = mount_list_lookupby_fsid(&vc.vc32.vc_fsid, 0, 1); /* works for 32 and 64 */
4656 	if (mp == NULL) {
4657 		error = ENOENT;
4658 		goto out;
4659 	}
4660 	gotref = 1;
4661 	/* reset so that the fs specific code can fetch it. */
4662 	req->newidx = 0;
4663 	/*
4664 	 * Note if this is a VFS_CTL then we pass the actual sysctl req
4665 	 * in for "oldp" so that the lower layer can DTRT and use the
4666 	 * SYSCTL_IN/OUT routines.
4667 	 */
4668 	if (mp->mnt_op->vfs_sysctl != NULL) {
4669 		if (is_64_bit) {
4670 			if (vfs_64bitready(mp)) {
4671 				error = mp->mnt_op->vfs_sysctl(name, namelen,
4672 				    CAST_USER_ADDR_T(req),
4673 				    NULL, USER_ADDR_NULL, 0,
4674 				    ctx);
4675 			} else {
4676 				error = ENOTSUP;
4677 			}
4678 		} else {
4679 			error = mp->mnt_op->vfs_sysctl(name, namelen,
4680 			    CAST_USER_ADDR_T(req),
4681 			    NULL, USER_ADDR_NULL, 0,
4682 			    ctx);
4683 		}
4684 		if (error != ENOTSUP) {
4685 			goto out;
4686 		}
4687 	}
4688 	switch (name[0]) {
4689 	case VFS_CTL_UMOUNT:
4690 #if CONFIG_MACF
4691 		error = mac_mount_check_umount(ctx, mp);
4692 		if (error != 0) {
4693 			goto out;
4694 		}
4695 #endif
4696 		req->newidx = 0;
4697 		if (is_64_bit) {
4698 			req->newptr = vc.vc64.vc_ptr;
4699 			req->newlen = (size_t)vc.vc64.vc_len;
4700 		} else {
4701 			req->newptr = CAST_USER_ADDR_T(vc.vc32.vc_ptr);
4702 			req->newlen = vc.vc32.vc_len;
4703 		}
4704 		error = SYSCTL_IN(req, &flags, sizeof(flags));
4705 		if (error) {
4706 			break;
4707 		}
4708 
4709 		mount_ref(mp, 0);
4710 		mount_iterdrop(mp);
4711 		gotref = 0;
4712 		/* safedounmount consumes a ref */
4713 		error = safedounmount(mp, flags, ctx);
4714 		break;
4715 	case VFS_CTL_OSTATFS:
4716 	case VFS_CTL_STATFS64:
4717 #if CONFIG_MACF
4718 		error = mac_mount_check_stat(ctx, mp);
4719 		if (error != 0) {
4720 			break;
4721 		}
4722 #endif
4723 		req->newidx = 0;
4724 		if (is_64_bit) {
4725 			req->newptr = vc.vc64.vc_ptr;
4726 			req->newlen = (size_t)vc.vc64.vc_len;
4727 		} else {
4728 			req->newptr = CAST_USER_ADDR_T(vc.vc32.vc_ptr);
4729 			req->newlen = vc.vc32.vc_len;
4730 		}
4731 		error = SYSCTL_IN(req, &flags, sizeof(flags));
4732 		if (error) {
4733 			break;
4734 		}
4735 		sp = &mp->mnt_vfsstat;
4736 		if (((flags & MNT_NOWAIT) == 0 || (flags & (MNT_WAIT | MNT_DWAIT))) &&
4737 		    (error = vfs_update_vfsstat(mp, ctx, VFS_USER_EVENT))) {
4738 			goto out;
4739 		}
4740 
4741 		sfsbuf = kalloc_type(typeof(*sfsbuf), Z_WAITOK);
4742 
4743 		if (name[0] == VFS_CTL_STATFS64) {
4744 			struct statfs64 *sfs = &sfsbuf->sfs64;
4745 
4746 			vfs_get_statfs64(mp, sfs);
4747 			error = SYSCTL_OUT(req, sfs, sizeof(*sfs));
4748 		} else if (is_64_bit) {
4749 			struct user64_statfs *sfs = &sfsbuf->osfs64;
4750 
4751 			bzero(sfs, sizeof(*sfs));
4752 			sfs->f_flags = mp->mnt_flag & MNT_VISFLAGMASK;
4753 			sfs->f_type = (short)mp->mnt_vtable->vfc_typenum;
4754 			sfs->f_bsize = (user64_long_t)sp->f_bsize;
4755 			sfs->f_iosize = (user64_long_t)sp->f_iosize;
4756 			sfs->f_blocks = (user64_long_t)sp->f_blocks;
4757 			sfs->f_bfree = (user64_long_t)sp->f_bfree;
4758 			sfs->f_bavail = (user64_long_t)sp->f_bavail;
4759 			sfs->f_files = (user64_long_t)sp->f_files;
4760 			sfs->f_ffree = (user64_long_t)sp->f_ffree;
4761 			sfs->f_fsid = sp->f_fsid;
4762 			sfs->f_owner = sp->f_owner;
4763 			if (mp->mnt_kern_flag & MNTK_TYPENAME_OVERRIDE) {
4764 				strlcpy(&sfs->f_fstypename[0], &mp->fstypename_override[0], MFSNAMELEN);
4765 			} else {
4766 				strlcpy(sfs->f_fstypename, sp->f_fstypename, MFSNAMELEN);
4767 			}
4768 			strlcpy(sfs->f_mntonname, sp->f_mntonname, MNAMELEN);
4769 			strlcpy(sfs->f_mntfromname, sp->f_mntfromname, MNAMELEN);
4770 
4771 			error = SYSCTL_OUT(req, sfs, sizeof(*sfs));
4772 		} else {
4773 			struct user32_statfs *sfs = &sfsbuf->osfs32;
4774 			long temp;
4775 
4776 			bzero(sfs, sizeof(*sfs));
4777 			sfs->f_flags = mp->mnt_flag & MNT_VISFLAGMASK;
4778 			sfs->f_type = (short)mp->mnt_vtable->vfc_typenum;
4779 
4780 			/*
4781 			 * It's possible for there to be more than 2^^31 blocks in the filesystem, so we
4782 			 * have to fudge the numbers here in that case.   We inflate the blocksize in order
4783 			 * to reflect the filesystem size as best we can.
4784 			 */
4785 			if (sp->f_blocks > INT_MAX) {
4786 				int             shift;
4787 
4788 				/*
4789 				 * Work out how far we have to shift the block count down to make it fit.
4790 				 * Note that it's possible to have to shift so far that the resulting
4791 				 * blocksize would be unreportably large.  At that point, we will clip
4792 				 * any values that don't fit.
4793 				 *
4794 				 * For safety's sake, we also ensure that f_iosize is never reported as
4795 				 * being smaller than f_bsize.
4796 				 */
4797 				for (shift = 0; shift < 32; shift++) {
4798 					if ((sp->f_blocks >> shift) <= INT_MAX) {
4799 						break;
4800 					}
4801 					if ((((long long)sp->f_bsize) << (shift + 1)) > INT_MAX) {
4802 						break;
4803 					}
4804 				}
4805 #define __SHIFT_OR_CLIP(x, s)   ((((x) >> (s)) > INT_MAX) ? INT_MAX : ((x) >> (s)))
4806 				sfs->f_blocks = (user32_long_t)__SHIFT_OR_CLIP(sp->f_blocks, shift);
4807 				sfs->f_bfree = (user32_long_t)__SHIFT_OR_CLIP(sp->f_bfree, shift);
4808 				sfs->f_bavail = (user32_long_t)__SHIFT_OR_CLIP(sp->f_bavail, shift);
4809 #undef __SHIFT_OR_CLIP
4810 				sfs->f_bsize = (user32_long_t)(sp->f_bsize << shift);
4811 				temp = lmax(sp->f_iosize, sp->f_bsize);
4812 				if (temp > INT32_MAX) {
4813 					error = EINVAL;
4814 					kfree_type(typeof(*sfsbuf), sfsbuf);
4815 					goto out;
4816 				}
4817 				sfs->f_iosize = (user32_long_t)temp;
4818 			} else {
4819 				sfs->f_bsize = (user32_long_t)sp->f_bsize;
4820 				sfs->f_iosize = (user32_long_t)sp->f_iosize;
4821 				sfs->f_blocks = (user32_long_t)sp->f_blocks;
4822 				sfs->f_bfree = (user32_long_t)sp->f_bfree;
4823 				sfs->f_bavail = (user32_long_t)sp->f_bavail;
4824 			}
4825 			sfs->f_files = (user32_long_t)sp->f_files;
4826 			sfs->f_ffree = (user32_long_t)sp->f_ffree;
4827 			sfs->f_fsid = sp->f_fsid;
4828 			sfs->f_owner = sp->f_owner;
4829 
4830 			if (mp->mnt_kern_flag & MNTK_TYPENAME_OVERRIDE) {
4831 				strlcpy(&sfs->f_fstypename[0], &mp->fstypename_override[0], MFSNAMELEN);
4832 			} else {
4833 				strlcpy(sfs->f_fstypename, sp->f_fstypename, MFSNAMELEN);
4834 			}
4835 			strlcpy(sfs->f_mntonname, sp->f_mntonname, MNAMELEN);
4836 			strlcpy(sfs->f_mntfromname, sp->f_mntfromname, MNAMELEN);
4837 
4838 			error = SYSCTL_OUT(req, sfs, sizeof(*sfs));
4839 		}
4840 		kfree_type(typeof(*sfsbuf), sfsbuf);
4841 		break;
4842 	default:
4843 		error = ENOTSUP;
4844 		goto out;
4845 	}
4846 out:
4847 	if (gotref != 0) {
4848 		mount_iterdrop(mp);
4849 	}
4850 	return error;
4851 }
4852 
4853 static int      filt_fsattach(struct knote *kn, struct kevent_qos_s *kev);
4854 static void     filt_fsdetach(struct knote *kn);
4855 static int      filt_fsevent(struct knote *kn, long hint);
4856 static int      filt_fstouch(struct knote *kn, struct kevent_qos_s *kev);
4857 static int      filt_fsprocess(struct knote *kn, struct kevent_qos_s *kev);
4858 SECURITY_READ_ONLY_EARLY(struct filterops) fs_filtops = {
4859 	.f_attach = filt_fsattach,
4860 	.f_detach = filt_fsdetach,
4861 	.f_event = filt_fsevent,
4862 	.f_touch = filt_fstouch,
4863 	.f_process = filt_fsprocess,
4864 };
4865 
4866 static int
filt_fsattach(struct knote * kn,__unused struct kevent_qos_s * kev)4867 filt_fsattach(struct knote *kn, __unused struct kevent_qos_s *kev)
4868 {
4869 	kn->kn_flags |= EV_CLEAR; /* automatic */
4870 	kn->kn_sdata = 0;         /* incoming data is ignored */
4871 
4872 	lck_mtx_lock(&fs_klist_lock);
4873 	KNOTE_ATTACH(&fs_klist, kn);
4874 	lck_mtx_unlock(&fs_klist_lock);
4875 
4876 	/*
4877 	 * filter only sees future events,
4878 	 * so it can't be fired already.
4879 	 */
4880 	return 0;
4881 }
4882 
4883 static void
filt_fsdetach(struct knote * kn)4884 filt_fsdetach(struct knote *kn)
4885 {
4886 	lck_mtx_lock(&fs_klist_lock);
4887 	KNOTE_DETACH(&fs_klist, kn);
4888 	lck_mtx_unlock(&fs_klist_lock);
4889 }
4890 
4891 static int
filt_fsevent(struct knote * kn,long hint)4892 filt_fsevent(struct knote *kn, long hint)
4893 {
4894 	/*
4895 	 * Backwards compatibility:
4896 	 * Other filters would do nothing if kn->kn_sfflags == 0
4897 	 */
4898 
4899 	if ((kn->kn_sfflags == 0) || (kn->kn_sfflags & hint)) {
4900 		kn->kn_fflags |= hint;
4901 	}
4902 
4903 	return kn->kn_fflags != 0;
4904 }
4905 
4906 static int
filt_fstouch(struct knote * kn,struct kevent_qos_s * kev)4907 filt_fstouch(struct knote *kn, struct kevent_qos_s *kev)
4908 {
4909 	int res;
4910 
4911 	lck_mtx_lock(&fs_klist_lock);
4912 
4913 	kn->kn_sfflags = kev->fflags;
4914 
4915 	/*
4916 	 * the above filter function sets bits even if nobody is looking for them.
4917 	 * Just preserve those bits even in the new mask is more selective
4918 	 * than before.
4919 	 *
4920 	 * For compatibility with previous implementations, we leave kn_fflags
4921 	 * as they were before.
4922 	 */
4923 	//if (kn->kn_sfflags)
4924 	//	kn->kn_fflags &= kn->kn_sfflags;
4925 	res = (kn->kn_fflags != 0);
4926 
4927 	lck_mtx_unlock(&fs_klist_lock);
4928 
4929 	return res;
4930 }
4931 
4932 static int
filt_fsprocess(struct knote * kn,struct kevent_qos_s * kev)4933 filt_fsprocess(struct knote *kn, struct kevent_qos_s *kev)
4934 {
4935 	int res = 0;
4936 
4937 	lck_mtx_lock(&fs_klist_lock);
4938 	if (kn->kn_fflags) {
4939 		knote_fill_kevent(kn, kev, 0);
4940 		res = 1;
4941 	}
4942 	lck_mtx_unlock(&fs_klist_lock);
4943 	return res;
4944 }
4945 
4946 static int
sysctl_vfs_noremotehang(__unused struct sysctl_oid * oidp,__unused void * arg1,__unused int arg2,struct sysctl_req * req)4947 sysctl_vfs_noremotehang(__unused struct sysctl_oid *oidp,
4948     __unused void *arg1, __unused int arg2, struct sysctl_req *req)
4949 {
4950 	int out, error;
4951 	pid_t pid;
4952 	proc_t p;
4953 
4954 	/* We need a pid. */
4955 	if (req->newptr == USER_ADDR_NULL) {
4956 		return EINVAL;
4957 	}
4958 
4959 	error = SYSCTL_IN(req, &pid, sizeof(pid));
4960 	if (error) {
4961 		return error;
4962 	}
4963 
4964 	p = proc_find(pid < 0 ? -pid : pid);
4965 	if (p == NULL) {
4966 		return ESRCH;
4967 	}
4968 
4969 	/*
4970 	 * Fetching the value is ok, but we only fetch if the old
4971 	 * pointer is given.
4972 	 */
4973 	if (req->oldptr != USER_ADDR_NULL) {
4974 		out = !((p->p_flag & P_NOREMOTEHANG) == 0);
4975 		proc_rele(p);
4976 		error = SYSCTL_OUT(req, &out, sizeof(out));
4977 		return error;
4978 	}
4979 
4980 	/* cansignal offers us enough security. */
4981 	if (p != req->p && proc_suser(req->p) != 0) {
4982 		proc_rele(p);
4983 		return EPERM;
4984 	}
4985 
4986 	if (pid < 0) {
4987 		OSBitAndAtomic(~((uint32_t)P_NOREMOTEHANG), &p->p_flag);
4988 	} else {
4989 		OSBitOrAtomic(P_NOREMOTEHANG, &p->p_flag);
4990 	}
4991 	proc_rele(p);
4992 
4993 	return 0;
4994 }
4995 
4996 static int
4997 sysctl_vfs_generic_conf SYSCTL_HANDLER_ARGS
4998 {
4999 	int *name, namelen;
5000 	struct vfstable *vfsp;
5001 	struct vfsconf vfsc = {};
5002 
5003 	(void)oidp;
5004 	name = arg1;
5005 	namelen = arg2;
5006 
5007 	if (namelen < 1) {
5008 		return EISDIR;
5009 	} else if (namelen > 1) {
5010 		return ENOTDIR;
5011 	}
5012 
5013 	mount_list_lock();
5014 	for (vfsp = vfsconf; vfsp; vfsp = vfsp->vfc_next) {
5015 		if (vfsp->vfc_typenum == name[0]) {
5016 			break;
5017 		}
5018 	}
5019 
5020 	if (vfsp == NULL) {
5021 		mount_list_unlock();
5022 		return ENOTSUP;
5023 	}
5024 
5025 	vfsc.vfc_reserved1 = 0;
5026 	bcopy(vfsp->vfc_name, vfsc.vfc_name, sizeof(vfsc.vfc_name));
5027 	vfsc.vfc_typenum = vfsp->vfc_typenum;
5028 	vfsc.vfc_refcount = vfsp->vfc_refcount;
5029 	vfsc.vfc_flags = vfsp->vfc_flags;
5030 	vfsc.vfc_reserved2 = 0;
5031 	vfsc.vfc_reserved3 = 0;
5032 
5033 	mount_list_unlock();
5034 	return SYSCTL_OUT(req, &vfsc, sizeof(struct vfsconf));
5035 }
5036 
5037 /* the vfs.generic. branch. */
5038 SYSCTL_EXTENSIBLE_NODE(_vfs, VFS_GENERIC, generic,
5039     CTLFLAG_RW | CTLFLAG_LOCKED, NULL, "vfs generic hinge");
5040 /* retreive a list of mounted filesystem fsid_t */
5041 SYSCTL_PROC(_vfs_generic, OID_AUTO, vfsidlist,
5042     CTLTYPE_STRUCT | CTLFLAG_RD | CTLFLAG_LOCKED,
5043     NULL, 0, sysctl_vfs_vfslist, "S,fsid", "List of mounted filesystem ids");
5044 /* perform operations on filesystem via fsid_t */
5045 SYSCTL_NODE(_vfs_generic, OID_AUTO, ctlbyfsid, CTLFLAG_RW | CTLFLAG_LOCKED,
5046     sysctl_vfs_ctlbyfsid, "ctlbyfsid");
5047 SYSCTL_PROC(_vfs_generic, OID_AUTO, noremotehang, CTLFLAG_RW | CTLFLAG_ANYBODY,
5048     NULL, 0, sysctl_vfs_noremotehang, "I", "noremotehang");
5049 SYSCTL_INT(_vfs_generic, VFS_MAXTYPENUM, maxtypenum,
5050     CTLFLAG_RD | CTLFLAG_KERN | CTLFLAG_LOCKED,
5051     &maxvfstypenum, 0, "");
5052 SYSCTL_INT(_vfs_generic, OID_AUTO, sync_timeout, CTLFLAG_RW | CTLFLAG_LOCKED, &sync_timeout_seconds, 0, "");
5053 SYSCTL_NODE(_vfs_generic, VFS_CONF, conf,
5054     CTLFLAG_RD | CTLFLAG_LOCKED,
5055     sysctl_vfs_generic_conf, "");
5056 #if DEVELOPMENT || DEBUG
5057 SYSCTL_INT(_vfs_generic, OID_AUTO, print_busy_vnodes,
5058     CTLTYPE_INT | CTLFLAG_RW,
5059     &print_busy_vnodes, 0,
5060     "VFS log busy vnodes blocking unmount");
5061 #endif
5062 
5063 /* Indicate that the root file system unmounted cleanly */
5064 static int vfs_root_unmounted_cleanly = 0;
5065 SYSCTL_INT(_vfs_generic, OID_AUTO, root_unmounted_cleanly, CTLFLAG_RD, &vfs_root_unmounted_cleanly, 0, "Root filesystem was unmounted cleanly");
5066 
5067 void
vfs_set_root_unmounted_cleanly(void)5068 vfs_set_root_unmounted_cleanly(void)
5069 {
5070 	vfs_root_unmounted_cleanly = 1;
5071 }
5072 
5073 /*
5074  * Print vnode state.
5075  */
5076 void
vn_print_state(struct vnode * vp,const char * fmt,...)5077 vn_print_state(struct vnode *vp, const char *fmt, ...)
5078 {
5079 	va_list ap;
5080 	char perm_str[] = "(VM_KERNEL_ADDRPERM pointer)";
5081 	char fs_name[MFSNAMELEN];
5082 
5083 	va_start(ap, fmt);
5084 	vprintf(fmt, ap);
5085 	va_end(ap);
5086 	printf("vp 0x%0llx %s: ", (uint64_t)VM_KERNEL_ADDRPERM(vp), perm_str);
5087 	printf("tag %d, type %d\n", vp->v_tag, vp->v_type);
5088 	/* Counts .. */
5089 	printf("    iocount %d, usecount %d, kusecount %d references %d\n",
5090 	    vp->v_iocount, vp->v_usecount, vp->v_kusecount, vp->v_references);
5091 	printf("    writecount %d, numoutput %d\n", vp->v_writecount,
5092 	    vp->v_numoutput);
5093 	/* Flags */
5094 	printf("    flag 0x%x, lflag 0x%x, listflag 0x%x\n", vp->v_flag,
5095 	    vp->v_lflag, vp->v_listflag);
5096 
5097 	if (vp->v_mount == NULL || vp->v_mount == dead_mountp) {
5098 		strlcpy(fs_name, "deadfs", MFSNAMELEN);
5099 	} else {
5100 		vfs_name(vp->v_mount, fs_name);
5101 	}
5102 
5103 	printf("    v_data 0x%0llx %s\n",
5104 	    (vp->v_data ? (uint64_t)VM_KERNEL_ADDRPERM(vp->v_data) : 0),
5105 	    perm_str);
5106 	printf("    v_mount 0x%0llx %s vfs_name %s\n",
5107 	    (vp->v_mount ? (uint64_t)VM_KERNEL_ADDRPERM(vp->v_mount) : 0),
5108 	    perm_str, fs_name);
5109 }
5110 
5111 long num_reusedvnodes = 0;
5112 
5113 
5114 static vnode_t
process_vp(vnode_t vp,int want_vp,bool can_defer,int * deferred)5115 process_vp(vnode_t vp, int want_vp, bool can_defer, int *deferred)
5116 {
5117 	unsigned int  vpid;
5118 
5119 	*deferred = 0;
5120 
5121 	vpid = vp->v_id;
5122 
5123 	vnode_list_remove_locked(vp);
5124 
5125 	vnode_hold(vp);
5126 	vnode_list_unlock();
5127 
5128 	vnode_lock_spin(vp);
5129 
5130 	/*
5131 	 * We could wait for the vnode_lock after removing the vp from the freelist
5132 	 * and the vid is bumped only at the very end of reclaim. So it is  possible
5133 	 * that we are looking at a vnode that is being terminated. If so skip it.
5134 	 */
5135 	if ((vpid != vp->v_id) || (vp->v_usecount != 0) || (vp->v_iocount != 0) ||
5136 	    VONLIST(vp) || (vp->v_lflag & VL_TERMINATE)) {
5137 		/*
5138 		 * we lost the race between dropping the list lock
5139 		 * and picking up the vnode_lock... someone else
5140 		 * used this vnode and it is now in a new state
5141 		 */
5142 		vnode_drop_and_unlock(vp);
5143 
5144 		return NULLVP;
5145 	}
5146 	if ((vp->v_lflag & (VL_NEEDINACTIVE | VL_MARKTERM)) == VL_NEEDINACTIVE) {
5147 		/*
5148 		 * we did a vnode_rele_ext that asked for
5149 		 * us not to reenter the filesystem during
5150 		 * the release even though VL_NEEDINACTIVE was
5151 		 * set... we'll do it here by doing a
5152 		 * vnode_get/vnode_put
5153 		 *
5154 		 * pick up an iocount so that we can call
5155 		 * vnode_put and drive the VNOP_INACTIVE...
5156 		 * vnode_put will either leave us off
5157 		 * the freelist if a new ref comes in,
5158 		 * or put us back on the end of the freelist
5159 		 * or recycle us if we were marked for termination...
5160 		 * so we'll just go grab a new candidate
5161 		 */
5162 		vp->v_iocount++;
5163 #ifdef CONFIG_IOCOUNT_TRACE
5164 		record_vp(vp, 1);
5165 #endif
5166 		vnode_put_locked(vp);
5167 		vnode_drop_and_unlock(vp);
5168 
5169 		return NULLVP;
5170 	}
5171 	/*
5172 	 * Checks for anyone racing us for recycle
5173 	 */
5174 	if (vp->v_type != VBAD) {
5175 		if ((want_vp || can_defer) && (vnode_on_reliable_media(vp) == FALSE || (vp->v_flag & VISDIRTY))) {
5176 			vnode_async_list_add(vp);
5177 			vnode_drop_and_unlock(vp);
5178 
5179 			*deferred = 1;
5180 
5181 			return NULLVP;
5182 		}
5183 		if (vp->v_lflag & VL_DEAD) {
5184 			panic("new_vnode(%p): the vnode is VL_DEAD but not VBAD", vp);
5185 		}
5186 
5187 		vnode_lock_convert(vp);
5188 		(void)vnode_reclaim_internal(vp, 1, want_vp, 0);
5189 
5190 		if (want_vp) {
5191 			if ((VONLIST(vp))) {
5192 				panic("new_vnode(%p): vp on list", vp);
5193 			}
5194 			if (vp->v_usecount || vp->v_iocount || vp->v_kusecount ||
5195 			    (vp->v_lflag & (VNAMED_UBC | VNAMED_MOUNT | VNAMED_FSHASH))) {
5196 				panic("new_vnode(%p): free vnode still referenced", vp);
5197 			}
5198 			if ((vp->v_mntvnodes.tqe_prev != 0) && (vp->v_mntvnodes.tqe_next != 0)) {
5199 				panic("new_vnode(%p): vnode seems to be on mount list", vp);
5200 			}
5201 			if (!LIST_EMPTY(&vp->v_nclinks) || !TAILQ_EMPTY(&vp->v_ncchildren)) {
5202 				panic("new_vnode(%p): vnode still hooked into the name cache", vp);
5203 			}
5204 		} else {
5205 			vnode_drop_and_unlock(vp);
5206 			vp = NULLVP;
5207 		}
5208 	}
5209 	return vp;
5210 }
5211 
5212 __attribute__((noreturn))
5213 static void
async_work_continue(void)5214 async_work_continue(void)
5215 {
5216 	struct async_work_lst *q;
5217 	int     deferred;
5218 	vnode_t vp;
5219 
5220 	q = &vnode_async_work_list;
5221 
5222 	for (;;) {
5223 		vnode_list_lock();
5224 
5225 		if (TAILQ_EMPTY(q)) {
5226 			assert_wait(q, (THREAD_UNINT));
5227 
5228 			vnode_list_unlock();
5229 
5230 			thread_block((thread_continue_t)async_work_continue);
5231 
5232 			continue;
5233 		}
5234 		async_work_handled++;
5235 
5236 		vp = TAILQ_FIRST(q);
5237 
5238 		vp = process_vp(vp, 0, false, &deferred);
5239 
5240 		if (vp != NULLVP) {
5241 			panic("found VBAD vp (%p) on async queue", vp);
5242 		}
5243 	}
5244 }
5245 
5246 __attribute__((noreturn))
5247 static void
vn_laundry_continue(void)5248 vn_laundry_continue(void)
5249 {
5250 	struct freelst *free_q;
5251 	struct ragelst *rage_q;
5252 	vnode_t vp;
5253 	int deferred;
5254 	bool rage_q_empty;
5255 	bool free_q_empty;
5256 
5257 
5258 	free_q = &vnode_free_list;
5259 	rage_q = &vnode_rage_list;
5260 
5261 	for (;;) {
5262 		vnode_list_lock();
5263 
5264 		if (!TAILQ_EMPTY(&vnode_async_work_list)) {
5265 			vp = TAILQ_FIRST(&vnode_async_work_list);
5266 			async_work_handled++;
5267 
5268 			vp = process_vp(vp, 0, false, &deferred);
5269 
5270 			if (vp != NULLVP) {
5271 				panic("found VBAD vp (%p) on async queue", vp);
5272 			}
5273 			continue;
5274 		}
5275 
5276 		free_q_empty = TAILQ_EMPTY(free_q);
5277 		rage_q_empty = TAILQ_EMPTY(rage_q);
5278 
5279 		if (!rage_q_empty && !free_q_empty) {
5280 			struct timeval current_tv;
5281 
5282 			microuptime(&current_tv);
5283 			if (ragevnodes < rage_limit &&
5284 			    ((current_tv.tv_sec - rage_tv.tv_sec) < RAGE_TIME_LIMIT)) {
5285 				rage_q_empty = true;
5286 			}
5287 		}
5288 
5289 		if (numvnodes < numvnodes_min || (rage_q_empty && free_q_empty) ||
5290 		    (reusablevnodes <= reusablevnodes_max && deadvnodes >= deadvnodes_high)) {
5291 			assert_wait(free_q, (THREAD_UNINT));
5292 
5293 			vnode_list_unlock();
5294 
5295 			thread_block((thread_continue_t)vn_laundry_continue);
5296 
5297 			continue;
5298 		}
5299 
5300 		if (!rage_q_empty) {
5301 			vp = TAILQ_FIRST(rage_q);
5302 		} else {
5303 			vp = TAILQ_FIRST(free_q);
5304 		}
5305 
5306 		vp = process_vp(vp, 0, false, &deferred);
5307 
5308 		if (vp != NULLVP) {
5309 			/* If process_vp returns a vnode, it is locked and has a holdcount */
5310 			vnode_drop_and_unlock(vp);
5311 			vp = NULLVP;
5312 		}
5313 	}
5314 }
5315 
5316 static inline void
wakeup_laundry_thread()5317 wakeup_laundry_thread()
5318 {
5319 	if (deadvnodes_noreuse || (numvnodes >= numvnodes_min && deadvnodes < deadvnodes_low &&
5320 	    (reusablevnodes > reusablevnodes_max || numvnodes >= desiredvnodes))) {
5321 		wakeup(&vnode_free_list);
5322 	}
5323 }
5324 
5325 static int
new_vnode(vnode_t * vpp,bool can_free)5326 new_vnode(vnode_t *vpp, bool can_free)
5327 {
5328 	long force_alloc_min;
5329 	vnode_t vp;
5330 	uint32_t retries = 0, max_retries = 100;                /* retry incase of tablefull */
5331 	uint32_t bdevvp_vnodes = 0;
5332 	int force_alloc = 0, walk_count = 0;
5333 	boolean_t need_reliable_vp = FALSE;
5334 	int deferred;
5335 	struct timeval initial_tv;
5336 	struct timeval current_tv;
5337 	proc_t  curproc = current_proc();
5338 	bool force_alloc_freeable = false;
5339 
5340 	if (vn_dealloc_level == DEALLOC_VNODE_NONE) {
5341 		can_free = false;
5342 	}
5343 
5344 	initial_tv.tv_sec = 0;
5345 retry:
5346 	vp = NULLVP;
5347 
5348 	vnode_list_lock();
5349 	newvnode++;
5350 
5351 	if (need_reliable_vp == TRUE) {
5352 		async_work_timed_out++;
5353 	}
5354 
5355 	/*
5356 	 * The vnode list lock was dropped after force_alloc_freeable was set,
5357 	 * reevaluate.
5358 	 */
5359 	force_alloc_min = MAX(desiredvnodes, numvnodes_min);
5360 	if (force_alloc_freeable &&
5361 	    (numvnodes < force_alloc_min || numvnodes >= numvnodes_max)) {
5362 		force_alloc_freeable = false;
5363 	}
5364 
5365 	if (((numvnodes - deadvnodes + deadvnodes_noreuse) < desiredvnodes) ||
5366 	    force_alloc || force_alloc_freeable) {
5367 		struct timespec ts;
5368 		uint32_t vflag = 0;
5369 
5370 		/*
5371 		 * Can always reuse a dead one except if it is in the process of
5372 		 * being freed or the FS cannot handle freeable vnodes.
5373 		 */
5374 		if (!TAILQ_EMPTY(&vnode_dead_list)) {
5375 			/* Select an appropriate deadvnode */
5376 			if (numvnodes <= numvnodes_min || !can_free) {
5377 				/* all vnodes upto numvnodes_min are not freeable */
5378 				vp = TAILQ_FIRST(&vnode_dead_list);
5379 				if (numvnodes > numvnodes_min &&
5380 				    (vp->v_flag & VCANDEALLOC)) {
5381 					/*
5382 					 * Freeable vnodes are added to the
5383 					 * back of the queue, so if the first
5384 					 * from the front is freeable, then
5385 					 * there are none on the dead list.
5386 					 */
5387 					vp = NULLVP;
5388 				}
5389 			} else {
5390 				/*
5391 				 * Filesystems which opt in to freeable vnodes
5392 				 * can get either one.
5393 				 */
5394 				TAILQ_FOREACH_REVERSE(vp, &vnode_dead_list,
5395 				    deadlst, v_freelist) {
5396 					if (!(vp->v_listflag & VLIST_NO_REUSE)) {
5397 						break;
5398 					}
5399 				}
5400 			}
5401 
5402 			if (vp) {
5403 				force_alloc_freeable = false;
5404 				goto steal_this_vp;
5405 			}
5406 		}
5407 
5408 		/*
5409 		 * no dead vnodes available... if we're under
5410 		 * the limit, we'll create a new vnode
5411 		 */
5412 		numvnodes++;
5413 		if (force_alloc) {
5414 			numvnodes_min++;
5415 		} else if (can_free && (numvnodes > numvnodes_min)) {
5416 			allocedvnodes++;
5417 			freeablevnodes++;
5418 			vflag = VCANDEALLOC;
5419 		}
5420 		vnode_list_unlock();
5421 
5422 		vp = zalloc_flags(vnode_zone, Z_WAITOK | Z_ZERO);
5423 		VLISTNONE(vp);          /* avoid double queue removal */
5424 		lck_mtx_init(&vp->v_lock, &vnode_lck_grp, &vnode_lck_attr);
5425 
5426 		TAILQ_INIT(&vp->v_ncchildren);
5427 
5428 		klist_init(&vp->v_knotes);
5429 		nanouptime(&ts);
5430 		vp->v_id = (uint32_t)ts.tv_nsec;
5431 		vp->v_flag = VSTANDARD | vflag;
5432 		if (force_alloc_freeable) {
5433 			/* This vnode should be recycled and freed immediately */
5434 			vp->v_lflag = VL_MARKTERM;
5435 			vp->v_listflag = VLIST_NO_REUSE;
5436 		}
5437 
5438 		if (vflag & VCANDEALLOC) {
5439 			os_atomic_inc(&busyvnodes, relaxed);
5440 		}
5441 
5442 #if CONFIG_MACF
5443 		if (mac_vnode_label_init_needed(vp)) {
5444 			mac_vnode_label_init(vp);
5445 		}
5446 #endif /* MAC */
5447 
5448 #if CONFIG_IOCOUNT_TRACE
5449 		if (__improbable(bootarg_vnode_iocount_trace)) {
5450 			vp->v_iocount_trace = (vnode_iocount_trace_t)zalloc_permanent(
5451 				IOCOUNT_TRACE_MAX_TYPES * sizeof(struct vnode_iocount_trace),
5452 				ZALIGN(struct vnode_iocount_trace));
5453 		}
5454 #endif /* CONFIG_IOCOUNT_TRACE */
5455 
5456 #if CONFIG_FILE_LEASES
5457 		LIST_INIT(&vp->v_leases);
5458 #endif
5459 
5460 		vp->v_iocount = 1;
5461 
5462 		goto done;
5463 	}
5464 
5465 	microuptime(&current_tv);
5466 
5467 #define MAX_WALK_COUNT 1000
5468 
5469 	if (!TAILQ_EMPTY(&vnode_rage_list) &&
5470 	    (ragevnodes >= rage_limit ||
5471 	    (current_tv.tv_sec - rage_tv.tv_sec) >= RAGE_TIME_LIMIT)) {
5472 		TAILQ_FOREACH(vp, &vnode_rage_list, v_freelist) {
5473 			if (!(vp->v_listflag & VLIST_RAGE)) {
5474 				panic("new_vnode: vp (%p) on RAGE list not marked VLIST_RAGE", vp);
5475 			}
5476 
5477 			// if we're a dependency-capable process, skip vnodes that can
5478 			// cause recycling deadlocks. (i.e. this process is diskimages
5479 			// helper and the vnode is in a disk image).  Querying the
5480 			// mnt_kern_flag for the mount's virtual device status
5481 			// is safer than checking the mnt_dependent_process, which
5482 			// may not be updated if there are multiple devnode layers
5483 			// in between the disk image and the final consumer.
5484 
5485 			if (((curproc->p_flag & P_DEPENDENCY_CAPABLE) == 0 || vp->v_mount == NULL ||
5486 			    (vp->v_mount->mnt_kern_flag & MNTK_VIRTUALDEV) == 0) &&
5487 			    !(vp->v_listflag & VLIST_NO_REUSE) &&
5488 			    (can_free || !(vp->v_flag & VCANDEALLOC))) {
5489 				/*
5490 				 * if need_reliable_vp == TRUE, then we've already sent one or more
5491 				 * non-reliable vnodes to the async thread for processing and timed
5492 				 * out waiting for a dead vnode to show up.  Use the MAX_WALK_COUNT
5493 				 * mechanism to first scan for a reliable vnode before forcing
5494 				 * a new vnode to be created
5495 				 */
5496 				if (need_reliable_vp == FALSE || vnode_on_reliable_media(vp) == TRUE) {
5497 					break;
5498 				}
5499 			}
5500 
5501 			// don't iterate more than MAX_WALK_COUNT vnodes to
5502 			// avoid keeping the vnode list lock held for too long.
5503 
5504 			if (walk_count++ > MAX_WALK_COUNT) {
5505 				vp = NULL;
5506 				break;
5507 			}
5508 		}
5509 	}
5510 
5511 	if (vp == NULL && !TAILQ_EMPTY(&vnode_free_list)) {
5512 		/*
5513 		 * Pick the first vp for possible reuse
5514 		 */
5515 		walk_count = 0;
5516 		TAILQ_FOREACH(vp, &vnode_free_list, v_freelist) {
5517 			// if we're a dependency-capable process, skip vnodes that can
5518 			// cause recycling deadlocks. (i.e. this process is diskimages
5519 			// helper and the vnode is in a disk image).  Querying the
5520 			// mnt_kern_flag for the mount's virtual device status
5521 			// is safer than checking the mnt_dependent_process, which
5522 			// may not be updated if there are multiple devnode layers
5523 			// in between the disk image and the final consumer.
5524 
5525 			if (((curproc->p_flag & P_DEPENDENCY_CAPABLE) == 0 || vp->v_mount == NULL ||
5526 			    (vp->v_mount->mnt_kern_flag & MNTK_VIRTUALDEV) == 0) &&
5527 			    !(vp->v_listflag & VLIST_NO_REUSE) &&
5528 			    (can_free || !(vp->v_flag & VCANDEALLOC))) {
5529 				/*
5530 				 * if need_reliable_vp == TRUE, then we've already sent one or more
5531 				 * non-reliable vnodes to the async thread for processing and timed
5532 				 * out waiting for a dead vnode to show up.  Use the MAX_WALK_COUNT
5533 				 * mechanism to first scan for a reliable vnode before forcing
5534 				 * a new vnode to be created
5535 				 */
5536 				if (need_reliable_vp == FALSE || vnode_on_reliable_media(vp) == TRUE) {
5537 					break;
5538 				}
5539 			}
5540 
5541 			// don't iterate more than MAX_WALK_COUNT vnodes to
5542 			// avoid keeping the vnode list lock held for too long.
5543 
5544 			if (walk_count++ > MAX_WALK_COUNT) {
5545 				vp = NULL;
5546 				break;
5547 			}
5548 		}
5549 	}
5550 
5551 	//
5552 	// if we don't have a vnode and the walk_count is >= MAX_WALK_COUNT
5553 	// then we're trying to create a vnode on behalf of a
5554 	// process like diskimages-helper that has file systems
5555 	// mounted on top of itself (and thus we can't reclaim
5556 	// vnodes in the file systems on top of us).  if we can't
5557 	// find a vnode to reclaim then we'll just have to force
5558 	// the allocation.
5559 	//
5560 	if (vp == NULL && walk_count >= MAX_WALK_COUNT) {
5561 		force_alloc = 1;
5562 		vnode_list_unlock();
5563 		goto retry;
5564 	}
5565 
5566 	if (vp == NULL) {
5567 		if (can_free && (vn_dealloc_level > DEALLOC_VNODE_NONE) &&
5568 		    (numvnodes >= force_alloc_min) && (numvnodes < numvnodes_max)) {
5569 			force_alloc_freeable = true;
5570 			vnode_list_unlock();
5571 			goto retry;
5572 		}
5573 
5574 		/*
5575 		 * we've reached the system imposed maximum number of vnodes
5576 		 * but there isn't a single one available
5577 		 * wait a bit and then retry... if we can't get a vnode
5578 		 * after our target number of retries, than log a complaint
5579 		 */
5580 		if (++retries <= max_retries) {
5581 			vnode_list_unlock();
5582 			delay_for_interval(1, 1000 * 1000);
5583 			goto retry;
5584 		}
5585 
5586 		vnode_list_unlock();
5587 		tablefull("vnode");
5588 		log(LOG_EMERG, "%d desired, %ld numvnodes, "
5589 		    "%ld free, %ld dead, %ld async, %d rage %d bdevvp\n",
5590 		    desiredvnodes, numvnodes, freevnodes, deadvnodes, async_work_vnodes, ragevnodes, bdevvp_vnodes);
5591 #if CONFIG_JETSAM
5592 
5593 #if DEVELOPMENT || DEBUG
5594 		if (bootarg_no_vnode_jetsam) {
5595 			panic("vnode table is full");
5596 		}
5597 #endif /* DEVELOPMENT || DEBUG */
5598 
5599 		/*
5600 		 * Running out of vnodes tends to make a system unusable. Start killing
5601 		 * processes that jetsam knows are killable.
5602 		 */
5603 		if (memorystatus_kill_on_vnode_limit() == FALSE) {
5604 			/*
5605 			 * If jetsam can't find any more processes to kill and there
5606 			 * still aren't any free vnodes, panic. Hopefully we'll get a
5607 			 * panic log to tell us why we ran out.
5608 			 */
5609 			panic("vnode table is full");
5610 		}
5611 
5612 		/*
5613 		 * Now that we've killed someone, wait a bit and continue looking
5614 		 * (with fewer retries before trying another kill).
5615 		 */
5616 		delay_for_interval(3, 1000 * 1000);
5617 		retries = 0;
5618 		max_retries = 10;
5619 		goto retry;
5620 #endif
5621 
5622 		*vpp = NULL;
5623 		return ENFILE;
5624 	}
5625 	newvnode_nodead++;
5626 steal_this_vp:
5627 	if ((vp = process_vp(vp, 1, true, &deferred)) == NULLVP) {
5628 		if (deferred) {
5629 			int     elapsed_msecs;
5630 			struct timeval elapsed_tv;
5631 
5632 			if (initial_tv.tv_sec == 0) {
5633 				microuptime(&initial_tv);
5634 			}
5635 
5636 			vnode_list_lock();
5637 
5638 			dead_vnode_waited++;
5639 			dead_vnode_wanted++;
5640 
5641 			/*
5642 			 * note that we're only going to explicitly wait 10ms
5643 			 * for a dead vnode to become available, since even if one
5644 			 * isn't available, a reliable vnode might now be available
5645 			 * at the head of the VRAGE or free lists... if so, we
5646 			 * can satisfy the new_vnode request with less latency then waiting
5647 			 * for the full 100ms duration we're ultimately willing to tolerate
5648 			 */
5649 			assert_wait_timeout((caddr_t)&dead_vnode_wanted, (THREAD_INTERRUPTIBLE), 10000, NSEC_PER_USEC);
5650 
5651 			vnode_list_unlock();
5652 
5653 			thread_block(THREAD_CONTINUE_NULL);
5654 
5655 			microuptime(&elapsed_tv);
5656 
5657 			timevalsub(&elapsed_tv, &initial_tv);
5658 			elapsed_msecs = (int)(elapsed_tv.tv_sec * 1000 + elapsed_tv.tv_usec / 1000);
5659 
5660 			if (elapsed_msecs >= 100) {
5661 				/*
5662 				 * we've waited long enough... 100ms is
5663 				 * somewhat arbitrary for this case, but the
5664 				 * normal worst case latency used for UI
5665 				 * interaction is 100ms, so I've chosen to
5666 				 * go with that.
5667 				 *
5668 				 * setting need_reliable_vp to TRUE
5669 				 * forces us to find a reliable vnode
5670 				 * that we can process synchronously, or
5671 				 * to create a new one if the scan for
5672 				 * a reliable one hits the scan limit
5673 				 */
5674 				need_reliable_vp = TRUE;
5675 			}
5676 		}
5677 		goto retry;
5678 	}
5679 	OSAddAtomicLong(1, &num_reusedvnodes);
5680 
5681 
5682 #if CONFIG_MACF
5683 	/*
5684 	 * We should never see VL_LABELWAIT or VL_LABEL here.
5685 	 * as those operations hold a reference.
5686 	 */
5687 	assert((vp->v_lflag & VL_LABELWAIT) != VL_LABELWAIT);
5688 	assert((vp->v_lflag & VL_LABEL) != VL_LABEL);
5689 	if (vp->v_lflag & VL_LABELED || mac_vnode_label(vp) != NULL) {
5690 		vnode_lock_convert(vp);
5691 		mac_vnode_label_recycle(vp);
5692 	} else if (mac_vnode_label_init_needed(vp)) {
5693 		vnode_lock_convert(vp);
5694 		mac_vnode_label_init(vp);
5695 	}
5696 
5697 #endif /* MAC */
5698 
5699 	vp->v_iocount = 1;
5700 	vp->v_lflag = 0;
5701 	vp->v_writecount = 0;
5702 	vp->v_references = 0;
5703 	vp->v_iterblkflags = 0;
5704 	if (can_free && (vp->v_flag & VCANDEALLOC)) {
5705 		vp->v_flag = VSTANDARD | VCANDEALLOC;
5706 	} else {
5707 		vp->v_flag = VSTANDARD;
5708 	}
5709 
5710 	/* vbad vnodes can point to dead_mountp */
5711 	vp->v_mount = NULL;
5712 	vp->v_defer_reclaimlist = (vnode_t)0;
5713 
5714 	/* process_vp returns a locked vnode with a holdcount */
5715 	vnode_drop_and_unlock(vp);
5716 
5717 done:
5718 	*vpp = vp;
5719 
5720 	return 0;
5721 }
5722 
5723 void
vnode_lock(vnode_t vp)5724 vnode_lock(vnode_t vp)
5725 {
5726 	lck_mtx_lock(&vp->v_lock);
5727 }
5728 
5729 void
vnode_lock_spin(vnode_t vp)5730 vnode_lock_spin(vnode_t vp)
5731 {
5732 	lck_mtx_lock_spin(&vp->v_lock);
5733 }
5734 
5735 void
vnode_unlock(vnode_t vp)5736 vnode_unlock(vnode_t vp)
5737 {
5738 	lck_mtx_unlock(&vp->v_lock);
5739 }
5740 
5741 void
vnode_hold(vnode_t vp)5742 vnode_hold(vnode_t vp)
5743 {
5744 	int32_t old_holdcount = os_atomic_inc_orig(&vp->v_holdcount, relaxed);
5745 
5746 	if (old_holdcount == INT32_MAX) {
5747 		/*
5748 		 * Because we allow atomic ops on the holdcount it is
5749 		 * possible that when the vnode is examined, its holdcount
5750 		 * is different than what will be printed in this
5751 		 * panic message.
5752 		 */
5753 		panic("%s: vp %p holdcount overflow from : %d v_tag = %d, v_type = %d, v_flag = %x.",
5754 		    __FUNCTION__, vp, old_holdcount, vp->v_tag, vp->v_type, vp->v_flag);
5755 	}
5756 }
5757 
5758 static vnode_t
vnode_drop_internal(vnode_t vp,bool locked)5759 vnode_drop_internal(vnode_t vp, bool locked)
5760 {
5761 	int32_t old_holdcount = os_atomic_dec_orig(&vp->v_holdcount, relaxed);
5762 
5763 	if (old_holdcount < 1) {
5764 		if (locked) {
5765 			vnode_unlock(vp);
5766 		}
5767 
5768 		/*
5769 		 * Because we allow atomic ops on the holdcount it is possible
5770 		 * that when the vnode is examined, its holdcount is different
5771 		 * than what will be printed in this panic message.
5772 		 */
5773 		panic("%s : vp %p holdcount -ve: %d.  v_tag = %d, v_type = %d, v_flag = %x.",
5774 		    __FUNCTION__, vp, old_holdcount - 1, vp->v_tag, vp->v_type, vp->v_flag);
5775 	}
5776 
5777 	if (vn_dealloc_level == DEALLOC_VNODE_NONE || old_holdcount > 1 ||
5778 	    !(vp->v_flag & VCANDEALLOC) || !(vp->v_lflag & VL_DEAD)) {
5779 		if (locked) {
5780 			vnode_unlock(vp);
5781 		}
5782 		return vp;
5783 	}
5784 
5785 	if (!locked) {
5786 		vnode_lock(vp);
5787 	}
5788 
5789 	if ((os_atomic_load(&vp->v_holdcount, relaxed) != 0) || vp->v_iocount ||
5790 	    vp->v_usecount || !(vp->v_flag & VCANDEALLOC) || !(vp->v_lflag & VL_DEAD)) {
5791 		vnode_unlock(vp);
5792 		return vp;
5793 	}
5794 
5795 	vnode_list_lock();
5796 
5797 	/*
5798 	 * the v_listflag field is protected by the vnode_list_lock
5799 	 */
5800 	if ((os_atomic_load(&vp->v_holdcount, relaxed) == 0) && VONLIST(vp) &&
5801 	    (vp->v_listflag & VLIST_DEAD) &&
5802 	    (numvnodes > desiredvnodes || (vp->v_listflag & VLIST_NO_REUSE) ||
5803 	    vn_dealloc_level != DEALLOC_VNODE_ALL || deadvnodes >= deadvnodes_high)) {
5804 		VREMDEAD("vnode_list_remove", vp);
5805 		numvnodes--;
5806 		freeablevnodes--;
5807 		deallocedvnodes++;
5808 		vp->v_listflag = 0;
5809 		vnode_list_unlock();
5810 
5811 #if CONFIG_MACF
5812 		struct label *tmpl = mac_vnode_label(vp);
5813 		vp->v_label = NULL;
5814 #endif /* CONFIG_MACF */
5815 
5816 		vnode_unlock(vp);
5817 
5818 #if CONFIG_MACF
5819 		if (tmpl) {
5820 			mac_vnode_label_free(tmpl);
5821 		}
5822 #endif /* CONFIG_MACF */
5823 
5824 		zfree(vnode_zone, vp);
5825 		vp = NULLVP;
5826 	} else {
5827 		vnode_list_unlock();
5828 		vnode_unlock(vp);
5829 	}
5830 
5831 	return vp;
5832 }
5833 
5834 vnode_t
vnode_drop_and_unlock(vnode_t vp)5835 vnode_drop_and_unlock(vnode_t vp)
5836 {
5837 	return vnode_drop_internal(vp, true);
5838 }
5839 
5840 vnode_t
vnode_drop(vnode_t vp)5841 vnode_drop(vnode_t vp)
5842 {
5843 	return vnode_drop_internal(vp, false);
5844 }
5845 
5846 SYSCTL_NODE(_vfs, OID_AUTO, vnstats, CTLFLAG_RD | CTLFLAG_LOCKED, NULL, "vfs vnode stats");
5847 
5848 SYSCTL_COMPAT_INT(_vfs_vnstats, OID_AUTO, vn_dealloc_level,
5849     CTLFLAG_RD | CTLFLAG_LOCKED,
5850     &vn_dealloc_level, 0, "");
5851 SYSCTL_COMPAT_INT(_vfs_vnstats, OID_AUTO, desired_vnodes,
5852     CTLFLAG_RD | CTLFLAG_LOCKED,
5853     &desiredvnodes, 0, "");
5854 SYSCTL_LONG(_vfs_vnstats, OID_AUTO, num_vnodes,
5855     CTLFLAG_RD | CTLFLAG_LOCKED,
5856     &numvnodes, "");
5857 SYSCTL_COMPAT_INT(_vfs_vnstats, OID_AUTO, num_deallocable_vnodes,
5858     CTLFLAG_RD | CTLFLAG_LOCKED,
5859     &freeablevnodes, 0, "");
5860 SYSCTL_LONG(_vfs_vnstats, OID_AUTO, num_deallocable_busy_vnodes,
5861     CTLFLAG_RD | CTLFLAG_LOCKED,
5862     &busyvnodes, "");
5863 SYSCTL_LONG(_vfs_vnstats, OID_AUTO, num_dead_vnodes,
5864     CTLFLAG_RD | CTLFLAG_LOCKED,
5865     &deadvnodes, "");
5866 SYSCTL_LONG(_vfs_vnstats, OID_AUTO, num_dead_vnodes_to_dealloc,
5867     CTLFLAG_RD | CTLFLAG_LOCKED,
5868     &deadvnodes_noreuse, "");
5869 SYSCTL_LONG(_vfs_vnstats, OID_AUTO, num_async_work_vnodes,
5870     CTLFLAG_RD | CTLFLAG_LOCKED,
5871     &async_work_vnodes, "");
5872 SYSCTL_COMPAT_INT(_vfs_vnstats, OID_AUTO, num_rapid_aging_vnodes,
5873     CTLFLAG_RD | CTLFLAG_LOCKED,
5874     &ragevnodes, 0, "");
5875 SYSCTL_LONG(_vfs_vnstats, OID_AUTO, num_free_vnodes,
5876     CTLFLAG_RD | CTLFLAG_LOCKED,
5877     &freevnodes, "");
5878 SYSCTL_LONG(_vfs_vnstats, OID_AUTO, num_recycledvnodes,
5879     CTLFLAG_RD | CTLFLAG_LOCKED,
5880     &num_recycledvnodes, "");
5881 SYSCTL_QUAD(_vfs_vnstats, OID_AUTO, num_allocedvnodes,
5882     CTLFLAG_RD | CTLFLAG_LOCKED,
5883     &allocedvnodes, "");
5884 SYSCTL_QUAD(_vfs_vnstats, OID_AUTO, num_deallocedvnodes,
5885     CTLFLAG_RD | CTLFLAG_LOCKED,
5886     &deallocedvnodes, "");
5887 SYSCTL_QUAD(_vfs_vnstats, OID_AUTO, num_newvnode_calls,
5888     CTLFLAG_RD | CTLFLAG_LOCKED,
5889     &newvnode, "");
5890 SYSCTL_QUAD(_vfs_vnstats, OID_AUTO, num_newvnode_calls_nodead,
5891     CTLFLAG_RD | CTLFLAG_LOCKED,
5892     &newvnode_nodead, "");
5893 
5894 int
vnode_get(struct vnode * vp)5895 vnode_get(struct vnode *vp)
5896 {
5897 	int retval;
5898 
5899 	vnode_lock_spin(vp);
5900 	retval = vnode_get_locked(vp);
5901 	vnode_unlock(vp);
5902 
5903 	return retval;
5904 }
5905 
5906 int
vnode_get_locked(struct vnode * vp)5907 vnode_get_locked(struct vnode *vp)
5908 {
5909 #if DIAGNOSTIC
5910 	lck_mtx_assert(&vp->v_lock, LCK_MTX_ASSERT_OWNED);
5911 #endif
5912 	if ((vp->v_iocount == 0) && (vp->v_lflag & (VL_TERMINATE | VL_DEAD))) {
5913 		return ENOENT;
5914 	}
5915 
5916 	if (os_add_overflow(vp->v_iocount, 1, &vp->v_iocount)) {
5917 		panic("v_iocount overflow");
5918 	}
5919 
5920 #ifdef CONFIG_IOCOUNT_TRACE
5921 	record_vp(vp, 1);
5922 #endif
5923 	return 0;
5924 }
5925 
5926 /*
5927  * vnode_getwithvid() cuts in line in front of a vnode drain (that is,
5928  * while the vnode is draining, but at no point after that) to prevent
5929  * deadlocks when getting vnodes from filesystem hashes while holding
5930  * resources that may prevent other iocounts from being released.
5931  */
5932 int
vnode_getwithvid(vnode_t vp,uint32_t vid)5933 vnode_getwithvid(vnode_t vp, uint32_t vid)
5934 {
5935 	return vget_internal(vp, vid, (VNODE_NODEAD | VNODE_WITHID | VNODE_DRAINO));
5936 }
5937 
5938 /*
5939  * vnode_getwithvid_drainok() is like vnode_getwithvid(), but *does* block behind a vnode
5940  * drain; it exists for use in the VFS name cache, where we really do want to block behind
5941  * vnode drain to prevent holding off an unmount.
5942  */
5943 int
vnode_getwithvid_drainok(vnode_t vp,uint32_t vid)5944 vnode_getwithvid_drainok(vnode_t vp, uint32_t vid)
5945 {
5946 	return vget_internal(vp, vid, (VNODE_NODEAD | VNODE_WITHID));
5947 }
5948 
5949 int
vnode_getwithref(vnode_t vp)5950 vnode_getwithref(vnode_t vp)
5951 {
5952 	return vget_internal(vp, 0, 0);
5953 }
5954 
5955 
5956 __private_extern__ int
vnode_getalways(vnode_t vp)5957 vnode_getalways(vnode_t vp)
5958 {
5959 	return vget_internal(vp, 0, VNODE_ALWAYS);
5960 }
5961 
5962 __private_extern__ int
vnode_getalways_from_pager(vnode_t vp)5963 vnode_getalways_from_pager(vnode_t vp)
5964 {
5965 	return vget_internal(vp, 0, VNODE_ALWAYS | VNODE_PAGER);
5966 }
5967 
5968 static inline void
vn_set_dead(vnode_t vp)5969 vn_set_dead(vnode_t vp)
5970 {
5971 	vp->v_mount = NULL;
5972 	vp->v_op = dead_vnodeop_p;
5973 	vp->v_tag = VT_NON;
5974 	vp->v_data = NULL;
5975 	vp->v_type = VBAD;
5976 	vp->v_lflag |= VL_DEAD;
5977 }
5978 
5979 static int
vnode_put_internal_locked(vnode_t vp,bool from_pager)5980 vnode_put_internal_locked(vnode_t vp, bool from_pager)
5981 {
5982 	vfs_context_t ctx = vfs_context_current();      /* hoist outside loop */
5983 
5984 #if DIAGNOSTIC
5985 	lck_mtx_assert(&vp->v_lock, LCK_MTX_ASSERT_OWNED);
5986 #endif
5987 retry:
5988 	if (vp->v_iocount < 1) {
5989 		panic("vnode_put(%p): iocount < 1", vp);
5990 	}
5991 
5992 	if ((vp->v_usecount > 0) || (vp->v_iocount > 1)) {
5993 		vnode_dropiocount(vp);
5994 		return 0;
5995 	}
5996 
5997 	if (((vp->v_lflag & (VL_DEAD | VL_NEEDINACTIVE)) == VL_NEEDINACTIVE)) {
5998 		vp->v_lflag &= ~VL_NEEDINACTIVE;
5999 
6000 		if (UBCINFOEXISTS(vp)) {
6001 			ubc_cs_free_and_vnode_unlock(vp);
6002 		} else {
6003 			vnode_unlock(vp);
6004 		}
6005 
6006 		VNOP_INACTIVE(vp, ctx);
6007 
6008 		vnode_lock_spin(vp);
6009 		/*
6010 		 * because we had to drop the vnode lock before calling
6011 		 * VNOP_INACTIVE, the state of this vnode may have changed...
6012 		 * we may pick up both VL_MARTERM and either
6013 		 * an iocount or a usecount while in the VNOP_INACTIVE call
6014 		 * we don't want to call vnode_reclaim_internal on a vnode
6015 		 * that has active references on it... so loop back around
6016 		 * and reevaluate the state
6017 		 */
6018 		goto retry;
6019 	}
6020 	vp->v_lflag &= ~VL_NEEDINACTIVE;
6021 
6022 	if ((vp->v_lflag & (VL_MARKTERM | VL_TERMINATE | VL_DEAD)) == VL_MARKTERM) {
6023 		if (from_pager) {
6024 			/*
6025 			 * We can't initiate reclaim when called from the pager
6026 			 * because it will deadlock with itself so we hand it
6027 			 * off to the async cleaner thread.
6028 			 */
6029 			vnode_async_list_add(vp);
6030 		} else {
6031 			vnode_lock_convert(vp);
6032 			vnode_reclaim_internal(vp, 1, 1, 0);
6033 		}
6034 	}
6035 	vnode_dropiocount(vp);
6036 	vnode_list_add(vp);
6037 
6038 	return 0;
6039 }
6040 
6041 int
vnode_put_locked(vnode_t vp)6042 vnode_put_locked(vnode_t vp)
6043 {
6044 	return vnode_put_internal_locked(vp, false);
6045 }
6046 
6047 int
vnode_put(vnode_t vp)6048 vnode_put(vnode_t vp)
6049 {
6050 	int retval;
6051 
6052 	vnode_lock_spin(vp);
6053 	vnode_hold(vp);
6054 	retval = vnode_put_internal_locked(vp, false);
6055 	vnode_drop_and_unlock(vp);
6056 
6057 	return retval;
6058 }
6059 
6060 int
vnode_put_from_pager(vnode_t vp)6061 vnode_put_from_pager(vnode_t vp)
6062 {
6063 	int retval;
6064 
6065 	vnode_lock_spin(vp);
6066 	vnode_hold(vp);
6067 	/* Cannot initiate reclaim while paging */
6068 	retval = vnode_put_internal_locked(vp, true);
6069 	vnode_drop_and_unlock(vp);
6070 
6071 	return retval;
6072 }
6073 
6074 int
vnode_writecount(vnode_t vp)6075 vnode_writecount(vnode_t vp)
6076 {
6077 	return vp->v_writecount;
6078 }
6079 
6080 /* is vnode_t in use by others?  */
6081 int
vnode_isinuse(vnode_t vp,int refcnt)6082 vnode_isinuse(vnode_t vp, int refcnt)
6083 {
6084 	return vnode_isinuse_locked(vp, refcnt, 0);
6085 }
6086 
6087 int
vnode_usecount(vnode_t vp)6088 vnode_usecount(vnode_t vp)
6089 {
6090 	return vp->v_usecount;
6091 }
6092 
6093 int
vnode_iocount(vnode_t vp)6094 vnode_iocount(vnode_t vp)
6095 {
6096 	return vp->v_iocount;
6097 }
6098 
6099 int
vnode_isinuse_locked(vnode_t vp,int refcnt,int locked)6100 vnode_isinuse_locked(vnode_t vp, int refcnt, int locked)
6101 {
6102 	int retval = 0;
6103 
6104 	if (!locked) {
6105 		vnode_lock_spin(vp);
6106 	}
6107 	if ((vp->v_type != VREG) && ((vp->v_usecount - vp->v_kusecount) > refcnt)) {
6108 		retval = 1;
6109 		goto out;
6110 	}
6111 	if (vp->v_type == VREG) {
6112 		retval = ubc_isinuse_locked(vp, refcnt, 1);
6113 	}
6114 
6115 out:
6116 	if (!locked) {
6117 		vnode_unlock(vp);
6118 	}
6119 	return retval;
6120 }
6121 
6122 kauth_cred_t
vnode_cred(vnode_t vp)6123 vnode_cred(vnode_t vp)
6124 {
6125 	if (vp->v_cred) {
6126 		return kauth_cred_require(vp->v_cred);
6127 	}
6128 
6129 	return NULL;
6130 }
6131 
6132 
6133 /* resume vnode_t */
6134 errno_t
vnode_resume(vnode_t vp)6135 vnode_resume(vnode_t vp)
6136 {
6137 	if ((vp->v_lflag & VL_SUSPENDED) && vp->v_owner == current_thread()) {
6138 		vnode_lock_spin(vp);
6139 		vp->v_lflag &= ~VL_SUSPENDED;
6140 		vp->v_owner = NULL;
6141 		vnode_unlock(vp);
6142 
6143 		wakeup(&vp->v_iocount);
6144 	}
6145 	return 0;
6146 }
6147 
6148 /* suspend vnode_t
6149  * Please do not use on more than one vnode at a time as it may
6150  * cause deadlocks.
6151  * xxx should we explicity prevent this from happening?
6152  */
6153 
6154 errno_t
vnode_suspend(vnode_t vp)6155 vnode_suspend(vnode_t vp)
6156 {
6157 	if (vp->v_lflag & VL_SUSPENDED) {
6158 		return EBUSY;
6159 	}
6160 
6161 	vnode_lock_spin(vp);
6162 
6163 	/*
6164 	 * xxx is this sufficient to check if a vnode_drain is
6165 	 * progress?
6166 	 */
6167 
6168 	if (vp->v_owner == NULL) {
6169 		vp->v_lflag |= VL_SUSPENDED;
6170 		vp->v_owner = current_thread();
6171 	}
6172 	vnode_unlock(vp);
6173 
6174 	return 0;
6175 }
6176 
6177 /*
6178  * Release any blocked locking requests on the vnode.
6179  * Used for forced-unmounts.
6180  *
6181  * XXX	What about network filesystems?
6182  */
6183 static void
vnode_abort_advlocks(vnode_t vp)6184 vnode_abort_advlocks(vnode_t vp)
6185 {
6186 	if (vp->v_flag & VLOCKLOCAL) {
6187 		lf_abort_advlocks(vp);
6188 	}
6189 }
6190 
6191 
6192 static errno_t
vnode_drain(vnode_t vp)6193 vnode_drain(vnode_t vp)
6194 {
6195 	if (vp->v_lflag & VL_DRAIN) {
6196 		panic("vnode_drain: recursive drain");
6197 		return ENOENT;
6198 	}
6199 	vp->v_lflag |= VL_DRAIN;
6200 	vp->v_owner = current_thread();
6201 
6202 	while (vp->v_iocount > 1) {
6203 		if (bootarg_no_vnode_drain) {
6204 			struct timespec ts = {.tv_sec = 10, .tv_nsec = 0};
6205 			int error;
6206 
6207 			if (vfs_unmountall_started) {
6208 				ts.tv_sec = 1;
6209 			}
6210 
6211 			error = msleep(&vp->v_iocount, &vp->v_lock, PVFS, "vnode_drain_with_timeout", &ts);
6212 
6213 			/* Try to deal with leaked iocounts under bootarg and shutting down */
6214 			if (vp->v_iocount > 1 && error == EWOULDBLOCK &&
6215 			    ts.tv_sec == 1 && vp->v_numoutput == 0) {
6216 				vp->v_iocount = 1;
6217 				break;
6218 			}
6219 		} else {
6220 			msleep(&vp->v_iocount, &vp->v_lock, PVFS, "vnode_drain", NULL);
6221 		}
6222 	}
6223 
6224 	vp->v_lflag &= ~VL_DRAIN;
6225 
6226 	return 0;
6227 }
6228 
6229 
6230 /*
6231  * if the number of recent references via vnode_getwithvid or vnode_getwithref
6232  * exceeds this threshold, than 'UN-AGE' the vnode by removing it from
6233  * the LRU list if it's currently on it... once the iocount and usecount both drop
6234  * to 0, it will get put back on the end of the list, effectively making it younger
6235  * this allows us to keep actively referenced vnodes in the list without having
6236  * to constantly remove and add to the list each time a vnode w/o a usecount is
6237  * referenced which costs us taking and dropping a global lock twice.
6238  * However, if the vnode is marked DIRTY, we want to pull it out much earlier
6239  */
6240 #define UNAGE_THRESHHOLD        25
6241 #define UNAGE_DIRTYTHRESHHOLD    6
6242 
6243 errno_t
vnode_getiocount(vnode_t vp,unsigned int vid,int vflags)6244 vnode_getiocount(vnode_t vp, unsigned int vid, int vflags)
6245 {
6246 	int nodead = vflags & VNODE_NODEAD;
6247 	int nosusp = vflags & VNODE_NOSUSPEND;
6248 	int always = vflags & VNODE_ALWAYS;
6249 	int beatdrain = vflags & VNODE_DRAINO;
6250 	int withvid = vflags & VNODE_WITHID;
6251 	int forpager = vflags & VNODE_PAGER;
6252 
6253 	for (;;) {
6254 		int sleepflg = 0;
6255 
6256 		/*
6257 		 * if it is a dead vnode with deadfs
6258 		 */
6259 		if (nodead && (vp->v_lflag & VL_DEAD) && ((vp->v_type == VBAD) || (vp->v_data == 0))) {
6260 			return ENOENT;
6261 		}
6262 		/*
6263 		 * will return VL_DEAD ones
6264 		 */
6265 		if ((vp->v_lflag & (VL_SUSPENDED | VL_DRAIN | VL_TERMINATE)) == 0) {
6266 			break;
6267 		}
6268 		/*
6269 		 * if suspended vnodes are to be failed
6270 		 */
6271 		if (nosusp && (vp->v_lflag & VL_SUSPENDED)) {
6272 			return ENOENT;
6273 		}
6274 		/*
6275 		 * if you are the owner of drain/suspend/termination , can acquire iocount
6276 		 * check for VL_TERMINATE; it does not set owner
6277 		 */
6278 		if ((vp->v_lflag & (VL_DRAIN | VL_SUSPENDED | VL_TERMINATE)) &&
6279 		    (vp->v_owner == current_thread())) {
6280 			break;
6281 		}
6282 
6283 		if (always != 0) {
6284 			break;
6285 		}
6286 
6287 		/*
6288 		 * If this vnode is getting drained, there are some cases where
6289 		 * we can't block or, in case of tty vnodes, want to be
6290 		 * interruptible.
6291 		 */
6292 		if (vp->v_lflag & VL_DRAIN) {
6293 			/*
6294 			 * In some situations, we want to get an iocount
6295 			 * even if the vnode is draining to prevent deadlock,
6296 			 * e.g. if we're in the filesystem, potentially holding
6297 			 * resources that could prevent other iocounts from
6298 			 * being released.
6299 			 */
6300 			if (beatdrain) {
6301 				break;
6302 			}
6303 			/*
6304 			 * Don't block if the vnode's mount point is unmounting as
6305 			 * we may be the thread the unmount is itself waiting on
6306 			 * Only callers who pass in vids (at this point, we've already
6307 			 * handled nosusp and nodead) are expecting error returns
6308 			 * from this function, so only we can only return errors for
6309 			 * those. ENODEV is intended to inform callers that the call
6310 			 * failed because an unmount is in progress.
6311 			 */
6312 			if (withvid && (vp->v_mount) && vfs_isunmount(vp->v_mount)) {
6313 				return ENODEV;
6314 			}
6315 
6316 			if (vnode_istty(vp)) {
6317 				sleepflg = PCATCH;
6318 			}
6319 		}
6320 
6321 		vnode_lock_convert(vp);
6322 
6323 		if (vp->v_lflag & VL_TERMINATE) {
6324 			int error;
6325 
6326 			vp->v_lflag |= VL_TERMWANT;
6327 
6328 			error = msleep(&vp->v_lflag, &vp->v_lock,
6329 			    (PVFS | sleepflg), "vnode getiocount", NULL);
6330 			if (error) {
6331 				return error;
6332 			}
6333 		} else {
6334 			msleep(&vp->v_iocount, &vp->v_lock, PVFS, "vnode_getiocount", NULL);
6335 		}
6336 	}
6337 	if (withvid && vid != vp->v_id) {
6338 		return ENOENT;
6339 	}
6340 	if (!forpager && (++vp->v_references >= UNAGE_THRESHHOLD ||
6341 	    (vp->v_flag & VISDIRTY && vp->v_references >= UNAGE_DIRTYTHRESHHOLD))) {
6342 		vp->v_references = 0;
6343 		vnode_list_remove(vp);
6344 	}
6345 	vp->v_iocount++;
6346 #ifdef CONFIG_IOCOUNT_TRACE
6347 	record_vp(vp, 1);
6348 #endif
6349 	return 0;
6350 }
6351 
6352 static void
vnode_dropiocount(vnode_t vp)6353 vnode_dropiocount(vnode_t vp)
6354 {
6355 	if (vp->v_iocount < 1) {
6356 		panic("vnode_dropiocount(%p): v_iocount < 1", vp);
6357 	}
6358 
6359 	vp->v_iocount--;
6360 #ifdef CONFIG_IOCOUNT_TRACE
6361 	record_vp(vp, -1);
6362 #endif
6363 	if ((vp->v_lflag & (VL_DRAIN | VL_SUSPENDED)) && (vp->v_iocount <= 1)) {
6364 		wakeup(&vp->v_iocount);
6365 	}
6366 }
6367 
6368 
6369 void
vnode_reclaim(struct vnode * vp)6370 vnode_reclaim(struct vnode * vp)
6371 {
6372 	vnode_reclaim_internal(vp, 0, 0, 0);
6373 }
6374 
6375 __private_extern__
6376 void
vnode_reclaim_internal(struct vnode * vp,int locked,int reuse,int flags)6377 vnode_reclaim_internal(struct vnode * vp, int locked, int reuse, int flags)
6378 {
6379 	int isfifo = 0;
6380 	bool clear_tty_revoke = false;
6381 
6382 	if (!locked) {
6383 		vnode_lock(vp);
6384 	}
6385 
6386 	if (vp->v_lflag & VL_TERMINATE) {
6387 		panic("vnode reclaim in progress");
6388 	}
6389 	vp->v_lflag |= VL_TERMINATE;
6390 
6391 	vn_clearunionwait(vp, 1);
6392 
6393 	/*
6394 	 * We have to force any terminals in reads to return and give up
6395 	 * their iocounts. It's important to do this after VL_TERMINATE
6396 	 * has been set to ensure new reads are blocked while the
6397 	 * revoke is in progress.
6398 	 */
6399 	if (vnode_istty(vp) && (flags & REVOKEALL) && (vp->v_iocount > 1)) {
6400 		vnode_unlock(vp);
6401 		VNOP_IOCTL(vp, TIOCREVOKE, (caddr_t)NULL, 0, vfs_context_kernel());
6402 		clear_tty_revoke = true;
6403 		vnode_lock(vp);
6404 	}
6405 
6406 	vnode_drain(vp);
6407 
6408 	if (clear_tty_revoke) {
6409 		vnode_unlock(vp);
6410 		VNOP_IOCTL(vp, TIOCREVOKECLEAR, (caddr_t)NULL, 0, vfs_context_kernel());
6411 		vnode_lock(vp);
6412 	}
6413 
6414 #if CONFIG_FILE_LEASES
6415 	/*
6416 	 * Revoke all leases in place for this vnode as it is about to be reclaimed.
6417 	 * In normal case, there shouldn't be any leases in place by the time we
6418 	 * get here as there shouldn't be any opens on the vnode (usecount == 0).
6419 	 * However, in the case of force unmount or unmount of a volume that
6420 	 * contains file that was opened with O_EVTONLY then the vnode can be
6421 	 * reclaimed while the file is still opened.
6422 	 */
6423 	vnode_revokelease(vp, true);
6424 #endif
6425 
6426 	isfifo = (vp->v_type == VFIFO);
6427 
6428 	if (vp->v_type != VBAD) {
6429 		vgone(vp, flags);               /* clean and reclaim the vnode */
6430 	}
6431 	/*
6432 	 * give the vnode a new identity so that vnode_getwithvid will fail
6433 	 * on any stale cache accesses...
6434 	 * grab the list_lock so that if we're in "new_vnode"
6435 	 * behind the list_lock trying to steal this vnode, the v_id is stable...
6436 	 * once new_vnode drops the list_lock, it will block trying to take
6437 	 * the vnode lock until we release it... at that point it will evaluate
6438 	 * whether the v_vid has changed
6439 	 * also need to make sure that the vnode isn't on a list where "new_vnode"
6440 	 * can find it after the v_id has been bumped until we are completely done
6441 	 * with the vnode (i.e. putting it back on a list has to be the very last
6442 	 * thing we do to this vnode... many of the callers of vnode_reclaim_internal
6443 	 * are holding an io_count on the vnode... they need to drop the io_count
6444 	 * BEFORE doing a vnode_list_add or make sure to hold the vnode lock until
6445 	 * they are completely done with the vnode
6446 	 */
6447 	vnode_list_lock();
6448 
6449 	vnode_list_remove_locked(vp);
6450 	vp->v_id++;
6451 
6452 	vnode_list_unlock();
6453 
6454 	if (isfifo) {
6455 		struct fifoinfo * fip;
6456 
6457 		fip = vp->v_fifoinfo;
6458 		vp->v_fifoinfo = NULL;
6459 		kfree_type(struct fifoinfo, fip);
6460 	}
6461 	vp->v_type = VBAD;
6462 
6463 	if (vp->v_data) {
6464 		panic("vnode_reclaim_internal: cleaned vnode isn't");
6465 	}
6466 	if (vp->v_numoutput) {
6467 		panic("vnode_reclaim_internal: clean vnode has pending I/O's");
6468 	}
6469 	if (UBCINFOEXISTS(vp)) {
6470 		panic("vnode_reclaim_internal: ubcinfo not cleaned");
6471 	}
6472 	if (vp->v_parent) {
6473 		panic("vnode_reclaim_internal: vparent not removed");
6474 	}
6475 	if (vp->v_name) {
6476 		panic("vnode_reclaim_internal: vname not removed");
6477 	}
6478 
6479 #if CONFIG_FILE_LEASES
6480 	if (__improbable(!LIST_EMPTY(&vp->v_leases))) {
6481 		panic("vnode_reclaim_internal: vleases NOT empty");
6482 	}
6483 #endif
6484 
6485 	vp->v_socket = NULL;
6486 
6487 	vp->v_lflag &= ~VL_TERMINATE;
6488 	vp->v_owner = NULL;
6489 
6490 #if CONFIG_IOCOUNT_TRACE
6491 	if (__improbable(bootarg_vnode_iocount_trace)) {
6492 		bzero(vp->v_iocount_trace,
6493 		    IOCOUNT_TRACE_MAX_TYPES * sizeof(struct vnode_iocount_trace));
6494 	}
6495 #endif /* CONFIG_IOCOUNT_TRACE */
6496 
6497 	KNOTE(&vp->v_knotes, NOTE_REVOKE);
6498 
6499 	/* Make sure that when we reuse the vnode, no knotes left over */
6500 	klist_init(&vp->v_knotes);
6501 
6502 	if (vp->v_lflag & VL_TERMWANT) {
6503 		vp->v_lflag &= ~VL_TERMWANT;
6504 		wakeup(&vp->v_lflag);
6505 	}
6506 	if (!reuse) {
6507 		/*
6508 		 * make sure we get on the
6509 		 * dead list if appropriate
6510 		 */
6511 		vnode_list_add(vp);
6512 	}
6513 	if (!locked) {
6514 		vnode_unlock(vp);
6515 	}
6516 }
6517 
6518 static int
vnode_create_internal(uint32_t flavor,uint32_t size,void * data,vnode_t * vpp,vnode_create_options_t vc_options)6519 vnode_create_internal(uint32_t flavor, uint32_t size, void *data, vnode_t *vpp,
6520     vnode_create_options_t vc_options)
6521 {
6522 	int error;
6523 	int insert = 1;
6524 	vnode_t vp = NULLVP;
6525 	vnode_t nvp;
6526 	vnode_t dvp;
6527 	struct  uthread *ut;
6528 	struct componentname *cnp;
6529 	struct vnode_fsparam *param = (struct vnode_fsparam *)data;
6530 #if CONFIG_TRIGGERS
6531 	struct vnode_trigger_param *tinfo = NULL;
6532 #endif
6533 	bool existing_vnode;
6534 	bool init_vnode = !(vc_options & VNODE_CREATE_EMPTY);
6535 
6536 	if (*vpp) {
6537 		vp = *vpp;
6538 		*vpp = NULLVP;
6539 		existing_vnode = true;
6540 	} else {
6541 		existing_vnode = false;
6542 	}
6543 
6544 	if (init_vnode) {
6545 		/* Do quick sanity check on the parameters. */
6546 		if ((param == NULL) || (param->vnfs_vtype == VBAD)) {
6547 			error = EINVAL;
6548 			goto error_out;
6549 		}
6550 
6551 #if CONFIG_TRIGGERS
6552 		if ((flavor == VNCREATE_TRIGGER) && (size == VNCREATE_TRIGGER_SIZE)) {
6553 			tinfo = (struct vnode_trigger_param *)data;
6554 
6555 			/* Validate trigger vnode input */
6556 			if ((param->vnfs_vtype != VDIR) ||
6557 			    (tinfo->vnt_resolve_func == NULL) ||
6558 			    (tinfo->vnt_flags & ~VNT_VALID_MASK)) {
6559 				error = EINVAL;
6560 				goto error_out;
6561 			}
6562 			/* Fall through a normal create (params will be the same) */
6563 			flavor = VNCREATE_FLAVOR;
6564 			size = VCREATESIZE;
6565 		}
6566 #endif
6567 		if ((flavor != VNCREATE_FLAVOR) || (size != VCREATESIZE)) {
6568 			error = EINVAL;
6569 			goto error_out;
6570 		}
6571 	}
6572 
6573 	if (!existing_vnode) {
6574 		if ((error = new_vnode(&vp, !(vc_options & VNODE_CREATE_NODEALLOC)))) {
6575 			return error;
6576 		}
6577 		if (!init_vnode) {
6578 			/* Make it so that it can be released by a vnode_put) */
6579 			vnode_lock(vp);
6580 			vn_set_dead(vp);
6581 			vnode_unlock(vp);
6582 			*vpp = vp;
6583 			return 0;
6584 		}
6585 	} else {
6586 		/*
6587 		 * A vnode obtained by vnode_create_empty has been passed to
6588 		 * vnode_initialize - Unset VL_DEAD set by vn_set_dead. After
6589 		 * this point, it is set back on any error.
6590 		 */
6591 		vnode_lock(vp);
6592 		vp->v_lflag &= ~VL_DEAD;
6593 		vnode_unlock(vp);
6594 	}
6595 
6596 	dvp = param->vnfs_dvp;
6597 	cnp = param->vnfs_cnp;
6598 
6599 	vp->v_op = param->vnfs_vops;
6600 	vp->v_type = (uint16_t)param->vnfs_vtype;
6601 	vp->v_data = param->vnfs_fsnode;
6602 
6603 	if (param->vnfs_markroot) {
6604 		vp->v_flag |= VROOT;
6605 	}
6606 	if (param->vnfs_marksystem) {
6607 		vp->v_flag |= VSYSTEM;
6608 	}
6609 	if (vp->v_type == VREG) {
6610 		error = ubc_info_init_withsize(vp, param->vnfs_filesize);
6611 		if (error) {
6612 #ifdef CONFIG_IOCOUNT_TRACE
6613 			record_vp(vp, 1);
6614 #endif
6615 			vnode_hold(vp);
6616 			vnode_lock(vp);
6617 			vn_set_dead(vp);
6618 
6619 			vnode_put_locked(vp);
6620 			vnode_drop_and_unlock(vp);
6621 			return error;
6622 		}
6623 		if (param->vnfs_mp->mnt_ioflags & MNT_IOFLAGS_IOSCHED_SUPPORTED) {
6624 			memory_object_mark_io_tracking(vp->v_ubcinfo->ui_control);
6625 		}
6626 	}
6627 #ifdef CONFIG_IOCOUNT_TRACE
6628 	record_vp(vp, 1);
6629 #endif
6630 
6631 #if CONFIG_FIRMLINKS
6632 	vp->v_fmlink = NULLVP;
6633 #endif
6634 	vp->v_flag &= ~VFMLINKTARGET;
6635 
6636 #if CONFIG_TRIGGERS
6637 	/*
6638 	 * For trigger vnodes, attach trigger info to vnode
6639 	 */
6640 	if ((vp->v_type == VDIR) && (tinfo != NULL)) {
6641 		/*
6642 		 * Note: has a side effect of incrementing trigger count on the
6643 		 * mount if successful, which we would need to undo on a
6644 		 * subsequent failure.
6645 		 */
6646 #ifdef CONFIG_IOCOUNT_TRACE
6647 		record_vp(vp, -1);
6648 #endif
6649 		error = vnode_resolver_create(param->vnfs_mp, vp, tinfo, FALSE);
6650 		if (error) {
6651 			printf("vnode_create: vnode_resolver_create() err %d\n", error);
6652 			vnode_hold(vp);
6653 			vnode_lock(vp);
6654 			vn_set_dead(vp);
6655 #ifdef CONFIG_IOCOUNT_TRACE
6656 			record_vp(vp, 1);
6657 #endif
6658 			vnode_put_locked(vp);
6659 			vnode_drop_and_unlock(vp);
6660 			return error;
6661 		}
6662 	}
6663 #endif
6664 	if (vp->v_type == VCHR || vp->v_type == VBLK) {
6665 		vp->v_tag = VT_DEVFS;           /* callers will reset if needed (bdevvp) */
6666 
6667 		if ((nvp = checkalias(vp, param->vnfs_rdev))) {
6668 			bool is_bdevvp;
6669 
6670 			/*
6671 			 * if checkalias returns a vnode, it will be locked
6672 			 *
6673 			 * first get rid of the unneeded vnode we acquired
6674 			 */
6675 			vp->v_data = NULL;
6676 			vp->v_op = spec_vnodeop_p;
6677 			vp->v_type = VBAD;
6678 			vp->v_lflag = VL_DEAD;
6679 			vp->v_data = NULL;
6680 			vp->v_tag = VT_NON;
6681 			vnode_put(vp);
6682 
6683 			/*
6684 			 * switch to aliased vnode and finish
6685 			 * preparing it
6686 			 */
6687 			vp = nvp;
6688 
6689 			is_bdevvp = (vp->v_flag & VBDEVVP);
6690 
6691 			if (is_bdevvp) {
6692 				printf("%s: alias vnode %p is in state of change (start)\n",
6693 				    __func__, vp);
6694 			}
6695 
6696 			vnode_hold(vp);
6697 			vp->v_lflag |= VL_OPSCHANGE;
6698 			vclean(vp, 0);
6699 			vp->v_op = param->vnfs_vops;
6700 			vp->v_type = (uint16_t)param->vnfs_vtype;
6701 			vp->v_data = param->vnfs_fsnode;
6702 			vp->v_lflag = VL_OPSCHANGE;
6703 			vp->v_mount = NULL;
6704 			insmntque(vp, param->vnfs_mp);
6705 			insert = 0;
6706 
6707 			if (is_bdevvp) {
6708 				printf("%s: alias vnode %p is in state of change (end)\n",
6709 				    __func__, vp);
6710 			}
6711 
6712 			vnode_drop_and_unlock(vp);
6713 			wakeup(&vp->v_lflag); /* chkvnlock is waitng for VL_DEAD to get unset */
6714 		}
6715 
6716 		if (VCHR == vp->v_type) {
6717 			u_int maj = major(vp->v_rdev);
6718 
6719 			if (maj < (u_int)nchrdev && cdevsw[maj].d_type == D_TTY) {
6720 				vp->v_flag |= VISTTY;
6721 			}
6722 		}
6723 	}
6724 
6725 	if (vp->v_type == VFIFO) {
6726 		struct fifoinfo *fip;
6727 
6728 		fip = kalloc_type(struct fifoinfo, Z_WAITOK | Z_ZERO);
6729 		vp->v_fifoinfo = fip;
6730 	}
6731 	/* The file systems must pass the address of the location where
6732 	 * they store the vnode pointer. When we add the vnode into the mount
6733 	 * list and name cache they become discoverable. So the file system node
6734 	 * must have the connection to vnode setup by then
6735 	 */
6736 	*vpp = vp;
6737 
6738 	/* Add fs named reference. */
6739 	if (param->vnfs_flags & VNFS_ADDFSREF) {
6740 		vp->v_lflag |= VNAMED_FSHASH;
6741 	}
6742 	if (param->vnfs_mp) {
6743 		if (param->vnfs_mp->mnt_kern_flag & MNTK_LOCK_LOCAL) {
6744 			vp->v_flag |= VLOCKLOCAL;
6745 		}
6746 		if (insert) {
6747 			if ((vp->v_freelist.tqe_prev != (struct vnode **)0xdeadb)) {
6748 				panic("insmntque: vp on the free list");
6749 			}
6750 
6751 			/*
6752 			 * enter in mount vnode list
6753 			 */
6754 			insmntque(vp, param->vnfs_mp);
6755 		}
6756 	}
6757 	if (dvp && vnode_ref(dvp) == 0) {
6758 		vp->v_parent = dvp;
6759 	}
6760 	if (cnp) {
6761 		if (dvp && ((param->vnfs_flags & (VNFS_NOCACHE | VNFS_CANTCACHE)) == 0)) {
6762 			/*
6763 			 * enter into name cache
6764 			 * we've got the info to enter it into the name cache now
6765 			 * cache_enter_create will pick up an extra reference on
6766 			 * the name entered into the string cache
6767 			 */
6768 			vp->v_name = cache_enter_create(dvp, vp, cnp);
6769 		} else {
6770 			vp->v_name = vfs_addname(cnp->cn_nameptr, cnp->cn_namelen, cnp->cn_hash, 0);
6771 		}
6772 
6773 		if ((cnp->cn_flags & UNIONCREATED) == UNIONCREATED) {
6774 			vp->v_flag |= VISUNION;
6775 		}
6776 	}
6777 	if ((param->vnfs_flags & VNFS_CANTCACHE) == 0) {
6778 		/*
6779 		 * this vnode is being created as cacheable in the name cache
6780 		 * this allows us to re-enter it in the cache
6781 		 */
6782 		vp->v_flag |= VNCACHEABLE;
6783 	}
6784 	ut = current_uthread();
6785 
6786 	if ((current_proc()->p_lflag & P_LRAGE_VNODES) ||
6787 	    (ut->uu_flag & (UT_RAGE_VNODES | UT_KERN_RAGE_VNODES))) {
6788 		/*
6789 		 * process has indicated that it wants any
6790 		 * vnodes created on its behalf to be rapidly
6791 		 * aged to reduce the impact on the cached set
6792 		 * of vnodes
6793 		 *
6794 		 * if UT_KERN_RAGE_VNODES is set, then the
6795 		 * kernel internally wants vnodes to be rapidly
6796 		 * aged, even if the process hasn't requested
6797 		 * this
6798 		 */
6799 		vp->v_flag |= VRAGE;
6800 	}
6801 
6802 #if CONFIG_SECLUDED_MEMORY
6803 	switch (secluded_for_filecache) {
6804 	case 0:
6805 		/*
6806 		 * secluded_for_filecache == 0:
6807 		 * + no file contents in secluded pool
6808 		 */
6809 		break;
6810 	case 1:
6811 		/*
6812 		 * secluded_for_filecache == 1:
6813 		 * + no files from /
6814 		 * + files from /Applications/ are OK
6815 		 * + files from /Applications/Camera are not OK
6816 		 * + no files that are open for write
6817 		 */
6818 		if (vnode_vtype(vp) == VREG &&
6819 		    vnode_mount(vp) != NULL &&
6820 		    (!(vfs_flags(vnode_mount(vp)) & MNT_ROOTFS))) {
6821 			/* not from root filesystem: eligible for secluded pages */
6822 			memory_object_mark_eligible_for_secluded(
6823 				ubc_getobject(vp, UBC_FLAGS_NONE),
6824 				TRUE);
6825 		}
6826 		break;
6827 	case 2:
6828 		/*
6829 		 * secluded_for_filecache == 2:
6830 		 * + all read-only files OK, except:
6831 		 *      + dyld_shared_cache_arm64*
6832 		 *      + Camera
6833 		 *	+ mediaserverd
6834 		 */
6835 		if (vnode_vtype(vp) == VREG) {
6836 			memory_object_mark_eligible_for_secluded(
6837 				ubc_getobject(vp, UBC_FLAGS_NONE),
6838 				TRUE);
6839 		}
6840 		break;
6841 	default:
6842 		break;
6843 	}
6844 #endif /* CONFIG_SECLUDED_MEMORY */
6845 
6846 	return 0;
6847 
6848 error_out:
6849 	if (existing_vnode) {
6850 		vnode_put(vp);
6851 	}
6852 	return error;
6853 }
6854 
6855 int
vnode_create_ext(uint32_t flavor,uint32_t size,void * data,vnode_t * vpp,vnode_create_options_t vc_options)6856 vnode_create_ext(uint32_t flavor, uint32_t size, void *data, vnode_t *vpp, vnode_create_options_t vc_options)
6857 {
6858 	if (vc_options & ~(VNODE_CREATE_EMPTY | VNODE_CREATE_NODEALLOC)) {
6859 		return EINVAL;
6860 	}
6861 	*vpp = NULLVP;
6862 	return vnode_create_internal(flavor, size, data, vpp, vc_options);
6863 }
6864 
6865 /* USAGE:
6866  * The following api creates a vnode and associates all the parameter specified in vnode_fsparam
6867  * structure and returns a vnode handle with a reference. device aliasing is handled here so checkalias
6868  * is obsoleted by this.
6869  */
6870 int
vnode_create(uint32_t flavor,uint32_t size,void * data,vnode_t * vpp)6871 vnode_create(uint32_t flavor, uint32_t size, void *data, vnode_t *vpp)
6872 {
6873 	return vnode_create_ext(flavor, size, data, vpp, VNODE_CREATE_NODEALLOC);
6874 }
6875 
6876 int
vnode_create_empty(vnode_t * vpp)6877 vnode_create_empty(vnode_t *vpp)
6878 {
6879 	return vnode_create_ext(VNCREATE_FLAVOR, VCREATESIZE, NULL,
6880 	           vpp, VNODE_CREATE_EMPTY);
6881 }
6882 
6883 int
vnode_initialize(uint32_t __unused flavor,uint32_t size,void * data,vnode_t * vpp)6884 vnode_initialize(uint32_t __unused flavor, uint32_t size, void *data, vnode_t *vpp)
6885 {
6886 	if (*vpp == NULLVP) {
6887 		panic("NULL vnode passed to vnode_initialize");
6888 	}
6889 #if DEVELOPMENT || DEBUG
6890 	/*
6891 	 * We lock to check that vnode is fit for unlocked use in
6892 	 * vnode_create_internal.
6893 	 */
6894 	vnode_lock_spin(*vpp);
6895 	VNASSERT(((*vpp)->v_iocount == 1), *vpp,
6896 	    ("vnode_initialize : iocount not 1, is %d", (*vpp)->v_iocount));
6897 	VNASSERT(((*vpp)->v_usecount == 0), *vpp,
6898 	    ("vnode_initialize : usecount not 0, is %d", (*vpp)->v_usecount));
6899 	VNASSERT(((*vpp)->v_lflag & VL_DEAD), *vpp,
6900 	    ("vnode_initialize : v_lflag does not have VL_DEAD, is 0x%x",
6901 	    (*vpp)->v_lflag));
6902 	VNASSERT(((*vpp)->v_data == NULL), *vpp,
6903 	    ("vnode_initialize : v_data not NULL"));
6904 	vnode_unlock(*vpp);
6905 #endif
6906 	return vnode_create_internal(flavor, size, data, vpp, VNODE_CREATE_DEFAULT);
6907 }
6908 
6909 int
vnode_addfsref(vnode_t vp)6910 vnode_addfsref(vnode_t vp)
6911 {
6912 	vnode_lock_spin(vp);
6913 	if (vp->v_lflag & VNAMED_FSHASH) {
6914 		panic("add_fsref: vp already has named reference");
6915 	}
6916 	if ((vp->v_freelist.tqe_prev != (struct vnode **)0xdeadb)) {
6917 		panic("addfsref: vp on the free list");
6918 	}
6919 	vp->v_lflag |= VNAMED_FSHASH;
6920 	vnode_unlock(vp);
6921 	return 0;
6922 }
6923 int
vnode_removefsref(vnode_t vp)6924 vnode_removefsref(vnode_t vp)
6925 {
6926 	vnode_lock_spin(vp);
6927 	if ((vp->v_lflag & VNAMED_FSHASH) == 0) {
6928 		panic("remove_fsref: no named reference");
6929 	}
6930 	vp->v_lflag &= ~VNAMED_FSHASH;
6931 	vnode_unlock(vp);
6932 	return 0;
6933 }
6934 
6935 
6936 int
vfs_iterate(int flags,int (* callout)(mount_t,void *),void * arg)6937 vfs_iterate(int flags, int (*callout)(mount_t, void *), void *arg)
6938 {
6939 	mount_t mp;
6940 	int ret = 0;
6941 	fsid_t * fsid_list;
6942 	int count, actualcount, i;
6943 	void * allocmem;
6944 	int indx_start, indx_stop, indx_incr;
6945 	int cb_dropref = (flags & VFS_ITERATE_CB_DROPREF);
6946 	int noskip_unmount = (flags & VFS_ITERATE_NOSKIP_UNMOUNT);
6947 
6948 	count = mount_getvfscnt();
6949 	count += 10;
6950 
6951 	fsid_list = kalloc_data(count * sizeof(fsid_t), Z_WAITOK);
6952 	allocmem = (void *)fsid_list;
6953 
6954 	actualcount = mount_fillfsids(fsid_list, count);
6955 
6956 	/*
6957 	 * Establish the iteration direction
6958 	 * VFS_ITERATE_TAIL_FIRST overrides default head first order (oldest first)
6959 	 */
6960 	if (flags & VFS_ITERATE_TAIL_FIRST) {
6961 		indx_start = actualcount - 1;
6962 		indx_stop = -1;
6963 		indx_incr = -1;
6964 	} else { /* Head first by default */
6965 		indx_start = 0;
6966 		indx_stop = actualcount;
6967 		indx_incr = 1;
6968 	}
6969 
6970 	for (i = indx_start; i != indx_stop; i += indx_incr) {
6971 		/* obtain the mount point with iteration reference */
6972 		mp = mount_list_lookupby_fsid(&fsid_list[i], 0, 1);
6973 
6974 		if (mp == (struct mount *)0) {
6975 			continue;
6976 		}
6977 		mount_lock(mp);
6978 		if ((mp->mnt_lflag & MNT_LDEAD) ||
6979 		    (!noskip_unmount && (mp->mnt_lflag & MNT_LUNMOUNT))) {
6980 			mount_unlock(mp);
6981 			mount_iterdrop(mp);
6982 			continue;
6983 		}
6984 		mount_unlock(mp);
6985 
6986 		/* iterate over all the vnodes */
6987 		ret = callout(mp, arg);
6988 
6989 		/*
6990 		 * Drop the iterref here if the callback didn't do it.
6991 		 * Note: If cb_dropref is set the mp may no longer exist.
6992 		 */
6993 		if (!cb_dropref) {
6994 			mount_iterdrop(mp);
6995 		}
6996 
6997 		switch (ret) {
6998 		case VFS_RETURNED:
6999 		case VFS_RETURNED_DONE:
7000 			if (ret == VFS_RETURNED_DONE) {
7001 				ret = 0;
7002 				goto out;
7003 			}
7004 			break;
7005 
7006 		case VFS_CLAIMED_DONE:
7007 			ret = 0;
7008 			goto out;
7009 		case VFS_CLAIMED:
7010 		default:
7011 			break;
7012 		}
7013 		ret = 0;
7014 	}
7015 
7016 out:
7017 	kfree_data(allocmem, count * sizeof(fsid_t));
7018 	return ret;
7019 }
7020 
7021 /*
7022  * Update the vfsstatfs structure in the mountpoint.
7023  * MAC: Parameter eventtype added, indicating whether the event that
7024  * triggered this update came from user space, via a system call
7025  * (VFS_USER_EVENT) or an internal kernel call (VFS_KERNEL_EVENT).
7026  */
7027 int
vfs_update_vfsstat(mount_t mp,vfs_context_t ctx,__unused int eventtype)7028 vfs_update_vfsstat(mount_t mp, vfs_context_t ctx, __unused int eventtype)
7029 {
7030 	struct vfs_attr va;
7031 	int             error;
7032 
7033 	/*
7034 	 * Request the attributes we want to propagate into
7035 	 * the per-mount vfsstat structure.
7036 	 */
7037 	VFSATTR_INIT(&va);
7038 	VFSATTR_WANTED(&va, f_iosize);
7039 	VFSATTR_WANTED(&va, f_blocks);
7040 	VFSATTR_WANTED(&va, f_bfree);
7041 	VFSATTR_WANTED(&va, f_bavail);
7042 	VFSATTR_WANTED(&va, f_bused);
7043 	VFSATTR_WANTED(&va, f_files);
7044 	VFSATTR_WANTED(&va, f_ffree);
7045 	VFSATTR_WANTED(&va, f_bsize);
7046 	VFSATTR_WANTED(&va, f_fssubtype);
7047 
7048 	if ((error = vfs_getattr(mp, &va, ctx)) != 0) {
7049 		KAUTH_DEBUG("STAT - filesystem returned error %d", error);
7050 		return error;
7051 	}
7052 #if CONFIG_MACF
7053 	if (eventtype == VFS_USER_EVENT) {
7054 		error = mac_mount_check_getattr(ctx, mp, &va);
7055 		if (error != 0) {
7056 			return error;
7057 		}
7058 	}
7059 #endif
7060 	/*
7061 	 * Unpack into the per-mount structure.
7062 	 *
7063 	 * We only overwrite these fields, which are likely to change:
7064 	 *	f_blocks
7065 	 *	f_bfree
7066 	 *	f_bavail
7067 	 *	f_bused
7068 	 *	f_files
7069 	 *	f_ffree
7070 	 *
7071 	 * And these which are not, but which the FS has no other way
7072 	 * of providing to us:
7073 	 *	f_bsize
7074 	 *	f_iosize
7075 	 *	f_fssubtype
7076 	 *
7077 	 */
7078 	if (VFSATTR_IS_SUPPORTED(&va, f_bsize)) {
7079 		/* 4822056 - protect against malformed server mount */
7080 		mp->mnt_vfsstat.f_bsize = (va.f_bsize > 0 ? va.f_bsize : 512);
7081 	} else {
7082 		mp->mnt_vfsstat.f_bsize = mp->mnt_devblocksize; /* default from the device block size */
7083 	}
7084 	if (VFSATTR_IS_SUPPORTED(&va, f_iosize)) {
7085 		mp->mnt_vfsstat.f_iosize = va.f_iosize;
7086 	} else {
7087 		mp->mnt_vfsstat.f_iosize = 1024 * 1024;         /* 1MB sensible I/O size */
7088 	}
7089 	if (VFSATTR_IS_SUPPORTED(&va, f_blocks)) {
7090 		mp->mnt_vfsstat.f_blocks = va.f_blocks;
7091 	}
7092 	if (VFSATTR_IS_SUPPORTED(&va, f_bfree)) {
7093 		mp->mnt_vfsstat.f_bfree = va.f_bfree;
7094 	}
7095 	if (VFSATTR_IS_SUPPORTED(&va, f_bavail)) {
7096 		mp->mnt_vfsstat.f_bavail = va.f_bavail;
7097 	}
7098 	if (VFSATTR_IS_SUPPORTED(&va, f_bused)) {
7099 		mp->mnt_vfsstat.f_bused = va.f_bused;
7100 	}
7101 	if (VFSATTR_IS_SUPPORTED(&va, f_files)) {
7102 		mp->mnt_vfsstat.f_files = va.f_files;
7103 	}
7104 	if (VFSATTR_IS_SUPPORTED(&va, f_ffree)) {
7105 		mp->mnt_vfsstat.f_ffree = va.f_ffree;
7106 	}
7107 
7108 	/* this is unlikely to change, but has to be queried for */
7109 	if (VFSATTR_IS_SUPPORTED(&va, f_fssubtype)) {
7110 		mp->mnt_vfsstat.f_fssubtype = va.f_fssubtype;
7111 	}
7112 
7113 	return 0;
7114 }
7115 
7116 int
mount_list_add(mount_t mp)7117 mount_list_add(mount_t mp)
7118 {
7119 	int res;
7120 
7121 	mount_list_lock();
7122 	if (get_system_inshutdown() != 0) {
7123 		res = -1;
7124 	} else {
7125 		TAILQ_INSERT_TAIL(&mountlist, mp, mnt_list);
7126 		nummounts++;
7127 		res = 0;
7128 	}
7129 	mount_list_unlock();
7130 
7131 	return res;
7132 }
7133 
7134 void
mount_list_remove(mount_t mp)7135 mount_list_remove(mount_t mp)
7136 {
7137 	mount_list_lock();
7138 	TAILQ_REMOVE(&mountlist, mp, mnt_list);
7139 	nummounts--;
7140 	mp->mnt_list.tqe_next = NULL;
7141 	mp->mnt_list.tqe_prev = NULL;
7142 	mount_list_unlock();
7143 }
7144 
7145 mount_t
mount_lookupby_volfsid(int volfs_id,int withref)7146 mount_lookupby_volfsid(int volfs_id, int withref)
7147 {
7148 	mount_t cur_mount = (mount_t)0;
7149 	mount_t mp;
7150 
7151 	mount_list_lock();
7152 	TAILQ_FOREACH(mp, &mountlist, mnt_list) {
7153 		if (!(mp->mnt_kern_flag & MNTK_UNMOUNT) &&
7154 		    (mp->mnt_kern_flag & MNTK_PATH_FROM_ID) &&
7155 		    (mp->mnt_vfsstat.f_fsid.val[0] == volfs_id)) {
7156 			cur_mount = mp;
7157 			if (withref) {
7158 				if (mount_iterref(cur_mount, 1)) {
7159 					cur_mount = (mount_t)0;
7160 					mount_list_unlock();
7161 					goto out;
7162 				}
7163 			}
7164 			break;
7165 		}
7166 	}
7167 	mount_list_unlock();
7168 	if (withref && (cur_mount != (mount_t)0)) {
7169 		mp = cur_mount;
7170 		if (vfs_busy(mp, LK_NOWAIT) != 0) {
7171 			cur_mount = (mount_t)0;
7172 		}
7173 		mount_iterdrop(mp);
7174 	}
7175 out:
7176 	return cur_mount;
7177 }
7178 
7179 mount_t
mount_list_lookupby_fsid(fsid_t * fsid,int locked,int withref)7180 mount_list_lookupby_fsid(fsid_t *fsid, int locked, int withref)
7181 {
7182 	mount_t retmp = (mount_t)0;
7183 	mount_t mp;
7184 
7185 	if (!locked) {
7186 		mount_list_lock();
7187 	}
7188 	TAILQ_FOREACH(mp, &mountlist, mnt_list)
7189 	if (mp->mnt_vfsstat.f_fsid.val[0] == fsid->val[0] &&
7190 	    mp->mnt_vfsstat.f_fsid.val[1] == fsid->val[1]) {
7191 		retmp = mp;
7192 		if (withref) {
7193 			if (mount_iterref(retmp, 1)) {
7194 				retmp = (mount_t)0;
7195 			}
7196 		}
7197 		goto out;
7198 	}
7199 out:
7200 	if (!locked) {
7201 		mount_list_unlock();
7202 	}
7203 	return retmp;
7204 }
7205 
7206 errno_t
vnode_lookupat(const char * path,int flags,vnode_t * vpp,vfs_context_t ctx,vnode_t start_dvp)7207 vnode_lookupat(const char *path, int flags, vnode_t *vpp, vfs_context_t ctx,
7208     vnode_t start_dvp)
7209 {
7210 	struct nameidata *ndp;
7211 	int error = 0;
7212 	u_int32_t ndflags = 0;
7213 
7214 	if (ctx == NULL) {
7215 		return EINVAL;
7216 	}
7217 
7218 	ndp = kalloc_type(struct nameidata, Z_WAITOK | Z_NOFAIL);
7219 
7220 	if (flags & VNODE_LOOKUP_NOFOLLOW) {
7221 		ndflags = NOFOLLOW;
7222 	} else {
7223 		ndflags = FOLLOW;
7224 	}
7225 
7226 	if (flags & VNODE_LOOKUP_NOCROSSMOUNT) {
7227 		ndflags |= NOCROSSMOUNT;
7228 	}
7229 
7230 	if (flags & VNODE_LOOKUP_CROSSMOUNTNOWAIT) {
7231 		ndflags |= CN_NBMOUNTLOOK;
7232 	}
7233 
7234 	/* XXX AUDITVNPATH1 needed ? */
7235 	NDINIT(ndp, LOOKUP, OP_LOOKUP, ndflags, UIO_SYSSPACE,
7236 	    CAST_USER_ADDR_T(path), ctx);
7237 
7238 	if (start_dvp && (path[0] != '/')) {
7239 		ndp->ni_dvp = start_dvp;
7240 		ndp->ni_cnd.cn_flags |= USEDVP;
7241 	}
7242 
7243 	if ((error = namei(ndp))) {
7244 		goto out_free;
7245 	}
7246 
7247 	ndp->ni_cnd.cn_flags &= ~USEDVP;
7248 
7249 	*vpp = ndp->ni_vp;
7250 	nameidone(ndp);
7251 
7252 out_free:
7253 	kfree_type(struct nameidata, ndp);
7254 	return error;
7255 }
7256 
7257 errno_t
vnode_lookup(const char * path,int flags,vnode_t * vpp,vfs_context_t ctx)7258 vnode_lookup(const char *path, int flags, vnode_t *vpp, vfs_context_t ctx)
7259 {
7260 	return vnode_lookupat(path, flags, vpp, ctx, NULLVP);
7261 }
7262 
7263 errno_t
vnode_open(const char * path,int fmode,int cmode,int flags,vnode_t * vpp,vfs_context_t ctx)7264 vnode_open(const char *path, int fmode, int cmode, int flags, vnode_t *vpp, vfs_context_t ctx)
7265 {
7266 	struct nameidata *ndp = NULL;
7267 	int error;
7268 	u_int32_t ndflags = 0;
7269 	int lflags = flags;
7270 
7271 	if (ctx == NULL) {              /* XXX technically an error */
7272 		ctx = vfs_context_current();
7273 	}
7274 
7275 	ndp = kalloc_type(struct nameidata, Z_WAITOK | Z_NOFAIL);
7276 
7277 	if (fmode & O_NOFOLLOW) {
7278 		lflags |= VNODE_LOOKUP_NOFOLLOW;
7279 	}
7280 
7281 	if (lflags & VNODE_LOOKUP_NOFOLLOW) {
7282 		ndflags = NOFOLLOW;
7283 	} else {
7284 		ndflags = FOLLOW;
7285 	}
7286 
7287 	if (lflags & VNODE_LOOKUP_NOCROSSMOUNT) {
7288 		ndflags |= NOCROSSMOUNT;
7289 	}
7290 
7291 	if (lflags & VNODE_LOOKUP_CROSSMOUNTNOWAIT) {
7292 		ndflags |= CN_NBMOUNTLOOK;
7293 	}
7294 
7295 	/* XXX AUDITVNPATH1 needed ? */
7296 	NDINIT(ndp, LOOKUP, OP_OPEN, ndflags, UIO_SYSSPACE,
7297 	    CAST_USER_ADDR_T(path), ctx);
7298 
7299 	if ((error = vn_open(ndp, fmode, cmode))) {
7300 		*vpp = NULL;
7301 	} else {
7302 		*vpp = ndp->ni_vp;
7303 	}
7304 
7305 	kfree_type(struct nameidata, ndp);
7306 	return error;
7307 }
7308 
7309 errno_t
vnode_close(vnode_t vp,int flags,vfs_context_t ctx)7310 vnode_close(vnode_t vp, int flags, vfs_context_t ctx)
7311 {
7312 	int error;
7313 
7314 	if (ctx == NULL) {
7315 		ctx = vfs_context_current();
7316 	}
7317 
7318 	error = vn_close(vp, flags, ctx);
7319 	vnode_put(vp);
7320 	return error;
7321 }
7322 
7323 errno_t
vnode_mtime(vnode_t vp,struct timespec * mtime,vfs_context_t ctx)7324 vnode_mtime(vnode_t vp, struct timespec *mtime, vfs_context_t ctx)
7325 {
7326 	struct vnode_attr       va;
7327 	int                     error;
7328 
7329 	VATTR_INIT(&va);
7330 	VATTR_WANTED(&va, va_modify_time);
7331 	error = vnode_getattr(vp, &va, ctx);
7332 	if (!error) {
7333 		*mtime = va.va_modify_time;
7334 	}
7335 	return error;
7336 }
7337 
7338 errno_t
vnode_flags(vnode_t vp,uint32_t * flags,vfs_context_t ctx)7339 vnode_flags(vnode_t vp, uint32_t *flags, vfs_context_t ctx)
7340 {
7341 	struct vnode_attr       va;
7342 	int                     error;
7343 
7344 	VATTR_INIT(&va);
7345 	VATTR_WANTED(&va, va_flags);
7346 	error = vnode_getattr(vp, &va, ctx);
7347 	if (!error) {
7348 		*flags = va.va_flags;
7349 	}
7350 	return error;
7351 }
7352 
7353 /*
7354  * Returns:	0			Success
7355  *	vnode_getattr:???
7356  */
7357 errno_t
vnode_size(vnode_t vp,off_t * sizep,vfs_context_t ctx)7358 vnode_size(vnode_t vp, off_t *sizep, vfs_context_t ctx)
7359 {
7360 	struct vnode_attr       va;
7361 	int                     error;
7362 
7363 	VATTR_INIT(&va);
7364 	VATTR_WANTED(&va, va_data_size);
7365 	error = vnode_getattr(vp, &va, ctx);
7366 	if (!error) {
7367 		*sizep = va.va_data_size;
7368 	}
7369 	return error;
7370 }
7371 
7372 errno_t
vnode_setsize(vnode_t vp,off_t size,int ioflag,vfs_context_t ctx)7373 vnode_setsize(vnode_t vp, off_t size, int ioflag, vfs_context_t ctx)
7374 {
7375 	struct vnode_attr       va;
7376 
7377 	VATTR_INIT(&va);
7378 	VATTR_SET(&va, va_data_size, size);
7379 	va.va_vaflags = ioflag & 0xffff;
7380 	return vnode_setattr(vp, &va, ctx);
7381 }
7382 
7383 int
vnode_setdirty(vnode_t vp)7384 vnode_setdirty(vnode_t vp)
7385 {
7386 	vnode_lock_spin(vp);
7387 	vp->v_flag |= VISDIRTY;
7388 	vnode_unlock(vp);
7389 	return 0;
7390 }
7391 
7392 int
vnode_cleardirty(vnode_t vp)7393 vnode_cleardirty(vnode_t vp)
7394 {
7395 	vnode_lock_spin(vp);
7396 	vp->v_flag &= ~VISDIRTY;
7397 	vnode_unlock(vp);
7398 	return 0;
7399 }
7400 
7401 int
vnode_isdirty(vnode_t vp)7402 vnode_isdirty(vnode_t vp)
7403 {
7404 	int dirty;
7405 
7406 	vnode_lock_spin(vp);
7407 	dirty = (vp->v_flag & VISDIRTY) ? 1 : 0;
7408 	vnode_unlock(vp);
7409 
7410 	return dirty;
7411 }
7412 
7413 static int
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)7414 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)
7415 {
7416 	/* Only use compound VNOP for compound operation */
7417 	if (vnode_compound_open_available(dvp) && ((flags & VN_CREATE_DOOPEN) != 0)) {
7418 		*vpp = NULLVP;
7419 		return VNOP_COMPOUND_OPEN(dvp, vpp, ndp, O_CREAT, fmode, statusp, vap, ctx);
7420 	} else {
7421 		return VNOP_CREATE(dvp, vpp, &ndp->ni_cnd, vap, ctx);
7422 	}
7423 }
7424 
7425 /*
7426  * Create a filesystem object of arbitrary type with arbitrary attributes in
7427  * the spevied directory with the specified name.
7428  *
7429  * Parameters:	dvp			Pointer to the vnode of the directory
7430  *					in which to create the object.
7431  *		vpp			Pointer to the area into which to
7432  *					return the vnode of the created object.
7433  *		cnp			Component name pointer from the namei
7434  *					data structure, containing the name to
7435  *					use for the create object.
7436  *		vap			Pointer to the vnode_attr structure
7437  *					describing the object to be created,
7438  *					including the type of object.
7439  *		flags			VN_* flags controlling ACL inheritance
7440  *					and whether or not authorization is to
7441  *					be required for the operation.
7442  *
7443  * Returns:	0			Success
7444  *		!0			errno value
7445  *
7446  * Implicit:	*vpp			Contains the vnode of the object that
7447  *					was created, if successful.
7448  *		*cnp			May be modified by the underlying VFS.
7449  *		*vap			May be modified by the underlying VFS.
7450  *					modified by either ACL inheritance or
7451  *
7452  *
7453  *					be modified, even if the operation is
7454  *
7455  *
7456  * Notes:	The kauth_filesec_t in 'vap', if any, is in host byte order.
7457  *
7458  *		Modification of '*cnp' and '*vap' by the underlying VFS is
7459  *		strongly discouraged.
7460  *
7461  * XXX:		This function is a 'vn_*' function; it belongs in vfs_vnops.c
7462  *
7463  * XXX:		We should enummerate the possible errno values here, and where
7464  *		in the code they originated.
7465  */
7466 errno_t
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)7467 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)
7468 {
7469 	errno_t error, old_error;
7470 	vnode_t vp = (vnode_t)0;
7471 	boolean_t batched;
7472 	struct componentname *cnp;
7473 	uint32_t defaulted;
7474 
7475 	cnp = &ndp->ni_cnd;
7476 	error = 0;
7477 	batched = namei_compound_available(dvp, ndp) ? TRUE : FALSE;
7478 
7479 	KAUTH_DEBUG("%p    CREATE - '%s'", dvp, cnp->cn_nameptr);
7480 
7481 	if (flags & VN_CREATE_NOINHERIT) {
7482 		vap->va_vaflags |= VA_NOINHERIT;
7483 	}
7484 	if (flags & VN_CREATE_NOAUTH) {
7485 		vap->va_vaflags |= VA_NOAUTH;
7486 	}
7487 	/*
7488 	 * Handle ACL inheritance, initialize vap.
7489 	 */
7490 	error = vn_attribute_prepare(dvp, vap, &defaulted, ctx);
7491 	if (error) {
7492 		return error;
7493 	}
7494 
7495 	if (vap->va_type != VREG && (fmode != 0 || (flags & VN_CREATE_DOOPEN) || statusp)) {
7496 		panic("Open parameters, but not a regular file.");
7497 	}
7498 	if ((fmode != 0) && ((flags & VN_CREATE_DOOPEN) == 0)) {
7499 		panic("Mode for open, but not trying to open...");
7500 	}
7501 
7502 
7503 	/*
7504 	 * Create the requested node.
7505 	 */
7506 	switch (vap->va_type) {
7507 	case VREG:
7508 		error = vn_create_reg(dvp, vpp, ndp, vap, flags, fmode, statusp, ctx);
7509 		break;
7510 	case VDIR:
7511 		error = vn_mkdir(dvp, vpp, ndp, vap, ctx);
7512 		break;
7513 	case VSOCK:
7514 	case VFIFO:
7515 	case VBLK:
7516 	case VCHR:
7517 		error = VNOP_MKNOD(dvp, vpp, cnp, vap, ctx);
7518 		break;
7519 	default:
7520 		panic("vnode_create: unknown vtype %d", vap->va_type);
7521 	}
7522 	if (error != 0) {
7523 		KAUTH_DEBUG("%p    CREATE - error %d returned by filesystem", dvp, error);
7524 		goto out;
7525 	}
7526 
7527 	vp = *vpp;
7528 	old_error = error;
7529 
7530 	/*
7531 	 * If some of the requested attributes weren't handled by the VNOP,
7532 	 * use our fallback code.
7533 	 */
7534 	if ((error == 0) && !VATTR_ALL_SUPPORTED(vap) && *vpp) {
7535 		KAUTH_DEBUG("     CREATE - doing fallback with ACL %p", vap->va_acl);
7536 		error = vnode_setattr_fallback(*vpp, vap, ctx);
7537 	}
7538 
7539 #if CONFIG_MACF
7540 	if ((error == 0) && !(flags & VN_CREATE_NOLABEL)) {
7541 		error = vnode_label(vnode_mount(vp), dvp, vp, cnp, VNODE_LABEL_CREATE, ctx);
7542 	}
7543 #endif
7544 
7545 	if ((error != 0) && (vp != (vnode_t)0)) {
7546 		/* If we've done a compound open, close */
7547 		if (batched && (old_error == 0) && (vap->va_type == VREG)) {
7548 			VNOP_CLOSE(vp, fmode, ctx);
7549 		}
7550 
7551 		/* Need to provide notifications if a create succeeded */
7552 		if (!batched) {
7553 			*vpp = (vnode_t) 0;
7554 			vnode_put(vp);
7555 			vp = NULLVP;
7556 		}
7557 	}
7558 
7559 	/*
7560 	 * For creation VNOPs, this is the equivalent of
7561 	 * lookup_handle_found_vnode.
7562 	 */
7563 	if (kdebug_enable && *vpp) {
7564 		kdebug_lookup(*vpp, cnp);
7565 	}
7566 
7567 out:
7568 	vn_attribute_cleanup(vap, defaulted);
7569 
7570 	return error;
7571 }
7572 
7573 static kauth_scope_t    vnode_scope;
7574 static int      vnode_authorize_callback(kauth_cred_t credential, void *idata, kauth_action_t action,
7575     uintptr_t arg0, uintptr_t arg1, uintptr_t arg2, uintptr_t arg3);
7576 static int vnode_authorize_callback_int(kauth_action_t action, vfs_context_t ctx,
7577     vnode_t vp, vnode_t dvp, int *errorp);
7578 
7579 typedef struct _vnode_authorize_context {
7580 	vnode_t         vp;
7581 	struct vnode_attr *vap;
7582 	vnode_t         dvp;
7583 	struct vnode_attr *dvap;
7584 	vfs_context_t   ctx;
7585 	int             flags;
7586 	int             flags_valid;
7587 #define _VAC_IS_OWNER           (1<<0)
7588 #define _VAC_IN_GROUP           (1<<1)
7589 #define _VAC_IS_DIR_OWNER       (1<<2)
7590 #define _VAC_IN_DIR_GROUP       (1<<3)
7591 #define _VAC_NO_VNODE_POINTERS  (1<<4)
7592 } *vauth_ctx;
7593 
7594 void
vnode_authorize_init(void)7595 vnode_authorize_init(void)
7596 {
7597 	vnode_scope = kauth_register_scope(KAUTH_SCOPE_VNODE, vnode_authorize_callback, NULL);
7598 }
7599 
7600 #define VATTR_PREPARE_DEFAULTED_UID             0x1
7601 #define VATTR_PREPARE_DEFAULTED_GID             0x2
7602 #define VATTR_PREPARE_DEFAULTED_MODE            0x4
7603 
7604 int
vn_attribute_prepare(vnode_t dvp,struct vnode_attr * vap,uint32_t * defaulted_fieldsp,vfs_context_t ctx)7605 vn_attribute_prepare(vnode_t dvp, struct vnode_attr *vap, uint32_t *defaulted_fieldsp, vfs_context_t ctx)
7606 {
7607 	kauth_acl_t nacl = NULL, oacl = NULL;
7608 	int error;
7609 
7610 	/*
7611 	 * Handle ACL inheritance.
7612 	 */
7613 	if (!(vap->va_vaflags & VA_NOINHERIT) && vfs_extendedsecurity(dvp->v_mount)) {
7614 		/* save the original filesec */
7615 		if (VATTR_IS_ACTIVE(vap, va_acl)) {
7616 			oacl = vap->va_acl;
7617 		}
7618 
7619 		vap->va_acl = NULL;
7620 		if ((error = kauth_acl_inherit(dvp,
7621 		    oacl,
7622 		    &nacl,
7623 		    vap->va_type == VDIR,
7624 		    ctx)) != 0) {
7625 			KAUTH_DEBUG("%p    CREATE - error %d processing inheritance", dvp, error);
7626 			return error;
7627 		}
7628 
7629 		/*
7630 		 * If the generated ACL is NULL, then we can save ourselves some effort
7631 		 * by clearing the active bit.
7632 		 */
7633 		if (nacl == NULL) {
7634 			VATTR_CLEAR_ACTIVE(vap, va_acl);
7635 		} else {
7636 			vap->va_base_acl = oacl;
7637 			VATTR_SET(vap, va_acl, nacl);
7638 		}
7639 	}
7640 
7641 	error = vnode_authattr_new_internal(dvp, vap, (vap->va_vaflags & VA_NOAUTH), defaulted_fieldsp, ctx);
7642 	if (error) {
7643 		vn_attribute_cleanup(vap, *defaulted_fieldsp);
7644 	}
7645 
7646 	return error;
7647 }
7648 
7649 void
vn_attribute_cleanup(struct vnode_attr * vap,uint32_t defaulted_fields)7650 vn_attribute_cleanup(struct vnode_attr *vap, uint32_t defaulted_fields)
7651 {
7652 	/*
7653 	 * If the caller supplied a filesec in vap, it has been replaced
7654 	 * now by the post-inheritance copy.  We need to put the original back
7655 	 * and free the inherited product.
7656 	 */
7657 	kauth_acl_t nacl, oacl;
7658 
7659 	if (VATTR_IS_ACTIVE(vap, va_acl)) {
7660 		nacl = vap->va_acl;
7661 		oacl = vap->va_base_acl;
7662 
7663 		if (oacl) {
7664 			VATTR_SET(vap, va_acl, oacl);
7665 			vap->va_base_acl = NULL;
7666 		} else {
7667 			VATTR_CLEAR_ACTIVE(vap, va_acl);
7668 		}
7669 
7670 		if (nacl != NULL) {
7671 			/*
7672 			 * Only free the ACL buffer if 'VA_FILESEC_ACL' is not set as it
7673 			 * should be freed by the caller or it is a post-inheritance copy.
7674 			 */
7675 			if (!(vap->va_vaflags & VA_FILESEC_ACL) ||
7676 			    (oacl != NULL && nacl != oacl)) {
7677 				kauth_acl_free(nacl);
7678 			}
7679 		}
7680 	}
7681 
7682 	if ((defaulted_fields & VATTR_PREPARE_DEFAULTED_MODE) != 0) {
7683 		VATTR_CLEAR_ACTIVE(vap, va_mode);
7684 	}
7685 	if ((defaulted_fields & VATTR_PREPARE_DEFAULTED_GID) != 0) {
7686 		VATTR_CLEAR_ACTIVE(vap, va_gid);
7687 	}
7688 	if ((defaulted_fields & VATTR_PREPARE_DEFAULTED_UID) != 0) {
7689 		VATTR_CLEAR_ACTIVE(vap, va_uid);
7690 	}
7691 
7692 	return;
7693 }
7694 
7695 int
vn_authorize_unlink(vnode_t dvp,vnode_t vp,struct componentname * cnp,vfs_context_t ctx,__unused void * reserved)7696 vn_authorize_unlink(vnode_t dvp, vnode_t vp, struct componentname *cnp, vfs_context_t ctx, __unused void *reserved)
7697 {
7698 #if !CONFIG_MACF
7699 #pragma unused(cnp)
7700 #endif
7701 	int error = 0;
7702 
7703 	/*
7704 	 * Normally, unlinking of directories is not supported.
7705 	 * However, some file systems may have limited support.
7706 	 */
7707 	if ((vp->v_type == VDIR) &&
7708 	    !(vp->v_mount->mnt_kern_flag & MNTK_DIR_HARDLINKS)) {
7709 		return EPERM; /* POSIX */
7710 	}
7711 
7712 	/* authorize the delete operation */
7713 #if CONFIG_MACF
7714 	if (!error) {
7715 		error = mac_vnode_check_unlink(ctx, dvp, vp, cnp);
7716 	}
7717 #endif /* MAC */
7718 	if (!error) {
7719 		error = vnode_authorize(vp, dvp, KAUTH_VNODE_DELETE, ctx);
7720 	}
7721 
7722 	return error;
7723 }
7724 
7725 int
vn_authorize_open_existing(vnode_t vp,struct componentname * cnp,int fmode,vfs_context_t ctx,void * reserved)7726 vn_authorize_open_existing(vnode_t vp, struct componentname *cnp, int fmode, vfs_context_t ctx, void *reserved)
7727 {
7728 	/* Open of existing case */
7729 	kauth_action_t action;
7730 	int error = 0;
7731 	if (cnp->cn_ndp == NULL) {
7732 		panic("NULL ndp");
7733 	}
7734 	if (reserved != NULL) {
7735 		panic("reserved not NULL.");
7736 	}
7737 
7738 #if CONFIG_MACF
7739 	/* XXX may do duplicate work here, but ignore that for now (idempotent) */
7740 	if (vfs_flags(vnode_mount(vp)) & MNT_MULTILABEL) {
7741 		error = vnode_label(vnode_mount(vp), NULL, vp, NULL, 0, ctx);
7742 		if (error) {
7743 			return error;
7744 		}
7745 	}
7746 #endif
7747 
7748 	if (vnode_isdir(vp)) {
7749 		if ((fmode & (FWRITE | O_TRUNC)) || /* disallow write operations on directories */
7750 		    ((fmode & FSEARCH) && !(fmode & O_DIRECTORY))) {
7751 			return EISDIR;
7752 		}
7753 	} else {
7754 		if (fmode & O_DIRECTORY) {
7755 			return ENOTDIR;
7756 		}
7757 
7758 		if (vp->v_type == VSOCK && vp->v_tag != VT_FDESC) {
7759 			return EOPNOTSUPP;    /* Operation not supported on socket */
7760 		}
7761 
7762 		if (vp->v_type == VLNK && (fmode & O_NOFOLLOW) != 0) {
7763 			return ELOOP;         /* O_NOFOLLOW was specified and the target is a symbolic link */
7764 		}
7765 
7766 		if (cnp->cn_ndp->ni_flag & NAMEI_TRAILINGSLASH) {
7767 			return ENOTDIR;
7768 		}
7769 
7770 		if (!vnode_isreg(vp) && (fmode & FEXEC)) {
7771 			return EACCES;
7772 		}
7773 	}
7774 
7775 #if CONFIG_MACF
7776 	/* If a file being opened is a shadow file containing
7777 	 * namedstream data, ignore the macf checks because it
7778 	 * is a kernel internal file and access should always
7779 	 * be allowed.
7780 	 */
7781 	if (!(vnode_isshadow(vp) && vnode_isnamedstream(vp))) {
7782 		error = mac_vnode_check_open(ctx, vp, fmode);
7783 		if (error) {
7784 			return error;
7785 		}
7786 	}
7787 #endif
7788 
7789 	/* compute action to be authorized */
7790 	action = 0;
7791 	if (fmode & FREAD) {
7792 		action |= KAUTH_VNODE_READ_DATA;
7793 	}
7794 	if (fmode & (FWRITE | O_TRUNC)) {
7795 		/*
7796 		 * If we are writing, appending, and not truncating,
7797 		 * indicate that we are appending so that if the
7798 		 * UF_APPEND or SF_APPEND bits are set, we do not deny
7799 		 * the open.
7800 		 */
7801 		if ((fmode & O_APPEND) && !(fmode & O_TRUNC)) {
7802 			action |= KAUTH_VNODE_APPEND_DATA;
7803 		} else {
7804 			action |= KAUTH_VNODE_WRITE_DATA;
7805 		}
7806 	}
7807 	if (fmode & (FSEARCH | FEXEC)) {
7808 		if (vnode_isdir(vp)) {
7809 			action |= KAUTH_VNODE_SEARCH;
7810 		} else {
7811 			action |= KAUTH_VNODE_EXECUTE;
7812 		}
7813 	}
7814 	error = vnode_authorize(vp, NULL, action, ctx);
7815 #if NAMEDSTREAMS
7816 	if (error == EACCES) {
7817 		/*
7818 		 * Shadow files may exist on-disk with a different UID/GID
7819 		 * than that of the current context.  Verify that this file
7820 		 * is really a shadow file.  If it was created successfully
7821 		 * then it should be authorized.
7822 		 */
7823 		if (vnode_isshadow(vp) && vnode_isnamedstream(vp)) {
7824 			error = vnode_verifynamedstream(vp);
7825 		}
7826 	}
7827 #endif
7828 
7829 	return error;
7830 }
7831 
7832 int
vn_authorize_create(vnode_t dvp,struct componentname * cnp,struct vnode_attr * vap,vfs_context_t ctx,void * reserved)7833 vn_authorize_create(vnode_t dvp, struct componentname *cnp, struct vnode_attr *vap, vfs_context_t ctx, void *reserved)
7834 {
7835 #if !CONFIG_MACF
7836 #pragma unused(vap)
7837 #endif
7838 	/* Creation case */
7839 	int error;
7840 
7841 	if (cnp->cn_ndp == NULL) {
7842 		panic("NULL cn_ndp");
7843 	}
7844 	if (reserved != NULL) {
7845 		panic("reserved not NULL.");
7846 	}
7847 
7848 	/* Only validate path for creation if we didn't do a complete lookup */
7849 	if (cnp->cn_ndp->ni_flag & NAMEI_UNFINISHED) {
7850 		error = lookup_validate_creation_path(cnp->cn_ndp);
7851 		if (error) {
7852 			return error;
7853 		}
7854 	}
7855 
7856 #if CONFIG_MACF
7857 	error = mac_vnode_check_create(ctx, dvp, cnp, vap);
7858 	if (error) {
7859 		return error;
7860 	}
7861 #endif /* CONFIG_MACF */
7862 
7863 	return vnode_authorize(dvp, NULL, KAUTH_VNODE_ADD_FILE, ctx);
7864 }
7865 
7866 int
vn_authorize_rename(struct vnode * fdvp,struct vnode * fvp,struct componentname * fcnp,struct vnode * tdvp,struct vnode * tvp,struct componentname * tcnp,vfs_context_t ctx,void * reserved)7867 vn_authorize_rename(struct vnode *fdvp, struct vnode *fvp, struct componentname *fcnp,
7868     struct vnode *tdvp, struct vnode *tvp, struct componentname *tcnp,
7869     vfs_context_t ctx, void *reserved)
7870 {
7871 	return vn_authorize_renamex(fdvp, fvp, fcnp, tdvp, tvp, tcnp, ctx, 0, reserved);
7872 }
7873 
7874 int
vn_authorize_renamex(struct vnode * fdvp,struct vnode * fvp,struct componentname * fcnp,struct vnode * tdvp,struct vnode * tvp,struct componentname * tcnp,vfs_context_t ctx,vfs_rename_flags_t flags,void * reserved)7875 vn_authorize_renamex(struct vnode *fdvp, struct vnode *fvp, struct componentname *fcnp,
7876     struct vnode *tdvp, struct vnode *tvp, struct componentname *tcnp,
7877     vfs_context_t ctx, vfs_rename_flags_t flags, void *reserved)
7878 {
7879 	return vn_authorize_renamex_with_paths(fdvp, fvp, fcnp, NULL, tdvp, tvp, tcnp, NULL, ctx, flags, reserved);
7880 }
7881 
7882 int
vn_authorize_renamex_with_paths(struct vnode * fdvp,struct vnode * fvp,struct componentname * fcnp,const char * from_path,struct vnode * tdvp,struct vnode * tvp,struct componentname * tcnp,const char * to_path,vfs_context_t ctx,vfs_rename_flags_t flags,void * reserved)7883 vn_authorize_renamex_with_paths(struct vnode *fdvp, struct vnode *fvp, struct componentname *fcnp, const char *from_path,
7884     struct vnode *tdvp, struct vnode *tvp, struct componentname *tcnp, const char *to_path,
7885     vfs_context_t ctx, vfs_rename_flags_t flags, void *reserved)
7886 {
7887 	int error = 0;
7888 	int moving = 0;
7889 	bool swap = flags & VFS_RENAME_SWAP;
7890 
7891 	if (reserved != NULL) {
7892 		panic("Passed something other than NULL as reserved field!");
7893 	}
7894 
7895 	/*
7896 	 * Avoid renaming "." and "..".
7897 	 *
7898 	 * XXX No need to check for this in the FS.  We should always have the leaves
7899 	 * in VFS in this case.
7900 	 */
7901 	if (fvp->v_type == VDIR &&
7902 	    ((fdvp == fvp) ||
7903 	    (fcnp->cn_namelen == 1 && fcnp->cn_nameptr[0] == '.') ||
7904 	    ((fcnp->cn_flags | tcnp->cn_flags) & ISDOTDOT))) {
7905 		error = EINVAL;
7906 		goto out;
7907 	}
7908 
7909 	if (tvp == NULLVP && vnode_compound_rename_available(tdvp)) {
7910 		error = lookup_validate_creation_path(tcnp->cn_ndp);
7911 		if (error) {
7912 			goto out;
7913 		}
7914 	}
7915 
7916 	/***** <MACF> *****/
7917 #if CONFIG_MACF
7918 	error = mac_vnode_check_rename(ctx, fdvp, fvp, fcnp, tdvp, tvp, tcnp);
7919 	if (error) {
7920 		goto out;
7921 	}
7922 	if (swap) {
7923 		error = mac_vnode_check_rename(ctx, tdvp, tvp, tcnp, fdvp, fvp, fcnp);
7924 		if (error) {
7925 			goto out;
7926 		}
7927 	}
7928 #endif
7929 	/***** </MACF> *****/
7930 
7931 	/***** <MiscChecks> *****/
7932 	if (tvp != NULL) {
7933 		if (!swap) {
7934 			if (fvp->v_type == VDIR && tvp->v_type != VDIR) {
7935 				error = ENOTDIR;
7936 				goto out;
7937 			} else if (fvp->v_type != VDIR && tvp->v_type == VDIR) {
7938 				error = EISDIR;
7939 				goto out;
7940 			}
7941 		}
7942 	} else if (swap) {
7943 		/*
7944 		 * Caller should have already checked this and returned
7945 		 * ENOENT.  If we send back ENOENT here, caller will retry
7946 		 * which isn't what we want so we send back EINVAL here
7947 		 * instead.
7948 		 */
7949 		error = EINVAL;
7950 		goto out;
7951 	}
7952 
7953 	if (fvp == tdvp) {
7954 		error = EINVAL;
7955 		goto out;
7956 	}
7957 
7958 	/*
7959 	 * The following edge case is caught here:
7960 	 * (to cannot be a descendent of from)
7961 	 *
7962 	 *       o fdvp
7963 	 *      /
7964 	 *     /
7965 	 *    o fvp
7966 	 *     \
7967 	 *      \
7968 	 *       o tdvp
7969 	 *      /
7970 	 *     /
7971 	 *    o tvp
7972 	 */
7973 	if (tdvp->v_parent == fvp) {
7974 		error = EINVAL;
7975 		goto out;
7976 	}
7977 
7978 	if (swap && fdvp->v_parent == tvp) {
7979 		error = EINVAL;
7980 		goto out;
7981 	}
7982 	/***** </MiscChecks> *****/
7983 
7984 	/***** <Kauth> *****/
7985 
7986 	/*
7987 	 * As part of the Kauth step, we call out to allow 3rd-party
7988 	 * fileop notification of "about to rename".  This is needed
7989 	 * in the event that 3rd-parties need to know that the DELETE
7990 	 * authorization is actually part of a rename.  It's important
7991 	 * that we guarantee that the DELETE call-out will always be
7992 	 * made if the WILL_RENAME call-out is made.  Another fileop
7993 	 * call-out will be performed once the operation is completed.
7994 	 * We can ignore the result of kauth_authorize_fileop().
7995 	 *
7996 	 * N.B. We are passing the vnode and *both* paths to each
7997 	 * call; kauth_authorize_fileop() extracts the "from" path
7998 	 * when posting a KAUTH_FILEOP_WILL_RENAME notification.
7999 	 * As such, we only post these notifications if all of the
8000 	 * information we need is provided.
8001 	 */
8002 
8003 	if (swap) {
8004 		kauth_action_t f = 0, t = 0;
8005 
8006 		/*
8007 		 * Directories changing parents need ...ADD_SUBDIR...  to
8008 		 * permit changing ".."
8009 		 */
8010 		if (fdvp != tdvp) {
8011 			if (vnode_isdir(fvp)) {
8012 				f = KAUTH_VNODE_ADD_SUBDIRECTORY;
8013 			}
8014 			if (vnode_isdir(tvp)) {
8015 				t = KAUTH_VNODE_ADD_SUBDIRECTORY;
8016 			}
8017 		}
8018 		if (to_path != NULL) {
8019 			kauth_authorize_fileop(vfs_context_ucred(ctx),
8020 			    KAUTH_FILEOP_WILL_RENAME,
8021 			    (uintptr_t)fvp,
8022 			    (uintptr_t)to_path);
8023 		}
8024 		error = vnode_authorize(fvp, fdvp, KAUTH_VNODE_DELETE | f, ctx);
8025 		if (error) {
8026 			goto out;
8027 		}
8028 		if (from_path != NULL) {
8029 			kauth_authorize_fileop(vfs_context_ucred(ctx),
8030 			    KAUTH_FILEOP_WILL_RENAME,
8031 			    (uintptr_t)tvp,
8032 			    (uintptr_t)from_path);
8033 		}
8034 		error = vnode_authorize(tvp, tdvp, KAUTH_VNODE_DELETE | t, ctx);
8035 		if (error) {
8036 			goto out;
8037 		}
8038 		f = vnode_isdir(fvp) ? KAUTH_VNODE_ADD_SUBDIRECTORY : KAUTH_VNODE_ADD_FILE;
8039 		t = vnode_isdir(tvp) ? KAUTH_VNODE_ADD_SUBDIRECTORY : KAUTH_VNODE_ADD_FILE;
8040 		if (fdvp == tdvp) {
8041 			error = vnode_authorize(fdvp, NULL, f | t, ctx);
8042 		} else {
8043 			error = vnode_authorize(fdvp, NULL, t, ctx);
8044 			if (error) {
8045 				goto out;
8046 			}
8047 			error = vnode_authorize(tdvp, NULL, f, ctx);
8048 		}
8049 		if (error) {
8050 			goto out;
8051 		}
8052 	} else {
8053 		error = 0;
8054 		if ((tvp != NULL) && vnode_isdir(tvp)) {
8055 			if (tvp != fdvp) {
8056 				moving = 1;
8057 			}
8058 		} else if (tdvp != fdvp) {
8059 			moving = 1;
8060 		}
8061 
8062 		/*
8063 		 * must have delete rights to remove the old name even in
8064 		 * the simple case of fdvp == tdvp.
8065 		 *
8066 		 * If fvp is a directory, and we are changing it's parent,
8067 		 * then we also need rights to rewrite its ".." entry as well.
8068 		 */
8069 		if (to_path != NULL) {
8070 			kauth_authorize_fileop(vfs_context_ucred(ctx),
8071 			    KAUTH_FILEOP_WILL_RENAME,
8072 			    (uintptr_t)fvp,
8073 			    (uintptr_t)to_path);
8074 		}
8075 		if (vnode_isdir(fvp)) {
8076 			if ((error = vnode_authorize(fvp, fdvp, KAUTH_VNODE_DELETE | KAUTH_VNODE_ADD_SUBDIRECTORY, ctx)) != 0) {
8077 				goto out;
8078 			}
8079 		} else {
8080 			if ((error = vnode_authorize(fvp, fdvp, KAUTH_VNODE_DELETE, ctx)) != 0) {
8081 				goto out;
8082 			}
8083 		}
8084 		if (moving) {
8085 			/* moving into tdvp or tvp, must have rights to add */
8086 			if ((error = vnode_authorize(((tvp != NULL) && vnode_isdir(tvp)) ? tvp : tdvp,
8087 			    NULL,
8088 			    vnode_isdir(fvp) ? KAUTH_VNODE_ADD_SUBDIRECTORY : KAUTH_VNODE_ADD_FILE,
8089 			    ctx)) != 0) {
8090 				goto out;
8091 			}
8092 		} else {
8093 			/* node staying in same directory, must be allowed to add new name */
8094 			if ((error = vnode_authorize(fdvp, NULL,
8095 			    vnode_isdir(fvp) ? KAUTH_VNODE_ADD_SUBDIRECTORY : KAUTH_VNODE_ADD_FILE, ctx)) != 0) {
8096 				goto out;
8097 			}
8098 		}
8099 		/* overwriting tvp */
8100 		if ((tvp != NULL) && !vnode_isdir(tvp) &&
8101 		    ((error = vnode_authorize(tvp, tdvp, KAUTH_VNODE_DELETE, ctx)) != 0)) {
8102 			goto out;
8103 		}
8104 	}
8105 
8106 	/***** </Kauth> *****/
8107 
8108 	/* XXX more checks? */
8109 out:
8110 	return error;
8111 }
8112 
8113 int
vn_authorize_mkdir(vnode_t dvp,struct componentname * cnp,struct vnode_attr * vap,vfs_context_t ctx,void * reserved)8114 vn_authorize_mkdir(vnode_t dvp, struct componentname *cnp, struct vnode_attr *vap, vfs_context_t ctx, void *reserved)
8115 {
8116 #if !CONFIG_MACF
8117 #pragma unused(vap)
8118 #endif
8119 	int error;
8120 
8121 	if (reserved != NULL) {
8122 		panic("reserved not NULL in vn_authorize_mkdir()");
8123 	}
8124 
8125 	/* XXX A hack for now, to make shadow files work */
8126 	if (cnp->cn_ndp == NULL) {
8127 		return 0;
8128 	}
8129 
8130 	if (vnode_compound_mkdir_available(dvp)) {
8131 		error = lookup_validate_creation_path(cnp->cn_ndp);
8132 		if (error) {
8133 			goto out;
8134 		}
8135 	}
8136 
8137 #if CONFIG_MACF
8138 	error = mac_vnode_check_create(ctx,
8139 	    dvp, cnp, vap);
8140 	if (error) {
8141 		goto out;
8142 	}
8143 #endif
8144 
8145 	/* authorize addition of a directory to the parent */
8146 	if ((error = vnode_authorize(dvp, NULL, KAUTH_VNODE_ADD_SUBDIRECTORY, ctx)) != 0) {
8147 		goto out;
8148 	}
8149 
8150 out:
8151 	return error;
8152 }
8153 
8154 int
vn_authorize_rmdir(vnode_t dvp,vnode_t vp,struct componentname * cnp,vfs_context_t ctx,void * reserved)8155 vn_authorize_rmdir(vnode_t dvp, vnode_t vp, struct componentname *cnp, vfs_context_t ctx, void *reserved)
8156 {
8157 #if CONFIG_MACF
8158 	int error;
8159 #else
8160 #pragma unused(cnp)
8161 #endif
8162 	if (reserved != NULL) {
8163 		panic("Non-NULL reserved argument to vn_authorize_rmdir()");
8164 	}
8165 
8166 	if (vp->v_type != VDIR) {
8167 		/*
8168 		 * rmdir only deals with directories
8169 		 */
8170 		return ENOTDIR;
8171 	}
8172 
8173 	if (dvp == vp) {
8174 		/*
8175 		 * No rmdir "." please.
8176 		 */
8177 		return EINVAL;
8178 	}
8179 
8180 #if CONFIG_MACF
8181 	error = mac_vnode_check_unlink(ctx, dvp,
8182 	    vp, cnp);
8183 	if (error) {
8184 		return error;
8185 	}
8186 #endif
8187 
8188 	return vnode_authorize(vp, dvp, KAUTH_VNODE_DELETE, ctx);
8189 }
8190 
8191 /*
8192  * Authorizer for directory cloning. This does not use vnodes but instead
8193  * uses prefilled vnode attributes from the filesystem.
8194  *
8195  * The same function is called to set up the attributes required, perform the
8196  * authorization and cleanup (if required)
8197  */
8198 int
vnode_attr_authorize_dir_clone(struct vnode_attr * vap,kauth_action_t action,struct vnode_attr * dvap,__unused vnode_t sdvp,mount_t mp,dir_clone_authorizer_op_t vattr_op,uint32_t flags,vfs_context_t ctx,__unused void * reserved)8199 vnode_attr_authorize_dir_clone(struct vnode_attr *vap, kauth_action_t action,
8200     struct vnode_attr *dvap, __unused vnode_t sdvp, mount_t mp,
8201     dir_clone_authorizer_op_t vattr_op, uint32_t flags, vfs_context_t ctx,
8202     __unused void *reserved)
8203 {
8204 	int error;
8205 	int is_suser = vfs_context_issuser(ctx);
8206 
8207 	if (vattr_op == OP_VATTR_SETUP) {
8208 		VATTR_INIT(vap);
8209 
8210 		/*
8211 		 * When ACL inheritence is implemented, both vap->va_acl and
8212 		 * dvap->va_acl will be required (even as superuser).
8213 		 */
8214 		VATTR_WANTED(vap, va_type);
8215 		VATTR_WANTED(vap, va_mode);
8216 		VATTR_WANTED(vap, va_flags);
8217 		VATTR_WANTED(vap, va_uid);
8218 		VATTR_WANTED(vap, va_gid);
8219 		if (dvap) {
8220 			VATTR_INIT(dvap);
8221 			VATTR_WANTED(dvap, va_flags);
8222 		}
8223 
8224 		if (!is_suser) {
8225 			/*
8226 			 * If not superuser, we have to evaluate ACLs and
8227 			 * need the target directory gid to set the initial
8228 			 * gid of the new object.
8229 			 */
8230 			VATTR_WANTED(vap, va_acl);
8231 			if (dvap) {
8232 				VATTR_WANTED(dvap, va_gid);
8233 			}
8234 		} else if (dvap && (flags & VNODE_CLONEFILE_NOOWNERCOPY)) {
8235 			VATTR_WANTED(dvap, va_gid);
8236 		}
8237 		return 0;
8238 	} else if (vattr_op == OP_VATTR_CLEANUP) {
8239 		return 0; /* Nothing to do for now */
8240 	}
8241 
8242 	/* dvap isn't used for authorization */
8243 	error = vnode_attr_authorize(vap, NULL, mp, action, ctx);
8244 
8245 	if (error) {
8246 		return error;
8247 	}
8248 
8249 	/*
8250 	 * vn_attribute_prepare should be able to accept attributes as well as
8251 	 * vnodes but for now we do this inline.
8252 	 */
8253 	if (!is_suser || (flags & VNODE_CLONEFILE_NOOWNERCOPY)) {
8254 		/*
8255 		 * If the filesystem is mounted IGNORE_OWNERSHIP and an explicit
8256 		 * owner is set, that owner takes ownership of all new files.
8257 		 */
8258 		if ((mp->mnt_flag & MNT_IGNORE_OWNERSHIP) &&
8259 		    (mp->mnt_fsowner != KAUTH_UID_NONE)) {
8260 			VATTR_SET(vap, va_uid, mp->mnt_fsowner);
8261 		} else {
8262 			/* default owner is current user */
8263 			VATTR_SET(vap, va_uid,
8264 			    kauth_cred_getuid(vfs_context_ucred(ctx)));
8265 		}
8266 
8267 		if ((mp->mnt_flag & MNT_IGNORE_OWNERSHIP) &&
8268 		    (mp->mnt_fsgroup != KAUTH_GID_NONE)) {
8269 			VATTR_SET(vap, va_gid, mp->mnt_fsgroup);
8270 		} else {
8271 			/*
8272 			 * default group comes from parent object,
8273 			 * fallback to current user
8274 			 */
8275 			if (VATTR_IS_SUPPORTED(dvap, va_gid)) {
8276 				VATTR_SET(vap, va_gid, dvap->va_gid);
8277 			} else {
8278 				VATTR_SET(vap, va_gid,
8279 				    kauth_cred_getgid(vfs_context_ucred(ctx)));
8280 			}
8281 		}
8282 	}
8283 
8284 	/* Inherit SF_RESTRICTED bit from destination directory only */
8285 	if (VATTR_IS_ACTIVE(vap, va_flags)) {
8286 		VATTR_SET(vap, va_flags,
8287 		    ((vap->va_flags & ~(UF_DATAVAULT | SF_RESTRICTED)))); /* Turn off from source */
8288 		if (VATTR_IS_ACTIVE(dvap, va_flags)) {
8289 			VATTR_SET(vap, va_flags,
8290 			    vap->va_flags | (dvap->va_flags & (UF_DATAVAULT | SF_RESTRICTED)));
8291 		}
8292 	} else if (VATTR_IS_ACTIVE(dvap, va_flags)) {
8293 		VATTR_SET(vap, va_flags, (dvap->va_flags & (UF_DATAVAULT | SF_RESTRICTED)));
8294 	}
8295 
8296 	return 0;
8297 }
8298 
8299 
8300 /*
8301  * Authorize an operation on a vnode.
8302  *
8303  * This is KPI, but here because it needs vnode_scope.
8304  *
8305  * Returns:	0			Success
8306  *	kauth_authorize_action:EPERM	...
8307  *	xlate => EACCES			Permission denied
8308  *	kauth_authorize_action:0	Success
8309  *	kauth_authorize_action:		Depends on callback return; this is
8310  *					usually only vnode_authorize_callback(),
8311  *					but may include other listerners, if any
8312  *					exist.
8313  *		EROFS
8314  *		EACCES
8315  *		EPERM
8316  *		???
8317  */
8318 int
vnode_authorize(vnode_t vp,vnode_t dvp,kauth_action_t action,vfs_context_t ctx)8319 vnode_authorize(vnode_t vp, vnode_t dvp, kauth_action_t action, vfs_context_t ctx)
8320 {
8321 	int     error, result;
8322 
8323 	/*
8324 	 * We can't authorize against a dead vnode; allow all operations through so that
8325 	 * the correct error can be returned.
8326 	 */
8327 	if (vp->v_type == VBAD) {
8328 		return 0;
8329 	}
8330 
8331 	error = 0;
8332 	result = kauth_authorize_action(vnode_scope, vfs_context_ucred(ctx), action,
8333 	    (uintptr_t)ctx, (uintptr_t)vp, (uintptr_t)dvp, (uintptr_t)&error);
8334 	if (result == EPERM) {          /* traditional behaviour */
8335 		result = EACCES;
8336 	}
8337 	/* did the lower layers give a better error return? */
8338 	if ((result != 0) && (error != 0)) {
8339 		return error;
8340 	}
8341 	return result;
8342 }
8343 
8344 /*
8345  * Test for vnode immutability.
8346  *
8347  * The 'append' flag is set when the authorization request is constrained
8348  * to operations which only request the right to append to a file.
8349  *
8350  * The 'ignore' flag is set when an operation modifying the immutability flags
8351  * is being authorized.  We check the system securelevel to determine which
8352  * immutability flags we can ignore.
8353  */
8354 static int
vnode_immutable(struct vnode_attr * vap,int append,int ignore)8355 vnode_immutable(struct vnode_attr *vap, int append, int ignore)
8356 {
8357 	int     mask;
8358 
8359 	/* start with all bits precluding the operation */
8360 	mask = IMMUTABLE | APPEND;
8361 
8362 	/* if appending only, remove the append-only bits */
8363 	if (append) {
8364 		mask &= ~APPEND;
8365 	}
8366 
8367 	/* ignore only set when authorizing flags changes */
8368 	if (ignore) {
8369 		if (securelevel <= 0) {
8370 			/* in insecure state, flags do not inhibit changes */
8371 			mask = 0;
8372 		} else {
8373 			/* in secure state, user flags don't inhibit */
8374 			mask &= ~(UF_IMMUTABLE | UF_APPEND);
8375 		}
8376 	}
8377 	KAUTH_DEBUG("IMMUTABLE - file flags 0x%x mask 0x%x append = %d ignore = %d", vap->va_flags, mask, append, ignore);
8378 	if ((vap->va_flags & mask) != 0) {
8379 		return EPERM;
8380 	}
8381 	return 0;
8382 }
8383 
8384 static int
vauth_node_owner(struct vnode_attr * vap,kauth_cred_t cred)8385 vauth_node_owner(struct vnode_attr *vap, kauth_cred_t cred)
8386 {
8387 	int result;
8388 
8389 	/* default assumption is not-owner */
8390 	result = 0;
8391 
8392 	/*
8393 	 * If the filesystem has given us a UID, we treat this as authoritative.
8394 	 */
8395 	if (vap && VATTR_IS_SUPPORTED(vap, va_uid)) {
8396 		result = (vap->va_uid == kauth_cred_getuid(cred)) ? 1 : 0;
8397 	}
8398 	/* we could test the owner UUID here if we had a policy for it */
8399 
8400 	return result;
8401 }
8402 
8403 /*
8404  * vauth_node_group
8405  *
8406  * Description:	Ask if a cred is a member of the group owning the vnode object
8407  *
8408  * Parameters:		vap		vnode attribute
8409  *				vap->va_gid	group owner of vnode object
8410  *			cred		credential to check
8411  *			ismember	pointer to where to put the answer
8412  *			idontknow	Return this if we can't get an answer
8413  *
8414  * Returns:		0		Success
8415  *			idontknow	Can't get information
8416  *	kauth_cred_ismember_gid:?	Error from kauth subsystem
8417  *	kauth_cred_ismember_gid:?	Error from kauth subsystem
8418  */
8419 static int
vauth_node_group(struct vnode_attr * vap,kauth_cred_t cred,int * ismember,int idontknow)8420 vauth_node_group(struct vnode_attr *vap, kauth_cred_t cred, int *ismember, int idontknow)
8421 {
8422 	int     error;
8423 	int     result;
8424 
8425 	error = 0;
8426 	result = 0;
8427 
8428 	/*
8429 	 * The caller is expected to have asked the filesystem for a group
8430 	 * at some point prior to calling this function.  The answer may
8431 	 * have been that there is no group ownership supported for the
8432 	 * vnode object, in which case we return
8433 	 */
8434 	if (vap && VATTR_IS_SUPPORTED(vap, va_gid)) {
8435 		error = kauth_cred_ismember_gid(cred, vap->va_gid, &result);
8436 		/*
8437 		 * Credentials which are opted into external group membership
8438 		 * resolution which are not known to the external resolver
8439 		 * will result in an ENOENT error.  We translate this into
8440 		 * the appropriate 'idontknow' response for our caller.
8441 		 *
8442 		 * XXX We do not make a distinction here between an ENOENT
8443 		 * XXX arising from a response from the external resolver,
8444 		 * XXX and an ENOENT which is internally generated.  This is
8445 		 * XXX a deficiency of the published kauth_cred_ismember_gid()
8446 		 * XXX KPI which can not be overcome without new KPI.  For
8447 		 * XXX all currently known cases, however, this wil result
8448 		 * XXX in correct behaviour.
8449 		 */
8450 		if (error == ENOENT) {
8451 			error = idontknow;
8452 		}
8453 	}
8454 	/*
8455 	 * XXX We could test the group UUID here if we had a policy for it,
8456 	 * XXX but this is problematic from the perspective of synchronizing
8457 	 * XXX group UUID and POSIX GID ownership of a file and keeping the
8458 	 * XXX values coherent over time.  The problem is that the local
8459 	 * XXX system will vend transient group UUIDs for unknown POSIX GID
8460 	 * XXX values, and these are not persistent, whereas storage of values
8461 	 * XXX is persistent.  One potential solution to this is a local
8462 	 * XXX (persistent) replica of remote directory entries and vended
8463 	 * XXX local ids in a local directory server (think in terms of a
8464 	 * XXX caching DNS server).
8465 	 */
8466 
8467 	if (!error) {
8468 		*ismember = result;
8469 	}
8470 	return error;
8471 }
8472 
8473 static int
vauth_file_owner(vauth_ctx vcp)8474 vauth_file_owner(vauth_ctx vcp)
8475 {
8476 	int result;
8477 
8478 	if (vcp->flags_valid & _VAC_IS_OWNER) {
8479 		result = (vcp->flags & _VAC_IS_OWNER) ? 1 : 0;
8480 	} else {
8481 		result = vauth_node_owner(vcp->vap, vcp->ctx->vc_ucred);
8482 
8483 		/* cache our result */
8484 		vcp->flags_valid |= _VAC_IS_OWNER;
8485 		if (result) {
8486 			vcp->flags |= _VAC_IS_OWNER;
8487 		} else {
8488 			vcp->flags &= ~_VAC_IS_OWNER;
8489 		}
8490 	}
8491 	return result;
8492 }
8493 
8494 
8495 /*
8496  * vauth_file_ingroup
8497  *
8498  * Description:	Ask if a user is a member of the group owning the directory
8499  *
8500  * Parameters:		vcp		The vnode authorization context that
8501  *					contains the user and directory info
8502  *				vcp->flags_valid	Valid flags
8503  *				vcp->flags		Flags values
8504  *				vcp->vap		File vnode attributes
8505  *				vcp->ctx		VFS Context (for user)
8506  *			ismember	pointer to where to put the answer
8507  *			idontknow	Return this if we can't get an answer
8508  *
8509  * Returns:		0		Success
8510  *		vauth_node_group:?	Error from vauth_node_group()
8511  *
8512  * Implicit returns:	*ismember	0	The user is not a group member
8513  *					1	The user is a group member
8514  */
8515 static int
vauth_file_ingroup(vauth_ctx vcp,int * ismember,int idontknow)8516 vauth_file_ingroup(vauth_ctx vcp, int *ismember, int idontknow)
8517 {
8518 	int     error;
8519 
8520 	/* Check for a cached answer first, to avoid the check if possible */
8521 	if (vcp->flags_valid & _VAC_IN_GROUP) {
8522 		*ismember = (vcp->flags & _VAC_IN_GROUP) ? 1 : 0;
8523 		error = 0;
8524 	} else {
8525 		/* Otherwise, go look for it */
8526 		error = vauth_node_group(vcp->vap, vcp->ctx->vc_ucred, ismember, idontknow);
8527 
8528 		if (!error) {
8529 			/* cache our result */
8530 			vcp->flags_valid |= _VAC_IN_GROUP;
8531 			if (*ismember) {
8532 				vcp->flags |= _VAC_IN_GROUP;
8533 			} else {
8534 				vcp->flags &= ~_VAC_IN_GROUP;
8535 			}
8536 		}
8537 	}
8538 	return error;
8539 }
8540 
8541 static int
vauth_dir_owner(vauth_ctx vcp)8542 vauth_dir_owner(vauth_ctx vcp)
8543 {
8544 	int result;
8545 
8546 	if (vcp->flags_valid & _VAC_IS_DIR_OWNER) {
8547 		result = (vcp->flags & _VAC_IS_DIR_OWNER) ? 1 : 0;
8548 	} else {
8549 		result = vauth_node_owner(vcp->dvap, vcp->ctx->vc_ucred);
8550 
8551 		/* cache our result */
8552 		vcp->flags_valid |= _VAC_IS_DIR_OWNER;
8553 		if (result) {
8554 			vcp->flags |= _VAC_IS_DIR_OWNER;
8555 		} else {
8556 			vcp->flags &= ~_VAC_IS_DIR_OWNER;
8557 		}
8558 	}
8559 	return result;
8560 }
8561 
8562 /*
8563  * vauth_dir_ingroup
8564  *
8565  * Description:	Ask if a user is a member of the group owning the directory
8566  *
8567  * Parameters:		vcp		The vnode authorization context that
8568  *					contains the user and directory info
8569  *				vcp->flags_valid	Valid flags
8570  *				vcp->flags		Flags values
8571  *				vcp->dvap		Dir vnode attributes
8572  *				vcp->ctx		VFS Context (for user)
8573  *			ismember	pointer to where to put the answer
8574  *			idontknow	Return this if we can't get an answer
8575  *
8576  * Returns:		0		Success
8577  *		vauth_node_group:?	Error from vauth_node_group()
8578  *
8579  * Implicit returns:	*ismember	0	The user is not a group member
8580  *					1	The user is a group member
8581  */
8582 static int
vauth_dir_ingroup(vauth_ctx vcp,int * ismember,int idontknow)8583 vauth_dir_ingroup(vauth_ctx vcp, int *ismember, int idontknow)
8584 {
8585 	int     error;
8586 
8587 	/* Check for a cached answer first, to avoid the check if possible */
8588 	if (vcp->flags_valid & _VAC_IN_DIR_GROUP) {
8589 		*ismember = (vcp->flags & _VAC_IN_DIR_GROUP) ? 1 : 0;
8590 		error = 0;
8591 	} else {
8592 		/* Otherwise, go look for it */
8593 		error = vauth_node_group(vcp->dvap, vcp->ctx->vc_ucred, ismember, idontknow);
8594 
8595 		if (!error) {
8596 			/* cache our result */
8597 			vcp->flags_valid |= _VAC_IN_DIR_GROUP;
8598 			if (*ismember) {
8599 				vcp->flags |= _VAC_IN_DIR_GROUP;
8600 			} else {
8601 				vcp->flags &= ~_VAC_IN_DIR_GROUP;
8602 			}
8603 		}
8604 	}
8605 	return error;
8606 }
8607 
8608 /*
8609  * Test the posix permissions in (vap) to determine whether (credential)
8610  * may perform (action)
8611  */
8612 static int
vnode_authorize_posix(vauth_ctx vcp,int action,int on_dir)8613 vnode_authorize_posix(vauth_ctx vcp, int action, int on_dir)
8614 {
8615 	struct vnode_attr *vap;
8616 	int needed, error, owner_ok, group_ok, world_ok, ismember;
8617 #ifdef KAUTH_DEBUG_ENABLE
8618 	const char *where = "uninitialized";
8619 # define _SETWHERE(c)   where = c;
8620 #else
8621 # define _SETWHERE(c)
8622 #endif
8623 
8624 	/* checking file or directory? */
8625 	if (on_dir) {
8626 		vap = vcp->dvap;
8627 	} else {
8628 		vap = vcp->vap;
8629 	}
8630 
8631 	error = 0;
8632 
8633 	/*
8634 	 * We want to do as little work here as possible.  So first we check
8635 	 * which sets of permissions grant us the access we need, and avoid checking
8636 	 * whether specific permissions grant access when more generic ones would.
8637 	 */
8638 
8639 	/* owner permissions */
8640 	needed = 0;
8641 	if (action & VREAD) {
8642 		needed |= S_IRUSR;
8643 	}
8644 	if (action & VWRITE) {
8645 		needed |= S_IWUSR;
8646 	}
8647 	if (action & VEXEC) {
8648 		needed |= S_IXUSR;
8649 	}
8650 	owner_ok = (needed & vap->va_mode) == needed;
8651 
8652 	/*
8653 	 * Processes with the appropriate entitlement can marked themselves as
8654 	 * ignoring file/directory permissions if they own it.
8655 	 */
8656 	if (!owner_ok && proc_ignores_node_permissions(vfs_context_proc(vcp->ctx))) {
8657 		owner_ok = 1;
8658 	}
8659 
8660 	/* group permissions */
8661 	needed = 0;
8662 	if (action & VREAD) {
8663 		needed |= S_IRGRP;
8664 	}
8665 	if (action & VWRITE) {
8666 		needed |= S_IWGRP;
8667 	}
8668 	if (action & VEXEC) {
8669 		needed |= S_IXGRP;
8670 	}
8671 	group_ok = (needed & vap->va_mode) == needed;
8672 
8673 	/* world permissions */
8674 	needed = 0;
8675 	if (action & VREAD) {
8676 		needed |= S_IROTH;
8677 	}
8678 	if (action & VWRITE) {
8679 		needed |= S_IWOTH;
8680 	}
8681 	if (action & VEXEC) {
8682 		needed |= S_IXOTH;
8683 	}
8684 	world_ok = (needed & vap->va_mode) == needed;
8685 
8686 	/* If granted/denied by all three, we're done */
8687 	if (owner_ok && group_ok && world_ok) {
8688 		_SETWHERE("all");
8689 		goto out;
8690 	}
8691 
8692 	if (!owner_ok && !group_ok && !world_ok) {
8693 		_SETWHERE("all");
8694 		error = EACCES;
8695 		goto out;
8696 	}
8697 
8698 	/* Check ownership (relatively cheap) */
8699 	if ((on_dir && vauth_dir_owner(vcp)) ||
8700 	    (!on_dir && vauth_file_owner(vcp))) {
8701 		_SETWHERE("user");
8702 		if (!owner_ok) {
8703 			error = EACCES;
8704 		}
8705 		goto out;
8706 	}
8707 
8708 	/* Not owner; if group and world both grant it we're done */
8709 	if (group_ok && world_ok) {
8710 		_SETWHERE("group/world");
8711 		goto out;
8712 	}
8713 	if (!group_ok && !world_ok) {
8714 		_SETWHERE("group/world");
8715 		error = EACCES;
8716 		goto out;
8717 	}
8718 
8719 	/* Check group membership (most expensive) */
8720 	ismember = 0;   /* Default to allow, if the target has no group owner */
8721 
8722 	/*
8723 	 * In the case we can't get an answer about the user from the call to
8724 	 * vauth_dir_ingroup() or vauth_file_ingroup(), we want to fail on
8725 	 * the side of caution, rather than simply granting access, or we will
8726 	 * fail to correctly implement exclusion groups, so we set the third
8727 	 * parameter on the basis of the state of 'group_ok'.
8728 	 */
8729 	if (on_dir) {
8730 		error = vauth_dir_ingroup(vcp, &ismember, (!group_ok ? EACCES : 0));
8731 	} else {
8732 		error = vauth_file_ingroup(vcp, &ismember, (!group_ok ? EACCES : 0));
8733 	}
8734 	if (error) {
8735 		if (!group_ok) {
8736 			ismember = 1;
8737 		}
8738 		error = 0;
8739 	}
8740 	if (ismember) {
8741 		_SETWHERE("group");
8742 		if (!group_ok) {
8743 			error = EACCES;
8744 		}
8745 		goto out;
8746 	}
8747 
8748 	/* Not owner, not in group, use world result */
8749 	_SETWHERE("world");
8750 	if (!world_ok) {
8751 		error = EACCES;
8752 	}
8753 
8754 	/* FALLTHROUGH */
8755 
8756 out:
8757 	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",
8758 	    vcp->vp, (error == 0) ? "ALLOWED" : "DENIED", where,
8759 	    (action & VREAD)  ? "r" : "-",
8760 	    (action & VWRITE) ? "w" : "-",
8761 	    (action & VEXEC)  ? "x" : "-",
8762 	    needed,
8763 	    (vap->va_mode & S_IRUSR) ? "r" : "-",
8764 	    (vap->va_mode & S_IWUSR) ? "w" : "-",
8765 	    (vap->va_mode & S_IXUSR) ? "x" : "-",
8766 	    (vap->va_mode & S_IRGRP) ? "r" : "-",
8767 	    (vap->va_mode & S_IWGRP) ? "w" : "-",
8768 	    (vap->va_mode & S_IXGRP) ? "x" : "-",
8769 	    (vap->va_mode & S_IROTH) ? "r" : "-",
8770 	    (vap->va_mode & S_IWOTH) ? "w" : "-",
8771 	    (vap->va_mode & S_IXOTH) ? "x" : "-",
8772 	    kauth_cred_getuid(vcp->ctx->vc_ucred),
8773 	    on_dir ? vcp->dvap->va_uid : vcp->vap->va_uid,
8774 	    on_dir ? vcp->dvap->va_gid : vcp->vap->va_gid);
8775 	return error;
8776 }
8777 
8778 /*
8779  * Authorize the deletion of the node vp from the directory dvp.
8780  *
8781  * We assume that:
8782  * - Neither the node nor the directory are immutable.
8783  * - The user is not the superuser.
8784  *
8785  * The precedence of factors for authorizing or denying delete for a credential
8786  *
8787  * 1) Explicit ACE on the node. (allow or deny DELETE)
8788  * 2) Explicit ACE on the directory (allow or deny DELETE_CHILD).
8789  *
8790  *    If there are conflicting ACEs on the node and the directory, the node
8791  *    ACE wins.
8792  *
8793  * 3) Sticky bit on the directory.
8794  *    Deletion is not permitted if the directory is sticky and the caller is
8795  *    not owner of the node or directory. The sticky bit rules are like a deny
8796  *    delete ACE except lower in priority than ACL's either allowing or denying
8797  *    delete.
8798  *
8799  * 4) POSIX permisions on the directory.
8800  *
8801  * As an optimization, we cache whether or not delete child is permitted
8802  * on directories. This enables us to skip directory ACL and POSIX checks
8803  * as we already have the result from those checks. However, we always check the
8804  * node ACL and, if the directory has the sticky bit set, we always check its
8805  * ACL (even for a directory with an authorized delete child). Furthermore,
8806  * caching the delete child authorization is independent of the sticky bit
8807  * being set as it is only applicable in determining whether the node can be
8808  * deleted or not.
8809  */
8810 static int
vnode_authorize_delete(vauth_ctx vcp,boolean_t cached_delete_child)8811 vnode_authorize_delete(vauth_ctx vcp, boolean_t cached_delete_child)
8812 {
8813 	struct vnode_attr       *vap = vcp->vap;
8814 	struct vnode_attr       *dvap = vcp->dvap;
8815 	kauth_cred_t            cred = vcp->ctx->vc_ucred;
8816 	struct kauth_acl_eval   eval;
8817 	int                     error, ismember;
8818 
8819 	/* Check the ACL on the node first */
8820 	if (VATTR_IS_NOT(vap, va_acl, NULL)) {
8821 		eval.ae_requested = KAUTH_VNODE_DELETE;
8822 		eval.ae_acl = &vap->va_acl->acl_ace[0];
8823 		eval.ae_count = vap->va_acl->acl_entrycount;
8824 		eval.ae_options = 0;
8825 		if (vauth_file_owner(vcp)) {
8826 			eval.ae_options |= KAUTH_AEVAL_IS_OWNER;
8827 		}
8828 		/*
8829 		 * We use ENOENT as a marker to indicate we could not get
8830 		 * information in order to delay evaluation until after we
8831 		 * have the ACL evaluation answer.  Previously, we would
8832 		 * always deny the operation at this point.
8833 		 */
8834 		if ((error = vauth_file_ingroup(vcp, &ismember, ENOENT)) != 0 && error != ENOENT) {
8835 			return error;
8836 		}
8837 		if (error == ENOENT) {
8838 			eval.ae_options |= KAUTH_AEVAL_IN_GROUP_UNKNOWN;
8839 		} else if (ismember) {
8840 			eval.ae_options |= KAUTH_AEVAL_IN_GROUP;
8841 		}
8842 		eval.ae_exp_gall = KAUTH_VNODE_GENERIC_ALL_BITS;
8843 		eval.ae_exp_gread = KAUTH_VNODE_GENERIC_READ_BITS;
8844 		eval.ae_exp_gwrite = KAUTH_VNODE_GENERIC_WRITE_BITS;
8845 		eval.ae_exp_gexec = KAUTH_VNODE_GENERIC_EXECUTE_BITS;
8846 
8847 		if ((error = kauth_acl_evaluate(cred, &eval)) != 0) {
8848 			KAUTH_DEBUG("%p    ERROR during ACL processing - %d", vcp->vp, error);
8849 			return error;
8850 		}
8851 
8852 		switch (eval.ae_result) {
8853 		case KAUTH_RESULT_DENY:
8854 			if (vauth_file_owner(vcp) && proc_ignores_node_permissions(vfs_context_proc(vcp->ctx))) {
8855 				KAUTH_DEBUG("%p    Override DENY due to entitlement", vcp->vp);
8856 				return 0;
8857 			}
8858 			KAUTH_DEBUG("%p    DENIED - denied by ACL", vcp->vp);
8859 			return EACCES;
8860 		case KAUTH_RESULT_ALLOW:
8861 			KAUTH_DEBUG("%p    ALLOWED - granted by ACL", vcp->vp);
8862 			return 0;
8863 		case KAUTH_RESULT_DEFER:
8864 		default:
8865 			/* Defer to directory */
8866 			KAUTH_DEBUG("%p    DEFERRED - by file ACL", vcp->vp);
8867 			break;
8868 		}
8869 	}
8870 
8871 	/*
8872 	 * Without a sticky bit, a previously authorized delete child is
8873 	 * sufficient to authorize this delete.
8874 	 *
8875 	 * If the sticky bit is set, a directory ACL which allows delete child
8876 	 * overrides a (potential) sticky bit deny. The authorized delete child
8877 	 * cannot tell us if it was authorized because of an explicit delete
8878 	 * child allow ACE or because of POSIX permisions so we have to check
8879 	 * the directory ACL everytime if the directory has a sticky bit.
8880 	 */
8881 	if (!(dvap->va_mode & S_ISTXT) && cached_delete_child) {
8882 		KAUTH_DEBUG("%p    ALLOWED - granted by directory ACL or POSIX permissions and no sticky bit on directory", vcp->vp);
8883 		return 0;
8884 	}
8885 
8886 	/* check the ACL on the directory */
8887 	if (VATTR_IS_NOT(dvap, va_acl, NULL)) {
8888 		eval.ae_requested = KAUTH_VNODE_DELETE_CHILD;
8889 		eval.ae_acl = &dvap->va_acl->acl_ace[0];
8890 		eval.ae_count = dvap->va_acl->acl_entrycount;
8891 		eval.ae_options = 0;
8892 		if (vauth_dir_owner(vcp)) {
8893 			eval.ae_options |= KAUTH_AEVAL_IS_OWNER;
8894 		}
8895 		/*
8896 		 * We use ENOENT as a marker to indicate we could not get
8897 		 * information in order to delay evaluation until after we
8898 		 * have the ACL evaluation answer.  Previously, we would
8899 		 * always deny the operation at this point.
8900 		 */
8901 		if ((error = vauth_dir_ingroup(vcp, &ismember, ENOENT)) != 0 && error != ENOENT) {
8902 			return error;
8903 		}
8904 		if (error == ENOENT) {
8905 			eval.ae_options |= KAUTH_AEVAL_IN_GROUP_UNKNOWN;
8906 		} else if (ismember) {
8907 			eval.ae_options |= KAUTH_AEVAL_IN_GROUP;
8908 		}
8909 		eval.ae_exp_gall = KAUTH_VNODE_GENERIC_ALL_BITS;
8910 		eval.ae_exp_gread = KAUTH_VNODE_GENERIC_READ_BITS;
8911 		eval.ae_exp_gwrite = KAUTH_VNODE_GENERIC_WRITE_BITS;
8912 		eval.ae_exp_gexec = KAUTH_VNODE_GENERIC_EXECUTE_BITS;
8913 
8914 		/*
8915 		 * If there is no entry, we are going to defer to other
8916 		 * authorization mechanisms.
8917 		 */
8918 		error = kauth_acl_evaluate(cred, &eval);
8919 
8920 		if (error != 0) {
8921 			KAUTH_DEBUG("%p    ERROR during ACL processing - %d", vcp->vp, error);
8922 			return error;
8923 		}
8924 		switch (eval.ae_result) {
8925 		case KAUTH_RESULT_DENY:
8926 			if (vauth_dir_owner(vcp) && proc_ignores_node_permissions(vfs_context_proc(vcp->ctx))) {
8927 				KAUTH_DEBUG("%p    Override DENY due to entitlement", vcp->vp);
8928 				return 0;
8929 			}
8930 			KAUTH_DEBUG("%p    DENIED - denied by directory ACL", vcp->vp);
8931 			return EACCES;
8932 		case KAUTH_RESULT_ALLOW:
8933 			KAUTH_DEBUG("%p    ALLOWED - granted by directory ACL", vcp->vp);
8934 			if (!cached_delete_child && vcp->dvp) {
8935 				vnode_cache_authorized_action(vcp->dvp,
8936 				    vcp->ctx, KAUTH_VNODE_DELETE_CHILD);
8937 			}
8938 			return 0;
8939 		case KAUTH_RESULT_DEFER:
8940 		default:
8941 			/* Deferred by directory ACL */
8942 			KAUTH_DEBUG("%p    DEFERRED - directory ACL", vcp->vp);
8943 			break;
8944 		}
8945 	}
8946 
8947 	/*
8948 	 * From this point, we can't explicitly allow and if we reach the end
8949 	 * of the function without a denial, then the delete is authorized.
8950 	 */
8951 	if (!cached_delete_child) {
8952 		if (vnode_authorize_posix(vcp, VWRITE, 1 /* on_dir */) != 0) {
8953 			KAUTH_DEBUG("%p    DENIED - denied by posix permisssions", vcp->vp);
8954 			return EACCES;
8955 		}
8956 		/*
8957 		 * Cache the authorized action on the vnode if allowed by the
8958 		 * directory ACL or POSIX permissions. It is correct to cache
8959 		 * this action even if sticky bit would deny deleting the node.
8960 		 */
8961 		if (vcp->dvp) {
8962 			vnode_cache_authorized_action(vcp->dvp, vcp->ctx,
8963 			    KAUTH_VNODE_DELETE_CHILD);
8964 		}
8965 	}
8966 
8967 	/* enforce sticky bit behaviour */
8968 	if ((dvap->va_mode & S_ISTXT) && !vauth_file_owner(vcp) && !vauth_dir_owner(vcp)) {
8969 		KAUTH_DEBUG("%p    DENIED - sticky bit rules (user %d  file %d  dir %d)",
8970 		    vcp->vp, cred->cr_posix.cr_uid, vap->va_uid, dvap->va_uid);
8971 		return EACCES;
8972 	}
8973 
8974 	/* not denied, must be OK */
8975 	return 0;
8976 }
8977 
8978 
8979 /*
8980  * Authorize an operation based on the node's attributes.
8981  */
8982 static int
vnode_authorize_simple(vauth_ctx vcp,kauth_ace_rights_t acl_rights,kauth_ace_rights_t preauth_rights,boolean_t * found_deny)8983 vnode_authorize_simple(vauth_ctx vcp, kauth_ace_rights_t acl_rights, kauth_ace_rights_t preauth_rights, boolean_t *found_deny)
8984 {
8985 	struct vnode_attr       *vap = vcp->vap;
8986 	kauth_cred_t            cred = vcp->ctx->vc_ucred;
8987 	struct kauth_acl_eval   eval;
8988 	int                     error, ismember;
8989 	mode_t                  posix_action;
8990 
8991 	/*
8992 	 * If we are the file owner, we automatically have some rights.
8993 	 *
8994 	 * Do we need to expand this to support group ownership?
8995 	 */
8996 	if (vauth_file_owner(vcp)) {
8997 		acl_rights &= ~(KAUTH_VNODE_WRITE_SECURITY);
8998 	}
8999 
9000 	/*
9001 	 * If we are checking both TAKE_OWNERSHIP and WRITE_SECURITY, we can
9002 	 * mask the latter.  If TAKE_OWNERSHIP is requested the caller is about to
9003 	 * change ownership to themselves, and WRITE_SECURITY is implicitly
9004 	 * granted to the owner.  We need to do this because at this point
9005 	 * WRITE_SECURITY may not be granted as the caller is not currently
9006 	 * the owner.
9007 	 */
9008 	if ((acl_rights & KAUTH_VNODE_TAKE_OWNERSHIP) &&
9009 	    (acl_rights & KAUTH_VNODE_WRITE_SECURITY)) {
9010 		acl_rights &= ~KAUTH_VNODE_WRITE_SECURITY;
9011 	}
9012 
9013 	if (acl_rights == 0) {
9014 		KAUTH_DEBUG("%p    ALLOWED - implicit or no rights required", vcp->vp);
9015 		return 0;
9016 	}
9017 
9018 	/* if we have an ACL, evaluate it */
9019 	if (VATTR_IS_NOT(vap, va_acl, NULL)) {
9020 		eval.ae_requested = acl_rights;
9021 		eval.ae_acl = &vap->va_acl->acl_ace[0];
9022 		eval.ae_count = vap->va_acl->acl_entrycount;
9023 		eval.ae_options = 0;
9024 		if (vauth_file_owner(vcp)) {
9025 			eval.ae_options |= KAUTH_AEVAL_IS_OWNER;
9026 		}
9027 		/*
9028 		 * We use ENOENT as a marker to indicate we could not get
9029 		 * information in order to delay evaluation until after we
9030 		 * have the ACL evaluation answer.  Previously, we would
9031 		 * always deny the operation at this point.
9032 		 */
9033 		if ((error = vauth_file_ingroup(vcp, &ismember, ENOENT)) != 0 && error != ENOENT) {
9034 			return error;
9035 		}
9036 		if (error == ENOENT) {
9037 			eval.ae_options |= KAUTH_AEVAL_IN_GROUP_UNKNOWN;
9038 		} else if (ismember) {
9039 			eval.ae_options |= KAUTH_AEVAL_IN_GROUP;
9040 		}
9041 		eval.ae_exp_gall = KAUTH_VNODE_GENERIC_ALL_BITS;
9042 		eval.ae_exp_gread = KAUTH_VNODE_GENERIC_READ_BITS;
9043 		eval.ae_exp_gwrite = KAUTH_VNODE_GENERIC_WRITE_BITS;
9044 		eval.ae_exp_gexec = KAUTH_VNODE_GENERIC_EXECUTE_BITS;
9045 
9046 		if ((error = kauth_acl_evaluate(cred, &eval)) != 0) {
9047 			KAUTH_DEBUG("%p    ERROR during ACL processing - %d", vcp->vp, error);
9048 			return error;
9049 		}
9050 
9051 		switch (eval.ae_result) {
9052 		case KAUTH_RESULT_DENY:
9053 			if (vauth_file_owner(vcp) && proc_ignores_node_permissions(vfs_context_proc(vcp->ctx))) {
9054 				KAUTH_DEBUG("%p    Override DENY due to entitlement", vcp->vp);
9055 				return 0;
9056 			}
9057 			KAUTH_DEBUG("%p    DENIED - by ACL", vcp->vp);
9058 			return EACCES;         /* deny, deny, counter-allege */
9059 		case KAUTH_RESULT_ALLOW:
9060 			KAUTH_DEBUG("%p    ALLOWED - all rights granted by ACL", vcp->vp);
9061 			return 0;
9062 		case KAUTH_RESULT_DEFER:
9063 		default:
9064 			/* Effectively the same as !delete_child_denied */
9065 			KAUTH_DEBUG("%p    DEFERRED - directory ACL", vcp->vp);
9066 			break;
9067 		}
9068 
9069 		*found_deny = eval.ae_found_deny;
9070 
9071 		/* fall through and evaluate residual rights */
9072 	} else {
9073 		/* no ACL, everything is residual */
9074 		eval.ae_residual = acl_rights;
9075 	}
9076 
9077 	/*
9078 	 * Grant residual rights that have been pre-authorized.
9079 	 */
9080 	eval.ae_residual &= ~preauth_rights;
9081 
9082 	/*
9083 	 * We grant WRITE_ATTRIBUTES to the owner if it hasn't been denied.
9084 	 */
9085 	if (vauth_file_owner(vcp)) {
9086 		eval.ae_residual &= ~KAUTH_VNODE_WRITE_ATTRIBUTES;
9087 	}
9088 
9089 	if (eval.ae_residual == 0) {
9090 		KAUTH_DEBUG("%p    ALLOWED - rights already authorized", vcp->vp);
9091 		return 0;
9092 	}
9093 
9094 	/*
9095 	 * Bail if we have residual rights that can't be granted by posix permissions,
9096 	 * or aren't presumed granted at this point.
9097 	 *
9098 	 * XXX these can be collapsed for performance
9099 	 */
9100 	if (eval.ae_residual & KAUTH_VNODE_CHANGE_OWNER) {
9101 		KAUTH_DEBUG("%p    DENIED - CHANGE_OWNER not permitted", vcp->vp);
9102 		return EACCES;
9103 	}
9104 	if (eval.ae_residual & KAUTH_VNODE_WRITE_SECURITY) {
9105 		KAUTH_DEBUG("%p    DENIED - WRITE_SECURITY not permitted", vcp->vp);
9106 		return EACCES;
9107 	}
9108 
9109 #if DIAGNOSTIC
9110 	if (eval.ae_residual & KAUTH_VNODE_DELETE) {
9111 		panic("vnode_authorize: can't be checking delete permission here");
9112 	}
9113 #endif
9114 
9115 	/*
9116 	 * Compute the fallback posix permissions that will satisfy the remaining
9117 	 * rights.
9118 	 */
9119 	posix_action = 0;
9120 	if (eval.ae_residual & (KAUTH_VNODE_READ_DATA |
9121 	    KAUTH_VNODE_LIST_DIRECTORY |
9122 	    KAUTH_VNODE_READ_EXTATTRIBUTES)) {
9123 		posix_action |= VREAD;
9124 	}
9125 	if (eval.ae_residual & (KAUTH_VNODE_WRITE_DATA |
9126 	    KAUTH_VNODE_ADD_FILE |
9127 	    KAUTH_VNODE_ADD_SUBDIRECTORY |
9128 	    KAUTH_VNODE_DELETE_CHILD |
9129 	    KAUTH_VNODE_WRITE_ATTRIBUTES |
9130 	    KAUTH_VNODE_WRITE_EXTATTRIBUTES)) {
9131 		posix_action |= VWRITE;
9132 	}
9133 	if (eval.ae_residual & (KAUTH_VNODE_EXECUTE |
9134 	    KAUTH_VNODE_SEARCH)) {
9135 		posix_action |= VEXEC;
9136 	}
9137 
9138 	if (posix_action != 0) {
9139 		return vnode_authorize_posix(vcp, posix_action, 0 /* !on_dir */);
9140 	} else {
9141 		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",
9142 		    vcp->vp,
9143 		    (eval.ae_residual & KAUTH_VNODE_READ_DATA)
9144 		    ? vnode_isdir(vcp->vp) ? " LIST_DIRECTORY" : " READ_DATA" : "",
9145 		    (eval.ae_residual & KAUTH_VNODE_WRITE_DATA)
9146 		    ? vnode_isdir(vcp->vp) ? " ADD_FILE" : " WRITE_DATA" : "",
9147 		    (eval.ae_residual & KAUTH_VNODE_EXECUTE)
9148 		    ? vnode_isdir(vcp->vp) ? " SEARCH" : " EXECUTE" : "",
9149 		    (eval.ae_residual & KAUTH_VNODE_DELETE)
9150 		    ? " DELETE" : "",
9151 		    (eval.ae_residual & KAUTH_VNODE_APPEND_DATA)
9152 		    ? vnode_isdir(vcp->vp) ? " ADD_SUBDIRECTORY" : " APPEND_DATA" : "",
9153 		    (eval.ae_residual & KAUTH_VNODE_DELETE_CHILD)
9154 		    ? " DELETE_CHILD" : "",
9155 		    (eval.ae_residual & KAUTH_VNODE_READ_ATTRIBUTES)
9156 		    ? " READ_ATTRIBUTES" : "",
9157 		    (eval.ae_residual & KAUTH_VNODE_WRITE_ATTRIBUTES)
9158 		    ? " WRITE_ATTRIBUTES" : "",
9159 		    (eval.ae_residual & KAUTH_VNODE_READ_EXTATTRIBUTES)
9160 		    ? " READ_EXTATTRIBUTES" : "",
9161 		    (eval.ae_residual & KAUTH_VNODE_WRITE_EXTATTRIBUTES)
9162 		    ? " WRITE_EXTATTRIBUTES" : "",
9163 		    (eval.ae_residual & KAUTH_VNODE_READ_SECURITY)
9164 		    ? " READ_SECURITY" : "",
9165 		    (eval.ae_residual & KAUTH_VNODE_WRITE_SECURITY)
9166 		    ? " WRITE_SECURITY" : "",
9167 		    (eval.ae_residual & KAUTH_VNODE_CHECKIMMUTABLE)
9168 		    ? " CHECKIMMUTABLE" : "",
9169 		    (eval.ae_residual & KAUTH_VNODE_CHANGE_OWNER)
9170 		    ? " CHANGE_OWNER" : "");
9171 	}
9172 
9173 	/*
9174 	 * Lack of required Posix permissions implies no reason to deny access.
9175 	 */
9176 	return 0;
9177 }
9178 
9179 /*
9180  * Check for file immutability.
9181  */
9182 static int
vnode_authorize_checkimmutable(mount_t mp,vauth_ctx vcp,struct vnode_attr * vap,int rights,int ignore)9183 vnode_authorize_checkimmutable(mount_t mp, vauth_ctx vcp,
9184     struct vnode_attr *vap, int rights, int ignore)
9185 {
9186 	int error;
9187 	int append;
9188 
9189 	/*
9190 	 * Perform immutability checks for operations that change data.
9191 	 *
9192 	 * Sockets, fifos and devices require special handling.
9193 	 */
9194 	switch (vap->va_type) {
9195 	case VSOCK:
9196 	case VFIFO:
9197 	case VBLK:
9198 	case VCHR:
9199 		/*
9200 		 * Writing to these nodes does not change the filesystem data,
9201 		 * so forget that it's being tried.
9202 		 */
9203 		rights &= ~KAUTH_VNODE_WRITE_DATA;
9204 		break;
9205 	default:
9206 		break;
9207 	}
9208 
9209 	error = 0;
9210 	if (rights & KAUTH_VNODE_WRITE_RIGHTS) {
9211 		/* check per-filesystem options if possible */
9212 		if (mp != NULL) {
9213 			/* check for no-EA filesystems */
9214 			if ((rights & KAUTH_VNODE_WRITE_EXTATTRIBUTES) &&
9215 			    (vfs_flags(mp) & MNT_NOUSERXATTR)) {
9216 				KAUTH_DEBUG("%p    DENIED - filesystem disallowed extended attributes", vap);
9217 				error = EACCES;  /* User attributes disabled */
9218 				goto out;
9219 			}
9220 		}
9221 
9222 		/*
9223 		 * check for file immutability. first, check if the requested rights are
9224 		 * allowable for a UF_APPEND file.
9225 		 */
9226 		append = 0;
9227 		if (vap->va_type == VDIR) {
9228 			if ((rights & (KAUTH_VNODE_ADD_FILE | KAUTH_VNODE_ADD_SUBDIRECTORY | KAUTH_VNODE_WRITE_EXTATTRIBUTES | ~KAUTH_VNODE_WRITE_RIGHTS)) == rights) {
9229 				append = 1;
9230 			}
9231 		} else {
9232 			if ((rights & (KAUTH_VNODE_APPEND_DATA | KAUTH_VNODE_WRITE_EXTATTRIBUTES | ~KAUTH_VNODE_WRITE_RIGHTS)) == rights) {
9233 				append = 1;
9234 			}
9235 		}
9236 		if ((error = vnode_immutable(vap, append, ignore)) != 0) {
9237 			if (error && !ignore) {
9238 				/*
9239 				 * In case of a rename, we want to check ownership for dvp as well.
9240 				 */
9241 				int owner = 0;
9242 				if (rights & KAUTH_VNODE_DELETE_CHILD && vcp->dvp != NULL) {
9243 					owner = vauth_file_owner(vcp) && vauth_dir_owner(vcp);
9244 				} else {
9245 					owner = vauth_file_owner(vcp);
9246 				}
9247 				if (owner && proc_ignores_node_permissions(vfs_context_proc(vcp->ctx))) {
9248 					error = vnode_immutable(vap, append, 1);
9249 				}
9250 			}
9251 		}
9252 		if (error) {
9253 			KAUTH_DEBUG("%p    DENIED - file is immutable", vap);
9254 			goto out;
9255 		}
9256 	}
9257 out:
9258 	return error;
9259 }
9260 
9261 /*
9262  * Handle authorization actions for filesystems that advertise that the
9263  * server will be enforcing.
9264  *
9265  * Returns:	0			Authorization should be handled locally
9266  *		1			Authorization was handled by the FS
9267  *
9268  * Note:	Imputed returns will only occur if the authorization request
9269  *		was handled by the FS.
9270  *
9271  * Imputed:	*resultp, modified	Return code from FS when the request is
9272  *					handled by the FS.
9273  *		VNOP_ACCESS:???
9274  *		VNOP_OPEN:???
9275  */
9276 static int
vnode_authorize_opaque(vnode_t vp,int * resultp,kauth_action_t action,vfs_context_t ctx)9277 vnode_authorize_opaque(vnode_t vp, int *resultp, kauth_action_t action, vfs_context_t ctx)
9278 {
9279 	int     error;
9280 
9281 	/*
9282 	 * If the vp is a device node, socket or FIFO it actually represents a local
9283 	 * endpoint, so we need to handle it locally.
9284 	 */
9285 	switch (vp->v_type) {
9286 	case VBLK:
9287 	case VCHR:
9288 	case VSOCK:
9289 	case VFIFO:
9290 		return 0;
9291 	default:
9292 		break;
9293 	}
9294 
9295 	/*
9296 	 * In the advisory request case, if the filesystem doesn't think it's reliable
9297 	 * we will attempt to formulate a result ourselves based on VNOP_GETATTR data.
9298 	 */
9299 	if ((action & KAUTH_VNODE_ACCESS) && !vfs_authopaqueaccess(vp->v_mount)) {
9300 		return 0;
9301 	}
9302 
9303 	/*
9304 	 * Let the filesystem have a say in the matter.  It's OK for it to not implemnent
9305 	 * VNOP_ACCESS, as most will authorise inline with the actual request.
9306 	 */
9307 	if ((error = VNOP_ACCESS(vp, action, ctx)) != ENOTSUP) {
9308 		*resultp = error;
9309 		KAUTH_DEBUG("%p    DENIED - opaque filesystem VNOP_ACCESS denied access", vp);
9310 		return 1;
9311 	}
9312 
9313 	/*
9314 	 * Typically opaque filesystems do authorisation in-line, but exec is a special case.  In
9315 	 * order to be reasonably sure that exec will be permitted, we try a bit harder here.
9316 	 */
9317 	if ((action & KAUTH_VNODE_EXECUTE) && (vp->v_type == VREG)) {
9318 		/* try a VNOP_OPEN for readonly access */
9319 		if ((error = VNOP_OPEN(vp, FREAD, ctx)) != 0) {
9320 			*resultp = error;
9321 			KAUTH_DEBUG("%p    DENIED - EXECUTE denied because file could not be opened readonly", vp);
9322 			return 1;
9323 		}
9324 		VNOP_CLOSE(vp, FREAD, ctx);
9325 	}
9326 
9327 	/*
9328 	 * We don't have any reason to believe that the request has to be denied at this point,
9329 	 * so go ahead and allow it.
9330 	 */
9331 	*resultp = 0;
9332 	KAUTH_DEBUG("%p    ALLOWED - bypassing access check for non-local filesystem", vp);
9333 	return 1;
9334 }
9335 
9336 
9337 
9338 
9339 /*
9340  * Returns:	KAUTH_RESULT_ALLOW
9341  *		KAUTH_RESULT_DENY
9342  *
9343  * Imputed:	*arg3, modified		Error code in the deny case
9344  *		EROFS			Read-only file system
9345  *		EACCES			Permission denied
9346  *		EPERM			Operation not permitted [no execute]
9347  *	vnode_getattr:ENOMEM		Not enough space [only if has filesec]
9348  *	vnode_getattr:???
9349  *	vnode_authorize_opaque:*arg2	???
9350  *	vnode_authorize_checkimmutable:???
9351  *	vnode_authorize_delete:???
9352  *	vnode_authorize_simple:???
9353  */
9354 
9355 
9356 static int
vnode_authorize_callback(__unused kauth_cred_t cred,__unused void * idata,kauth_action_t action,uintptr_t arg0,uintptr_t arg1,uintptr_t arg2,uintptr_t arg3)9357 vnode_authorize_callback(__unused kauth_cred_t cred, __unused void *idata,
9358     kauth_action_t action, uintptr_t arg0, uintptr_t arg1, uintptr_t arg2,
9359     uintptr_t arg3)
9360 {
9361 	vfs_context_t   ctx;
9362 	vnode_t         cvp = NULLVP;
9363 	vnode_t         vp, dvp;
9364 	int             result = KAUTH_RESULT_DENY;
9365 	int             parent_iocount = 0;
9366 	int             parent_action = 0; /* In case we need to use namedstream's data fork for cached rights*/
9367 
9368 	ctx = (vfs_context_t)arg0;
9369 	vp = (vnode_t)arg1;
9370 	dvp = (vnode_t)arg2;
9371 
9372 	/*
9373 	 * if there are 2 vnodes passed in, we don't know at
9374 	 * this point which rights to look at based on the
9375 	 * combined action being passed in... defer until later...
9376 	 * otherwise check the kauth 'rights' cache hung
9377 	 * off of the vnode we're interested in... if we've already
9378 	 * been granted the right we're currently interested in,
9379 	 * we can just return success... otherwise we'll go through
9380 	 * the process of authorizing the requested right(s)... if that
9381 	 * succeeds, we'll add the right(s) to the cache.
9382 	 * VNOP_SETATTR and VNOP_SETXATTR will invalidate this cache
9383 	 */
9384 	if (dvp && vp) {
9385 		goto defer;
9386 	}
9387 	if (dvp) {
9388 		cvp = dvp;
9389 	} else {
9390 		/*
9391 		 * For named streams on local-authorization volumes, rights are cached on the parent;
9392 		 * authorization is determined by looking at the parent's properties anyway, so storing
9393 		 * on the parent means that we don't recompute for the named stream and that if
9394 		 * we need to flush rights (e.g. on VNOP_SETATTR()) we don't need to track down the
9395 		 * stream to flush its cache separately.  If we miss in the cache, then we authorize
9396 		 * as if there were no cached rights (passing the named stream vnode and desired rights to
9397 		 * vnode_authorize_callback_int()).
9398 		 *
9399 		 * On an opaquely authorized volume, we don't know the relationship between the
9400 		 * data fork's properties and the rights granted on a stream.  Thus, named stream vnodes
9401 		 * on such a volume are authorized directly (rather than using the parent) and have their
9402 		 * own caches.  When a named stream vnode is created, we mark the parent as having a named
9403 		 * stream. On a VNOP_SETATTR() for the parent that may invalidate cached authorization, we
9404 		 * find the stream and flush its cache.
9405 		 */
9406 		if (vnode_isnamedstream(vp) && (!vfs_authopaque(vp->v_mount))) {
9407 			cvp = vnode_getparent(vp);
9408 			if (cvp != NULLVP) {
9409 				parent_iocount = 1;
9410 			} else {
9411 				cvp = NULL;
9412 				goto defer; /* If we can't use the parent, take the slow path */
9413 			}
9414 
9415 			/* Have to translate some actions */
9416 			parent_action = action;
9417 			if (parent_action & KAUTH_VNODE_READ_DATA) {
9418 				parent_action &= ~KAUTH_VNODE_READ_DATA;
9419 				parent_action |= KAUTH_VNODE_READ_EXTATTRIBUTES;
9420 			}
9421 			if (parent_action & KAUTH_VNODE_WRITE_DATA) {
9422 				parent_action &= ~KAUTH_VNODE_WRITE_DATA;
9423 				parent_action |= KAUTH_VNODE_WRITE_EXTATTRIBUTES;
9424 			}
9425 		} else {
9426 			cvp = vp;
9427 		}
9428 	}
9429 
9430 	if (vnode_cache_is_authorized(cvp, ctx, parent_iocount ? parent_action : action) == TRUE) {
9431 		result = KAUTH_RESULT_ALLOW;
9432 		goto out;
9433 	}
9434 defer:
9435 	result = vnode_authorize_callback_int(action, ctx, vp, dvp, (int *)arg3);
9436 
9437 	if (result == KAUTH_RESULT_ALLOW && cvp != NULLVP) {
9438 		KAUTH_DEBUG("%p - caching action = %x", cvp, action);
9439 		vnode_cache_authorized_action(cvp, ctx, action);
9440 	}
9441 
9442 out:
9443 	if (parent_iocount) {
9444 		vnode_put(cvp);
9445 	}
9446 
9447 	return result;
9448 }
9449 
9450 static int
vnode_attr_authorize_internal(vauth_ctx vcp,mount_t mp,kauth_ace_rights_t rights,int is_suser,boolean_t * found_deny,int noimmutable,int parent_authorized_for_delete_child)9451 vnode_attr_authorize_internal(vauth_ctx vcp, mount_t mp,
9452     kauth_ace_rights_t rights, int is_suser, boolean_t *found_deny,
9453     int noimmutable, int parent_authorized_for_delete_child)
9454 {
9455 	int result;
9456 
9457 	/*
9458 	 * Check for immutability.
9459 	 *
9460 	 * In the deletion case, parent directory immutability vetoes specific
9461 	 * file rights.
9462 	 */
9463 	if ((result = vnode_authorize_checkimmutable(mp, vcp, vcp->vap, rights,
9464 	    noimmutable)) != 0) {
9465 		goto out;
9466 	}
9467 
9468 	if ((rights & KAUTH_VNODE_DELETE) &&
9469 	    !parent_authorized_for_delete_child) {
9470 		result = vnode_authorize_checkimmutable(mp, vcp, vcp->dvap,
9471 		    KAUTH_VNODE_DELETE_CHILD, 0);
9472 		if (result) {
9473 			goto out;
9474 		}
9475 	}
9476 
9477 	/*
9478 	 * Clear rights that have been authorized by reaching this point, bail if nothing left to
9479 	 * check.
9480 	 */
9481 	rights &= ~(KAUTH_VNODE_LINKTARGET | KAUTH_VNODE_CHECKIMMUTABLE);
9482 	if (rights == 0) {
9483 		goto out;
9484 	}
9485 
9486 	/*
9487 	 * If we're not the superuser, authorize based on file properties;
9488 	 * note that even if parent_authorized_for_delete_child is TRUE, we
9489 	 * need to check on the node itself.
9490 	 */
9491 	if (!is_suser) {
9492 		/* process delete rights */
9493 		if ((rights & KAUTH_VNODE_DELETE) &&
9494 		    ((result = vnode_authorize_delete(vcp, parent_authorized_for_delete_child)) != 0)) {
9495 			goto out;
9496 		}
9497 
9498 		/* process remaining rights */
9499 		if ((rights & ~KAUTH_VNODE_DELETE) &&
9500 		    (result = vnode_authorize_simple(vcp, rights, rights & KAUTH_VNODE_DELETE, found_deny)) != 0) {
9501 			goto out;
9502 		}
9503 	} else {
9504 		/*
9505 		 * Execute is only granted to root if one of the x bits is set.  This check only
9506 		 * makes sense if the posix mode bits are actually supported.
9507 		 */
9508 		if ((rights & KAUTH_VNODE_EXECUTE) &&
9509 		    (vcp->vap->va_type == VREG) &&
9510 		    VATTR_IS_SUPPORTED(vcp->vap, va_mode) &&
9511 		    !(vcp->vap->va_mode & (S_IXUSR | S_IXGRP | S_IXOTH))) {
9512 			result = EPERM;
9513 			KAUTH_DEBUG("%p    DENIED - root execute requires at least one x bit in 0x%x", vcp, vcp->vap->va_mode);
9514 			goto out;
9515 		}
9516 
9517 		/* Assume that there were DENYs so we don't wrongly cache KAUTH_VNODE_SEARCHBYANYONE */
9518 		*found_deny = TRUE;
9519 
9520 		KAUTH_DEBUG("%p    ALLOWED - caller is superuser", vcp);
9521 	}
9522 out:
9523 	return result;
9524 }
9525 
9526 static int
vnode_authorize_callback_int(kauth_action_t action,vfs_context_t ctx,vnode_t vp,vnode_t dvp,int * errorp)9527 vnode_authorize_callback_int(kauth_action_t action, vfs_context_t ctx,
9528     vnode_t vp, vnode_t dvp, int *errorp)
9529 {
9530 	struct _vnode_authorize_context auth_context;
9531 	vauth_ctx               vcp;
9532 	kauth_cred_t            cred;
9533 	kauth_ace_rights_t      rights;
9534 	struct vnode_attr       va, dva;
9535 	int                     result;
9536 	int                     noimmutable;
9537 	boolean_t               parent_authorized_for_delete_child = FALSE;
9538 	boolean_t               found_deny = FALSE;
9539 	boolean_t               parent_ref = FALSE;
9540 	boolean_t               is_suser = FALSE;
9541 
9542 	vcp = &auth_context;
9543 	vcp->ctx = ctx;
9544 	vcp->vp = vp;
9545 	vcp->dvp = dvp;
9546 	/*
9547 	 * Note that we authorize against the context, not the passed cred
9548 	 * (the same thing anyway)
9549 	 */
9550 	cred = ctx->vc_ucred;
9551 
9552 	VATTR_INIT(&va);
9553 	vcp->vap = &va;
9554 	VATTR_INIT(&dva);
9555 	vcp->dvap = &dva;
9556 
9557 	vcp->flags = vcp->flags_valid = 0;
9558 
9559 #if DIAGNOSTIC
9560 	if ((ctx == NULL) || (vp == NULL) || (cred == NULL)) {
9561 		panic("vnode_authorize: bad arguments (context %p  vp %p  cred %p)", ctx, vp, cred);
9562 	}
9563 #endif
9564 
9565 	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)",
9566 	    vp, vfs_context_proc(ctx)->p_comm,
9567 	    (action & KAUTH_VNODE_ACCESS)               ? "access" : "auth",
9568 	    (action & KAUTH_VNODE_READ_DATA)            ? vnode_isdir(vp) ? " LIST_DIRECTORY" : " READ_DATA" : "",
9569 	    (action & KAUTH_VNODE_WRITE_DATA)           ? vnode_isdir(vp) ? " ADD_FILE" : " WRITE_DATA" : "",
9570 	    (action & KAUTH_VNODE_EXECUTE)              ? vnode_isdir(vp) ? " SEARCH" : " EXECUTE" : "",
9571 	    (action & KAUTH_VNODE_DELETE)               ? " DELETE" : "",
9572 	    (action & KAUTH_VNODE_APPEND_DATA)          ? vnode_isdir(vp) ? " ADD_SUBDIRECTORY" : " APPEND_DATA" : "",
9573 	    (action & KAUTH_VNODE_DELETE_CHILD)         ? " DELETE_CHILD" : "",
9574 	    (action & KAUTH_VNODE_READ_ATTRIBUTES)      ? " READ_ATTRIBUTES" : "",
9575 	    (action & KAUTH_VNODE_WRITE_ATTRIBUTES)     ? " WRITE_ATTRIBUTES" : "",
9576 	    (action & KAUTH_VNODE_READ_EXTATTRIBUTES)   ? " READ_EXTATTRIBUTES" : "",
9577 	    (action & KAUTH_VNODE_WRITE_EXTATTRIBUTES)  ? " WRITE_EXTATTRIBUTES" : "",
9578 	    (action & KAUTH_VNODE_READ_SECURITY)        ? " READ_SECURITY" : "",
9579 	    (action & KAUTH_VNODE_WRITE_SECURITY)       ? " WRITE_SECURITY" : "",
9580 	    (action & KAUTH_VNODE_CHANGE_OWNER)         ? " CHANGE_OWNER" : "",
9581 	    (action & KAUTH_VNODE_NOIMMUTABLE)          ? " (noimmutable)" : "",
9582 	    vnode_isdir(vp) ? "directory" : "file",
9583 	    vp->v_name ? vp->v_name : "<NULL>", action, vp, dvp);
9584 
9585 	/*
9586 	 * Extract the control bits from the action, everything else is
9587 	 * requested rights.
9588 	 */
9589 	noimmutable = (action & KAUTH_VNODE_NOIMMUTABLE) ? 1 : 0;
9590 	rights = action & ~(KAUTH_VNODE_ACCESS | KAUTH_VNODE_NOIMMUTABLE);
9591 
9592 	if (rights & KAUTH_VNODE_DELETE) {
9593 #if DIAGNOSTIC
9594 		if (dvp == NULL) {
9595 			panic("vnode_authorize: KAUTH_VNODE_DELETE test requires a directory");
9596 		}
9597 #endif
9598 		/*
9599 		 * check to see if we've already authorized the parent
9600 		 * directory for deletion of its children... if so, we
9601 		 * can skip a whole bunch of work... we will still have to
9602 		 * authorize that this specific child can be removed
9603 		 */
9604 		if (vnode_cache_is_authorized(dvp, ctx, KAUTH_VNODE_DELETE_CHILD) == TRUE) {
9605 			parent_authorized_for_delete_child = TRUE;
9606 		}
9607 	} else {
9608 		vcp->dvp = NULLVP;
9609 		vcp->dvap = NULL;
9610 	}
9611 
9612 	/*
9613 	 * Check for read-only filesystems.
9614 	 */
9615 	if ((rights & KAUTH_VNODE_WRITE_RIGHTS) &&
9616 	    (vp->v_mount->mnt_flag & MNT_RDONLY) &&
9617 	    ((vp->v_type == VREG) || (vp->v_type == VDIR) ||
9618 	    (vp->v_type == VLNK) || (vp->v_type == VCPLX) ||
9619 	    (rights & KAUTH_VNODE_DELETE) || (rights & KAUTH_VNODE_DELETE_CHILD))) {
9620 		result = EROFS;
9621 		goto out;
9622 	}
9623 
9624 	/*
9625 	 * Check for noexec filesystems.
9626 	 */
9627 	if ((rights & KAUTH_VNODE_EXECUTE) && (vp->v_type == VREG) && (vp->v_mount->mnt_flag & MNT_NOEXEC)) {
9628 		result = EACCES;
9629 		goto out;
9630 	}
9631 
9632 	/*
9633 	 * Handle cases related to filesystems with non-local enforcement.
9634 	 * This call can return 0, in which case we will fall through to perform a
9635 	 * check based on VNOP_GETATTR data.  Otherwise it returns 1 and sets
9636 	 * an appropriate result, at which point we can return immediately.
9637 	 */
9638 	if ((vp->v_mount->mnt_kern_flag & MNTK_AUTH_OPAQUE) && vnode_authorize_opaque(vp, &result, action, ctx)) {
9639 		goto out;
9640 	}
9641 
9642 	/*
9643 	 * If the vnode is a namedstream (extended attribute) data vnode (eg.
9644 	 * a resource fork), *_DATA becomes *_EXTATTRIBUTES.
9645 	 */
9646 	if (vnode_isnamedstream(vp)) {
9647 		if (rights & KAUTH_VNODE_READ_DATA) {
9648 			rights &= ~KAUTH_VNODE_READ_DATA;
9649 			rights |= KAUTH_VNODE_READ_EXTATTRIBUTES;
9650 		}
9651 		if (rights & KAUTH_VNODE_WRITE_DATA) {
9652 			rights &= ~KAUTH_VNODE_WRITE_DATA;
9653 			rights |= KAUTH_VNODE_WRITE_EXTATTRIBUTES;
9654 		}
9655 
9656 		/*
9657 		 * Point 'vp' to the namedstream's parent for ACL checking
9658 		 */
9659 		if ((vp->v_parent != NULL) &&
9660 		    (vget_internal(vp->v_parent, 0, VNODE_NODEAD | VNODE_DRAINO) == 0)) {
9661 			parent_ref = TRUE;
9662 			vcp->vp = vp = vp->v_parent;
9663 		}
9664 	}
9665 
9666 	if (vfs_context_issuser(ctx)) {
9667 		/*
9668 		 * if we're not asking for execute permissions or modifications,
9669 		 * then we're done, this action is authorized.
9670 		 */
9671 		if (!(rights & (KAUTH_VNODE_EXECUTE | KAUTH_VNODE_WRITE_RIGHTS))) {
9672 			goto success;
9673 		}
9674 
9675 		is_suser = TRUE;
9676 	}
9677 
9678 	/*
9679 	 * Get vnode attributes and extended security information for the vnode
9680 	 * and directory if required.
9681 	 *
9682 	 * If we're root we only want mode bits and flags for checking
9683 	 * execute and immutability.
9684 	 */
9685 	VATTR_WANTED(&va, va_mode);
9686 	VATTR_WANTED(&va, va_flags);
9687 	if (!is_suser) {
9688 		VATTR_WANTED(&va, va_uid);
9689 		VATTR_WANTED(&va, va_gid);
9690 		VATTR_WANTED(&va, va_acl);
9691 	}
9692 	if ((result = vnode_getattr(vp, &va, ctx)) != 0) {
9693 		KAUTH_DEBUG("%p    ERROR - failed to get vnode attributes - %d", vp, result);
9694 		goto out;
9695 	}
9696 	VATTR_WANTED(&va, va_type);
9697 	VATTR_RETURN(&va, va_type, vnode_vtype(vp));
9698 
9699 	if (vcp->dvp) {
9700 		VATTR_WANTED(&dva, va_mode);
9701 		VATTR_WANTED(&dva, va_flags);
9702 		if (!is_suser) {
9703 			VATTR_WANTED(&dva, va_uid);
9704 			VATTR_WANTED(&dva, va_gid);
9705 			VATTR_WANTED(&dva, va_acl);
9706 		}
9707 		if ((result = vnode_getattr(vcp->dvp, &dva, ctx)) != 0) {
9708 			KAUTH_DEBUG("%p    ERROR - failed to get directory vnode attributes - %d", vp, result);
9709 			goto out;
9710 		}
9711 		VATTR_WANTED(&dva, va_type);
9712 		VATTR_RETURN(&dva, va_type, vnode_vtype(vcp->dvp));
9713 	}
9714 
9715 	result = vnode_attr_authorize_internal(vcp, vp->v_mount, rights, is_suser,
9716 	    &found_deny, noimmutable, parent_authorized_for_delete_child);
9717 out:
9718 	if (VATTR_IS_SUPPORTED(&va, va_acl) && (va.va_acl != NULL)) {
9719 		kauth_acl_free(va.va_acl);
9720 	}
9721 	if (VATTR_IS_SUPPORTED(&dva, va_acl) && (dva.va_acl != NULL)) {
9722 		kauth_acl_free(dva.va_acl);
9723 	}
9724 
9725 	if (result) {
9726 		if (parent_ref) {
9727 			vnode_put(vp);
9728 		}
9729 		*errorp = result;
9730 		KAUTH_DEBUG("%p    DENIED - auth denied", vp);
9731 		return KAUTH_RESULT_DENY;
9732 	}
9733 	if ((rights & KAUTH_VNODE_SEARCH) && found_deny == FALSE && vp->v_type == VDIR) {
9734 		/*
9735 		 * if we were successfully granted the right to search this directory
9736 		 * and there were NO ACL DENYs for search and the posix permissions also don't
9737 		 * deny execute, we can synthesize a global right that allows anyone to
9738 		 * traverse this directory during a pathname lookup without having to
9739 		 * match the credential associated with this cache of rights.
9740 		 *
9741 		 * Note that we can correctly cache KAUTH_VNODE_SEARCHBYANYONE
9742 		 * only if we actually check ACLs which we don't for root. As
9743 		 * a workaround, the lookup fast path checks for root.
9744 		 */
9745 		if (!VATTR_IS_SUPPORTED(&va, va_mode) ||
9746 		    ((va.va_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) ==
9747 		    (S_IXUSR | S_IXGRP | S_IXOTH))) {
9748 			vnode_cache_authorized_action(vp, ctx, KAUTH_VNODE_SEARCHBYANYONE);
9749 		}
9750 	}
9751 success:
9752 	if (parent_ref) {
9753 		vnode_put(vp);
9754 	}
9755 
9756 	/*
9757 	 * Note that this implies that we will allow requests for no rights, as well as
9758 	 * for rights that we do not recognise.  There should be none of these.
9759 	 */
9760 	KAUTH_DEBUG("%p    ALLOWED - auth granted", vp);
9761 	return KAUTH_RESULT_ALLOW;
9762 }
9763 
9764 int
vnode_attr_authorize_init(struct vnode_attr * vap,struct vnode_attr * dvap,kauth_action_t action,vfs_context_t ctx)9765 vnode_attr_authorize_init(struct vnode_attr *vap, struct vnode_attr *dvap,
9766     kauth_action_t action, vfs_context_t ctx)
9767 {
9768 	VATTR_INIT(vap);
9769 	VATTR_WANTED(vap, va_type);
9770 	VATTR_WANTED(vap, va_mode);
9771 	VATTR_WANTED(vap, va_flags);
9772 	if (dvap) {
9773 		VATTR_INIT(dvap);
9774 		if (action & KAUTH_VNODE_DELETE) {
9775 			VATTR_WANTED(dvap, va_type);
9776 			VATTR_WANTED(dvap, va_mode);
9777 			VATTR_WANTED(dvap, va_flags);
9778 		}
9779 	} else if (action & KAUTH_VNODE_DELETE) {
9780 		return EINVAL;
9781 	}
9782 
9783 	if (!vfs_context_issuser(ctx)) {
9784 		VATTR_WANTED(vap, va_uid);
9785 		VATTR_WANTED(vap, va_gid);
9786 		VATTR_WANTED(vap, va_acl);
9787 		if (dvap && (action & KAUTH_VNODE_DELETE)) {
9788 			VATTR_WANTED(dvap, va_uid);
9789 			VATTR_WANTED(dvap, va_gid);
9790 			VATTR_WANTED(dvap, va_acl);
9791 		}
9792 	}
9793 
9794 	return 0;
9795 }
9796 
9797 #define VNODE_SEC_ATTRS_NO_ACL (VNODE_ATTR_va_uid | VNODE_ATTR_va_gid | VNODE_ATTR_va_mode | VNODE_ATTR_va_flags | VNODE_ATTR_va_type)
9798 
9799 int
vnode_attr_authorize(struct vnode_attr * vap,struct vnode_attr * dvap,mount_t mp,kauth_action_t action,vfs_context_t ctx)9800 vnode_attr_authorize(struct vnode_attr *vap, struct vnode_attr *dvap, mount_t mp,
9801     kauth_action_t action, vfs_context_t ctx)
9802 {
9803 	struct _vnode_authorize_context auth_context;
9804 	vauth_ctx vcp;
9805 	kauth_ace_rights_t rights;
9806 	int noimmutable;
9807 	boolean_t found_deny;
9808 	boolean_t is_suser = FALSE;
9809 	int result = 0;
9810 	uid_t ouid = vap->va_uid;
9811 	gid_t ogid = vap->va_gid;
9812 
9813 	vcp = &auth_context;
9814 	vcp->ctx = ctx;
9815 	vcp->vp = NULLVP;
9816 	vcp->vap = vap;
9817 	vcp->dvp = NULLVP;
9818 	vcp->dvap = dvap;
9819 	vcp->flags = vcp->flags_valid = 0;
9820 
9821 	noimmutable = (action & KAUTH_VNODE_NOIMMUTABLE) ? 1 : 0;
9822 	rights = action & ~(KAUTH_VNODE_ACCESS | KAUTH_VNODE_NOIMMUTABLE);
9823 
9824 	/*
9825 	 * Check for read-only filesystems.
9826 	 */
9827 	if ((rights & KAUTH_VNODE_WRITE_RIGHTS) &&
9828 	    mp && (mp->mnt_flag & MNT_RDONLY) &&
9829 	    ((vap->va_type == VREG) || (vap->va_type == VDIR) ||
9830 	    (vap->va_type == VLNK) || (rights & KAUTH_VNODE_DELETE) ||
9831 	    (rights & KAUTH_VNODE_DELETE_CHILD))) {
9832 		result = EROFS;
9833 		goto out;
9834 	}
9835 
9836 	/*
9837 	 * Check for noexec filesystems.
9838 	 */
9839 	if ((rights & KAUTH_VNODE_EXECUTE) &&
9840 	    (vap->va_type == VREG) && mp && (mp->mnt_flag & MNT_NOEXEC)) {
9841 		result = EACCES;
9842 		goto out;
9843 	}
9844 
9845 	if (vfs_context_issuser(ctx)) {
9846 		/*
9847 		 * if we're not asking for execute permissions or modifications,
9848 		 * then we're done, this action is authorized.
9849 		 */
9850 		if (!(rights & (KAUTH_VNODE_EXECUTE | KAUTH_VNODE_WRITE_RIGHTS))) {
9851 			goto out;
9852 		}
9853 		is_suser = TRUE;
9854 	}
9855 
9856 	if (mp) {
9857 		if (vfs_extendedsecurity(mp) && VATTR_IS_ACTIVE(vap, va_acl) && !VATTR_IS_SUPPORTED(vap, va_acl)) {
9858 			panic("(1) vnode attrs not complete for vnode_attr_authorize");
9859 		}
9860 		vnode_attr_handle_uid_and_gid(vap, mp, ctx);
9861 	}
9862 
9863 	if ((vap->va_active & VNODE_SEC_ATTRS_NO_ACL) != (vap->va_supported & VNODE_SEC_ATTRS_NO_ACL)) {
9864 		panic("(2) vnode attrs not complete for vnode_attr_authorize (2) vap->va_active = 0x%llx , vap->va_supported = 0x%llx",
9865 		    vap->va_active, vap->va_supported);
9866 	}
9867 
9868 	result = vnode_attr_authorize_internal(vcp, mp, rights, is_suser,
9869 	    &found_deny, noimmutable, FALSE);
9870 
9871 	if (mp) {
9872 		vap->va_uid = ouid;
9873 		vap->va_gid = ogid;
9874 	}
9875 
9876 	if (result == EPERM) {
9877 		result = EACCES;
9878 	}
9879 out:
9880 	return result;
9881 }
9882 
9883 
9884 int
vnode_authattr_new(vnode_t dvp,struct vnode_attr * vap,int noauth,vfs_context_t ctx)9885 vnode_authattr_new(vnode_t dvp, struct vnode_attr *vap, int noauth, vfs_context_t ctx)
9886 {
9887 	return vnode_authattr_new_internal(dvp, vap, noauth, NULL, ctx);
9888 }
9889 
9890 /*
9891  * Check that the attribute information in vattr can be legally applied to
9892  * a new file by the context.
9893  */
9894 static int
vnode_authattr_new_internal(vnode_t dvp,struct vnode_attr * vap,int noauth,uint32_t * defaulted_fieldsp,vfs_context_t ctx)9895 vnode_authattr_new_internal(vnode_t dvp, struct vnode_attr *vap, int noauth, uint32_t *defaulted_fieldsp, vfs_context_t ctx)
9896 {
9897 	int             error;
9898 	int             has_priv_suser, ismember, defaulted_owner, defaulted_group, defaulted_mode;
9899 	uint32_t        inherit_flags;
9900 	kauth_cred_t    cred;
9901 	guid_t          changer;
9902 	mount_t         dmp;
9903 	struct vnode_attr dva;
9904 
9905 	error = 0;
9906 
9907 	if (defaulted_fieldsp) {
9908 		*defaulted_fieldsp = 0;
9909 	}
9910 
9911 	defaulted_owner = defaulted_group = defaulted_mode = 0;
9912 
9913 	inherit_flags = 0;
9914 
9915 	/*
9916 	 * Require that the filesystem support extended security to apply any.
9917 	 */
9918 	if (!vfs_extendedsecurity(dvp->v_mount) &&
9919 	    (VATTR_IS_ACTIVE(vap, va_acl) || VATTR_IS_ACTIVE(vap, va_uuuid) || VATTR_IS_ACTIVE(vap, va_guuid))) {
9920 		error = EINVAL;
9921 		goto out;
9922 	}
9923 
9924 	/*
9925 	 * Default some fields.
9926 	 */
9927 	dmp = dvp->v_mount;
9928 
9929 	/*
9930 	 * If the filesystem is mounted IGNORE_OWNERSHIP and an explicit owner is set, that
9931 	 * owner takes ownership of all new files.
9932 	 */
9933 	if ((dmp->mnt_flag & MNT_IGNORE_OWNERSHIP) && (dmp->mnt_fsowner != KAUTH_UID_NONE)) {
9934 		VATTR_SET(vap, va_uid, dmp->mnt_fsowner);
9935 		defaulted_owner = 1;
9936 	} else {
9937 		if (!VATTR_IS_ACTIVE(vap, va_uid)) {
9938 			/* default owner is current user */
9939 			VATTR_SET(vap, va_uid, kauth_cred_getuid(vfs_context_ucred(ctx)));
9940 			defaulted_owner = 1;
9941 		}
9942 	}
9943 
9944 	/*
9945 	 * We need the dvp's va_flags and *may* need the gid of the directory,
9946 	 * we ask for both here.
9947 	 */
9948 	VATTR_INIT(&dva);
9949 	VATTR_WANTED(&dva, va_gid);
9950 	VATTR_WANTED(&dva, va_flags);
9951 	if ((error = vnode_getattr(dvp, &dva, ctx)) != 0) {
9952 		goto out;
9953 	}
9954 
9955 	/*
9956 	 * If the filesystem is mounted IGNORE_OWNERSHIP and an explicit grouo is set, that
9957 	 * group takes ownership of all new files.
9958 	 */
9959 	if ((dmp->mnt_flag & MNT_IGNORE_OWNERSHIP) && (dmp->mnt_fsgroup != KAUTH_GID_NONE)) {
9960 		VATTR_SET(vap, va_gid, dmp->mnt_fsgroup);
9961 		defaulted_group = 1;
9962 	} else {
9963 		if (!VATTR_IS_ACTIVE(vap, va_gid)) {
9964 			/* default group comes from parent object, fallback to current user */
9965 			if (VATTR_IS_SUPPORTED(&dva, va_gid)) {
9966 				VATTR_SET(vap, va_gid, dva.va_gid);
9967 			} else {
9968 				VATTR_SET(vap, va_gid, kauth_cred_getgid(vfs_context_ucred(ctx)));
9969 			}
9970 			defaulted_group = 1;
9971 		}
9972 	}
9973 
9974 	if (!VATTR_IS_ACTIVE(vap, va_flags)) {
9975 		VATTR_SET(vap, va_flags, 0);
9976 	}
9977 
9978 	/* Determine if SF_RESTRICTED should be inherited from the parent
9979 	 * directory. */
9980 	if (VATTR_IS_SUPPORTED(&dva, va_flags)) {
9981 		inherit_flags = dva.va_flags & (UF_DATAVAULT | SF_RESTRICTED);
9982 	}
9983 
9984 	/* default mode is everything, masked with current umask */
9985 	if (!VATTR_IS_ACTIVE(vap, va_mode)) {
9986 		VATTR_SET(vap, va_mode, ACCESSPERMS & ~vfs_context_proc(ctx)->p_fd.fd_cmask);
9987 		KAUTH_DEBUG("ATTR - defaulting new file mode to %o from umask %o",
9988 		    vap->va_mode, vfs_context_proc(ctx)->p_fd.fd_cmask);
9989 		defaulted_mode = 1;
9990 	}
9991 	/* set timestamps to now */
9992 	if (!VATTR_IS_ACTIVE(vap, va_create_time)) {
9993 		nanotime(&vap->va_create_time);
9994 		VATTR_SET_ACTIVE(vap, va_create_time);
9995 	}
9996 
9997 	/*
9998 	 * Check for attempts to set nonsensical fields.
9999 	 */
10000 	if (vap->va_active & ~VNODE_ATTR_NEWOBJ) {
10001 		error = EINVAL;
10002 		KAUTH_DEBUG("ATTR - ERROR - attempt to set unsupported new-file attributes %llx",
10003 		    vap->va_active & ~VNODE_ATTR_NEWOBJ);
10004 		goto out;
10005 	}
10006 
10007 	/*
10008 	 * Quickly check for the applicability of any enforcement here.
10009 	 * Tests below maintain the integrity of the local security model.
10010 	 */
10011 	if (vfs_authopaque(dvp->v_mount)) {
10012 		goto out;
10013 	}
10014 
10015 	/*
10016 	 * We need to know if the caller is the superuser, or if the work is
10017 	 * otherwise already authorised.
10018 	 */
10019 	cred = vfs_context_ucred(ctx);
10020 	if (noauth) {
10021 		/* doing work for the kernel */
10022 		has_priv_suser = 1;
10023 	} else {
10024 		has_priv_suser = vfs_context_issuser(ctx);
10025 	}
10026 
10027 
10028 	if (VATTR_IS_ACTIVE(vap, va_flags)) {
10029 		vap->va_flags &= ~SF_SYNTHETIC;
10030 		if (has_priv_suser) {
10031 			if ((vap->va_flags & (UF_SETTABLE | SF_SETTABLE)) != vap->va_flags) {
10032 				error = EPERM;
10033 				KAUTH_DEBUG("  DENIED - superuser attempt to set illegal flag(s)");
10034 				goto out;
10035 			}
10036 		} else {
10037 			if ((vap->va_flags & UF_SETTABLE) != vap->va_flags) {
10038 				error = EPERM;
10039 				KAUTH_DEBUG("  DENIED - user attempt to set illegal flag(s)");
10040 				goto out;
10041 			}
10042 		}
10043 	}
10044 
10045 	/* if not superuser, validate legality of new-item attributes */
10046 	if (!has_priv_suser) {
10047 		if (!defaulted_mode && VATTR_IS_ACTIVE(vap, va_mode)) {
10048 			/* setgid? */
10049 			if (vap->va_mode & S_ISGID) {
10050 				if ((error = kauth_cred_ismember_gid(cred, vap->va_gid, &ismember)) != 0) {
10051 					KAUTH_DEBUG("ATTR - ERROR: got %d checking for membership in %d", error, vap->va_gid);
10052 					goto out;
10053 				}
10054 				if (!ismember) {
10055 					KAUTH_DEBUG("  DENIED - can't set SGID bit, not a member of %d", vap->va_gid);
10056 					error = EPERM;
10057 					goto out;
10058 				}
10059 			}
10060 
10061 			/* setuid? */
10062 			if ((vap->va_mode & S_ISUID) && (vap->va_uid != kauth_cred_getuid(cred))) {
10063 				KAUTH_DEBUG("ATTR - ERROR: illegal attempt to set the setuid bit");
10064 				error = EPERM;
10065 				goto out;
10066 			}
10067 		}
10068 		if (!defaulted_owner && (vap->va_uid != kauth_cred_getuid(cred))) {
10069 			KAUTH_DEBUG("  DENIED - cannot create new item owned by %d", vap->va_uid);
10070 			error = EPERM;
10071 			goto out;
10072 		}
10073 		if (!defaulted_group) {
10074 			if ((error = kauth_cred_ismember_gid(cred, vap->va_gid, &ismember)) != 0) {
10075 				KAUTH_DEBUG("  ERROR - got %d checking for membership in %d", error, vap->va_gid);
10076 				goto out;
10077 			}
10078 			if (!ismember) {
10079 				KAUTH_DEBUG("  DENIED - cannot create new item with group %d - not a member", vap->va_gid);
10080 				error = EPERM;
10081 				goto out;
10082 			}
10083 		}
10084 
10085 		/* initialising owner/group UUID */
10086 		if (VATTR_IS_ACTIVE(vap, va_uuuid)) {
10087 			if ((error = kauth_cred_getguid(cred, &changer)) != 0) {
10088 				KAUTH_DEBUG("  ERROR - got %d trying to get caller UUID", error);
10089 				/* XXX ENOENT here - no GUID - should perhaps become EPERM */
10090 				goto out;
10091 			}
10092 			if (!kauth_guid_equal(&vap->va_uuuid, &changer)) {
10093 				KAUTH_DEBUG("  ERROR - cannot create item with supplied owner UUID - not us");
10094 				error = EPERM;
10095 				goto out;
10096 			}
10097 		}
10098 		if (VATTR_IS_ACTIVE(vap, va_guuid)) {
10099 			if ((error = kauth_cred_ismember_guid(cred, &vap->va_guuid, &ismember)) != 0) {
10100 				KAUTH_DEBUG("  ERROR - got %d trying to check group membership", error);
10101 				goto out;
10102 			}
10103 			if (!ismember) {
10104 				KAUTH_DEBUG("  ERROR - cannot create item with supplied group UUID - not a member");
10105 				error = EPERM;
10106 				goto out;
10107 			}
10108 		}
10109 	}
10110 out:
10111 	if (inherit_flags) {
10112 		/* Apply SF_RESTRICTED to the file if its parent directory was
10113 		 * restricted.  This is done at the end so that root is not
10114 		 * required if this flag is only set due to inheritance. */
10115 		VATTR_SET(vap, va_flags, (vap->va_flags | inherit_flags));
10116 	}
10117 	if (defaulted_fieldsp) {
10118 		if (defaulted_mode) {
10119 			*defaulted_fieldsp |= VATTR_PREPARE_DEFAULTED_MODE;
10120 		}
10121 		if (defaulted_group) {
10122 			*defaulted_fieldsp |= VATTR_PREPARE_DEFAULTED_GID;
10123 		}
10124 		if (defaulted_owner) {
10125 			*defaulted_fieldsp |= VATTR_PREPARE_DEFAULTED_UID;
10126 		}
10127 	}
10128 	return error;
10129 }
10130 
10131 /*
10132  * Check that the attribute information in vap can be legally written by the
10133  * context.
10134  *
10135  * Call this when you're not sure about the vnode_attr; either its contents
10136  * have come from an unknown source, or when they are variable.
10137  *
10138  * Returns errno, or zero and sets *actionp to the KAUTH_VNODE_* actions that
10139  * must be authorized to be permitted to write the vattr.
10140  */
10141 int
vnode_authattr(vnode_t vp,struct vnode_attr * vap,kauth_action_t * actionp,vfs_context_t ctx)10142 vnode_authattr(vnode_t vp, struct vnode_attr *vap, kauth_action_t *actionp, vfs_context_t ctx)
10143 {
10144 	struct vnode_attr ova;
10145 	kauth_action_t  required_action;
10146 	int             error, has_priv_suser, ismember, chowner, chgroup, clear_suid, clear_sgid;
10147 	guid_t          changer;
10148 	gid_t           group;
10149 	uid_t           owner;
10150 	mode_t          newmode;
10151 	kauth_cred_t    cred;
10152 	uint32_t        fdelta;
10153 
10154 	VATTR_INIT(&ova);
10155 	required_action = 0;
10156 	error = 0;
10157 
10158 	/*
10159 	 * Quickly check for enforcement applicability.
10160 	 */
10161 	if (vfs_authopaque(vp->v_mount)) {
10162 		goto out;
10163 	}
10164 
10165 	/*
10166 	 * Check for attempts to set nonsensical fields.
10167 	 */
10168 	if (vap->va_active & VNODE_ATTR_RDONLY) {
10169 		KAUTH_DEBUG("ATTR - ERROR: attempt to set readonly attribute(s)");
10170 		error = EINVAL;
10171 		goto out;
10172 	}
10173 
10174 	/*
10175 	 * We need to know if the caller is the superuser.
10176 	 */
10177 	cred = vfs_context_ucred(ctx);
10178 	has_priv_suser = kauth_cred_issuser(cred);
10179 
10180 	/*
10181 	 * If any of the following are changing, we need information from the old file:
10182 	 * va_uid
10183 	 * va_gid
10184 	 * va_mode
10185 	 * va_uuuid
10186 	 * va_guuid
10187 	 */
10188 	if (VATTR_IS_ACTIVE(vap, va_uid) ||
10189 	    VATTR_IS_ACTIVE(vap, va_gid) ||
10190 	    VATTR_IS_ACTIVE(vap, va_mode) ||
10191 	    VATTR_IS_ACTIVE(vap, va_uuuid) ||
10192 	    VATTR_IS_ACTIVE(vap, va_guuid)) {
10193 		VATTR_WANTED(&ova, va_mode);
10194 		VATTR_WANTED(&ova, va_uid);
10195 		VATTR_WANTED(&ova, va_gid);
10196 		VATTR_WANTED(&ova, va_uuuid);
10197 		VATTR_WANTED(&ova, va_guuid);
10198 		KAUTH_DEBUG("ATTR - security information changing, fetching existing attributes");
10199 	}
10200 
10201 	/*
10202 	 * If timestamps are being changed, we need to know who the file is owned
10203 	 * by.
10204 	 */
10205 	if (VATTR_IS_ACTIVE(vap, va_create_time) ||
10206 	    VATTR_IS_ACTIVE(vap, va_change_time) ||
10207 	    VATTR_IS_ACTIVE(vap, va_modify_time) ||
10208 	    VATTR_IS_ACTIVE(vap, va_access_time) ||
10209 	    VATTR_IS_ACTIVE(vap, va_backup_time) ||
10210 	    VATTR_IS_ACTIVE(vap, va_addedtime)) {
10211 		VATTR_WANTED(&ova, va_uid);
10212 #if 0   /* enable this when we support UUIDs as official owners */
10213 		VATTR_WANTED(&ova, va_uuuid);
10214 #endif
10215 		KAUTH_DEBUG("ATTR - timestamps changing, fetching uid and GUID");
10216 	}
10217 
10218 	/*
10219 	 * If flags are being changed, we need the old flags.
10220 	 */
10221 	if (VATTR_IS_ACTIVE(vap, va_flags)) {
10222 		KAUTH_DEBUG("ATTR - flags changing, fetching old flags");
10223 		VATTR_WANTED(&ova, va_flags);
10224 	}
10225 
10226 	/*
10227 	 * If ACLs are being changed, we need the old ACLs.
10228 	 */
10229 	if (VATTR_IS_ACTIVE(vap, va_acl)) {
10230 		KAUTH_DEBUG("ATTR - acl changing, fetching old flags");
10231 		VATTR_WANTED(&ova, va_acl);
10232 	}
10233 
10234 	/*
10235 	 * If the size is being set, make sure it's not a directory.
10236 	 */
10237 	if (VATTR_IS_ACTIVE(vap, va_data_size)) {
10238 		/* size is only meaningful on regular files, don't permit otherwise */
10239 		if (!vnode_isreg(vp)) {
10240 			KAUTH_DEBUG("ATTR - ERROR: size change requested on non-file");
10241 			error = vnode_isdir(vp) ? EISDIR : EINVAL;
10242 			goto out;
10243 		}
10244 	}
10245 
10246 	/*
10247 	 * Get old data.
10248 	 */
10249 	KAUTH_DEBUG("ATTR - fetching old attributes %016llx", ova.va_active);
10250 	if ((error = vnode_getattr(vp, &ova, ctx)) != 0) {
10251 		KAUTH_DEBUG("  ERROR - got %d trying to get attributes", error);
10252 		goto out;
10253 	}
10254 
10255 	/*
10256 	 * Size changes require write access to the file data.
10257 	 */
10258 	if (VATTR_IS_ACTIVE(vap, va_data_size)) {
10259 		/* if we can't get the size, or it's different, we need write access */
10260 		KAUTH_DEBUG("ATTR - size change, requiring WRITE_DATA");
10261 		required_action |= KAUTH_VNODE_WRITE_DATA;
10262 	}
10263 
10264 	/*
10265 	 * Changing timestamps?
10266 	 *
10267 	 * Note that we are only called to authorize user-requested time changes;
10268 	 * side-effect time changes are not authorized.  Authorisation is only
10269 	 * required for existing files.
10270 	 *
10271 	 * Non-owners are not permitted to change the time on an existing
10272 	 * file to anything other than the current time.
10273 	 */
10274 	if (VATTR_IS_ACTIVE(vap, va_create_time) ||
10275 	    VATTR_IS_ACTIVE(vap, va_change_time) ||
10276 	    VATTR_IS_ACTIVE(vap, va_modify_time) ||
10277 	    VATTR_IS_ACTIVE(vap, va_access_time) ||
10278 	    VATTR_IS_ACTIVE(vap, va_backup_time) ||
10279 	    VATTR_IS_ACTIVE(vap, va_addedtime)) {
10280 		/*
10281 		 * The owner and root may set any timestamps they like,
10282 		 * provided that the file is not immutable.  The owner still needs
10283 		 * WRITE_ATTRIBUTES (implied by ownership but still deniable).
10284 		 */
10285 		if (has_priv_suser || vauth_node_owner(&ova, cred)) {
10286 			KAUTH_DEBUG("ATTR - root or owner changing timestamps");
10287 			required_action |= KAUTH_VNODE_CHECKIMMUTABLE | KAUTH_VNODE_WRITE_ATTRIBUTES;
10288 		} else {
10289 			/* just setting the current time? */
10290 			if (vap->va_vaflags & VA_UTIMES_NULL) {
10291 				KAUTH_DEBUG("ATTR - non-root/owner changing timestamps, requiring WRITE_ATTRIBUTES");
10292 				required_action |= KAUTH_VNODE_WRITE_ATTRIBUTES;
10293 			} else {
10294 				KAUTH_DEBUG("ATTR - ERROR: illegal timestamp modification attempted");
10295 				error = EACCES;
10296 				goto out;
10297 			}
10298 		}
10299 	}
10300 
10301 	/*
10302 	 * Changing file mode?
10303 	 */
10304 	if (VATTR_IS_ACTIVE(vap, va_mode) && VATTR_IS_SUPPORTED(&ova, va_mode) && (ova.va_mode != vap->va_mode)) {
10305 		KAUTH_DEBUG("ATTR - mode change from %06o to %06o", ova.va_mode, vap->va_mode);
10306 
10307 		/*
10308 		 * Mode changes always have the same basic auth requirements.
10309 		 */
10310 		if (has_priv_suser) {
10311 			KAUTH_DEBUG("ATTR - superuser mode change, requiring immutability check");
10312 			required_action |= KAUTH_VNODE_CHECKIMMUTABLE;
10313 		} else {
10314 			/* need WRITE_SECURITY */
10315 			KAUTH_DEBUG("ATTR - non-superuser mode change, requiring WRITE_SECURITY");
10316 			required_action |= KAUTH_VNODE_WRITE_SECURITY;
10317 		}
10318 
10319 		/*
10320 		 * Can't set the setgid bit if you're not in the group and not root.  Have to have
10321 		 * existing group information in the case we're not setting it right now.
10322 		 */
10323 		if (vap->va_mode & S_ISGID) {
10324 			required_action |= KAUTH_VNODE_CHECKIMMUTABLE;  /* always required */
10325 			if (!has_priv_suser) {
10326 				if (VATTR_IS_ACTIVE(vap, va_gid)) {
10327 					group = vap->va_gid;
10328 				} else if (VATTR_IS_SUPPORTED(&ova, va_gid)) {
10329 					group = ova.va_gid;
10330 				} else {
10331 					KAUTH_DEBUG("ATTR - ERROR: setgid but no gid available");
10332 					error = EINVAL;
10333 					goto out;
10334 				}
10335 				/*
10336 				 * This might be too restrictive; WRITE_SECURITY might be implied by
10337 				 * membership in this case, rather than being an additional requirement.
10338 				 */
10339 				if ((error = kauth_cred_ismember_gid(cred, group, &ismember)) != 0) {
10340 					KAUTH_DEBUG("ATTR - ERROR: got %d checking for membership in %d", error, vap->va_gid);
10341 					goto out;
10342 				}
10343 				if (!ismember) {
10344 					KAUTH_DEBUG("  DENIED - can't set SGID bit, not a member of %d", group);
10345 					error = EPERM;
10346 					goto out;
10347 				}
10348 			}
10349 		}
10350 
10351 		/*
10352 		 * Can't set the setuid bit unless you're root or the file's owner.
10353 		 */
10354 		if (vap->va_mode & S_ISUID) {
10355 			required_action |= KAUTH_VNODE_CHECKIMMUTABLE;  /* always required */
10356 			if (!has_priv_suser) {
10357 				if (VATTR_IS_ACTIVE(vap, va_uid)) {
10358 					owner = vap->va_uid;
10359 				} else if (VATTR_IS_SUPPORTED(&ova, va_uid)) {
10360 					owner = ova.va_uid;
10361 				} else {
10362 					KAUTH_DEBUG("ATTR - ERROR: setuid but no uid available");
10363 					error = EINVAL;
10364 					goto out;
10365 				}
10366 				if (owner != kauth_cred_getuid(cred)) {
10367 					/*
10368 					 * We could allow this if WRITE_SECURITY is permitted, perhaps.
10369 					 */
10370 					KAUTH_DEBUG("ATTR - ERROR: illegal attempt to set the setuid bit");
10371 					error = EPERM;
10372 					goto out;
10373 				}
10374 			}
10375 		}
10376 	}
10377 
10378 	/*
10379 	 * Validate/mask flags changes.  This checks that only the flags in
10380 	 * the UF_SETTABLE mask are being set, and preserves the flags in
10381 	 * the SF_SETTABLE case.
10382 	 *
10383 	 * Since flags changes may be made in conjunction with other changes,
10384 	 * we will ask the auth code to ignore immutability in the case that
10385 	 * the SF_* flags are not set and we are only manipulating the file flags.
10386 	 *
10387 	 */
10388 	if (VATTR_IS_ACTIVE(vap, va_flags)) {
10389 		/* compute changing flags bits */
10390 		vap->va_flags &= ~SF_SYNTHETIC;
10391 		ova.va_flags &= ~SF_SYNTHETIC;
10392 		if (VATTR_IS_SUPPORTED(&ova, va_flags)) {
10393 			fdelta = vap->va_flags ^ ova.va_flags;
10394 		} else {
10395 			fdelta = vap->va_flags;
10396 		}
10397 
10398 		if (fdelta != 0) {
10399 			KAUTH_DEBUG("ATTR - flags changing, requiring WRITE_SECURITY");
10400 			required_action |= KAUTH_VNODE_WRITE_SECURITY;
10401 
10402 			/* check that changing bits are legal */
10403 			if (has_priv_suser) {
10404 				/*
10405 				 * The immutability check will prevent us from clearing the SF_*
10406 				 * flags unless the system securelevel permits it, so just check
10407 				 * for legal flags here.
10408 				 */
10409 				if (fdelta & ~(UF_SETTABLE | SF_SETTABLE)) {
10410 					error = EPERM;
10411 					KAUTH_DEBUG("  DENIED - superuser attempt to set illegal flag(s)");
10412 					goto out;
10413 				}
10414 			} else {
10415 				if (fdelta & ~UF_SETTABLE) {
10416 					error = EPERM;
10417 					KAUTH_DEBUG("  DENIED - user attempt to set illegal flag(s)");
10418 					goto out;
10419 				}
10420 			}
10421 			/*
10422 			 * If the caller has the ability to manipulate file flags,
10423 			 * security is not reduced by ignoring them for this operation.
10424 			 *
10425 			 * A more complete test here would consider the 'after' states of the flags
10426 			 * to determine whether it would permit the operation, but this becomes
10427 			 * very complex.
10428 			 *
10429 			 * Ignoring immutability is conditional on securelevel; this does not bypass
10430 			 * the SF_* flags if securelevel > 0.
10431 			 */
10432 			required_action |= KAUTH_VNODE_NOIMMUTABLE;
10433 		}
10434 	}
10435 
10436 	/*
10437 	 * Validate ownership information.
10438 	 */
10439 	chowner = 0;
10440 	chgroup = 0;
10441 	clear_suid = 0;
10442 	clear_sgid = 0;
10443 
10444 	/*
10445 	 * uid changing
10446 	 * Note that if the filesystem didn't give us a UID, we expect that it doesn't
10447 	 * support them in general, and will ignore it if/when we try to set it.
10448 	 * We might want to clear the uid out of vap completely here.
10449 	 */
10450 	if (VATTR_IS_ACTIVE(vap, va_uid)) {
10451 		if (VATTR_IS_SUPPORTED(&ova, va_uid) && (vap->va_uid != ova.va_uid)) {
10452 			if (!has_priv_suser && (kauth_cred_getuid(cred) != vap->va_uid)) {
10453 				KAUTH_DEBUG("  DENIED - non-superuser cannot change ownershipt to a third party");
10454 				error = EPERM;
10455 				goto out;
10456 			}
10457 			chowner = 1;
10458 		}
10459 		clear_suid = 1;
10460 	}
10461 
10462 	/*
10463 	 * gid changing
10464 	 * Note that if the filesystem didn't give us a GID, we expect that it doesn't
10465 	 * support them in general, and will ignore it if/when we try to set it.
10466 	 * We might want to clear the gid out of vap completely here.
10467 	 */
10468 	if (VATTR_IS_ACTIVE(vap, va_gid)) {
10469 		if (VATTR_IS_SUPPORTED(&ova, va_gid) && (vap->va_gid != ova.va_gid)) {
10470 			if (!has_priv_suser) {
10471 				if ((error = kauth_cred_ismember_gid(cred, vap->va_gid, &ismember)) != 0) {
10472 					KAUTH_DEBUG("  ERROR - got %d checking for membership in %d", error, vap->va_gid);
10473 					goto out;
10474 				}
10475 				if (!ismember) {
10476 					KAUTH_DEBUG("  DENIED - group change from %d to %d but not a member of target group",
10477 					    ova.va_gid, vap->va_gid);
10478 					error = EPERM;
10479 					goto out;
10480 				}
10481 			}
10482 			chgroup = 1;
10483 		}
10484 		clear_sgid = 1;
10485 	}
10486 
10487 	/*
10488 	 * Owner UUID being set or changed.
10489 	 */
10490 	if (VATTR_IS_ACTIVE(vap, va_uuuid)) {
10491 		/* if the owner UUID is not actually changing ... */
10492 		if (VATTR_IS_SUPPORTED(&ova, va_uuuid)) {
10493 			if (kauth_guid_equal(&vap->va_uuuid, &ova.va_uuuid)) {
10494 				goto no_uuuid_change;
10495 			}
10496 
10497 			/*
10498 			 * If the current owner UUID is a null GUID, check
10499 			 * it against the UUID corresponding to the owner UID.
10500 			 */
10501 			if (kauth_guid_equal(&ova.va_uuuid, &kauth_null_guid) &&
10502 			    VATTR_IS_SUPPORTED(&ova, va_uid)) {
10503 				guid_t uid_guid;
10504 
10505 				if (kauth_cred_uid2guid(ova.va_uid, &uid_guid) == 0 &&
10506 				    kauth_guid_equal(&vap->va_uuuid, &uid_guid)) {
10507 					goto no_uuuid_change;
10508 				}
10509 			}
10510 		}
10511 
10512 		/*
10513 		 * The owner UUID cannot be set by a non-superuser to anything other than
10514 		 * their own or a null GUID (to "unset" the owner UUID).
10515 		 * Note that file systems must be prepared to handle the
10516 		 * null UUID case in a manner appropriate for that file
10517 		 * system.
10518 		 */
10519 		if (!has_priv_suser) {
10520 			if ((error = kauth_cred_getguid(cred, &changer)) != 0) {
10521 				KAUTH_DEBUG("  ERROR - got %d trying to get caller UUID", error);
10522 				/* XXX ENOENT here - no UUID - should perhaps become EPERM */
10523 				goto out;
10524 			}
10525 			if (!kauth_guid_equal(&vap->va_uuuid, &changer) &&
10526 			    !kauth_guid_equal(&vap->va_uuuid, &kauth_null_guid)) {
10527 				KAUTH_DEBUG("  ERROR - cannot set supplied owner UUID - not us / null");
10528 				error = EPERM;
10529 				goto out;
10530 			}
10531 		}
10532 		chowner = 1;
10533 		clear_suid = 1;
10534 	}
10535 no_uuuid_change:
10536 	/*
10537 	 * Group UUID being set or changed.
10538 	 */
10539 	if (VATTR_IS_ACTIVE(vap, va_guuid)) {
10540 		/* if the group UUID is not actually changing ... */
10541 		if (VATTR_IS_SUPPORTED(&ova, va_guuid)) {
10542 			if (kauth_guid_equal(&vap->va_guuid, &ova.va_guuid)) {
10543 				goto no_guuid_change;
10544 			}
10545 
10546 			/*
10547 			 * If the current group UUID is a null UUID, check
10548 			 * it against the UUID corresponding to the group GID.
10549 			 */
10550 			if (kauth_guid_equal(&ova.va_guuid, &kauth_null_guid) &&
10551 			    VATTR_IS_SUPPORTED(&ova, va_gid)) {
10552 				guid_t gid_guid;
10553 
10554 				if (kauth_cred_gid2guid(ova.va_gid, &gid_guid) == 0 &&
10555 				    kauth_guid_equal(&vap->va_guuid, &gid_guid)) {
10556 					goto no_guuid_change;
10557 				}
10558 			}
10559 		}
10560 
10561 		/*
10562 		 * The group UUID cannot be set by a non-superuser to anything other than
10563 		 * one of which they are a member or a null GUID (to "unset"
10564 		 * the group UUID).
10565 		 * Note that file systems must be prepared to handle the
10566 		 * null UUID case in a manner appropriate for that file
10567 		 * system.
10568 		 */
10569 		if (!has_priv_suser) {
10570 			if (kauth_guid_equal(&vap->va_guuid, &kauth_null_guid)) {
10571 				ismember = 1;
10572 			} else if ((error = kauth_cred_ismember_guid(cred, &vap->va_guuid, &ismember)) != 0) {
10573 				KAUTH_DEBUG("  ERROR - got %d trying to check group membership", error);
10574 				goto out;
10575 			}
10576 			if (!ismember) {
10577 				KAUTH_DEBUG("  ERROR - cannot set supplied group UUID - not a member / null");
10578 				error = EPERM;
10579 				goto out;
10580 			}
10581 		}
10582 		chgroup = 1;
10583 	}
10584 no_guuid_change:
10585 
10586 	/*
10587 	 * Compute authorisation for group/ownership changes.
10588 	 */
10589 	if (chowner || chgroup || clear_suid || clear_sgid) {
10590 		if (has_priv_suser) {
10591 			KAUTH_DEBUG("ATTR - superuser changing file owner/group, requiring immutability check");
10592 			required_action |= KAUTH_VNODE_CHECKIMMUTABLE;
10593 		} else {
10594 			if (chowner) {
10595 				KAUTH_DEBUG("ATTR - ownership change, requiring TAKE_OWNERSHIP");
10596 				required_action |= KAUTH_VNODE_TAKE_OWNERSHIP;
10597 			}
10598 			if (chgroup && !chowner) {
10599 				KAUTH_DEBUG("ATTR - group change, requiring WRITE_SECURITY");
10600 				required_action |= KAUTH_VNODE_WRITE_SECURITY;
10601 			}
10602 		}
10603 
10604 		/*
10605 		 * clear set-uid and set-gid bits. POSIX only requires this for
10606 		 * non-privileged processes but we do it even for root.
10607 		 */
10608 		if (VATTR_IS_ACTIVE(vap, va_mode)) {
10609 			newmode = vap->va_mode;
10610 		} else if (VATTR_IS_SUPPORTED(&ova, va_mode)) {
10611 			newmode = ova.va_mode;
10612 		} else {
10613 			KAUTH_DEBUG("CHOWN - trying to change owner but cannot get mode from filesystem to mask setugid bits");
10614 			newmode = 0;
10615 		}
10616 
10617 		/* chown always clears setuid/gid bits. An exception is made for
10618 		 * setattrlist which can set both at the same time: <uid, gid, mode> on a file:
10619 		 * setattrlist is allowed to set the new mode on the file and change (chown)
10620 		 * uid/gid.
10621 		 */
10622 		if (newmode & (S_ISUID | S_ISGID)) {
10623 			if (!VATTR_IS_ACTIVE(vap, va_mode)) {
10624 				KAUTH_DEBUG("CHOWN - masking setugid bits from mode %o to %o",
10625 				    newmode, newmode & ~(S_ISUID | S_ISGID));
10626 				newmode &= ~(S_ISUID | S_ISGID);
10627 			}
10628 			VATTR_SET(vap, va_mode, newmode);
10629 		}
10630 	}
10631 
10632 	/*
10633 	 * Authorise changes in the ACL.
10634 	 */
10635 	if (VATTR_IS_ACTIVE(vap, va_acl)) {
10636 		/* no existing ACL */
10637 		if (!VATTR_IS_ACTIVE(&ova, va_acl) || (ova.va_acl == NULL)) {
10638 			/* adding an ACL */
10639 			if (vap->va_acl != NULL) {
10640 				required_action |= KAUTH_VNODE_WRITE_SECURITY;
10641 				KAUTH_DEBUG("CHMOD - adding ACL");
10642 			}
10643 
10644 			/* removing an existing ACL */
10645 		} else if (vap->va_acl == NULL) {
10646 			required_action |= KAUTH_VNODE_WRITE_SECURITY;
10647 			KAUTH_DEBUG("CHMOD - removing ACL");
10648 
10649 			/* updating an existing ACL */
10650 		} else {
10651 			if (vap->va_acl->acl_entrycount != ova.va_acl->acl_entrycount) {
10652 				/* entry count changed, must be different */
10653 				required_action |= KAUTH_VNODE_WRITE_SECURITY;
10654 				KAUTH_DEBUG("CHMOD - adding/removing ACL entries");
10655 			} else if (vap->va_acl->acl_entrycount > 0) {
10656 				/* both ACLs have the same ACE count, said count is 1 or more, bitwise compare ACLs */
10657 				if (memcmp(&vap->va_acl->acl_ace[0], &ova.va_acl->acl_ace[0],
10658 				    sizeof(struct kauth_ace) * vap->va_acl->acl_entrycount)) {
10659 					required_action |= KAUTH_VNODE_WRITE_SECURITY;
10660 					KAUTH_DEBUG("CHMOD - changing ACL entries");
10661 				}
10662 			}
10663 		}
10664 	}
10665 
10666 	/*
10667 	 * Other attributes that require authorisation.
10668 	 */
10669 	if (VATTR_IS_ACTIVE(vap, va_encoding)) {
10670 		required_action |= KAUTH_VNODE_WRITE_ATTRIBUTES;
10671 	}
10672 
10673 out:
10674 	if (VATTR_IS_SUPPORTED(&ova, va_acl) && (ova.va_acl != NULL)) {
10675 		kauth_acl_free(ova.va_acl);
10676 	}
10677 	if (error == 0) {
10678 		*actionp = required_action;
10679 	}
10680 	return error;
10681 }
10682 
10683 static int
setlocklocal_callback(struct vnode * vp,__unused void * cargs)10684 setlocklocal_callback(struct vnode *vp, __unused void *cargs)
10685 {
10686 	vnode_lock_spin(vp);
10687 	vp->v_flag |= VLOCKLOCAL;
10688 	vnode_unlock(vp);
10689 
10690 	return VNODE_RETURNED;
10691 }
10692 
10693 void
vfs_setlocklocal(mount_t mp)10694 vfs_setlocklocal(mount_t mp)
10695 {
10696 	mount_lock_spin(mp);
10697 	mp->mnt_kern_flag |= MNTK_LOCK_LOCAL;
10698 	mount_unlock(mp);
10699 
10700 	/*
10701 	 * The number of active vnodes is expected to be
10702 	 * very small when vfs_setlocklocal is invoked.
10703 	 */
10704 	vnode_iterate(mp, 0, setlocklocal_callback, NULL);
10705 }
10706 
10707 void
vfs_setcompoundopen(mount_t mp)10708 vfs_setcompoundopen(mount_t mp)
10709 {
10710 	mount_lock_spin(mp);
10711 	mp->mnt_compound_ops |= COMPOUND_VNOP_OPEN;
10712 	mount_unlock(mp);
10713 }
10714 
10715 void
vnode_setswapmount(vnode_t vp)10716 vnode_setswapmount(vnode_t vp)
10717 {
10718 	mount_lock(vp->v_mount);
10719 	vp->v_mount->mnt_kern_flag |= MNTK_SWAP_MOUNT;
10720 	mount_unlock(vp->v_mount);
10721 }
10722 
10723 
10724 int64_t
vnode_getswappin_avail(vnode_t vp)10725 vnode_getswappin_avail(vnode_t vp)
10726 {
10727 	int64_t max_swappin_avail = 0;
10728 
10729 	mount_lock(vp->v_mount);
10730 	if (vp->v_mount->mnt_ioflags & MNT_IOFLAGS_SWAPPIN_SUPPORTED) {
10731 		max_swappin_avail = vp->v_mount->mnt_max_swappin_available;
10732 	}
10733 	mount_unlock(vp->v_mount);
10734 
10735 	return max_swappin_avail;
10736 }
10737 
10738 
10739 void
vn_setunionwait(vnode_t vp)10740 vn_setunionwait(vnode_t vp)
10741 {
10742 	vnode_lock_spin(vp);
10743 	vp->v_flag |= VISUNION;
10744 	vnode_unlock(vp);
10745 }
10746 
10747 
10748 void
vn_checkunionwait(vnode_t vp)10749 vn_checkunionwait(vnode_t vp)
10750 {
10751 	vnode_lock_spin(vp);
10752 	while ((vp->v_flag & VISUNION) == VISUNION) {
10753 		msleep((caddr_t)&vp->v_flag, &vp->v_lock, 0, 0, 0);
10754 	}
10755 	vnode_unlock(vp);
10756 }
10757 
10758 void
vn_clearunionwait(vnode_t vp,int locked)10759 vn_clearunionwait(vnode_t vp, int locked)
10760 {
10761 	if (!locked) {
10762 		vnode_lock_spin(vp);
10763 	}
10764 	if ((vp->v_flag & VISUNION) == VISUNION) {
10765 		vp->v_flag &= ~VISUNION;
10766 		wakeup((caddr_t)&vp->v_flag);
10767 	}
10768 	if (!locked) {
10769 		vnode_unlock(vp);
10770 	}
10771 }
10772 
10773 int
vnode_materialize_dataless_file(vnode_t vp,uint64_t op_type)10774 vnode_materialize_dataless_file(vnode_t vp, uint64_t op_type)
10775 {
10776 	int error;
10777 
10778 	/* Swap files are special; ignore them */
10779 	if (vnode_isswap(vp)) {
10780 		return 0;
10781 	}
10782 
10783 	error = resolve_nspace_item(vp,
10784 	    op_type | NAMESPACE_HANDLER_NSPACE_EVENT);
10785 
10786 	/*
10787 	 * The file resolver owns the logic about what error to return
10788 	 * to the caller.  We only need to handle a couple of special
10789 	 * cases here:
10790 	 */
10791 	if (error == EJUSTRETURN) {
10792 		/*
10793 		 * The requesting process is allowed to interact with
10794 		 * dataless objects.  Make a couple of sanity-checks
10795 		 * here to ensure the action makes sense.
10796 		 */
10797 		switch (op_type) {
10798 		case NAMESPACE_HANDLER_WRITE_OP:
10799 		case NAMESPACE_HANDLER_TRUNCATE_OP:
10800 		case NAMESPACE_HANDLER_RENAME_OP:
10801 			/*
10802 			 * This handles the case of the resolver itself
10803 			 * writing data to the file (or throwing it
10804 			 * away).
10805 			 */
10806 			error = 0;
10807 			break;
10808 		case NAMESPACE_HANDLER_READ_OP:
10809 			/*
10810 			 * This handles the case of the resolver needing
10811 			 * to look up inside of a dataless directory while
10812 			 * it's in the process of materializing it (for
10813 			 * example, creating files or directories).
10814 			 */
10815 			error = (vnode_vtype(vp) == VDIR) ? 0 : EBADF;
10816 			break;
10817 		default:
10818 			error = EBADF;
10819 			break;
10820 		}
10821 	}
10822 
10823 	return error;
10824 }
10825 
10826 /*
10827  * Removes orphaned apple double files during a rmdir
10828  * Works by:
10829  * 1. vnode_suspend().
10830  * 2. Call VNOP_READDIR() till the end of directory is reached.
10831  * 3. Check if the directory entries returned are regular files with name starting with "._".  If not, return ENOTEMPTY.
10832  * 4. Continue (2) and (3) till end of directory is reached.
10833  * 5. If all the entries in the directory were files with "._" name, delete all the files.
10834  * 6. vnode_resume()
10835  * 7. If deletion of all files succeeded, call VNOP_RMDIR() again.
10836  */
10837 
10838 errno_t
rmdir_remove_orphaned_appleDouble(vnode_t vp,vfs_context_t ctx,int * restart_flag)10839 rmdir_remove_orphaned_appleDouble(vnode_t vp, vfs_context_t ctx, int * restart_flag)
10840 {
10841 #define UIO_BUFF_SIZE 2048
10842 	uio_t auio = NULL;
10843 	int eofflag, siz = UIO_BUFF_SIZE, alloc_size = 0, nentries = 0;
10844 	int open_flag = 0, full_erase_flag = 0;
10845 	uio_stackbuf_t uio_buf[UIO_SIZEOF(1)];
10846 	char *rbuf = NULL;
10847 	void *dir_pos;
10848 	void *dir_end;
10849 	struct dirent *dp;
10850 	errno_t error;
10851 
10852 	error = vnode_suspend(vp);
10853 
10854 	/*
10855 	 * restart_flag is set so that the calling rmdir sleeps and resets
10856 	 */
10857 	if (error == EBUSY) {
10858 		*restart_flag = 1;
10859 	}
10860 	if (error != 0) {
10861 		return error;
10862 	}
10863 
10864 	/*
10865 	 * Prevent dataless fault materialization while we have
10866 	 * a suspended vnode.
10867 	 */
10868 	uthread_t ut = current_uthread();
10869 	bool saved_nodatalessfaults =
10870 	    (ut->uu_flag & UT_NSPACE_NODATALESSFAULTS) ? true : false;
10871 	ut->uu_flag |= UT_NSPACE_NODATALESSFAULTS;
10872 
10873 	/*
10874 	 * set up UIO
10875 	 */
10876 	rbuf = kalloc_data(siz, Z_WAITOK);
10877 	alloc_size = siz;
10878 	if (rbuf) {
10879 		auio = uio_createwithbuffer(1, 0, UIO_SYSSPACE, UIO_READ,
10880 		    &uio_buf[0], sizeof(uio_buf));
10881 	}
10882 	if (!rbuf || !auio) {
10883 		error = ENOMEM;
10884 		goto outsc;
10885 	}
10886 
10887 	uio_setoffset(auio, 0);
10888 
10889 	eofflag = 0;
10890 
10891 	if ((error = VNOP_OPEN(vp, FREAD, ctx))) {
10892 		goto outsc;
10893 	} else {
10894 		open_flag = 1;
10895 	}
10896 
10897 	/*
10898 	 * First pass checks if all files are appleDouble files.
10899 	 */
10900 
10901 	do {
10902 		siz = UIO_BUFF_SIZE;
10903 		uio_reset(auio, uio_offset(auio), UIO_SYSSPACE, UIO_READ);
10904 		uio_addiov(auio, CAST_USER_ADDR_T(rbuf), UIO_BUFF_SIZE);
10905 
10906 		if ((error = VNOP_READDIR(vp, auio, 0, &eofflag, &nentries, ctx))) {
10907 			goto outsc;
10908 		}
10909 
10910 		if (uio_resid(auio) != 0) {
10911 			siz -= uio_resid(auio);
10912 		}
10913 
10914 		/*
10915 		 * Iterate through directory
10916 		 */
10917 		dir_pos = (void*) rbuf;
10918 		dir_end = (void*) (rbuf + siz);
10919 		dp = (struct dirent*) (dir_pos);
10920 
10921 		if (dir_pos == dir_end) {
10922 			eofflag = 1;
10923 		}
10924 
10925 		while (dir_pos < dir_end) {
10926 			/*
10927 			 * Check for . and .. as well as directories
10928 			 */
10929 			if (dp->d_ino != 0 &&
10930 			    !((dp->d_namlen == 1 && dp->d_name[0] == '.') ||
10931 			    (dp->d_namlen == 2 && dp->d_name[0] == '.' && dp->d_name[1] == '.'))) {
10932 				/*
10933 				 * Check for irregular files and ._ files
10934 				 * If there is a ._._ file abort the op
10935 				 */
10936 				if (dp->d_namlen < 2 ||
10937 				    strncmp(dp->d_name, "._", 2) ||
10938 				    (dp->d_namlen >= 4 && !strncmp(&(dp->d_name[2]), "._", 2))) {
10939 					error = ENOTEMPTY;
10940 					goto outsc;
10941 				}
10942 			}
10943 			dir_pos = (void*) ((uint8_t*)dir_pos + dp->d_reclen);
10944 			dp = (struct dirent*)dir_pos;
10945 		}
10946 
10947 		/*
10948 		 * workaround for HFS/NFS setting eofflag before end of file
10949 		 */
10950 		if (vp->v_tag == VT_HFS && nentries > 2) {
10951 			eofflag = 0;
10952 		}
10953 
10954 		if (vp->v_tag == VT_NFS) {
10955 			if (eofflag && !full_erase_flag) {
10956 				full_erase_flag = 1;
10957 				eofflag = 0;
10958 				uio_reset(auio, 0, UIO_SYSSPACE, UIO_READ);
10959 			} else if (!eofflag && full_erase_flag) {
10960 				full_erase_flag = 0;
10961 			}
10962 		}
10963 	} while (!eofflag);
10964 	/*
10965 	 * If we've made it here all the files in the dir are ._ files.
10966 	 * We can delete the files even though the node is suspended
10967 	 * because we are the owner of the file.
10968 	 */
10969 
10970 	uio_reset(auio, 0, UIO_SYSSPACE, UIO_READ);
10971 	eofflag = 0;
10972 	full_erase_flag = 0;
10973 
10974 	do {
10975 		siz = UIO_BUFF_SIZE;
10976 		uio_reset(auio, uio_offset(auio), UIO_SYSSPACE, UIO_READ);
10977 		uio_addiov(auio, CAST_USER_ADDR_T(rbuf), UIO_BUFF_SIZE);
10978 
10979 		error = VNOP_READDIR(vp, auio, 0, &eofflag, &nentries, ctx);
10980 
10981 		if (error != 0) {
10982 			goto outsc;
10983 		}
10984 
10985 		if (uio_resid(auio) != 0) {
10986 			siz -= uio_resid(auio);
10987 		}
10988 
10989 		/*
10990 		 * Iterate through directory
10991 		 */
10992 		dir_pos = (void*) rbuf;
10993 		dir_end = (void*) (rbuf + siz);
10994 		dp = (struct dirent*) dir_pos;
10995 
10996 		if (dir_pos == dir_end) {
10997 			eofflag = 1;
10998 		}
10999 
11000 		while (dir_pos < dir_end) {
11001 			/*
11002 			 * Check for . and .. as well as directories
11003 			 */
11004 			if (dp->d_ino != 0 &&
11005 			    !((dp->d_namlen == 1 && dp->d_name[0] == '.') ||
11006 			    (dp->d_namlen == 2 && dp->d_name[0] == '.' && dp->d_name[1] == '.'))
11007 			    ) {
11008 				error = unlink1(ctx, vp,
11009 				    CAST_USER_ADDR_T(dp->d_name), UIO_SYSSPACE,
11010 				    VNODE_REMOVE_SKIP_NAMESPACE_EVENT |
11011 				    VNODE_REMOVE_NO_AUDIT_PATH);
11012 
11013 				if (error && error != ENOENT) {
11014 					goto outsc;
11015 				}
11016 			}
11017 			dir_pos = (void*) ((uint8_t*)dir_pos + dp->d_reclen);
11018 			dp = (struct dirent*)dir_pos;
11019 		}
11020 
11021 		/*
11022 		 * workaround for HFS/NFS setting eofflag before end of file
11023 		 */
11024 		if (vp->v_tag == VT_HFS && nentries > 2) {
11025 			eofflag = 0;
11026 		}
11027 
11028 		if (vp->v_tag == VT_NFS) {
11029 			if (eofflag && !full_erase_flag) {
11030 				full_erase_flag = 1;
11031 				eofflag = 0;
11032 				uio_reset(auio, 0, UIO_SYSSPACE, UIO_READ);
11033 			} else if (!eofflag && full_erase_flag) {
11034 				full_erase_flag = 0;
11035 			}
11036 		}
11037 	} while (!eofflag);
11038 
11039 
11040 	error = 0;
11041 
11042 outsc:
11043 	if (open_flag) {
11044 		VNOP_CLOSE(vp, FREAD, ctx);
11045 	}
11046 
11047 	if (auio) {
11048 		uio_free(auio);
11049 	}
11050 	kfree_data(rbuf, alloc_size);
11051 
11052 	if (saved_nodatalessfaults == false) {
11053 		ut->uu_flag &= ~UT_NSPACE_NODATALESSFAULTS;
11054 	}
11055 
11056 	vnode_resume(vp);
11057 
11058 	return error;
11059 }
11060 
11061 
11062 void
lock_vnode_and_post(vnode_t vp,int kevent_num)11063 lock_vnode_and_post(vnode_t vp, int kevent_num)
11064 {
11065 	/* Only take the lock if there's something there! */
11066 	if (vp->v_knotes.slh_first != NULL) {
11067 		vnode_lock(vp);
11068 		KNOTE(&vp->v_knotes, kevent_num);
11069 		vnode_unlock(vp);
11070 	}
11071 }
11072 
11073 void panic_print_vnodes(void);
11074 
11075 /* define PANIC_PRINTS_VNODES only if investigation is required. */
11076 #ifdef PANIC_PRINTS_VNODES
11077 
11078 static const char *
__vtype(uint16_t vtype)11079 __vtype(uint16_t vtype)
11080 {
11081 	switch (vtype) {
11082 	case VREG:
11083 		return "R";
11084 	case VDIR:
11085 		return "D";
11086 	case VBLK:
11087 		return "B";
11088 	case VCHR:
11089 		return "C";
11090 	case VLNK:
11091 		return "L";
11092 	case VSOCK:
11093 		return "S";
11094 	case VFIFO:
11095 		return "F";
11096 	case VBAD:
11097 		return "x";
11098 	case VSTR:
11099 		return "T";
11100 	case VCPLX:
11101 		return "X";
11102 	default:
11103 		return "?";
11104 	}
11105 }
11106 
11107 /*
11108  * build a path from the bottom up
11109  * NOTE: called from the panic path - no alloc'ing of memory and no locks!
11110  */
11111 static char *
__vpath(vnode_t vp,char * str,int len,int depth)11112 __vpath(vnode_t vp, char *str, int len, int depth)
11113 {
11114 	int vnm_len;
11115 	const char *src;
11116 	char *dst;
11117 
11118 	if (len <= 0) {
11119 		return str;
11120 	}
11121 	/* str + len is the start of the string we created */
11122 	if (!vp->v_name) {
11123 		return str + len;
11124 	}
11125 
11126 	/* follow mount vnodes to get the full path */
11127 	if ((vp->v_flag & VROOT)) {
11128 		if (vp->v_mount != NULL && vp->v_mount->mnt_vnodecovered) {
11129 			return __vpath(vp->v_mount->mnt_vnodecovered,
11130 			           str, len, depth + 1);
11131 		}
11132 		return str + len;
11133 	}
11134 
11135 	src = vp->v_name;
11136 	vnm_len = strlen(src);
11137 	if (vnm_len > len) {
11138 		/* truncate the name to fit in the string */
11139 		src += (vnm_len - len);
11140 		vnm_len = len;
11141 	}
11142 
11143 	/* start from the back and copy just characters (no NULLs) */
11144 
11145 	/* this will chop off leaf path (file) names */
11146 	if (depth > 0) {
11147 		dst = str + len - vnm_len;
11148 		memcpy(dst, src, vnm_len);
11149 		len -= vnm_len;
11150 	} else {
11151 		dst = str + len;
11152 	}
11153 
11154 	if (vp->v_parent && len > 1) {
11155 		/* follow parents up the chain */
11156 		len--;
11157 		*(dst - 1) = '/';
11158 		return __vpath(vp->v_parent, str, len, depth + 1);
11159 	}
11160 
11161 	return dst;
11162 }
11163 
11164 #define SANE_VNODE_PRINT_LIMIT 5000
11165 void
panic_print_vnodes(void)11166 panic_print_vnodes(void)
11167 {
11168 	mount_t mnt;
11169 	vnode_t vp;
11170 	int nvnodes = 0;
11171 	const char *type;
11172 	char *nm;
11173 	char vname[257];
11174 
11175 	paniclog_append_noflush("\n***** VNODES *****\n"
11176 	    "TYPE UREF ICNT PATH\n");
11177 
11178 	/* NULL-terminate the path name */
11179 	vname[sizeof(vname) - 1] = '\0';
11180 
11181 	/*
11182 	 * iterate all vnodelist items in all mounts (mntlist) -> mnt_vnodelist
11183 	 */
11184 	TAILQ_FOREACH(mnt, &mountlist, mnt_list) {
11185 		if (!ml_validate_nofault((vm_offset_t)mnt, sizeof(mount_t))) {
11186 			paniclog_append_noflush("Unable to iterate the mount list %p - encountered an invalid mount pointer %p \n",
11187 			    &mountlist, mnt);
11188 			break;
11189 		}
11190 
11191 		TAILQ_FOREACH(vp, &mnt->mnt_vnodelist, v_mntvnodes) {
11192 			if (!ml_validate_nofault((vm_offset_t)vp, sizeof(vnode_t))) {
11193 				paniclog_append_noflush("Unable to iterate the vnode list %p - encountered an invalid vnode pointer %p \n",
11194 				    &mnt->mnt_vnodelist, vp);
11195 				break;
11196 			}
11197 
11198 			if (++nvnodes > SANE_VNODE_PRINT_LIMIT) {
11199 				return;
11200 			}
11201 			type = __vtype(vp->v_type);
11202 			nm = __vpath(vp, vname, sizeof(vname) - 1, 0);
11203 			paniclog_append_noflush("%s %0d %0d %s\n",
11204 			    type, vp->v_usecount, vp->v_iocount, nm);
11205 		}
11206 	}
11207 }
11208 
11209 #else /* !PANIC_PRINTS_VNODES */
11210 void
panic_print_vnodes(void)11211 panic_print_vnodes(void)
11212 {
11213 	return;
11214 }
11215 #endif
11216 
11217 
11218 #ifdef CONFIG_IOCOUNT_TRACE
11219 static void
record_iocount_trace_vnode(vnode_t vp,int type)11220 record_iocount_trace_vnode(vnode_t vp, int type)
11221 {
11222 	void *stacks[IOCOUNT_TRACE_MAX_FRAMES] = {0};
11223 	int idx = vp->v_iocount_trace[type].idx;
11224 
11225 	if (idx >= IOCOUNT_TRACE_MAX_IDX) {
11226 		return;
11227 	}
11228 
11229 	OSBacktrace((void **)&stacks[0], IOCOUNT_TRACE_MAX_FRAMES);
11230 
11231 	/*
11232 	 * To save index space, only store the unique backtraces. If dup is found,
11233 	 * just bump the count and return.
11234 	 */
11235 	for (int i = 0; i < idx; i++) {
11236 		if (memcmp(&stacks[0], &vp->v_iocount_trace[type].stacks[i][0],
11237 		    sizeof(stacks)) == 0) {
11238 			vp->v_iocount_trace[type].counts[i]++;
11239 			return;
11240 		}
11241 	}
11242 
11243 	memcpy(&vp->v_iocount_trace[type].stacks[idx][0], &stacks[0],
11244 	    sizeof(stacks));
11245 	vp->v_iocount_trace[type].counts[idx] = 1;
11246 	vp->v_iocount_trace[type].idx++;
11247 }
11248 
11249 static void
record_iocount_trace_uthread(vnode_t vp,int count)11250 record_iocount_trace_uthread(vnode_t vp, int count)
11251 {
11252 	struct uthread *ut;
11253 
11254 	ut = current_uthread();
11255 	ut->uu_iocount += count;
11256 
11257 	if (count == 1) {
11258 		if (ut->uu_vpindex < 32) {
11259 			OSBacktrace((void **)&ut->uu_pcs[ut->uu_vpindex][0], 10);
11260 
11261 			ut->uu_vps[ut->uu_vpindex] = vp;
11262 			ut->uu_vpindex++;
11263 		}
11264 	}
11265 }
11266 
11267 static void
record_vp(vnode_t vp,int count)11268 record_vp(vnode_t vp, int count)
11269 {
11270 	if (__probable(bootarg_vnode_iocount_trace == 0 &&
11271 	    bootarg_uthread_iocount_trace == 0)) {
11272 		return;
11273 	}
11274 
11275 #if CONFIG_TRIGGERS
11276 	if (vp->v_resolve) {
11277 		return;
11278 	}
11279 #endif
11280 	if ((vp->v_flag & VSYSTEM)) {
11281 		return;
11282 	}
11283 
11284 	if (bootarg_vnode_iocount_trace) {
11285 		record_iocount_trace_vnode(vp,
11286 		    (count > 0) ? IOCOUNT_TRACE_VGET : IOCOUNT_TRACE_VPUT);
11287 	}
11288 	if (bootarg_uthread_iocount_trace) {
11289 		record_iocount_trace_uthread(vp, count);
11290 	}
11291 }
11292 #endif /* CONFIG_IOCOUNT_TRACE */
11293 
11294 #if CONFIG_TRIGGERS
11295 #define __triggers_unused
11296 #else
11297 #define __triggers_unused       __unused
11298 #endif
11299 
11300 resolver_result_t
vfs_resolver_result(__triggers_unused uint32_t seq,__triggers_unused enum resolver_status stat,__triggers_unused int aux)11301 vfs_resolver_result(__triggers_unused uint32_t seq, __triggers_unused enum resolver_status stat, __triggers_unused int aux)
11302 {
11303 #if CONFIG_TRIGGERS
11304 	/*
11305 	 * |<---   32   --->|<---  28  --->|<- 4 ->|
11306 	 *      sequence        auxiliary    status
11307 	 */
11308 	return (((uint64_t)seq) << 32) |
11309 	       (((uint64_t)(aux & 0x0fffffff)) << 4) |
11310 	       (uint64_t)(stat & 0x0000000F);
11311 #else
11312 	return (0x0ULL) | (((uint64_t)ENOTSUP) << 4) | (((uint64_t)RESOLVER_ERROR) & 0xF);
11313 #endif
11314 }
11315 
11316 #if CONFIG_TRIGGERS
11317 
11318 #define TRIG_DEBUG 0
11319 
11320 #if TRIG_DEBUG
11321 #define TRIG_LOG(...) do { printf("%s: ", __FUNCTION__); printf(__VA_ARGS__); } while (0)
11322 #else
11323 #define TRIG_LOG(...)
11324 #endif
11325 
11326 /*
11327  * Resolver result functions
11328  */
11329 
11330 
11331 enum resolver_status
vfs_resolver_status(resolver_result_t result)11332 vfs_resolver_status(resolver_result_t result)
11333 {
11334 	/* lower 4 bits is status */
11335 	return result & 0x0000000F;
11336 }
11337 
11338 uint32_t
vfs_resolver_sequence(resolver_result_t result)11339 vfs_resolver_sequence(resolver_result_t result)
11340 {
11341 	/* upper 32 bits is sequence */
11342 	return (uint32_t)(result >> 32);
11343 }
11344 
11345 int
vfs_resolver_auxiliary(resolver_result_t result)11346 vfs_resolver_auxiliary(resolver_result_t result)
11347 {
11348 	/* 28 bits of auxiliary */
11349 	return (int)(((uint32_t)(result & 0xFFFFFFF0)) >> 4);
11350 }
11351 
11352 /*
11353  * SPI
11354  * Call in for resolvers to update vnode trigger state
11355  */
11356 int
vnode_trigger_update(vnode_t vp,resolver_result_t result)11357 vnode_trigger_update(vnode_t vp, resolver_result_t result)
11358 {
11359 	vnode_resolve_t rp;
11360 	uint32_t seq;
11361 	enum resolver_status stat;
11362 
11363 	if (vp->v_resolve == NULL) {
11364 		return EINVAL;
11365 	}
11366 
11367 	stat = vfs_resolver_status(result);
11368 	seq = vfs_resolver_sequence(result);
11369 
11370 	if ((stat != RESOLVER_RESOLVED) && (stat != RESOLVER_UNRESOLVED)) {
11371 		return EINVAL;
11372 	}
11373 
11374 	rp = vp->v_resolve;
11375 	lck_mtx_lock(&rp->vr_lock);
11376 
11377 	if (seq > rp->vr_lastseq) {
11378 		if (stat == RESOLVER_RESOLVED) {
11379 			rp->vr_flags |= VNT_RESOLVED;
11380 		} else {
11381 			rp->vr_flags &= ~VNT_RESOLVED;
11382 		}
11383 
11384 		rp->vr_lastseq = seq;
11385 	}
11386 
11387 	lck_mtx_unlock(&rp->vr_lock);
11388 
11389 	return 0;
11390 }
11391 
11392 static int
vnode_resolver_attach(vnode_t vp,vnode_resolve_t rp,boolean_t ref)11393 vnode_resolver_attach(vnode_t vp, vnode_resolve_t rp, boolean_t ref)
11394 {
11395 	int error;
11396 
11397 	vnode_lock_spin(vp);
11398 	if (vp->v_resolve != NULL) {
11399 		vnode_unlock(vp);
11400 		return EINVAL;
11401 	} else {
11402 		vp->v_resolve = rp;
11403 	}
11404 	vnode_unlock(vp);
11405 
11406 	if (ref) {
11407 		error = vnode_ref_ext(vp, O_EVTONLY, VNODE_REF_FORCE);
11408 		if (error != 0) {
11409 			panic("VNODE_REF_FORCE didn't help...");
11410 		}
11411 	}
11412 
11413 	return 0;
11414 }
11415 
11416 /*
11417  * VFS internal interfaces for vnode triggers
11418  *
11419  * vnode must already have an io count on entry
11420  * v_resolve is stable when io count is non-zero
11421  */
11422 static int
vnode_resolver_create(mount_t mp,vnode_t vp,struct vnode_trigger_param * tinfo,boolean_t external)11423 vnode_resolver_create(mount_t mp, vnode_t vp, struct vnode_trigger_param *tinfo, boolean_t external)
11424 {
11425 	vnode_resolve_t rp;
11426 	int result;
11427 	char byte;
11428 
11429 #if 1
11430 	/* minimum pointer test (debugging) */
11431 	if (tinfo->vnt_data) {
11432 		byte = *((char *)tinfo->vnt_data);
11433 	}
11434 #endif
11435 	rp = kalloc_type(struct vnode_resolve, Z_WAITOK | Z_NOFAIL);
11436 
11437 	lck_mtx_init(&rp->vr_lock, &trigger_vnode_lck_grp, &trigger_vnode_lck_attr);
11438 
11439 	rp->vr_resolve_func = tinfo->vnt_resolve_func;
11440 	rp->vr_unresolve_func = tinfo->vnt_unresolve_func;
11441 	rp->vr_rearm_func = tinfo->vnt_rearm_func;
11442 	rp->vr_reclaim_func = tinfo->vnt_reclaim_func;
11443 	rp->vr_data = tinfo->vnt_data;
11444 	rp->vr_lastseq = 0;
11445 	rp->vr_flags = tinfo->vnt_flags & VNT_VALID_MASK;
11446 	if (external) {
11447 		rp->vr_flags |= VNT_EXTERNAL;
11448 	}
11449 
11450 	result = vnode_resolver_attach(vp, rp, external);
11451 	if (result != 0) {
11452 		goto out;
11453 	}
11454 
11455 	if (mp) {
11456 		OSAddAtomic(1, &mp->mnt_numtriggers);
11457 	}
11458 
11459 	return result;
11460 
11461 out:
11462 	kfree_type(struct vnode_resolve, rp);
11463 	return result;
11464 }
11465 
11466 static void
vnode_resolver_release(vnode_resolve_t rp)11467 vnode_resolver_release(vnode_resolve_t rp)
11468 {
11469 	/*
11470 	 * Give them a chance to free any private data
11471 	 */
11472 	if (rp->vr_data && rp->vr_reclaim_func) {
11473 		rp->vr_reclaim_func(NULLVP, rp->vr_data);
11474 	}
11475 
11476 	lck_mtx_destroy(&rp->vr_lock, &trigger_vnode_lck_grp);
11477 	kfree_type(struct vnode_resolve, rp);
11478 }
11479 
11480 /* Called after the vnode has been drained */
11481 static void
vnode_resolver_detach(vnode_t vp)11482 vnode_resolver_detach(vnode_t vp)
11483 {
11484 	vnode_resolve_t rp;
11485 	mount_t mp;
11486 
11487 	mp = vnode_mount(vp);
11488 
11489 	vnode_lock(vp);
11490 	rp = vp->v_resolve;
11491 	vp->v_resolve = NULL;
11492 	vnode_unlock(vp);
11493 
11494 	if ((rp->vr_flags & VNT_EXTERNAL) != 0) {
11495 		vnode_rele_ext(vp, O_EVTONLY, 1);
11496 	}
11497 
11498 	vnode_resolver_release(rp);
11499 
11500 	/* Keep count of active trigger vnodes per mount */
11501 	OSAddAtomic(-1, &mp->mnt_numtriggers);
11502 }
11503 
11504 __private_extern__
11505 void
vnode_trigger_rearm(vnode_t vp,vfs_context_t ctx)11506 vnode_trigger_rearm(vnode_t vp, vfs_context_t ctx)
11507 {
11508 	vnode_resolve_t rp;
11509 	resolver_result_t result;
11510 	enum resolver_status status;
11511 	uint32_t seq;
11512 
11513 	if ((vp->v_resolve == NULL) ||
11514 	    (vp->v_resolve->vr_rearm_func == NULL) ||
11515 	    (vp->v_resolve->vr_flags & VNT_AUTO_REARM) == 0) {
11516 		return;
11517 	}
11518 
11519 	rp = vp->v_resolve;
11520 	lck_mtx_lock(&rp->vr_lock);
11521 
11522 	/*
11523 	 * Check if VFS initiated this unmount. If so, we'll catch it after the unresolve completes.
11524 	 */
11525 	if (rp->vr_flags & VNT_VFS_UNMOUNTED) {
11526 		lck_mtx_unlock(&rp->vr_lock);
11527 		return;
11528 	}
11529 
11530 	/* Check if this vnode is already armed */
11531 	if ((rp->vr_flags & VNT_RESOLVED) == 0) {
11532 		lck_mtx_unlock(&rp->vr_lock);
11533 		return;
11534 	}
11535 
11536 	lck_mtx_unlock(&rp->vr_lock);
11537 
11538 	result = rp->vr_rearm_func(vp, 0, rp->vr_data, ctx);
11539 	status = vfs_resolver_status(result);
11540 	seq = vfs_resolver_sequence(result);
11541 
11542 	lck_mtx_lock(&rp->vr_lock);
11543 	if (seq > rp->vr_lastseq) {
11544 		if (status == RESOLVER_UNRESOLVED) {
11545 			rp->vr_flags &= ~VNT_RESOLVED;
11546 		}
11547 		rp->vr_lastseq = seq;
11548 	}
11549 	lck_mtx_unlock(&rp->vr_lock);
11550 }
11551 
11552 __private_extern__
11553 int
vnode_trigger_resolve(vnode_t vp,struct nameidata * ndp,vfs_context_t ctx)11554 vnode_trigger_resolve(vnode_t vp, struct nameidata *ndp, vfs_context_t ctx)
11555 {
11556 	vnode_resolve_t rp;
11557 	enum path_operation op;
11558 	resolver_result_t result;
11559 	enum resolver_status status;
11560 	uint32_t seq;
11561 
11562 	/*
11563 	 * N.B. we cannot call vfs_context_can_resolve_triggers()
11564 	 * here because we really only want to suppress that in
11565 	 * the event the trigger will be resolved by something in
11566 	 * user-space.  Any triggers that are resolved by the kernel
11567 	 * do not pose a threat of deadlock.
11568 	 */
11569 
11570 	/* Only trigger on topmost vnodes */
11571 	if ((vp->v_resolve == NULL) ||
11572 	    (vp->v_resolve->vr_resolve_func == NULL) ||
11573 	    (vp->v_mountedhere != NULL)) {
11574 		return 0;
11575 	}
11576 
11577 	rp = vp->v_resolve;
11578 	lck_mtx_lock(&rp->vr_lock);
11579 
11580 	/* Check if this vnode is already resolved */
11581 	if (rp->vr_flags & VNT_RESOLVED) {
11582 		lck_mtx_unlock(&rp->vr_lock);
11583 		return 0;
11584 	}
11585 
11586 	lck_mtx_unlock(&rp->vr_lock);
11587 
11588 #if CONFIG_MACF
11589 	if ((rp->vr_flags & VNT_KERN_RESOLVE) == 0) {
11590 		/*
11591 		 * VNT_KERN_RESOLVE indicates this trigger has no parameters
11592 		 * at the discression of the accessing process other than
11593 		 * the act of access. All other triggers must be checked
11594 		 */
11595 		int rv = mac_vnode_check_trigger_resolve(ctx, vp, &ndp->ni_cnd);
11596 		if (rv != 0) {
11597 			return rv;
11598 		}
11599 	}
11600 #endif
11601 
11602 	/*
11603 	 * XXX
11604 	 * assumes that resolver will not access this trigger vnode (otherwise the kernel will deadlock)
11605 	 * is there anyway to know this???
11606 	 * there can also be other legitimate lookups in parallel
11607 	 *
11608 	 * XXX - should we call this on a separate thread with a timeout?
11609 	 *
11610 	 * XXX - should we use ISLASTCN to pick the op value???  Perhaps only leafs should
11611 	 * get the richer set and non-leafs should get generic OP_LOOKUP?  TBD
11612 	 */
11613 	op = (ndp->ni_op < OP_MAXOP) ? ndp->ni_op: OP_LOOKUP;
11614 
11615 	result = rp->vr_resolve_func(vp, &ndp->ni_cnd, op, 0, rp->vr_data, ctx);
11616 	status = vfs_resolver_status(result);
11617 	seq = vfs_resolver_sequence(result);
11618 
11619 	lck_mtx_lock(&rp->vr_lock);
11620 	if (seq > rp->vr_lastseq) {
11621 		if (status == RESOLVER_RESOLVED) {
11622 			rp->vr_flags |= VNT_RESOLVED;
11623 		}
11624 		rp->vr_lastseq = seq;
11625 	}
11626 	lck_mtx_unlock(&rp->vr_lock);
11627 
11628 	/* On resolver errors, propagate the error back up */
11629 	return status == RESOLVER_ERROR ? vfs_resolver_auxiliary(result) : 0;
11630 }
11631 
11632 static int
vnode_trigger_unresolve(vnode_t vp,int flags,vfs_context_t ctx)11633 vnode_trigger_unresolve(vnode_t vp, int flags, vfs_context_t ctx)
11634 {
11635 	vnode_resolve_t rp;
11636 	resolver_result_t result;
11637 	enum resolver_status status;
11638 	uint32_t seq;
11639 
11640 	if ((vp->v_resolve == NULL) || (vp->v_resolve->vr_unresolve_func == NULL)) {
11641 		return 0;
11642 	}
11643 
11644 	rp = vp->v_resolve;
11645 	lck_mtx_lock(&rp->vr_lock);
11646 
11647 	/* Check if this vnode is already resolved */
11648 	if ((rp->vr_flags & VNT_RESOLVED) == 0) {
11649 		printf("vnode_trigger_unresolve: not currently resolved\n");
11650 		lck_mtx_unlock(&rp->vr_lock);
11651 		return 0;
11652 	}
11653 
11654 	rp->vr_flags |= VNT_VFS_UNMOUNTED;
11655 
11656 	lck_mtx_unlock(&rp->vr_lock);
11657 
11658 	/*
11659 	 * XXX
11660 	 * assumes that resolver will not access this trigger vnode (otherwise the kernel will deadlock)
11661 	 * there can also be other legitimate lookups in parallel
11662 	 *
11663 	 * XXX - should we call this on a separate thread with a timeout?
11664 	 */
11665 
11666 	result = rp->vr_unresolve_func(vp, flags, rp->vr_data, ctx);
11667 	status = vfs_resolver_status(result);
11668 	seq = vfs_resolver_sequence(result);
11669 
11670 	lck_mtx_lock(&rp->vr_lock);
11671 	if (seq > rp->vr_lastseq) {
11672 		if (status == RESOLVER_UNRESOLVED) {
11673 			rp->vr_flags &= ~VNT_RESOLVED;
11674 		}
11675 		rp->vr_lastseq = seq;
11676 	}
11677 	rp->vr_flags &= ~VNT_VFS_UNMOUNTED;
11678 	lck_mtx_unlock(&rp->vr_lock);
11679 
11680 	/* On resolver errors, propagate the error back up */
11681 	return status == RESOLVER_ERROR ? vfs_resolver_auxiliary(result) : 0;
11682 }
11683 
11684 static int
triggerisdescendant(mount_t mp,mount_t rmp)11685 triggerisdescendant(mount_t mp, mount_t rmp)
11686 {
11687 	int match = FALSE;
11688 
11689 	/*
11690 	 * walk up vnode covered chain looking for a match
11691 	 */
11692 	name_cache_lock_shared();
11693 
11694 	while (1) {
11695 		vnode_t vp;
11696 
11697 		/* did we encounter "/" ? */
11698 		if (mp->mnt_flag & MNT_ROOTFS) {
11699 			break;
11700 		}
11701 
11702 		vp = mp->mnt_vnodecovered;
11703 		if (vp == NULLVP) {
11704 			break;
11705 		}
11706 
11707 		mp = vp->v_mount;
11708 		if (mp == rmp) {
11709 			match = TRUE;
11710 			break;
11711 		}
11712 	}
11713 
11714 	name_cache_unlock();
11715 
11716 	return match;
11717 }
11718 
11719 struct trigger_unmount_info {
11720 	vfs_context_t   ctx;
11721 	mount_t         top_mp;
11722 	vnode_t         trigger_vp;
11723 	mount_t         trigger_mp;
11724 	uint32_t        trigger_vid;
11725 	int             flags;
11726 };
11727 
11728 static int
trigger_unmount_callback(mount_t mp,void * arg)11729 trigger_unmount_callback(mount_t mp, void * arg)
11730 {
11731 	struct trigger_unmount_info * infop = (struct trigger_unmount_info *)arg;
11732 	boolean_t mountedtrigger = FALSE;
11733 
11734 	/*
11735 	 * When we encounter the top level mount we're done
11736 	 */
11737 	if (mp == infop->top_mp) {
11738 		return VFS_RETURNED_DONE;
11739 	}
11740 
11741 	if ((mp->mnt_vnodecovered == NULL) ||
11742 	    (vnode_getwithref(mp->mnt_vnodecovered) != 0)) {
11743 		return VFS_RETURNED;
11744 	}
11745 
11746 	if ((mp->mnt_vnodecovered->v_mountedhere == mp) &&
11747 	    (mp->mnt_vnodecovered->v_resolve != NULL) &&
11748 	    (mp->mnt_vnodecovered->v_resolve->vr_flags & VNT_RESOLVED)) {
11749 		mountedtrigger = TRUE;
11750 	}
11751 	vnode_put(mp->mnt_vnodecovered);
11752 
11753 	/*
11754 	 * When we encounter a mounted trigger, check if its under the top level mount
11755 	 */
11756 	if (!mountedtrigger || !triggerisdescendant(mp, infop->top_mp)) {
11757 		return VFS_RETURNED;
11758 	}
11759 
11760 	/*
11761 	 * Process any pending nested mount (now that its not referenced)
11762 	 */
11763 	if ((infop->trigger_vp != NULLVP) &&
11764 	    (vnode_getwithvid(infop->trigger_vp, infop->trigger_vid) == 0)) {
11765 		vnode_t vp = infop->trigger_vp;
11766 		int error;
11767 
11768 		vnode_drop(infop->trigger_vp);
11769 		infop->trigger_vp = NULLVP;
11770 
11771 		if (mp == vp->v_mountedhere) {
11772 			vnode_put(vp);
11773 			printf("trigger_unmount_callback: unexpected match '%s'\n",
11774 			    mp->mnt_vfsstat.f_mntonname);
11775 			return VFS_RETURNED;
11776 		}
11777 		if (infop->trigger_mp != vp->v_mountedhere) {
11778 			vnode_put(vp);
11779 			printf("trigger_unmount_callback: trigger mnt changed! (%p != %p)\n",
11780 			    infop->trigger_mp, vp->v_mountedhere);
11781 			goto savenext;
11782 		}
11783 
11784 		error = vnode_trigger_unresolve(vp, infop->flags, infop->ctx);
11785 		vnode_put(vp);
11786 		if (error) {
11787 			printf("unresolving: '%s', err %d\n",
11788 			    vp->v_mountedhere ? vp->v_mountedhere->mnt_vfsstat.f_mntonname :
11789 			    "???", error);
11790 			return VFS_RETURNED_DONE; /* stop iteration on errors */
11791 		}
11792 	} else if (infop->trigger_vp != NULLVP) {
11793 		vnode_drop(infop->trigger_vp);
11794 	}
11795 
11796 savenext:
11797 	/*
11798 	 * We can't call resolver here since we hold a mount iter
11799 	 * ref on mp so save its covered vp for later processing
11800 	 */
11801 	infop->trigger_vp = mp->mnt_vnodecovered;
11802 	if ((infop->trigger_vp != NULLVP) &&
11803 	    (vnode_getwithref(infop->trigger_vp) == 0)) {
11804 		if (infop->trigger_vp->v_mountedhere == mp) {
11805 			infop->trigger_vid = infop->trigger_vp->v_id;
11806 			vnode_hold(infop->trigger_vp);
11807 			infop->trigger_mp = mp;
11808 		}
11809 		vnode_put(infop->trigger_vp);
11810 	}
11811 
11812 	return VFS_RETURNED;
11813 }
11814 
11815 /*
11816  * Attempt to unmount any trigger mounts nested underneath a mount.
11817  * This is a best effort attempt and no retries are performed here.
11818  *
11819  * Note: mp->mnt_rwlock is held exclusively on entry (so be carefull)
11820  */
11821 __private_extern__
11822 void
vfs_nested_trigger_unmounts(mount_t mp,int flags,vfs_context_t ctx)11823 vfs_nested_trigger_unmounts(mount_t mp, int flags, vfs_context_t ctx)
11824 {
11825 	struct trigger_unmount_info info;
11826 
11827 	/* Must have trigger vnodes */
11828 	if (mp->mnt_numtriggers == 0) {
11829 		return;
11830 	}
11831 	/* Avoid recursive requests (by checking covered vnode) */
11832 	if ((mp->mnt_vnodecovered != NULL) &&
11833 	    (vnode_getwithref(mp->mnt_vnodecovered) == 0)) {
11834 		boolean_t recursive = FALSE;
11835 
11836 		if ((mp->mnt_vnodecovered->v_mountedhere == mp) &&
11837 		    (mp->mnt_vnodecovered->v_resolve != NULL) &&
11838 		    (mp->mnt_vnodecovered->v_resolve->vr_flags & VNT_VFS_UNMOUNTED)) {
11839 			recursive = TRUE;
11840 		}
11841 		vnode_put(mp->mnt_vnodecovered);
11842 		if (recursive) {
11843 			return;
11844 		}
11845 	}
11846 
11847 	/*
11848 	 * Attempt to unmount any nested trigger mounts (best effort)
11849 	 */
11850 	info.ctx = ctx;
11851 	info.top_mp = mp;
11852 	info.trigger_vp = NULLVP;
11853 	info.trigger_vid = 0;
11854 	info.trigger_mp = NULL;
11855 	info.flags = flags;
11856 
11857 	(void) vfs_iterate(VFS_ITERATE_TAIL_FIRST, trigger_unmount_callback, &info);
11858 
11859 	/*
11860 	 * Process remaining nested mount (now that its not referenced)
11861 	 */
11862 	if ((info.trigger_vp != NULLVP) &&
11863 	    (vnode_getwithvid(info.trigger_vp, info.trigger_vid) == 0)) {
11864 		vnode_t vp = info.trigger_vp;
11865 
11866 		if (info.trigger_mp == vp->v_mountedhere) {
11867 			(void) vnode_trigger_unresolve(vp, flags, ctx);
11868 		}
11869 		vnode_put(vp);
11870 		vnode_drop(vp);
11871 	} else if (info.trigger_vp != NULLVP) {
11872 		vnode_drop(info.trigger_vp);
11873 	}
11874 }
11875 
11876 int
vfs_addtrigger(mount_t mp,const char * relpath,struct vnode_trigger_info * vtip,vfs_context_t ctx)11877 vfs_addtrigger(mount_t mp, const char *relpath, struct vnode_trigger_info *vtip, vfs_context_t ctx)
11878 {
11879 	struct nameidata *ndp;
11880 	int res;
11881 	vnode_t rvp, vp;
11882 	struct vnode_trigger_param vtp;
11883 
11884 	/*
11885 	 * Must be called for trigger callback, wherein rwlock is held
11886 	 */
11887 	lck_rw_assert(&mp->mnt_rwlock, LCK_RW_ASSERT_HELD);
11888 
11889 	TRIG_LOG("Adding trigger at %s\n", relpath);
11890 	TRIG_LOG("Trying VFS_ROOT\n");
11891 
11892 	ndp = kalloc_type(struct nameidata, Z_WAITOK | Z_NOFAIL);
11893 
11894 	/*
11895 	 * We do a lookup starting at the root of the mountpoint, unwilling
11896 	 * to cross into other mountpoints.
11897 	 */
11898 	res = VFS_ROOT(mp, &rvp, ctx);
11899 	if (res != 0) {
11900 		goto out;
11901 	}
11902 
11903 	TRIG_LOG("Trying namei\n");
11904 
11905 	NDINIT(ndp, LOOKUP, OP_LOOKUP, USEDVP | NOCROSSMOUNT | FOLLOW, UIO_SYSSPACE,
11906 	    CAST_USER_ADDR_T(relpath), ctx);
11907 	ndp->ni_dvp = rvp;
11908 	res = namei(ndp);
11909 	if (res != 0) {
11910 		vnode_put(rvp);
11911 		goto out;
11912 	}
11913 
11914 	vp = ndp->ni_vp;
11915 	nameidone(ndp);
11916 	vnode_put(rvp);
11917 
11918 	TRIG_LOG("Trying vnode_resolver_create()\n");
11919 
11920 	/*
11921 	 * Set up blob.  vnode_create() takes a larger structure
11922 	 * with creation info, and we needed something different
11923 	 * for this case.  One needs to win, or we need to munge both;
11924 	 * vnode_create() wins.
11925 	 */
11926 	bzero(&vtp, sizeof(vtp));
11927 	vtp.vnt_resolve_func = vtip->vti_resolve_func;
11928 	vtp.vnt_unresolve_func = vtip->vti_unresolve_func;
11929 	vtp.vnt_rearm_func = vtip->vti_rearm_func;
11930 	vtp.vnt_reclaim_func = vtip->vti_reclaim_func;
11931 	vtp.vnt_reclaim_func = vtip->vti_reclaim_func;
11932 	vtp.vnt_data = vtip->vti_data;
11933 	vtp.vnt_flags = vtip->vti_flags;
11934 
11935 	res = vnode_resolver_create(mp, vp, &vtp, TRUE);
11936 	vnode_put(vp);
11937 out:
11938 	kfree_type(struct nameidata, ndp);
11939 	TRIG_LOG("Returning %d\n", res);
11940 	return res;
11941 }
11942 
11943 #endif /* CONFIG_TRIGGERS */
11944 
11945 vm_offset_t
kdebug_vnode(vnode_t vp)11946 kdebug_vnode(vnode_t vp)
11947 {
11948 	return VM_KERNEL_ADDRPERM(vp);
11949 }
11950 
11951 static int flush_cache_on_write = 0;
11952 SYSCTL_INT(_kern, OID_AUTO, flush_cache_on_write,
11953     CTLFLAG_RW | CTLFLAG_LOCKED, &flush_cache_on_write, 0,
11954     "always flush the drive cache on writes to uncached files");
11955 
11956 int
vnode_should_flush_after_write(vnode_t vp,int ioflag)11957 vnode_should_flush_after_write(vnode_t vp, int ioflag)
11958 {
11959 	return flush_cache_on_write
11960 	       && (ISSET(ioflag, IO_NOCACHE) || vnode_isnocache(vp));
11961 }
11962 
11963 /*
11964  * sysctl for use by disk I/O tracing tools to get the list of existing
11965  * vnodes' paths
11966  */
11967 
11968 #define NPATH_WORDS (MAXPATHLEN / sizeof(unsigned long))
11969 struct vnode_trace_paths_context {
11970 	uint64_t count;
11971 	/*
11972 	 * Must be a multiple of 4, then -1, for tracing!
11973 	 */
11974 	unsigned long path[NPATH_WORDS + (4 - (NPATH_WORDS % 4)) - 1];
11975 };
11976 
11977 static int
vnode_trace_path_callback(struct vnode * vp,void * vctx)11978 vnode_trace_path_callback(struct vnode *vp, void *vctx)
11979 {
11980 	struct vnode_trace_paths_context *ctx = vctx;
11981 	size_t path_len = sizeof(ctx->path);
11982 
11983 	int getpath_len = (int)path_len;
11984 	if (vn_getpath(vp, (char *)ctx->path, &getpath_len) == 0) {
11985 		/* vn_getpath() NUL-terminates, and len includes the NUL. */
11986 		assert(getpath_len >= 0);
11987 		path_len = (size_t)getpath_len;
11988 
11989 		assert(path_len <= sizeof(ctx->path));
11990 		kdebug_vfs_lookup(ctx->path, (int)path_len, vp,
11991 		    KDBG_VFS_LOOKUP_FLAG_LOOKUP | KDBG_VFS_LOOKUP_FLAG_NOPROCFILT);
11992 
11993 		if (++(ctx->count) == 1000) {
11994 			thread_yield_to_preemption();
11995 			ctx->count = 0;
11996 		}
11997 	}
11998 
11999 	return VNODE_RETURNED;
12000 }
12001 
12002 static int
vfs_trace_paths_callback(mount_t mp,void * arg)12003 vfs_trace_paths_callback(mount_t mp, void *arg)
12004 {
12005 	if (mp->mnt_flag & MNT_LOCAL) {
12006 		vnode_iterate(mp, VNODE_ITERATE_ALL, vnode_trace_path_callback, arg);
12007 	}
12008 
12009 	return VFS_RETURNED;
12010 }
12011 
12012 static int sysctl_vfs_trace_paths SYSCTL_HANDLER_ARGS {
12013 	struct vnode_trace_paths_context ctx;
12014 
12015 	(void)oidp;
12016 	(void)arg1;
12017 	(void)arg2;
12018 	(void)req;
12019 
12020 	if (!kauth_cred_issuser(kauth_cred_get())) {
12021 		return EPERM;
12022 	}
12023 
12024 	if (!kdebug_enable || !kdebug_debugid_enabled(VFS_LOOKUP)) {
12025 		return EINVAL;
12026 	}
12027 
12028 	bzero(&ctx, sizeof(struct vnode_trace_paths_context));
12029 
12030 	vfs_iterate(0, vfs_trace_paths_callback, &ctx);
12031 
12032 	return 0;
12033 }
12034 
12035 SYSCTL_PROC(_vfs_generic, OID_AUTO, trace_paths, CTLFLAG_RD | CTLFLAG_LOCKED | CTLFLAG_MASKED, NULL, 0, &sysctl_vfs_trace_paths, "-", "trace_paths");
12036 
12037 #if CONFIG_FILE_LEASES
12038 #include <IOKit/IOBSD.h>
12039 #include <sys/file_internal.h>
12040 
12041 #define FILE_LEASES_ENTITLEMENT    "com.apple.private.vfs.file-leases"
12042 
12043 static uint32_t lease_break_timeout = 60; /* secs */
12044 
12045 #if (DEVELOPMENT || DEBUG)
12046 static int lease_debug = 0;
12047 static int lease_entitlement_override = 0;
12048 
12049 SYSCTL_NODE(_vfs, OID_AUTO, lease, CTLFLAG_RW | CTLFLAG_LOCKED, NULL, "vfs lease");
12050 SYSCTL_UINT(_vfs_lease, OID_AUTO, break_timeout, CTLFLAG_RW | CTLFLAG_LOCKED, &lease_break_timeout, 0, "");
12051 SYSCTL_INT(_vfs_lease, OID_AUTO, debug, CTLFLAG_RW | CTLFLAG_LOCKED, &lease_debug, 0, "");
12052 SYSCTL_INT(_vfs_lease, OID_AUTO, entitlement_override, CTLFLAG_RW | CTLFLAG_LOCKED, &lease_entitlement_override, 0, "");
12053 
12054 #define LEASEDBG(fmt, args...)                                       \
12055 do {                                                                 \
12056 	if (__improbable(lease_debug)) {                                 \
12057 	        pid_t cur_pid = proc_getpid(current_proc());             \
12058 	        printf("%s(%d): " fmt "\n", __func__, cur_pid, ##args);  \
12059 	}                                                                \
12060 } while(0)
12061 #else
12062 #define LEASEDBG(fmt, args...)  /**/
12063 #endif /* (DEVELOPMENT || DEBUG) */
12064 
12065 static bool
allow_setlease(vfs_context_t ctx)12066 allow_setlease(vfs_context_t ctx)
12067 {
12068 	bool entitled;
12069 
12070 	entitled = IOTaskHasEntitlement(vfs_context_task(ctx),
12071 	    FILE_LEASES_ENTITLEMENT);
12072 
12073 #if (DEVELOPMENT || DEBUG)
12074 	if (!entitled) {
12075 		entitled = (lease_entitlement_override == 1);
12076 	}
12077 #endif
12078 
12079 	return entitled;
12080 }
12081 
12082 static file_lease_t
file_lease_alloc(struct fileglob * fg,int fl_type,pid_t pid)12083 file_lease_alloc(struct fileglob *fg, int fl_type, pid_t pid)
12084 {
12085 	file_lease_t fl;
12086 
12087 	fl = kalloc_type(struct file_lease, Z_WAITOK);
12088 	/*
12089 	 * Duplicated file descriptors created by dup() or fork() would have the
12090 	 * same 'fileglob' so the lease can be released or modified with the
12091 	 * duplicated fds. Opening the same file (by either same or different
12092 	 * process) would have different 'fileglob' so a lease always follows a
12093 	 * 'fileglob'.
12094 	 */
12095 	fl->fl_fg = fg;
12096 	fl->fl_type = fl_type;
12097 	fl->fl_pid = pid;
12098 	fl->fl_downgrade_start = fl->fl_release_start = 0;
12099 
12100 	return fl;
12101 }
12102 
12103 static void
file_lease_free(file_lease_t fl)12104 file_lease_free(file_lease_t fl)
12105 {
12106 	kfree_type(struct file_lease, fl);
12107 }
12108 
12109 /*
12110  * A read lease can be placed only on a file/directory that is opened for
12111  * read-only which means no other processes have the file/directory opened in
12112  * read-write/write-only mode or mmap'ed writable.
12113  * A write lease can be placed on a file only if there are no other opens
12114  * for the file.
12115  *
12116  * Needs to be called with vnode's lock held.
12117  */
12118 static int
check_for_open_conflict(vnode_t vp,struct fileglob * fg,int fl_type,int expcounts)12119 check_for_open_conflict(vnode_t vp, struct fileglob *fg, int fl_type,
12120     int expcounts)
12121 {
12122 	int error = 0;
12123 
12124 	if (fl_type == F_RDLCK) {
12125 		if (vp->v_writecount > expcounts &&
12126 		    !(vp->v_writecount == 1 && (fg->fg_flag & FWRITE))) {
12127 			error = EAGAIN;
12128 		} else if (ubc_is_mapped_writable(vp)) {
12129 			error = EAGAIN;
12130 		}
12131 	} else if (fl_type == F_WRLCK && vp->v_usecount > expcounts) {
12132 		error = EAGAIN;
12133 	}
12134 
12135 	return error;
12136 }
12137 
12138 /* Needs to be called with vnode's lock held. */
12139 static void
modify_file_lease(vnode_t vp,file_lease_t fl,int new_fl_type,struct fileglob * new_fg)12140 modify_file_lease(vnode_t vp, file_lease_t fl, int new_fl_type,
12141     struct fileglob *new_fg)
12142 {
12143 	LEASEDBG("fl %p changing fl_type from %d to %d (flags 0x%x)",
12144 	    fl, fl->fl_type, new_fl_type, fl->fl_flags);
12145 
12146 	fl->fl_type = new_fl_type;
12147 
12148 	/*
12149 	 * The lease being modified may be using a different file
12150 	 * descriptor, so usurp the fileglob pointer here.  In this
12151 	 * case the old descriptor no longer holds the lease.
12152 	 */
12153 	if (new_fg != NULL) {
12154 		fl->fl_fg = new_fg;
12155 	}
12156 
12157 	if (fl->fl_flags & FL_FLAG_RELEASE_PENDING ||
12158 	    fl->fl_flags & FL_FLAG_DOWNGRADE_PENDING) {
12159 		wakeup(&vp->v_leases);
12160 	}
12161 }
12162 
12163 static int
acquire_file_lease(vnode_t vp,struct fileglob * fg,int fl_type,int expcounts,vfs_context_t ctx)12164 acquire_file_lease(vnode_t vp, struct fileglob *fg, int fl_type, int expcounts,
12165     vfs_context_t ctx)
12166 {
12167 	file_lease_t fl, new_fl, our_fl;
12168 	int error;
12169 
12170 	/* Make sure "expected count" looks sane. */
12171 	if (expcounts < 0 || expcounts > OPEN_MAX) {
12172 		return EINVAL;
12173 	}
12174 
12175 	new_fl = file_lease_alloc(fg, fl_type, vfs_context_pid(ctx));
12176 
12177 	vnode_lock(vp);
12178 
12179 	error = check_for_open_conflict(vp, fg, fl_type, expcounts);
12180 	if (error) {
12181 		LEASEDBG("open conflict on vp %p type %d writecnt %d usecnt %d "
12182 		    "fl_type %d expcounts %d",
12183 		    vp, vp->v_type, vp->v_writecount, vp->v_usecount, fl_type,
12184 		    expcounts);
12185 		goto out;
12186 	}
12187 
12188 	our_fl = NULL;
12189 	LIST_FOREACH(fl, &vp->v_leases, fl_link) {
12190 		/* Does the existing lease belong to us? */
12191 		if (fl->fl_fg == new_fl->fl_fg ||
12192 		    fl->fl_pid == new_fl->fl_pid) {
12193 			our_fl = fl;
12194 			continue;
12195 		}
12196 
12197 		/*
12198 		 * We don't allow placing a new write lease when there is an existing
12199 		 * read lease that doesn't belong to us. We also don't allow putting
12200 		 * a new read lease if there is a pending release on the lease.
12201 		 * Putting a new read lease when there is a pending downgrade on the
12202 		 * lease is fine as it won't cause lease conflict.
12203 		 */
12204 		if (fl_type == F_WRLCK || fl->fl_flags & FL_FLAG_RELEASE_PENDING) {
12205 			break;
12206 		}
12207 	}
12208 
12209 	/*
12210 	 * Found an existing lease that we don't own and it conflicts with the
12211 	 * new lease.
12212 	 */
12213 	if (fl) {
12214 		LEASEDBG("lease conflict on vp %p fl %p fl_type %d cur_fl_type %d",
12215 		    vp, fl, fl_type, fl->fl_type);
12216 		goto out;
12217 	}
12218 
12219 	/* Found an existing lease that we own so just change the type. */
12220 	if (our_fl) {
12221 		LEASEDBG("replace lease on vp %p fl %p old_fl_type %d new_fl_type %d",
12222 		    vp, our_fl, our_fl->fl_type, fl_type);
12223 
12224 		modify_file_lease(vp, our_fl, new_fl->fl_type, new_fl->fl_fg);
12225 		goto out;
12226 	}
12227 
12228 	LEASEDBG("acquired lease on vp %p type %d fl %p fl_type %d fg %p",
12229 	    vp, vp->v_type, new_fl, new_fl->fl_type, new_fl->fl_fg);
12230 
12231 	LIST_INSERT_HEAD(&vp->v_leases, new_fl, fl_link);
12232 	new_fl = NULL;
12233 
12234 out:
12235 	vnode_unlock(vp);
12236 
12237 	if (new_fl) {
12238 		file_lease_free(new_fl);
12239 	}
12240 
12241 	return error;
12242 }
12243 
12244 static int
release_file_lease(vnode_t vp,struct fileglob * fg)12245 release_file_lease(vnode_t vp, struct fileglob *fg)
12246 {
12247 	file_lease_t fl, fl_tmp;
12248 	int error = 0;
12249 
12250 	LEASEDBG("request to release lease on vp %p type %d fg %p",
12251 	    vp, vp->v_type, fg);
12252 
12253 	vnode_lock(vp);
12254 
12255 	LIST_FOREACH_SAFE(fl, &vp->v_leases, fl_link, fl_tmp) {
12256 		if (fl->fl_fg == fg) {
12257 			LEASEDBG("released lease on vp %p fl %p type %d",
12258 			    vp, fl, fl->fl_type);
12259 
12260 			LIST_REMOVE(fl, fl_link);
12261 			modify_file_lease(vp, fl, F_UNLCK, NULL);
12262 			break;
12263 		}
12264 	}
12265 
12266 	vnode_unlock(vp);
12267 
12268 	if (fl) {
12269 		file_lease_free(fl);
12270 	} else {
12271 		error = ENOLCK;
12272 	}
12273 
12274 	return error;
12275 }
12276 
12277 /*
12278  * Acquire or release a file lease according to the given type (F_RDLCK,
12279  * F_WRLCK or F_UNLCK).
12280  *
12281  * Returns:	0			Success
12282  *		EAGAIN			Failed to acquire a file lease due to conflicting opens
12283  *		ENOLCK			Failed to release a file lease due to lease not found
12284  *		EPERM           Current task doesn't have the entitlement
12285  */
12286 int
vnode_setlease(vnode_t vp,struct fileglob * fg,int fl_type,int expcounts,vfs_context_t ctx)12287 vnode_setlease(vnode_t vp, struct fileglob *fg, int fl_type, int expcounts,
12288     vfs_context_t ctx)
12289 {
12290 	int error;
12291 
12292 	if (!allow_setlease(ctx)) {
12293 		return EPERM;
12294 	}
12295 
12296 	error = (fl_type == F_UNLCK) ? release_file_lease(vp, fg) :
12297 	    acquire_file_lease(vp, fg, fl_type, expcounts, ctx);
12298 
12299 	return error;
12300 }
12301 
12302 /*
12303  * Retrieve the currently in place lease for the file.
12304  *
12305  * Returns:
12306  *		F_RDLCK			Read lease
12307  *		F_WRLCK			Write lease
12308  *		F_UNLCK			No lease
12309  */
12310 int
vnode_getlease(vnode_t vp)12311 vnode_getlease(vnode_t vp)
12312 {
12313 	file_lease_t fl;
12314 	int fl_type = F_UNLCK;
12315 
12316 	vnode_lock(vp);
12317 
12318 	/*
12319 	 * There should be only one type of lease in the list as read and write
12320 	 * leases can't co-exist for the same file.
12321 	 */
12322 	fl = LIST_FIRST(&vp->v_leases);
12323 	if (fl) {
12324 		fl_type = fl->fl_type;
12325 	}
12326 
12327 	vnode_unlock(vp);
12328 
12329 	LEASEDBG("vp %p fl %p fl_type %d", vp, fl, fl_type);
12330 
12331 	return fl_type;
12332 }
12333 
12334 /* Must be called with vnode's lock held. */
12335 static bool
check_for_lease_conflict(vnode_t vp,int breaker_fl_type,vfs_context_t ctx)12336 check_for_lease_conflict(vnode_t vp, int breaker_fl_type, vfs_context_t ctx)
12337 {
12338 	file_lease_t fl;
12339 	pid_t pid = vfs_context_pid(ctx);
12340 	bool is_conflict = false;
12341 
12342 	LIST_FOREACH(fl, &vp->v_leases, fl_link) {
12343 		if ((fl->fl_type == F_WRLCK && fl->fl_pid != pid) ||
12344 		    (breaker_fl_type == F_WRLCK && fl->fl_pid != pid)) {
12345 			LEASEDBG("conflict detected on vp %p type %d fl_type %d "
12346 			    "breaker_fl_type %d",
12347 			    vp, vp->v_type, fl->fl_type, breaker_fl_type);
12348 
12349 			is_conflict = true;
12350 			break;
12351 		}
12352 	}
12353 
12354 	return is_conflict;
12355 }
12356 
12357 static uint64_t
absolutetime_elapsed_in_secs(uint64_t start)12358 absolutetime_elapsed_in_secs(uint64_t start)
12359 {
12360 	uint64_t elapsed, elapsed_sec;
12361 	uint64_t now = mach_absolute_time();
12362 
12363 	elapsed = now - start;
12364 	absolutetime_to_nanoseconds(elapsed, &elapsed_sec);
12365 	elapsed_sec /= NSEC_PER_SEC;
12366 
12367 	return elapsed_sec;
12368 }
12369 
12370 /* Must be called with vnode's lock held. */
12371 static void
handle_lease_break_timedout(vnode_t vp)12372 handle_lease_break_timedout(vnode_t vp)
12373 {
12374 	file_lease_t fl, fl_tmp;
12375 	uint64_t elapsed_sec;
12376 
12377 	LIST_FOREACH_SAFE(fl, &vp->v_leases, fl_link, fl_tmp) {
12378 		if (fl->fl_flags & FL_FLAG_DOWNGRADE_PENDING) {
12379 			elapsed_sec = absolutetime_elapsed_in_secs(fl->fl_downgrade_start);
12380 
12381 			if (elapsed_sec >= lease_break_timeout) {
12382 				LEASEDBG("force downgrade on vp %p for fl %p elapsed %llu "
12383 				    "timeout %u", vp, fl, elapsed_sec, lease_break_timeout);
12384 
12385 				fl->fl_flags &= ~FL_FLAG_DOWNGRADE_PENDING;
12386 				fl->fl_downgrade_start = 0;
12387 				modify_file_lease(vp, fl, F_RDLCK, NULL);
12388 				continue;
12389 			}
12390 		}
12391 		if (fl->fl_flags & FL_FLAG_RELEASE_PENDING) {
12392 			elapsed_sec = absolutetime_elapsed_in_secs(fl->fl_release_start);
12393 
12394 			if (elapsed_sec >= lease_break_timeout) {
12395 				LEASEDBG("force release on vp %p for fl %p elapsed %llu "
12396 				    "timeout %u", vp, fl, elapsed_sec, lease_break_timeout);
12397 
12398 				LIST_REMOVE(fl, fl_link);
12399 				file_lease_free(fl);
12400 				continue;
12401 			}
12402 		}
12403 	}
12404 
12405 	/* Wakeup the lease breaker(s). */
12406 	wakeup(&vp->v_leases);
12407 }
12408 
12409 /* Must be called with vnode's lock held. */
12410 static void
wait_for_lease_break(vnode_t vp,int breaker_fl_type,vfs_context_t ctx)12411 wait_for_lease_break(vnode_t vp, int breaker_fl_type, vfs_context_t ctx)
12412 {
12413 	file_lease_t fl;
12414 	struct timespec ts;
12415 	uint64_t elapsed_sec, start_time;
12416 	int error;
12417 
12418 restart:
12419 	fl = LIST_FIRST(&vp->v_leases);
12420 	assert(fl);
12421 
12422 	/*
12423 	 * In a rare case it is possible that the lease that we are blocked on has
12424 	 * been released and a new lease has been put in place after we are
12425 	 * signalled to wake up. In this particular, we would treat it as no
12426 	 * conflict and proceed. This could only happen for directory leasing.
12427 	 */
12428 	if ((fl->fl_flags & (FL_FLAG_DOWNGRADE_PENDING | FL_FLAG_RELEASE_PENDING)) == 0) {
12429 		LEASEDBG("new lease in place on vp %p fl %p fl_type %d "
12430 		    "breaker_fl_type %d",
12431 		    vp, fl, fl->fl_type, breaker_fl_type);
12432 
12433 		return;
12434 	}
12435 	/*
12436 	 * Figure out which timer to use for lease break timedout as we could have
12437 	 * both timers active. If both timers active, pick the one with earliest
12438 	 * start time.
12439 	 */
12440 	if (fl->fl_release_start) {
12441 		if (fl->fl_downgrade_start == 0 ||
12442 		    fl->fl_downgrade_start < fl->fl_release_start) {
12443 			start_time = fl->fl_release_start;
12444 		} else {
12445 			start_time = fl->fl_downgrade_start;
12446 		}
12447 	} else {
12448 		start_time = fl->fl_downgrade_start;
12449 	}
12450 	assert(start_time > 0);
12451 
12452 	elapsed_sec = absolutetime_elapsed_in_secs(start_time);
12453 
12454 	LEASEDBG("elapsed_sec %llu release_start %llu downgrade_start %llu",
12455 	    elapsed_sec, fl->fl_release_start, fl->fl_downgrade_start);
12456 
12457 	ts.tv_sec = (lease_break_timeout > elapsed_sec ?
12458 	    (lease_break_timeout - elapsed_sec) : 0);
12459 	ts.tv_nsec = (ts.tv_sec == 0 ? 1 : 0);
12460 	error = msleep(&vp->v_leases, &vp->v_lock, PVFS, __func__, &ts);
12461 
12462 	if (error == 0 || error != EWOULDBLOCK) {
12463 		/*
12464 		 * Woken up due to lease is released/downgraded by lease holder.
12465 		 * We don't expect any other error from msleep() beside EWOULDBLOCK.
12466 		 * Check if there is any further conflicts. If so, then continue to
12467 		 * wait for the next conflict to resolve.
12468 		 */
12469 		if (check_for_lease_conflict(vp, breaker_fl_type, ctx)) {
12470 			goto restart;
12471 		}
12472 	} else {
12473 		/*
12474 		 * Woken due to lease break timeout expired (EWOULDBLOCK returned).
12475 		 * Break/downgrade all conflicting leases.
12476 		 */
12477 		handle_lease_break_timedout(vp);
12478 
12479 		if (check_for_lease_conflict(vp, breaker_fl_type, ctx)) {
12480 			goto restart;
12481 		}
12482 	}
12483 }
12484 
12485 /* Must be called with vnode's lock held. */
12486 static void
send_lease_break_event(vnode_t vp,uint32_t event)12487 send_lease_break_event(vnode_t vp, uint32_t event)
12488 {
12489 	if (vp->v_knotes.slh_first != NULL) {
12490 		KNOTE(&vp->v_knotes, event);
12491 	}
12492 }
12493 
12494 /*
12495  * Break lease(s) in place for the file when there is conflict.
12496  * This function would return 0 for almost all call sites. The only exception
12497  * is when it is called from open1() with O_NONBLOCK flag and it needs to block
12498  * waiting for the lease conflict(s) to resolve. In this case EWOULDBLOCK is
12499  * returned.
12500  */
12501 int
vnode_breaklease(vnode_t vp,uint32_t oflags,vfs_context_t ctx)12502 vnode_breaklease(vnode_t vp, uint32_t oflags, vfs_context_t ctx)
12503 {
12504 	file_lease_t fl;
12505 	uint64_t now;
12506 	int fl_type;
12507 	int error = 0;
12508 
12509 	vnode_lock(vp);
12510 
12511 	if (__probable(LIST_EMPTY(&vp->v_leases))) {
12512 		goto out_unlock;
12513 	}
12514 
12515 	/* Determine the access mode requested by the lease breaker. */
12516 	fl_type = (oflags & (O_WRONLY | O_RDWR | O_CREAT | O_TRUNC)) ? F_WRLCK : F_RDLCK;
12517 
12518 	/*
12519 	 * If the lease-breaker is just reading, check that it can break
12520 	 * leases first.  If the lease-breaker is writing, or if the
12521 	 * context was not specified, we always break.
12522 	 */
12523 	if (fl_type == F_RDLCK && !vfs_context_can_break_leases(ctx)) {
12524 		goto out_unlock;
12525 	}
12526 
12527 	if (!check_for_lease_conflict(vp, fl_type, ctx)) {
12528 		goto out_unlock;
12529 	}
12530 
12531 	now = mach_absolute_time();
12532 
12533 	LEASEDBG("break lease on vp %p type %d oflags 0x%x cur_time %llu",
12534 	    vp, vp->v_type, oflags, now);
12535 
12536 	/*
12537 	 * We get to this point then this means all lease(s) are conflict and
12538 	 * we need to send the lease break event to the lease holder(s).
12539 	 * It is possible that a lease could have both downgrade and release events
12540 	 * pending triggered by multiple breakers trying to open the file in
12541 	 * different modes. Both events would have different lease break timers.
12542 	 * Consider the following case:
12543 	 * 1. Process A holds the write lease on file X.
12544 	 * 2. Provess B opens the file X in read-only mode.
12545 	 *    This triggers downgrade lease event to Process A.
12546 	 * 3. While downgrade is pending, Process C opens the file X in read-write
12547 	 *    mode. This triggers release lease event to Process A.
12548 	 */
12549 	LIST_FOREACH(fl, &vp->v_leases, fl_link) {
12550 		if (fl_type == F_WRLCK) {
12551 			/* File is opened for writing or truncate. */
12552 			if (fl->fl_flags & FL_FLAG_RELEASE_PENDING) {
12553 				continue;
12554 			}
12555 			fl->fl_release_start = now;
12556 			fl->fl_flags |= FL_FLAG_RELEASE_PENDING;
12557 			send_lease_break_event(vp, NOTE_LEASE_RELEASE);
12558 		} else {
12559 			/* File is opened for reading. */
12560 			if (fl->fl_flags & FL_FLAG_DOWNGRADE_PENDING ||
12561 			    fl->fl_flags & FL_FLAG_RELEASE_PENDING) {
12562 				continue;
12563 			}
12564 			fl->fl_downgrade_start = now;
12565 			fl->fl_flags |= FL_FLAG_DOWNGRADE_PENDING;
12566 			send_lease_break_event(vp, NOTE_LEASE_DOWNGRADE);
12567 		}
12568 	}
12569 
12570 	/*
12571 	 * If open is requested with O_NONBLOCK, then we can't block and wait for
12572 	 * the lease to be released/downgraded. Just bail out with EWOULDBLOCK.
12573 	 */
12574 	if (oflags & O_NONBLOCK) {
12575 		error = EWOULDBLOCK;
12576 		goto out_unlock;
12577 	}
12578 
12579 	wait_for_lease_break(vp, fl_type, ctx);
12580 
12581 	LEASEDBG("break lease on vp %p oflags 0x%x, error %d", vp, oflags, error);
12582 
12583 out_unlock:
12584 	vnode_unlock(vp);
12585 
12586 	return error;
12587 }
12588 
12589 /*
12590  * Get parent vnode by parent ID (only for file system that supports
12591  * MNTK_PATH_FROM_ID).
12592  * On success, the parent's vnode is returned with iocount held.
12593  */
12594 static vnode_t
vnode_getparent_byid(vnode_t vp)12595 vnode_getparent_byid(vnode_t vp)
12596 {
12597 	struct vnode_attr va;
12598 	vnode_t dvp = NULLVP;
12599 	vfs_context_t ctx = vfs_context_current();
12600 	int error;
12601 
12602 	if (!(vp->v_mount->mnt_kern_flag & MNTK_PATH_FROM_ID)) {
12603 		goto out;
12604 	}
12605 
12606 	VATTR_INIT(&va);
12607 	VATTR_WANTED(&va, va_parentid);
12608 
12609 	/* Get the vnode's parent id from the file system. */
12610 	error = vnode_getattr(vp, &va, ctx);
12611 	if (error || !VATTR_IS_SUPPORTED(&va, va_parentid)) {
12612 		goto out;
12613 	}
12614 
12615 	/*
12616 	 * Ask the file system for the parent vnode.
12617 	 * We are ignoring the error here as we don't expect the parent vnode to be
12618 	 * populated on error.
12619 	 */
12620 	(void)VFS_VGET(vp->v_mount, (ino64_t)va.va_parentid, &dvp, ctx);
12621 
12622 out:
12623 	return dvp;
12624 }
12625 
12626 /*
12627  * Break directory's lease.
12628  * If 'need_parent' is true, then parent is obtained via vnode_getparent() (or
12629  * vnode_getparent_byid()) on the provided 'vp'.
12630  */
12631 void
vnode_breakdirlease(vnode_t vp,bool need_parent,uint32_t oflags)12632 vnode_breakdirlease(vnode_t vp, bool need_parent, uint32_t oflags)
12633 {
12634 	vnode_t dvp;
12635 
12636 	if ((vnode_vtype(vp) != VREG && vnode_vtype(vp) != VDIR) ||
12637 	    (vp == rootvnode)) {
12638 		return;
12639 	}
12640 
12641 	/*
12642 	 * If parent is not provided, first try to get it from the name cache.
12643 	 * If failed, then we will attempt to ask the file system for parent vnode.
12644 	 * This is just a best effort as both attempts could still fail.
12645 	 */
12646 	if (need_parent) {
12647 		dvp = vnode_getparent(vp);
12648 		if (__improbable(dvp == NULLVP)) {
12649 			dvp = vnode_getparent_byid(vp);
12650 		}
12651 	} else {
12652 		dvp = vp;
12653 	}
12654 
12655 	if (__probable(dvp != NULLVP)) {
12656 		/* Always break dir leases. */
12657 		(void)vnode_breaklease(dvp, oflags, NULL);
12658 	}
12659 
12660 	if (need_parent && (dvp != NULLVP)) {
12661 		vnode_put(dvp);
12662 	}
12663 }
12664 
12665 /*
12666  * Revoke all lease(s) in place for the file.
12667  * This is called when the vnode is reclaimed.
12668  */
12669 void
vnode_revokelease(vnode_t vp,bool locked)12670 vnode_revokelease(vnode_t vp, bool locked)
12671 {
12672 	file_lease_t fl, fl_tmp;
12673 	bool need_wakeup = false;
12674 
12675 	if ((vnode_vtype(vp) != VREG && vnode_vtype(vp) != VDIR)) {
12676 		return;
12677 	}
12678 
12679 	if (!locked) {
12680 		vnode_lock(vp);
12681 	}
12682 
12683 	LIST_FOREACH_SAFE(fl, &vp->v_leases, fl_link, fl_tmp) {
12684 		LIST_REMOVE(fl, fl_link);
12685 		file_lease_free(fl);
12686 		need_wakeup = true;
12687 	}
12688 
12689 	/* Wakeup any lease breaker(s) that might be currently blocked. */
12690 	if (__improbable(need_wakeup)) {
12691 		wakeup(&vp->v_leases);
12692 	}
12693 
12694 	if (!locked) {
12695 		vnode_unlock(vp);
12696 	}
12697 }
12698 
12699 #endif /* CONFIG_FILE_LEASES */
12700