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