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