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