xref: /freebsd/sys/kern/vfs_mount.c (revision d7d962ead0b6e5e8a39202d0590022082bf5bfb6)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1999-2004 Poul-Henning Kamp
5  * Copyright (c) 1999 Michael Smith
6  * Copyright (c) 1989, 1993
7  *	The Regents of the University of California.  All rights reserved.
8  * (c) UNIX System Laboratories, Inc.
9  * All or some portions of this file are derived from material licensed
10  * to the University of California by American Telephone and Telegraph
11  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
12  * the permission of UNIX System Laboratories, Inc.
13  *
14  * Redistribution and use in source and binary forms, with or without
15  * modification, are permitted provided that the following conditions
16  * are met:
17  * 1. Redistributions of source code must retain the above copyright
18  *    notice, this list of conditions and the following disclaimer.
19  * 2. Redistributions in binary form must reproduce the above copyright
20  *    notice, this list of conditions and the following disclaimer in the
21  *    documentation and/or other materials provided with the distribution.
22  * 3. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  */
38 
39 #include <sys/cdefs.h>
40 __FBSDID("$FreeBSD$");
41 
42 #include <sys/param.h>
43 #include <sys/conf.h>
44 #include <sys/smp.h>
45 #include <sys/devctl.h>
46 #include <sys/eventhandler.h>
47 #include <sys/fcntl.h>
48 #include <sys/jail.h>
49 #include <sys/kernel.h>
50 #include <sys/ktr.h>
51 #include <sys/libkern.h>
52 #include <sys/limits.h>
53 #include <sys/malloc.h>
54 #include <sys/mount.h>
55 #include <sys/mutex.h>
56 #include <sys/namei.h>
57 #include <sys/priv.h>
58 #include <sys/proc.h>
59 #include <sys/filedesc.h>
60 #include <sys/reboot.h>
61 #include <sys/sbuf.h>
62 #include <sys/syscallsubr.h>
63 #include <sys/sysproto.h>
64 #include <sys/sx.h>
65 #include <sys/sysctl.h>
66 #include <sys/sysent.h>
67 #include <sys/systm.h>
68 #include <sys/taskqueue.h>
69 #include <sys/vnode.h>
70 #include <vm/uma.h>
71 
72 #include <geom/geom.h>
73 
74 #include <machine/stdarg.h>
75 
76 #include <security/audit/audit.h>
77 #include <security/mac/mac_framework.h>
78 
79 #define	VFS_MOUNTARG_SIZE_MAX	(1024 * 64)
80 
81 static int	vfs_domount(struct thread *td, const char *fstype, char *fspath,
82 		    uint64_t fsflags, struct vfsoptlist **optlist);
83 static void	free_mntarg(struct mntarg *ma);
84 
85 static int	usermount = 0;
86 SYSCTL_INT(_vfs, OID_AUTO, usermount, CTLFLAG_RW, &usermount, 0,
87     "Unprivileged users may mount and unmount file systems");
88 
89 static bool	default_autoro = false;
90 SYSCTL_BOOL(_vfs, OID_AUTO, default_autoro, CTLFLAG_RW, &default_autoro, 0,
91     "Retry failed r/w mount as r/o if no explicit ro/rw option is specified");
92 
93 static bool	recursive_forced_unmount = false;
94 SYSCTL_BOOL(_vfs, OID_AUTO, recursive_forced_unmount, CTLFLAG_RW,
95     &recursive_forced_unmount, 0, "Recursively unmount stacked upper mounts"
96     " when a file system is forcibly unmounted");
97 
98 static SYSCTL_NODE(_vfs, OID_AUTO, deferred_unmount,
99     CTLFLAG_RD | CTLFLAG_MPSAFE, 0, "deferred unmount controls");
100 
101 static unsigned int	deferred_unmount_retry_limit = 10;
102 SYSCTL_UINT(_vfs_deferred_unmount, OID_AUTO, retry_limit, CTLFLAG_RW,
103     &deferred_unmount_retry_limit, 0,
104     "Maximum number of retries for deferred unmount failure");
105 
106 static int	deferred_unmount_retry_delay_hz;
107 SYSCTL_INT(_vfs_deferred_unmount, OID_AUTO, retry_delay_hz, CTLFLAG_RW,
108     &deferred_unmount_retry_delay_hz, 0,
109     "Delay in units of [1/kern.hz]s when retrying a failed deferred unmount");
110 
111 static int	deferred_unmount_total_retries = 0;
112 SYSCTL_INT(_vfs_deferred_unmount, OID_AUTO, total_retries, CTLFLAG_RD,
113     &deferred_unmount_total_retries, 0,
114     "Total number of retried deferred unmounts");
115 
116 MALLOC_DEFINE(M_MOUNT, "mount", "vfs mount structure");
117 MALLOC_DEFINE(M_STATFS, "statfs", "statfs structure");
118 static uma_zone_t mount_zone;
119 
120 /* List of mounted filesystems. */
121 struct mntlist mountlist = TAILQ_HEAD_INITIALIZER(mountlist);
122 
123 /* For any iteration/modification of mountlist */
124 struct mtx_padalign __exclusive_cache_line mountlist_mtx;
125 
126 EVENTHANDLER_LIST_DEFINE(vfs_mounted);
127 EVENTHANDLER_LIST_DEFINE(vfs_unmounted);
128 
129 static void vfs_deferred_unmount(void *arg, int pending);
130 static struct timeout_task deferred_unmount_task;
131 static struct mtx deferred_unmount_lock;
132 MTX_SYSINIT(deferred_unmount, &deferred_unmount_lock, "deferred_unmount",
133     MTX_DEF);
134 static STAILQ_HEAD(, mount) deferred_unmount_list =
135     STAILQ_HEAD_INITIALIZER(deferred_unmount_list);
136 TASKQUEUE_DEFINE_THREAD(deferred_unmount);
137 
138 static void mount_devctl_event(const char *type, struct mount *mp, bool donew);
139 
140 /*
141  * Global opts, taken by all filesystems
142  */
143 static const char *global_opts[] = {
144 	"errmsg",
145 	"fstype",
146 	"fspath",
147 	"ro",
148 	"rw",
149 	"nosuid",
150 	"noexec",
151 	NULL
152 };
153 
154 static int
155 mount_init(void *mem, int size, int flags)
156 {
157 	struct mount *mp;
158 
159 	mp = (struct mount *)mem;
160 	mtx_init(&mp->mnt_mtx, "struct mount mtx", NULL, MTX_DEF);
161 	mtx_init(&mp->mnt_listmtx, "struct mount vlist mtx", NULL, MTX_DEF);
162 	lockinit(&mp->mnt_explock, PVFS, "explock", 0, 0);
163 	mp->mnt_pcpu = uma_zalloc_pcpu(pcpu_zone_16, M_WAITOK | M_ZERO);
164 	mp->mnt_ref = 0;
165 	mp->mnt_vfs_ops = 1;
166 	mp->mnt_rootvnode = NULL;
167 	return (0);
168 }
169 
170 static void
171 mount_fini(void *mem, int size)
172 {
173 	struct mount *mp;
174 
175 	mp = (struct mount *)mem;
176 	uma_zfree_pcpu(pcpu_zone_16, mp->mnt_pcpu);
177 	lockdestroy(&mp->mnt_explock);
178 	mtx_destroy(&mp->mnt_listmtx);
179 	mtx_destroy(&mp->mnt_mtx);
180 }
181 
182 static void
183 vfs_mount_init(void *dummy __unused)
184 {
185 	TIMEOUT_TASK_INIT(taskqueue_deferred_unmount, &deferred_unmount_task,
186 	    0, vfs_deferred_unmount, NULL);
187 	deferred_unmount_retry_delay_hz = hz;
188 	mount_zone = uma_zcreate("Mountpoints", sizeof(struct mount), NULL,
189 	    NULL, mount_init, mount_fini, UMA_ALIGN_CACHE, UMA_ZONE_NOFREE);
190 	mtx_init(&mountlist_mtx, "mountlist", NULL, MTX_DEF);
191 }
192 SYSINIT(vfs_mount, SI_SUB_VFS, SI_ORDER_ANY, vfs_mount_init, NULL);
193 
194 /*
195  * ---------------------------------------------------------------------
196  * Functions for building and sanitizing the mount options
197  */
198 
199 /* Remove one mount option. */
200 static void
201 vfs_freeopt(struct vfsoptlist *opts, struct vfsopt *opt)
202 {
203 
204 	TAILQ_REMOVE(opts, opt, link);
205 	free(opt->name, M_MOUNT);
206 	if (opt->value != NULL)
207 		free(opt->value, M_MOUNT);
208 	free(opt, M_MOUNT);
209 }
210 
211 /* Release all resources related to the mount options. */
212 void
213 vfs_freeopts(struct vfsoptlist *opts)
214 {
215 	struct vfsopt *opt;
216 
217 	while (!TAILQ_EMPTY(opts)) {
218 		opt = TAILQ_FIRST(opts);
219 		vfs_freeopt(opts, opt);
220 	}
221 	free(opts, M_MOUNT);
222 }
223 
224 void
225 vfs_deleteopt(struct vfsoptlist *opts, const char *name)
226 {
227 	struct vfsopt *opt, *temp;
228 
229 	if (opts == NULL)
230 		return;
231 	TAILQ_FOREACH_SAFE(opt, opts, link, temp)  {
232 		if (strcmp(opt->name, name) == 0)
233 			vfs_freeopt(opts, opt);
234 	}
235 }
236 
237 static int
238 vfs_isopt_ro(const char *opt)
239 {
240 
241 	if (strcmp(opt, "ro") == 0 || strcmp(opt, "rdonly") == 0 ||
242 	    strcmp(opt, "norw") == 0)
243 		return (1);
244 	return (0);
245 }
246 
247 static int
248 vfs_isopt_rw(const char *opt)
249 {
250 
251 	if (strcmp(opt, "rw") == 0 || strcmp(opt, "noro") == 0)
252 		return (1);
253 	return (0);
254 }
255 
256 /*
257  * Check if options are equal (with or without the "no" prefix).
258  */
259 static int
260 vfs_equalopts(const char *opt1, const char *opt2)
261 {
262 	char *p;
263 
264 	/* "opt" vs. "opt" or "noopt" vs. "noopt" */
265 	if (strcmp(opt1, opt2) == 0)
266 		return (1);
267 	/* "noopt" vs. "opt" */
268 	if (strncmp(opt1, "no", 2) == 0 && strcmp(opt1 + 2, opt2) == 0)
269 		return (1);
270 	/* "opt" vs. "noopt" */
271 	if (strncmp(opt2, "no", 2) == 0 && strcmp(opt1, opt2 + 2) == 0)
272 		return (1);
273 	while ((p = strchr(opt1, '.')) != NULL &&
274 	    !strncmp(opt1, opt2, ++p - opt1)) {
275 		opt2 += p - opt1;
276 		opt1 = p;
277 		/* "foo.noopt" vs. "foo.opt" */
278 		if (strncmp(opt1, "no", 2) == 0 && strcmp(opt1 + 2, opt2) == 0)
279 			return (1);
280 		/* "foo.opt" vs. "foo.noopt" */
281 		if (strncmp(opt2, "no", 2) == 0 && strcmp(opt1, opt2 + 2) == 0)
282 			return (1);
283 	}
284 	/* "ro" / "rdonly" / "norw" / "rw" / "noro" */
285 	if ((vfs_isopt_ro(opt1) || vfs_isopt_rw(opt1)) &&
286 	    (vfs_isopt_ro(opt2) || vfs_isopt_rw(opt2)))
287 		return (1);
288 	return (0);
289 }
290 
291 /*
292  * If a mount option is specified several times,
293  * (with or without the "no" prefix) only keep
294  * the last occurrence of it.
295  */
296 static void
297 vfs_sanitizeopts(struct vfsoptlist *opts)
298 {
299 	struct vfsopt *opt, *opt2, *tmp;
300 
301 	TAILQ_FOREACH_REVERSE(opt, opts, vfsoptlist, link) {
302 		opt2 = TAILQ_PREV(opt, vfsoptlist, link);
303 		while (opt2 != NULL) {
304 			if (vfs_equalopts(opt->name, opt2->name)) {
305 				tmp = TAILQ_PREV(opt2, vfsoptlist, link);
306 				vfs_freeopt(opts, opt2);
307 				opt2 = tmp;
308 			} else {
309 				opt2 = TAILQ_PREV(opt2, vfsoptlist, link);
310 			}
311 		}
312 	}
313 }
314 
315 /*
316  * Build a linked list of mount options from a struct uio.
317  */
318 int
319 vfs_buildopts(struct uio *auio, struct vfsoptlist **options)
320 {
321 	struct vfsoptlist *opts;
322 	struct vfsopt *opt;
323 	size_t memused, namelen, optlen;
324 	unsigned int i, iovcnt;
325 	int error;
326 
327 	opts = malloc(sizeof(struct vfsoptlist), M_MOUNT, M_WAITOK);
328 	TAILQ_INIT(opts);
329 	memused = 0;
330 	iovcnt = auio->uio_iovcnt;
331 	for (i = 0; i < iovcnt; i += 2) {
332 		namelen = auio->uio_iov[i].iov_len;
333 		optlen = auio->uio_iov[i + 1].iov_len;
334 		memused += sizeof(struct vfsopt) + optlen + namelen;
335 		/*
336 		 * Avoid consuming too much memory, and attempts to overflow
337 		 * memused.
338 		 */
339 		if (memused > VFS_MOUNTARG_SIZE_MAX ||
340 		    optlen > VFS_MOUNTARG_SIZE_MAX ||
341 		    namelen > VFS_MOUNTARG_SIZE_MAX) {
342 			error = EINVAL;
343 			goto bad;
344 		}
345 
346 		opt = malloc(sizeof(struct vfsopt), M_MOUNT, M_WAITOK);
347 		opt->name = malloc(namelen, M_MOUNT, M_WAITOK);
348 		opt->value = NULL;
349 		opt->len = 0;
350 		opt->pos = i / 2;
351 		opt->seen = 0;
352 
353 		/*
354 		 * Do this early, so jumps to "bad" will free the current
355 		 * option.
356 		 */
357 		TAILQ_INSERT_TAIL(opts, opt, link);
358 
359 		if (auio->uio_segflg == UIO_SYSSPACE) {
360 			bcopy(auio->uio_iov[i].iov_base, opt->name, namelen);
361 		} else {
362 			error = copyin(auio->uio_iov[i].iov_base, opt->name,
363 			    namelen);
364 			if (error)
365 				goto bad;
366 		}
367 		/* Ensure names are null-terminated strings. */
368 		if (namelen == 0 || opt->name[namelen - 1] != '\0') {
369 			error = EINVAL;
370 			goto bad;
371 		}
372 		if (optlen != 0) {
373 			opt->len = optlen;
374 			opt->value = malloc(optlen, M_MOUNT, M_WAITOK);
375 			if (auio->uio_segflg == UIO_SYSSPACE) {
376 				bcopy(auio->uio_iov[i + 1].iov_base, opt->value,
377 				    optlen);
378 			} else {
379 				error = copyin(auio->uio_iov[i + 1].iov_base,
380 				    opt->value, optlen);
381 				if (error)
382 					goto bad;
383 			}
384 		}
385 	}
386 	vfs_sanitizeopts(opts);
387 	*options = opts;
388 	return (0);
389 bad:
390 	vfs_freeopts(opts);
391 	return (error);
392 }
393 
394 /*
395  * Merge the old mount options with the new ones passed
396  * in the MNT_UPDATE case.
397  *
398  * XXX: This function will keep a "nofoo" option in the new
399  * options.  E.g, if the option's canonical name is "foo",
400  * "nofoo" ends up in the mount point's active options.
401  */
402 static void
403 vfs_mergeopts(struct vfsoptlist *toopts, struct vfsoptlist *oldopts)
404 {
405 	struct vfsopt *opt, *new;
406 
407 	TAILQ_FOREACH(opt, oldopts, link) {
408 		new = malloc(sizeof(struct vfsopt), M_MOUNT, M_WAITOK);
409 		new->name = strdup(opt->name, M_MOUNT);
410 		if (opt->len != 0) {
411 			new->value = malloc(opt->len, M_MOUNT, M_WAITOK);
412 			bcopy(opt->value, new->value, opt->len);
413 		} else
414 			new->value = NULL;
415 		new->len = opt->len;
416 		new->seen = opt->seen;
417 		TAILQ_INSERT_HEAD(toopts, new, link);
418 	}
419 	vfs_sanitizeopts(toopts);
420 }
421 
422 /*
423  * Mount a filesystem.
424  */
425 #ifndef _SYS_SYSPROTO_H_
426 struct nmount_args {
427 	struct iovec *iovp;
428 	unsigned int iovcnt;
429 	int flags;
430 };
431 #endif
432 int
433 sys_nmount(struct thread *td, struct nmount_args *uap)
434 {
435 	struct uio *auio;
436 	int error;
437 	u_int iovcnt;
438 	uint64_t flags;
439 
440 	/*
441 	 * Mount flags are now 64-bits. On 32-bit archtectures only
442 	 * 32-bits are passed in, but from here on everything handles
443 	 * 64-bit flags correctly.
444 	 */
445 	flags = uap->flags;
446 
447 	AUDIT_ARG_FFLAGS(flags);
448 	CTR4(KTR_VFS, "%s: iovp %p with iovcnt %d and flags %d", __func__,
449 	    uap->iovp, uap->iovcnt, flags);
450 
451 	/*
452 	 * Filter out MNT_ROOTFS.  We do not want clients of nmount() in
453 	 * userspace to set this flag, but we must filter it out if we want
454 	 * MNT_UPDATE on the root file system to work.
455 	 * MNT_ROOTFS should only be set by the kernel when mounting its
456 	 * root file system.
457 	 */
458 	flags &= ~MNT_ROOTFS;
459 
460 	iovcnt = uap->iovcnt;
461 	/*
462 	 * Check that we have an even number of iovec's
463 	 * and that we have at least two options.
464 	 */
465 	if ((iovcnt & 1) || (iovcnt < 4)) {
466 		CTR2(KTR_VFS, "%s: failed for invalid iovcnt %d", __func__,
467 		    uap->iovcnt);
468 		return (EINVAL);
469 	}
470 
471 	error = copyinuio(uap->iovp, iovcnt, &auio);
472 	if (error) {
473 		CTR2(KTR_VFS, "%s: failed for invalid uio op with %d errno",
474 		    __func__, error);
475 		return (error);
476 	}
477 	error = vfs_donmount(td, flags, auio);
478 
479 	free(auio, M_IOV);
480 	return (error);
481 }
482 
483 /*
484  * ---------------------------------------------------------------------
485  * Various utility functions
486  */
487 
488 /*
489  * Get a reference on a mount point from a vnode.
490  *
491  * The vnode is allowed to be passed unlocked and race against dooming. Note in
492  * such case there are no guarantees the referenced mount point will still be
493  * associated with it after the function returns.
494  */
495 struct mount *
496 vfs_ref_from_vp(struct vnode *vp)
497 {
498 	struct mount *mp;
499 	struct mount_pcpu *mpcpu;
500 
501 	mp = atomic_load_ptr(&vp->v_mount);
502 	if (__predict_false(mp == NULL)) {
503 		return (mp);
504 	}
505 	if (vfs_op_thread_enter(mp, mpcpu)) {
506 		if (__predict_true(mp == vp->v_mount)) {
507 			vfs_mp_count_add_pcpu(mpcpu, ref, 1);
508 			vfs_op_thread_exit(mp, mpcpu);
509 		} else {
510 			vfs_op_thread_exit(mp, mpcpu);
511 			mp = NULL;
512 		}
513 	} else {
514 		MNT_ILOCK(mp);
515 		if (mp == vp->v_mount) {
516 			MNT_REF(mp);
517 			MNT_IUNLOCK(mp);
518 		} else {
519 			MNT_IUNLOCK(mp);
520 			mp = NULL;
521 		}
522 	}
523 	return (mp);
524 }
525 
526 void
527 vfs_ref(struct mount *mp)
528 {
529 	struct mount_pcpu *mpcpu;
530 
531 	CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
532 	if (vfs_op_thread_enter(mp, mpcpu)) {
533 		vfs_mp_count_add_pcpu(mpcpu, ref, 1);
534 		vfs_op_thread_exit(mp, mpcpu);
535 		return;
536 	}
537 
538 	MNT_ILOCK(mp);
539 	MNT_REF(mp);
540 	MNT_IUNLOCK(mp);
541 }
542 
543 /*
544  * Register ump as an upper mount of the mount associated with
545  * vnode vp.  This registration will be tracked through
546  * mount_upper_node upper, which should be allocated by the
547  * caller and stored in per-mount data associated with mp.
548  *
549  * If successful, this function will return the mount associated
550  * with vp, and will ensure that it cannot be unmounted until
551  * ump has been unregistered as one of its upper mounts.
552  *
553  * Upon failure this function will return NULL.
554  */
555 struct mount *
556 vfs_register_upper_from_vp(struct vnode *vp, struct mount *ump,
557     struct mount_upper_node *upper)
558 {
559 	struct mount *mp;
560 
561 	mp = atomic_load_ptr(&vp->v_mount);
562 	if (mp == NULL)
563 		return (NULL);
564 	MNT_ILOCK(mp);
565 	if (mp != vp->v_mount ||
566 	    ((mp->mnt_kern_flag & (MNTK_UNMOUNT | MNTK_RECURSE)) != 0)) {
567 		MNT_IUNLOCK(mp);
568 		return (NULL);
569 	}
570 	KASSERT(ump != mp, ("upper and lower mounts are identical"));
571 	upper->mp = ump;
572 	MNT_REF(mp);
573 	TAILQ_INSERT_TAIL(&mp->mnt_uppers, upper, mnt_upper_link);
574 	MNT_IUNLOCK(mp);
575 	return (mp);
576 }
577 
578 /*
579  * Register upper mount ump to receive vnode unlink/reclaim
580  * notifications from lower mount mp. This registration will
581  * be tracked through mount_upper_node upper, which should be
582  * allocated by the caller and stored in per-mount data
583  * associated with mp.
584  *
585  * ump must already be registered as an upper mount of mp
586  * through a call to vfs_register_upper_from_vp().
587  */
588 void
589 vfs_register_for_notification(struct mount *mp, struct mount *ump,
590     struct mount_upper_node *upper)
591 {
592 	upper->mp = ump;
593 	MNT_ILOCK(mp);
594 	TAILQ_INSERT_TAIL(&mp->mnt_notify, upper, mnt_upper_link);
595 	MNT_IUNLOCK(mp);
596 }
597 
598 static void
599 vfs_drain_upper_locked(struct mount *mp)
600 {
601 	mtx_assert(MNT_MTX(mp), MA_OWNED);
602 	while (mp->mnt_upper_pending != 0) {
603 		mp->mnt_kern_flag |= MNTK_UPPER_WAITER;
604 		msleep(&mp->mnt_uppers, MNT_MTX(mp), 0, "mntupw", 0);
605 	}
606 }
607 
608 /*
609  * Undo a previous call to vfs_register_for_notification().
610  * The mount represented by upper must be currently registered
611  * as an upper mount for mp.
612  */
613 void
614 vfs_unregister_for_notification(struct mount *mp,
615     struct mount_upper_node *upper)
616 {
617 	MNT_ILOCK(mp);
618 	vfs_drain_upper_locked(mp);
619 	TAILQ_REMOVE(&mp->mnt_notify, upper, mnt_upper_link);
620 	MNT_IUNLOCK(mp);
621 }
622 
623 /*
624  * Undo a previous call to vfs_register_upper_from_vp().
625  * This must be done before mp can be unmounted.
626  */
627 void
628 vfs_unregister_upper(struct mount *mp, struct mount_upper_node *upper)
629 {
630 	MNT_ILOCK(mp);
631 	KASSERT((mp->mnt_kern_flag & MNTK_UNMOUNT) == 0,
632 	    ("registered upper with pending unmount"));
633 	vfs_drain_upper_locked(mp);
634 	TAILQ_REMOVE(&mp->mnt_uppers, upper, mnt_upper_link);
635 	if ((mp->mnt_kern_flag & MNTK_TASKQUEUE_WAITER) != 0 &&
636 	    TAILQ_EMPTY(&mp->mnt_uppers)) {
637 		mp->mnt_kern_flag &= ~MNTK_TASKQUEUE_WAITER;
638 		wakeup(&mp->mnt_taskqueue_link);
639 	}
640 	MNT_REL(mp);
641 	MNT_IUNLOCK(mp);
642 }
643 
644 void
645 vfs_rel(struct mount *mp)
646 {
647 	struct mount_pcpu *mpcpu;
648 
649 	CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
650 	if (vfs_op_thread_enter(mp, mpcpu)) {
651 		vfs_mp_count_sub_pcpu(mpcpu, ref, 1);
652 		vfs_op_thread_exit(mp, mpcpu);
653 		return;
654 	}
655 
656 	MNT_ILOCK(mp);
657 	MNT_REL(mp);
658 	MNT_IUNLOCK(mp);
659 }
660 
661 /*
662  * Allocate and initialize the mount point struct.
663  */
664 struct mount *
665 vfs_mount_alloc(struct vnode *vp, struct vfsconf *vfsp, const char *fspath,
666     struct ucred *cred)
667 {
668 	struct mount *mp;
669 
670 	mp = uma_zalloc(mount_zone, M_WAITOK);
671 	bzero(&mp->mnt_startzero,
672 	    __rangeof(struct mount, mnt_startzero, mnt_endzero));
673 	mp->mnt_kern_flag = 0;
674 	mp->mnt_flag = 0;
675 	mp->mnt_rootvnode = NULL;
676 	mp->mnt_vnodecovered = NULL;
677 	mp->mnt_op = NULL;
678 	mp->mnt_vfc = NULL;
679 	TAILQ_INIT(&mp->mnt_nvnodelist);
680 	mp->mnt_nvnodelistsize = 0;
681 	TAILQ_INIT(&mp->mnt_lazyvnodelist);
682 	mp->mnt_lazyvnodelistsize = 0;
683 	if (mp->mnt_ref != 0 || mp->mnt_lockref != 0 ||
684 	    mp->mnt_writeopcount != 0)
685 		panic("%s: non-zero counters on new mp %p\n", __func__, mp);
686 	if (mp->mnt_vfs_ops != 1)
687 		panic("%s: vfs_ops should be 1 but %d found\n", __func__,
688 		    mp->mnt_vfs_ops);
689 	(void) vfs_busy(mp, MBF_NOWAIT);
690 	atomic_add_acq_int(&vfsp->vfc_refcount, 1);
691 	mp->mnt_op = vfsp->vfc_vfsops;
692 	mp->mnt_vfc = vfsp;
693 	mp->mnt_stat.f_type = vfsp->vfc_typenum;
694 	mp->mnt_gen++;
695 	strlcpy(mp->mnt_stat.f_fstypename, vfsp->vfc_name, MFSNAMELEN);
696 	mp->mnt_vnodecovered = vp;
697 	mp->mnt_cred = crdup(cred);
698 	mp->mnt_stat.f_owner = cred->cr_uid;
699 	strlcpy(mp->mnt_stat.f_mntonname, fspath, MNAMELEN);
700 	mp->mnt_iosize_max = DFLTPHYS;
701 #ifdef MAC
702 	mac_mount_init(mp);
703 	mac_mount_create(cred, mp);
704 #endif
705 	arc4rand(&mp->mnt_hashseed, sizeof mp->mnt_hashseed, 0);
706 	mp->mnt_upper_pending = 0;
707 	TAILQ_INIT(&mp->mnt_uppers);
708 	TAILQ_INIT(&mp->mnt_notify);
709 	mp->mnt_taskqueue_flags = 0;
710 	mp->mnt_unmount_retries = 0;
711 	return (mp);
712 }
713 
714 /*
715  * Destroy the mount struct previously allocated by vfs_mount_alloc().
716  */
717 void
718 vfs_mount_destroy(struct mount *mp)
719 {
720 
721 	if (mp->mnt_vfs_ops == 0)
722 		panic("%s: entered with zero vfs_ops\n", __func__);
723 
724 	vfs_assert_mount_counters(mp);
725 
726 	MNT_ILOCK(mp);
727 	mp->mnt_kern_flag |= MNTK_REFEXPIRE;
728 	if (mp->mnt_kern_flag & MNTK_MWAIT) {
729 		mp->mnt_kern_flag &= ~MNTK_MWAIT;
730 		wakeup(mp);
731 	}
732 	while (mp->mnt_ref)
733 		msleep(mp, MNT_MTX(mp), PVFS, "mntref", 0);
734 	KASSERT(mp->mnt_ref == 0,
735 	    ("%s: invalid refcount in the drain path @ %s:%d", __func__,
736 	    __FILE__, __LINE__));
737 	if (mp->mnt_writeopcount != 0)
738 		panic("vfs_mount_destroy: nonzero writeopcount");
739 	if (mp->mnt_secondary_writes != 0)
740 		panic("vfs_mount_destroy: nonzero secondary_writes");
741 	atomic_subtract_rel_int(&mp->mnt_vfc->vfc_refcount, 1);
742 	if (!TAILQ_EMPTY(&mp->mnt_nvnodelist)) {
743 		struct vnode *vp;
744 
745 		TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes)
746 			vn_printf(vp, "dangling vnode ");
747 		panic("unmount: dangling vnode");
748 	}
749 	KASSERT(mp->mnt_upper_pending == 0, ("mnt_upper_pending"));
750 	KASSERT(TAILQ_EMPTY(&mp->mnt_uppers), ("mnt_uppers"));
751 	KASSERT(TAILQ_EMPTY(&mp->mnt_notify), ("mnt_notify"));
752 	if (mp->mnt_nvnodelistsize != 0)
753 		panic("vfs_mount_destroy: nonzero nvnodelistsize");
754 	if (mp->mnt_lazyvnodelistsize != 0)
755 		panic("vfs_mount_destroy: nonzero lazyvnodelistsize");
756 	if (mp->mnt_lockref != 0)
757 		panic("vfs_mount_destroy: nonzero lock refcount");
758 	MNT_IUNLOCK(mp);
759 
760 	if (mp->mnt_vfs_ops != 1)
761 		panic("%s: vfs_ops should be 1 but %d found\n", __func__,
762 		    mp->mnt_vfs_ops);
763 
764 	if (mp->mnt_rootvnode != NULL)
765 		panic("%s: mount point still has a root vnode %p\n", __func__,
766 		    mp->mnt_rootvnode);
767 
768 	if (mp->mnt_vnodecovered != NULL)
769 		vrele(mp->mnt_vnodecovered);
770 #ifdef MAC
771 	mac_mount_destroy(mp);
772 #endif
773 	if (mp->mnt_opt != NULL)
774 		vfs_freeopts(mp->mnt_opt);
775 	crfree(mp->mnt_cred);
776 	uma_zfree(mount_zone, mp);
777 }
778 
779 static bool
780 vfs_should_downgrade_to_ro_mount(uint64_t fsflags, int error)
781 {
782 	/* This is an upgrade of an exisiting mount. */
783 	if ((fsflags & MNT_UPDATE) != 0)
784 		return (false);
785 	/* This is already an R/O mount. */
786 	if ((fsflags & MNT_RDONLY) != 0)
787 		return (false);
788 
789 	switch (error) {
790 	case ENODEV:	/* generic, geom, ... */
791 	case EACCES:	/* cam/scsi, ... */
792 	case EROFS:	/* md, mmcsd, ... */
793 		/*
794 		 * These errors can be returned by the storage layer to signal
795 		 * that the media is read-only.  No harm in the R/O mount
796 		 * attempt if the error was returned for some other reason.
797 		 */
798 		return (true);
799 	default:
800 		return (false);
801 	}
802 }
803 
804 int
805 vfs_donmount(struct thread *td, uint64_t fsflags, struct uio *fsoptions)
806 {
807 	struct vfsoptlist *optlist;
808 	struct vfsopt *opt, *tmp_opt;
809 	char *fstype, *fspath, *errmsg;
810 	int error, fstypelen, fspathlen, errmsg_len, errmsg_pos;
811 	bool autoro;
812 
813 	errmsg = fspath = NULL;
814 	errmsg_len = fspathlen = 0;
815 	errmsg_pos = -1;
816 	autoro = default_autoro;
817 
818 	error = vfs_buildopts(fsoptions, &optlist);
819 	if (error)
820 		return (error);
821 
822 	if (vfs_getopt(optlist, "errmsg", (void **)&errmsg, &errmsg_len) == 0)
823 		errmsg_pos = vfs_getopt_pos(optlist, "errmsg");
824 
825 	/*
826 	 * We need these two options before the others,
827 	 * and they are mandatory for any filesystem.
828 	 * Ensure they are NUL terminated as well.
829 	 */
830 	fstypelen = 0;
831 	error = vfs_getopt(optlist, "fstype", (void **)&fstype, &fstypelen);
832 	if (error || fstypelen <= 0 || fstype[fstypelen - 1] != '\0') {
833 		error = EINVAL;
834 		if (errmsg != NULL)
835 			strncpy(errmsg, "Invalid fstype", errmsg_len);
836 		goto bail;
837 	}
838 	fspathlen = 0;
839 	error = vfs_getopt(optlist, "fspath", (void **)&fspath, &fspathlen);
840 	if (error || fspathlen <= 0 || fspath[fspathlen - 1] != '\0') {
841 		error = EINVAL;
842 		if (errmsg != NULL)
843 			strncpy(errmsg, "Invalid fspath", errmsg_len);
844 		goto bail;
845 	}
846 
847 	/*
848 	 * We need to see if we have the "update" option
849 	 * before we call vfs_domount(), since vfs_domount() has special
850 	 * logic based on MNT_UPDATE.  This is very important
851 	 * when we want to update the root filesystem.
852 	 */
853 	TAILQ_FOREACH_SAFE(opt, optlist, link, tmp_opt) {
854 		int do_freeopt = 0;
855 
856 		if (strcmp(opt->name, "update") == 0) {
857 			fsflags |= MNT_UPDATE;
858 			do_freeopt = 1;
859 		}
860 		else if (strcmp(opt->name, "async") == 0)
861 			fsflags |= MNT_ASYNC;
862 		else if (strcmp(opt->name, "force") == 0) {
863 			fsflags |= MNT_FORCE;
864 			do_freeopt = 1;
865 		}
866 		else if (strcmp(opt->name, "reload") == 0) {
867 			fsflags |= MNT_RELOAD;
868 			do_freeopt = 1;
869 		}
870 		else if (strcmp(opt->name, "multilabel") == 0)
871 			fsflags |= MNT_MULTILABEL;
872 		else if (strcmp(opt->name, "noasync") == 0)
873 			fsflags &= ~MNT_ASYNC;
874 		else if (strcmp(opt->name, "noatime") == 0)
875 			fsflags |= MNT_NOATIME;
876 		else if (strcmp(opt->name, "atime") == 0) {
877 			free(opt->name, M_MOUNT);
878 			opt->name = strdup("nonoatime", M_MOUNT);
879 		}
880 		else if (strcmp(opt->name, "noclusterr") == 0)
881 			fsflags |= MNT_NOCLUSTERR;
882 		else if (strcmp(opt->name, "clusterr") == 0) {
883 			free(opt->name, M_MOUNT);
884 			opt->name = strdup("nonoclusterr", M_MOUNT);
885 		}
886 		else if (strcmp(opt->name, "noclusterw") == 0)
887 			fsflags |= MNT_NOCLUSTERW;
888 		else if (strcmp(opt->name, "clusterw") == 0) {
889 			free(opt->name, M_MOUNT);
890 			opt->name = strdup("nonoclusterw", M_MOUNT);
891 		}
892 		else if (strcmp(opt->name, "noexec") == 0)
893 			fsflags |= MNT_NOEXEC;
894 		else if (strcmp(opt->name, "exec") == 0) {
895 			free(opt->name, M_MOUNT);
896 			opt->name = strdup("nonoexec", M_MOUNT);
897 		}
898 		else if (strcmp(opt->name, "nosuid") == 0)
899 			fsflags |= MNT_NOSUID;
900 		else if (strcmp(opt->name, "suid") == 0) {
901 			free(opt->name, M_MOUNT);
902 			opt->name = strdup("nonosuid", M_MOUNT);
903 		}
904 		else if (strcmp(opt->name, "nosymfollow") == 0)
905 			fsflags |= MNT_NOSYMFOLLOW;
906 		else if (strcmp(opt->name, "symfollow") == 0) {
907 			free(opt->name, M_MOUNT);
908 			opt->name = strdup("nonosymfollow", M_MOUNT);
909 		}
910 		else if (strcmp(opt->name, "noro") == 0) {
911 			fsflags &= ~MNT_RDONLY;
912 			autoro = false;
913 		}
914 		else if (strcmp(opt->name, "rw") == 0) {
915 			fsflags &= ~MNT_RDONLY;
916 			autoro = false;
917 		}
918 		else if (strcmp(opt->name, "ro") == 0) {
919 			fsflags |= MNT_RDONLY;
920 			autoro = false;
921 		}
922 		else if (strcmp(opt->name, "rdonly") == 0) {
923 			free(opt->name, M_MOUNT);
924 			opt->name = strdup("ro", M_MOUNT);
925 			fsflags |= MNT_RDONLY;
926 			autoro = false;
927 		}
928 		else if (strcmp(opt->name, "autoro") == 0) {
929 			do_freeopt = 1;
930 			autoro = true;
931 		}
932 		else if (strcmp(opt->name, "suiddir") == 0)
933 			fsflags |= MNT_SUIDDIR;
934 		else if (strcmp(opt->name, "sync") == 0)
935 			fsflags |= MNT_SYNCHRONOUS;
936 		else if (strcmp(opt->name, "union") == 0)
937 			fsflags |= MNT_UNION;
938 		else if (strcmp(opt->name, "automounted") == 0) {
939 			fsflags |= MNT_AUTOMOUNTED;
940 			do_freeopt = 1;
941 		} else if (strcmp(opt->name, "nocover") == 0) {
942 			fsflags |= MNT_NOCOVER;
943 			do_freeopt = 1;
944 		} else if (strcmp(opt->name, "cover") == 0) {
945 			fsflags &= ~MNT_NOCOVER;
946 			do_freeopt = 1;
947 		} else if (strcmp(opt->name, "emptydir") == 0) {
948 			fsflags |= MNT_EMPTYDIR;
949 			do_freeopt = 1;
950 		} else if (strcmp(opt->name, "noemptydir") == 0) {
951 			fsflags &= ~MNT_EMPTYDIR;
952 			do_freeopt = 1;
953 		}
954 		if (do_freeopt)
955 			vfs_freeopt(optlist, opt);
956 	}
957 
958 	/*
959 	 * Be ultra-paranoid about making sure the type and fspath
960 	 * variables will fit in our mp buffers, including the
961 	 * terminating NUL.
962 	 */
963 	if (fstypelen > MFSNAMELEN || fspathlen > MNAMELEN) {
964 		error = ENAMETOOLONG;
965 		goto bail;
966 	}
967 
968 	error = vfs_domount(td, fstype, fspath, fsflags, &optlist);
969 
970 	/*
971 	 * See if we can mount in the read-only mode if the error code suggests
972 	 * that it could be possible and the mount options allow for that.
973 	 * Never try it if "[no]{ro|rw}" has been explicitly requested and not
974 	 * overridden by "autoro".
975 	 */
976 	if (autoro && vfs_should_downgrade_to_ro_mount(fsflags, error)) {
977 		printf("%s: R/W mount failed, possibly R/O media,"
978 		    " trying R/O mount\n", __func__);
979 		fsflags |= MNT_RDONLY;
980 		error = vfs_domount(td, fstype, fspath, fsflags, &optlist);
981 	}
982 bail:
983 	/* copyout the errmsg */
984 	if (errmsg_pos != -1 && ((2 * errmsg_pos + 1) < fsoptions->uio_iovcnt)
985 	    && errmsg_len > 0 && errmsg != NULL) {
986 		if (fsoptions->uio_segflg == UIO_SYSSPACE) {
987 			bcopy(errmsg,
988 			    fsoptions->uio_iov[2 * errmsg_pos + 1].iov_base,
989 			    fsoptions->uio_iov[2 * errmsg_pos + 1].iov_len);
990 		} else {
991 			copyout(errmsg,
992 			    fsoptions->uio_iov[2 * errmsg_pos + 1].iov_base,
993 			    fsoptions->uio_iov[2 * errmsg_pos + 1].iov_len);
994 		}
995 	}
996 
997 	if (optlist != NULL)
998 		vfs_freeopts(optlist);
999 	return (error);
1000 }
1001 
1002 /*
1003  * Old mount API.
1004  */
1005 #ifndef _SYS_SYSPROTO_H_
1006 struct mount_args {
1007 	char	*type;
1008 	char	*path;
1009 	int	flags;
1010 	caddr_t	data;
1011 };
1012 #endif
1013 /* ARGSUSED */
1014 int
1015 sys_mount(struct thread *td, struct mount_args *uap)
1016 {
1017 	char *fstype;
1018 	struct vfsconf *vfsp = NULL;
1019 	struct mntarg *ma = NULL;
1020 	uint64_t flags;
1021 	int error;
1022 
1023 	/*
1024 	 * Mount flags are now 64-bits. On 32-bit architectures only
1025 	 * 32-bits are passed in, but from here on everything handles
1026 	 * 64-bit flags correctly.
1027 	 */
1028 	flags = uap->flags;
1029 
1030 	AUDIT_ARG_FFLAGS(flags);
1031 
1032 	/*
1033 	 * Filter out MNT_ROOTFS.  We do not want clients of mount() in
1034 	 * userspace to set this flag, but we must filter it out if we want
1035 	 * MNT_UPDATE on the root file system to work.
1036 	 * MNT_ROOTFS should only be set by the kernel when mounting its
1037 	 * root file system.
1038 	 */
1039 	flags &= ~MNT_ROOTFS;
1040 
1041 	fstype = malloc(MFSNAMELEN, M_TEMP, M_WAITOK);
1042 	error = copyinstr(uap->type, fstype, MFSNAMELEN, NULL);
1043 	if (error) {
1044 		free(fstype, M_TEMP);
1045 		return (error);
1046 	}
1047 
1048 	AUDIT_ARG_TEXT(fstype);
1049 	vfsp = vfs_byname_kld(fstype, td, &error);
1050 	free(fstype, M_TEMP);
1051 	if (vfsp == NULL)
1052 		return (ENOENT);
1053 	if (((vfsp->vfc_flags & VFCF_SBDRY) != 0 &&
1054 	    vfsp->vfc_vfsops_sd->vfs_cmount == NULL) ||
1055 	    ((vfsp->vfc_flags & VFCF_SBDRY) == 0 &&
1056 	    vfsp->vfc_vfsops->vfs_cmount == NULL))
1057 		return (EOPNOTSUPP);
1058 
1059 	ma = mount_argsu(ma, "fstype", uap->type, MFSNAMELEN);
1060 	ma = mount_argsu(ma, "fspath", uap->path, MNAMELEN);
1061 	ma = mount_argb(ma, flags & MNT_RDONLY, "noro");
1062 	ma = mount_argb(ma, !(flags & MNT_NOSUID), "nosuid");
1063 	ma = mount_argb(ma, !(flags & MNT_NOEXEC), "noexec");
1064 
1065 	if ((vfsp->vfc_flags & VFCF_SBDRY) != 0)
1066 		return (vfsp->vfc_vfsops_sd->vfs_cmount(ma, uap->data, flags));
1067 	return (vfsp->vfc_vfsops->vfs_cmount(ma, uap->data, flags));
1068 }
1069 
1070 /*
1071  * vfs_domount_first(): first file system mount (not update)
1072  */
1073 static int
1074 vfs_domount_first(
1075 	struct thread *td,		/* Calling thread. */
1076 	struct vfsconf *vfsp,		/* File system type. */
1077 	char *fspath,			/* Mount path. */
1078 	struct vnode *vp,		/* Vnode to be covered. */
1079 	uint64_t fsflags,		/* Flags common to all filesystems. */
1080 	struct vfsoptlist **optlist	/* Options local to the filesystem. */
1081 	)
1082 {
1083 	struct vattr va;
1084 	struct mount *mp;
1085 	struct vnode *newdp, *rootvp;
1086 	int error, error1;
1087 	bool unmounted;
1088 
1089 	ASSERT_VOP_ELOCKED(vp, __func__);
1090 	KASSERT((fsflags & MNT_UPDATE) == 0, ("MNT_UPDATE shouldn't be here"));
1091 
1092 	if ((fsflags & MNT_EMPTYDIR) != 0) {
1093 		error = vfs_emptydir(vp);
1094 		if (error != 0) {
1095 			vput(vp);
1096 			return (error);
1097 		}
1098 	}
1099 
1100 	/*
1101 	 * If the jail of the calling thread lacks permission for this type of
1102 	 * file system, or is trying to cover its own root, deny immediately.
1103 	 */
1104 	if (jailed(td->td_ucred) && (!prison_allow(td->td_ucred,
1105 	    vfsp->vfc_prison_flag) || vp == td->td_ucred->cr_prison->pr_root)) {
1106 		vput(vp);
1107 		return (EPERM);
1108 	}
1109 
1110 	/*
1111 	 * If the user is not root, ensure that they own the directory
1112 	 * onto which we are attempting to mount.
1113 	 */
1114 	error = VOP_GETATTR(vp, &va, td->td_ucred);
1115 	if (error == 0 && va.va_uid != td->td_ucred->cr_uid)
1116 		error = priv_check_cred(td->td_ucred, PRIV_VFS_ADMIN);
1117 	if (error == 0)
1118 		error = vinvalbuf(vp, V_SAVE, 0, 0);
1119 	if (error == 0 && vp->v_type != VDIR)
1120 		error = ENOTDIR;
1121 	if (error == 0) {
1122 		VI_LOCK(vp);
1123 		if ((vp->v_iflag & VI_MOUNT) == 0 && vp->v_mountedhere == NULL)
1124 			vp->v_iflag |= VI_MOUNT;
1125 		else
1126 			error = EBUSY;
1127 		VI_UNLOCK(vp);
1128 	}
1129 	if (error != 0) {
1130 		vput(vp);
1131 		return (error);
1132 	}
1133 	vn_seqc_write_begin(vp);
1134 	VOP_UNLOCK(vp);
1135 
1136 	/* Allocate and initialize the filesystem. */
1137 	mp = vfs_mount_alloc(vp, vfsp, fspath, td->td_ucred);
1138 	/* XXXMAC: pass to vfs_mount_alloc? */
1139 	mp->mnt_optnew = *optlist;
1140 	/* Set the mount level flags. */
1141 	mp->mnt_flag = (fsflags & (MNT_UPDATEMASK | MNT_ROOTFS | MNT_RDONLY));
1142 
1143 	/*
1144 	 * Mount the filesystem.
1145 	 * XXX The final recipients of VFS_MOUNT just overwrite the ndp they
1146 	 * get.  No freeing of cn_pnbuf.
1147 	 */
1148 	error1 = 0;
1149 	unmounted = true;
1150 	if ((error = VFS_MOUNT(mp)) != 0 ||
1151 	    (error1 = VFS_STATFS(mp, &mp->mnt_stat)) != 0 ||
1152 	    (error1 = VFS_ROOT(mp, LK_EXCLUSIVE, &newdp)) != 0) {
1153 		rootvp = NULL;
1154 		if (error1 != 0) {
1155 			MPASS(error == 0);
1156 			rootvp = vfs_cache_root_clear(mp);
1157 			if (rootvp != NULL) {
1158 				vhold(rootvp);
1159 				vrele(rootvp);
1160 			}
1161 			(void)vn_start_write(NULL, &mp, V_WAIT);
1162 			MNT_ILOCK(mp);
1163 			mp->mnt_kern_flag |= MNTK_UNMOUNT | MNTK_UNMOUNTF;
1164 			MNT_IUNLOCK(mp);
1165 			VFS_PURGE(mp);
1166 			error = VFS_UNMOUNT(mp, 0);
1167 			vn_finished_write(mp);
1168 			if (error != 0) {
1169 				printf(
1170 		    "failed post-mount (%d): rollback unmount returned %d\n",
1171 				    error1, error);
1172 				unmounted = false;
1173 			}
1174 			error = error1;
1175 		}
1176 		vfs_unbusy(mp);
1177 		mp->mnt_vnodecovered = NULL;
1178 		if (unmounted) {
1179 			/* XXXKIB wait for mnt_lockref drain? */
1180 			vfs_mount_destroy(mp);
1181 		}
1182 		VI_LOCK(vp);
1183 		vp->v_iflag &= ~VI_MOUNT;
1184 		VI_UNLOCK(vp);
1185 		if (rootvp != NULL) {
1186 			vn_seqc_write_end(rootvp);
1187 			vdrop(rootvp);
1188 		}
1189 		vn_seqc_write_end(vp);
1190 		vrele(vp);
1191 		return (error);
1192 	}
1193 	vn_seqc_write_begin(newdp);
1194 	VOP_UNLOCK(newdp);
1195 
1196 	if (mp->mnt_opt != NULL)
1197 		vfs_freeopts(mp->mnt_opt);
1198 	mp->mnt_opt = mp->mnt_optnew;
1199 	*optlist = NULL;
1200 
1201 	/*
1202 	 * Prevent external consumers of mount options from reading mnt_optnew.
1203 	 */
1204 	mp->mnt_optnew = NULL;
1205 
1206 	MNT_ILOCK(mp);
1207 	if ((mp->mnt_flag & MNT_ASYNC) != 0 &&
1208 	    (mp->mnt_kern_flag & MNTK_NOASYNC) == 0)
1209 		mp->mnt_kern_flag |= MNTK_ASYNC;
1210 	else
1211 		mp->mnt_kern_flag &= ~MNTK_ASYNC;
1212 	MNT_IUNLOCK(mp);
1213 
1214 	VI_LOCK(vp);
1215 	vn_irflag_set_locked(vp, VIRF_MOUNTPOINT);
1216 	vp->v_mountedhere = mp;
1217 	VI_UNLOCK(vp);
1218 	cache_purge(vp);
1219 
1220 	/*
1221 	 * We need to lock both vnodes.
1222 	 *
1223 	 * Use vn_lock_pair to avoid establishing an ordering between vnodes
1224 	 * from different filesystems.
1225 	 */
1226 	vn_lock_pair(vp, false, newdp, false);
1227 
1228 	VI_LOCK(vp);
1229 	vp->v_iflag &= ~VI_MOUNT;
1230 	VI_UNLOCK(vp);
1231 	/* Place the new filesystem at the end of the mount list. */
1232 	mtx_lock(&mountlist_mtx);
1233 	TAILQ_INSERT_TAIL(&mountlist, mp, mnt_list);
1234 	mtx_unlock(&mountlist_mtx);
1235 	vfs_event_signal(NULL, VQ_MOUNT, 0);
1236 	VOP_UNLOCK(vp);
1237 	EVENTHANDLER_DIRECT_INVOKE(vfs_mounted, mp, newdp, td);
1238 	VOP_UNLOCK(newdp);
1239 	mount_devctl_event("MOUNT", mp, false);
1240 	mountcheckdirs(vp, newdp);
1241 	vn_seqc_write_end(vp);
1242 	vn_seqc_write_end(newdp);
1243 	vrele(newdp);
1244 	if ((mp->mnt_flag & MNT_RDONLY) == 0)
1245 		vfs_allocate_syncvnode(mp);
1246 	vfs_op_exit(mp);
1247 	vfs_unbusy(mp);
1248 	return (0);
1249 }
1250 
1251 /*
1252  * vfs_domount_update(): update of mounted file system
1253  */
1254 static int
1255 vfs_domount_update(
1256 	struct thread *td,		/* Calling thread. */
1257 	struct vnode *vp,		/* Mount point vnode. */
1258 	uint64_t fsflags,		/* Flags common to all filesystems. */
1259 	struct vfsoptlist **optlist	/* Options local to the filesystem. */
1260 	)
1261 {
1262 	struct export_args export;
1263 	struct o2export_args o2export;
1264 	struct vnode *rootvp;
1265 	void *bufp;
1266 	struct mount *mp;
1267 	int error, export_error, i, len;
1268 	uint64_t flag;
1269 	gid_t *grps;
1270 
1271 	ASSERT_VOP_ELOCKED(vp, __func__);
1272 	KASSERT((fsflags & MNT_UPDATE) != 0, ("MNT_UPDATE should be here"));
1273 	mp = vp->v_mount;
1274 
1275 	if ((vp->v_vflag & VV_ROOT) == 0) {
1276 		if (vfs_copyopt(*optlist, "export", &export, sizeof(export))
1277 		    == 0)
1278 			error = EXDEV;
1279 		else
1280 			error = EINVAL;
1281 		vput(vp);
1282 		return (error);
1283 	}
1284 
1285 	/*
1286 	 * We only allow the filesystem to be reloaded if it
1287 	 * is currently mounted read-only.
1288 	 */
1289 	flag = mp->mnt_flag;
1290 	if ((fsflags & MNT_RELOAD) != 0 && (flag & MNT_RDONLY) == 0) {
1291 		vput(vp);
1292 		return (EOPNOTSUPP);	/* Needs translation */
1293 	}
1294 	/*
1295 	 * Only privileged root, or (if MNT_USER is set) the user that
1296 	 * did the original mount is permitted to update it.
1297 	 */
1298 	error = vfs_suser(mp, td);
1299 	if (error != 0) {
1300 		vput(vp);
1301 		return (error);
1302 	}
1303 	if (vfs_busy(mp, MBF_NOWAIT)) {
1304 		vput(vp);
1305 		return (EBUSY);
1306 	}
1307 	VI_LOCK(vp);
1308 	if ((vp->v_iflag & VI_MOUNT) != 0 || vp->v_mountedhere != NULL) {
1309 		VI_UNLOCK(vp);
1310 		vfs_unbusy(mp);
1311 		vput(vp);
1312 		return (EBUSY);
1313 	}
1314 	vp->v_iflag |= VI_MOUNT;
1315 	VI_UNLOCK(vp);
1316 	VOP_UNLOCK(vp);
1317 
1318 	vfs_op_enter(mp);
1319 	vn_seqc_write_begin(vp);
1320 
1321 	rootvp = NULL;
1322 	MNT_ILOCK(mp);
1323 	if ((mp->mnt_kern_flag & MNTK_UNMOUNT) != 0) {
1324 		MNT_IUNLOCK(mp);
1325 		error = EBUSY;
1326 		goto end;
1327 	}
1328 	mp->mnt_flag &= ~MNT_UPDATEMASK;
1329 	mp->mnt_flag |= fsflags & (MNT_RELOAD | MNT_FORCE | MNT_UPDATE |
1330 	    MNT_SNAPSHOT | MNT_ROOTFS | MNT_UPDATEMASK | MNT_RDONLY);
1331 	if ((mp->mnt_flag & MNT_ASYNC) == 0)
1332 		mp->mnt_kern_flag &= ~MNTK_ASYNC;
1333 	rootvp = vfs_cache_root_clear(mp);
1334 	MNT_IUNLOCK(mp);
1335 	mp->mnt_optnew = *optlist;
1336 	vfs_mergeopts(mp->mnt_optnew, mp->mnt_opt);
1337 
1338 	/*
1339 	 * Mount the filesystem.
1340 	 * XXX The final recipients of VFS_MOUNT just overwrite the ndp they
1341 	 * get.  No freeing of cn_pnbuf.
1342 	 */
1343 	error = VFS_MOUNT(mp);
1344 
1345 	export_error = 0;
1346 	/* Process the export option. */
1347 	if (error == 0 && vfs_getopt(mp->mnt_optnew, "export", &bufp,
1348 	    &len) == 0) {
1349 		/* Assume that there is only 1 ABI for each length. */
1350 		switch (len) {
1351 		case (sizeof(struct oexport_args)):
1352 			bzero(&o2export, sizeof(o2export));
1353 			/* FALLTHROUGH */
1354 		case (sizeof(o2export)):
1355 			bcopy(bufp, &o2export, len);
1356 			export.ex_flags = (uint64_t)o2export.ex_flags;
1357 			export.ex_root = o2export.ex_root;
1358 			export.ex_uid = o2export.ex_anon.cr_uid;
1359 			export.ex_groups = NULL;
1360 			export.ex_ngroups = o2export.ex_anon.cr_ngroups;
1361 			if (export.ex_ngroups > 0) {
1362 				if (export.ex_ngroups <= XU_NGROUPS) {
1363 					export.ex_groups = malloc(
1364 					    export.ex_ngroups * sizeof(gid_t),
1365 					    M_TEMP, M_WAITOK);
1366 					for (i = 0; i < export.ex_ngroups; i++)
1367 						export.ex_groups[i] =
1368 						  o2export.ex_anon.cr_groups[i];
1369 				} else
1370 					export_error = EINVAL;
1371 			} else if (export.ex_ngroups < 0)
1372 				export_error = EINVAL;
1373 			export.ex_addr = o2export.ex_addr;
1374 			export.ex_addrlen = o2export.ex_addrlen;
1375 			export.ex_mask = o2export.ex_mask;
1376 			export.ex_masklen = o2export.ex_masklen;
1377 			export.ex_indexfile = o2export.ex_indexfile;
1378 			export.ex_numsecflavors = o2export.ex_numsecflavors;
1379 			if (export.ex_numsecflavors < MAXSECFLAVORS) {
1380 				for (i = 0; i < export.ex_numsecflavors; i++)
1381 					export.ex_secflavors[i] =
1382 					    o2export.ex_secflavors[i];
1383 			} else
1384 				export_error = EINVAL;
1385 			if (export_error == 0)
1386 				export_error = vfs_export(mp, &export);
1387 			free(export.ex_groups, M_TEMP);
1388 			break;
1389 		case (sizeof(export)):
1390 			bcopy(bufp, &export, len);
1391 			grps = NULL;
1392 			if (export.ex_ngroups > 0) {
1393 				if (export.ex_ngroups <= NGROUPS_MAX) {
1394 					grps = malloc(export.ex_ngroups *
1395 					    sizeof(gid_t), M_TEMP, M_WAITOK);
1396 					export_error = copyin(export.ex_groups,
1397 					    grps, export.ex_ngroups *
1398 					    sizeof(gid_t));
1399 					if (export_error == 0)
1400 						export.ex_groups = grps;
1401 				} else
1402 					export_error = EINVAL;
1403 			} else if (export.ex_ngroups == 0)
1404 				export.ex_groups = NULL;
1405 			else
1406 				export_error = EINVAL;
1407 			if (export_error == 0)
1408 				export_error = vfs_export(mp, &export);
1409 			free(grps, M_TEMP);
1410 			break;
1411 		default:
1412 			export_error = EINVAL;
1413 			break;
1414 		}
1415 	}
1416 
1417 	MNT_ILOCK(mp);
1418 	if (error == 0) {
1419 		mp->mnt_flag &=	~(MNT_UPDATE | MNT_RELOAD | MNT_FORCE |
1420 		    MNT_SNAPSHOT);
1421 	} else {
1422 		/*
1423 		 * If we fail, restore old mount flags. MNT_QUOTA is special,
1424 		 * because it is not part of MNT_UPDATEMASK, but it could have
1425 		 * changed in the meantime if quotactl(2) was called.
1426 		 * All in all we want current value of MNT_QUOTA, not the old
1427 		 * one.
1428 		 */
1429 		mp->mnt_flag = (mp->mnt_flag & MNT_QUOTA) | (flag & ~MNT_QUOTA);
1430 	}
1431 	if ((mp->mnt_flag & MNT_ASYNC) != 0 &&
1432 	    (mp->mnt_kern_flag & MNTK_NOASYNC) == 0)
1433 		mp->mnt_kern_flag |= MNTK_ASYNC;
1434 	else
1435 		mp->mnt_kern_flag &= ~MNTK_ASYNC;
1436 	MNT_IUNLOCK(mp);
1437 
1438 	if (error != 0)
1439 		goto end;
1440 
1441 	mount_devctl_event("REMOUNT", mp, true);
1442 	if (mp->mnt_opt != NULL)
1443 		vfs_freeopts(mp->mnt_opt);
1444 	mp->mnt_opt = mp->mnt_optnew;
1445 	*optlist = NULL;
1446 	(void)VFS_STATFS(mp, &mp->mnt_stat);
1447 	/*
1448 	 * Prevent external consumers of mount options from reading
1449 	 * mnt_optnew.
1450 	 */
1451 	mp->mnt_optnew = NULL;
1452 
1453 	if ((mp->mnt_flag & MNT_RDONLY) == 0)
1454 		vfs_allocate_syncvnode(mp);
1455 	else
1456 		vfs_deallocate_syncvnode(mp);
1457 end:
1458 	vfs_op_exit(mp);
1459 	if (rootvp != NULL) {
1460 		vn_seqc_write_end(rootvp);
1461 		vrele(rootvp);
1462 	}
1463 	vn_seqc_write_end(vp);
1464 	vfs_unbusy(mp);
1465 	VI_LOCK(vp);
1466 	vp->v_iflag &= ~VI_MOUNT;
1467 	VI_UNLOCK(vp);
1468 	vrele(vp);
1469 	return (error != 0 ? error : export_error);
1470 }
1471 
1472 /*
1473  * vfs_domount(): actually attempt a filesystem mount.
1474  */
1475 static int
1476 vfs_domount(
1477 	struct thread *td,		/* Calling thread. */
1478 	const char *fstype,		/* Filesystem type. */
1479 	char *fspath,			/* Mount path. */
1480 	uint64_t fsflags,		/* Flags common to all filesystems. */
1481 	struct vfsoptlist **optlist	/* Options local to the filesystem. */
1482 	)
1483 {
1484 	struct vfsconf *vfsp;
1485 	struct nameidata nd;
1486 	struct vnode *vp;
1487 	char *pathbuf;
1488 	int error;
1489 
1490 	/*
1491 	 * Be ultra-paranoid about making sure the type and fspath
1492 	 * variables will fit in our mp buffers, including the
1493 	 * terminating NUL.
1494 	 */
1495 	if (strlen(fstype) >= MFSNAMELEN || strlen(fspath) >= MNAMELEN)
1496 		return (ENAMETOOLONG);
1497 
1498 	if (jailed(td->td_ucred) || usermount == 0) {
1499 		if ((error = priv_check(td, PRIV_VFS_MOUNT)) != 0)
1500 			return (error);
1501 	}
1502 
1503 	/*
1504 	 * Do not allow NFS export or MNT_SUIDDIR by unprivileged users.
1505 	 */
1506 	if (fsflags & MNT_EXPORTED) {
1507 		error = priv_check(td, PRIV_VFS_MOUNT_EXPORTED);
1508 		if (error)
1509 			return (error);
1510 	}
1511 	if (fsflags & MNT_SUIDDIR) {
1512 		error = priv_check(td, PRIV_VFS_MOUNT_SUIDDIR);
1513 		if (error)
1514 			return (error);
1515 	}
1516 	/*
1517 	 * Silently enforce MNT_NOSUID and MNT_USER for unprivileged users.
1518 	 */
1519 	if ((fsflags & (MNT_NOSUID | MNT_USER)) != (MNT_NOSUID | MNT_USER)) {
1520 		if (priv_check(td, PRIV_VFS_MOUNT_NONUSER) != 0)
1521 			fsflags |= MNT_NOSUID | MNT_USER;
1522 	}
1523 
1524 	/* Load KLDs before we lock the covered vnode to avoid reversals. */
1525 	vfsp = NULL;
1526 	if ((fsflags & MNT_UPDATE) == 0) {
1527 		/* Don't try to load KLDs if we're mounting the root. */
1528 		if (fsflags & MNT_ROOTFS)
1529 			vfsp = vfs_byname(fstype);
1530 		else
1531 			vfsp = vfs_byname_kld(fstype, td, &error);
1532 		if (vfsp == NULL)
1533 			return (ENODEV);
1534 	}
1535 
1536 	/*
1537 	 * Get vnode to be covered or mount point's vnode in case of MNT_UPDATE.
1538 	 */
1539 	NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF | AUDITVNODE1,
1540 	    UIO_SYSSPACE, fspath, td);
1541 	error = namei(&nd);
1542 	if (error != 0)
1543 		return (error);
1544 	NDFREE(&nd, NDF_ONLY_PNBUF);
1545 	vp = nd.ni_vp;
1546 	if ((fsflags & MNT_UPDATE) == 0) {
1547 		if ((vp->v_vflag & VV_ROOT) != 0 &&
1548 		    (fsflags & MNT_NOCOVER) != 0) {
1549 			vput(vp);
1550 			return (EBUSY);
1551 		}
1552 		pathbuf = malloc(MNAMELEN, M_TEMP, M_WAITOK);
1553 		strcpy(pathbuf, fspath);
1554 		error = vn_path_to_global_path(td, vp, pathbuf, MNAMELEN);
1555 		if (error == 0) {
1556 			error = vfs_domount_first(td, vfsp, pathbuf, vp,
1557 			    fsflags, optlist);
1558 		}
1559 		free(pathbuf, M_TEMP);
1560 	} else
1561 		error = vfs_domount_update(td, vp, fsflags, optlist);
1562 
1563 	return (error);
1564 }
1565 
1566 /*
1567  * Unmount a filesystem.
1568  *
1569  * Note: unmount takes a path to the vnode mounted on as argument, not
1570  * special file (as before).
1571  */
1572 #ifndef _SYS_SYSPROTO_H_
1573 struct unmount_args {
1574 	char	*path;
1575 	int	flags;
1576 };
1577 #endif
1578 /* ARGSUSED */
1579 int
1580 sys_unmount(struct thread *td, struct unmount_args *uap)
1581 {
1582 
1583 	return (kern_unmount(td, uap->path, uap->flags));
1584 }
1585 
1586 int
1587 kern_unmount(struct thread *td, const char *path, int flags)
1588 {
1589 	struct nameidata nd;
1590 	struct mount *mp;
1591 	char *fsidbuf, *pathbuf;
1592 	fsid_t fsid;
1593 	int error;
1594 
1595 	AUDIT_ARG_VALUE(flags);
1596 	if (jailed(td->td_ucred) || usermount == 0) {
1597 		error = priv_check(td, PRIV_VFS_UNMOUNT);
1598 		if (error)
1599 			return (error);
1600 	}
1601 
1602 	if (flags & MNT_BYFSID) {
1603 		fsidbuf = malloc(MNAMELEN, M_TEMP, M_WAITOK);
1604 		error = copyinstr(path, fsidbuf, MNAMELEN, NULL);
1605 		if (error) {
1606 			free(fsidbuf, M_TEMP);
1607 			return (error);
1608 		}
1609 
1610 		AUDIT_ARG_TEXT(fsidbuf);
1611 		/* Decode the filesystem ID. */
1612 		if (sscanf(fsidbuf, "FSID:%d:%d", &fsid.val[0], &fsid.val[1]) != 2) {
1613 			free(fsidbuf, M_TEMP);
1614 			return (EINVAL);
1615 		}
1616 
1617 		mp = vfs_getvfs(&fsid);
1618 		free(fsidbuf, M_TEMP);
1619 		if (mp == NULL) {
1620 			return (ENOENT);
1621 		}
1622 	} else {
1623 		pathbuf = malloc(MNAMELEN, M_TEMP, M_WAITOK);
1624 		error = copyinstr(path, pathbuf, MNAMELEN, NULL);
1625 		if (error) {
1626 			free(pathbuf, M_TEMP);
1627 			return (error);
1628 		}
1629 
1630 		/*
1631 		 * Try to find global path for path argument.
1632 		 */
1633 		NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF | AUDITVNODE1,
1634 		    UIO_SYSSPACE, pathbuf, td);
1635 		if (namei(&nd) == 0) {
1636 			NDFREE(&nd, NDF_ONLY_PNBUF);
1637 			error = vn_path_to_global_path(td, nd.ni_vp, pathbuf,
1638 			    MNAMELEN);
1639 			if (error == 0)
1640 				vput(nd.ni_vp);
1641 		}
1642 		mtx_lock(&mountlist_mtx);
1643 		TAILQ_FOREACH_REVERSE(mp, &mountlist, mntlist, mnt_list) {
1644 			if (strcmp(mp->mnt_stat.f_mntonname, pathbuf) == 0) {
1645 				vfs_ref(mp);
1646 				break;
1647 			}
1648 		}
1649 		mtx_unlock(&mountlist_mtx);
1650 		free(pathbuf, M_TEMP);
1651 		if (mp == NULL) {
1652 			/*
1653 			 * Previously we returned ENOENT for a nonexistent path and
1654 			 * EINVAL for a non-mountpoint.  We cannot tell these apart
1655 			 * now, so in the !MNT_BYFSID case return the more likely
1656 			 * EINVAL for compatibility.
1657 			 */
1658 			return (EINVAL);
1659 		}
1660 	}
1661 
1662 	/*
1663 	 * Don't allow unmounting the root filesystem.
1664 	 */
1665 	if (mp->mnt_flag & MNT_ROOTFS) {
1666 		vfs_rel(mp);
1667 		return (EINVAL);
1668 	}
1669 	error = dounmount(mp, flags, td);
1670 	return (error);
1671 }
1672 
1673 /*
1674  * Return error if any of the vnodes, ignoring the root vnode
1675  * and the syncer vnode, have non-zero usecount.
1676  *
1677  * This function is purely advisory - it can return false positives
1678  * and negatives.
1679  */
1680 static int
1681 vfs_check_usecounts(struct mount *mp)
1682 {
1683 	struct vnode *vp, *mvp;
1684 
1685 	MNT_VNODE_FOREACH_ALL(vp, mp, mvp) {
1686 		if ((vp->v_vflag & VV_ROOT) == 0 && vp->v_type != VNON &&
1687 		    vp->v_usecount != 0) {
1688 			VI_UNLOCK(vp);
1689 			MNT_VNODE_FOREACH_ALL_ABORT(mp, mvp);
1690 			return (EBUSY);
1691 		}
1692 		VI_UNLOCK(vp);
1693 	}
1694 
1695 	return (0);
1696 }
1697 
1698 static void
1699 dounmount_cleanup(struct mount *mp, struct vnode *coveredvp, int mntkflags)
1700 {
1701 
1702 	mtx_assert(MNT_MTX(mp), MA_OWNED);
1703 	mp->mnt_kern_flag &= ~mntkflags;
1704 	if ((mp->mnt_kern_flag & MNTK_MWAIT) != 0) {
1705 		mp->mnt_kern_flag &= ~MNTK_MWAIT;
1706 		wakeup(mp);
1707 	}
1708 	vfs_op_exit_locked(mp);
1709 	MNT_IUNLOCK(mp);
1710 	if (coveredvp != NULL) {
1711 		VOP_UNLOCK(coveredvp);
1712 		vdrop(coveredvp);
1713 	}
1714 	vn_finished_write(mp);
1715 }
1716 
1717 /*
1718  * There are various reference counters associated with the mount point.
1719  * Normally it is permitted to modify them without taking the mnt ilock,
1720  * but this behavior can be temporarily disabled if stable value is needed
1721  * or callers are expected to block (e.g. to not allow new users during
1722  * forced unmount).
1723  */
1724 void
1725 vfs_op_enter(struct mount *mp)
1726 {
1727 	struct mount_pcpu *mpcpu;
1728 	int cpu;
1729 
1730 	MNT_ILOCK(mp);
1731 	mp->mnt_vfs_ops++;
1732 	if (mp->mnt_vfs_ops > 1) {
1733 		MNT_IUNLOCK(mp);
1734 		return;
1735 	}
1736 	vfs_op_barrier_wait(mp);
1737 	CPU_FOREACH(cpu) {
1738 		mpcpu = vfs_mount_pcpu_remote(mp, cpu);
1739 
1740 		mp->mnt_ref += mpcpu->mntp_ref;
1741 		mpcpu->mntp_ref = 0;
1742 
1743 		mp->mnt_lockref += mpcpu->mntp_lockref;
1744 		mpcpu->mntp_lockref = 0;
1745 
1746 		mp->mnt_writeopcount += mpcpu->mntp_writeopcount;
1747 		mpcpu->mntp_writeopcount = 0;
1748 	}
1749 	if (mp->mnt_ref <= 0 || mp->mnt_lockref < 0 || mp->mnt_writeopcount < 0)
1750 		panic("%s: invalid count(s) on mp %p: ref %d lockref %d writeopcount %d\n",
1751 		    __func__, mp, mp->mnt_ref, mp->mnt_lockref, mp->mnt_writeopcount);
1752 	MNT_IUNLOCK(mp);
1753 	vfs_assert_mount_counters(mp);
1754 }
1755 
1756 void
1757 vfs_op_exit_locked(struct mount *mp)
1758 {
1759 
1760 	mtx_assert(MNT_MTX(mp), MA_OWNED);
1761 
1762 	if (mp->mnt_vfs_ops <= 0)
1763 		panic("%s: invalid vfs_ops count %d for mp %p\n",
1764 		    __func__, mp->mnt_vfs_ops, mp);
1765 	mp->mnt_vfs_ops--;
1766 }
1767 
1768 void
1769 vfs_op_exit(struct mount *mp)
1770 {
1771 
1772 	MNT_ILOCK(mp);
1773 	vfs_op_exit_locked(mp);
1774 	MNT_IUNLOCK(mp);
1775 }
1776 
1777 struct vfs_op_barrier_ipi {
1778 	struct mount *mp;
1779 	struct smp_rendezvous_cpus_retry_arg srcra;
1780 };
1781 
1782 static void
1783 vfs_op_action_func(void *arg)
1784 {
1785 	struct vfs_op_barrier_ipi *vfsopipi;
1786 	struct mount *mp;
1787 
1788 	vfsopipi = __containerof(arg, struct vfs_op_barrier_ipi, srcra);
1789 	mp = vfsopipi->mp;
1790 
1791 	if (!vfs_op_thread_entered(mp))
1792 		smp_rendezvous_cpus_done(arg);
1793 }
1794 
1795 static void
1796 vfs_op_wait_func(void *arg, int cpu)
1797 {
1798 	struct vfs_op_barrier_ipi *vfsopipi;
1799 	struct mount *mp;
1800 	struct mount_pcpu *mpcpu;
1801 
1802 	vfsopipi = __containerof(arg, struct vfs_op_barrier_ipi, srcra);
1803 	mp = vfsopipi->mp;
1804 
1805 	mpcpu = vfs_mount_pcpu_remote(mp, cpu);
1806 	while (atomic_load_int(&mpcpu->mntp_thread_in_ops))
1807 		cpu_spinwait();
1808 }
1809 
1810 void
1811 vfs_op_barrier_wait(struct mount *mp)
1812 {
1813 	struct vfs_op_barrier_ipi vfsopipi;
1814 
1815 	vfsopipi.mp = mp;
1816 
1817 	smp_rendezvous_cpus_retry(all_cpus,
1818 	    smp_no_rendezvous_barrier,
1819 	    vfs_op_action_func,
1820 	    smp_no_rendezvous_barrier,
1821 	    vfs_op_wait_func,
1822 	    &vfsopipi.srcra);
1823 }
1824 
1825 #ifdef DIAGNOSTIC
1826 void
1827 vfs_assert_mount_counters(struct mount *mp)
1828 {
1829 	struct mount_pcpu *mpcpu;
1830 	int cpu;
1831 
1832 	if (mp->mnt_vfs_ops == 0)
1833 		return;
1834 
1835 	CPU_FOREACH(cpu) {
1836 		mpcpu = vfs_mount_pcpu_remote(mp, cpu);
1837 		if (mpcpu->mntp_ref != 0 ||
1838 		    mpcpu->mntp_lockref != 0 ||
1839 		    mpcpu->mntp_writeopcount != 0)
1840 			vfs_dump_mount_counters(mp);
1841 	}
1842 }
1843 
1844 void
1845 vfs_dump_mount_counters(struct mount *mp)
1846 {
1847 	struct mount_pcpu *mpcpu;
1848 	int ref, lockref, writeopcount;
1849 	int cpu;
1850 
1851 	printf("%s: mp %p vfs_ops %d\n", __func__, mp, mp->mnt_vfs_ops);
1852 
1853 	printf("        ref : ");
1854 	ref = mp->mnt_ref;
1855 	CPU_FOREACH(cpu) {
1856 		mpcpu = vfs_mount_pcpu_remote(mp, cpu);
1857 		printf("%d ", mpcpu->mntp_ref);
1858 		ref += mpcpu->mntp_ref;
1859 	}
1860 	printf("\n");
1861 	printf("    lockref : ");
1862 	lockref = mp->mnt_lockref;
1863 	CPU_FOREACH(cpu) {
1864 		mpcpu = vfs_mount_pcpu_remote(mp, cpu);
1865 		printf("%d ", mpcpu->mntp_lockref);
1866 		lockref += mpcpu->mntp_lockref;
1867 	}
1868 	printf("\n");
1869 	printf("writeopcount: ");
1870 	writeopcount = mp->mnt_writeopcount;
1871 	CPU_FOREACH(cpu) {
1872 		mpcpu = vfs_mount_pcpu_remote(mp, cpu);
1873 		printf("%d ", mpcpu->mntp_writeopcount);
1874 		writeopcount += mpcpu->mntp_writeopcount;
1875 	}
1876 	printf("\n");
1877 
1878 	printf("counter       struct total\n");
1879 	printf("ref             %-5d  %-5d\n", mp->mnt_ref, ref);
1880 	printf("lockref         %-5d  %-5d\n", mp->mnt_lockref, lockref);
1881 	printf("writeopcount    %-5d  %-5d\n", mp->mnt_writeopcount, writeopcount);
1882 
1883 	panic("invalid counts on struct mount");
1884 }
1885 #endif
1886 
1887 int
1888 vfs_mount_fetch_counter(struct mount *mp, enum mount_counter which)
1889 {
1890 	struct mount_pcpu *mpcpu;
1891 	int cpu, sum;
1892 
1893 	switch (which) {
1894 	case MNT_COUNT_REF:
1895 		sum = mp->mnt_ref;
1896 		break;
1897 	case MNT_COUNT_LOCKREF:
1898 		sum = mp->mnt_lockref;
1899 		break;
1900 	case MNT_COUNT_WRITEOPCOUNT:
1901 		sum = mp->mnt_writeopcount;
1902 		break;
1903 	}
1904 
1905 	CPU_FOREACH(cpu) {
1906 		mpcpu = vfs_mount_pcpu_remote(mp, cpu);
1907 		switch (which) {
1908 		case MNT_COUNT_REF:
1909 			sum += mpcpu->mntp_ref;
1910 			break;
1911 		case MNT_COUNT_LOCKREF:
1912 			sum += mpcpu->mntp_lockref;
1913 			break;
1914 		case MNT_COUNT_WRITEOPCOUNT:
1915 			sum += mpcpu->mntp_writeopcount;
1916 			break;
1917 		}
1918 	}
1919 	return (sum);
1920 }
1921 
1922 static bool
1923 deferred_unmount_enqueue(struct mount *mp, uint64_t flags, bool requeue,
1924     int timeout_ticks)
1925 {
1926 	bool enqueued;
1927 
1928 	enqueued = false;
1929 	mtx_lock(&deferred_unmount_lock);
1930 	if ((mp->mnt_taskqueue_flags & MNT_DEFERRED) == 0 || requeue) {
1931 		mp->mnt_taskqueue_flags = flags | MNT_DEFERRED;
1932 		STAILQ_INSERT_TAIL(&deferred_unmount_list, mp,
1933 		    mnt_taskqueue_link);
1934 		enqueued = true;
1935 	}
1936 	mtx_unlock(&deferred_unmount_lock);
1937 
1938 	if (enqueued) {
1939 		taskqueue_enqueue_timeout(taskqueue_deferred_unmount,
1940 		    &deferred_unmount_task, timeout_ticks);
1941 	}
1942 
1943 	return (enqueued);
1944 }
1945 
1946 /*
1947  * Taskqueue handler for processing async/recursive unmounts
1948  */
1949 static void
1950 vfs_deferred_unmount(void *argi __unused, int pending __unused)
1951 {
1952 	STAILQ_HEAD(, mount) local_unmounts;
1953 	uint64_t flags;
1954 	struct mount *mp, *tmp;
1955 	int error;
1956 	unsigned int retries;
1957 	bool unmounted;
1958 
1959 	STAILQ_INIT(&local_unmounts);
1960 	mtx_lock(&deferred_unmount_lock);
1961 	STAILQ_CONCAT(&local_unmounts, &deferred_unmount_list);
1962 	mtx_unlock(&deferred_unmount_lock);
1963 
1964 	STAILQ_FOREACH_SAFE(mp, &local_unmounts, mnt_taskqueue_link, tmp) {
1965 		flags = mp->mnt_taskqueue_flags;
1966 		KASSERT((flags & MNT_DEFERRED) != 0,
1967 		    ("taskqueue unmount without MNT_DEFERRED"));
1968 		error = dounmount(mp, flags, curthread);
1969 		if (error != 0) {
1970 			MNT_ILOCK(mp);
1971 			unmounted = ((mp->mnt_kern_flag & MNTK_REFEXPIRE) != 0);
1972 			MNT_IUNLOCK(mp);
1973 
1974 			/*
1975 			 * The deferred unmount thread is the only thread that
1976 			 * modifies the retry counts, so locking/atomics aren't
1977 			 * needed here.
1978 			 */
1979 			retries = (mp->mnt_unmount_retries)++;
1980 			deferred_unmount_total_retries++;
1981 			if (!unmounted && retries < deferred_unmount_retry_limit) {
1982 				deferred_unmount_enqueue(mp, flags, true,
1983 				    -deferred_unmount_retry_delay_hz);
1984 			} else {
1985 				if (retries >= deferred_unmount_retry_limit) {
1986 					printf("giving up on deferred unmount "
1987 					    "of %s after %d retries, error %d\n",
1988 					    mp->mnt_stat.f_mntonname, retries, error);
1989 				}
1990 				vfs_rel(mp);
1991 			}
1992 		}
1993 	}
1994 }
1995 
1996 /*
1997  * Do the actual filesystem unmount.
1998  */
1999 int
2000 dounmount(struct mount *mp, uint64_t flags, struct thread *td)
2001 {
2002 	struct mount_upper_node *upper;
2003 	struct vnode *coveredvp, *rootvp;
2004 	int error;
2005 	uint64_t async_flag;
2006 	int mnt_gen_r;
2007 	unsigned int retries;
2008 
2009 	KASSERT((flags & MNT_DEFERRED) == 0 ||
2010 	    (flags & (MNT_RECURSE | MNT_FORCE)) == (MNT_RECURSE | MNT_FORCE),
2011 	    ("MNT_DEFERRED requires MNT_RECURSE | MNT_FORCE"));
2012 
2013 	/*
2014 	 * If the caller has explicitly requested the unmount to be handled by
2015 	 * the taskqueue and we're not already in taskqueue context, queue
2016 	 * up the unmount request and exit.  This is done prior to any
2017 	 * credential checks; MNT_DEFERRED should be used only for kernel-
2018 	 * initiated unmounts and will therefore be processed with the
2019 	 * (kernel) credentials of the taskqueue thread.  Still, callers
2020 	 * should be sure this is the behavior they want.
2021 	 */
2022 	if ((flags & MNT_DEFERRED) != 0 &&
2023 	    taskqueue_member(taskqueue_deferred_unmount, curthread) == 0) {
2024 		if (!deferred_unmount_enqueue(mp, flags, false, 0))
2025 			vfs_rel(mp);
2026 		return (EINPROGRESS);
2027 	}
2028 
2029 	/*
2030 	 * Only privileged root, or (if MNT_USER is set) the user that did the
2031 	 * original mount is permitted to unmount this filesystem.
2032 	 * This check should be made prior to queueing up any recursive
2033 	 * unmounts of upper filesystems.  Those unmounts will be executed
2034 	 * with kernel thread credentials and are expected to succeed, so
2035 	 * we must at least ensure the originating context has sufficient
2036 	 * privilege to unmount the base filesystem before proceeding with
2037 	 * the uppers.
2038 	 */
2039 	error = vfs_suser(mp, td);
2040 	if (error != 0) {
2041 		KASSERT((flags & MNT_DEFERRED) == 0,
2042 		    ("taskqueue unmount with insufficient privilege"));
2043 		vfs_rel(mp);
2044 		return (error);
2045 	}
2046 
2047 	if (recursive_forced_unmount && ((flags & MNT_FORCE) != 0))
2048 		flags |= MNT_RECURSE;
2049 
2050 	if ((flags & MNT_RECURSE) != 0) {
2051 		KASSERT((flags & MNT_FORCE) != 0,
2052 		    ("MNT_RECURSE requires MNT_FORCE"));
2053 
2054 		MNT_ILOCK(mp);
2055 		/*
2056 		 * Set MNTK_RECURSE to prevent new upper mounts from being
2057 		 * added, and note that an operation on the uppers list is in
2058 		 * progress.  This will ensure that unregistration from the
2059 		 * uppers list, and therefore any pending unmount of the upper
2060 		 * FS, can't complete until after we finish walking the list.
2061 		 */
2062 		mp->mnt_kern_flag |= MNTK_RECURSE;
2063 		mp->mnt_upper_pending++;
2064 		TAILQ_FOREACH(upper, &mp->mnt_uppers, mnt_upper_link) {
2065 			retries = upper->mp->mnt_unmount_retries;
2066 			if (retries > deferred_unmount_retry_limit) {
2067 				error = EBUSY;
2068 				continue;
2069 			}
2070 			MNT_IUNLOCK(mp);
2071 
2072 			vfs_ref(upper->mp);
2073 			if (!deferred_unmount_enqueue(upper->mp, flags,
2074 			    false, 0))
2075 				vfs_rel(upper->mp);
2076 			MNT_ILOCK(mp);
2077 		}
2078 		mp->mnt_upper_pending--;
2079 		if ((mp->mnt_kern_flag & MNTK_UPPER_WAITER) != 0 &&
2080 		    mp->mnt_upper_pending == 0) {
2081 			mp->mnt_kern_flag &= ~MNTK_UPPER_WAITER;
2082 			wakeup(&mp->mnt_uppers);
2083 		}
2084 
2085 		/*
2086 		 * If we're not on the taskqueue, wait until the uppers list
2087 		 * is drained before proceeding with unmount.  Otherwise, if
2088 		 * we are on the taskqueue and there are still pending uppers,
2089 		 * just re-enqueue on the end of the taskqueue.
2090 		 */
2091 		if ((flags & MNT_DEFERRED) == 0) {
2092 			while (error == 0 && !TAILQ_EMPTY(&mp->mnt_uppers)) {
2093 				mp->mnt_kern_flag |= MNTK_TASKQUEUE_WAITER;
2094 				error = msleep(&mp->mnt_taskqueue_link,
2095 				    MNT_MTX(mp), PCATCH, "umntqw", 0);
2096 			}
2097 			if (error != 0) {
2098 				MNT_REL(mp);
2099 				MNT_IUNLOCK(mp);
2100 				return (error);
2101 			}
2102 		} else if (!TAILQ_EMPTY(&mp->mnt_uppers)) {
2103 			MNT_IUNLOCK(mp);
2104 			if (error == 0)
2105 				deferred_unmount_enqueue(mp, flags, true, 0);
2106 			return (error);
2107 		}
2108 		MNT_IUNLOCK(mp);
2109 		KASSERT(TAILQ_EMPTY(&mp->mnt_uppers), ("mnt_uppers not empty"));
2110 	}
2111 
2112 	/* Allow the taskqueue to safely re-enqueue on failure */
2113 	if ((flags & MNT_DEFERRED) != 0)
2114 		vfs_ref(mp);
2115 
2116 	if ((coveredvp = mp->mnt_vnodecovered) != NULL) {
2117 		mnt_gen_r = mp->mnt_gen;
2118 		VI_LOCK(coveredvp);
2119 		vholdl(coveredvp);
2120 		vn_lock(coveredvp, LK_EXCLUSIVE | LK_INTERLOCK | LK_RETRY);
2121 		/*
2122 		 * Check for mp being unmounted while waiting for the
2123 		 * covered vnode lock.
2124 		 */
2125 		if (coveredvp->v_mountedhere != mp ||
2126 		    coveredvp->v_mountedhere->mnt_gen != mnt_gen_r) {
2127 			VOP_UNLOCK(coveredvp);
2128 			vdrop(coveredvp);
2129 			vfs_rel(mp);
2130 			return (EBUSY);
2131 		}
2132 	}
2133 
2134 	vfs_op_enter(mp);
2135 
2136 	vn_start_write(NULL, &mp, V_WAIT | V_MNTREF);
2137 	MNT_ILOCK(mp);
2138 	if ((mp->mnt_kern_flag & MNTK_UNMOUNT) != 0 ||
2139 	    (mp->mnt_flag & MNT_UPDATE) != 0 ||
2140 	    !TAILQ_EMPTY(&mp->mnt_uppers)) {
2141 		dounmount_cleanup(mp, coveredvp, 0);
2142 		return (EBUSY);
2143 	}
2144 	mp->mnt_kern_flag |= MNTK_UNMOUNT;
2145 	rootvp = vfs_cache_root_clear(mp);
2146 	if (coveredvp != NULL)
2147 		vn_seqc_write_begin(coveredvp);
2148 	if (flags & MNT_NONBUSY) {
2149 		MNT_IUNLOCK(mp);
2150 		error = vfs_check_usecounts(mp);
2151 		MNT_ILOCK(mp);
2152 		if (error != 0) {
2153 			vn_seqc_write_end(coveredvp);
2154 			dounmount_cleanup(mp, coveredvp, MNTK_UNMOUNT);
2155 			if (rootvp != NULL) {
2156 				vn_seqc_write_end(rootvp);
2157 				vrele(rootvp);
2158 			}
2159 			return (error);
2160 		}
2161 	}
2162 	/* Allow filesystems to detect that a forced unmount is in progress. */
2163 	if (flags & MNT_FORCE) {
2164 		mp->mnt_kern_flag |= MNTK_UNMOUNTF;
2165 		MNT_IUNLOCK(mp);
2166 		/*
2167 		 * Must be done after setting MNTK_UNMOUNTF and before
2168 		 * waiting for mnt_lockref to become 0.
2169 		 */
2170 		VFS_PURGE(mp);
2171 		MNT_ILOCK(mp);
2172 	}
2173 	error = 0;
2174 	if (mp->mnt_lockref) {
2175 		mp->mnt_kern_flag |= MNTK_DRAINING;
2176 		error = msleep(&mp->mnt_lockref, MNT_MTX(mp), PVFS,
2177 		    "mount drain", 0);
2178 	}
2179 	MNT_IUNLOCK(mp);
2180 	KASSERT(mp->mnt_lockref == 0,
2181 	    ("%s: invalid lock refcount in the drain path @ %s:%d",
2182 	    __func__, __FILE__, __LINE__));
2183 	KASSERT(error == 0,
2184 	    ("%s: invalid return value for msleep in the drain path @ %s:%d",
2185 	    __func__, __FILE__, __LINE__));
2186 
2187 	/*
2188 	 * We want to keep the vnode around so that we can vn_seqc_write_end
2189 	 * after we are done with unmount. Downgrade our reference to a mere
2190 	 * hold count so that we don't interefere with anything.
2191 	 */
2192 	if (rootvp != NULL) {
2193 		vhold(rootvp);
2194 		vrele(rootvp);
2195 	}
2196 
2197 	if (mp->mnt_flag & MNT_EXPUBLIC)
2198 		vfs_setpublicfs(NULL, NULL, NULL);
2199 
2200 	vfs_periodic(mp, MNT_WAIT);
2201 	MNT_ILOCK(mp);
2202 	async_flag = mp->mnt_flag & MNT_ASYNC;
2203 	mp->mnt_flag &= ~MNT_ASYNC;
2204 	mp->mnt_kern_flag &= ~MNTK_ASYNC;
2205 	MNT_IUNLOCK(mp);
2206 	vfs_deallocate_syncvnode(mp);
2207 	error = VFS_UNMOUNT(mp, flags);
2208 	vn_finished_write(mp);
2209 	/*
2210 	 * If we failed to flush the dirty blocks for this mount point,
2211 	 * undo all the cdir/rdir and rootvnode changes we made above.
2212 	 * Unless we failed to do so because the device is reporting that
2213 	 * it doesn't exist anymore.
2214 	 */
2215 	if (error && error != ENXIO) {
2216 		MNT_ILOCK(mp);
2217 		if ((mp->mnt_flag & MNT_RDONLY) == 0) {
2218 			MNT_IUNLOCK(mp);
2219 			vfs_allocate_syncvnode(mp);
2220 			MNT_ILOCK(mp);
2221 		}
2222 		mp->mnt_kern_flag &= ~(MNTK_UNMOUNT | MNTK_UNMOUNTF);
2223 		mp->mnt_flag |= async_flag;
2224 		if ((mp->mnt_flag & MNT_ASYNC) != 0 &&
2225 		    (mp->mnt_kern_flag & MNTK_NOASYNC) == 0)
2226 			mp->mnt_kern_flag |= MNTK_ASYNC;
2227 		if (mp->mnt_kern_flag & MNTK_MWAIT) {
2228 			mp->mnt_kern_flag &= ~MNTK_MWAIT;
2229 			wakeup(mp);
2230 		}
2231 		vfs_op_exit_locked(mp);
2232 		MNT_IUNLOCK(mp);
2233 		if (coveredvp) {
2234 			vn_seqc_write_end(coveredvp);
2235 			VOP_UNLOCK(coveredvp);
2236 			vdrop(coveredvp);
2237 		}
2238 		if (rootvp != NULL) {
2239 			vn_seqc_write_end(rootvp);
2240 			vdrop(rootvp);
2241 		}
2242 		return (error);
2243 	}
2244 
2245 	mtx_lock(&mountlist_mtx);
2246 	TAILQ_REMOVE(&mountlist, mp, mnt_list);
2247 	mtx_unlock(&mountlist_mtx);
2248 	EVENTHANDLER_DIRECT_INVOKE(vfs_unmounted, mp, td);
2249 	if (coveredvp != NULL) {
2250 		VI_LOCK(coveredvp);
2251 		vn_irflag_unset_locked(coveredvp, VIRF_MOUNTPOINT);
2252 		coveredvp->v_mountedhere = NULL;
2253 		vn_seqc_write_end_locked(coveredvp);
2254 		VI_UNLOCK(coveredvp);
2255 		VOP_UNLOCK(coveredvp);
2256 		vdrop(coveredvp);
2257 	}
2258 	mount_devctl_event("UNMOUNT", mp, false);
2259 	if (rootvp != NULL) {
2260 		vn_seqc_write_end(rootvp);
2261 		vdrop(rootvp);
2262 	}
2263 	vfs_event_signal(NULL, VQ_UNMOUNT, 0);
2264 	if (rootvnode != NULL && mp == rootvnode->v_mount) {
2265 		vrele(rootvnode);
2266 		rootvnode = NULL;
2267 	}
2268 	if (mp == rootdevmp)
2269 		rootdevmp = NULL;
2270 	if ((flags & MNT_DEFERRED) != 0)
2271 		vfs_rel(mp);
2272 	vfs_mount_destroy(mp);
2273 	return (0);
2274 }
2275 
2276 /*
2277  * Report errors during filesystem mounting.
2278  */
2279 void
2280 vfs_mount_error(struct mount *mp, const char *fmt, ...)
2281 {
2282 	struct vfsoptlist *moptlist = mp->mnt_optnew;
2283 	va_list ap;
2284 	int error, len;
2285 	char *errmsg;
2286 
2287 	error = vfs_getopt(moptlist, "errmsg", (void **)&errmsg, &len);
2288 	if (error || errmsg == NULL || len <= 0)
2289 		return;
2290 
2291 	va_start(ap, fmt);
2292 	vsnprintf(errmsg, (size_t)len, fmt, ap);
2293 	va_end(ap);
2294 }
2295 
2296 void
2297 vfs_opterror(struct vfsoptlist *opts, const char *fmt, ...)
2298 {
2299 	va_list ap;
2300 	int error, len;
2301 	char *errmsg;
2302 
2303 	error = vfs_getopt(opts, "errmsg", (void **)&errmsg, &len);
2304 	if (error || errmsg == NULL || len <= 0)
2305 		return;
2306 
2307 	va_start(ap, fmt);
2308 	vsnprintf(errmsg, (size_t)len, fmt, ap);
2309 	va_end(ap);
2310 }
2311 
2312 /*
2313  * ---------------------------------------------------------------------
2314  * Functions for querying mount options/arguments from filesystems.
2315  */
2316 
2317 /*
2318  * Check that no unknown options are given
2319  */
2320 int
2321 vfs_filteropt(struct vfsoptlist *opts, const char **legal)
2322 {
2323 	struct vfsopt *opt;
2324 	char errmsg[255];
2325 	const char **t, *p, *q;
2326 	int ret = 0;
2327 
2328 	TAILQ_FOREACH(opt, opts, link) {
2329 		p = opt->name;
2330 		q = NULL;
2331 		if (p[0] == 'n' && p[1] == 'o')
2332 			q = p + 2;
2333 		for(t = global_opts; *t != NULL; t++) {
2334 			if (strcmp(*t, p) == 0)
2335 				break;
2336 			if (q != NULL) {
2337 				if (strcmp(*t, q) == 0)
2338 					break;
2339 			}
2340 		}
2341 		if (*t != NULL)
2342 			continue;
2343 		for(t = legal; *t != NULL; t++) {
2344 			if (strcmp(*t, p) == 0)
2345 				break;
2346 			if (q != NULL) {
2347 				if (strcmp(*t, q) == 0)
2348 					break;
2349 			}
2350 		}
2351 		if (*t != NULL)
2352 			continue;
2353 		snprintf(errmsg, sizeof(errmsg),
2354 		    "mount option <%s> is unknown", p);
2355 		ret = EINVAL;
2356 	}
2357 	if (ret != 0) {
2358 		TAILQ_FOREACH(opt, opts, link) {
2359 			if (strcmp(opt->name, "errmsg") == 0) {
2360 				strncpy((char *)opt->value, errmsg, opt->len);
2361 				break;
2362 			}
2363 		}
2364 		if (opt == NULL)
2365 			printf("%s\n", errmsg);
2366 	}
2367 	return (ret);
2368 }
2369 
2370 /*
2371  * Get a mount option by its name.
2372  *
2373  * Return 0 if the option was found, ENOENT otherwise.
2374  * If len is non-NULL it will be filled with the length
2375  * of the option. If buf is non-NULL, it will be filled
2376  * with the address of the option.
2377  */
2378 int
2379 vfs_getopt(struct vfsoptlist *opts, const char *name, void **buf, int *len)
2380 {
2381 	struct vfsopt *opt;
2382 
2383 	KASSERT(opts != NULL, ("vfs_getopt: caller passed 'opts' as NULL"));
2384 
2385 	TAILQ_FOREACH(opt, opts, link) {
2386 		if (strcmp(name, opt->name) == 0) {
2387 			opt->seen = 1;
2388 			if (len != NULL)
2389 				*len = opt->len;
2390 			if (buf != NULL)
2391 				*buf = opt->value;
2392 			return (0);
2393 		}
2394 	}
2395 	return (ENOENT);
2396 }
2397 
2398 int
2399 vfs_getopt_pos(struct vfsoptlist *opts, const char *name)
2400 {
2401 	struct vfsopt *opt;
2402 
2403 	if (opts == NULL)
2404 		return (-1);
2405 
2406 	TAILQ_FOREACH(opt, opts, link) {
2407 		if (strcmp(name, opt->name) == 0) {
2408 			opt->seen = 1;
2409 			return (opt->pos);
2410 		}
2411 	}
2412 	return (-1);
2413 }
2414 
2415 int
2416 vfs_getopt_size(struct vfsoptlist *opts, const char *name, off_t *value)
2417 {
2418 	char *opt_value, *vtp;
2419 	quad_t iv;
2420 	int error, opt_len;
2421 
2422 	error = vfs_getopt(opts, name, (void **)&opt_value, &opt_len);
2423 	if (error != 0)
2424 		return (error);
2425 	if (opt_len == 0 || opt_value == NULL)
2426 		return (EINVAL);
2427 	if (opt_value[0] == '\0' || opt_value[opt_len - 1] != '\0')
2428 		return (EINVAL);
2429 	iv = strtoq(opt_value, &vtp, 0);
2430 	if (vtp == opt_value || (vtp[0] != '\0' && vtp[1] != '\0'))
2431 		return (EINVAL);
2432 	if (iv < 0)
2433 		return (EINVAL);
2434 	switch (vtp[0]) {
2435 	case 't': case 'T':
2436 		iv *= 1024;
2437 		/* FALLTHROUGH */
2438 	case 'g': case 'G':
2439 		iv *= 1024;
2440 		/* FALLTHROUGH */
2441 	case 'm': case 'M':
2442 		iv *= 1024;
2443 		/* FALLTHROUGH */
2444 	case 'k': case 'K':
2445 		iv *= 1024;
2446 	case '\0':
2447 		break;
2448 	default:
2449 		return (EINVAL);
2450 	}
2451 	*value = iv;
2452 
2453 	return (0);
2454 }
2455 
2456 char *
2457 vfs_getopts(struct vfsoptlist *opts, const char *name, int *error)
2458 {
2459 	struct vfsopt *opt;
2460 
2461 	*error = 0;
2462 	TAILQ_FOREACH(opt, opts, link) {
2463 		if (strcmp(name, opt->name) != 0)
2464 			continue;
2465 		opt->seen = 1;
2466 		if (opt->len == 0 ||
2467 		    ((char *)opt->value)[opt->len - 1] != '\0') {
2468 			*error = EINVAL;
2469 			return (NULL);
2470 		}
2471 		return (opt->value);
2472 	}
2473 	*error = ENOENT;
2474 	return (NULL);
2475 }
2476 
2477 int
2478 vfs_flagopt(struct vfsoptlist *opts, const char *name, uint64_t *w,
2479 	uint64_t val)
2480 {
2481 	struct vfsopt *opt;
2482 
2483 	TAILQ_FOREACH(opt, opts, link) {
2484 		if (strcmp(name, opt->name) == 0) {
2485 			opt->seen = 1;
2486 			if (w != NULL)
2487 				*w |= val;
2488 			return (1);
2489 		}
2490 	}
2491 	if (w != NULL)
2492 		*w &= ~val;
2493 	return (0);
2494 }
2495 
2496 int
2497 vfs_scanopt(struct vfsoptlist *opts, const char *name, const char *fmt, ...)
2498 {
2499 	va_list ap;
2500 	struct vfsopt *opt;
2501 	int ret;
2502 
2503 	KASSERT(opts != NULL, ("vfs_getopt: caller passed 'opts' as NULL"));
2504 
2505 	TAILQ_FOREACH(opt, opts, link) {
2506 		if (strcmp(name, opt->name) != 0)
2507 			continue;
2508 		opt->seen = 1;
2509 		if (opt->len == 0 || opt->value == NULL)
2510 			return (0);
2511 		if (((char *)opt->value)[opt->len - 1] != '\0')
2512 			return (0);
2513 		va_start(ap, fmt);
2514 		ret = vsscanf(opt->value, fmt, ap);
2515 		va_end(ap);
2516 		return (ret);
2517 	}
2518 	return (0);
2519 }
2520 
2521 int
2522 vfs_setopt(struct vfsoptlist *opts, const char *name, void *value, int len)
2523 {
2524 	struct vfsopt *opt;
2525 
2526 	TAILQ_FOREACH(opt, opts, link) {
2527 		if (strcmp(name, opt->name) != 0)
2528 			continue;
2529 		opt->seen = 1;
2530 		if (opt->value == NULL)
2531 			opt->len = len;
2532 		else {
2533 			if (opt->len != len)
2534 				return (EINVAL);
2535 			bcopy(value, opt->value, len);
2536 		}
2537 		return (0);
2538 	}
2539 	return (ENOENT);
2540 }
2541 
2542 int
2543 vfs_setopt_part(struct vfsoptlist *opts, const char *name, void *value, int len)
2544 {
2545 	struct vfsopt *opt;
2546 
2547 	TAILQ_FOREACH(opt, opts, link) {
2548 		if (strcmp(name, opt->name) != 0)
2549 			continue;
2550 		opt->seen = 1;
2551 		if (opt->value == NULL)
2552 			opt->len = len;
2553 		else {
2554 			if (opt->len < len)
2555 				return (EINVAL);
2556 			opt->len = len;
2557 			bcopy(value, opt->value, len);
2558 		}
2559 		return (0);
2560 	}
2561 	return (ENOENT);
2562 }
2563 
2564 int
2565 vfs_setopts(struct vfsoptlist *opts, const char *name, const char *value)
2566 {
2567 	struct vfsopt *opt;
2568 
2569 	TAILQ_FOREACH(opt, opts, link) {
2570 		if (strcmp(name, opt->name) != 0)
2571 			continue;
2572 		opt->seen = 1;
2573 		if (opt->value == NULL)
2574 			opt->len = strlen(value) + 1;
2575 		else if (strlcpy(opt->value, value, opt->len) >= opt->len)
2576 			return (EINVAL);
2577 		return (0);
2578 	}
2579 	return (ENOENT);
2580 }
2581 
2582 /*
2583  * Find and copy a mount option.
2584  *
2585  * The size of the buffer has to be specified
2586  * in len, if it is not the same length as the
2587  * mount option, EINVAL is returned.
2588  * Returns ENOENT if the option is not found.
2589  */
2590 int
2591 vfs_copyopt(struct vfsoptlist *opts, const char *name, void *dest, int len)
2592 {
2593 	struct vfsopt *opt;
2594 
2595 	KASSERT(opts != NULL, ("vfs_copyopt: caller passed 'opts' as NULL"));
2596 
2597 	TAILQ_FOREACH(opt, opts, link) {
2598 		if (strcmp(name, opt->name) == 0) {
2599 			opt->seen = 1;
2600 			if (len != opt->len)
2601 				return (EINVAL);
2602 			bcopy(opt->value, dest, opt->len);
2603 			return (0);
2604 		}
2605 	}
2606 	return (ENOENT);
2607 }
2608 
2609 int
2610 __vfs_statfs(struct mount *mp, struct statfs *sbp)
2611 {
2612 
2613 	/*
2614 	 * Filesystems only fill in part of the structure for updates, we
2615 	 * have to read the entirety first to get all content.
2616 	 */
2617 	if (sbp != &mp->mnt_stat)
2618 		memcpy(sbp, &mp->mnt_stat, sizeof(*sbp));
2619 
2620 	/*
2621 	 * Set these in case the underlying filesystem fails to do so.
2622 	 */
2623 	sbp->f_version = STATFS_VERSION;
2624 	sbp->f_namemax = NAME_MAX;
2625 	sbp->f_flags = mp->mnt_flag & MNT_VISFLAGMASK;
2626 
2627 	return (mp->mnt_op->vfs_statfs(mp, sbp));
2628 }
2629 
2630 void
2631 vfs_mountedfrom(struct mount *mp, const char *from)
2632 {
2633 
2634 	bzero(mp->mnt_stat.f_mntfromname, sizeof mp->mnt_stat.f_mntfromname);
2635 	strlcpy(mp->mnt_stat.f_mntfromname, from,
2636 	    sizeof mp->mnt_stat.f_mntfromname);
2637 }
2638 
2639 /*
2640  * ---------------------------------------------------------------------
2641  * This is the api for building mount args and mounting filesystems from
2642  * inside the kernel.
2643  *
2644  * The API works by accumulation of individual args.  First error is
2645  * latched.
2646  *
2647  * XXX: should be documented in new manpage kernel_mount(9)
2648  */
2649 
2650 /* A memory allocation which must be freed when we are done */
2651 struct mntaarg {
2652 	SLIST_ENTRY(mntaarg)	next;
2653 };
2654 
2655 /* The header for the mount arguments */
2656 struct mntarg {
2657 	struct iovec *v;
2658 	int len;
2659 	int error;
2660 	SLIST_HEAD(, mntaarg)	list;
2661 };
2662 
2663 /*
2664  * Add a boolean argument.
2665  *
2666  * flag is the boolean value.
2667  * name must start with "no".
2668  */
2669 struct mntarg *
2670 mount_argb(struct mntarg *ma, int flag, const char *name)
2671 {
2672 
2673 	KASSERT(name[0] == 'n' && name[1] == 'o',
2674 	    ("mount_argb(...,%s): name must start with 'no'", name));
2675 
2676 	return (mount_arg(ma, name + (flag ? 2 : 0), NULL, 0));
2677 }
2678 
2679 /*
2680  * Add an argument printf style
2681  */
2682 struct mntarg *
2683 mount_argf(struct mntarg *ma, const char *name, const char *fmt, ...)
2684 {
2685 	va_list ap;
2686 	struct mntaarg *maa;
2687 	struct sbuf *sb;
2688 	int len;
2689 
2690 	if (ma == NULL) {
2691 		ma = malloc(sizeof *ma, M_MOUNT, M_WAITOK | M_ZERO);
2692 		SLIST_INIT(&ma->list);
2693 	}
2694 	if (ma->error)
2695 		return (ma);
2696 
2697 	ma->v = realloc(ma->v, sizeof *ma->v * (ma->len + 2),
2698 	    M_MOUNT, M_WAITOK);
2699 	ma->v[ma->len].iov_base = (void *)(uintptr_t)name;
2700 	ma->v[ma->len].iov_len = strlen(name) + 1;
2701 	ma->len++;
2702 
2703 	sb = sbuf_new_auto();
2704 	va_start(ap, fmt);
2705 	sbuf_vprintf(sb, fmt, ap);
2706 	va_end(ap);
2707 	sbuf_finish(sb);
2708 	len = sbuf_len(sb) + 1;
2709 	maa = malloc(sizeof *maa + len, M_MOUNT, M_WAITOK | M_ZERO);
2710 	SLIST_INSERT_HEAD(&ma->list, maa, next);
2711 	bcopy(sbuf_data(sb), maa + 1, len);
2712 	sbuf_delete(sb);
2713 
2714 	ma->v[ma->len].iov_base = maa + 1;
2715 	ma->v[ma->len].iov_len = len;
2716 	ma->len++;
2717 
2718 	return (ma);
2719 }
2720 
2721 /*
2722  * Add an argument which is a userland string.
2723  */
2724 struct mntarg *
2725 mount_argsu(struct mntarg *ma, const char *name, const void *val, int len)
2726 {
2727 	struct mntaarg *maa;
2728 	char *tbuf;
2729 
2730 	if (val == NULL)
2731 		return (ma);
2732 	if (ma == NULL) {
2733 		ma = malloc(sizeof *ma, M_MOUNT, M_WAITOK | M_ZERO);
2734 		SLIST_INIT(&ma->list);
2735 	}
2736 	if (ma->error)
2737 		return (ma);
2738 	maa = malloc(sizeof *maa + len, M_MOUNT, M_WAITOK | M_ZERO);
2739 	SLIST_INSERT_HEAD(&ma->list, maa, next);
2740 	tbuf = (void *)(maa + 1);
2741 	ma->error = copyinstr(val, tbuf, len, NULL);
2742 	return (mount_arg(ma, name, tbuf, -1));
2743 }
2744 
2745 /*
2746  * Plain argument.
2747  *
2748  * If length is -1, treat value as a C string.
2749  */
2750 struct mntarg *
2751 mount_arg(struct mntarg *ma, const char *name, const void *val, int len)
2752 {
2753 
2754 	if (ma == NULL) {
2755 		ma = malloc(sizeof *ma, M_MOUNT, M_WAITOK | M_ZERO);
2756 		SLIST_INIT(&ma->list);
2757 	}
2758 	if (ma->error)
2759 		return (ma);
2760 
2761 	ma->v = realloc(ma->v, sizeof *ma->v * (ma->len + 2),
2762 	    M_MOUNT, M_WAITOK);
2763 	ma->v[ma->len].iov_base = (void *)(uintptr_t)name;
2764 	ma->v[ma->len].iov_len = strlen(name) + 1;
2765 	ma->len++;
2766 
2767 	ma->v[ma->len].iov_base = (void *)(uintptr_t)val;
2768 	if (len < 0)
2769 		ma->v[ma->len].iov_len = strlen(val) + 1;
2770 	else
2771 		ma->v[ma->len].iov_len = len;
2772 	ma->len++;
2773 	return (ma);
2774 }
2775 
2776 /*
2777  * Free a mntarg structure
2778  */
2779 static void
2780 free_mntarg(struct mntarg *ma)
2781 {
2782 	struct mntaarg *maa;
2783 
2784 	while (!SLIST_EMPTY(&ma->list)) {
2785 		maa = SLIST_FIRST(&ma->list);
2786 		SLIST_REMOVE_HEAD(&ma->list, next);
2787 		free(maa, M_MOUNT);
2788 	}
2789 	free(ma->v, M_MOUNT);
2790 	free(ma, M_MOUNT);
2791 }
2792 
2793 /*
2794  * Mount a filesystem
2795  */
2796 int
2797 kernel_mount(struct mntarg *ma, uint64_t flags)
2798 {
2799 	struct uio auio;
2800 	int error;
2801 
2802 	KASSERT(ma != NULL, ("kernel_mount NULL ma"));
2803 	KASSERT(ma->v != NULL, ("kernel_mount NULL ma->v"));
2804 	KASSERT(!(ma->len & 1), ("kernel_mount odd ma->len (%d)", ma->len));
2805 
2806 	auio.uio_iov = ma->v;
2807 	auio.uio_iovcnt = ma->len;
2808 	auio.uio_segflg = UIO_SYSSPACE;
2809 
2810 	error = ma->error;
2811 	if (!error)
2812 		error = vfs_donmount(curthread, flags, &auio);
2813 	free_mntarg(ma);
2814 	return (error);
2815 }
2816 
2817 /*
2818  * A printflike function to mount a filesystem.
2819  */
2820 int
2821 kernel_vmount(int flags, ...)
2822 {
2823 	struct mntarg *ma = NULL;
2824 	va_list ap;
2825 	const char *cp;
2826 	const void *vp;
2827 	int error;
2828 
2829 	va_start(ap, flags);
2830 	for (;;) {
2831 		cp = va_arg(ap, const char *);
2832 		if (cp == NULL)
2833 			break;
2834 		vp = va_arg(ap, const void *);
2835 		ma = mount_arg(ma, cp, vp, (vp != NULL ? -1 : 0));
2836 	}
2837 	va_end(ap);
2838 
2839 	error = kernel_mount(ma, flags);
2840 	return (error);
2841 }
2842 
2843 /* Map from mount options to printable formats. */
2844 static struct mntoptnames optnames[] = {
2845 	MNTOPT_NAMES
2846 };
2847 
2848 #define DEVCTL_LEN 1024
2849 static void
2850 mount_devctl_event(const char *type, struct mount *mp, bool donew)
2851 {
2852 	const uint8_t *cp;
2853 	struct mntoptnames *fp;
2854 	struct sbuf sb;
2855 	struct statfs *sfp = &mp->mnt_stat;
2856 	char *buf;
2857 
2858 	buf = malloc(DEVCTL_LEN, M_MOUNT, M_NOWAIT);
2859 	if (buf == NULL)
2860 		return;
2861 	sbuf_new(&sb, buf, DEVCTL_LEN, SBUF_FIXEDLEN);
2862 	sbuf_cpy(&sb, "mount-point=\"");
2863 	devctl_safe_quote_sb(&sb, sfp->f_mntonname);
2864 	sbuf_cat(&sb, "\" mount-dev=\"");
2865 	devctl_safe_quote_sb(&sb, sfp->f_mntfromname);
2866 	sbuf_cat(&sb, "\" mount-type=\"");
2867 	devctl_safe_quote_sb(&sb, sfp->f_fstypename);
2868 	sbuf_cat(&sb, "\" fsid=0x");
2869 	cp = (const uint8_t *)&sfp->f_fsid.val[0];
2870 	for (int i = 0; i < sizeof(sfp->f_fsid); i++)
2871 		sbuf_printf(&sb, "%02x", cp[i]);
2872 	sbuf_printf(&sb, " owner=%u flags=\"", sfp->f_owner);
2873 	for (fp = optnames; fp->o_opt != 0; fp++) {
2874 		if ((mp->mnt_flag & fp->o_opt) != 0) {
2875 			sbuf_cat(&sb, fp->o_name);
2876 			sbuf_putc(&sb, ';');
2877 		}
2878 	}
2879 	sbuf_putc(&sb, '"');
2880 	sbuf_finish(&sb);
2881 
2882 	/*
2883 	 * Options are not published because the form of the options depends on
2884 	 * the file system and may include binary data. In addition, they don't
2885 	 * necessarily provide enough useful information to be actionable when
2886 	 * devd processes them.
2887 	 */
2888 
2889 	if (sbuf_error(&sb) == 0)
2890 		devctl_notify("VFS", "FS", type, sbuf_data(&sb));
2891 	sbuf_delete(&sb);
2892 	free(buf, M_MOUNT);
2893 }
2894 
2895 /*
2896  * Suspend write operations on all local writeable filesystems.  Does
2897  * full sync of them in the process.
2898  *
2899  * Iterate over the mount points in reverse order, suspending most
2900  * recently mounted filesystems first.  It handles a case where a
2901  * filesystem mounted from a md(4) vnode-backed device should be
2902  * suspended before the filesystem that owns the vnode.
2903  */
2904 void
2905 suspend_all_fs(void)
2906 {
2907 	struct mount *mp;
2908 	int error;
2909 
2910 	mtx_lock(&mountlist_mtx);
2911 	TAILQ_FOREACH_REVERSE(mp, &mountlist, mntlist, mnt_list) {
2912 		error = vfs_busy(mp, MBF_MNTLSTLOCK | MBF_NOWAIT);
2913 		if (error != 0)
2914 			continue;
2915 		if ((mp->mnt_flag & (MNT_RDONLY | MNT_LOCAL)) != MNT_LOCAL ||
2916 		    (mp->mnt_kern_flag & MNTK_SUSPEND) != 0) {
2917 			mtx_lock(&mountlist_mtx);
2918 			vfs_unbusy(mp);
2919 			continue;
2920 		}
2921 		error = vfs_write_suspend(mp, 0);
2922 		if (error == 0) {
2923 			MNT_ILOCK(mp);
2924 			MPASS((mp->mnt_kern_flag & MNTK_SUSPEND_ALL) == 0);
2925 			mp->mnt_kern_flag |= MNTK_SUSPEND_ALL;
2926 			MNT_IUNLOCK(mp);
2927 			mtx_lock(&mountlist_mtx);
2928 		} else {
2929 			printf("suspend of %s failed, error %d\n",
2930 			    mp->mnt_stat.f_mntonname, error);
2931 			mtx_lock(&mountlist_mtx);
2932 			vfs_unbusy(mp);
2933 		}
2934 	}
2935 	mtx_unlock(&mountlist_mtx);
2936 }
2937 
2938 void
2939 resume_all_fs(void)
2940 {
2941 	struct mount *mp;
2942 
2943 	mtx_lock(&mountlist_mtx);
2944 	TAILQ_FOREACH(mp, &mountlist, mnt_list) {
2945 		if ((mp->mnt_kern_flag & MNTK_SUSPEND_ALL) == 0)
2946 			continue;
2947 		mtx_unlock(&mountlist_mtx);
2948 		MNT_ILOCK(mp);
2949 		MPASS((mp->mnt_kern_flag & MNTK_SUSPEND) != 0);
2950 		mp->mnt_kern_flag &= ~MNTK_SUSPEND_ALL;
2951 		MNT_IUNLOCK(mp);
2952 		vfs_write_resume(mp, 0);
2953 		mtx_lock(&mountlist_mtx);
2954 		vfs_unbusy(mp);
2955 	}
2956 	mtx_unlock(&mountlist_mtx);
2957 }
2958