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