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