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