]> git.saurik.com Git - apple/xnu.git/blob - bsd/vfs/vfs_subr.c
be1ba3291a06ae7516bf95c53d6c888458854bc0
[apple/xnu.git] / bsd / vfs / vfs_subr.c
1 /*
2 * Copyright (c) 2000-2007 Apple Inc. All rights reserved.
3 *
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. The rights granted to you under the License
10 * may not be used to create, or enable the creation or redistribution of,
11 * unlawful or unlicensed copies of an Apple operating system, or to
12 * circumvent, violate, or enable the circumvention or violation of, any
13 * terms of an Apple operating system software license agreement.
14 *
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
17 *
18 * The Original Code and all software distributed under the License are
19 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23 * Please see the License for the specific language governing rights and
24 * limitations under the License.
25 *
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27 */
28 /* Copyright (c) 1995 NeXT Computer, Inc. All Rights Reserved */
29 /*
30 * Copyright (c) 1989, 1993
31 * The Regents of the University of California. All rights reserved.
32 * (c) UNIX System Laboratories, Inc.
33 * All or some portions of this file are derived from material licensed
34 * to the University of California by American Telephone and Telegraph
35 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
36 * the permission of UNIX System Laboratories, Inc.
37 *
38 * Redistribution and use in source and binary forms, with or without
39 * modification, are permitted provided that the following conditions
40 * are met:
41 * 1. Redistributions of source code must retain the above copyright
42 * notice, this list of conditions and the following disclaimer.
43 * 2. Redistributions in binary form must reproduce the above copyright
44 * notice, this list of conditions and the following disclaimer in the
45 * documentation and/or other materials provided with the distribution.
46 * 3. All advertising materials mentioning features or use of this software
47 * must display the following acknowledgement:
48 * This product includes software developed by the University of
49 * California, Berkeley and its contributors.
50 * 4. Neither the name of the University nor the names of its contributors
51 * may be used to endorse or promote products derived from this software
52 * without specific prior written permission.
53 *
54 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
55 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
56 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
57 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
58 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
59 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
60 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
61 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
62 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
63 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
64 * SUCH DAMAGE.
65 *
66 * @(#)vfs_subr.c 8.31 (Berkeley) 5/26/95
67 */
68 /*
69 * NOTICE: This file was modified by SPARTA, Inc. in 2005 to introduce
70 * support for mandatory and extensible security protections. This notice
71 * is included in support of clause 2.2 (b) of the Apple Public License,
72 * Version 2.0.
73 */
74
75 /*
76 * External virtual filesystem routines
77 */
78
79
80 #include <sys/param.h>
81 #include <sys/systm.h>
82 #include <sys/proc_internal.h>
83 #include <sys/kauth.h>
84 #include <sys/mount_internal.h>
85 #include <sys/time.h>
86 #include <sys/lock.h>
87 #include <sys/vnode.h>
88 #include <sys/vnode_internal.h>
89 #include <sys/stat.h>
90 #include <sys/namei.h>
91 #include <sys/ucred.h>
92 #include <sys/buf_internal.h>
93 #include <sys/errno.h>
94 #include <sys/malloc.h>
95 #include <sys/uio_internal.h>
96 #include <sys/uio.h>
97 #include <sys/domain.h>
98 #include <sys/mbuf.h>
99 #include <sys/syslog.h>
100 #include <sys/ubc_internal.h>
101 #include <sys/vm.h>
102 #include <sys/sysctl.h>
103 #include <sys/filedesc.h>
104 #include <sys/event.h>
105 #include <sys/kdebug.h>
106 #include <sys/kauth.h>
107 #include <sys/user.h>
108 #include <miscfs/fifofs/fifo.h>
109
110 #include <string.h>
111 #include <machine/spl.h>
112
113
114 #include <kern/assert.h>
115
116 #include <miscfs/specfs/specdev.h>
117
118 #include <mach/mach_types.h>
119 #include <mach/memory_object_types.h>
120
121 #include <kern/kalloc.h> /* kalloc()/kfree() */
122 #include <kern/clock.h> /* delay_for_interval() */
123 #include <libkern/OSAtomic.h> /* OSAddAtomic() */
124
125
126 #include <vm/vm_protos.h> /* vnode_pager_vrele() */
127
128 #if CONFIG_MACF
129 #include <security/mac_framework.h>
130 #endif
131
132 extern lck_grp_t *vnode_lck_grp;
133 extern lck_attr_t *vnode_lck_attr;
134
135
136 extern lck_mtx_t * mnt_list_mtx_lock;
137
138 enum vtype iftovt_tab[16] = {
139 VNON, VFIFO, VCHR, VNON, VDIR, VNON, VBLK, VNON,
140 VREG, VNON, VLNK, VNON, VSOCK, VNON, VNON, VBAD,
141 };
142 int vttoif_tab[9] = {
143 0, S_IFREG, S_IFDIR, S_IFBLK, S_IFCHR, S_IFLNK,
144 S_IFSOCK, S_IFIFO, S_IFMT,
145 };
146
147 /* XXX next protptype should be from <nfs/nfs.h> */
148 extern int nfs_vinvalbuf(vnode_t, int, vfs_context_t, int);
149
150 /* XXX next prototytype should be from libsa/stdlib.h> but conflicts libkern */
151 __private_extern__ void qsort(
152 void * array,
153 size_t nmembers,
154 size_t member_size,
155 int (*)(const void *, const void *));
156
157 extern kern_return_t adjust_vm_object_cache(vm_size_t oval, vm_size_t nval);
158 __private_extern__ void vntblinit(void);
159 __private_extern__ kern_return_t reset_vmobjectcache(unsigned int val1,
160 unsigned int val2);
161 __private_extern__ int unlink1(vfs_context_t, struct nameidata *, int);
162
163 static void vnode_list_add(vnode_t);
164 static void vnode_list_remove(vnode_t);
165
166 static errno_t vnode_drain(vnode_t);
167 static void vgone(vnode_t, int flags);
168 static void vclean(vnode_t vp, int flag);
169 static void vnode_reclaim_internal(vnode_t, int, int, int);
170
171 static void vnode_dropiocount (vnode_t);
172 static errno_t vnode_getiocount(vnode_t vp, int vid, int vflags);
173 static int vget_internal(vnode_t, int, int);
174
175 static vnode_t checkalias(vnode_t vp, dev_t nvp_rdev);
176 static int vnode_reload(vnode_t);
177 static int vnode_isinuse_locked(vnode_t, int, int);
178
179 static void insmntque(vnode_t vp, mount_t mp);
180 static int mount_getvfscnt(void);
181 static int mount_fillfsids(fsid_t *, int );
182 static void vnode_iterate_setup(mount_t);
183 static int vnode_umount_preflight(mount_t, vnode_t, int);
184 static int vnode_iterate_prepare(mount_t);
185 static int vnode_iterate_reloadq(mount_t);
186 static void vnode_iterate_clear(mount_t);
187
188 errno_t rmdir_remove_orphaned_appleDouble(vnode_t, vfs_context_t, int *);
189
190 TAILQ_HEAD(freelst, vnode) vnode_free_list; /* vnode free list */
191 TAILQ_HEAD(deadlst, vnode) vnode_dead_list; /* vnode dead list */
192
193 TAILQ_HEAD(ragelst, vnode) vnode_rage_list; /* vnode rapid age list */
194 struct timeval rage_tv;
195 int rage_limit = 0;
196 int ragevnodes = 0;
197
198 #define RAGE_LIMIT_MIN 100
199 #define RAGE_TIME_LIMIT 5
200
201 struct mntlist mountlist; /* mounted filesystem list */
202 static int nummounts = 0;
203
204 #if DIAGNOSTIC
205 #define VLISTCHECK(fun, vp, list) \
206 if ((vp)->v_freelist.tqe_prev == (struct vnode **)0xdeadb) \
207 panic("%s: %s vnode not on %slist", (fun), (list), (list));
208 #else
209 #define VLISTCHECK(fun, vp, list)
210 #endif /* DIAGNOSTIC */
211
212 #define VLISTNONE(vp) \
213 do { \
214 (vp)->v_freelist.tqe_next = (struct vnode *)0; \
215 (vp)->v_freelist.tqe_prev = (struct vnode **)0xdeadb; \
216 } while(0)
217
218 #define VONLIST(vp) \
219 ((vp)->v_freelist.tqe_prev != (struct vnode **)0xdeadb)
220
221 /* remove a vnode from free vnode list */
222 #define VREMFREE(fun, vp) \
223 do { \
224 VLISTCHECK((fun), (vp), "free"); \
225 TAILQ_REMOVE(&vnode_free_list, (vp), v_freelist); \
226 VLISTNONE((vp)); \
227 freevnodes--; \
228 } while(0)
229
230
231
232 /* remove a vnode from dead vnode list */
233 #define VREMDEAD(fun, vp) \
234 do { \
235 VLISTCHECK((fun), (vp), "dead"); \
236 TAILQ_REMOVE(&vnode_dead_list, (vp), v_freelist); \
237 VLISTNONE((vp)); \
238 vp->v_listflag &= ~VLIST_DEAD; \
239 deadvnodes--; \
240 } while(0)
241
242
243 /* remove a vnode from rage vnode list */
244 #define VREMRAGE(fun, vp) \
245 do { \
246 if ( !(vp->v_listflag & VLIST_RAGE)) \
247 panic("VREMRAGE: vp not on rage list"); \
248 VLISTCHECK((fun), (vp), "rage"); \
249 TAILQ_REMOVE(&vnode_rage_list, (vp), v_freelist); \
250 VLISTNONE((vp)); \
251 vp->v_listflag &= ~VLIST_RAGE; \
252 ragevnodes--; \
253 } while(0)
254
255
256 /*
257 * vnodetarget hasn't been used in a long time, but
258 * it was exported for some reason... I'm leaving in
259 * place for now... it should be deprecated out of the
260 * exports and removed eventually.
261 */
262 unsigned long vnodetarget; /* target for vnreclaim() */
263 #define VNODE_FREE_TARGET 20 /* Default value for vnodetarget */
264
265 /*
266 * We need quite a few vnodes on the free list to sustain the
267 * rapid stat() the compilation process does, and still benefit from the name
268 * cache. Having too few vnodes on the free list causes serious disk
269 * thrashing as we cycle through them.
270 */
271 #define VNODE_FREE_MIN CONFIG_VNODE_FREE_MIN /* freelist should have at least this many */
272
273 /*
274 * Initialize the vnode management data structures.
275 */
276 __private_extern__ void
277 vntblinit(void)
278 {
279 TAILQ_INIT(&vnode_free_list);
280 TAILQ_INIT(&vnode_rage_list);
281 TAILQ_INIT(&vnode_dead_list);
282 TAILQ_INIT(&mountlist);
283
284 if (!vnodetarget)
285 vnodetarget = VNODE_FREE_TARGET;
286
287 microuptime(&rage_tv);
288 rage_limit = desiredvnodes / 100;
289
290 if (rage_limit < RAGE_LIMIT_MIN)
291 rage_limit = RAGE_LIMIT_MIN;
292
293 /*
294 * Scale the vm_object_cache to accomodate the vnodes
295 * we want to cache
296 */
297 (void) adjust_vm_object_cache(0, desiredvnodes - VNODE_FREE_MIN);
298 }
299
300 /* Reset the VM Object Cache with the values passed in */
301 __private_extern__ kern_return_t
302 reset_vmobjectcache(unsigned int val1, unsigned int val2)
303 {
304 vm_size_t oval = val1 - VNODE_FREE_MIN;
305 vm_size_t nval;
306
307 if(val2 < VNODE_FREE_MIN)
308 nval = 0;
309 else
310 nval = val2 - VNODE_FREE_MIN;
311
312 return(adjust_vm_object_cache(oval, nval));
313 }
314
315
316 /* the timeout is in 10 msecs */
317 int
318 vnode_waitforwrites(vnode_t vp, int output_target, int slpflag, int slptimeout, const char *msg) {
319 int error = 0;
320 struct timespec ts;
321
322 KERNEL_DEBUG(0x3010280 | DBG_FUNC_START, (int)vp, output_target, vp->v_numoutput, 0, 0);
323
324 if (vp->v_numoutput > output_target) {
325
326 slpflag &= ~PDROP;
327
328 vnode_lock(vp);
329
330 while ((vp->v_numoutput > output_target) && error == 0) {
331 if (output_target)
332 vp->v_flag |= VTHROTTLED;
333 else
334 vp->v_flag |= VBWAIT;
335
336 ts.tv_sec = (slptimeout/100);
337 ts.tv_nsec = (slptimeout % 1000) * 10 * NSEC_PER_USEC * 1000 ;
338 error = msleep((caddr_t)&vp->v_numoutput, &vp->v_lock, (slpflag | (PRIBIO + 1)), msg, &ts);
339 }
340 vnode_unlock(vp);
341 }
342 KERNEL_DEBUG(0x3010280 | DBG_FUNC_END, (int)vp, output_target, vp->v_numoutput, error, 0);
343
344 return error;
345 }
346
347
348 void
349 vnode_startwrite(vnode_t vp) {
350
351 OSAddAtomic(1, &vp->v_numoutput);
352 }
353
354
355 void
356 vnode_writedone(vnode_t vp)
357 {
358 if (vp) {
359 OSAddAtomic(-1, &vp->v_numoutput);
360
361 if (vp->v_numoutput <= 1) {
362 int need_wakeup = 0;
363
364 vnode_lock_spin(vp);
365
366 if (vp->v_numoutput < 0)
367 panic("vnode_writedone: numoutput < 0");
368
369 if ((vp->v_flag & VTHROTTLED) && (vp->v_numoutput <= 1)) {
370 vp->v_flag &= ~VTHROTTLED;
371 need_wakeup = 1;
372 }
373 if ((vp->v_flag & VBWAIT) && (vp->v_numoutput == 0)) {
374 vp->v_flag &= ~VBWAIT;
375 need_wakeup = 1;
376 }
377 vnode_unlock(vp);
378
379 if (need_wakeup)
380 wakeup((caddr_t)&vp->v_numoutput);
381 }
382 }
383 }
384
385
386
387 int
388 vnode_hasdirtyblks(vnode_t vp)
389 {
390 struct cl_writebehind *wbp;
391
392 /*
393 * Not taking the buf_mtxp as there is little
394 * point doing it. Even if the lock is taken the
395 * state can change right after that. If their
396 * needs to be a synchronization, it must be driven
397 * by the caller
398 */
399 if (vp->v_dirtyblkhd.lh_first)
400 return (1);
401
402 if (!UBCINFOEXISTS(vp))
403 return (0);
404
405 wbp = vp->v_ubcinfo->cl_wbehind;
406
407 if (wbp && (wbp->cl_number || wbp->cl_scmap))
408 return (1);
409
410 return (0);
411 }
412
413 int
414 vnode_hascleanblks(vnode_t vp)
415 {
416 /*
417 * Not taking the buf_mtxp as there is little
418 * point doing it. Even if the lock is taken the
419 * state can change right after that. If their
420 * needs to be a synchronization, it must be driven
421 * by the caller
422 */
423 if (vp->v_cleanblkhd.lh_first)
424 return (1);
425 return (0);
426 }
427
428 void
429 vnode_iterate_setup(mount_t mp)
430 {
431 while (mp->mnt_lflag & MNT_LITER) {
432 mp->mnt_lflag |= MNT_LITERWAIT;
433 msleep((caddr_t)mp, &mp->mnt_mlock, PVFS, "vnode_iterate_setup", NULL);
434 }
435
436 mp->mnt_lflag |= MNT_LITER;
437
438 }
439
440 static int
441 vnode_umount_preflight(mount_t mp, vnode_t skipvp, int flags)
442 {
443 vnode_t vp;
444
445 TAILQ_FOREACH(vp, &mp->mnt_vnodelist, v_mntvnodes) {
446 /* disable preflight only for udf, a hack to be removed after 4073176 is fixed */
447 if (vp->v_tag == VT_UDF)
448 return 0;
449 if (vp->v_type == VDIR)
450 continue;
451 if (vp == skipvp)
452 continue;
453 if ((flags & SKIPSYSTEM) && ((vp->v_flag & VSYSTEM) ||
454 (vp->v_flag & VNOFLUSH)))
455 continue;
456 if ((flags & SKIPSWAP) && (vp->v_flag & VSWAP))
457 continue;
458 if ((flags & WRITECLOSE) &&
459 (vp->v_writecount == 0 || vp->v_type != VREG))
460 continue;
461 /* Look for busy vnode */
462 if (((vp->v_usecount != 0) &&
463 ((vp->v_usecount - vp->v_kusecount) != 0)))
464 return(1);
465 }
466
467 return(0);
468 }
469
470 /*
471 * This routine prepares iteration by moving all the vnodes to worker queue
472 * called with mount lock held
473 */
474 int
475 vnode_iterate_prepare(mount_t mp)
476 {
477 vnode_t vp;
478
479 if (TAILQ_EMPTY(&mp->mnt_vnodelist)) {
480 /* nothing to do */
481 return (0);
482 }
483
484 vp = TAILQ_FIRST(&mp->mnt_vnodelist);
485 vp->v_mntvnodes.tqe_prev = &(mp->mnt_workerqueue.tqh_first);
486 mp->mnt_workerqueue.tqh_first = mp->mnt_vnodelist.tqh_first;
487 mp->mnt_workerqueue.tqh_last = mp->mnt_vnodelist.tqh_last;
488
489 TAILQ_INIT(&mp->mnt_vnodelist);
490 if (mp->mnt_newvnodes.tqh_first != NULL)
491 panic("vnode_iterate_prepare: newvnode when entering vnode");
492 TAILQ_INIT(&mp->mnt_newvnodes);
493
494 return (1);
495 }
496
497
498 /* called with mount lock held */
499 int
500 vnode_iterate_reloadq(mount_t mp)
501 {
502 int moved = 0;
503
504 /* add the remaining entries in workerq to the end of mount vnode list */
505 if (!TAILQ_EMPTY(&mp->mnt_workerqueue)) {
506 struct vnode * mvp;
507 mvp = TAILQ_LAST(&mp->mnt_vnodelist, vnodelst);
508
509 /* Joining the workerque entities to mount vnode list */
510 if (mvp)
511 mvp->v_mntvnodes.tqe_next = mp->mnt_workerqueue.tqh_first;
512 else
513 mp->mnt_vnodelist.tqh_first = mp->mnt_workerqueue.tqh_first;
514 mp->mnt_workerqueue.tqh_first->v_mntvnodes.tqe_prev = mp->mnt_vnodelist.tqh_last;
515 mp->mnt_vnodelist.tqh_last = mp->mnt_workerqueue.tqh_last;
516 TAILQ_INIT(&mp->mnt_workerqueue);
517 }
518
519 /* add the newvnodes to the head of mount vnode list */
520 if (!TAILQ_EMPTY(&mp->mnt_newvnodes)) {
521 struct vnode * nlvp;
522 nlvp = TAILQ_LAST(&mp->mnt_newvnodes, vnodelst);
523
524 mp->mnt_newvnodes.tqh_first->v_mntvnodes.tqe_prev = &mp->mnt_vnodelist.tqh_first;
525 nlvp->v_mntvnodes.tqe_next = mp->mnt_vnodelist.tqh_first;
526 if(mp->mnt_vnodelist.tqh_first)
527 mp->mnt_vnodelist.tqh_first->v_mntvnodes.tqe_prev = &nlvp->v_mntvnodes.tqe_next;
528 else
529 mp->mnt_vnodelist.tqh_last = mp->mnt_newvnodes.tqh_last;
530 mp->mnt_vnodelist.tqh_first = mp->mnt_newvnodes.tqh_first;
531 TAILQ_INIT(&mp->mnt_newvnodes);
532 moved = 1;
533 }
534
535 return(moved);
536 }
537
538
539 void
540 vnode_iterate_clear(mount_t mp)
541 {
542 mp->mnt_lflag &= ~MNT_LITER;
543 if (mp->mnt_lflag & MNT_LITERWAIT) {
544 mp->mnt_lflag &= ~MNT_LITERWAIT;
545 wakeup(mp);
546 }
547 }
548
549
550 int
551 vnode_iterate(mount_t mp, int flags, int (*callout)(struct vnode *, void *),
552 void *arg)
553 {
554 struct vnode *vp;
555 int vid, retval;
556 int ret = 0;
557
558 mount_lock(mp);
559
560 vnode_iterate_setup(mp);
561
562 /* it is returns 0 then there is nothing to do */
563 retval = vnode_iterate_prepare(mp);
564
565 if (retval == 0) {
566 vnode_iterate_clear(mp);
567 mount_unlock(mp);
568 return(ret);
569 }
570
571 /* iterate over all the vnodes */
572 while (!TAILQ_EMPTY(&mp->mnt_workerqueue)) {
573 vp = TAILQ_FIRST(&mp->mnt_workerqueue);
574 TAILQ_REMOVE(&mp->mnt_workerqueue, vp, v_mntvnodes);
575 TAILQ_INSERT_TAIL(&mp->mnt_vnodelist, vp, v_mntvnodes);
576 vid = vp->v_id;
577 if ((vp->v_data == NULL) || (vp->v_type == VNON) || (vp->v_mount != mp)) {
578 continue;
579 }
580 mount_unlock(mp);
581
582 if ( vget_internal(vp, vid, (flags | VNODE_NODEAD| VNODE_WITHID | VNODE_NOSUSPEND))) {
583 mount_lock(mp);
584 continue;
585 }
586 if (flags & VNODE_RELOAD) {
587 /*
588 * we're reloading the filesystem
589 * cast out any inactive vnodes...
590 */
591 if (vnode_reload(vp)) {
592 /* vnode will be recycled on the refcount drop */
593 vnode_put(vp);
594 mount_lock(mp);
595 continue;
596 }
597 }
598
599 retval = callout(vp, arg);
600
601 switch (retval) {
602 case VNODE_RETURNED:
603 case VNODE_RETURNED_DONE:
604 vnode_put(vp);
605 if (retval == VNODE_RETURNED_DONE) {
606 mount_lock(mp);
607 ret = 0;
608 goto out;
609 }
610 break;
611
612 case VNODE_CLAIMED_DONE:
613 mount_lock(mp);
614 ret = 0;
615 goto out;
616 case VNODE_CLAIMED:
617 default:
618 break;
619 }
620 mount_lock(mp);
621 }
622
623 out:
624 (void)vnode_iterate_reloadq(mp);
625 vnode_iterate_clear(mp);
626 mount_unlock(mp);
627 return (ret);
628 }
629
630 void
631 mount_lock_renames(mount_t mp)
632 {
633 lck_mtx_lock(&mp->mnt_renamelock);
634 }
635
636 void
637 mount_unlock_renames(mount_t mp)
638 {
639 lck_mtx_unlock(&mp->mnt_renamelock);
640 }
641
642 void
643 mount_lock(mount_t mp)
644 {
645 lck_mtx_lock(&mp->mnt_mlock);
646 }
647
648 void
649 mount_unlock(mount_t mp)
650 {
651 lck_mtx_unlock(&mp->mnt_mlock);
652 }
653
654
655 void
656 mount_ref(mount_t mp, int locked)
657 {
658 if ( !locked)
659 mount_lock(mp);
660
661 mp->mnt_count++;
662
663 if ( !locked)
664 mount_unlock(mp);
665 }
666
667
668 void
669 mount_drop(mount_t mp, int locked)
670 {
671 if ( !locked)
672 mount_lock(mp);
673
674 mp->mnt_count--;
675
676 if (mp->mnt_count == 0 && (mp->mnt_lflag & MNT_LDRAIN))
677 wakeup(&mp->mnt_lflag);
678
679 if ( !locked)
680 mount_unlock(mp);
681 }
682
683
684 int
685 mount_iterref(mount_t mp, int locked)
686 {
687 int retval = 0;
688
689 if (!locked)
690 mount_list_lock();
691 if (mp->mnt_iterref < 0) {
692 retval = 1;
693 } else {
694 mp->mnt_iterref++;
695 }
696 if (!locked)
697 mount_list_unlock();
698 return(retval);
699 }
700
701 int
702 mount_isdrained(mount_t mp, int locked)
703 {
704 int retval;
705
706 if (!locked)
707 mount_list_lock();
708 if (mp->mnt_iterref < 0)
709 retval = 1;
710 else
711 retval = 0;
712 if (!locked)
713 mount_list_unlock();
714 return(retval);
715 }
716
717 void
718 mount_iterdrop(mount_t mp)
719 {
720 mount_list_lock();
721 mp->mnt_iterref--;
722 wakeup(&mp->mnt_iterref);
723 mount_list_unlock();
724 }
725
726 void
727 mount_iterdrain(mount_t mp)
728 {
729 mount_list_lock();
730 while (mp->mnt_iterref)
731 msleep((caddr_t)&mp->mnt_iterref, mnt_list_mtx_lock, PVFS, "mount_iterdrain", NULL);
732 /* mount iterations drained */
733 mp->mnt_iterref = -1;
734 mount_list_unlock();
735 }
736 void
737 mount_iterreset(mount_t mp)
738 {
739 mount_list_lock();
740 if (mp->mnt_iterref == -1)
741 mp->mnt_iterref = 0;
742 mount_list_unlock();
743 }
744
745 /* always called with mount lock held */
746 int
747 mount_refdrain(mount_t mp)
748 {
749 if (mp->mnt_lflag & MNT_LDRAIN)
750 panic("already in drain");
751 mp->mnt_lflag |= MNT_LDRAIN;
752
753 while (mp->mnt_count)
754 msleep((caddr_t)&mp->mnt_lflag, &mp->mnt_mlock, PVFS, "mount_drain", NULL);
755
756 if (mp->mnt_vnodelist.tqh_first != NULL)
757 panic("mount_refdrain: dangling vnode");
758
759 mp->mnt_lflag &= ~MNT_LDRAIN;
760
761 return(0);
762 }
763
764
765 /*
766 * Mark a mount point as busy. Used to synchronize access and to delay
767 * unmounting.
768 */
769 int
770 vfs_busy(mount_t mp, int flags)
771 {
772
773 restart:
774 if (mp->mnt_lflag & MNT_LDEAD)
775 return(ENOENT);
776
777 if (mp->mnt_lflag & MNT_LUNMOUNT) {
778 if (flags & LK_NOWAIT)
779 return (ENOENT);
780
781 mount_lock(mp);
782
783 if (mp->mnt_lflag & MNT_LDEAD) {
784 mount_unlock(mp);
785 return(ENOENT);
786 }
787 if (mp->mnt_lflag & MNT_LUNMOUNT) {
788 mp->mnt_lflag |= MNT_LWAIT;
789 /*
790 * Since all busy locks are shared except the exclusive
791 * lock granted when unmounting, the only place that a
792 * wakeup needs to be done is at the release of the
793 * exclusive lock at the end of dounmount.
794 */
795 msleep((caddr_t)mp, &mp->mnt_mlock, (PVFS | PDROP), "vfsbusy", NULL);
796 return (ENOENT);
797 }
798 mount_unlock(mp);
799 }
800
801 lck_rw_lock_shared(&mp->mnt_rwlock);
802
803 /*
804 * until we are granted the rwlock, it's possible for the mount point to
805 * change state, so reevaluate before granting the vfs_busy
806 */
807 if (mp->mnt_lflag & (MNT_LDEAD | MNT_LUNMOUNT)) {
808 lck_rw_done(&mp->mnt_rwlock);
809 goto restart;
810 }
811 return (0);
812 }
813
814 /*
815 * Free a busy filesystem.
816 */
817
818 void
819 vfs_unbusy(mount_t mp)
820 {
821 lck_rw_done(&mp->mnt_rwlock);
822 }
823
824
825
826 static void
827 vfs_rootmountfailed(mount_t mp) {
828
829 mount_list_lock();
830 mp->mnt_vtable->vfc_refcount--;
831 mount_list_unlock();
832
833 vfs_unbusy(mp);
834
835 mount_lock_destroy(mp);
836
837 #if CONFIG_MACF
838 mac_mount_label_destroy(mp);
839 #endif
840
841 FREE_ZONE(mp, sizeof(struct mount), M_MOUNT);
842 }
843
844 /*
845 * Lookup a filesystem type, and if found allocate and initialize
846 * a mount structure for it.
847 *
848 * Devname is usually updated by mount(8) after booting.
849 */
850 static mount_t
851 vfs_rootmountalloc_internal(struct vfstable *vfsp, const char *devname)
852 {
853 mount_t mp;
854
855 mp = _MALLOC_ZONE((u_long)sizeof(struct mount), M_MOUNT, M_WAITOK);
856 bzero((char *)mp, (u_long)sizeof(struct mount));
857
858 /* Initialize the default IO constraints */
859 mp->mnt_maxreadcnt = mp->mnt_maxwritecnt = MAXPHYS;
860 mp->mnt_segreadcnt = mp->mnt_segwritecnt = 32;
861 mp->mnt_maxsegreadsize = mp->mnt_maxreadcnt;
862 mp->mnt_maxsegwritesize = mp->mnt_maxwritecnt;
863 mp->mnt_devblocksize = DEV_BSIZE;
864 mp->mnt_alignmentmask = PAGE_MASK;
865 mp->mnt_ioflags = 0;
866 mp->mnt_realrootvp = NULLVP;
867 mp->mnt_authcache_ttl = CACHED_LOOKUP_RIGHT_TTL;
868
869 mount_lock_init(mp);
870 (void)vfs_busy(mp, LK_NOWAIT);
871
872 TAILQ_INIT(&mp->mnt_vnodelist);
873 TAILQ_INIT(&mp->mnt_workerqueue);
874 TAILQ_INIT(&mp->mnt_newvnodes);
875
876 mp->mnt_vtable = vfsp;
877 mp->mnt_op = vfsp->vfc_vfsops;
878 mp->mnt_flag = MNT_RDONLY | MNT_ROOTFS;
879 mp->mnt_vnodecovered = NULLVP;
880 //mp->mnt_stat.f_type = vfsp->vfc_typenum;
881 mp->mnt_flag |= vfsp->vfc_flags & MNT_VISFLAGMASK;
882
883 mount_list_lock();
884 vfsp->vfc_refcount++;
885 mount_list_unlock();
886
887 strncpy(mp->mnt_vfsstat.f_fstypename, vfsp->vfc_name, MFSTYPENAMELEN);
888 mp->mnt_vfsstat.f_mntonname[0] = '/';
889 /* XXX const poisoning layering violation */
890 (void) copystr((const void *)devname, mp->mnt_vfsstat.f_mntfromname, MAXPATHLEN - 1, NULL);
891
892 #if CONFIG_MACF
893 mac_mount_label_init(mp);
894 mac_mount_label_associate(vfs_context_kernel(), mp);
895 #endif
896 return (mp);
897 }
898
899 errno_t
900 vfs_rootmountalloc(const char *fstypename, const char *devname, mount_t *mpp)
901 {
902 struct vfstable *vfsp;
903
904 for (vfsp = vfsconf; vfsp; vfsp = vfsp->vfc_next)
905 if (!strncmp(vfsp->vfc_name, fstypename,
906 sizeof(vfsp->vfc_name)))
907 break;
908 if (vfsp == NULL)
909 return (ENODEV);
910
911 *mpp = vfs_rootmountalloc_internal(vfsp, devname);
912
913 if (*mpp)
914 return (0);
915
916 return (ENOMEM);
917 }
918
919
920 /*
921 * Find an appropriate filesystem to use for the root. If a filesystem
922 * has not been preselected, walk through the list of known filesystems
923 * trying those that have mountroot routines, and try them until one
924 * works or we have tried them all.
925 */
926 extern int (*mountroot)(void);
927
928 int
929 vfs_mountroot(void)
930 {
931 #if CONFIG_MACF
932 struct vnode *vp;
933 #endif
934 struct vfstable *vfsp;
935 vfs_context_t ctx = vfs_context_kernel();
936 struct vfs_attr vfsattr;
937 int error;
938 mount_t mp;
939 vnode_t bdevvp_rootvp;
940
941 if (mountroot != NULL) {
942 /*
943 * used for netboot which follows a different set of rules
944 */
945 error = (*mountroot)();
946 return (error);
947 }
948 if ((error = bdevvp(rootdev, &rootvp))) {
949 printf("vfs_mountroot: can't setup bdevvp\n");
950 return (error);
951 }
952 /*
953 * 4951998 - code we call in vfc_mountroot may replace rootvp
954 * so keep a local copy for some house keeping.
955 */
956 bdevvp_rootvp = rootvp;
957
958 for (vfsp = vfsconf; vfsp; vfsp = vfsp->vfc_next) {
959 if (vfsp->vfc_mountroot == NULL)
960 continue;
961
962 mp = vfs_rootmountalloc_internal(vfsp, "root_device");
963 mp->mnt_devvp = rootvp;
964
965 if ((error = (*vfsp->vfc_mountroot)(mp, rootvp, ctx)) == 0) {
966 if ( bdevvp_rootvp != rootvp ) {
967 /*
968 * rootvp changed...
969 * bump the iocount and fix up mnt_devvp for the
970 * new rootvp (it will already have a usecount taken)...
971 * drop the iocount and the usecount on the orignal
972 * since we are no longer going to use it...
973 */
974 vnode_getwithref(rootvp);
975 mp->mnt_devvp = rootvp;
976
977 vnode_rele(bdevvp_rootvp);
978 vnode_put(bdevvp_rootvp);
979 }
980 mp->mnt_devvp->v_specflags |= SI_MOUNTEDON;
981
982 vfs_unbusy(mp);
983
984 mount_list_add(mp);
985
986 /*
987 * cache the IO attributes for the underlying physical media...
988 * an error return indicates the underlying driver doesn't
989 * support all the queries necessary... however, reasonable
990 * defaults will have been set, so no reason to bail or care
991 */
992 vfs_init_io_attributes(rootvp, mp);
993
994 /*
995 * Shadow the VFC_VFSNATIVEXATTR flag to MNTK_EXTENDED_ATTRS.
996 */
997 if (mp->mnt_vtable->vfc_vfsflags & VFC_VFSNATIVEXATTR) {
998 mp->mnt_kern_flag |= MNTK_EXTENDED_ATTRS;
999 }
1000 if (mp->mnt_vtable->vfc_vfsflags & VFC_VFSPREFLIGHT) {
1001 mp->mnt_kern_flag |= MNTK_UNMOUNT_PREFLIGHT;
1002 }
1003
1004 /*
1005 * Probe root file system for additional features.
1006 */
1007 (void)VFS_START(mp, 0, ctx);
1008
1009 VFSATTR_INIT(&vfsattr);
1010 VFSATTR_WANTED(&vfsattr, f_capabilities);
1011 if (vfs_getattr(mp, &vfsattr, ctx) == 0 &&
1012 VFSATTR_IS_SUPPORTED(&vfsattr, f_capabilities)) {
1013 if ((vfsattr.f_capabilities.capabilities[VOL_CAPABILITIES_INTERFACES] & VOL_CAP_INT_EXTENDED_ATTR) &&
1014 (vfsattr.f_capabilities.valid[VOL_CAPABILITIES_INTERFACES] & VOL_CAP_INT_EXTENDED_ATTR)) {
1015 mp->mnt_kern_flag |= MNTK_EXTENDED_ATTRS;
1016 }
1017 #if NAMEDSTREAMS
1018 if ((vfsattr.f_capabilities.capabilities[VOL_CAPABILITIES_INTERFACES] & VOL_CAP_INT_NAMEDSTREAMS) &&
1019 (vfsattr.f_capabilities.valid[VOL_CAPABILITIES_INTERFACES] & VOL_CAP_INT_NAMEDSTREAMS)) {
1020 mp->mnt_kern_flag |= MNTK_NAMED_STREAMS;
1021 }
1022 #endif
1023 if ((vfsattr.f_capabilities.capabilities[VOL_CAPABILITIES_FORMAT] & VOL_CAP_FMT_PATH_FROM_ID) &&
1024 (vfsattr.f_capabilities.valid[VOL_CAPABILITIES_FORMAT] & VOL_CAP_FMT_PATH_FROM_ID)) {
1025 mp->mnt_kern_flag |= MNTK_PATH_FROM_ID;
1026 }
1027 }
1028
1029 /*
1030 * get rid of iocount reference returned
1031 * by bdevvp (or picked up by us on the substitued
1032 * rootvp)... it (or we) will have also taken
1033 * a usecount reference which we want to keep
1034 */
1035 vnode_put(rootvp);
1036
1037 #if CONFIG_MACF
1038 if ((vfs_flags(mp) & MNT_MULTILABEL) == 0)
1039 return (0);
1040
1041 error = VFS_ROOT(mp, &vp, ctx);
1042 if (error) {
1043 printf("%s() VFS_ROOT() returned %d\n",
1044 __func__, error);
1045 dounmount(mp, MNT_FORCE, 0, ctx);
1046 goto fail;
1047 }
1048
1049 /* VFS_ROOT provides reference so flags = 0 */
1050 error = vnode_label(mp, NULL, vp, NULL, 0, ctx);
1051 if (error) {
1052 printf("%s() vnode_label() returned %d\n",
1053 __func__, error);
1054 dounmount(mp, MNT_FORCE, 0, ctx);
1055 goto fail;
1056 }
1057 #endif
1058 return (0);
1059 }
1060 #if CONFIG_MACF
1061 fail:
1062 #endif
1063 vfs_rootmountfailed(mp);
1064
1065 if (error != EINVAL)
1066 printf("%s_mountroot failed: %d\n", vfsp->vfc_name, error);
1067 }
1068 return (ENODEV);
1069 }
1070
1071 /*
1072 * Lookup a mount point by filesystem identifier.
1073 */
1074 extern mount_t vfs_getvfs_locked(fsid_t *);
1075
1076 struct mount *
1077 vfs_getvfs(fsid_t *fsid)
1078 {
1079 return (mount_list_lookupby_fsid(fsid, 0, 0));
1080 }
1081
1082 struct mount *
1083 vfs_getvfs_locked(fsid_t *fsid)
1084 {
1085 return(mount_list_lookupby_fsid(fsid, 1, 0));
1086 }
1087
1088 struct mount *
1089 vfs_getvfs_by_mntonname(char *path)
1090 {
1091 mount_t retmp = (mount_t)0;
1092 mount_t mp;
1093
1094 mount_list_lock();
1095 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
1096 if (!strncmp(mp->mnt_vfsstat.f_mntonname, path,
1097 sizeof(mp->mnt_vfsstat.f_mntonname))) {
1098 retmp = mp;
1099 goto out;
1100 }
1101 }
1102 out:
1103 mount_list_unlock();
1104 return (retmp);
1105 }
1106
1107 /* generation number for creation of new fsids */
1108 u_short mntid_gen = 0;
1109 /*
1110 * Get a new unique fsid
1111 */
1112 void
1113 vfs_getnewfsid(struct mount *mp)
1114 {
1115
1116 fsid_t tfsid;
1117 int mtype;
1118 mount_t nmp;
1119
1120 mount_list_lock();
1121
1122 /* generate a new fsid */
1123 mtype = mp->mnt_vtable->vfc_typenum;
1124 if (++mntid_gen == 0)
1125 mntid_gen++;
1126 tfsid.val[0] = makedev(nblkdev + mtype, mntid_gen);
1127 tfsid.val[1] = mtype;
1128
1129 TAILQ_FOREACH(nmp, &mountlist, mnt_list) {
1130 while (vfs_getvfs_locked(&tfsid)) {
1131 if (++mntid_gen == 0)
1132 mntid_gen++;
1133 tfsid.val[0] = makedev(nblkdev + mtype, mntid_gen);
1134 }
1135 }
1136 mp->mnt_vfsstat.f_fsid.val[0] = tfsid.val[0];
1137 mp->mnt_vfsstat.f_fsid.val[1] = tfsid.val[1];
1138 mount_list_unlock();
1139 }
1140
1141 /*
1142 * Routines having to do with the management of the vnode table.
1143 */
1144 extern int (**dead_vnodeop_p)(void *);
1145 long numvnodes, freevnodes, deadvnodes;
1146
1147
1148 /*
1149 * Move a vnode from one mount queue to another.
1150 */
1151 static void
1152 insmntque(vnode_t vp, mount_t mp)
1153 {
1154 mount_t lmp;
1155 /*
1156 * Delete from old mount point vnode list, if on one.
1157 */
1158 if ( (lmp = vp->v_mount) != NULL && lmp != dead_mountp) {
1159 if ((vp->v_lflag & VNAMED_MOUNT) == 0)
1160 panic("insmntque: vp not in mount vnode list");
1161 vp->v_lflag &= ~VNAMED_MOUNT;
1162
1163 mount_lock(lmp);
1164
1165 mount_drop(lmp, 1);
1166
1167 if (vp->v_mntvnodes.tqe_next == NULL) {
1168 if (TAILQ_LAST(&lmp->mnt_vnodelist, vnodelst) == vp)
1169 TAILQ_REMOVE(&lmp->mnt_vnodelist, vp, v_mntvnodes);
1170 else if (TAILQ_LAST(&lmp->mnt_newvnodes, vnodelst) == vp)
1171 TAILQ_REMOVE(&lmp->mnt_newvnodes, vp, v_mntvnodes);
1172 else if (TAILQ_LAST(&lmp->mnt_workerqueue, vnodelst) == vp)
1173 TAILQ_REMOVE(&lmp->mnt_workerqueue, vp, v_mntvnodes);
1174 } else {
1175 vp->v_mntvnodes.tqe_next->v_mntvnodes.tqe_prev = vp->v_mntvnodes.tqe_prev;
1176 *vp->v_mntvnodes.tqe_prev = vp->v_mntvnodes.tqe_next;
1177 }
1178 vp->v_mntvnodes.tqe_next = NULL;
1179 vp->v_mntvnodes.tqe_prev = NULL;
1180 mount_unlock(lmp);
1181 return;
1182 }
1183
1184 /*
1185 * Insert into list of vnodes for the new mount point, if available.
1186 */
1187 if ((vp->v_mount = mp) != NULL) {
1188 mount_lock(mp);
1189 if ((vp->v_mntvnodes.tqe_next != 0) && (vp->v_mntvnodes.tqe_prev != 0))
1190 panic("vp already in mount list");
1191 if (mp->mnt_lflag & MNT_LITER)
1192 TAILQ_INSERT_HEAD(&mp->mnt_newvnodes, vp, v_mntvnodes);
1193 else
1194 TAILQ_INSERT_HEAD(&mp->mnt_vnodelist, vp, v_mntvnodes);
1195 if (vp->v_lflag & VNAMED_MOUNT)
1196 panic("insmntque: vp already in mount vnode list");
1197 if ((vp->v_freelist.tqe_prev != (struct vnode **)0xdeadb))
1198 panic("insmntque: vp on the free list\n");
1199 vp->v_lflag |= VNAMED_MOUNT;
1200 mount_ref(mp, 1);
1201 mount_unlock(mp);
1202 }
1203 }
1204
1205
1206 /*
1207 * Create a vnode for a block device.
1208 * Used for root filesystem, argdev, and swap areas.
1209 * Also used for memory file system special devices.
1210 */
1211 int
1212 bdevvp(dev_t dev, vnode_t *vpp)
1213 {
1214 vnode_t nvp;
1215 int error;
1216 struct vnode_fsparam vfsp;
1217 struct vfs_context context;
1218
1219 if (dev == NODEV) {
1220 *vpp = NULLVP;
1221 return (ENODEV);
1222 }
1223
1224 context.vc_thread = current_thread();
1225 context.vc_ucred = FSCRED;
1226
1227 vfsp.vnfs_mp = (struct mount *)0;
1228 vfsp.vnfs_vtype = VBLK;
1229 vfsp.vnfs_str = "bdevvp";
1230 vfsp.vnfs_dvp = NULL;
1231 vfsp.vnfs_fsnode = NULL;
1232 vfsp.vnfs_cnp = NULL;
1233 vfsp.vnfs_vops = spec_vnodeop_p;
1234 vfsp.vnfs_rdev = dev;
1235 vfsp.vnfs_filesize = 0;
1236
1237 vfsp.vnfs_flags = VNFS_NOCACHE | VNFS_CANTCACHE;
1238
1239 vfsp.vnfs_marksystem = 0;
1240 vfsp.vnfs_markroot = 0;
1241
1242 if ( (error = vnode_create(VNCREATE_FLAVOR, VCREATESIZE, &vfsp, &nvp)) ) {
1243 *vpp = NULLVP;
1244 return (error);
1245 }
1246 vnode_lock_spin(nvp);
1247 nvp->v_flag |= VBDEVVP;
1248 nvp->v_tag = VT_NON; /* set this to VT_NON so during aliasing it can be replaced */
1249 vnode_unlock(nvp);
1250 if ( (error = vnode_ref(nvp)) ) {
1251 panic("bdevvp failed: vnode_ref");
1252 return (error);
1253 }
1254 if ( (error = VNOP_FSYNC(nvp, MNT_WAIT, &context)) ) {
1255 panic("bdevvp failed: fsync");
1256 return (error);
1257 }
1258 if ( (error = buf_invalidateblks(nvp, BUF_WRITE_DATA, 0, 0)) ) {
1259 panic("bdevvp failed: invalidateblks");
1260 return (error);
1261 }
1262
1263 #if CONFIG_MACF
1264 /*
1265 * XXXMAC: We can't put a MAC check here, the system will
1266 * panic without this vnode.
1267 */
1268 #endif /* MAC */
1269
1270 if ( (error = VNOP_OPEN(nvp, FREAD, &context)) ) {
1271 panic("bdevvp failed: open");
1272 return (error);
1273 }
1274 *vpp = nvp;
1275
1276 return (0);
1277 }
1278
1279 /*
1280 * Check to see if the new vnode represents a special device
1281 * for which we already have a vnode (either because of
1282 * bdevvp() or because of a different vnode representing
1283 * the same block device). If such an alias exists, deallocate
1284 * the existing contents and return the aliased vnode. The
1285 * caller is responsible for filling it with its new contents.
1286 */
1287 static vnode_t
1288 checkalias(struct vnode *nvp, dev_t nvp_rdev)
1289 {
1290 struct vnode *vp;
1291 struct vnode **vpp;
1292 int vid = 0;
1293
1294 vpp = &speclisth[SPECHASH(nvp_rdev)];
1295 loop:
1296 SPECHASH_LOCK();
1297
1298 for (vp = *vpp; vp; vp = vp->v_specnext) {
1299 if (nvp_rdev == vp->v_rdev && nvp->v_type == vp->v_type) {
1300 vid = vp->v_id;
1301 break;
1302 }
1303 }
1304 SPECHASH_UNLOCK();
1305
1306 if (vp) {
1307 if (vnode_getwithvid(vp,vid)) {
1308 goto loop;
1309 }
1310 /*
1311 * Termination state is checked in vnode_getwithvid
1312 */
1313 vnode_lock(vp);
1314
1315 /*
1316 * Alias, but not in use, so flush it out.
1317 */
1318 if ((vp->v_iocount == 1) && (vp->v_usecount == 0)) {
1319 vnode_reclaim_internal(vp, 1, 0, 0);
1320 vnode_unlock(vp);
1321 vnode_put(vp);
1322 goto loop;
1323 }
1324 }
1325 if (vp == NULL || vp->v_tag != VT_NON) {
1326 retnullvp:
1327 MALLOC_ZONE(nvp->v_specinfo, struct specinfo *, sizeof(struct specinfo),
1328 M_SPECINFO, M_WAITOK);
1329 bzero(nvp->v_specinfo, sizeof(struct specinfo));
1330 nvp->v_rdev = nvp_rdev;
1331 nvp->v_specflags = 0;
1332 nvp->v_speclastr = -1;
1333
1334 SPECHASH_LOCK();
1335 nvp->v_hashchain = vpp;
1336 nvp->v_specnext = *vpp;
1337 *vpp = nvp;
1338 SPECHASH_UNLOCK();
1339
1340 if (vp != NULLVP) {
1341 nvp->v_flag |= VALIASED;
1342 vp->v_flag |= VALIASED;
1343 vnode_unlock(vp);
1344 vnode_put(vp);
1345 }
1346 return (NULLVP);
1347 }
1348 if ((vp->v_flag & (VBDEVVP | VDEVFLUSH)) != 0)
1349 return(vp);
1350 else {
1351 panic("checkalias with VT_NON vp that shouldn't: %x", (unsigned int)vp);
1352 goto retnullvp;
1353 }
1354 return (vp);
1355 }
1356
1357
1358 /*
1359 * Get a reference on a particular vnode and lock it if requested.
1360 * If the vnode was on the inactive list, remove it from the list.
1361 * If the vnode was on the free list, remove it from the list and
1362 * move it to inactive list as needed.
1363 * The vnode lock bit is set if the vnode is being eliminated in
1364 * vgone. The process is awakened when the transition is completed,
1365 * and an error returned to indicate that the vnode is no longer
1366 * usable (possibly having been changed to a new file system type).
1367 */
1368 static int
1369 vget_internal(vnode_t vp, int vid, int vflags)
1370 {
1371 int error = 0;
1372 int vpid;
1373
1374 vnode_lock_spin(vp);
1375
1376 if (vflags & VNODE_WITHID)
1377 vpid = vid;
1378 else
1379 vpid = vp->v_id; // save off the original v_id
1380
1381 if ((vflags & VNODE_WRITEABLE) && (vp->v_writecount == 0))
1382 /*
1383 * vnode to be returned only if it has writers opened
1384 */
1385 error = EINVAL;
1386 else
1387 error = vnode_getiocount(vp, vpid, vflags);
1388
1389 vnode_unlock(vp);
1390
1391 return (error);
1392 }
1393
1394 /*
1395 * Returns: 0 Success
1396 * ENOENT No such file or directory [terminating]
1397 */
1398 int
1399 vnode_ref(vnode_t vp)
1400 {
1401
1402 return (vnode_ref_ext(vp, 0));
1403 }
1404
1405 /*
1406 * Returns: 0 Success
1407 * ENOENT No such file or directory [terminating]
1408 */
1409 int
1410 vnode_ref_ext(vnode_t vp, int fmode)
1411 {
1412 int error = 0;
1413
1414 vnode_lock_spin(vp);
1415
1416 /*
1417 * once all the current call sites have been fixed to insure they have
1418 * taken an iocount, we can toughen this assert up and insist that the
1419 * iocount is non-zero... a non-zero usecount doesn't insure correctness
1420 */
1421 if (vp->v_iocount <= 0 && vp->v_usecount <= 0)
1422 panic("vnode_ref_ext: vp %p has no valid reference %d, %d", vp, vp->v_iocount, vp->v_usecount);
1423
1424 /*
1425 * if you are the owner of drain/termination, can acquire usecount
1426 */
1427 if ((vp->v_lflag & (VL_DRAIN | VL_TERMINATE | VL_DEAD))) {
1428 if (vp->v_owner != current_thread()) {
1429 error = ENOENT;
1430 goto out;
1431 }
1432 }
1433 vp->v_usecount++;
1434
1435 if (fmode & FWRITE) {
1436 if (++vp->v_writecount <= 0)
1437 panic("vnode_ref_ext: v_writecount");
1438 }
1439 if (fmode & O_EVTONLY) {
1440 if (++vp->v_kusecount <= 0)
1441 panic("vnode_ref_ext: v_kusecount");
1442 }
1443 if (vp->v_flag & VRAGE) {
1444 struct uthread *ut;
1445
1446 ut = get_bsdthread_info(current_thread());
1447
1448 if ( !(current_proc()->p_lflag & P_LRAGE_VNODES) &&
1449 !(ut->uu_flag & UT_RAGE_VNODES)) {
1450 /*
1451 * a 'normal' process accessed this vnode
1452 * so make sure its no longer marked
1453 * for rapid aging... also, make sure
1454 * it gets removed from the rage list...
1455 * when v_usecount drops back to 0, it
1456 * will be put back on the real free list
1457 */
1458 vp->v_flag &= ~VRAGE;
1459 vp->v_references = 0;
1460 vnode_list_remove(vp);
1461 }
1462 }
1463 out:
1464 vnode_unlock(vp);
1465
1466 return (error);
1467 }
1468
1469
1470 /*
1471 * put the vnode on appropriate free list.
1472 * called with vnode LOCKED
1473 */
1474 static void
1475 vnode_list_add(vnode_t vp)
1476 {
1477 /*
1478 * if it is already on a list or non zero references return
1479 */
1480 if (VONLIST(vp) || (vp->v_usecount != 0) || (vp->v_iocount != 0))
1481 return;
1482 vnode_list_lock();
1483
1484 if ((vp->v_flag & VRAGE) && !(vp->v_lflag & VL_DEAD)) {
1485 /*
1486 * add the new guy to the appropriate end of the RAGE list
1487 */
1488 if ((vp->v_flag & VAGE))
1489 TAILQ_INSERT_HEAD(&vnode_rage_list, vp, v_freelist);
1490 else
1491 TAILQ_INSERT_TAIL(&vnode_rage_list, vp, v_freelist);
1492
1493 vp->v_listflag |= VLIST_RAGE;
1494 ragevnodes++;
1495
1496 /*
1497 * reset the timestamp for the last inserted vp on the RAGE
1498 * queue to let new_vnode know that its not ok to start stealing
1499 * from this list... as long as we're actively adding to this list
1500 * we'll push out the vnodes we want to donate to the real free list
1501 * once we stop pushing, we'll let some time elapse before we start
1502 * stealing them in the new_vnode routine
1503 */
1504 microuptime(&rage_tv);
1505 } else {
1506 /*
1507 * if VL_DEAD, insert it at head of the dead list
1508 * else insert at tail of LRU list or at head if VAGE is set
1509 */
1510 if ( (vp->v_lflag & VL_DEAD)) {
1511 TAILQ_INSERT_HEAD(&vnode_dead_list, vp, v_freelist);
1512 vp->v_listflag |= VLIST_DEAD;
1513 deadvnodes++;
1514 } else if ((vp->v_flag & VAGE)) {
1515 TAILQ_INSERT_HEAD(&vnode_free_list, vp, v_freelist);
1516 vp->v_flag &= ~VAGE;
1517 freevnodes++;
1518 } else {
1519 TAILQ_INSERT_TAIL(&vnode_free_list, vp, v_freelist);
1520 freevnodes++;
1521 }
1522 }
1523 vnode_list_unlock();
1524 }
1525
1526 /*
1527 * remove the vnode from appropriate free list.
1528 */
1529 static void
1530 vnode_list_remove(vnode_t vp)
1531 {
1532 /*
1533 * we want to avoid taking the list lock
1534 * in the case where we're not on the free
1535 * list... this will be true for most
1536 * directories and any currently in use files
1537 *
1538 * we're guaranteed that we can't go from
1539 * the not-on-list state to the on-list
1540 * state since we hold the vnode lock...
1541 * all calls to vnode_list_add are done
1542 * under the vnode lock... so we can
1543 * check for that condition (the prevelant one)
1544 * without taking the list lock
1545 */
1546 if (VONLIST(vp)) {
1547 vnode_list_lock();
1548 /*
1549 * however, we're not guaranteed that
1550 * we won't go from the on-list state
1551 * to the non-on-list state until we
1552 * hold the vnode_list_lock... this
1553 * is due to new_vnode removing vnodes
1554 * from the free list uder the list_lock
1555 * w/o the vnode lock... so we need to
1556 * check again whether we're currently
1557 * on the free list
1558 */
1559 if (VONLIST(vp)) {
1560 if (vp->v_listflag & VLIST_RAGE)
1561 VREMRAGE("vnode_list_remove", vp);
1562 else if (vp->v_listflag & VLIST_DEAD)
1563 VREMDEAD("vnode_list_remove", vp);
1564 else
1565 VREMFREE("vnode_list_remove", vp);
1566
1567 VLISTNONE(vp);
1568 }
1569 vnode_list_unlock();
1570 }
1571 }
1572
1573
1574 void
1575 vnode_rele(vnode_t vp)
1576 {
1577 vnode_rele_internal(vp, 0, 0, 0);
1578 }
1579
1580
1581 void
1582 vnode_rele_ext(vnode_t vp, int fmode, int dont_reenter)
1583 {
1584 vnode_rele_internal(vp, fmode, dont_reenter, 0);
1585 }
1586
1587
1588 void
1589 vnode_rele_internal(vnode_t vp, int fmode, int dont_reenter, int locked)
1590 {
1591 if ( !locked)
1592 vnode_lock_spin(vp);
1593
1594 if (--vp->v_usecount < 0)
1595 panic("vnode_rele_ext: vp %p usecount -ve : %d", vp, vp->v_usecount);
1596
1597 if (fmode & FWRITE) {
1598 if (--vp->v_writecount < 0)
1599 panic("vnode_rele_ext: vp %p writecount -ve : %ld", vp, vp->v_writecount);
1600 }
1601 if (fmode & O_EVTONLY) {
1602 if (--vp->v_kusecount < 0)
1603 panic("vnode_rele_ext: vp %p kusecount -ve : %d", vp, vp->v_kusecount);
1604 }
1605 if (vp->v_kusecount > vp->v_usecount)
1606 panic("vnode_rele_ext: vp %p kusecount(%d) out of balance with usecount(%d)\n",vp, vp->v_kusecount, vp->v_usecount);
1607 if ((vp->v_iocount > 0) || (vp->v_usecount > 0)) {
1608 /*
1609 * vnode is still busy... if we're the last
1610 * usecount, mark for a future call to VNOP_INACTIVE
1611 * when the iocount finally drops to 0
1612 */
1613 if (vp->v_usecount == 0) {
1614 vp->v_lflag |= VL_NEEDINACTIVE;
1615 vp->v_flag &= ~(VNOCACHE_DATA | VRAOFF | VOPENEVT);
1616 }
1617 if ( !locked)
1618 vnode_unlock(vp);
1619 return;
1620 }
1621 vp->v_flag &= ~(VNOCACHE_DATA | VRAOFF | VOPENEVT);
1622
1623 if ( (vp->v_lflag & (VL_TERMINATE | VL_DEAD)) || dont_reenter) {
1624 /*
1625 * vnode is being cleaned, or
1626 * we've requested that we don't reenter
1627 * the filesystem on this release... in
1628 * this case, we'll mark the vnode aged
1629 * if it's been marked for termination
1630 */
1631 if (dont_reenter) {
1632 if ( !(vp->v_lflag & (VL_TERMINATE | VL_DEAD | VL_MARKTERM)) )
1633 vp->v_lflag |= VL_NEEDINACTIVE;
1634 vp->v_flag |= VAGE;
1635 }
1636 vnode_list_add(vp);
1637 if ( !locked)
1638 vnode_unlock(vp);
1639 return;
1640 }
1641 /*
1642 * at this point both the iocount and usecount
1643 * are zero
1644 * pick up an iocount so that we can call
1645 * VNOP_INACTIVE with the vnode lock unheld
1646 */
1647 vp->v_iocount++;
1648 #ifdef JOE_DEBUG
1649 record_vp(vp, 1);
1650 #endif
1651 vp->v_lflag &= ~VL_NEEDINACTIVE;
1652 vnode_unlock(vp);
1653
1654 VNOP_INACTIVE(vp, vfs_context_current());
1655
1656 vnode_lock_spin(vp);
1657 /*
1658 * because we dropped the vnode lock to call VNOP_INACTIVE
1659 * the state of the vnode may have changed... we may have
1660 * picked up an iocount, usecount or the MARKTERM may have
1661 * been set... we need to reevaluate the reference counts
1662 * to determine if we can call vnode_reclaim_internal at
1663 * this point... if the reference counts are up, we'll pick
1664 * up the MARKTERM state when they get subsequently dropped
1665 */
1666 if ( (vp->v_iocount == 1) && (vp->v_usecount == 0) &&
1667 ((vp->v_lflag & (VL_MARKTERM | VL_TERMINATE | VL_DEAD)) == VL_MARKTERM)) {
1668 struct uthread *ut;
1669
1670 ut = get_bsdthread_info(current_thread());
1671
1672 if (ut->uu_defer_reclaims) {
1673 vp->v_defer_reclaimlist = ut->uu_vreclaims;
1674 ut->uu_vreclaims = vp;
1675 goto defer_reclaim;
1676 }
1677 vnode_lock_convert(vp);
1678 vnode_reclaim_internal(vp, 1, 0, 0);
1679 }
1680 vnode_dropiocount(vp);
1681 vnode_list_add(vp);
1682 defer_reclaim:
1683 if ( !locked)
1684 vnode_unlock(vp);
1685 return;
1686 }
1687
1688 /*
1689 * Remove any vnodes in the vnode table belonging to mount point mp.
1690 *
1691 * If MNT_NOFORCE is specified, there should not be any active ones,
1692 * return error if any are found (nb: this is a user error, not a
1693 * system error). If MNT_FORCE is specified, detach any active vnodes
1694 * that are found.
1695 */
1696 #if DIAGNOSTIC
1697 int busyprt = 0; /* print out busy vnodes */
1698 #if 0
1699 struct ctldebug debug1 = { "busyprt", &busyprt };
1700 #endif /* 0 */
1701 #endif
1702
1703 int
1704 vflush(struct mount *mp, struct vnode *skipvp, int flags)
1705 {
1706 struct vnode *vp;
1707 int busy = 0;
1708 int reclaimed = 0;
1709 int retval;
1710 int vid;
1711
1712 mount_lock(mp);
1713 vnode_iterate_setup(mp);
1714 /*
1715 * On regular unmounts(not forced) do a
1716 * quick check for vnodes to be in use. This
1717 * preserves the caching of vnodes. automounter
1718 * tries unmounting every so often to see whether
1719 * it is still busy or not.
1720 */
1721 if (((flags & FORCECLOSE)==0) && ((mp->mnt_kern_flag & MNTK_UNMOUNT_PREFLIGHT) != 0)) {
1722 if (vnode_umount_preflight(mp, skipvp, flags)) {
1723 vnode_iterate_clear(mp);
1724 mount_unlock(mp);
1725 return(EBUSY);
1726 }
1727 }
1728 loop:
1729 /* it is returns 0 then there is nothing to do */
1730 retval = vnode_iterate_prepare(mp);
1731
1732 if (retval == 0) {
1733 vnode_iterate_clear(mp);
1734 mount_unlock(mp);
1735 return(retval);
1736 }
1737
1738 /* iterate over all the vnodes */
1739 while (!TAILQ_EMPTY(&mp->mnt_workerqueue)) {
1740 vp = TAILQ_FIRST(&mp->mnt_workerqueue);
1741 TAILQ_REMOVE(&mp->mnt_workerqueue, vp, v_mntvnodes);
1742 TAILQ_INSERT_TAIL(&mp->mnt_vnodelist, vp, v_mntvnodes);
1743 if ( (vp->v_mount != mp) || (vp == skipvp)) {
1744 continue;
1745 }
1746 vid = vp->v_id;
1747 mount_unlock(mp);
1748 vnode_lock(vp);
1749
1750 if ((vp->v_id != vid) || ((vp->v_lflag & (VL_DEAD | VL_TERMINATE)))) {
1751 vnode_unlock(vp);
1752 mount_lock(mp);
1753 continue;
1754 }
1755
1756 /*
1757 * If requested, skip over vnodes marked VSYSTEM.
1758 * Skip over all vnodes marked VNOFLUSH.
1759 */
1760 if ((flags & SKIPSYSTEM) && ((vp->v_flag & VSYSTEM) ||
1761 (vp->v_flag & VNOFLUSH))) {
1762 vnode_unlock(vp);
1763 mount_lock(mp);
1764 continue;
1765 }
1766 /*
1767 * If requested, skip over vnodes marked VSWAP.
1768 */
1769 if ((flags & SKIPSWAP) && (vp->v_flag & VSWAP)) {
1770 vnode_unlock(vp);
1771 mount_lock(mp);
1772 continue;
1773 }
1774 /*
1775 * If requested, skip over vnodes marked VSWAP.
1776 */
1777 if ((flags & SKIPROOT) && (vp->v_flag & VROOT)) {
1778 vnode_unlock(vp);
1779 mount_lock(mp);
1780 continue;
1781 }
1782 /*
1783 * If WRITECLOSE is set, only flush out regular file
1784 * vnodes open for writing.
1785 */
1786 if ((flags & WRITECLOSE) &&
1787 (vp->v_writecount == 0 || vp->v_type != VREG)) {
1788 vnode_unlock(vp);
1789 mount_lock(mp);
1790 continue;
1791 }
1792 /*
1793 * If the real usecount is 0, all we need to do is clear
1794 * out the vnode data structures and we are done.
1795 */
1796 if (((vp->v_usecount == 0) ||
1797 ((vp->v_usecount - vp->v_kusecount) == 0))) {
1798 vp->v_iocount++; /* so that drain waits for * other iocounts */
1799 #ifdef JOE_DEBUG
1800 record_vp(vp, 1);
1801 #endif
1802 vnode_reclaim_internal(vp, 1, 0, 0);
1803 vnode_dropiocount(vp);
1804 vnode_list_add(vp);
1805
1806 vnode_unlock(vp);
1807 reclaimed++;
1808 mount_lock(mp);
1809 continue;
1810 }
1811 /*
1812 * If FORCECLOSE is set, forcibly close the vnode.
1813 * For block or character devices, revert to an
1814 * anonymous device. For all other files, just kill them.
1815 */
1816 if (flags & FORCECLOSE) {
1817 if (vp->v_type != VBLK && vp->v_type != VCHR) {
1818 vp->v_iocount++; /* so that drain waits * for other iocounts */
1819 #ifdef JOE_DEBUG
1820 record_vp(vp, 1);
1821 #endif
1822 vnode_reclaim_internal(vp, 1, 0, 0);
1823 vnode_dropiocount(vp);
1824 vnode_list_add(vp);
1825 vnode_unlock(vp);
1826 } else {
1827 vclean(vp, 0);
1828 vp->v_lflag &= ~VL_DEAD;
1829 vp->v_op = spec_vnodeop_p;
1830 vp->v_flag |= VDEVFLUSH;
1831 vnode_unlock(vp);
1832 }
1833 mount_lock(mp);
1834 continue;
1835 }
1836 #if DIAGNOSTIC
1837 if (busyprt)
1838 vprint("vflush: busy vnode", vp);
1839 #endif
1840 vnode_unlock(vp);
1841 mount_lock(mp);
1842 busy++;
1843 }
1844
1845 /* At this point the worker queue is completed */
1846 if (busy && ((flags & FORCECLOSE)==0) && reclaimed) {
1847 busy = 0;
1848 reclaimed = 0;
1849 (void)vnode_iterate_reloadq(mp);
1850 /* returned with mount lock held */
1851 goto loop;
1852 }
1853
1854 /* if new vnodes were created in between retry the reclaim */
1855 if ( vnode_iterate_reloadq(mp) != 0) {
1856 if (!(busy && ((flags & FORCECLOSE)==0)))
1857 goto loop;
1858 }
1859 vnode_iterate_clear(mp);
1860 mount_unlock(mp);
1861
1862 if (busy && ((flags & FORCECLOSE)==0))
1863 return (EBUSY);
1864 return (0);
1865 }
1866
1867 long num_recycledvnodes = 0; /* long for OSAddAtomic */
1868 /*
1869 * Disassociate the underlying file system from a vnode.
1870 * The vnode lock is held on entry.
1871 */
1872 static void
1873 vclean(vnode_t vp, int flags)
1874 {
1875 vfs_context_t ctx = vfs_context_current();
1876 int active;
1877 int need_inactive;
1878 int already_terminating;
1879 int clflags = 0;
1880
1881 /*
1882 * Check to see if the vnode is in use.
1883 * If so we have to reference it before we clean it out
1884 * so that its count cannot fall to zero and generate a
1885 * race against ourselves to recycle it.
1886 */
1887 active = vp->v_usecount;
1888
1889 /*
1890 * just in case we missed sending a needed
1891 * VNOP_INACTIVE, we'll do it now
1892 */
1893 need_inactive = (vp->v_lflag & VL_NEEDINACTIVE);
1894
1895 vp->v_lflag &= ~VL_NEEDINACTIVE;
1896
1897 /*
1898 * Prevent the vnode from being recycled or
1899 * brought into use while we clean it out.
1900 */
1901 already_terminating = (vp->v_lflag & VL_TERMINATE);
1902
1903 vp->v_lflag |= VL_TERMINATE;
1904
1905 /*
1906 * remove the vnode from any mount list
1907 * it might be on...
1908 */
1909 insmntque(vp, (struct mount *)0);
1910
1911 vnode_unlock(vp);
1912
1913 OSAddAtomic(1, &num_recycledvnodes);
1914 /*
1915 * purge from the name cache as early as possible...
1916 */
1917 cache_purge(vp);
1918
1919 if (flags & DOCLOSE)
1920 clflags |= IO_NDELAY;
1921 if (flags & REVOKEALL)
1922 clflags |= IO_REVOKE;
1923
1924 if (active && (flags & DOCLOSE))
1925 VNOP_CLOSE(vp, clflags, ctx);
1926
1927 /*
1928 * Clean out any buffers associated with the vnode.
1929 */
1930 if (flags & DOCLOSE) {
1931 #if NFSCLIENT
1932 if (vp->v_tag == VT_NFS)
1933 nfs_vinvalbuf(vp, V_SAVE, ctx, 0);
1934 else
1935 #endif
1936 {
1937 VNOP_FSYNC(vp, MNT_WAIT, ctx);
1938 buf_invalidateblks(vp, BUF_WRITE_DATA, 0, 0);
1939 }
1940 if (UBCINFOEXISTS(vp))
1941 /*
1942 * Clean the pages in VM.
1943 */
1944 (void)ubc_sync_range(vp, (off_t)0, ubc_getsize(vp), UBC_PUSHALL);
1945 }
1946 if (active || need_inactive)
1947 VNOP_INACTIVE(vp, ctx);
1948
1949 /*
1950 * Destroy ubc named reference
1951 * cluster_release is done on this path
1952 * along with dropping the reference on the ucred
1953 */
1954 ubc_destroy_named(vp);
1955
1956 /*
1957 * Reclaim the vnode.
1958 */
1959 if (VNOP_RECLAIM(vp, ctx))
1960 panic("vclean: cannot reclaim");
1961
1962 // make sure the name & parent ptrs get cleaned out!
1963 vnode_update_identity(vp, NULLVP, NULL, 0, 0, VNODE_UPDATE_PARENT | VNODE_UPDATE_NAME);
1964
1965 vnode_lock(vp);
1966
1967 vp->v_mount = dead_mountp;
1968 vp->v_op = dead_vnodeop_p;
1969 vp->v_tag = VT_NON;
1970 vp->v_data = NULL;
1971
1972 vp->v_lflag |= VL_DEAD;
1973
1974 if (already_terminating == 0) {
1975 vp->v_lflag &= ~VL_TERMINATE;
1976 /*
1977 * Done with purge, notify sleepers of the grim news.
1978 */
1979 if (vp->v_lflag & VL_TERMWANT) {
1980 vp->v_lflag &= ~VL_TERMWANT;
1981 wakeup(&vp->v_lflag);
1982 }
1983 }
1984 }
1985
1986 /*
1987 * Eliminate all activity associated with the requested vnode
1988 * and with all vnodes aliased to the requested vnode.
1989 */
1990 int
1991 #if DIAGNOSTIC
1992 vn_revoke(vnode_t vp, int flags, __unused vfs_context_t a_context)
1993 #else
1994 vn_revoke(vnode_t vp, __unused int flags, __unused vfs_context_t a_context)
1995 #endif
1996 {
1997 struct vnode *vq;
1998 int vid;
1999
2000 #if DIAGNOSTIC
2001 if ((flags & REVOKEALL) == 0)
2002 panic("vnop_revoke");
2003 #endif
2004
2005 if (vp->v_flag & VALIASED) {
2006 /*
2007 * If a vgone (or vclean) is already in progress,
2008 * wait until it is done and return.
2009 */
2010 vnode_lock(vp);
2011 if (vp->v_lflag & VL_TERMINATE) {
2012 vnode_unlock(vp);
2013 return(ENOENT);
2014 }
2015 vnode_unlock(vp);
2016 /*
2017 * Ensure that vp will not be vgone'd while we
2018 * are eliminating its aliases.
2019 */
2020 SPECHASH_LOCK();
2021 while (vp->v_flag & VALIASED) {
2022 for (vq = *vp->v_hashchain; vq; vq = vq->v_specnext) {
2023 if (vq->v_rdev != vp->v_rdev ||
2024 vq->v_type != vp->v_type || vp == vq)
2025 continue;
2026 vid = vq->v_id;
2027 SPECHASH_UNLOCK();
2028 if (vnode_getwithvid(vq,vid)){
2029 SPECHASH_LOCK();
2030 break;
2031 }
2032 vnode_reclaim_internal(vq, 0, 0, 0);
2033 vnode_put(vq);
2034 SPECHASH_LOCK();
2035 break;
2036 }
2037 }
2038 SPECHASH_UNLOCK();
2039 }
2040 vnode_reclaim_internal(vp, 0, 0, REVOKEALL);
2041
2042 return (0);
2043 }
2044
2045 /*
2046 * Recycle an unused vnode to the front of the free list.
2047 * Release the passed interlock if the vnode will be recycled.
2048 */
2049 int
2050 vnode_recycle(struct vnode *vp)
2051 {
2052 vnode_lock(vp);
2053
2054 if (vp->v_iocount || vp->v_usecount) {
2055 vp->v_lflag |= VL_MARKTERM;
2056 vnode_unlock(vp);
2057 return(0);
2058 }
2059 vnode_reclaim_internal(vp, 1, 0, 0);
2060 vnode_unlock(vp);
2061
2062 return (1);
2063 }
2064
2065 static int
2066 vnode_reload(vnode_t vp)
2067 {
2068 vnode_lock_spin(vp);
2069
2070 if ((vp->v_iocount > 1) || vp->v_usecount) {
2071 vnode_unlock(vp);
2072 return(0);
2073 }
2074 if (vp->v_iocount <= 0)
2075 panic("vnode_reload with no iocount %d", vp->v_iocount);
2076
2077 /* mark for release when iocount is dopped */
2078 vp->v_lflag |= VL_MARKTERM;
2079 vnode_unlock(vp);
2080
2081 return (1);
2082 }
2083
2084
2085 static void
2086 vgone(vnode_t vp, int flags)
2087 {
2088 struct vnode *vq;
2089 struct vnode *vx;
2090
2091 /*
2092 * Clean out the filesystem specific data.
2093 * vclean also takes care of removing the
2094 * vnode from any mount list it might be on
2095 */
2096 vclean(vp, flags | DOCLOSE);
2097
2098 /*
2099 * If special device, remove it from special device alias list
2100 * if it is on one.
2101 */
2102 if ((vp->v_type == VBLK || vp->v_type == VCHR) && vp->v_specinfo != 0) {
2103 SPECHASH_LOCK();
2104 if (*vp->v_hashchain == vp) {
2105 *vp->v_hashchain = vp->v_specnext;
2106 } else {
2107 for (vq = *vp->v_hashchain; vq; vq = vq->v_specnext) {
2108 if (vq->v_specnext != vp)
2109 continue;
2110 vq->v_specnext = vp->v_specnext;
2111 break;
2112 }
2113 if (vq == NULL)
2114 panic("missing bdev");
2115 }
2116 if (vp->v_flag & VALIASED) {
2117 vx = NULL;
2118 for (vq = *vp->v_hashchain; vq; vq = vq->v_specnext) {
2119 if (vq->v_rdev != vp->v_rdev ||
2120 vq->v_type != vp->v_type)
2121 continue;
2122 if (vx)
2123 break;
2124 vx = vq;
2125 }
2126 if (vx == NULL)
2127 panic("missing alias");
2128 if (vq == NULL)
2129 vx->v_flag &= ~VALIASED;
2130 vp->v_flag &= ~VALIASED;
2131 }
2132 SPECHASH_UNLOCK();
2133 {
2134 struct specinfo *tmp = vp->v_specinfo;
2135 vp->v_specinfo = NULL;
2136 FREE_ZONE((void *)tmp, sizeof(struct specinfo), M_SPECINFO);
2137 }
2138 }
2139 }
2140
2141 /*
2142 * Lookup a vnode by device number.
2143 */
2144 int
2145 check_mountedon(dev_t dev, enum vtype type, int *errorp)
2146 {
2147 vnode_t vp;
2148 int rc = 0;
2149 int vid;
2150
2151 loop:
2152 SPECHASH_LOCK();
2153 for (vp = speclisth[SPECHASH(dev)]; vp; vp = vp->v_specnext) {
2154 if (dev != vp->v_rdev || type != vp->v_type)
2155 continue;
2156 vid = vp->v_id;
2157 SPECHASH_UNLOCK();
2158 if (vnode_getwithvid(vp,vid))
2159 goto loop;
2160 vnode_lock_spin(vp);
2161 if ((vp->v_usecount > 0) || (vp->v_iocount > 1)) {
2162 vnode_unlock(vp);
2163 if ((*errorp = vfs_mountedon(vp)) != 0)
2164 rc = 1;
2165 } else
2166 vnode_unlock(vp);
2167 vnode_put(vp);
2168 return(rc);
2169 }
2170 SPECHASH_UNLOCK();
2171 return (0);
2172 }
2173
2174 /*
2175 * Calculate the total number of references to a special device.
2176 */
2177 int
2178 vcount(vnode_t vp)
2179 {
2180 vnode_t vq, vnext;
2181 int count;
2182 int vid;
2183
2184 loop:
2185 if ((vp->v_flag & VALIASED) == 0)
2186 return (vp->v_usecount - vp->v_kusecount);
2187 count = 0;
2188
2189 SPECHASH_LOCK();
2190 /*
2191 * Grab first vnode and its vid.
2192 */
2193 vq = *vp->v_hashchain;
2194 vid = vq ? vq->v_id : 0;
2195
2196 SPECHASH_UNLOCK();
2197
2198 while (vq) {
2199 /*
2200 * Attempt to get the vnode outside the SPECHASH lock.
2201 */
2202 if (vnode_getwithvid(vq, vid)) {
2203 goto loop;
2204 }
2205 vnode_lock(vq);
2206
2207 if (vq->v_rdev == vp->v_rdev && vq->v_type == vp->v_type) {
2208 if ((vq->v_usecount == 0) && (vq->v_iocount == 1) && vq != vp) {
2209 /*
2210 * Alias, but not in use, so flush it out.
2211 */
2212 vnode_reclaim_internal(vq, 1, 0, 0);
2213 vnode_unlock(vq);
2214 vnode_put(vq);
2215 goto loop;
2216 }
2217 count += (vq->v_usecount - vq->v_kusecount);
2218 }
2219 vnode_unlock(vq);
2220
2221 SPECHASH_LOCK();
2222 /*
2223 * must do this with the reference still held on 'vq'
2224 * so that it can't be destroyed while we're poking
2225 * through v_specnext
2226 */
2227 vnext = vq->v_specnext;
2228 vid = vnext ? vnext->v_id : 0;
2229
2230 SPECHASH_UNLOCK();
2231
2232 vnode_put(vq);
2233
2234 vq = vnext;
2235 }
2236
2237 return (count);
2238 }
2239
2240 int prtactive = 0; /* 1 => print out reclaim of active vnodes */
2241
2242 /*
2243 * Print out a description of a vnode.
2244 */
2245 #if !CONFIG_NO_PRINTF_STRINGS
2246 static const char *typename[] =
2247 { "VNON", "VREG", "VDIR", "VBLK", "VCHR", "VLNK", "VSOCK", "VFIFO", "VBAD" };
2248 #endif
2249
2250 void
2251 vprint(const char *label, struct vnode *vp)
2252 {
2253 char sbuf[64];
2254
2255 if (label != NULL)
2256 printf("%s: ", label);
2257 printf("type %s, usecount %d, writecount %ld",
2258 typename[vp->v_type], vp->v_usecount, vp->v_writecount);
2259 sbuf[0] = '\0';
2260 if (vp->v_flag & VROOT)
2261 strlcat(sbuf, "|VROOT", sizeof(sbuf));
2262 if (vp->v_flag & VTEXT)
2263 strlcat(sbuf, "|VTEXT", sizeof(sbuf));
2264 if (vp->v_flag & VSYSTEM)
2265 strlcat(sbuf, "|VSYSTEM", sizeof(sbuf));
2266 if (vp->v_flag & VNOFLUSH)
2267 strlcat(sbuf, "|VNOFLUSH", sizeof(sbuf));
2268 if (vp->v_flag & VBWAIT)
2269 strlcat(sbuf, "|VBWAIT", sizeof(sbuf));
2270 if (vp->v_flag & VALIASED)
2271 strlcat(sbuf, "|VALIASED", sizeof(sbuf));
2272 if (sbuf[0] != '\0')
2273 printf(" flags (%s)", &sbuf[1]);
2274 }
2275
2276
2277 int
2278 vn_getpath(struct vnode *vp, char *pathbuf, int *len)
2279 {
2280 return build_path(vp, pathbuf, *len, len, BUILDPATH_NO_FS_ENTER, vfs_context_current());
2281 }
2282
2283
2284 int
2285 vn_getcdhash(struct vnode *vp, off_t offset, unsigned char *cdhash)
2286 {
2287 return ubc_cs_getcdhash(vp, offset, cdhash);
2288 }
2289
2290
2291 static char *extension_table=NULL;
2292 static int nexts;
2293 static int max_ext_width;
2294
2295 static int
2296 extension_cmp(const void *a, const void *b)
2297 {
2298 return (strlen((const char *)a) - strlen((const char *)b));
2299 }
2300
2301
2302 //
2303 // This is the api LaunchServices uses to inform the kernel
2304 // the list of package extensions to ignore.
2305 //
2306 // Internally we keep the list sorted by the length of the
2307 // the extension (from longest to shortest). We sort the
2308 // list of extensions so that we can speed up our searches
2309 // when comparing file names -- we only compare extensions
2310 // that could possibly fit into the file name, not all of
2311 // them (i.e. a short 8 character name can't have an 8
2312 // character extension).
2313 //
2314 __private_extern__ int
2315 set_package_extensions_table(void *data, int nentries, int maxwidth)
2316 {
2317 char *new_exts;
2318 int error;
2319
2320 if (nentries <= 0 || nentries > 1024 || maxwidth <= 0 || maxwidth > 255) {
2321 return EINVAL;
2322 }
2323
2324 MALLOC(new_exts, char *, nentries * maxwidth, M_TEMP, M_WAITOK);
2325
2326 error = copyin(CAST_USER_ADDR_T(data), new_exts, nentries * maxwidth);
2327 if (error) {
2328 FREE(new_exts, M_TEMP);
2329 return error;
2330 }
2331
2332 if (extension_table) {
2333 FREE(extension_table, M_TEMP);
2334 }
2335 extension_table = new_exts;
2336 nexts = nentries;
2337 max_ext_width = maxwidth;
2338
2339 qsort(extension_table, nexts, maxwidth, extension_cmp);
2340
2341 return 0;
2342 }
2343
2344
2345 __private_extern__ int
2346 is_package_name(const char *name, int len)
2347 {
2348 int i, extlen;
2349 const char *ptr, *name_ext;
2350
2351 if (len <= 3) {
2352 return 0;
2353 }
2354
2355 name_ext = NULL;
2356 for(ptr=name; *ptr != '\0'; ptr++) {
2357 if (*ptr == '.') {
2358 name_ext = ptr;
2359 }
2360 }
2361
2362 // if there is no "." extension, it can't match
2363 if (name_ext == NULL) {
2364 return 0;
2365 }
2366
2367 // advance over the "."
2368 name_ext++;
2369
2370 // now iterate over all the extensions to see if any match
2371 ptr = &extension_table[0];
2372 for(i=0; i < nexts; i++, ptr+=max_ext_width) {
2373 extlen = strlen(ptr);
2374 if (strncasecmp(name_ext, ptr, extlen) == 0 && name_ext[extlen] == '\0') {
2375 // aha, a match!
2376 return 1;
2377 }
2378 }
2379
2380 // if we get here, no extension matched
2381 return 0;
2382 }
2383
2384 int
2385 vn_path_package_check(__unused vnode_t vp, char *path, int pathlen, int *component)
2386 {
2387 char *ptr, *end;
2388 int comp=0;
2389
2390 *component = -1;
2391 if (*path != '/') {
2392 return EINVAL;
2393 }
2394
2395 end = path + 1;
2396 while(end < path + pathlen && *end != '\0') {
2397 while(end < path + pathlen && *end == '/' && *end != '\0') {
2398 end++;
2399 }
2400
2401 ptr = end;
2402
2403 while(end < path + pathlen && *end != '/' && *end != '\0') {
2404 end++;
2405 }
2406
2407 if (end > path + pathlen) {
2408 // hmm, string wasn't null terminated
2409 return EINVAL;
2410 }
2411
2412 *end = '\0';
2413 if (is_package_name(ptr, end - ptr)) {
2414 *component = comp;
2415 break;
2416 }
2417
2418 end++;
2419 comp++;
2420 }
2421
2422 return 0;
2423 }
2424
2425
2426 /*
2427 * Top level filesystem related information gathering.
2428 */
2429 extern unsigned int vfs_nummntops;
2430
2431 int
2432 vfs_sysctl(int *name, u_int namelen, user_addr_t oldp, size_t *oldlenp,
2433 user_addr_t newp, size_t newlen, proc_t p)
2434 {
2435 struct vfstable *vfsp;
2436 int *username;
2437 u_int usernamelen;
2438 int error;
2439 struct vfsconf *vfsc;
2440
2441 /* All non VFS_GENERIC and in VFS_GENERIC,
2442 * VFS_MAXTYPENUM, VFS_CONF, VFS_SET_PACKAGE_EXTS
2443 * needs to have root priv to have modifiers.
2444 * For rest the userland_sysctl(CTLFLAG_ANYBODY) would cover.
2445 */
2446 if ((newp != USER_ADDR_NULL) && ((name[0] != VFS_GENERIC) ||
2447 ((name[1] == VFS_MAXTYPENUM) ||
2448 (name[1] == VFS_CONF) ||
2449 (name[1] == VFS_SET_PACKAGE_EXTS)))
2450 && (error = suser(kauth_cred_get(), &p->p_acflag))) {
2451 return(error);
2452 }
2453 /*
2454 * The VFS_NUMMNTOPS shouldn't be at name[0] since
2455 * is a VFS generic variable. So now we must check
2456 * namelen so we don't end up covering any UFS
2457 * variables (sinc UFS vfc_typenum is 1).
2458 *
2459 * It should have been:
2460 * name[0]: VFS_GENERIC
2461 * name[1]: VFS_NUMMNTOPS
2462 */
2463 if (namelen == 1 && name[0] == VFS_NUMMNTOPS) {
2464 return (sysctl_rdint(oldp, oldlenp, newp, vfs_nummntops));
2465 }
2466
2467 /* all sysctl names at this level are at least name and field */
2468 if (namelen < 2)
2469 return (EISDIR); /* overloaded */
2470 if (name[0] != VFS_GENERIC) {
2471 for (vfsp = vfsconf; vfsp; vfsp = vfsp->vfc_next)
2472 if (vfsp->vfc_typenum == name[0])
2473 break;
2474 if (vfsp == NULL)
2475 return (ENOTSUP);
2476
2477 /* XXX current context proxy for proc p? */
2478 return ((*vfsp->vfc_vfsops->vfs_sysctl)(&name[1], namelen - 1,
2479 oldp, oldlenp, newp, newlen,
2480 vfs_context_current()));
2481 }
2482 switch (name[1]) {
2483 case VFS_MAXTYPENUM:
2484 return (sysctl_rdint(oldp, oldlenp, newp, maxvfsconf));
2485 case VFS_CONF:
2486 if (namelen < 3)
2487 return (ENOTDIR); /* overloaded */
2488 for (vfsp = vfsconf; vfsp; vfsp = vfsp->vfc_next)
2489 if (vfsp->vfc_typenum == name[2])
2490 break;
2491 if (vfsp == NULL)
2492 return (ENOTSUP);
2493 vfsc = (struct vfsconf *)vfsp;
2494 if (proc_is64bit(p)) {
2495 struct user_vfsconf usr_vfsc;
2496 usr_vfsc.vfc_vfsops = CAST_USER_ADDR_T(vfsc->vfc_vfsops);
2497 bcopy(vfsc->vfc_name, usr_vfsc.vfc_name, sizeof(usr_vfsc.vfc_name));
2498 usr_vfsc.vfc_typenum = vfsc->vfc_typenum;
2499 usr_vfsc.vfc_refcount = vfsc->vfc_refcount;
2500 usr_vfsc.vfc_flags = vfsc->vfc_flags;
2501 usr_vfsc.vfc_mountroot = CAST_USER_ADDR_T(vfsc->vfc_mountroot);
2502 usr_vfsc.vfc_next = CAST_USER_ADDR_T(vfsc->vfc_next);
2503 return (sysctl_rdstruct(oldp, oldlenp, newp, &usr_vfsc,
2504 sizeof(usr_vfsc)));
2505 }
2506 else {
2507 return (sysctl_rdstruct(oldp, oldlenp, newp, vfsc,
2508 sizeof(struct vfsconf)));
2509 }
2510
2511 case VFS_SET_PACKAGE_EXTS:
2512 return set_package_extensions_table((void *)name[1], name[2], name[3]);
2513 }
2514 /*
2515 * We need to get back into the general MIB, so we need to re-prepend
2516 * CTL_VFS to our name and try userland_sysctl().
2517 */
2518 usernamelen = namelen + 1;
2519 MALLOC(username, int *, usernamelen * sizeof(*username),
2520 M_TEMP, M_WAITOK);
2521 bcopy(name, username + 1, namelen * sizeof(*name));
2522 username[0] = CTL_VFS;
2523 error = userland_sysctl(p, username, usernamelen, oldp,
2524 oldlenp, 1, newp, newlen, oldlenp);
2525 FREE(username, M_TEMP);
2526 return (error);
2527 }
2528
2529 /*
2530 * Dump vnode list (via sysctl) - defunct
2531 * use "pstat" instead
2532 */
2533 /* ARGSUSED */
2534 int
2535 sysctl_vnode
2536 (__unused struct sysctl_oid *oidp, __unused void *arg1, __unused int arg2, __unused struct sysctl_req *req)
2537 {
2538 return(EINVAL);
2539 }
2540
2541 SYSCTL_PROC(_kern, KERN_VNODE, vnode,
2542 CTLTYPE_STRUCT | CTLFLAG_RD | CTLFLAG_MASKED,
2543 0, 0, sysctl_vnode, "S,", "");
2544
2545
2546 /*
2547 * Check to see if a filesystem is mounted on a block device.
2548 */
2549 int
2550 vfs_mountedon(struct vnode *vp)
2551 {
2552 struct vnode *vq;
2553 int error = 0;
2554
2555 SPECHASH_LOCK();
2556 if (vp->v_specflags & SI_MOUNTEDON) {
2557 error = EBUSY;
2558 goto out;
2559 }
2560 if (vp->v_flag & VALIASED) {
2561 for (vq = *vp->v_hashchain; vq; vq = vq->v_specnext) {
2562 if (vq->v_rdev != vp->v_rdev ||
2563 vq->v_type != vp->v_type)
2564 continue;
2565 if (vq->v_specflags & SI_MOUNTEDON) {
2566 error = EBUSY;
2567 break;
2568 }
2569 }
2570 }
2571 out:
2572 SPECHASH_UNLOCK();
2573 return (error);
2574 }
2575
2576 /*
2577 * Unmount all filesystems. The list is traversed in reverse order
2578 * of mounting to avoid dependencies.
2579 */
2580 __private_extern__ void
2581 vfs_unmountall(void)
2582 {
2583 struct mount *mp;
2584 int error;
2585
2586 /*
2587 * Since this only runs when rebooting, it is not interlocked.
2588 */
2589 mount_list_lock();
2590 while(!TAILQ_EMPTY(&mountlist)) {
2591 mp = TAILQ_LAST(&mountlist, mntlist);
2592 mount_list_unlock();
2593 error = dounmount(mp, MNT_FORCE, 0, vfs_context_current());
2594 if ((error != 0) && (error != EBUSY)) {
2595 printf("unmount of %s failed (", mp->mnt_vfsstat.f_mntonname);
2596 printf("%d)\n", error);
2597 mount_list_lock();
2598 TAILQ_REMOVE(&mountlist, mp, mnt_list);
2599 continue;
2600 } else if (error == EBUSY) {
2601 /* If EBUSY is returned, the unmount was already in progress */
2602 printf("unmount of %x failed (", (unsigned int)mp);
2603 printf("BUSY)\n");
2604 }
2605 mount_list_lock();
2606 }
2607 mount_list_unlock();
2608 }
2609
2610
2611 /*
2612 * This routine is called from vnode_pager_deallocate out of the VM
2613 * The path to vnode_pager_deallocate can only be initiated by ubc_destroy_named
2614 * on a vnode that has a UBCINFO
2615 */
2616 __private_extern__ void
2617 vnode_pager_vrele(vnode_t vp)
2618 {
2619 struct ubc_info *uip;
2620
2621 vnode_lock(vp);
2622
2623 vp->v_lflag &= ~VNAMED_UBC;
2624
2625 uip = vp->v_ubcinfo;
2626 vp->v_ubcinfo = UBC_INFO_NULL;
2627
2628 ubc_info_deallocate(uip);
2629
2630 vnode_unlock(vp);
2631 }
2632
2633
2634 #include <sys/disk.h>
2635
2636 errno_t
2637 vfs_init_io_attributes(vnode_t devvp, mount_t mp)
2638 {
2639 int error;
2640 off_t readblockcnt;
2641 off_t writeblockcnt;
2642 off_t readmaxcnt;
2643 off_t writemaxcnt;
2644 off_t readsegcnt;
2645 off_t writesegcnt;
2646 off_t readsegsize;
2647 off_t writesegsize;
2648 off_t alignment;
2649 u_long blksize;
2650 u_int64_t temp;
2651 u_int32_t features;
2652 vfs_context_t ctx = vfs_context_current();
2653
2654 int isvirtual = 0;
2655 /*
2656 * determine if this mount point exists on the same device as the root
2657 * partition... if so, then it comes under the hard throttle control
2658 */
2659 int thisunit = -1;
2660 static int rootunit = -1;
2661
2662 if (rootunit == -1) {
2663 if (VNOP_IOCTL(rootvp, DKIOCGETBSDUNIT, (caddr_t)&rootunit, 0, ctx))
2664 rootunit = -1;
2665 else if (rootvp == devvp)
2666 mp->mnt_kern_flag |= MNTK_ROOTDEV;
2667 }
2668 if (devvp != rootvp && rootunit != -1) {
2669 if (VNOP_IOCTL(devvp, DKIOCGETBSDUNIT, (caddr_t)&thisunit, 0, ctx) == 0) {
2670 if (thisunit == rootunit)
2671 mp->mnt_kern_flag |= MNTK_ROOTDEV;
2672 }
2673 }
2674 /*
2675 * force the spec device to re-cache
2676 * the underlying block size in case
2677 * the filesystem overrode the initial value
2678 */
2679 set_fsblocksize(devvp);
2680
2681
2682 if ((error = VNOP_IOCTL(devvp, DKIOCGETBLOCKSIZE,
2683 (caddr_t)&blksize, 0, ctx)))
2684 return (error);
2685
2686 mp->mnt_devblocksize = blksize;
2687
2688 if (VNOP_IOCTL(devvp, DKIOCISVIRTUAL, (caddr_t)&isvirtual, 0, ctx) == 0) {
2689 if (isvirtual)
2690 mp->mnt_kern_flag |= MNTK_VIRTUALDEV;
2691 }
2692
2693 if ((error = VNOP_IOCTL(devvp, DKIOCGETFEATURES,
2694 (caddr_t)&features, 0, ctx)))
2695 return (error);
2696
2697 if ((error = VNOP_IOCTL(devvp, DKIOCGETMAXBLOCKCOUNTREAD,
2698 (caddr_t)&readblockcnt, 0, ctx)))
2699 return (error);
2700
2701 if ((error = VNOP_IOCTL(devvp, DKIOCGETMAXBLOCKCOUNTWRITE,
2702 (caddr_t)&writeblockcnt, 0, ctx)))
2703 return (error);
2704
2705 if ((error = VNOP_IOCTL(devvp, DKIOCGETMAXBYTECOUNTREAD,
2706 (caddr_t)&readmaxcnt, 0, ctx)))
2707 return (error);
2708
2709 if ((error = VNOP_IOCTL(devvp, DKIOCGETMAXBYTECOUNTWRITE,
2710 (caddr_t)&writemaxcnt, 0, ctx)))
2711 return (error);
2712
2713 if ((error = VNOP_IOCTL(devvp, DKIOCGETMAXSEGMENTCOUNTREAD,
2714 (caddr_t)&readsegcnt, 0, ctx)))
2715 return (error);
2716
2717 if ((error = VNOP_IOCTL(devvp, DKIOCGETMAXSEGMENTCOUNTWRITE,
2718 (caddr_t)&writesegcnt, 0, ctx)))
2719 return (error);
2720
2721 if ((error = VNOP_IOCTL(devvp, DKIOCGETMAXSEGMENTBYTECOUNTREAD,
2722 (caddr_t)&readsegsize, 0, ctx)))
2723 return (error);
2724
2725 if ((error = VNOP_IOCTL(devvp, DKIOCGETMAXSEGMENTBYTECOUNTWRITE,
2726 (caddr_t)&writesegsize, 0, ctx)))
2727 return (error);
2728
2729 if ((error = VNOP_IOCTL(devvp, DKIOCGETMINSEGMENTALIGNMENTBYTECOUNT,
2730 (caddr_t)&alignment, 0, ctx)))
2731 return (error);
2732
2733 if (readmaxcnt)
2734 temp = (readmaxcnt > UINT32_MAX) ? UINT32_MAX : readmaxcnt;
2735 else {
2736 if (readblockcnt) {
2737 temp = readblockcnt * blksize;
2738 temp = (temp > UINT32_MAX) ? UINT32_MAX : temp;
2739 } else
2740 temp = MAXPHYS;
2741 }
2742 mp->mnt_maxreadcnt = (u_int32_t)temp;
2743
2744 if (writemaxcnt)
2745 temp = (writemaxcnt > UINT32_MAX) ? UINT32_MAX : writemaxcnt;
2746 else {
2747 if (writeblockcnt) {
2748 temp = writeblockcnt * blksize;
2749 temp = (temp > UINT32_MAX) ? UINT32_MAX : temp;
2750 } else
2751 temp = MAXPHYS;
2752 }
2753 mp->mnt_maxwritecnt = (u_int32_t)temp;
2754
2755 if (readsegcnt) {
2756 temp = (readsegcnt > UINT16_MAX) ? UINT16_MAX : readsegcnt;
2757 mp->mnt_segreadcnt = (u_int16_t)temp;
2758 }
2759 if (writesegcnt) {
2760 temp = (writesegcnt > UINT16_MAX) ? UINT16_MAX : writesegcnt;
2761 mp->mnt_segwritecnt = (u_int16_t)temp;
2762 }
2763 if (readsegsize)
2764 temp = (readsegsize > UINT32_MAX) ? UINT32_MAX : readsegsize;
2765 else
2766 temp = mp->mnt_maxreadcnt;
2767 mp->mnt_maxsegreadsize = (u_int32_t)temp;
2768
2769 if (writesegsize)
2770 temp = (writesegsize > UINT32_MAX) ? UINT32_MAX : writesegsize;
2771 else
2772 temp = mp->mnt_maxwritecnt;
2773 mp->mnt_maxsegwritesize = (u_int32_t)temp;
2774
2775 if (alignment)
2776 temp = (alignment > PAGE_SIZE) ? PAGE_MASK : alignment - 1;
2777 else
2778 temp = 0;
2779 mp->mnt_alignmentmask = temp;
2780
2781 if (features & DK_FEATURE_FORCE_UNIT_ACCESS)
2782 mp->mnt_ioflags |= MNT_IOFLAGS_FUA_SUPPORTED;
2783
2784 return (error);
2785 }
2786
2787 static struct klist fs_klist;
2788
2789 void
2790 vfs_event_init(void)
2791 {
2792
2793 klist_init(&fs_klist);
2794 }
2795
2796 void
2797 vfs_event_signal(__unused fsid_t *fsid, u_int32_t event, __unused intptr_t data)
2798 {
2799
2800 KNOTE(&fs_klist, event);
2801 }
2802
2803 /*
2804 * return the number of mounted filesystems.
2805 */
2806 static int
2807 sysctl_vfs_getvfscnt(void)
2808 {
2809 return(mount_getvfscnt());
2810 }
2811
2812
2813 static int
2814 mount_getvfscnt(void)
2815 {
2816 int ret;
2817
2818 mount_list_lock();
2819 ret = nummounts;
2820 mount_list_unlock();
2821 return (ret);
2822
2823 }
2824
2825
2826
2827 static int
2828 mount_fillfsids(fsid_t *fsidlst, int count)
2829 {
2830 struct mount *mp;
2831 int actual=0;
2832
2833 actual = 0;
2834 mount_list_lock();
2835 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
2836 if (actual <= count) {
2837 fsidlst[actual] = mp->mnt_vfsstat.f_fsid;
2838 actual++;
2839 }
2840 }
2841 mount_list_unlock();
2842 return (actual);
2843
2844 }
2845
2846 /*
2847 * fill in the array of fsid_t's up to a max of 'count', the actual
2848 * number filled in will be set in '*actual'. If there are more fsid_t's
2849 * than room in fsidlst then ENOMEM will be returned and '*actual' will
2850 * have the actual count.
2851 * having *actual filled out even in the error case is depended upon.
2852 */
2853 static int
2854 sysctl_vfs_getvfslist(fsid_t *fsidlst, int count, int *actual)
2855 {
2856 struct mount *mp;
2857
2858 *actual = 0;
2859 mount_list_lock();
2860 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
2861 (*actual)++;
2862 if (*actual <= count)
2863 fsidlst[(*actual) - 1] = mp->mnt_vfsstat.f_fsid;
2864 }
2865 mount_list_unlock();
2866 return (*actual <= count ? 0 : ENOMEM);
2867 }
2868
2869 static int
2870 sysctl_vfs_vfslist(__unused struct sysctl_oid *oidp, __unused void *arg1,
2871 __unused int arg2, struct sysctl_req *req)
2872 {
2873 int actual, error;
2874 size_t space;
2875 fsid_t *fsidlst;
2876
2877 /* This is a readonly node. */
2878 if (req->newptr != USER_ADDR_NULL)
2879 return (EPERM);
2880
2881 /* they are querying us so just return the space required. */
2882 if (req->oldptr == USER_ADDR_NULL) {
2883 req->oldidx = sysctl_vfs_getvfscnt() * sizeof(fsid_t);
2884 return 0;
2885 }
2886 again:
2887 /*
2888 * Retrieve an accurate count of the amount of space required to copy
2889 * out all the fsids in the system.
2890 */
2891 space = req->oldlen;
2892 req->oldlen = sysctl_vfs_getvfscnt() * sizeof(fsid_t);
2893
2894 /* they didn't give us enough space. */
2895 if (space < req->oldlen)
2896 return (ENOMEM);
2897
2898 MALLOC(fsidlst, fsid_t *, req->oldlen, M_TEMP, M_WAITOK);
2899 error = sysctl_vfs_getvfslist(fsidlst, req->oldlen / sizeof(fsid_t),
2900 &actual);
2901 /*
2902 * If we get back ENOMEM, then another mount has been added while we
2903 * slept in malloc above. If this is the case then try again.
2904 */
2905 if (error == ENOMEM) {
2906 FREE(fsidlst, M_TEMP);
2907 req->oldlen = space;
2908 goto again;
2909 }
2910 if (error == 0) {
2911 error = SYSCTL_OUT(req, fsidlst, actual * sizeof(fsid_t));
2912 }
2913 FREE(fsidlst, M_TEMP);
2914 return (error);
2915 }
2916
2917 /*
2918 * Do a sysctl by fsid.
2919 */
2920 static int
2921 sysctl_vfs_ctlbyfsid(__unused struct sysctl_oid *oidp, void *arg1, int arg2,
2922 struct sysctl_req *req)
2923 {
2924 struct vfsidctl vc;
2925 struct user_vfsidctl user_vc;
2926 struct mount *mp;
2927 struct vfsstatfs *sp;
2928 int *name, flags, namelen;
2929 int error=0, gotref=0;
2930 vfs_context_t ctx = vfs_context_current();
2931 proc_t p = req->p; /* XXX req->p != current_proc()? */
2932 boolean_t is_64_bit;
2933
2934 name = arg1;
2935 namelen = arg2;
2936 is_64_bit = proc_is64bit(p);
2937
2938 if (is_64_bit) {
2939 error = SYSCTL_IN(req, &user_vc, sizeof(user_vc));
2940 if (error)
2941 goto out;
2942 if (user_vc.vc_vers != VFS_CTL_VERS1) {
2943 error = EINVAL;
2944 goto out;
2945 }
2946 mp = mount_list_lookupby_fsid(&user_vc.vc_fsid, 0, 1);
2947 }
2948 else {
2949 error = SYSCTL_IN(req, &vc, sizeof(vc));
2950 if (error)
2951 goto out;
2952 if (vc.vc_vers != VFS_CTL_VERS1) {
2953 error = EINVAL;
2954 goto out;
2955 }
2956 mp = mount_list_lookupby_fsid(&vc.vc_fsid, 0, 1);
2957 }
2958 if (mp == NULL) {
2959 error = ENOENT;
2960 goto out;
2961 }
2962 gotref = 1;
2963 /* reset so that the fs specific code can fetch it. */
2964 req->newidx = 0;
2965 /*
2966 * Note if this is a VFS_CTL then we pass the actual sysctl req
2967 * in for "oldp" so that the lower layer can DTRT and use the
2968 * SYSCTL_IN/OUT routines.
2969 */
2970 if (mp->mnt_op->vfs_sysctl != NULL) {
2971 if (is_64_bit) {
2972 if (vfs_64bitready(mp)) {
2973 error = mp->mnt_op->vfs_sysctl(name, namelen,
2974 CAST_USER_ADDR_T(req),
2975 NULL, USER_ADDR_NULL, 0,
2976 ctx);
2977 }
2978 else {
2979 error = ENOTSUP;
2980 }
2981 }
2982 else {
2983 error = mp->mnt_op->vfs_sysctl(name, namelen,
2984 CAST_USER_ADDR_T(req),
2985 NULL, USER_ADDR_NULL, 0,
2986 ctx);
2987 }
2988 if (error != ENOTSUP) {
2989 goto out;
2990 }
2991 }
2992 switch (name[0]) {
2993 case VFS_CTL_UMOUNT:
2994 req->newidx = 0;
2995 if (is_64_bit) {
2996 req->newptr = user_vc.vc_ptr;
2997 req->newlen = (size_t)user_vc.vc_len;
2998 }
2999 else {
3000 req->newptr = CAST_USER_ADDR_T(vc.vc_ptr);
3001 req->newlen = vc.vc_len;
3002 }
3003 error = SYSCTL_IN(req, &flags, sizeof(flags));
3004 if (error)
3005 break;
3006
3007 mount_ref(mp, 0);
3008 mount_iterdrop(mp);
3009 gotref = 0;
3010 /* safedounmount consumes a ref */
3011 error = safedounmount(mp, flags, ctx);
3012 break;
3013 case VFS_CTL_STATFS:
3014 req->newidx = 0;
3015 if (is_64_bit) {
3016 req->newptr = user_vc.vc_ptr;
3017 req->newlen = (size_t)user_vc.vc_len;
3018 }
3019 else {
3020 req->newptr = CAST_USER_ADDR_T(vc.vc_ptr);
3021 req->newlen = vc.vc_len;
3022 }
3023 error = SYSCTL_IN(req, &flags, sizeof(flags));
3024 if (error)
3025 break;
3026 sp = &mp->mnt_vfsstat;
3027 if (((flags & MNT_NOWAIT) == 0 || (flags & MNT_WAIT)) &&
3028 (error = vfs_update_vfsstat(mp, ctx, VFS_USER_EVENT)))
3029 goto out;
3030 if (is_64_bit) {
3031 struct user_statfs sfs;
3032 bzero(&sfs, sizeof(sfs));
3033 sfs.f_flags = mp->mnt_flag & MNT_VISFLAGMASK;
3034 sfs.f_type = mp->mnt_vtable->vfc_typenum;
3035 sfs.f_bsize = (user_long_t)sp->f_bsize;
3036 sfs.f_iosize = (user_long_t)sp->f_iosize;
3037 sfs.f_blocks = (user_long_t)sp->f_blocks;
3038 sfs.f_bfree = (user_long_t)sp->f_bfree;
3039 sfs.f_bavail = (user_long_t)sp->f_bavail;
3040 sfs.f_files = (user_long_t)sp->f_files;
3041 sfs.f_ffree = (user_long_t)sp->f_ffree;
3042 sfs.f_fsid = sp->f_fsid;
3043 sfs.f_owner = sp->f_owner;
3044
3045 strlcpy(sfs.f_fstypename, sp->f_fstypename, MFSNAMELEN);
3046 strlcpy(sfs.f_mntonname, sp->f_mntonname, MNAMELEN);
3047 strlcpy(sfs.f_mntfromname, sp->f_mntfromname, MNAMELEN);
3048
3049 error = SYSCTL_OUT(req, &sfs, sizeof(sfs));
3050 }
3051 else {
3052 struct statfs sfs;
3053 bzero(&sfs, sizeof(struct statfs));
3054 sfs.f_flags = mp->mnt_flag & MNT_VISFLAGMASK;
3055 sfs.f_type = mp->mnt_vtable->vfc_typenum;
3056
3057 /*
3058 * It's possible for there to be more than 2^^31 blocks in the filesystem, so we
3059 * have to fudge the numbers here in that case. We inflate the blocksize in order
3060 * to reflect the filesystem size as best we can.
3061 */
3062 if (sp->f_blocks > LONG_MAX) {
3063 int shift;
3064
3065 /*
3066 * Work out how far we have to shift the block count down to make it fit.
3067 * Note that it's possible to have to shift so far that the resulting
3068 * blocksize would be unreportably large. At that point, we will clip
3069 * any values that don't fit.
3070 *
3071 * For safety's sake, we also ensure that f_iosize is never reported as
3072 * being smaller than f_bsize.
3073 */
3074 for (shift = 0; shift < 32; shift++) {
3075 if ((sp->f_blocks >> shift) <= LONG_MAX)
3076 break;
3077 if ((sp->f_bsize << (shift + 1)) > LONG_MAX)
3078 break;
3079 }
3080 #define __SHIFT_OR_CLIP(x, s) ((((x) >> (s)) > LONG_MAX) ? LONG_MAX : ((x) >> (s)))
3081 sfs.f_blocks = (long)__SHIFT_OR_CLIP(sp->f_blocks, shift);
3082 sfs.f_bfree = (long)__SHIFT_OR_CLIP(sp->f_bfree, shift);
3083 sfs.f_bavail = (long)__SHIFT_OR_CLIP(sp->f_bavail, shift);
3084 #undef __SHIFT_OR_CLIP
3085 sfs.f_bsize = (long)(sp->f_bsize << shift);
3086 sfs.f_iosize = lmax(sp->f_iosize, sp->f_bsize);
3087 } else {
3088 sfs.f_bsize = (long)sp->f_bsize;
3089 sfs.f_iosize = (long)sp->f_iosize;
3090 sfs.f_blocks = (long)sp->f_blocks;
3091 sfs.f_bfree = (long)sp->f_bfree;
3092 sfs.f_bavail = (long)sp->f_bavail;
3093 }
3094 sfs.f_files = (long)sp->f_files;
3095 sfs.f_ffree = (long)sp->f_ffree;
3096 sfs.f_fsid = sp->f_fsid;
3097 sfs.f_owner = sp->f_owner;
3098
3099 strlcpy(sfs.f_fstypename, sp->f_fstypename, MFSNAMELEN);
3100 strlcpy(sfs.f_mntonname, sp->f_mntonname, MNAMELEN);
3101 strlcpy(sfs.f_mntfromname, sp->f_mntfromname, MNAMELEN);
3102
3103 error = SYSCTL_OUT(req, &sfs, sizeof(sfs));
3104 }
3105 break;
3106 default:
3107 error = ENOTSUP;
3108 goto out;
3109 }
3110 out:
3111 if(gotref != 0)
3112 mount_iterdrop(mp);
3113 return (error);
3114 }
3115
3116 static int filt_fsattach(struct knote *kn);
3117 static void filt_fsdetach(struct knote *kn);
3118 static int filt_fsevent(struct knote *kn, long hint);
3119
3120 struct filterops fs_filtops =
3121 { 0, filt_fsattach, filt_fsdetach, filt_fsevent };
3122
3123 static int
3124 filt_fsattach(struct knote *kn)
3125 {
3126
3127 kn->kn_flags |= EV_CLEAR;
3128 KNOTE_ATTACH(&fs_klist, kn);
3129 return (0);
3130 }
3131
3132 static void
3133 filt_fsdetach(struct knote *kn)
3134 {
3135
3136 KNOTE_DETACH(&fs_klist, kn);
3137 }
3138
3139 static int
3140 filt_fsevent(struct knote *kn, long hint)
3141 {
3142 /*
3143 * Backwards compatibility:
3144 * Other filters would do nothing if kn->kn_sfflags == 0
3145 */
3146
3147 if ((kn->kn_sfflags == 0) || (kn->kn_sfflags & hint)) {
3148 kn->kn_fflags |= hint;
3149 }
3150
3151 return (kn->kn_fflags != 0);
3152 }
3153
3154 static int
3155 sysctl_vfs_noremotehang(__unused struct sysctl_oid *oidp,
3156 __unused void *arg1, __unused int arg2, struct sysctl_req *req)
3157 {
3158 int out, error;
3159 pid_t pid;
3160 proc_t p;
3161
3162 /* We need a pid. */
3163 if (req->newptr == USER_ADDR_NULL)
3164 return (EINVAL);
3165
3166 error = SYSCTL_IN(req, &pid, sizeof(pid));
3167 if (error)
3168 return (error);
3169
3170 p = proc_find(pid < 0 ? -pid : pid);
3171 if (p == NULL)
3172 return (ESRCH);
3173
3174 /*
3175 * Fetching the value is ok, but we only fetch if the old
3176 * pointer is given.
3177 */
3178 if (req->oldptr != USER_ADDR_NULL) {
3179 out = !((p->p_flag & P_NOREMOTEHANG) == 0);
3180 proc_rele(p);
3181 error = SYSCTL_OUT(req, &out, sizeof(out));
3182 return (error);
3183 }
3184
3185 /* cansignal offers us enough security. */
3186 if (p != req->p && proc_suser(req->p) != 0) {
3187 proc_rele(p);
3188 return (EPERM);
3189 }
3190
3191 if (pid < 0)
3192 OSBitAndAtomic(~((uint32_t)P_NOREMOTEHANG), (UInt32 *)&p->p_flag);
3193 else
3194 OSBitOrAtomic(P_NOREMOTEHANG, (UInt32 *)&p->p_flag);
3195 proc_rele(p);
3196
3197 return (0);
3198 }
3199
3200 /* the vfs.generic. branch. */
3201 SYSCTL_NODE(_vfs, VFS_GENERIC, generic, CTLFLAG_RW|CTLFLAG_LOCKED, NULL, "vfs generic hinge");
3202 /* retreive a list of mounted filesystem fsid_t */
3203 SYSCTL_PROC(_vfs_generic, OID_AUTO, vfsidlist, CTLFLAG_RD,
3204 NULL, 0, sysctl_vfs_vfslist, "S,fsid", "List of mounted filesystem ids");
3205 /* perform operations on filesystem via fsid_t */
3206 SYSCTL_NODE(_vfs_generic, OID_AUTO, ctlbyfsid, CTLFLAG_RW|CTLFLAG_LOCKED,
3207 sysctl_vfs_ctlbyfsid, "ctlbyfsid");
3208 SYSCTL_PROC(_vfs_generic, OID_AUTO, noremotehang, CTLFLAG_RW|CTLFLAG_ANYBODY,
3209 NULL, 0, sysctl_vfs_noremotehang, "I", "noremotehang");
3210
3211
3212 long num_reusedvnodes = 0; /* long for OSAddAtomic */
3213
3214 static int
3215 new_vnode(vnode_t *vpp)
3216 {
3217 vnode_t vp;
3218 int retries = 0; /* retry incase of tablefull */
3219 int force_alloc = 0, walk_count = 0;
3220 int vpid;
3221 struct timespec ts;
3222 struct timeval current_tv;
3223 struct unsafe_fsnode *l_unsafefs = 0;
3224 proc_t curproc = current_proc();
3225 pid_t current_pid = proc_pid(curproc);
3226
3227 retry:
3228 microuptime(&current_tv);
3229
3230 vp = NULLVP;
3231
3232 vnode_list_lock();
3233
3234 if ( !TAILQ_EMPTY(&vnode_dead_list)) {
3235 /*
3236 * Can always reuse a dead one
3237 */
3238 vp = TAILQ_FIRST(&vnode_dead_list);
3239 goto steal_this_vp;
3240 }
3241 /*
3242 * no dead vnodes available... if we're under
3243 * the limit, we'll create a new vnode
3244 */
3245 if (numvnodes < desiredvnodes || force_alloc) {
3246 numvnodes++;
3247 vnode_list_unlock();
3248 MALLOC_ZONE(vp, struct vnode *, sizeof(*vp), M_VNODE, M_WAITOK);
3249 bzero((char *)vp, sizeof(*vp));
3250 VLISTNONE(vp); /* avoid double queue removal */
3251 lck_mtx_init(&vp->v_lock, vnode_lck_grp, vnode_lck_attr);
3252
3253 nanouptime(&ts);
3254 vp->v_id = ts.tv_nsec;
3255 vp->v_flag = VSTANDARD;
3256
3257 #if CONFIG_MACF
3258 mac_vnode_label_init(vp);
3259 #endif /* MAC */
3260
3261 goto done;
3262 }
3263
3264 #define MAX_WALK_COUNT 1000
3265
3266 if ( !TAILQ_EMPTY(&vnode_rage_list) &&
3267 (ragevnodes >= rage_limit ||
3268 (current_tv.tv_sec - rage_tv.tv_sec) >= RAGE_TIME_LIMIT)) {
3269
3270 TAILQ_FOREACH(vp, &vnode_rage_list, v_freelist) {
3271 if ( !(vp->v_listflag & VLIST_RAGE) || !(vp->v_flag & VRAGE))
3272 panic("new_vnode: vp on RAGE list not marked both VLIST_RAGE and VRAGE");
3273
3274 // skip vnodes which have a dependency on this process
3275 // (i.e. they're vnodes in a disk image and this process
3276 // is diskimages-helper)
3277 //
3278 if (vp->v_mount && vp->v_mount->mnt_dependent_pid != current_pid && vp->v_mount->mnt_dependent_process != curproc) {
3279 break;
3280 }
3281
3282 // don't iterate more than MAX_WALK_COUNT vnodes to
3283 // avoid keeping the vnode list lock held for too long.
3284 if (walk_count++ > MAX_WALK_COUNT) {
3285 vp = NULL;
3286 break;
3287 }
3288 }
3289
3290 }
3291
3292 if (vp == NULL && !TAILQ_EMPTY(&vnode_free_list)) {
3293 /*
3294 * Pick the first vp for possible reuse
3295 */
3296 walk_count = 0;
3297 TAILQ_FOREACH(vp, &vnode_free_list, v_freelist) {
3298 // skip vnodes which have a dependency on this process
3299 // (i.e. they're vnodes in a disk image and this process
3300 // is diskimages-helper)
3301 //
3302 if (vp->v_mount && vp->v_mount->mnt_dependent_pid != current_pid && vp->v_mount->mnt_dependent_process != curproc) {
3303 break;
3304 }
3305
3306 // don't iterate more than MAX_WALK_COUNT vnodes to
3307 // avoid keeping the vnode list lock held for too long.
3308 if (walk_count++ > MAX_WALK_COUNT) {
3309 vp = NULL;
3310 break;
3311 }
3312 }
3313
3314 }
3315
3316 //
3317 // if we don't have a vnode and the walk_count is >= MAX_WALK_COUNT
3318 // then we're trying to create a vnode on behalf of a
3319 // process like diskimages-helper that has file systems
3320 // mounted on top of itself (and thus we can't reclaim
3321 // vnodes in the file systems on top of us). if we can't
3322 // find a vnode to reclaim then we'll just have to force
3323 // the allocation.
3324 //
3325 if (vp == NULL && walk_count >= MAX_WALK_COUNT) {
3326 force_alloc = 1;
3327 vnode_list_unlock();
3328 goto retry;
3329 }
3330
3331 if (vp == NULL) {
3332 /*
3333 * we've reached the system imposed maximum number of vnodes
3334 * but there isn't a single one available
3335 * wait a bit and then retry... if we can't get a vnode
3336 * after 100 retries, than log a complaint
3337 */
3338 if (++retries <= 100) {
3339 vnode_list_unlock();
3340 delay_for_interval(1, 1000 * 1000);
3341 goto retry;
3342 }
3343
3344 vnode_list_unlock();
3345 tablefull("vnode");
3346 log(LOG_EMERG, "%d desired, %d numvnodes, "
3347 "%d free, %d dead, %d rage\n",
3348 desiredvnodes, numvnodes, freevnodes, deadvnodes, ragevnodes);
3349 *vpp = NULL;
3350 return (ENFILE);
3351 }
3352 steal_this_vp:
3353 vpid = vp->v_id;
3354
3355 /*
3356 * the v_listflag field is
3357 * protected by the vnode_list_lock
3358 */
3359 if (vp->v_listflag & VLIST_DEAD)
3360 VREMDEAD("new_vnode", vp);
3361 else if (vp->v_listflag & VLIST_RAGE)
3362 VREMRAGE("new_vnode", vp);
3363 else
3364 VREMFREE("new_vnode", vp);
3365 VLISTNONE(vp);
3366
3367 vnode_list_unlock();
3368 vnode_lock_spin(vp);
3369
3370 /*
3371 * We could wait for the vnode_lock after removing the vp from the freelist
3372 * and the vid is bumped only at the very end of reclaim. So it is possible
3373 * that we are looking at a vnode that is being terminated. If so skip it.
3374 */
3375 if ((vpid != vp->v_id) || (vp->v_usecount != 0) || (vp->v_iocount != 0) ||
3376 VONLIST(vp) || (vp->v_lflag & VL_TERMINATE)) {
3377 /*
3378 * we lost the race between dropping the list lock
3379 * and picking up the vnode_lock... someone else
3380 * used this vnode and it is now in a new state
3381 * so we need to go back and try again
3382 */
3383 vnode_unlock(vp);
3384 goto retry;
3385 }
3386 if ( (vp->v_lflag & (VL_NEEDINACTIVE | VL_MARKTERM)) == VL_NEEDINACTIVE ) {
3387 /*
3388 * we did a vnode_rele_ext that asked for
3389 * us not to reenter the filesystem during
3390 * the release even though VL_NEEDINACTIVE was
3391 * set... we'll do it here by doing a
3392 * vnode_get/vnode_put
3393 *
3394 * pick up an iocount so that we can call
3395 * vnode_put and drive the VNOP_INACTIVE...
3396 * vnode_put will either leave us off
3397 * the freelist if a new ref comes in,
3398 * or put us back on the end of the freelist
3399 * or recycle us if we were marked for termination...
3400 * so we'll just go grab a new candidate
3401 */
3402 vp->v_iocount++;
3403 #ifdef JOE_DEBUG
3404 record_vp(vp, 1);
3405 #endif
3406 vnode_put_locked(vp);
3407 vnode_unlock(vp);
3408 goto retry;
3409 }
3410 OSAddAtomic(1, &num_reusedvnodes);
3411
3412 /* Checks for anyone racing us for recycle */
3413 if (vp->v_type != VBAD) {
3414 if (vp->v_lflag & VL_DEAD)
3415 panic("new_vnode: the vnode is VL_DEAD but not VBAD");
3416 vnode_lock_convert(vp);
3417
3418 (void)vnode_reclaim_internal(vp, 1, 1, 0);
3419
3420 if ((VONLIST(vp)))
3421 panic("new_vnode: vp on list ");
3422 if (vp->v_usecount || vp->v_iocount || vp->v_kusecount ||
3423 (vp->v_lflag & (VNAMED_UBC | VNAMED_MOUNT | VNAMED_FSHASH)))
3424 panic("new_vnode: free vnode still referenced\n");
3425 if ((vp->v_mntvnodes.tqe_prev != 0) && (vp->v_mntvnodes.tqe_next != 0))
3426 panic("new_vnode: vnode seems to be on mount list ");
3427 if ( !LIST_EMPTY(&vp->v_nclinks) || !LIST_EMPTY(&vp->v_ncchildren))
3428 panic("new_vnode: vnode still hooked into the name cache");
3429 }
3430 if (vp->v_unsafefs) {
3431 l_unsafefs = vp->v_unsafefs;
3432 vp->v_unsafefs = (struct unsafe_fsnode *)NULL;
3433 }
3434
3435 #if CONFIG_MACF
3436 /*
3437 * We should never see VL_LABELWAIT or VL_LABEL here.
3438 * as those operations hold a reference.
3439 */
3440 assert ((vp->v_lflag & VL_LABELWAIT) != VL_LABELWAIT);
3441 assert ((vp->v_lflag & VL_LABEL) != VL_LABEL);
3442 if (vp->v_lflag & VL_LABELED) {
3443 vnode_lock_convert(vp);
3444 mac_vnode_label_recycle(vp);
3445 }
3446 #endif /* MAC */
3447
3448 vp->v_lflag = 0;
3449 vp->v_writecount = 0;
3450 vp->v_references = 0;
3451 vp->v_iterblkflags = 0;
3452 vp->v_flag = VSTANDARD;
3453 /* vbad vnodes can point to dead_mountp */
3454 vp->v_mount = NULL;
3455 vp->v_defer_reclaimlist = (vnode_t)0;
3456
3457 vnode_unlock(vp);
3458
3459 if (l_unsafefs) {
3460 lck_mtx_destroy(&l_unsafefs->fsnodelock, vnode_lck_grp);
3461 FREE_ZONE((void *)l_unsafefs, sizeof(struct unsafe_fsnode), M_UNSAFEFS);
3462 }
3463 done:
3464 *vpp = vp;
3465
3466 return (0);
3467 }
3468
3469 void
3470 vnode_lock(vnode_t vp)
3471 {
3472 lck_mtx_lock(&vp->v_lock);
3473 }
3474
3475 void
3476 vnode_lock_spin(vnode_t vp)
3477 {
3478 lck_mtx_lock_spin(&vp->v_lock);
3479 }
3480
3481 void
3482 vnode_unlock(vnode_t vp)
3483 {
3484 lck_mtx_unlock(&vp->v_lock);
3485 }
3486
3487
3488
3489 int
3490 vnode_get(struct vnode *vp)
3491 {
3492 int retval;
3493
3494 vnode_lock_spin(vp);
3495 retval = vnode_get_locked(vp);
3496 vnode_unlock(vp);
3497
3498 return(retval);
3499 }
3500
3501 int
3502 vnode_get_locked(struct vnode *vp)
3503 {
3504
3505 if ((vp->v_iocount == 0) && (vp->v_lflag & (VL_TERMINATE | VL_DEAD))) {
3506 return(ENOENT);
3507 }
3508 vp->v_iocount++;
3509 #ifdef JOE_DEBUG
3510 record_vp(vp, 1);
3511 #endif
3512 return (0);
3513 }
3514
3515 int
3516 vnode_getwithvid(vnode_t vp, int vid)
3517 {
3518 return(vget_internal(vp, vid, ( VNODE_NODEAD| VNODE_WITHID)));
3519 }
3520
3521 int
3522 vnode_getwithref(vnode_t vp)
3523 {
3524 return(vget_internal(vp, 0, 0));
3525 }
3526
3527
3528 int
3529 vnode_put(vnode_t vp)
3530 {
3531 int retval;
3532
3533 vnode_lock_spin(vp);
3534 retval = vnode_put_locked(vp);
3535 vnode_unlock(vp);
3536
3537 return(retval);
3538 }
3539
3540 int
3541 vnode_put_locked(vnode_t vp)
3542 {
3543 vfs_context_t ctx = vfs_context_current(); /* hoist outside loop */
3544
3545 retry:
3546 if (vp->v_iocount < 1)
3547 panic("vnode_put(%p): iocount < 1", vp);
3548
3549 if ((vp->v_usecount > 0) || (vp->v_iocount > 1)) {
3550 vnode_dropiocount(vp);
3551 return(0);
3552 }
3553 if ((vp->v_lflag & (VL_MARKTERM | VL_TERMINATE | VL_DEAD | VL_NEEDINACTIVE)) == VL_NEEDINACTIVE) {
3554
3555 vp->v_lflag &= ~VL_NEEDINACTIVE;
3556 vnode_unlock(vp);
3557
3558 VNOP_INACTIVE(vp, ctx);
3559
3560 vnode_lock_spin(vp);
3561 /*
3562 * because we had to drop the vnode lock before calling
3563 * VNOP_INACTIVE, the state of this vnode may have changed...
3564 * we may pick up both VL_MARTERM and either
3565 * an iocount or a usecount while in the VNOP_INACTIVE call
3566 * we don't want to call vnode_reclaim_internal on a vnode
3567 * that has active references on it... so loop back around
3568 * and reevaluate the state
3569 */
3570 goto retry;
3571 }
3572 vp->v_lflag &= ~VL_NEEDINACTIVE;
3573
3574 if ((vp->v_lflag & (VL_MARKTERM | VL_TERMINATE | VL_DEAD)) == VL_MARKTERM) {
3575 vnode_lock_convert(vp);
3576 vnode_reclaim_internal(vp, 1, 0, 0);
3577 }
3578 vnode_dropiocount(vp);
3579 vnode_list_add(vp);
3580
3581 return(0);
3582 }
3583
3584 /* is vnode_t in use by others? */
3585 int
3586 vnode_isinuse(vnode_t vp, int refcnt)
3587 {
3588 return(vnode_isinuse_locked(vp, refcnt, 0));
3589 }
3590
3591
3592 static int
3593 vnode_isinuse_locked(vnode_t vp, int refcnt, int locked)
3594 {
3595 int retval = 0;
3596
3597 if (!locked)
3598 vnode_lock_spin(vp);
3599 if ((vp->v_type != VREG) && ((vp->v_usecount - vp->v_kusecount) > refcnt)) {
3600 retval = 1;
3601 goto out;
3602 }
3603 if (vp->v_type == VREG) {
3604 retval = ubc_isinuse_locked(vp, refcnt, 1);
3605 }
3606
3607 out:
3608 if (!locked)
3609 vnode_unlock(vp);
3610 return(retval);
3611 }
3612
3613
3614 /* resume vnode_t */
3615 errno_t
3616 vnode_resume(vnode_t vp)
3617 {
3618
3619 vnode_lock_spin(vp);
3620
3621 if (vp->v_owner == current_thread()) {
3622 vp->v_lflag &= ~VL_SUSPENDED;
3623 vp->v_owner = NULL;
3624 vnode_unlock(vp);
3625 wakeup(&vp->v_iocount);
3626 } else
3627 vnode_unlock(vp);
3628
3629 return(0);
3630 }
3631
3632 /* suspend vnode_t
3633 * Please do not use on more than one vnode at a time as it may
3634 * cause deadlocks.
3635 * xxx should we explicity prevent this from happening?
3636 */
3637
3638 errno_t
3639 vnode_suspend(vnode_t vp)
3640 {
3641 if (vp->v_lflag & VL_SUSPENDED) {
3642 return(EBUSY);
3643 }
3644
3645 vnode_lock_spin(vp);
3646
3647 /*
3648 * xxx is this sufficient to check if a vnode_drain is
3649 * progress?
3650 */
3651
3652 if (vp->v_owner == NULL) {
3653 vp->v_lflag |= VL_SUSPENDED;
3654 vp->v_owner = current_thread();
3655 }
3656 vnode_unlock(vp);
3657
3658 return(0);
3659 }
3660
3661
3662
3663 static errno_t
3664 vnode_drain(vnode_t vp)
3665 {
3666
3667 if (vp->v_lflag & VL_DRAIN) {
3668 panic("vnode_drain: recursuve drain");
3669 return(ENOENT);
3670 }
3671 vp->v_lflag |= VL_DRAIN;
3672 vp->v_owner = current_thread();
3673
3674 while (vp->v_iocount > 1)
3675 msleep(&vp->v_iocount, &vp->v_lock, PVFS, "vnode_drain", NULL);
3676 return(0);
3677 }
3678
3679
3680 /*
3681 * if the number of recent references via vnode_getwithvid or vnode_getwithref
3682 * exceeds this threshhold, than 'UN-AGE' the vnode by removing it from
3683 * the LRU list if it's currently on it... once the iocount and usecount both drop
3684 * to 0, it will get put back on the end of the list, effectively making it younger
3685 * this allows us to keep actively referenced vnodes in the list without having
3686 * to constantly remove and add to the list each time a vnode w/o a usecount is
3687 * referenced which costs us taking and dropping a global lock twice.
3688 */
3689 #define UNAGE_THRESHHOLD 25
3690
3691 static errno_t
3692 vnode_getiocount(vnode_t vp, int vid, int vflags)
3693 {
3694 int nodead = vflags & VNODE_NODEAD;
3695 int nosusp = vflags & VNODE_NOSUSPEND;
3696
3697 for (;;) {
3698 /*
3699 * if it is a dead vnode with deadfs
3700 */
3701 if (nodead && (vp->v_lflag & VL_DEAD) && ((vp->v_type == VBAD) || (vp->v_data == 0))) {
3702 return(ENOENT);
3703 }
3704 /*
3705 * will return VL_DEAD ones
3706 */
3707 if ((vp->v_lflag & (VL_SUSPENDED | VL_DRAIN | VL_TERMINATE)) == 0 ) {
3708 break;
3709 }
3710 /*
3711 * if suspended vnodes are to be failed
3712 */
3713 if (nosusp && (vp->v_lflag & VL_SUSPENDED)) {
3714 return(ENOENT);
3715 }
3716 /*
3717 * if you are the owner of drain/suspend/termination , can acquire iocount
3718 * check for VL_TERMINATE; it does not set owner
3719 */
3720 if ((vp->v_lflag & (VL_DRAIN | VL_SUSPENDED | VL_TERMINATE)) &&
3721 (vp->v_owner == current_thread())) {
3722 break;
3723 }
3724 vnode_lock_convert(vp);
3725
3726 if (vp->v_lflag & VL_TERMINATE) {
3727 vp->v_lflag |= VL_TERMWANT;
3728
3729 msleep(&vp->v_lflag, &vp->v_lock, PVFS, "vnode getiocount", NULL);
3730 } else
3731 msleep(&vp->v_iocount, &vp->v_lock, PVFS, "vnode_getiocount", NULL);
3732 }
3733 if (vid != vp->v_id) {
3734 return(ENOENT);
3735 }
3736 if (++vp->v_references >= UNAGE_THRESHHOLD) {
3737 vp->v_references = 0;
3738 vnode_list_remove(vp);
3739 }
3740 vp->v_iocount++;
3741 #ifdef JOE_DEBUG
3742 record_vp(vp, 1);
3743 #endif
3744 return(0);
3745 }
3746
3747 static void
3748 vnode_dropiocount (vnode_t vp)
3749 {
3750 if (vp->v_iocount < 1)
3751 panic("vnode_dropiocount(%p): v_iocount < 1", vp);
3752
3753 vp->v_iocount--;
3754 #ifdef JOE_DEBUG
3755 record_vp(vp, -1);
3756 #endif
3757 if ((vp->v_lflag & (VL_DRAIN | VL_SUSPENDED)) && (vp->v_iocount <= 1)) {
3758 vnode_lock_convert(vp);
3759 wakeup(&vp->v_iocount);
3760 }
3761 }
3762
3763
3764 void
3765 vnode_reclaim(struct vnode * vp)
3766 {
3767 vnode_reclaim_internal(vp, 0, 0, 0);
3768 }
3769
3770 __private_extern__
3771 void
3772 vnode_reclaim_internal(struct vnode * vp, int locked, int reuse, int flags)
3773 {
3774 int isfifo = 0;
3775
3776 if (!locked)
3777 vnode_lock(vp);
3778
3779 if (vp->v_lflag & VL_TERMINATE) {
3780 panic("vnode reclaim in progress");
3781 }
3782 vp->v_lflag |= VL_TERMINATE;
3783
3784 vn_clearunionwait(vp, 1);
3785
3786 if (vnode_drain(vp)) {
3787 panic("vnode drain failed");
3788 vnode_unlock(vp);
3789 return;
3790 }
3791 isfifo = (vp->v_type == VFIFO);
3792
3793 if (vp->v_type != VBAD)
3794 vgone(vp, flags); /* clean and reclaim the vnode */
3795
3796 /*
3797 * give the vnode a new identity so
3798 * that vnode_getwithvid will fail
3799 * on any stale cache accesses
3800 */
3801 vp->v_id++;
3802 if (isfifo) {
3803 struct fifoinfo * fip;
3804
3805 fip = vp->v_fifoinfo;
3806 vp->v_fifoinfo = NULL;
3807 FREE(fip, M_TEMP);
3808 }
3809
3810 vp->v_type = VBAD;
3811
3812 if (vp->v_data)
3813 panic("vnode_reclaim_internal: cleaned vnode isn't");
3814 if (vp->v_numoutput)
3815 panic("vnode_reclaim_internal: Clean vnode has pending I/O's");
3816 if (UBCINFOEXISTS(vp))
3817 panic("vnode_reclaim_internal: ubcinfo not cleaned");
3818 if (vp->v_parent)
3819 panic("vnode_reclaim_internal: vparent not removed");
3820 if (vp->v_name)
3821 panic("vnode_reclaim_internal: vname not removed");
3822
3823 vp->v_socket = NULL;
3824
3825 vp->v_lflag &= ~VL_TERMINATE;
3826 vp->v_lflag &= ~VL_DRAIN;
3827 vp->v_owner = NULL;
3828
3829 if (vp->v_lflag & VL_TERMWANT) {
3830 vp->v_lflag &= ~VL_TERMWANT;
3831 wakeup(&vp->v_lflag);
3832 }
3833 if (!reuse && vp->v_usecount == 0) {
3834 /*
3835 * make sure we get on the
3836 * dead list
3837 */
3838 vnode_list_remove(vp);
3839 vnode_list_add(vp);
3840 }
3841 if (!locked)
3842 vnode_unlock(vp);
3843 }
3844
3845 /* USAGE:
3846 * The following api creates a vnode and associates all the parameter specified in vnode_fsparam
3847 * structure and returns a vnode handle with a reference. device aliasing is handled here so checkalias
3848 * is obsoleted by this.
3849 * vnode_create(int flavor, size_t size, void * param, vnode_t *vp)
3850 */
3851 int
3852 vnode_create(int flavor, size_t size, void *data, vnode_t *vpp)
3853 {
3854 int error;
3855 int insert = 1;
3856 vnode_t vp;
3857 vnode_t nvp;
3858 vnode_t dvp;
3859 struct uthread *ut;
3860 struct componentname *cnp;
3861 struct vnode_fsparam *param = (struct vnode_fsparam *)data;
3862
3863 if (flavor == VNCREATE_FLAVOR && (size == VCREATESIZE) && param) {
3864 if ( (error = new_vnode(&vp)) ) {
3865 return(error);
3866 } else {
3867 dvp = param->vnfs_dvp;
3868 cnp = param->vnfs_cnp;
3869
3870 vp->v_op = param->vnfs_vops;
3871 vp->v_type = param->vnfs_vtype;
3872 vp->v_data = param->vnfs_fsnode;
3873 vp->v_iocount = 1;
3874
3875 if (param->vnfs_markroot)
3876 vp->v_flag |= VROOT;
3877 if (param->vnfs_marksystem)
3878 vp->v_flag |= VSYSTEM;
3879 if (vp->v_type == VREG) {
3880 error = ubc_info_init_withsize(vp, param->vnfs_filesize);
3881 if (error) {
3882 #ifdef JOE_DEBUG
3883 record_vp(vp, 1);
3884 #endif
3885 vp->v_mount = NULL;
3886 vp->v_op = dead_vnodeop_p;
3887 vp->v_tag = VT_NON;
3888 vp->v_data = NULL;
3889 vp->v_type = VBAD;
3890 vp->v_lflag |= VL_DEAD;
3891
3892 vnode_put(vp);
3893 return(error);
3894 }
3895 }
3896 #ifdef JOE_DEBUG
3897 record_vp(vp, 1);
3898 #endif
3899 if (vp->v_type == VCHR || vp->v_type == VBLK) {
3900
3901 vp->v_tag = VT_DEVFS; /* callers will reset if needed (bdevvp) */
3902
3903 if ( (nvp = checkalias(vp, param->vnfs_rdev)) ) {
3904 /*
3905 * if checkalias returns a vnode, it will be locked
3906 *
3907 * first get rid of the unneeded vnode we acquired
3908 */
3909 vp->v_data = NULL;
3910 vp->v_op = spec_vnodeop_p;
3911 vp->v_type = VBAD;
3912 vp->v_lflag = VL_DEAD;
3913 vp->v_data = NULL;
3914 vp->v_tag = VT_NON;
3915 vnode_put(vp);
3916
3917 /*
3918 * switch to aliased vnode and finish
3919 * preparing it
3920 */
3921 vp = nvp;
3922
3923 vclean(vp, 0);
3924 vp->v_op = param->vnfs_vops;
3925 vp->v_type = param->vnfs_vtype;
3926 vp->v_data = param->vnfs_fsnode;
3927 vp->v_lflag = 0;
3928 vp->v_mount = NULL;
3929 insmntque(vp, param->vnfs_mp);
3930 insert = 0;
3931 vnode_unlock(vp);
3932 }
3933 }
3934
3935 if (vp->v_type == VFIFO) {
3936 struct fifoinfo *fip;
3937
3938 MALLOC(fip, struct fifoinfo *,
3939 sizeof(*fip), M_TEMP, M_WAITOK);
3940 bzero(fip, sizeof(struct fifoinfo ));
3941 vp->v_fifoinfo = fip;
3942 }
3943 /* The file systems usually pass the address of the location where
3944 * where there store the vnode pointer. When we add the vnode in mount
3945 * point and name cache they are discoverable. So the file system node
3946 * will have the connection to vnode setup by then
3947 */
3948 *vpp = vp;
3949
3950 /* Add fs named reference. */
3951 if (param->vnfs_flags & VNFS_ADDFSREF) {
3952 vp->v_lflag |= VNAMED_FSHASH;
3953 }
3954 if (param->vnfs_mp) {
3955 if (param->vnfs_mp->mnt_kern_flag & MNTK_LOCK_LOCAL)
3956 vp->v_flag |= VLOCKLOCAL;
3957 if (insert) {
3958 /*
3959 * enter in mount vnode list
3960 */
3961 insmntque(vp, param->vnfs_mp);
3962 }
3963 #ifdef INTERIM_FSNODE_LOCK
3964 if (param->vnfs_mp->mnt_vtable->vfc_threadsafe == 0) {
3965 MALLOC_ZONE(vp->v_unsafefs, struct unsafe_fsnode *,
3966 sizeof(struct unsafe_fsnode), M_UNSAFEFS, M_WAITOK);
3967 vp->v_unsafefs->fsnode_count = 0;
3968 vp->v_unsafefs->fsnodeowner = (void *)NULL;
3969 lck_mtx_init(&vp->v_unsafefs->fsnodelock, vnode_lck_grp, vnode_lck_attr);
3970 }
3971 #endif /* INTERIM_FSNODE_LOCK */
3972 }
3973 if (dvp && vnode_ref(dvp) == 0) {
3974 vp->v_parent = dvp;
3975 }
3976 if (cnp) {
3977 if (dvp && ((param->vnfs_flags & (VNFS_NOCACHE | VNFS_CANTCACHE)) == 0)) {
3978 /*
3979 * enter into name cache
3980 * we've got the info to enter it into the name cache now
3981 */
3982 cache_enter(dvp, vp, cnp);
3983 }
3984 vp->v_name = vfs_addname(cnp->cn_nameptr, cnp->cn_namelen, cnp->cn_hash, 0);
3985 if ((cnp->cn_flags & UNIONCREATED) == UNIONCREATED)
3986 vp->v_flag |= VISUNION;
3987 }
3988 if ((param->vnfs_flags & VNFS_CANTCACHE) == 0) {
3989 /*
3990 * this vnode is being created as cacheable in the name cache
3991 * this allows us to re-enter it in the cache
3992 */
3993 vp->v_flag |= VNCACHEABLE;
3994 }
3995 ut = get_bsdthread_info(current_thread());
3996
3997 if ((current_proc()->p_lflag & P_LRAGE_VNODES) ||
3998 (ut->uu_flag & UT_RAGE_VNODES)) {
3999 /*
4000 * process has indicated that it wants any
4001 * vnodes created on its behalf to be rapidly
4002 * aged to reduce the impact on the cached set
4003 * of vnodes
4004 */
4005 vp->v_flag |= VRAGE;
4006 }
4007 return(0);
4008 }
4009 }
4010 return (EINVAL);
4011 }
4012
4013 int
4014 vnode_addfsref(vnode_t vp)
4015 {
4016 vnode_lock_spin(vp);
4017 if (vp->v_lflag & VNAMED_FSHASH)
4018 panic("add_fsref: vp already has named reference");
4019 if ((vp->v_freelist.tqe_prev != (struct vnode **)0xdeadb))
4020 panic("addfsref: vp on the free list\n");
4021 vp->v_lflag |= VNAMED_FSHASH;
4022 vnode_unlock(vp);
4023 return(0);
4024
4025 }
4026 int
4027 vnode_removefsref(vnode_t vp)
4028 {
4029 vnode_lock_spin(vp);
4030 if ((vp->v_lflag & VNAMED_FSHASH) == 0)
4031 panic("remove_fsref: no named reference");
4032 vp->v_lflag &= ~VNAMED_FSHASH;
4033 vnode_unlock(vp);
4034 return(0);
4035
4036 }
4037
4038
4039 int
4040 vfs_iterate(__unused int flags, int (*callout)(mount_t, void *), void *arg)
4041 {
4042 mount_t mp;
4043 int ret = 0;
4044 fsid_t * fsid_list;
4045 int count, actualcount, i;
4046 void * allocmem;
4047
4048 count = mount_getvfscnt();
4049 count += 10;
4050
4051 fsid_list = (fsid_t *)kalloc(count * sizeof(fsid_t));
4052 allocmem = (void *)fsid_list;
4053
4054 actualcount = mount_fillfsids(fsid_list, count);
4055
4056 for (i=0; i< actualcount; i++) {
4057
4058 /* obtain the mount point with iteration reference */
4059 mp = mount_list_lookupby_fsid(&fsid_list[i], 0, 1);
4060
4061 if(mp == (struct mount *)0)
4062 continue;
4063 mount_lock(mp);
4064 if (mp->mnt_lflag & (MNT_LDEAD | MNT_LUNMOUNT)) {
4065 mount_unlock(mp);
4066 mount_iterdrop(mp);
4067 continue;
4068
4069 }
4070 mount_unlock(mp);
4071
4072 /* iterate over all the vnodes */
4073 ret = callout(mp, arg);
4074
4075 mount_iterdrop(mp);
4076
4077 switch (ret) {
4078 case VFS_RETURNED:
4079 case VFS_RETURNED_DONE:
4080 if (ret == VFS_RETURNED_DONE) {
4081 ret = 0;
4082 goto out;
4083 }
4084 break;
4085
4086 case VFS_CLAIMED_DONE:
4087 ret = 0;
4088 goto out;
4089 case VFS_CLAIMED:
4090 default:
4091 break;
4092 }
4093 ret = 0;
4094 }
4095
4096 out:
4097 kfree(allocmem, (count * sizeof(fsid_t)));
4098 return (ret);
4099 }
4100
4101 /*
4102 * Update the vfsstatfs structure in the mountpoint.
4103 * MAC: Parameter eventtype added, indicating whether the event that
4104 * triggered this update came from user space, via a system call
4105 * (VFS_USER_EVENT) or an internal kernel call (VFS_KERNEL_EVENT).
4106 */
4107 int
4108 vfs_update_vfsstat(mount_t mp, vfs_context_t ctx, __unused int eventtype)
4109 {
4110 struct vfs_attr va;
4111 int error;
4112
4113 /*
4114 * Request the attributes we want to propagate into
4115 * the per-mount vfsstat structure.
4116 */
4117 VFSATTR_INIT(&va);
4118 VFSATTR_WANTED(&va, f_iosize);
4119 VFSATTR_WANTED(&va, f_blocks);
4120 VFSATTR_WANTED(&va, f_bfree);
4121 VFSATTR_WANTED(&va, f_bavail);
4122 VFSATTR_WANTED(&va, f_bused);
4123 VFSATTR_WANTED(&va, f_files);
4124 VFSATTR_WANTED(&va, f_ffree);
4125 VFSATTR_WANTED(&va, f_bsize);
4126 VFSATTR_WANTED(&va, f_fssubtype);
4127 #if CONFIG_MACF
4128 if (eventtype == VFS_USER_EVENT) {
4129 error = mac_mount_check_getattr(ctx, mp, &va);
4130 if (error != 0)
4131 return (error);
4132 }
4133 #endif
4134
4135 if ((error = vfs_getattr(mp, &va, ctx)) != 0) {
4136 KAUTH_DEBUG("STAT - filesystem returned error %d", error);
4137 return(error);
4138 }
4139
4140 /*
4141 * Unpack into the per-mount structure.
4142 *
4143 * We only overwrite these fields, which are likely to change:
4144 * f_blocks
4145 * f_bfree
4146 * f_bavail
4147 * f_bused
4148 * f_files
4149 * f_ffree
4150 *
4151 * And these which are not, but which the FS has no other way
4152 * of providing to us:
4153 * f_bsize
4154 * f_iosize
4155 * f_fssubtype
4156 *
4157 */
4158 if (VFSATTR_IS_SUPPORTED(&va, f_bsize)) {
4159 /* 4822056 - protect against malformed server mount */
4160 mp->mnt_vfsstat.f_bsize = (va.f_bsize > 0 ? va.f_bsize : 512);
4161 } else {
4162 mp->mnt_vfsstat.f_bsize = mp->mnt_devblocksize; /* default from the device block size */
4163 }
4164 if (VFSATTR_IS_SUPPORTED(&va, f_iosize)) {
4165 mp->mnt_vfsstat.f_iosize = va.f_iosize;
4166 } else {
4167 mp->mnt_vfsstat.f_iosize = 1024 * 1024; /* 1MB sensible I/O size */
4168 }
4169 if (VFSATTR_IS_SUPPORTED(&va, f_blocks))
4170 mp->mnt_vfsstat.f_blocks = va.f_blocks;
4171 if (VFSATTR_IS_SUPPORTED(&va, f_bfree))
4172 mp->mnt_vfsstat.f_bfree = va.f_bfree;
4173 if (VFSATTR_IS_SUPPORTED(&va, f_bavail))
4174 mp->mnt_vfsstat.f_bavail = va.f_bavail;
4175 if (VFSATTR_IS_SUPPORTED(&va, f_bused))
4176 mp->mnt_vfsstat.f_bused = va.f_bused;
4177 if (VFSATTR_IS_SUPPORTED(&va, f_files))
4178 mp->mnt_vfsstat.f_files = va.f_files;
4179 if (VFSATTR_IS_SUPPORTED(&va, f_ffree))
4180 mp->mnt_vfsstat.f_ffree = va.f_ffree;
4181
4182 /* this is unlikely to change, but has to be queried for */
4183 if (VFSATTR_IS_SUPPORTED(&va, f_fssubtype))
4184 mp->mnt_vfsstat.f_fssubtype = va.f_fssubtype;
4185
4186 return(0);
4187 }
4188
4189 void
4190 mount_list_add(mount_t mp)
4191 {
4192 mount_list_lock();
4193 TAILQ_INSERT_TAIL(&mountlist, mp, mnt_list);
4194 nummounts++;
4195 mount_list_unlock();
4196 }
4197
4198 void
4199 mount_list_remove(mount_t mp)
4200 {
4201 mount_list_lock();
4202 TAILQ_REMOVE(&mountlist, mp, mnt_list);
4203 nummounts--;
4204 mp->mnt_list.tqe_next = NULL;
4205 mp->mnt_list.tqe_prev = NULL;
4206 mount_list_unlock();
4207 }
4208
4209 #if CONFIG_VOLFS
4210 mount_t
4211 mount_lookupby_volfsid(int volfs_id, int withref)
4212 {
4213 mount_t cur_mount = (mount_t)0;
4214 mount_t mp;
4215
4216 mount_list_lock();
4217 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
4218 if (!(mp->mnt_kern_flag & MNTK_UNMOUNT) &&
4219 (mp->mnt_kern_flag & MNTK_PATH_FROM_ID) &&
4220 (mp->mnt_vfsstat.f_fsid.val[0] == volfs_id)) {
4221 cur_mount = mp;
4222 if (withref) {
4223 if (mount_iterref(cur_mount, 1)) {
4224 cur_mount = (mount_t)0;
4225 mount_list_unlock();
4226 goto out;
4227 }
4228 }
4229 break;
4230 }
4231 }
4232 mount_list_unlock();
4233 if (withref && (cur_mount != (mount_t)0)) {
4234 mp = cur_mount;
4235 if (vfs_busy(mp, LK_NOWAIT) != 0) {
4236 cur_mount = (mount_t)0;
4237 }
4238 mount_iterdrop(mp);
4239 }
4240 out:
4241 return(cur_mount);
4242 }
4243 #endif
4244
4245
4246 mount_t
4247 mount_list_lookupby_fsid(fsid_t *fsid, int locked, int withref)
4248 {
4249 mount_t retmp = (mount_t)0;
4250 mount_t mp;
4251
4252 if (!locked)
4253 mount_list_lock();
4254 TAILQ_FOREACH(mp, &mountlist, mnt_list)
4255 if (mp->mnt_vfsstat.f_fsid.val[0] == fsid->val[0] &&
4256 mp->mnt_vfsstat.f_fsid.val[1] == fsid->val[1]) {
4257 retmp = mp;
4258 if (withref) {
4259 if (mount_iterref(retmp, 1))
4260 retmp = (mount_t)0;
4261 }
4262 goto out;
4263 }
4264 out:
4265 if (!locked)
4266 mount_list_unlock();
4267 return (retmp);
4268 }
4269
4270 errno_t
4271 vnode_lookup(const char *path, int flags, vnode_t *vpp, vfs_context_t ctx)
4272 {
4273 struct nameidata nd;
4274 int error;
4275 u_long ndflags = 0;
4276
4277 if (ctx == NULL) { /* XXX technically an error */
4278 ctx = vfs_context_current();
4279 }
4280
4281 if (flags & VNODE_LOOKUP_NOFOLLOW)
4282 ndflags = NOFOLLOW;
4283 else
4284 ndflags = FOLLOW;
4285
4286 if (flags & VNODE_LOOKUP_NOCROSSMOUNT)
4287 ndflags |= NOCROSSMOUNT;
4288 if (flags & VNODE_LOOKUP_DOWHITEOUT)
4289 ndflags |= DOWHITEOUT;
4290
4291 /* XXX AUDITVNPATH1 needed ? */
4292 NDINIT(&nd, LOOKUP, ndflags, UIO_SYSSPACE, CAST_USER_ADDR_T(path), ctx);
4293
4294 if ((error = namei(&nd)))
4295 return (error);
4296 *vpp = nd.ni_vp;
4297 nameidone(&nd);
4298
4299 return (0);
4300 }
4301
4302 errno_t
4303 vnode_open(const char *path, int fmode, int cmode, int flags, vnode_t *vpp, vfs_context_t ctx)
4304 {
4305 struct nameidata nd;
4306 int error;
4307 u_long ndflags = 0;
4308 int lflags = flags;
4309
4310 if (ctx == NULL) { /* XXX technically an error */
4311 ctx = vfs_context_current();
4312 }
4313
4314 if (fmode & O_NOFOLLOW)
4315 lflags |= VNODE_LOOKUP_NOFOLLOW;
4316
4317 if (lflags & VNODE_LOOKUP_NOFOLLOW)
4318 ndflags = NOFOLLOW;
4319 else
4320 ndflags = FOLLOW;
4321
4322 if (lflags & VNODE_LOOKUP_NOCROSSMOUNT)
4323 ndflags |= NOCROSSMOUNT;
4324 if (lflags & VNODE_LOOKUP_DOWHITEOUT)
4325 ndflags |= DOWHITEOUT;
4326
4327 /* XXX AUDITVNPATH1 needed ? */
4328 NDINIT(&nd, LOOKUP, ndflags, UIO_SYSSPACE, CAST_USER_ADDR_T(path), ctx);
4329
4330 if ((error = vn_open(&nd, fmode, cmode)))
4331 *vpp = NULL;
4332 else
4333 *vpp = nd.ni_vp;
4334
4335 return (error);
4336 }
4337
4338 errno_t
4339 vnode_close(vnode_t vp, int flags, vfs_context_t ctx)
4340 {
4341 int error;
4342
4343 if (ctx == NULL) {
4344 ctx = vfs_context_current();
4345 }
4346
4347 error = vn_close(vp, flags, ctx);
4348 vnode_put(vp);
4349 return (error);
4350 }
4351
4352 /*
4353 * Returns: 0 Success
4354 * vnode_getattr:???
4355 */
4356 errno_t
4357 vnode_size(vnode_t vp, off_t *sizep, vfs_context_t ctx)
4358 {
4359 struct vnode_attr va;
4360 int error;
4361
4362 VATTR_INIT(&va);
4363 VATTR_WANTED(&va, va_data_size);
4364 error = vnode_getattr(vp, &va, ctx);
4365 if (!error)
4366 *sizep = va.va_data_size;
4367 return(error);
4368 }
4369
4370 errno_t
4371 vnode_setsize(vnode_t vp, off_t size, int ioflag, vfs_context_t ctx)
4372 {
4373 struct vnode_attr va;
4374
4375 VATTR_INIT(&va);
4376 VATTR_SET(&va, va_data_size, size);
4377 va.va_vaflags = ioflag & 0xffff;
4378 return(vnode_setattr(vp, &va, ctx));
4379 }
4380
4381 /*
4382 * Create a filesystem object of arbitrary type with arbitrary attributes in
4383 * the spevied directory with the specified name.
4384 *
4385 * Parameters: dvp Pointer to the vnode of the directory
4386 * in which to create the object.
4387 * vpp Pointer to the area into which to
4388 * return the vnode of the created object.
4389 * cnp Component name pointer from the namei
4390 * data structure, containing the name to
4391 * use for the create object.
4392 * vap Pointer to the vnode_attr structure
4393 * describing the object to be created,
4394 * including the type of object.
4395 * flags VN_* flags controlling ACL inheritance
4396 * and whether or not authorization is to
4397 * be required for the operation.
4398 *
4399 * Returns: 0 Success
4400 * !0 errno value
4401 *
4402 * Implicit: *vpp Contains the vnode of the object that
4403 * was created, if successful.
4404 * *cnp May be modified by the underlying VFS.
4405 * *vap May be modified by the underlying VFS.
4406 * modified by either ACL inheritance or
4407 *
4408 *
4409 * be modified, even if the operation is
4410 *
4411 *
4412 * Notes: The kauth_filesec_t in 'vap', if any, is in host byte order.
4413 *
4414 * Modification of '*cnp' and '*vap' by the underlying VFS is
4415 * strongly discouraged.
4416 *
4417 * XXX: This function is a 'vn_*' function; it belongs in vfs_vnops.c
4418 *
4419 * XXX: We should enummerate the possible errno values here, and where
4420 * in the code they originated.
4421 */
4422 errno_t
4423 vn_create(vnode_t dvp, vnode_t *vpp, struct componentname *cnp, struct vnode_attr *vap, int flags, vfs_context_t ctx)
4424 {
4425 kauth_acl_t oacl, nacl;
4426 int initial_acl;
4427 errno_t error;
4428 vnode_t vp = (vnode_t)0;
4429
4430 error = 0;
4431 oacl = nacl = NULL;
4432 initial_acl = 0;
4433
4434 KAUTH_DEBUG("%p CREATE - '%s'", dvp, cnp->cn_nameptr);
4435
4436 /*
4437 * Handle ACL inheritance.
4438 */
4439 if (!(flags & VN_CREATE_NOINHERIT) && vfs_extendedsecurity(dvp->v_mount)) {
4440 /* save the original filesec */
4441 if (VATTR_IS_ACTIVE(vap, va_acl)) {
4442 initial_acl = 1;
4443 oacl = vap->va_acl;
4444 }
4445
4446 vap->va_acl = NULL;
4447 if ((error = kauth_acl_inherit(dvp,
4448 oacl,
4449 &nacl,
4450 vap->va_type == VDIR,
4451 ctx)) != 0) {
4452 KAUTH_DEBUG("%p CREATE - error %d processing inheritance", dvp, error);
4453 return(error);
4454 }
4455
4456 /*
4457 * If the generated ACL is NULL, then we can save ourselves some effort
4458 * by clearing the active bit.
4459 */
4460 if (nacl == NULL) {
4461 VATTR_CLEAR_ACTIVE(vap, va_acl);
4462 } else {
4463 VATTR_SET(vap, va_acl, nacl);
4464 }
4465 }
4466
4467 /*
4468 * Check and default new attributes.
4469 * This will set va_uid, va_gid, va_mode and va_create_time at least, if the caller
4470 * hasn't supplied them.
4471 */
4472 if ((error = vnode_authattr_new(dvp, vap, flags & VN_CREATE_NOAUTH, ctx)) != 0) {
4473 KAUTH_DEBUG("%p CREATE - error %d handing/defaulting attributes", dvp, error);
4474 goto out;
4475 }
4476
4477
4478 /*
4479 * Create the requested node.
4480 */
4481 switch(vap->va_type) {
4482 case VREG:
4483 error = VNOP_CREATE(dvp, vpp, cnp, vap, ctx);
4484 break;
4485 case VDIR:
4486 error = VNOP_MKDIR(dvp, vpp, cnp, vap, ctx);
4487 break;
4488 case VSOCK:
4489 case VFIFO:
4490 case VBLK:
4491 case VCHR:
4492 error = VNOP_MKNOD(dvp, vpp, cnp, vap, ctx);
4493 break;
4494 default:
4495 panic("vnode_create: unknown vtype %d", vap->va_type);
4496 }
4497 if (error != 0) {
4498 KAUTH_DEBUG("%p CREATE - error %d returned by filesystem", dvp, error);
4499 goto out;
4500 }
4501
4502 vp = *vpp;
4503 #if CONFIG_MACF
4504 if (!(flags & VN_CREATE_NOLABEL)) {
4505 error = vnode_label(vnode_mount(vp), dvp, vp, cnp,
4506 VNODE_LABEL_CREATE|VNODE_LABEL_NEEDREF, ctx);
4507 if (error)
4508 goto error;
4509 }
4510 #endif
4511
4512 /*
4513 * If some of the requested attributes weren't handled by the VNOP,
4514 * use our fallback code.
4515 */
4516 if (!VATTR_ALL_SUPPORTED(vap) && *vpp) {
4517 KAUTH_DEBUG(" CREATE - doing fallback with ACL %p", vap->va_acl);
4518 error = vnode_setattr_fallback(*vpp, vap, ctx);
4519 }
4520 #if CONFIG_MACF
4521 error:
4522 #endif
4523 if ((error != 0 ) && (vp != (vnode_t)0)) {
4524 *vpp = (vnode_t) 0;
4525 vnode_put(vp);
4526 }
4527
4528 out:
4529 /*
4530 * If the caller supplied a filesec in vap, it has been replaced
4531 * now by the post-inheritance copy. We need to put the original back
4532 * and free the inherited product.
4533 */
4534 if (initial_acl) {
4535 VATTR_SET(vap, va_acl, oacl);
4536 } else {
4537 VATTR_CLEAR_ACTIVE(vap, va_acl);
4538 }
4539 if (nacl != NULL)
4540 kauth_acl_free(nacl);
4541
4542 return(error);
4543 }
4544
4545 static kauth_scope_t vnode_scope;
4546 static int vnode_authorize_callback(kauth_cred_t credential, void *idata, kauth_action_t action,
4547 uintptr_t arg0, uintptr_t arg1, uintptr_t arg2, uintptr_t arg3);
4548 static int vnode_authorize_callback_int(__unused kauth_cred_t credential, __unused void *idata, kauth_action_t action,
4549 uintptr_t arg0, uintptr_t arg1, uintptr_t arg2, uintptr_t arg3);
4550
4551 typedef struct _vnode_authorize_context {
4552 vnode_t vp;
4553 struct vnode_attr *vap;
4554 vnode_t dvp;
4555 struct vnode_attr *dvap;
4556 vfs_context_t ctx;
4557 int flags;
4558 int flags_valid;
4559 #define _VAC_IS_OWNER (1<<0)
4560 #define _VAC_IN_GROUP (1<<1)
4561 #define _VAC_IS_DIR_OWNER (1<<2)
4562 #define _VAC_IN_DIR_GROUP (1<<3)
4563 } *vauth_ctx;
4564
4565 void
4566 vnode_authorize_init(void)
4567 {
4568 vnode_scope = kauth_register_scope(KAUTH_SCOPE_VNODE, vnode_authorize_callback, NULL);
4569 }
4570
4571 /*
4572 * Authorize an operation on a vnode.
4573 *
4574 * This is KPI, but here because it needs vnode_scope.
4575 *
4576 * Returns: 0 Success
4577 * kauth_authorize_action:EPERM ...
4578 * xlate => EACCES Permission denied
4579 * kauth_authorize_action:0 Success
4580 * kauth_authorize_action: Depends on callback return; this is
4581 * usually only vnode_authorize_callback(),
4582 * but may include other listerners, if any
4583 * exist.
4584 * EROFS
4585 * EACCES
4586 * EPERM
4587 * ???
4588 */
4589 int
4590 vnode_authorize(vnode_t vp, vnode_t dvp, kauth_action_t action, vfs_context_t ctx)
4591 {
4592 int error, result;
4593
4594 /*
4595 * We can't authorize against a dead vnode; allow all operations through so that
4596 * the correct error can be returned.
4597 */
4598 if (vp->v_type == VBAD)
4599 return(0);
4600
4601 error = 0;
4602 result = kauth_authorize_action(vnode_scope, vfs_context_ucred(ctx), action,
4603 (uintptr_t)ctx, (uintptr_t)vp, (uintptr_t)dvp, (uintptr_t)&error);
4604 if (result == EPERM) /* traditional behaviour */
4605 result = EACCES;
4606 /* did the lower layers give a better error return? */
4607 if ((result != 0) && (error != 0))
4608 return(error);
4609 return(result);
4610 }
4611
4612 /*
4613 * Test for vnode immutability.
4614 *
4615 * The 'append' flag is set when the authorization request is constrained
4616 * to operations which only request the right to append to a file.
4617 *
4618 * The 'ignore' flag is set when an operation modifying the immutability flags
4619 * is being authorized. We check the system securelevel to determine which
4620 * immutability flags we can ignore.
4621 */
4622 static int
4623 vnode_immutable(struct vnode_attr *vap, int append, int ignore)
4624 {
4625 int mask;
4626
4627 /* start with all bits precluding the operation */
4628 mask = IMMUTABLE | APPEND;
4629
4630 /* if appending only, remove the append-only bits */
4631 if (append)
4632 mask &= ~APPEND;
4633
4634 /* ignore only set when authorizing flags changes */
4635 if (ignore) {
4636 if (securelevel <= 0) {
4637 /* in insecure state, flags do not inhibit changes */
4638 mask = 0;
4639 } else {
4640 /* in secure state, user flags don't inhibit */
4641 mask &= ~(UF_IMMUTABLE | UF_APPEND);
4642 }
4643 }
4644 KAUTH_DEBUG("IMMUTABLE - file flags 0x%x mask 0x%x append = %d ignore = %d", vap->va_flags, mask, append, ignore);
4645 if ((vap->va_flags & mask) != 0)
4646 return(EPERM);
4647 return(0);
4648 }
4649
4650 static int
4651 vauth_node_owner(struct vnode_attr *vap, kauth_cred_t cred)
4652 {
4653 int result;
4654
4655 /* default assumption is not-owner */
4656 result = 0;
4657
4658 /*
4659 * If the filesystem has given us a UID, we treat this as authoritative.
4660 */
4661 if (vap && VATTR_IS_SUPPORTED(vap, va_uid)) {
4662 result = (vap->va_uid == kauth_cred_getuid(cred)) ? 1 : 0;
4663 }
4664 /* we could test the owner UUID here if we had a policy for it */
4665
4666 return(result);
4667 }
4668
4669 static int
4670 vauth_node_group(struct vnode_attr *vap, kauth_cred_t cred, int *ismember)
4671 {
4672 int error;
4673 int result;
4674
4675 error = 0;
4676 result = 0;
4677
4678 /* the caller is expected to have asked the filesystem for a group at some point */
4679 if (vap && VATTR_IS_SUPPORTED(vap, va_gid)) {
4680 error = kauth_cred_ismember_gid(cred, vap->va_gid, &result);
4681 }
4682 /* we could test the group UUID here if we had a policy for it */
4683
4684 if (!error)
4685 *ismember = result;
4686 return(error);
4687 }
4688
4689 static int
4690 vauth_file_owner(vauth_ctx vcp)
4691 {
4692 int result;
4693
4694 if (vcp->flags_valid & _VAC_IS_OWNER) {
4695 result = (vcp->flags & _VAC_IS_OWNER) ? 1 : 0;
4696 } else {
4697 result = vauth_node_owner(vcp->vap, vcp->ctx->vc_ucred);
4698
4699 /* cache our result */
4700 vcp->flags_valid |= _VAC_IS_OWNER;
4701 if (result) {
4702 vcp->flags |= _VAC_IS_OWNER;
4703 } else {
4704 vcp->flags &= ~_VAC_IS_OWNER;
4705 }
4706 }
4707 return(result);
4708 }
4709
4710 static int
4711 vauth_file_ingroup(vauth_ctx vcp, int *ismember)
4712 {
4713 int error;
4714
4715 if (vcp->flags_valid & _VAC_IN_GROUP) {
4716 *ismember = (vcp->flags & _VAC_IN_GROUP) ? 1 : 0;
4717 error = 0;
4718 } else {
4719 error = vauth_node_group(vcp->vap, vcp->ctx->vc_ucred, ismember);
4720
4721 if (!error) {
4722 /* cache our result */
4723 vcp->flags_valid |= _VAC_IN_GROUP;
4724 if (*ismember) {
4725 vcp->flags |= _VAC_IN_GROUP;
4726 } else {
4727 vcp->flags &= ~_VAC_IN_GROUP;
4728 }
4729 }
4730
4731 }
4732 return(error);
4733 }
4734
4735 static int
4736 vauth_dir_owner(vauth_ctx vcp)
4737 {
4738 int result;
4739
4740 if (vcp->flags_valid & _VAC_IS_DIR_OWNER) {
4741 result = (vcp->flags & _VAC_IS_DIR_OWNER) ? 1 : 0;
4742 } else {
4743 result = vauth_node_owner(vcp->dvap, vcp->ctx->vc_ucred);
4744
4745 /* cache our result */
4746 vcp->flags_valid |= _VAC_IS_DIR_OWNER;
4747 if (result) {
4748 vcp->flags |= _VAC_IS_DIR_OWNER;
4749 } else {
4750 vcp->flags &= ~_VAC_IS_DIR_OWNER;
4751 }
4752 }
4753 return(result);
4754 }
4755
4756 static int
4757 vauth_dir_ingroup(vauth_ctx vcp, int *ismember)
4758 {
4759 int error;
4760
4761 if (vcp->flags_valid & _VAC_IN_DIR_GROUP) {
4762 *ismember = (vcp->flags & _VAC_IN_DIR_GROUP) ? 1 : 0;
4763 error = 0;
4764 } else {
4765 error = vauth_node_group(vcp->dvap, vcp->ctx->vc_ucred, ismember);
4766
4767 if (!error) {
4768 /* cache our result */
4769 vcp->flags_valid |= _VAC_IN_DIR_GROUP;
4770 if (*ismember) {
4771 vcp->flags |= _VAC_IN_DIR_GROUP;
4772 } else {
4773 vcp->flags &= ~_VAC_IN_DIR_GROUP;
4774 }
4775 }
4776 }
4777 return(error);
4778 }
4779
4780 /*
4781 * Test the posix permissions in (vap) to determine whether (credential)
4782 * may perform (action)
4783 */
4784 static int
4785 vnode_authorize_posix(vauth_ctx vcp, int action, int on_dir)
4786 {
4787 struct vnode_attr *vap;
4788 int needed, error, owner_ok, group_ok, world_ok, ismember;
4789 #ifdef KAUTH_DEBUG_ENABLE
4790 const char *where = "uninitialized";
4791 # define _SETWHERE(c) where = c;
4792 #else
4793 # define _SETWHERE(c)
4794 #endif
4795
4796 /* checking file or directory? */
4797 if (on_dir) {
4798 vap = vcp->dvap;
4799 } else {
4800 vap = vcp->vap;
4801 }
4802
4803 error = 0;
4804
4805 /*
4806 * We want to do as little work here as possible. So first we check
4807 * which sets of permissions grant us the access we need, and avoid checking
4808 * whether specific permissions grant access when more generic ones would.
4809 */
4810
4811 /* owner permissions */
4812 needed = 0;
4813 if (action & VREAD)
4814 needed |= S_IRUSR;
4815 if (action & VWRITE)
4816 needed |= S_IWUSR;
4817 if (action & VEXEC)
4818 needed |= S_IXUSR;
4819 owner_ok = (needed & vap->va_mode) == needed;
4820
4821 /* group permissions */
4822 needed = 0;
4823 if (action & VREAD)
4824 needed |= S_IRGRP;
4825 if (action & VWRITE)
4826 needed |= S_IWGRP;
4827 if (action & VEXEC)
4828 needed |= S_IXGRP;
4829 group_ok = (needed & vap->va_mode) == needed;
4830
4831 /* world permissions */
4832 needed = 0;
4833 if (action & VREAD)
4834 needed |= S_IROTH;
4835 if (action & VWRITE)
4836 needed |= S_IWOTH;
4837 if (action & VEXEC)
4838 needed |= S_IXOTH;
4839 world_ok = (needed & vap->va_mode) == needed;
4840
4841 /* If granted/denied by all three, we're done */
4842 if (owner_ok && group_ok && world_ok) {
4843 _SETWHERE("all");
4844 goto out;
4845 }
4846 if (!owner_ok && !group_ok && !world_ok) {
4847 _SETWHERE("all");
4848 error = EACCES;
4849 goto out;
4850 }
4851
4852 /* Check ownership (relatively cheap) */
4853 if ((on_dir && vauth_dir_owner(vcp)) ||
4854 (!on_dir && vauth_file_owner(vcp))) {
4855 _SETWHERE("user");
4856 if (!owner_ok)
4857 error = EACCES;
4858 goto out;
4859 }
4860
4861 /* Not owner; if group and world both grant it we're done */
4862 if (group_ok && world_ok) {
4863 _SETWHERE("group/world");
4864 goto out;
4865 }
4866 if (!group_ok && !world_ok) {
4867 _SETWHERE("group/world");
4868 error = EACCES;
4869 goto out;
4870 }
4871
4872 /* Check group membership (most expensive) */
4873 ismember = 0;
4874 if (on_dir) {
4875 error = vauth_dir_ingroup(vcp, &ismember);
4876 } else {
4877 error = vauth_file_ingroup(vcp, &ismember);
4878 }
4879 if (error)
4880 goto out;
4881 if (ismember) {
4882 _SETWHERE("group");
4883 if (!group_ok)
4884 error = EACCES;
4885 goto out;
4886 }
4887
4888 /* Not owner, not in group, use world result */
4889 _SETWHERE("world");
4890 if (!world_ok)
4891 error = EACCES;
4892
4893 /* FALLTHROUGH */
4894
4895 out:
4896 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",
4897 vcp->vp, (error == 0) ? "ALLOWED" : "DENIED", where,
4898 (action & VREAD) ? "r" : "-",
4899 (action & VWRITE) ? "w" : "-",
4900 (action & VEXEC) ? "x" : "-",
4901 needed,
4902 (vap->va_mode & S_IRUSR) ? "r" : "-",
4903 (vap->va_mode & S_IWUSR) ? "w" : "-",
4904 (vap->va_mode & S_IXUSR) ? "x" : "-",
4905 (vap->va_mode & S_IRGRP) ? "r" : "-",
4906 (vap->va_mode & S_IWGRP) ? "w" : "-",
4907 (vap->va_mode & S_IXGRP) ? "x" : "-",
4908 (vap->va_mode & S_IROTH) ? "r" : "-",
4909 (vap->va_mode & S_IWOTH) ? "w" : "-",
4910 (vap->va_mode & S_IXOTH) ? "x" : "-",
4911 kauth_cred_getuid(vcp->ctx->vc_ucred),
4912 on_dir ? vcp->dvap->va_uid : vcp->vap->va_uid,
4913 on_dir ? vcp->dvap->va_gid : vcp->vap->va_gid);
4914 return(error);
4915 }
4916
4917 /*
4918 * Authorize the deletion of the node vp from the directory dvp.
4919 *
4920 * We assume that:
4921 * - Neither the node nor the directory are immutable.
4922 * - The user is not the superuser.
4923 *
4924 * Deletion is not permitted if the directory is sticky and the caller is not owner of the
4925 * node or directory.
4926 *
4927 * If either the node grants DELETE, or the directory grants DELETE_CHILD, the node may be
4928 * deleted. If neither denies the permission, and the caller has Posix write access to the
4929 * directory, then the node may be deleted.
4930 */
4931 static int
4932 vnode_authorize_delete(vauth_ctx vcp)
4933 {
4934 struct vnode_attr *vap = vcp->vap;
4935 struct vnode_attr *dvap = vcp->dvap;
4936 kauth_cred_t cred = vcp->ctx->vc_ucred;
4937 struct kauth_acl_eval eval;
4938 int error, delete_denied, delete_child_denied, ismember;
4939
4940 /* check the ACL on the directory */
4941 delete_child_denied = 0;
4942 if (VATTR_IS_NOT(dvap, va_acl, NULL)) {
4943 eval.ae_requested = KAUTH_VNODE_DELETE_CHILD;
4944 eval.ae_acl = &dvap->va_acl->acl_ace[0];
4945 eval.ae_count = dvap->va_acl->acl_entrycount;
4946 eval.ae_options = 0;
4947 if (vauth_dir_owner(vcp))
4948 eval.ae_options |= KAUTH_AEVAL_IS_OWNER;
4949 if ((error = vauth_dir_ingroup(vcp, &ismember)) != 0)
4950 return(error);
4951 if (ismember)
4952 eval.ae_options |= KAUTH_AEVAL_IN_GROUP;
4953 eval.ae_exp_gall = KAUTH_VNODE_GENERIC_ALL_BITS;
4954 eval.ae_exp_gread = KAUTH_VNODE_GENERIC_READ_BITS;
4955 eval.ae_exp_gwrite = KAUTH_VNODE_GENERIC_WRITE_BITS;
4956 eval.ae_exp_gexec = KAUTH_VNODE_GENERIC_EXECUTE_BITS;
4957
4958 error = kauth_acl_evaluate(cred, &eval);
4959
4960 if (error != 0) {
4961 KAUTH_DEBUG("%p ERROR during ACL processing - %d", vcp->vp, error);
4962 return(error);
4963 }
4964 if (eval.ae_result == KAUTH_RESULT_DENY)
4965 delete_child_denied = 1;
4966 if (eval.ae_result == KAUTH_RESULT_ALLOW) {
4967 KAUTH_DEBUG("%p ALLOWED - granted by directory ACL", vcp->vp);
4968 return(0);
4969 }
4970 }
4971
4972 /* check the ACL on the node */
4973 delete_denied = 0;
4974 if (VATTR_IS_NOT(vap, va_acl, NULL)) {
4975 eval.ae_requested = KAUTH_VNODE_DELETE;
4976 eval.ae_acl = &vap->va_acl->acl_ace[0];
4977 eval.ae_count = vap->va_acl->acl_entrycount;
4978 eval.ae_options = 0;
4979 if (vauth_file_owner(vcp))
4980 eval.ae_options |= KAUTH_AEVAL_IS_OWNER;
4981 if ((error = vauth_file_ingroup(vcp, &ismember)) != 0)
4982 return(error);
4983 if (ismember)
4984 eval.ae_options |= KAUTH_AEVAL_IN_GROUP;
4985 eval.ae_exp_gall = KAUTH_VNODE_GENERIC_ALL_BITS;
4986 eval.ae_exp_gread = KAUTH_VNODE_GENERIC_READ_BITS;
4987 eval.ae_exp_gwrite = KAUTH_VNODE_GENERIC_WRITE_BITS;
4988 eval.ae_exp_gexec = KAUTH_VNODE_GENERIC_EXECUTE_BITS;
4989
4990 if ((error = kauth_acl_evaluate(cred, &eval)) != 0) {
4991 KAUTH_DEBUG("%p ERROR during ACL processing - %d", vcp->vp, error);
4992 return(error);
4993 }
4994 if (eval.ae_result == KAUTH_RESULT_DENY)
4995 delete_denied = 1;
4996 if (eval.ae_result == KAUTH_RESULT_ALLOW) {
4997 KAUTH_DEBUG("%p ALLOWED - granted by file ACL", vcp->vp);
4998 return(0);
4999 }
5000 }
5001
5002 /* if denied by ACL on directory or node, return denial */
5003 if (delete_denied || delete_child_denied) {
5004 KAUTH_DEBUG("%p ALLOWED - denied by ACL", vcp->vp);
5005 return(EACCES);
5006 }
5007
5008 /* enforce sticky bit behaviour */
5009 if ((dvap->va_mode & S_ISTXT) && !vauth_file_owner(vcp) && !vauth_dir_owner(vcp)) {
5010 KAUTH_DEBUG("%p DENIED - sticky bit rules (user %d file %d dir %d)",
5011 vcp->vp, cred->cr_uid, vap->va_uid, dvap->va_uid);
5012 return(EACCES);
5013 }
5014
5015 /* check the directory */
5016 if ((error = vnode_authorize_posix(vcp, VWRITE, 1 /* on_dir */)) != 0) {
5017 KAUTH_DEBUG("%p ALLOWED - granted by posix permisssions", vcp->vp);
5018 return(error);
5019 }
5020
5021 /* not denied, must be OK */
5022 return(0);
5023 }
5024
5025
5026 /*
5027 * Authorize an operation based on the node's attributes.
5028 */
5029 static int
5030 vnode_authorize_simple(vauth_ctx vcp, kauth_ace_rights_t acl_rights, kauth_ace_rights_t preauth_rights, boolean_t *found_deny)
5031 {
5032 struct vnode_attr *vap = vcp->vap;
5033 kauth_cred_t cred = vcp->ctx->vc_ucred;
5034 struct kauth_acl_eval eval;
5035 int error, ismember;
5036 mode_t posix_action;
5037
5038 /*
5039 * If we are the file owner, we automatically have some rights.
5040 *
5041 * Do we need to expand this to support group ownership?
5042 */
5043 if (vauth_file_owner(vcp))
5044 acl_rights &= ~(KAUTH_VNODE_WRITE_SECURITY);
5045
5046 /*
5047 * If we are checking both TAKE_OWNERSHIP and WRITE_SECURITY, we can
5048 * mask the latter. If TAKE_OWNERSHIP is requested the caller is about to
5049 * change ownership to themselves, and WRITE_SECURITY is implicitly
5050 * granted to the owner. We need to do this because at this point
5051 * WRITE_SECURITY may not be granted as the caller is not currently
5052 * the owner.
5053 */
5054 if ((acl_rights & KAUTH_VNODE_TAKE_OWNERSHIP) &&
5055 (acl_rights & KAUTH_VNODE_WRITE_SECURITY))
5056 acl_rights &= ~KAUTH_VNODE_WRITE_SECURITY;
5057
5058 if (acl_rights == 0) {
5059 KAUTH_DEBUG("%p ALLOWED - implicit or no rights required", vcp->vp);
5060 return(0);
5061 }
5062
5063 /* if we have an ACL, evaluate it */
5064 if (VATTR_IS_NOT(vap, va_acl, NULL)) {
5065 eval.ae_requested = acl_rights;
5066 eval.ae_acl = &vap->va_acl->acl_ace[0];
5067 eval.ae_count = vap->va_acl->acl_entrycount;
5068 eval.ae_options = 0;
5069 if (vauth_file_owner(vcp))
5070 eval.ae_options |= KAUTH_AEVAL_IS_OWNER;
5071 if ((error = vauth_file_ingroup(vcp, &ismember)) != 0)
5072 return(error);
5073 if (ismember)
5074 eval.ae_options |= KAUTH_AEVAL_IN_GROUP;
5075 eval.ae_exp_gall = KAUTH_VNODE_GENERIC_ALL_BITS;
5076 eval.ae_exp_gread = KAUTH_VNODE_GENERIC_READ_BITS;
5077 eval.ae_exp_gwrite = KAUTH_VNODE_GENERIC_WRITE_BITS;
5078 eval.ae_exp_gexec = KAUTH_VNODE_GENERIC_EXECUTE_BITS;
5079
5080 if ((error = kauth_acl_evaluate(cred, &eval)) != 0) {
5081 KAUTH_DEBUG("%p ERROR during ACL processing - %d", vcp->vp, error);
5082 return(error);
5083 }
5084
5085 if (eval.ae_result == KAUTH_RESULT_DENY) {
5086 KAUTH_DEBUG("%p DENIED - by ACL", vcp->vp);
5087 return(EACCES); /* deny, deny, counter-allege */
5088 }
5089 if (eval.ae_result == KAUTH_RESULT_ALLOW) {
5090 KAUTH_DEBUG("%p ALLOWED - all rights granted by ACL", vcp->vp);
5091 return(0);
5092 }
5093 *found_deny = eval.ae_found_deny;
5094
5095 /* fall through and evaluate residual rights */
5096 } else {
5097 /* no ACL, everything is residual */
5098 eval.ae_residual = acl_rights;
5099 }
5100
5101 /*
5102 * Grant residual rights that have been pre-authorized.
5103 */
5104 eval.ae_residual &= ~preauth_rights;
5105
5106 /*
5107 * We grant WRITE_ATTRIBUTES to the owner if it hasn't been denied.
5108 */
5109 if (vauth_file_owner(vcp))
5110 eval.ae_residual &= ~KAUTH_VNODE_WRITE_ATTRIBUTES;
5111
5112 if (eval.ae_residual == 0) {
5113 KAUTH_DEBUG("%p ALLOWED - rights already authorized", vcp->vp);
5114 return(0);
5115 }
5116
5117 /*
5118 * Bail if we have residual rights that can't be granted by posix permissions,
5119 * or aren't presumed granted at this point.
5120 *
5121 * XXX these can be collapsed for performance
5122 */
5123 if (eval.ae_residual & KAUTH_VNODE_CHANGE_OWNER) {
5124 KAUTH_DEBUG("%p DENIED - CHANGE_OWNER not permitted", vcp->vp);
5125 return(EACCES);
5126 }
5127 if (eval.ae_residual & KAUTH_VNODE_WRITE_SECURITY) {
5128 KAUTH_DEBUG("%p DENIED - WRITE_SECURITY not permitted", vcp->vp);
5129 return(EACCES);
5130 }
5131
5132 #if DIAGNOSTIC
5133 if (eval.ae_residual & KAUTH_VNODE_DELETE)
5134 panic("vnode_authorize: can't be checking delete permission here");
5135 #endif
5136
5137 /*
5138 * Compute the fallback posix permissions that will satisfy the remaining
5139 * rights.
5140 */
5141 posix_action = 0;
5142 if (eval.ae_residual & (KAUTH_VNODE_READ_DATA |
5143 KAUTH_VNODE_LIST_DIRECTORY |
5144 KAUTH_VNODE_READ_EXTATTRIBUTES))
5145 posix_action |= VREAD;
5146 if (eval.ae_residual & (KAUTH_VNODE_WRITE_DATA |
5147 KAUTH_VNODE_ADD_FILE |
5148 KAUTH_VNODE_ADD_SUBDIRECTORY |
5149 KAUTH_VNODE_DELETE_CHILD |
5150 KAUTH_VNODE_WRITE_ATTRIBUTES |
5151 KAUTH_VNODE_WRITE_EXTATTRIBUTES))
5152 posix_action |= VWRITE;
5153 if (eval.ae_residual & (KAUTH_VNODE_EXECUTE |
5154 KAUTH_VNODE_SEARCH))
5155 posix_action |= VEXEC;
5156
5157 if (posix_action != 0) {
5158 return(vnode_authorize_posix(vcp, posix_action, 0 /* !on_dir */));
5159 } else {
5160 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",
5161 vcp->vp,
5162 (eval.ae_residual & KAUTH_VNODE_READ_DATA)
5163 ? vnode_isdir(vcp->vp) ? " LIST_DIRECTORY" : " READ_DATA" : "",
5164 (eval.ae_residual & KAUTH_VNODE_WRITE_DATA)
5165 ? vnode_isdir(vcp->vp) ? " ADD_FILE" : " WRITE_DATA" : "",
5166 (eval.ae_residual & KAUTH_VNODE_EXECUTE)
5167 ? vnode_isdir(vcp->vp) ? " SEARCH" : " EXECUTE" : "",
5168 (eval.ae_residual & KAUTH_VNODE_DELETE)
5169 ? " DELETE" : "",
5170 (eval.ae_residual & KAUTH_VNODE_APPEND_DATA)
5171 ? vnode_isdir(vcp->vp) ? " ADD_SUBDIRECTORY" : " APPEND_DATA" : "",
5172 (eval.ae_residual & KAUTH_VNODE_DELETE_CHILD)
5173 ? " DELETE_CHILD" : "",
5174 (eval.ae_residual & KAUTH_VNODE_READ_ATTRIBUTES)
5175 ? " READ_ATTRIBUTES" : "",
5176 (eval.ae_residual & KAUTH_VNODE_WRITE_ATTRIBUTES)
5177 ? " WRITE_ATTRIBUTES" : "",
5178 (eval.ae_residual & KAUTH_VNODE_READ_EXTATTRIBUTES)
5179 ? " READ_EXTATTRIBUTES" : "",
5180 (eval.ae_residual & KAUTH_VNODE_WRITE_EXTATTRIBUTES)
5181 ? " WRITE_EXTATTRIBUTES" : "",
5182 (eval.ae_residual & KAUTH_VNODE_READ_SECURITY)
5183 ? " READ_SECURITY" : "",
5184 (eval.ae_residual & KAUTH_VNODE_WRITE_SECURITY)
5185 ? " WRITE_SECURITY" : "",
5186 (eval.ae_residual & KAUTH_VNODE_CHECKIMMUTABLE)
5187 ? " CHECKIMMUTABLE" : "",
5188 (eval.ae_residual & KAUTH_VNODE_CHANGE_OWNER)
5189 ? " CHANGE_OWNER" : "");
5190 }
5191
5192 /*
5193 * Lack of required Posix permissions implies no reason to deny access.
5194 */
5195 return(0);
5196 }
5197
5198 /*
5199 * Check for file immutability.
5200 */
5201 static int
5202 vnode_authorize_checkimmutable(vnode_t vp, struct vnode_attr *vap, int rights, int ignore)
5203 {
5204 mount_t mp;
5205 int error;
5206 int append;
5207
5208 /*
5209 * Perform immutability checks for operations that change data.
5210 *
5211 * Sockets, fifos and devices require special handling.
5212 */
5213 switch(vp->v_type) {
5214 case VSOCK:
5215 case VFIFO:
5216 case VBLK:
5217 case VCHR:
5218 /*
5219 * Writing to these nodes does not change the filesystem data,
5220 * so forget that it's being tried.
5221 */
5222 rights &= ~KAUTH_VNODE_WRITE_DATA;
5223 break;
5224 default:
5225 break;
5226 }
5227
5228 error = 0;
5229 if (rights & KAUTH_VNODE_WRITE_RIGHTS) {
5230
5231 /* check per-filesystem options if possible */
5232 mp = vp->v_mount;
5233 if (mp != NULL) {
5234
5235 /* check for no-EA filesystems */
5236 if ((rights & KAUTH_VNODE_WRITE_EXTATTRIBUTES) &&
5237 (vfs_flags(mp) & MNT_NOUSERXATTR)) {
5238 KAUTH_DEBUG("%p DENIED - filesystem disallowed extended attributes", vp);
5239 error = EACCES; /* User attributes disabled */
5240 goto out;
5241 }
5242 }
5243
5244 /* check for file immutability */
5245 append = 0;
5246 if (vp->v_type == VDIR) {
5247 if ((rights & (KAUTH_VNODE_ADD_FILE | KAUTH_VNODE_ADD_SUBDIRECTORY)) == rights)
5248 append = 1;
5249 } else {
5250 if ((rights & KAUTH_VNODE_APPEND_DATA) == rights)
5251 append = 1;
5252 }
5253 if ((error = vnode_immutable(vap, append, ignore)) != 0) {
5254 KAUTH_DEBUG("%p DENIED - file is immutable", vp);
5255 goto out;
5256 }
5257 }
5258 out:
5259 return(error);
5260 }
5261
5262 /*
5263 * Handle authorization actions for filesystems that advertise that the
5264 * server will be enforcing.
5265 *
5266 * Returns: 0 Authorization should be handled locally
5267 * 1 Authorization was handled by the FS
5268 *
5269 * Note: Imputed returns will only occur if the authorization request
5270 * was handled by the FS.
5271 *
5272 * Imputed: *resultp, modified Return code from FS when the request is
5273 * handled by the FS.
5274 * VNOP_ACCESS:???
5275 * VNOP_OPEN:???
5276 */
5277 static int
5278 vnode_authorize_opaque(vnode_t vp, int *resultp, kauth_action_t action, vfs_context_t ctx)
5279 {
5280 int error;
5281
5282 /*
5283 * If the vp is a device node, socket or FIFO it actually represents a local
5284 * endpoint, so we need to handle it locally.
5285 */
5286 switch(vp->v_type) {
5287 case VBLK:
5288 case VCHR:
5289 case VSOCK:
5290 case VFIFO:
5291 return(0);
5292 default:
5293 break;
5294 }
5295
5296 /*
5297 * In the advisory request case, if the filesystem doesn't think it's reliable
5298 * we will attempt to formulate a result ourselves based on VNOP_GETATTR data.
5299 */
5300 if ((action & KAUTH_VNODE_ACCESS) && !vfs_authopaqueaccess(vp->v_mount))
5301 return(0);
5302
5303 /*
5304 * Let the filesystem have a say in the matter. It's OK for it to not implemnent
5305 * VNOP_ACCESS, as most will authorise inline with the actual request.
5306 */
5307 if ((error = VNOP_ACCESS(vp, action, ctx)) != ENOTSUP) {
5308 *resultp = error;
5309 KAUTH_DEBUG("%p DENIED - opaque filesystem VNOP_ACCESS denied access", vp);
5310 return(1);
5311 }
5312
5313 /*
5314 * Typically opaque filesystems do authorisation in-line, but exec is a special case. In
5315 * order to be reasonably sure that exec will be permitted, we try a bit harder here.
5316 */
5317 if ((action & KAUTH_VNODE_EXECUTE) && (vp->v_type == VREG)) {
5318 /* try a VNOP_OPEN for readonly access */
5319 if ((error = VNOP_OPEN(vp, FREAD, ctx)) != 0) {
5320 *resultp = error;
5321 KAUTH_DEBUG("%p DENIED - EXECUTE denied because file could not be opened readonly", vp);
5322 return(1);
5323 }
5324 VNOP_CLOSE(vp, FREAD, ctx);
5325 }
5326
5327 /*
5328 * We don't have any reason to believe that the request has to be denied at this point,
5329 * so go ahead and allow it.
5330 */
5331 *resultp = 0;
5332 KAUTH_DEBUG("%p ALLOWED - bypassing access check for non-local filesystem", vp);
5333 return(1);
5334 }
5335
5336
5337
5338
5339 /*
5340 * Returns: KAUTH_RESULT_ALLOW
5341 * KAUTH_RESULT_DENY
5342 *
5343 * Imputed: *arg3, modified Error code in the deny case
5344 * EROFS Read-only file system
5345 * EACCES Permission denied
5346 * EPERM Operation not permitted [no execute]
5347 * vnode_getattr:ENOMEM Not enough space [only if has filesec]
5348 * vnode_getattr:???
5349 * vnode_authorize_opaque:*arg2 ???
5350 * vnode_authorize_checkimmutable:???
5351 * vnode_authorize_delete:???
5352 * vnode_authorize_simple:???
5353 */
5354
5355
5356 static int
5357 vnode_authorize_callback(kauth_cred_t cred, void *idata, kauth_action_t action,
5358 uintptr_t arg0, uintptr_t arg1, uintptr_t arg2, uintptr_t arg3)
5359 {
5360 vfs_context_t ctx;
5361 vnode_t cvp = NULLVP;
5362 vnode_t vp, dvp;
5363 int result;
5364
5365 ctx = (vfs_context_t)arg0;
5366 vp = (vnode_t)arg1;
5367 dvp = (vnode_t)arg2;
5368
5369 /*
5370 * if there are 2 vnodes passed in, we don't know at
5371 * this point which rights to look at based on the
5372 * combined action being passed in... defer until later...
5373 * otherwise check the kauth 'rights' cache hung
5374 * off of the vnode we're interested in... if we've already
5375 * been granted the right we're currently interested in,
5376 * we can just return success... otherwise we'll go through
5377 * the process of authorizing the requested right(s)... if that
5378 * succeeds, we'll add the right(s) to the cache.
5379 * VNOP_SETATTR and VNOP_SETXATTR will invalidate this cache
5380 */
5381 if (dvp && vp)
5382 goto defer;
5383 if (dvp)
5384 cvp = dvp;
5385 else
5386 cvp = vp;
5387
5388 if (vnode_cache_is_authorized(cvp, ctx, action) == TRUE)
5389 return KAUTH_RESULT_ALLOW;
5390 defer:
5391 result = vnode_authorize_callback_int(cred, idata, action, arg0, arg1, arg2, arg3);
5392
5393 if (result == KAUTH_RESULT_ALLOW && cvp != NULLVP)
5394 vnode_cache_authorized_action(cvp, ctx, action);
5395
5396 return result;
5397 }
5398
5399
5400 static int
5401 vnode_authorize_callback_int(__unused kauth_cred_t unused_cred, __unused void *idata, kauth_action_t action,
5402 uintptr_t arg0, uintptr_t arg1, uintptr_t arg2, uintptr_t arg3)
5403 {
5404 struct _vnode_authorize_context auth_context;
5405 vauth_ctx vcp;
5406 vfs_context_t ctx;
5407 vnode_t vp, dvp;
5408 kauth_cred_t cred;
5409 kauth_ace_rights_t rights;
5410 struct vnode_attr va, dva;
5411 int result;
5412 int *errorp;
5413 int noimmutable;
5414 boolean_t parent_authorized_for_delete = FALSE;
5415 boolean_t found_deny = FALSE;
5416 boolean_t parent_ref= FALSE;
5417
5418 vcp = &auth_context;
5419 ctx = vcp->ctx = (vfs_context_t)arg0;
5420 vp = vcp->vp = (vnode_t)arg1;
5421 dvp = vcp->dvp = (vnode_t)arg2;
5422 errorp = (int *)arg3;
5423 /*
5424 * Note that we authorize against the context, not the passed cred
5425 * (the same thing anyway)
5426 */
5427 cred = ctx->vc_ucred;
5428
5429 VATTR_INIT(&va);
5430 vcp->vap = &va;
5431 VATTR_INIT(&dva);
5432 vcp->dvap = &dva;
5433
5434 vcp->flags = vcp->flags_valid = 0;
5435
5436 #if DIAGNOSTIC
5437 if ((ctx == NULL) || (vp == NULL) || (cred == NULL))
5438 panic("vnode_authorize: bad arguments (context %p vp %p cred %p)", ctx, vp, cred);
5439 #endif
5440
5441 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)",
5442 vp, vfs_context_proc(ctx)->p_comm,
5443 (action & KAUTH_VNODE_ACCESS) ? "access" : "auth",
5444 (action & KAUTH_VNODE_READ_DATA) ? vnode_isdir(vp) ? " LIST_DIRECTORY" : " READ_DATA" : "",
5445 (action & KAUTH_VNODE_WRITE_DATA) ? vnode_isdir(vp) ? " ADD_FILE" : " WRITE_DATA" : "",
5446 (action & KAUTH_VNODE_EXECUTE) ? vnode_isdir(vp) ? " SEARCH" : " EXECUTE" : "",
5447 (action & KAUTH_VNODE_DELETE) ? " DELETE" : "",
5448 (action & KAUTH_VNODE_APPEND_DATA) ? vnode_isdir(vp) ? " ADD_SUBDIRECTORY" : " APPEND_DATA" : "",
5449 (action & KAUTH_VNODE_DELETE_CHILD) ? " DELETE_CHILD" : "",
5450 (action & KAUTH_VNODE_READ_ATTRIBUTES) ? " READ_ATTRIBUTES" : "",
5451 (action & KAUTH_VNODE_WRITE_ATTRIBUTES) ? " WRITE_ATTRIBUTES" : "",
5452 (action & KAUTH_VNODE_READ_EXTATTRIBUTES) ? " READ_EXTATTRIBUTES" : "",
5453 (action & KAUTH_VNODE_WRITE_EXTATTRIBUTES) ? " WRITE_EXTATTRIBUTES" : "",
5454 (action & KAUTH_VNODE_READ_SECURITY) ? " READ_SECURITY" : "",
5455 (action & KAUTH_VNODE_WRITE_SECURITY) ? " WRITE_SECURITY" : "",
5456 (action & KAUTH_VNODE_CHANGE_OWNER) ? " CHANGE_OWNER" : "",
5457 (action & KAUTH_VNODE_NOIMMUTABLE) ? " (noimmutable)" : "",
5458 vnode_isdir(vp) ? "directory" : "file",
5459 vp->v_name ? vp->v_name : "<NULL>", action, vp, dvp);
5460
5461 /*
5462 * Extract the control bits from the action, everything else is
5463 * requested rights.
5464 */
5465 noimmutable = (action & KAUTH_VNODE_NOIMMUTABLE) ? 1 : 0;
5466 rights = action & ~(KAUTH_VNODE_ACCESS | KAUTH_VNODE_NOIMMUTABLE);
5467
5468 if (rights & KAUTH_VNODE_DELETE) {
5469 #if DIAGNOSTIC
5470 if (dvp == NULL)
5471 panic("vnode_authorize: KAUTH_VNODE_DELETE test requires a directory");
5472 #endif
5473 /*
5474 * check to see if we've already authorized the parent
5475 * directory for deletion of its children... if so, we
5476 * can skip a whole bunch of work... we will still have to
5477 * authorize that this specific child can be removed
5478 */
5479 if (vnode_cache_is_authorized(dvp, ctx, KAUTH_VNODE_DELETE) == TRUE)
5480 parent_authorized_for_delete = TRUE;
5481 } else {
5482 dvp = NULL;
5483 }
5484
5485 /*
5486 * Check for read-only filesystems.
5487 */
5488 if ((rights & KAUTH_VNODE_WRITE_RIGHTS) &&
5489 (vp->v_mount->mnt_flag & MNT_RDONLY) &&
5490 ((vp->v_type == VREG) || (vp->v_type == VDIR) ||
5491 (vp->v_type == VLNK) || (vp->v_type == VCPLX) ||
5492 (rights & KAUTH_VNODE_DELETE) || (rights & KAUTH_VNODE_DELETE_CHILD))) {
5493 result = EROFS;
5494 goto out;
5495 }
5496
5497 /*
5498 * Check for noexec filesystems.
5499 */
5500 if ((rights & KAUTH_VNODE_EXECUTE) && (vp->v_type == VREG) && (vp->v_mount->mnt_flag & MNT_NOEXEC)) {
5501 result = EACCES;
5502 goto out;
5503 }
5504
5505 /*
5506 * Handle cases related to filesystems with non-local enforcement.
5507 * This call can return 0, in which case we will fall through to perform a
5508 * check based on VNOP_GETATTR data. Otherwise it returns 1 and sets
5509 * an appropriate result, at which point we can return immediately.
5510 */
5511 if ((vp->v_mount->mnt_kern_flag & MNTK_AUTH_OPAQUE) && vnode_authorize_opaque(vp, &result, action, ctx))
5512 goto out;
5513
5514 /*
5515 * Get vnode attributes and extended security information for the vnode
5516 * and directory if required.
5517 */
5518 VATTR_WANTED(&va, va_mode);
5519 VATTR_WANTED(&va, va_uid);
5520 VATTR_WANTED(&va, va_gid);
5521 VATTR_WANTED(&va, va_flags);
5522 VATTR_WANTED(&va, va_acl);
5523 if ((result = vnode_getattr(vp, &va, ctx)) != 0) {
5524 KAUTH_DEBUG("%p ERROR - failed to get vnode attributes - %d", vp, result);
5525 goto out;
5526 }
5527 if (dvp && parent_authorized_for_delete == FALSE) {
5528 VATTR_WANTED(&dva, va_mode);
5529 VATTR_WANTED(&dva, va_uid);
5530 VATTR_WANTED(&dva, va_gid);
5531 VATTR_WANTED(&dva, va_flags);
5532 VATTR_WANTED(&dva, va_acl);
5533 if ((result = vnode_getattr(dvp, &dva, ctx)) != 0) {
5534 KAUTH_DEBUG("%p ERROR - failed to get directory vnode attributes - %d", vp, result);
5535 goto out;
5536 }
5537 }
5538
5539 /*
5540 * If the vnode is an extended attribute data vnode (eg. a resource fork), *_DATA becomes
5541 * *_EXTATTRIBUTES.
5542 */
5543 if (S_ISXATTR(va.va_mode) || vnode_isnamedstream(vp)) {
5544 if (rights & KAUTH_VNODE_READ_DATA) {
5545 rights &= ~KAUTH_VNODE_READ_DATA;
5546 rights |= KAUTH_VNODE_READ_EXTATTRIBUTES;
5547 }
5548 if (rights & KAUTH_VNODE_WRITE_DATA) {
5549 rights &= ~KAUTH_VNODE_WRITE_DATA;
5550 rights |= KAUTH_VNODE_WRITE_EXTATTRIBUTES;
5551 }
5552 }
5553
5554 /*
5555 * Point 'vp' to the resource fork's parent for ACL checking
5556 */
5557 if (vnode_isnamedstream(vp) &&
5558 (vp->v_parent != NULL) &&
5559 (vget_internal(vp->v_parent, 0, VNODE_NODEAD) == 0)) {
5560 parent_ref = TRUE;
5561 vcp->vp = vp = vp->v_parent;
5562 if (VATTR_IS_SUPPORTED(&va, va_acl) && (va.va_acl != NULL))
5563 kauth_acl_free(va.va_acl);
5564 VATTR_INIT(&va);
5565 VATTR_WANTED(&va, va_mode);
5566 VATTR_WANTED(&va, va_uid);
5567 VATTR_WANTED(&va, va_gid);
5568 VATTR_WANTED(&va, va_flags);
5569 VATTR_WANTED(&va, va_acl);
5570 if ((result = vnode_getattr(vp, &va, ctx)) != 0)
5571 goto out;
5572 }
5573
5574 /*
5575 * Check for immutability.
5576 *
5577 * In the deletion case, parent directory immutability vetoes specific
5578 * file rights.
5579 */
5580 if ((result = vnode_authorize_checkimmutable(vp, &va, rights, noimmutable)) != 0)
5581 goto out;
5582 if ((rights & KAUTH_VNODE_DELETE) &&
5583 parent_authorized_for_delete == FALSE &&
5584 ((result = vnode_authorize_checkimmutable(dvp, &dva, KAUTH_VNODE_DELETE_CHILD, 0)) != 0))
5585 goto out;
5586
5587 /*
5588 * Clear rights that have been authorized by reaching this point, bail if nothing left to
5589 * check.
5590 */
5591 rights &= ~(KAUTH_VNODE_LINKTARGET | KAUTH_VNODE_CHECKIMMUTABLE);
5592 if (rights == 0)
5593 goto out;
5594
5595 /*
5596 * If we're not the superuser, authorize based on file properties.
5597 */
5598 if (!vfs_context_issuser(ctx)) {
5599 /* process delete rights */
5600 if ((rights & KAUTH_VNODE_DELETE) &&
5601 parent_authorized_for_delete == FALSE &&
5602 ((result = vnode_authorize_delete(vcp)) != 0))
5603 goto out;
5604
5605 /* process remaining rights */
5606 if ((rights & ~KAUTH_VNODE_DELETE) &&
5607 (result = vnode_authorize_simple(vcp, rights, rights & KAUTH_VNODE_DELETE, &found_deny)) != 0)
5608 goto out;
5609 } else {
5610
5611 /*
5612 * Execute is only granted to root if one of the x bits is set. This check only
5613 * makes sense if the posix mode bits are actually supported.
5614 */
5615 if ((rights & KAUTH_VNODE_EXECUTE) &&
5616 (vp->v_type == VREG) &&
5617 VATTR_IS_SUPPORTED(&va, va_mode) &&
5618 !(va.va_mode & (S_IXUSR | S_IXGRP | S_IXOTH))) {
5619 result = EPERM;
5620 KAUTH_DEBUG("%p DENIED - root execute requires at least one x bit in 0x%x", vp, va.va_mode);
5621 goto out;
5622 }
5623
5624 KAUTH_DEBUG("%p ALLOWED - caller is superuser", vp);
5625 }
5626 out:
5627 if (VATTR_IS_SUPPORTED(&va, va_acl) && (va.va_acl != NULL))
5628 kauth_acl_free(va.va_acl);
5629 if (VATTR_IS_SUPPORTED(&dva, va_acl) && (dva.va_acl != NULL))
5630 kauth_acl_free(dva.va_acl);
5631
5632 if (result) {
5633 if (parent_ref)
5634 vnode_put(vp);
5635 *errorp = result;
5636 KAUTH_DEBUG("%p DENIED - auth denied", vp);
5637 return(KAUTH_RESULT_DENY);
5638 }
5639 if ((rights & KAUTH_VNODE_SEARCH) && found_deny == FALSE && vp->v_type == VDIR) {
5640 /*
5641 * if we were successfully granted the right to search this directory
5642 * and there were NO ACL DENYs for search and the posix permissions also don't
5643 * deny execute, we can synthesize a global right that allows anyone to
5644 * traverse this directory during a pathname lookup without having to
5645 * match the credential associated with this cache of rights.
5646 */
5647 if (!VATTR_IS_SUPPORTED(&va, va_mode) ||
5648 ((va.va_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) ==
5649 (S_IXUSR | S_IXGRP | S_IXOTH))) {
5650 vnode_cache_authorized_action(vp, ctx, KAUTH_VNODE_SEARCHBYANYONE);
5651 }
5652 }
5653 if ((rights & KAUTH_VNODE_DELETE) && parent_authorized_for_delete == FALSE) {
5654 /*
5655 * parent was successfully and newly authorized for deletions
5656 * add it to the cache
5657 */
5658 vnode_cache_authorized_action(dvp, ctx, KAUTH_VNODE_DELETE);
5659 }
5660 if (parent_ref)
5661 vnode_put(vp);
5662 /*
5663 * Note that this implies that we will allow requests for no rights, as well as
5664 * for rights that we do not recognise. There should be none of these.
5665 */
5666 KAUTH_DEBUG("%p ALLOWED - auth granted", vp);
5667 return(KAUTH_RESULT_ALLOW);
5668 }
5669
5670 /*
5671 * Check that the attribute information in vattr can be legally applied to
5672 * a new file by the context.
5673 */
5674 int
5675 vnode_authattr_new(vnode_t dvp, struct vnode_attr *vap, int noauth, vfs_context_t ctx)
5676 {
5677 int error;
5678 int has_priv_suser, ismember, defaulted_owner, defaulted_group, defaulted_mode;
5679 kauth_cred_t cred;
5680 guid_t changer;
5681 mount_t dmp;
5682
5683 error = 0;
5684 defaulted_owner = defaulted_group = defaulted_mode = 0;
5685
5686 /*
5687 * Require that the filesystem support extended security to apply any.
5688 */
5689 if (!vfs_extendedsecurity(dvp->v_mount) &&
5690 (VATTR_IS_ACTIVE(vap, va_acl) || VATTR_IS_ACTIVE(vap, va_uuuid) || VATTR_IS_ACTIVE(vap, va_guuid))) {
5691 error = EINVAL;
5692 goto out;
5693 }
5694
5695 /*
5696 * Default some fields.
5697 */
5698 dmp = dvp->v_mount;
5699
5700 /*
5701 * If the filesystem is mounted IGNORE_OWNERSHIP and an explicit owner is set, that
5702 * owner takes ownership of all new files.
5703 */
5704 if ((dmp->mnt_flag & MNT_IGNORE_OWNERSHIP) && (dmp->mnt_fsowner != KAUTH_UID_NONE)) {
5705 VATTR_SET(vap, va_uid, dmp->mnt_fsowner);
5706 defaulted_owner = 1;
5707 } else {
5708 if (!VATTR_IS_ACTIVE(vap, va_uid)) {
5709 /* default owner is current user */
5710 VATTR_SET(vap, va_uid, kauth_cred_getuid(vfs_context_ucred(ctx)));
5711 defaulted_owner = 1;
5712 }
5713 }
5714
5715 /*
5716 * If the filesystem is mounted IGNORE_OWNERSHIP and an explicit grouo is set, that
5717 * group takes ownership of all new files.
5718 */
5719 if ((dmp->mnt_flag & MNT_IGNORE_OWNERSHIP) && (dmp->mnt_fsgroup != KAUTH_GID_NONE)) {
5720 VATTR_SET(vap, va_gid, dmp->mnt_fsgroup);
5721 defaulted_group = 1;
5722 } else {
5723 if (!VATTR_IS_ACTIVE(vap, va_gid)) {
5724 /* default group comes from parent object, fallback to current user */
5725 struct vnode_attr dva;
5726 VATTR_INIT(&dva);
5727 VATTR_WANTED(&dva, va_gid);
5728 if ((error = vnode_getattr(dvp, &dva, ctx)) != 0)
5729 goto out;
5730 if (VATTR_IS_SUPPORTED(&dva, va_gid)) {
5731 VATTR_SET(vap, va_gid, dva.va_gid);
5732 } else {
5733 VATTR_SET(vap, va_gid, kauth_cred_getgid(vfs_context_ucred(ctx)));
5734 }
5735 defaulted_group = 1;
5736 }
5737 }
5738
5739 if (!VATTR_IS_ACTIVE(vap, va_flags))
5740 VATTR_SET(vap, va_flags, 0);
5741
5742 /* default mode is everything, masked with current umask */
5743 if (!VATTR_IS_ACTIVE(vap, va_mode)) {
5744 VATTR_SET(vap, va_mode, ACCESSPERMS & ~vfs_context_proc(ctx)->p_fd->fd_cmask);
5745 KAUTH_DEBUG("ATTR - defaulting new file mode to %o from umask %o", vap->va_mode, vfs_context_proc(ctx)->p_fd->fd_cmask);
5746 defaulted_mode = 1;
5747 }
5748 /* set timestamps to now */
5749 if (!VATTR_IS_ACTIVE(vap, va_create_time)) {
5750 nanotime(&vap->va_create_time);
5751 VATTR_SET_ACTIVE(vap, va_create_time);
5752 }
5753
5754 /*
5755 * Check for attempts to set nonsensical fields.
5756 */
5757 if (vap->va_active & ~VNODE_ATTR_NEWOBJ) {
5758 error = EINVAL;
5759 KAUTH_DEBUG("ATTR - ERROR - attempt to set unsupported new-file attributes %llx",
5760 vap->va_active & ~VNODE_ATTR_NEWOBJ);
5761 goto out;
5762 }
5763
5764 /*
5765 * Quickly check for the applicability of any enforcement here.
5766 * Tests below maintain the integrity of the local security model.
5767 */
5768 if (vfs_authopaque(dvp->v_mount))
5769 goto out;
5770
5771 /*
5772 * We need to know if the caller is the superuser, or if the work is
5773 * otherwise already authorised.
5774 */
5775 cred = vfs_context_ucred(ctx);
5776 if (noauth) {
5777 /* doing work for the kernel */
5778 has_priv_suser = 1;
5779 } else {
5780 has_priv_suser = vfs_context_issuser(ctx);
5781 }
5782
5783
5784 if (VATTR_IS_ACTIVE(vap, va_flags)) {
5785 if (has_priv_suser) {
5786 if ((vap->va_flags & (UF_SETTABLE | SF_SETTABLE)) != vap->va_flags) {
5787 error = EPERM;
5788 KAUTH_DEBUG(" DENIED - superuser attempt to set illegal flag(s)");
5789 goto out;
5790 }
5791 } else {
5792 if ((vap->va_flags & UF_SETTABLE) != vap->va_flags) {
5793 error = EPERM;
5794 KAUTH_DEBUG(" DENIED - user attempt to set illegal flag(s)");
5795 goto out;
5796 }
5797 }
5798 }
5799
5800 /* if not superuser, validate legality of new-item attributes */
5801 if (!has_priv_suser) {
5802 if (!defaulted_mode && VATTR_IS_ACTIVE(vap, va_mode)) {
5803 /* setgid? */
5804 if (vap->va_mode & S_ISGID) {
5805 if ((error = kauth_cred_ismember_gid(cred, vap->va_gid, &ismember)) != 0) {
5806 KAUTH_DEBUG("ATTR - ERROR: got %d checking for membership in %d", error, vap->va_gid);
5807 goto out;
5808 }
5809 if (!ismember) {
5810 KAUTH_DEBUG(" DENIED - can't set SGID bit, not a member of %d", vap->va_gid);
5811 error = EPERM;
5812 goto out;
5813 }
5814 }
5815
5816 /* setuid? */
5817 if ((vap->va_mode & S_ISUID) && (vap->va_uid != kauth_cred_getuid(cred))) {
5818 KAUTH_DEBUG("ATTR - ERROR: illegal attempt to set the setuid bit");
5819 error = EPERM;
5820 goto out;
5821 }
5822 }
5823 if (!defaulted_owner && (vap->va_uid != kauth_cred_getuid(cred))) {
5824 KAUTH_DEBUG(" DENIED - cannot create new item owned by %d", vap->va_uid);
5825 error = EPERM;
5826 goto out;
5827 }
5828 if (!defaulted_group) {
5829 if ((error = kauth_cred_ismember_gid(cred, vap->va_gid, &ismember)) != 0) {
5830 KAUTH_DEBUG(" ERROR - got %d checking for membership in %d", error, vap->va_gid);
5831 goto out;
5832 }
5833 if (!ismember) {
5834 KAUTH_DEBUG(" DENIED - cannot create new item with group %d - not a member", vap->va_gid);
5835 error = EPERM;
5836 goto out;
5837 }
5838 }
5839
5840 /* initialising owner/group UUID */
5841 if (VATTR_IS_ACTIVE(vap, va_uuuid)) {
5842 if ((error = kauth_cred_getguid(cred, &changer)) != 0) {
5843 KAUTH_DEBUG(" ERROR - got %d trying to get caller UUID", error);
5844 /* XXX ENOENT here - no GUID - should perhaps become EPERM */
5845 goto out;
5846 }
5847 if (!kauth_guid_equal(&vap->va_uuuid, &changer)) {
5848 KAUTH_DEBUG(" ERROR - cannot create item with supplied owner UUID - not us");
5849 error = EPERM;
5850 goto out;
5851 }
5852 }
5853 if (VATTR_IS_ACTIVE(vap, va_guuid)) {
5854 if ((error = kauth_cred_ismember_guid(cred, &vap->va_guuid, &ismember)) != 0) {
5855 KAUTH_DEBUG(" ERROR - got %d trying to check group membership", error);
5856 goto out;
5857 }
5858 if (!ismember) {
5859 KAUTH_DEBUG(" ERROR - cannot create item with supplied group UUID - not a member");
5860 error = EPERM;
5861 goto out;
5862 }
5863 }
5864 }
5865 out:
5866 return(error);
5867 }
5868
5869 /*
5870 * Check that the attribute information in vap can be legally written by the
5871 * context.
5872 *
5873 * Call this when you're not sure about the vnode_attr; either its contents
5874 * have come from an unknown source, or when they are variable.
5875 *
5876 * Returns errno, or zero and sets *actionp to the KAUTH_VNODE_* actions that
5877 * must be authorized to be permitted to write the vattr.
5878 */
5879 int
5880 vnode_authattr(vnode_t vp, struct vnode_attr *vap, kauth_action_t *actionp, vfs_context_t ctx)
5881 {
5882 struct vnode_attr ova;
5883 kauth_action_t required_action;
5884 int error, has_priv_suser, ismember, chowner, chgroup, clear_suid, clear_sgid;
5885 guid_t changer;
5886 gid_t group;
5887 uid_t owner;
5888 mode_t newmode;
5889 kauth_cred_t cred;
5890 uint32_t fdelta;
5891
5892 VATTR_INIT(&ova);
5893 required_action = 0;
5894 error = 0;
5895
5896 /*
5897 * Quickly check for enforcement applicability.
5898 */
5899 if (vfs_authopaque(vp->v_mount))
5900 goto out;
5901
5902 /*
5903 * Check for attempts to set nonsensical fields.
5904 */
5905 if (vap->va_active & VNODE_ATTR_RDONLY) {
5906 KAUTH_DEBUG("ATTR - ERROR: attempt to set readonly attribute(s)");
5907 error = EINVAL;
5908 goto out;
5909 }
5910
5911 /*
5912 * We need to know if the caller is the superuser.
5913 */
5914 cred = vfs_context_ucred(ctx);
5915 has_priv_suser = kauth_cred_issuser(cred);
5916
5917 /*
5918 * If any of the following are changing, we need information from the old file:
5919 * va_uid
5920 * va_gid
5921 * va_mode
5922 * va_uuuid
5923 * va_guuid
5924 */
5925 if (VATTR_IS_ACTIVE(vap, va_uid) ||
5926 VATTR_IS_ACTIVE(vap, va_gid) ||
5927 VATTR_IS_ACTIVE(vap, va_mode) ||
5928 VATTR_IS_ACTIVE(vap, va_uuuid) ||
5929 VATTR_IS_ACTIVE(vap, va_guuid)) {
5930 VATTR_WANTED(&ova, va_mode);
5931 VATTR_WANTED(&ova, va_uid);
5932 VATTR_WANTED(&ova, va_gid);
5933 VATTR_WANTED(&ova, va_uuuid);
5934 VATTR_WANTED(&ova, va_guuid);
5935 KAUTH_DEBUG("ATTR - security information changing, fetching existing attributes");
5936 }
5937
5938 /*
5939 * If timestamps are being changed, we need to know who the file is owned
5940 * by.
5941 */
5942 if (VATTR_IS_ACTIVE(vap, va_create_time) ||
5943 VATTR_IS_ACTIVE(vap, va_change_time) ||
5944 VATTR_IS_ACTIVE(vap, va_modify_time) ||
5945 VATTR_IS_ACTIVE(vap, va_access_time) ||
5946 VATTR_IS_ACTIVE(vap, va_backup_time)) {
5947
5948 VATTR_WANTED(&ova, va_uid);
5949 #if 0 /* enable this when we support UUIDs as official owners */
5950 VATTR_WANTED(&ova, va_uuuid);
5951 #endif
5952 KAUTH_DEBUG("ATTR - timestamps changing, fetching uid and GUID");
5953 }
5954
5955 /*
5956 * If flags are being changed, we need the old flags.
5957 */
5958 if (VATTR_IS_ACTIVE(vap, va_flags)) {
5959 KAUTH_DEBUG("ATTR - flags changing, fetching old flags");
5960 VATTR_WANTED(&ova, va_flags);
5961 }
5962
5963 /*
5964 * If the size is being set, make sure it's not a directory.
5965 */
5966 if (VATTR_IS_ACTIVE(vap, va_data_size)) {
5967 /* size is meaningless on a directory, don't permit this */
5968 if (vnode_isdir(vp)) {
5969 KAUTH_DEBUG("ATTR - ERROR: size change requested on a directory");
5970 error = EISDIR;
5971 goto out;
5972 }
5973 }
5974
5975 /*
5976 * Get old data.
5977 */
5978 KAUTH_DEBUG("ATTR - fetching old attributes %016llx", ova.va_active);
5979 if ((error = vnode_getattr(vp, &ova, ctx)) != 0) {
5980 KAUTH_DEBUG(" ERROR - got %d trying to get attributes", error);
5981 goto out;
5982 }
5983
5984 /*
5985 * Size changes require write access to the file data.
5986 */
5987 if (VATTR_IS_ACTIVE(vap, va_data_size)) {
5988 /* if we can't get the size, or it's different, we need write access */
5989 KAUTH_DEBUG("ATTR - size change, requiring WRITE_DATA");
5990 required_action |= KAUTH_VNODE_WRITE_DATA;
5991 }
5992
5993 /*
5994 * Changing timestamps?
5995 *
5996 * Note that we are only called to authorize user-requested time changes;
5997 * side-effect time changes are not authorized. Authorisation is only
5998 * required for existing files.
5999 *
6000 * Non-owners are not permitted to change the time on an existing
6001 * file to anything other than the current time.
6002 */
6003 if (VATTR_IS_ACTIVE(vap, va_create_time) ||
6004 VATTR_IS_ACTIVE(vap, va_change_time) ||
6005 VATTR_IS_ACTIVE(vap, va_modify_time) ||
6006 VATTR_IS_ACTIVE(vap, va_access_time) ||
6007 VATTR_IS_ACTIVE(vap, va_backup_time)) {
6008 /*
6009 * The owner and root may set any timestamps they like,
6010 * provided that the file is not immutable. The owner still needs
6011 * WRITE_ATTRIBUTES (implied by ownership but still deniable).
6012 */
6013 if (has_priv_suser || vauth_node_owner(&ova, cred)) {
6014 KAUTH_DEBUG("ATTR - root or owner changing timestamps");
6015 required_action |= KAUTH_VNODE_CHECKIMMUTABLE | KAUTH_VNODE_WRITE_ATTRIBUTES;
6016 } else {
6017 /* just setting the current time? */
6018 if (vap->va_vaflags & VA_UTIMES_NULL) {
6019 KAUTH_DEBUG("ATTR - non-root/owner changing timestamps, requiring WRITE_ATTRIBUTES");
6020 required_action |= KAUTH_VNODE_WRITE_ATTRIBUTES;
6021 } else {
6022 KAUTH_DEBUG("ATTR - ERROR: illegal timestamp modification attempted");
6023 error = EACCES;
6024 goto out;
6025 }
6026 }
6027 }
6028
6029 /*
6030 * Changing file mode?
6031 */
6032 if (VATTR_IS_ACTIVE(vap, va_mode) && VATTR_IS_SUPPORTED(&ova, va_mode) && (ova.va_mode != vap->va_mode)) {
6033 KAUTH_DEBUG("ATTR - mode change from %06o to %06o", ova.va_mode, vap->va_mode);
6034
6035 /*
6036 * Mode changes always have the same basic auth requirements.
6037 */
6038 if (has_priv_suser) {
6039 KAUTH_DEBUG("ATTR - superuser mode change, requiring immutability check");
6040 required_action |= KAUTH_VNODE_CHECKIMMUTABLE;
6041 } else {
6042 /* need WRITE_SECURITY */
6043 KAUTH_DEBUG("ATTR - non-superuser mode change, requiring WRITE_SECURITY");
6044 required_action |= KAUTH_VNODE_WRITE_SECURITY;
6045 }
6046
6047 /*
6048 * Can't set the setgid bit if you're not in the group and not root. Have to have
6049 * existing group information in the case we're not setting it right now.
6050 */
6051 if (vap->va_mode & S_ISGID) {
6052 required_action |= KAUTH_VNODE_CHECKIMMUTABLE; /* always required */
6053 if (!has_priv_suser) {
6054 if (VATTR_IS_ACTIVE(vap, va_gid)) {
6055 group = vap->va_gid;
6056 } else if (VATTR_IS_SUPPORTED(&ova, va_gid)) {
6057 group = ova.va_gid;
6058 } else {
6059 KAUTH_DEBUG("ATTR - ERROR: setgid but no gid available");
6060 error = EINVAL;
6061 goto out;
6062 }
6063 /*
6064 * This might be too restrictive; WRITE_SECURITY might be implied by
6065 * membership in this case, rather than being an additional requirement.
6066 */
6067 if ((error = kauth_cred_ismember_gid(cred, group, &ismember)) != 0) {
6068 KAUTH_DEBUG("ATTR - ERROR: got %d checking for membership in %d", error, vap->va_gid);
6069 goto out;
6070 }
6071 if (!ismember) {
6072 KAUTH_DEBUG(" DENIED - can't set SGID bit, not a member of %d", group);
6073 error = EPERM;
6074 goto out;
6075 }
6076 }
6077 }
6078
6079 /*
6080 * Can't set the setuid bit unless you're root or the file's owner.
6081 */
6082 if (vap->va_mode & S_ISUID) {
6083 required_action |= KAUTH_VNODE_CHECKIMMUTABLE; /* always required */
6084 if (!has_priv_suser) {
6085 if (VATTR_IS_ACTIVE(vap, va_uid)) {
6086 owner = vap->va_uid;
6087 } else if (VATTR_IS_SUPPORTED(&ova, va_uid)) {
6088 owner = ova.va_uid;
6089 } else {
6090 KAUTH_DEBUG("ATTR - ERROR: setuid but no uid available");
6091 error = EINVAL;
6092 goto out;
6093 }
6094 if (owner != kauth_cred_getuid(cred)) {
6095 /*
6096 * We could allow this if WRITE_SECURITY is permitted, perhaps.
6097 */
6098 KAUTH_DEBUG("ATTR - ERROR: illegal attempt to set the setuid bit");
6099 error = EPERM;
6100 goto out;
6101 }
6102 }
6103 }
6104 }
6105
6106 /*
6107 * Validate/mask flags changes. This checks that only the flags in
6108 * the UF_SETTABLE mask are being set, and preserves the flags in
6109 * the SF_SETTABLE case.
6110 *
6111 * Since flags changes may be made in conjunction with other changes,
6112 * we will ask the auth code to ignore immutability in the case that
6113 * the SF_* flags are not set and we are only manipulating the file flags.
6114 *
6115 */
6116 if (VATTR_IS_ACTIVE(vap, va_flags)) {
6117 /* compute changing flags bits */
6118 if (VATTR_IS_SUPPORTED(&ova, va_flags)) {
6119 fdelta = vap->va_flags ^ ova.va_flags;
6120 } else {
6121 fdelta = vap->va_flags;
6122 }
6123
6124 if (fdelta != 0) {
6125 KAUTH_DEBUG("ATTR - flags changing, requiring WRITE_SECURITY");
6126 required_action |= KAUTH_VNODE_WRITE_SECURITY;
6127
6128 /* check that changing bits are legal */
6129 if (has_priv_suser) {
6130 /*
6131 * The immutability check will prevent us from clearing the SF_*
6132 * flags unless the system securelevel permits it, so just check
6133 * for legal flags here.
6134 */
6135 if (fdelta & ~(UF_SETTABLE | SF_SETTABLE)) {
6136 error = EPERM;
6137 KAUTH_DEBUG(" DENIED - superuser attempt to set illegal flag(s)");
6138 goto out;
6139 }
6140 } else {
6141 if (fdelta & ~UF_SETTABLE) {
6142 error = EPERM;
6143 KAUTH_DEBUG(" DENIED - user attempt to set illegal flag(s)");
6144 goto out;
6145 }
6146 }
6147 /*
6148 * If the caller has the ability to manipulate file flags,
6149 * security is not reduced by ignoring them for this operation.
6150 *
6151 * A more complete test here would consider the 'after' states of the flags
6152 * to determine whether it would permit the operation, but this becomes
6153 * very complex.
6154 *
6155 * Ignoring immutability is conditional on securelevel; this does not bypass
6156 * the SF_* flags if securelevel > 0.
6157 */
6158 required_action |= KAUTH_VNODE_NOIMMUTABLE;
6159 }
6160 }
6161
6162 /*
6163 * Validate ownership information.
6164 */
6165 chowner = 0;
6166 chgroup = 0;
6167 clear_suid = 0;
6168 clear_sgid = 0;
6169
6170 /*
6171 * uid changing
6172 * Note that if the filesystem didn't give us a UID, we expect that it doesn't
6173 * support them in general, and will ignore it if/when we try to set it.
6174 * We might want to clear the uid out of vap completely here.
6175 */
6176 if (VATTR_IS_ACTIVE(vap, va_uid)) {
6177 if (VATTR_IS_SUPPORTED(&ova, va_uid) && (vap->va_uid != ova.va_uid)) {
6178 if (!has_priv_suser && (kauth_cred_getuid(cred) != vap->va_uid)) {
6179 KAUTH_DEBUG(" DENIED - non-superuser cannot change ownershipt to a third party");
6180 error = EPERM;
6181 goto out;
6182 }
6183 chowner = 1;
6184 }
6185 clear_suid = 1;
6186 }
6187
6188 /*
6189 * gid changing
6190 * Note that if the filesystem didn't give us a GID, we expect that it doesn't
6191 * support them in general, and will ignore it if/when we try to set it.
6192 * We might want to clear the gid out of vap completely here.
6193 */
6194 if (VATTR_IS_ACTIVE(vap, va_gid)) {
6195 if (VATTR_IS_SUPPORTED(&ova, va_gid) && (vap->va_gid != ova.va_gid)) {
6196 if (!has_priv_suser) {
6197 if ((error = kauth_cred_ismember_gid(cred, vap->va_gid, &ismember)) != 0) {
6198 KAUTH_DEBUG(" ERROR - got %d checking for membership in %d", error, vap->va_gid);
6199 goto out;
6200 }
6201 if (!ismember) {
6202 KAUTH_DEBUG(" DENIED - group change from %d to %d but not a member of target group",
6203 ova.va_gid, vap->va_gid);
6204 error = EPERM;
6205 goto out;
6206 }
6207 }
6208 chgroup = 1;
6209 }
6210 clear_sgid = 1;
6211 }
6212
6213 /*
6214 * Owner UUID being set or changed.
6215 */
6216 if (VATTR_IS_ACTIVE(vap, va_uuuid)) {
6217 /* if the owner UUID is not actually changing ... */
6218 if (VATTR_IS_SUPPORTED(&ova, va_uuuid) && kauth_guid_equal(&vap->va_uuuid, &ova.va_uuuid))
6219 goto no_uuuid_change;
6220
6221 /*
6222 * The owner UUID cannot be set by a non-superuser to anything other than
6223 * their own.
6224 */
6225 if (!has_priv_suser) {
6226 if ((error = kauth_cred_getguid(cred, &changer)) != 0) {
6227 KAUTH_DEBUG(" ERROR - got %d trying to get caller UUID", error);
6228 /* XXX ENOENT here - no UUID - should perhaps become EPERM */
6229 goto out;
6230 }
6231 if (!kauth_guid_equal(&vap->va_uuuid, &changer)) {
6232 KAUTH_DEBUG(" ERROR - cannot set supplied owner UUID - not us");
6233 error = EPERM;
6234 goto out;
6235 }
6236 }
6237 chowner = 1;
6238 clear_suid = 1;
6239 }
6240 no_uuuid_change:
6241 /*
6242 * Group UUID being set or changed.
6243 */
6244 if (VATTR_IS_ACTIVE(vap, va_guuid)) {
6245 /* if the group UUID is not actually changing ... */
6246 if (VATTR_IS_SUPPORTED(&ova, va_guuid) && kauth_guid_equal(&vap->va_guuid, &ova.va_guuid))
6247 goto no_guuid_change;
6248
6249 /*
6250 * The group UUID cannot be set by a non-superuser to anything other than
6251 * one of which they are a member.
6252 */
6253 if (!has_priv_suser) {
6254 if ((error = kauth_cred_ismember_guid(cred, &vap->va_guuid, &ismember)) != 0) {
6255 KAUTH_DEBUG(" ERROR - got %d trying to check group membership", error);
6256 goto out;
6257 }
6258 if (!ismember) {
6259 KAUTH_DEBUG(" ERROR - cannot create item with supplied group UUID - not a member");
6260 error = EPERM;
6261 goto out;
6262 }
6263 }
6264 chgroup = 1;
6265 }
6266 no_guuid_change:
6267
6268 /*
6269 * Compute authorisation for group/ownership changes.
6270 */
6271 if (chowner || chgroup || clear_suid || clear_sgid) {
6272 if (has_priv_suser) {
6273 KAUTH_DEBUG("ATTR - superuser changing file owner/group, requiring immutability check");
6274 required_action |= KAUTH_VNODE_CHECKIMMUTABLE;
6275 } else {
6276 if (chowner) {
6277 KAUTH_DEBUG("ATTR - ownership change, requiring TAKE_OWNERSHIP");
6278 required_action |= KAUTH_VNODE_TAKE_OWNERSHIP;
6279 }
6280 if (chgroup && !chowner) {
6281 KAUTH_DEBUG("ATTR - group change, requiring WRITE_SECURITY");
6282 required_action |= KAUTH_VNODE_WRITE_SECURITY;
6283 }
6284
6285 /* clear set-uid and set-gid bits as required by Posix */
6286 if (VATTR_IS_ACTIVE(vap, va_mode)) {
6287 newmode = vap->va_mode;
6288 } else if (VATTR_IS_SUPPORTED(&ova, va_mode)) {
6289 newmode = ova.va_mode;
6290 } else {
6291 KAUTH_DEBUG("CHOWN - trying to change owner but cannot get mode from filesystem to mask setugid bits");
6292 newmode = 0;
6293 }
6294 if (newmode & (S_ISUID | S_ISGID)) {
6295 VATTR_SET(vap, va_mode, newmode & ~(S_ISUID | S_ISGID));
6296 KAUTH_DEBUG("CHOWN - masking setugid bits from mode %o to %o", newmode, vap->va_mode);
6297 }
6298 }
6299 }
6300
6301 /*
6302 * Authorise changes in the ACL.
6303 */
6304 if (VATTR_IS_ACTIVE(vap, va_acl)) {
6305
6306 /* no existing ACL */
6307 if (!VATTR_IS_ACTIVE(&ova, va_acl) || (ova.va_acl == NULL)) {
6308
6309 /* adding an ACL */
6310 if (vap->va_acl != NULL) {
6311 required_action |= KAUTH_VNODE_WRITE_SECURITY;
6312 KAUTH_DEBUG("CHMOD - adding ACL");
6313 }
6314
6315 /* removing an existing ACL */
6316 } else if (vap->va_acl == NULL) {
6317 required_action |= KAUTH_VNODE_WRITE_SECURITY;
6318 KAUTH_DEBUG("CHMOD - removing ACL");
6319
6320 /* updating an existing ACL */
6321 } else {
6322 if (vap->va_acl->acl_entrycount != ova.va_acl->acl_entrycount) {
6323 /* entry count changed, must be different */
6324 required_action |= KAUTH_VNODE_WRITE_SECURITY;
6325 KAUTH_DEBUG("CHMOD - adding/removing ACL entries");
6326 } else if (vap->va_acl->acl_entrycount > 0) {
6327 /* both ACLs have the same ACE count, said count is 1 or more, bitwise compare ACLs */
6328 if (!memcmp(&vap->va_acl->acl_ace[0], &ova.va_acl->acl_ace[0],
6329 sizeof(struct kauth_ace) * vap->va_acl->acl_entrycount)) {
6330 required_action |= KAUTH_VNODE_WRITE_SECURITY;
6331 KAUTH_DEBUG("CHMOD - changing ACL entries");
6332 }
6333 }
6334 }
6335 }
6336
6337 /*
6338 * Other attributes that require authorisation.
6339 */
6340 if (VATTR_IS_ACTIVE(vap, va_encoding))
6341 required_action |= KAUTH_VNODE_WRITE_ATTRIBUTES;
6342
6343 out:
6344 if (VATTR_IS_SUPPORTED(&ova, va_acl) && (ova.va_acl != NULL))
6345 kauth_acl_free(ova.va_acl);
6346 if (error == 0)
6347 *actionp = required_action;
6348 return(error);
6349 }
6350
6351
6352 void
6353 vfs_setlocklocal(mount_t mp)
6354 {
6355 vnode_t vp;
6356
6357 mount_lock(mp);
6358 mp->mnt_kern_flag |= MNTK_LOCK_LOCAL;
6359
6360 /*
6361 * We do not expect anyone to be using any vnodes at the
6362 * time this routine is called. So no need for vnode locking
6363 */
6364 TAILQ_FOREACH(vp, &mp->mnt_vnodelist, v_mntvnodes) {
6365 vp->v_flag |= VLOCKLOCAL;
6366 }
6367 TAILQ_FOREACH(vp, &mp->mnt_workerqueue, v_mntvnodes) {
6368 vp->v_flag |= VLOCKLOCAL;
6369 }
6370 TAILQ_FOREACH(vp, &mp->mnt_newvnodes, v_mntvnodes) {
6371 vp->v_flag |= VLOCKLOCAL;
6372 }
6373 mount_unlock(mp);
6374 }
6375
6376 void
6377 vn_setunionwait(vnode_t vp)
6378 {
6379 vnode_lock_spin(vp);
6380 vp->v_flag |= VISUNION;
6381 vnode_unlock(vp);
6382 }
6383
6384
6385 void
6386 vn_checkunionwait(vnode_t vp)
6387 {
6388 vnode_lock(vp);
6389 while ((vp->v_flag & VISUNION) == VISUNION)
6390 msleep((caddr_t)&vp->v_flag, &vp->v_lock, 0, 0, 0);
6391 vnode_unlock(vp);
6392 }
6393
6394 void
6395 vn_clearunionwait(vnode_t vp, int locked)
6396 {
6397 if (!locked)
6398 vnode_lock(vp);
6399 if((vp->v_flag & VISUNION) == VISUNION) {
6400 vp->v_flag &= ~VISUNION;
6401 wakeup((caddr_t)&vp->v_flag);
6402 }
6403 if (!locked)
6404 vnode_unlock(vp);
6405 }
6406
6407 /*
6408 * XXX - get "don't trigger mounts" flag for thread; used by autofs.
6409 */
6410 extern int thread_notrigger(void);
6411
6412 int
6413 thread_notrigger(void)
6414 {
6415 struct uthread *uth = (struct uthread *)get_bsdthread_info(current_thread());
6416 return (uth->uu_notrigger);
6417 }
6418
6419 /*
6420 * Removes orphaned apple double files during a rmdir
6421 * Works by:
6422 * 1. vnode_suspend().
6423 * 2. Call VNOP_READDIR() till the end of directory is reached.
6424 * 3. Check if the directory entries returned are regular files with name starting with "._". If not, return ENOTEMPTY.
6425 * 4. Continue (2) and (3) till end of directory is reached.
6426 * 5. If all the entries in the directory were files with "._" name, delete all the files.
6427 * 6. vnode_resume()
6428 * 7. If deletion of all files succeeded, call VNOP_RMDIR() again.
6429 */
6430
6431 errno_t rmdir_remove_orphaned_appleDouble(vnode_t vp , vfs_context_t ctx, int * restart_flag)
6432 {
6433
6434 #define UIO_BUFF_SIZE 2048
6435 uio_t auio = NULL;
6436 int eofflag, siz = UIO_BUFF_SIZE, nentries = 0;
6437 int open_flag = 0, full_erase_flag = 0;
6438 char uio_buf[ UIO_SIZEOF(1) ];
6439 char *rbuf = NULL, *cpos, *cend;
6440 struct nameidata nd_temp;
6441 struct dirent *dp;
6442 errno_t error;
6443
6444 error = vnode_suspend(vp);
6445
6446 /*
6447 * restart_flag is set so that the calling rmdir sleeps and resets
6448 */
6449 if (error == EBUSY)
6450 *restart_flag = 1;
6451 if (error != 0)
6452 goto outsc;
6453
6454 /*
6455 * set up UIO
6456 */
6457 MALLOC(rbuf, caddr_t, siz, M_TEMP, M_WAITOK);
6458 if (rbuf)
6459 auio = uio_createwithbuffer(1, 0, UIO_SYSSPACE, UIO_READ,
6460 &uio_buf[0], sizeof(uio_buf));
6461 if (!rbuf || !auio) {
6462 error = ENOMEM;
6463 goto outsc;
6464 }
6465
6466 uio_setoffset(auio,0);
6467
6468 eofflag = 0;
6469
6470 if ((error = VNOP_OPEN(vp, FREAD, ctx)))
6471 goto outsc;
6472 else
6473 open_flag = 1;
6474
6475 /*
6476 * First pass checks if all files are appleDouble files.
6477 */
6478
6479 do {
6480 siz = UIO_BUFF_SIZE;
6481 uio_reset(auio, uio_offset(auio), UIO_SYSSPACE, UIO_READ);
6482 uio_addiov(auio, CAST_USER_ADDR_T(rbuf), UIO_BUFF_SIZE);
6483
6484 if((error = VNOP_READDIR(vp, auio, 0, &eofflag, &nentries, ctx)))
6485 goto outsc;
6486
6487 if (uio_resid(auio) != 0)
6488 siz -= uio_resid(auio);
6489
6490 /*
6491 * Iterate through directory
6492 */
6493 cpos = rbuf;
6494 cend = rbuf + siz;
6495 dp = (struct dirent*) cpos;
6496
6497 if (cpos == cend)
6498 eofflag = 1;
6499
6500 while ((cpos < cend)) {
6501 /*
6502 * Check for . and .. as well as directories
6503 */
6504 if (dp->d_ino != 0 &&
6505 !((dp->d_namlen == 1 && dp->d_name[0] == '.') ||
6506 (dp->d_namlen == 2 && dp->d_name[0] == '.' && dp->d_name[1] == '.'))) {
6507 /*
6508 * Check for irregular files and ._ files
6509 * If there is a ._._ file abort the op
6510 */
6511 if ( dp->d_namlen < 2 ||
6512 strncmp(dp->d_name,"._",2) ||
6513 (dp->d_namlen >= 4 && !strncmp(&(dp->d_name[2]), "._",2))) {
6514 error = ENOTEMPTY;
6515 goto outsc;
6516 }
6517 }
6518 cpos += dp->d_reclen;
6519 dp = (struct dirent*)cpos;
6520 }
6521
6522 } while (!eofflag);
6523 /*
6524 * If we've made it here all the files in the dir are AppleDouble
6525 * We can delete the files even though the node is suspended
6526 * because we are the owner of the file.
6527 */
6528
6529 uio_reset(auio, 0, UIO_SYSSPACE, UIO_READ);
6530 eofflag = 0;
6531
6532 do {
6533 siz = UIO_BUFF_SIZE;
6534 uio_reset(auio, uio_offset(auio), UIO_SYSSPACE, UIO_READ);
6535 uio_addiov(auio, CAST_USER_ADDR_T(rbuf), UIO_BUFF_SIZE);
6536
6537 error = VNOP_READDIR(vp, auio, 0, &eofflag, &nentries, ctx);
6538
6539 if (error != 0)
6540 goto outsc;
6541
6542 if (uio_resid(auio) != 0)
6543 siz -= uio_resid(auio);
6544
6545 /*
6546 * Iterate through directory
6547 */
6548 cpos = rbuf;
6549 cend = rbuf + siz;
6550 dp = (struct dirent*) cpos;
6551
6552 if (cpos == cend)
6553 eofflag = 1;
6554
6555 while ((cpos < cend)) {
6556 /*
6557 * Check for . and .. as well as directories
6558 */
6559 if (dp->d_ino != 0 &&
6560 !((dp->d_namlen == 1 && dp->d_name[0] == '.') ||
6561 (dp->d_namlen == 2 && dp->d_name[0] == '.' && dp->d_name[1] == '.'))
6562 ) {
6563 NDINIT(&nd_temp, DELETE, USEDVP, UIO_SYSSPACE, CAST_USER_ADDR_T(dp->d_name), ctx);
6564 nd_temp.ni_dvp = vp;
6565 error = unlink1(ctx, &nd_temp, 0);
6566 if(error && error != ENOENT)
6567 goto outsc;
6568 }
6569 cpos += dp->d_reclen;
6570 dp = (struct dirent*)cpos;
6571 }
6572
6573 /*
6574 * workaround for HFS/NFS setting eofflag before end of file
6575 */
6576 if (vp->v_tag == VT_HFS && nentries > 2)
6577 eofflag=0;
6578
6579 if (vp->v_tag == VT_NFS) {
6580 if (eofflag && !full_erase_flag) {
6581 full_erase_flag = 1;
6582 eofflag = 0;
6583 uio_reset(auio, 0, UIO_SYSSPACE, UIO_READ);
6584 }
6585 else if (!eofflag && full_erase_flag)
6586 full_erase_flag = 0;
6587 }
6588
6589 } while (!eofflag);
6590
6591
6592 error = 0;
6593
6594 outsc:
6595 if (open_flag)
6596 VNOP_CLOSE(vp, FREAD, ctx);
6597
6598 uio_free(auio);
6599 FREE(rbuf, M_TEMP);
6600
6601 vnode_resume(vp);
6602
6603
6604 return(error);
6605
6606 }
6607
6608
6609 #ifdef JOE_DEBUG
6610
6611 record_vp(vnode_t vp, int count) {
6612 struct uthread *ut;
6613 int i;
6614
6615 if ((vp->v_flag & VSYSTEM))
6616 return;
6617
6618 ut = get_bsdthread_info(current_thread());
6619 ut->uu_iocount += count;
6620
6621 if (ut->uu_vpindex < 32) {
6622 for (i = 0; i < ut->uu_vpindex; i++) {
6623 if (ut->uu_vps[i] == vp)
6624 return;
6625 }
6626 ut->uu_vps[ut->uu_vpindex] = vp;
6627 ut->uu_vpindex++;
6628 }
6629 }
6630 #endif