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