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