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