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