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