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