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