xref: /titanic_50/usr/src/uts/common/fs/vfs.c (revision 81d2f16decea68b37031d78bb59a281bf486e420)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright (c) 1988, 2010, Oracle and/or its affiliates. All rights reserved.
23  * Copyright (c) 2014, Joyent, Inc. All rights reserved.
24  * Copyright 2015 Nexenta Systems, Inc. All rights reserved.
25  * Copyright 2017 RackTop Systems.
26  */
27 
28 /*	Copyright (c) 1983, 1984, 1985, 1986, 1987, 1988, 1989 AT&T	*/
29 /*	  All Rights Reserved  	*/
30 
31 /*
32  * University Copyright- Copyright (c) 1982, 1986, 1988
33  * The Regents of the University of California
34  * All Rights Reserved
35  *
36  * University Acknowledgment- Portions of this document are derived from
37  * software developed by the University of California, Berkeley, and its
38  * contributors.
39  */
40 
41 #include <sys/types.h>
42 #include <sys/t_lock.h>
43 #include <sys/param.h>
44 #include <sys/errno.h>
45 #include <sys/user.h>
46 #include <sys/fstyp.h>
47 #include <sys/kmem.h>
48 #include <sys/systm.h>
49 #include <sys/proc.h>
50 #include <sys/mount.h>
51 #include <sys/vfs.h>
52 #include <sys/vfs_opreg.h>
53 #include <sys/fem.h>
54 #include <sys/mntent.h>
55 #include <sys/stat.h>
56 #include <sys/statvfs.h>
57 #include <sys/statfs.h>
58 #include <sys/cred.h>
59 #include <sys/vnode.h>
60 #include <sys/rwstlock.h>
61 #include <sys/dnlc.h>
62 #include <sys/file.h>
63 #include <sys/time.h>
64 #include <sys/atomic.h>
65 #include <sys/cmn_err.h>
66 #include <sys/buf.h>
67 #include <sys/swap.h>
68 #include <sys/debug.h>
69 #include <sys/vnode.h>
70 #include <sys/modctl.h>
71 #include <sys/ddi.h>
72 #include <sys/pathname.h>
73 #include <sys/bootconf.h>
74 #include <sys/dumphdr.h>
75 #include <sys/dc_ki.h>
76 #include <sys/poll.h>
77 #include <sys/sunddi.h>
78 #include <sys/sysmacros.h>
79 #include <sys/zone.h>
80 #include <sys/policy.h>
81 #include <sys/ctfs.h>
82 #include <sys/objfs.h>
83 #include <sys/console.h>
84 #include <sys/reboot.h>
85 #include <sys/attr.h>
86 #include <sys/zio.h>
87 #include <sys/spa.h>
88 #include <sys/lofi.h>
89 #include <sys/bootprops.h>
90 #include <sys/avl.h>
91 
92 #include <vm/page.h>
93 
94 #include <fs/fs_subr.h>
95 /* Private interfaces to create vopstats-related data structures */
96 extern void		initialize_vopstats(vopstats_t *);
97 extern vopstats_t	*get_fstype_vopstats(struct vfs *, struct vfssw *);
98 extern vsk_anchor_t	*get_vskstat_anchor(struct vfs *);
99 
100 static void vfs_clearmntopt_nolock(mntopts_t *, const char *, int);
101 static void vfs_setmntopt_nolock(mntopts_t *, const char *,
102     const char *, int, int);
103 static int  vfs_optionisset_nolock(const mntopts_t *, const char *, char **);
104 static void vfs_freemnttab(struct vfs *);
105 static void vfs_freeopt(mntopt_t *);
106 static void vfs_swapopttbl_nolock(mntopts_t *, mntopts_t *);
107 static void vfs_swapopttbl(mntopts_t *, mntopts_t *);
108 static void vfs_copyopttbl_extend(const mntopts_t *, mntopts_t *, int);
109 static void vfs_createopttbl_extend(mntopts_t *, const char *,
110     const mntopts_t *);
111 static char **vfs_copycancelopt_extend(char **const, int);
112 static void vfs_freecancelopt(char **);
113 static void getrootfs(char **, char **);
114 static int getmacpath(dev_info_t *, void *);
115 static void vfs_mnttabvp_setup(void);
116 
117 struct ipmnt {
118 	struct ipmnt	*mip_next;
119 	dev_t		mip_dev;
120 	struct vfs	*mip_vfsp;
121 };
122 
123 static kmutex_t		vfs_miplist_mutex;
124 static struct ipmnt	*vfs_miplist = NULL;
125 static struct ipmnt	*vfs_miplist_end = NULL;
126 
127 static kmem_cache_t *vfs_cache;	/* Pointer to VFS kmem cache */
128 
129 /*
130  * VFS global data.
131  */
132 vnode_t *rootdir;		/* pointer to root inode vnode. */
133 vnode_t *devicesdir;		/* pointer to inode of devices root */
134 vnode_t	*devdir;		/* pointer to inode of dev root */
135 
136 char *server_rootpath;		/* root path for diskless clients */
137 char *server_hostname;		/* hostname of diskless server */
138 
139 static struct vfs root;
140 static struct vfs devices;
141 static struct vfs dev;
142 struct vfs *rootvfs = &root;	/* pointer to root vfs; head of VFS list. */
143 avl_tree_t vfs_by_dev;		/* avl tree to index mounted VFSs by dev */
144 avl_tree_t vfs_by_mntpnt;	/* avl tree to index mounted VFSs by mntpnt */
145 uint64_t vfs_curr_mntix;	/* counter to provide a unique mntix for
146 				 * entries in the above avl trees.
147 				 * protected by vfslist lock */
148 rvfs_t *rvfs_list;		/* array of vfs ptrs for vfs hash list */
149 int vfshsz = 512;		/* # of heads/locks in vfs hash arrays */
150 				/* must be power of 2!	*/
151 timespec_t vfs_mnttab_ctime;	/* mnttab created time */
152 timespec_t vfs_mnttab_mtime;	/* mnttab last modified time */
153 char *vfs_dummyfstype = "\0";
154 struct pollhead vfs_pollhd;	/* for mnttab pollers */
155 struct vnode *vfs_mntdummyvp;	/* to fake mnttab read/write for file events */
156 int	mntfstype;		/* will be set once mnt fs is mounted */
157 
158 /*
159  * Table for generic options recognized in the VFS layer and acted
160  * on at this level before parsing file system specific options.
161  * The nosuid option is stronger than any of the devices and setuid
162  * options, so those are canceled when nosuid is seen.
163  *
164  * All options which are added here need to be added to the
165  * list of standard options in usr/src/cmd/fs.d/fslib.c as well.
166  */
167 /*
168  * VFS Mount options table
169  */
170 static char *ro_cancel[] = { MNTOPT_RW, NULL };
171 static char *rw_cancel[] = { MNTOPT_RO, NULL };
172 static char *suid_cancel[] = { MNTOPT_NOSUID, NULL };
173 static char *nosuid_cancel[] = { MNTOPT_SUID, MNTOPT_DEVICES, MNTOPT_NODEVICES,
174     MNTOPT_NOSETUID, MNTOPT_SETUID, NULL };
175 static char *devices_cancel[] = { MNTOPT_NODEVICES, NULL };
176 static char *nodevices_cancel[] = { MNTOPT_DEVICES, NULL };
177 static char *setuid_cancel[] = { MNTOPT_NOSETUID, NULL };
178 static char *nosetuid_cancel[] = { MNTOPT_SETUID, NULL };
179 static char *nbmand_cancel[] = { MNTOPT_NONBMAND, NULL };
180 static char *nonbmand_cancel[] = { MNTOPT_NBMAND, NULL };
181 static char *exec_cancel[] = { MNTOPT_NOEXEC, NULL };
182 static char *noexec_cancel[] = { MNTOPT_EXEC, NULL };
183 
184 static const mntopt_t mntopts[] = {
185 /*
186  *	option name		cancel options		default arg	flags
187  */
188 	{ MNTOPT_REMOUNT,	NULL,			NULL,
189 		MO_NODISPLAY, (void *)0 },
190 	{ MNTOPT_RO,		ro_cancel,		NULL,		0,
191 		(void *)0 },
192 	{ MNTOPT_RW,		rw_cancel,		NULL,		0,
193 		(void *)0 },
194 	{ MNTOPT_SUID,		suid_cancel,		NULL,		0,
195 		(void *)0 },
196 	{ MNTOPT_NOSUID,	nosuid_cancel,		NULL,		0,
197 		(void *)0 },
198 	{ MNTOPT_DEVICES,	devices_cancel,		NULL,		0,
199 		(void *)0 },
200 	{ MNTOPT_NODEVICES,	nodevices_cancel,	NULL,		0,
201 		(void *)0 },
202 	{ MNTOPT_SETUID,	setuid_cancel,		NULL,		0,
203 		(void *)0 },
204 	{ MNTOPT_NOSETUID,	nosetuid_cancel,	NULL,		0,
205 		(void *)0 },
206 	{ MNTOPT_NBMAND,	nbmand_cancel,		NULL,		0,
207 		(void *)0 },
208 	{ MNTOPT_NONBMAND,	nonbmand_cancel,	NULL,		0,
209 		(void *)0 },
210 	{ MNTOPT_EXEC,		exec_cancel,		NULL,		0,
211 		(void *)0 },
212 	{ MNTOPT_NOEXEC,	noexec_cancel,		NULL,		0,
213 		(void *)0 },
214 };
215 
216 const mntopts_t vfs_mntopts = {
217 	sizeof (mntopts) / sizeof (mntopt_t),
218 	(mntopt_t *)&mntopts[0]
219 };
220 
221 /*
222  * File system operation dispatch functions.
223  */
224 
225 int
226 fsop_mount(vfs_t *vfsp, vnode_t *mvp, struct mounta *uap, cred_t *cr)
227 {
228 	return (*(vfsp)->vfs_op->vfs_mount)(vfsp, mvp, uap, cr);
229 }
230 
231 int
232 fsop_unmount(vfs_t *vfsp, int flag, cred_t *cr)
233 {
234 	return (*(vfsp)->vfs_op->vfs_unmount)(vfsp, flag, cr);
235 }
236 
237 int
238 fsop_root(vfs_t *vfsp, vnode_t **vpp)
239 {
240 	refstr_t *mntpt;
241 	int ret = (*(vfsp)->vfs_op->vfs_root)(vfsp, vpp);
242 	/*
243 	 * Make sure this root has a path.  With lofs, it is possible to have
244 	 * a NULL mountpoint.
245 	 */
246 	if (ret == 0 && vfsp->vfs_mntpt != NULL && (*vpp)->v_path == NULL) {
247 		mntpt = vfs_getmntpoint(vfsp);
248 		vn_setpath_str(*vpp, refstr_value(mntpt),
249 		    strlen(refstr_value(mntpt)));
250 		refstr_rele(mntpt);
251 	}
252 
253 	return (ret);
254 }
255 
256 int
257 fsop_statfs(vfs_t *vfsp, statvfs64_t *sp)
258 {
259 	return (*(vfsp)->vfs_op->vfs_statvfs)(vfsp, sp);
260 }
261 
262 int
263 fsop_sync(vfs_t *vfsp, short flag, cred_t *cr)
264 {
265 	return (*(vfsp)->vfs_op->vfs_sync)(vfsp, flag, cr);
266 }
267 
268 int
269 fsop_vget(vfs_t *vfsp, vnode_t **vpp, fid_t *fidp)
270 {
271 	/*
272 	 * In order to handle system attribute fids in a manner
273 	 * transparent to the underlying fs, we embed the fid for
274 	 * the sysattr parent object in the sysattr fid and tack on
275 	 * some extra bytes that only the sysattr layer knows about.
276 	 *
277 	 * This guarantees that sysattr fids are larger than other fids
278 	 * for this vfs. If the vfs supports the sysattr view interface
279 	 * (as indicated by VFSFT_SYSATTR_VIEWS), we cannot have a size
280 	 * collision with XATTR_FIDSZ.
281 	 */
282 	if (vfs_has_feature(vfsp, VFSFT_SYSATTR_VIEWS) &&
283 	    fidp->fid_len == XATTR_FIDSZ)
284 		return (xattr_dir_vget(vfsp, vpp, fidp));
285 
286 	return (*(vfsp)->vfs_op->vfs_vget)(vfsp, vpp, fidp);
287 }
288 
289 int
290 fsop_mountroot(vfs_t *vfsp, enum whymountroot reason)
291 {
292 	return (*(vfsp)->vfs_op->vfs_mountroot)(vfsp, reason);
293 }
294 
295 void
296 fsop_freefs(vfs_t *vfsp)
297 {
298 	(*(vfsp)->vfs_op->vfs_freevfs)(vfsp);
299 }
300 
301 int
302 fsop_vnstate(vfs_t *vfsp, vnode_t *vp, vntrans_t nstate)
303 {
304 	return ((*(vfsp)->vfs_op->vfs_vnstate)(vfsp, vp, nstate));
305 }
306 
307 int
308 fsop_sync_by_kind(int fstype, short flag, cred_t *cr)
309 {
310 	ASSERT((fstype >= 0) && (fstype < nfstype));
311 
312 	if (ALLOCATED_VFSSW(&vfssw[fstype]) && VFS_INSTALLED(&vfssw[fstype]))
313 		return (*vfssw[fstype].vsw_vfsops.vfs_sync) (NULL, flag, cr);
314 	else
315 		return (ENOTSUP);
316 }
317 
318 /*
319  * File system initialization.  vfs_setfsops() must be called from a file
320  * system's init routine.
321  */
322 
323 static int
324 fs_copyfsops(const fs_operation_def_t *template, vfsops_t *actual,
325     int *unused_ops)
326 {
327 	static const fs_operation_trans_def_t vfs_ops_table[] = {
328 		VFSNAME_MOUNT, offsetof(vfsops_t, vfs_mount),
329 			fs_nosys, fs_nosys,
330 
331 		VFSNAME_UNMOUNT, offsetof(vfsops_t, vfs_unmount),
332 			fs_nosys, fs_nosys,
333 
334 		VFSNAME_ROOT, offsetof(vfsops_t, vfs_root),
335 			fs_nosys, fs_nosys,
336 
337 		VFSNAME_STATVFS, offsetof(vfsops_t, vfs_statvfs),
338 			fs_nosys, fs_nosys,
339 
340 		VFSNAME_SYNC, offsetof(vfsops_t, vfs_sync),
341 			(fs_generic_func_p) fs_sync,
342 			(fs_generic_func_p) fs_sync,	/* No errors allowed */
343 
344 		VFSNAME_VGET, offsetof(vfsops_t, vfs_vget),
345 			fs_nosys, fs_nosys,
346 
347 		VFSNAME_MOUNTROOT, offsetof(vfsops_t, vfs_mountroot),
348 			fs_nosys, fs_nosys,
349 
350 		VFSNAME_FREEVFS, offsetof(vfsops_t, vfs_freevfs),
351 			(fs_generic_func_p)fs_freevfs,
352 			(fs_generic_func_p)fs_freevfs,	/* Shouldn't fail */
353 
354 		VFSNAME_VNSTATE, offsetof(vfsops_t, vfs_vnstate),
355 			(fs_generic_func_p)fs_nosys,
356 			(fs_generic_func_p)fs_nosys,
357 
358 		NULL, 0, NULL, NULL
359 	};
360 
361 	return (fs_build_vector(actual, unused_ops, vfs_ops_table, template));
362 }
363 
364 void
365 zfs_boot_init() {
366 
367 	if (strcmp(rootfs.bo_fstype, MNTTYPE_ZFS) == 0)
368 		spa_boot_init();
369 }
370 
371 int
372 vfs_setfsops(int fstype, const fs_operation_def_t *template, vfsops_t **actual)
373 {
374 	int error;
375 	int unused_ops;
376 
377 	/*
378 	 * Verify that fstype refers to a valid fs.  Note that
379 	 * 0 is valid since it's used to set "stray" ops.
380 	 */
381 	if ((fstype < 0) || (fstype >= nfstype))
382 		return (EINVAL);
383 
384 	if (!ALLOCATED_VFSSW(&vfssw[fstype]))
385 		return (EINVAL);
386 
387 	/* Set up the operations vector. */
388 
389 	error = fs_copyfsops(template, &vfssw[fstype].vsw_vfsops, &unused_ops);
390 
391 	if (error != 0)
392 		return (error);
393 
394 	vfssw[fstype].vsw_flag |= VSW_INSTALLED;
395 
396 	if (actual != NULL)
397 		*actual = &vfssw[fstype].vsw_vfsops;
398 
399 #if DEBUG
400 	if (unused_ops != 0)
401 		cmn_err(CE_WARN, "vfs_setfsops: %s: %d operations supplied "
402 		    "but not used", vfssw[fstype].vsw_name, unused_ops);
403 #endif
404 
405 	return (0);
406 }
407 
408 int
409 vfs_makefsops(const fs_operation_def_t *template, vfsops_t **actual)
410 {
411 	int error;
412 	int unused_ops;
413 
414 	*actual = (vfsops_t *)kmem_alloc(sizeof (vfsops_t), KM_SLEEP);
415 
416 	error = fs_copyfsops(template, *actual, &unused_ops);
417 	if (error != 0) {
418 		kmem_free(*actual, sizeof (vfsops_t));
419 		*actual = NULL;
420 		return (error);
421 	}
422 
423 	return (0);
424 }
425 
426 /*
427  * Free a vfsops structure created as a result of vfs_makefsops().
428  * NOTE: For a vfsops structure initialized by vfs_setfsops(), use
429  * vfs_freevfsops_by_type().
430  */
431 void
432 vfs_freevfsops(vfsops_t *vfsops)
433 {
434 	kmem_free(vfsops, sizeof (vfsops_t));
435 }
436 
437 /*
438  * Since the vfsops structure is part of the vfssw table and wasn't
439  * really allocated, we're not really freeing anything.  We keep
440  * the name for consistency with vfs_freevfsops().  We do, however,
441  * need to take care of a little bookkeeping.
442  * NOTE: For a vfsops structure created by vfs_setfsops(), use
443  * vfs_freevfsops_by_type().
444  */
445 int
446 vfs_freevfsops_by_type(int fstype)
447 {
448 
449 	/* Verify that fstype refers to a loaded fs (and not fsid 0). */
450 	if ((fstype <= 0) || (fstype >= nfstype))
451 		return (EINVAL);
452 
453 	WLOCK_VFSSW();
454 	if ((vfssw[fstype].vsw_flag & VSW_INSTALLED) == 0) {
455 		WUNLOCK_VFSSW();
456 		return (EINVAL);
457 	}
458 
459 	vfssw[fstype].vsw_flag &= ~VSW_INSTALLED;
460 	WUNLOCK_VFSSW();
461 
462 	return (0);
463 }
464 
465 /* Support routines used to reference vfs_op */
466 
467 /* Set the operations vector for a vfs */
468 void
469 vfs_setops(vfs_t *vfsp, vfsops_t *vfsops)
470 {
471 	vfsops_t	*op;
472 
473 	ASSERT(vfsp != NULL);
474 	ASSERT(vfsops != NULL);
475 
476 	op = vfsp->vfs_op;
477 	membar_consumer();
478 	if (vfsp->vfs_femhead == NULL &&
479 	    atomic_cas_ptr(&vfsp->vfs_op, op, vfsops) == op) {
480 		return;
481 	}
482 	fsem_setvfsops(vfsp, vfsops);
483 }
484 
485 /* Retrieve the operations vector for a vfs */
486 vfsops_t *
487 vfs_getops(vfs_t *vfsp)
488 {
489 	vfsops_t	*op;
490 
491 	ASSERT(vfsp != NULL);
492 
493 	op = vfsp->vfs_op;
494 	membar_consumer();
495 	if (vfsp->vfs_femhead == NULL && op == vfsp->vfs_op) {
496 		return (op);
497 	} else {
498 		return (fsem_getvfsops(vfsp));
499 	}
500 }
501 
502 /*
503  * Returns non-zero (1) if the vfsops matches that of the vfs.
504  * Returns zero (0) if not.
505  */
506 int
507 vfs_matchops(vfs_t *vfsp, vfsops_t *vfsops)
508 {
509 	return (vfs_getops(vfsp) == vfsops);
510 }
511 
512 /*
513  * Returns non-zero (1) if the file system has installed a non-default,
514  * non-error vfs_sync routine.  Returns zero (0) otherwise.
515  */
516 int
517 vfs_can_sync(vfs_t *vfsp)
518 {
519 	/* vfs_sync() routine is not the default/error function */
520 	return (vfs_getops(vfsp)->vfs_sync != fs_sync);
521 }
522 
523 /*
524  * Initialize a vfs structure.
525  */
526 void
527 vfs_init(vfs_t *vfsp, vfsops_t *op, void *data)
528 {
529 	/* Other initialization has been moved to vfs_alloc() */
530 	vfsp->vfs_count = 0;
531 	vfsp->vfs_next = vfsp;
532 	vfsp->vfs_prev = vfsp;
533 	vfsp->vfs_zone_next = vfsp;
534 	vfsp->vfs_zone_prev = vfsp;
535 	vfsp->vfs_lofi_minor = 0;
536 	sema_init(&vfsp->vfs_reflock, 1, NULL, SEMA_DEFAULT, NULL);
537 	vfsimpl_setup(vfsp);
538 	vfsp->vfs_data = (data);
539 	vfs_setops((vfsp), (op));
540 }
541 
542 /*
543  * Allocate and initialize the vfs implementation private data
544  * structure, vfs_impl_t.
545  */
546 void
547 vfsimpl_setup(vfs_t *vfsp)
548 {
549 	int i;
550 
551 	if (vfsp->vfs_implp != NULL) {
552 		return;
553 	}
554 
555 	vfsp->vfs_implp = kmem_alloc(sizeof (vfs_impl_t), KM_SLEEP);
556 	/* Note that these are #define'd in vfs.h */
557 	vfsp->vfs_vskap = NULL;
558 	vfsp->vfs_fstypevsp = NULL;
559 
560 	/* Set size of counted array, then zero the array */
561 	vfsp->vfs_featureset[0] = VFS_FEATURE_MAXSZ - 1;
562 	for (i = 1; i <  VFS_FEATURE_MAXSZ; i++) {
563 		vfsp->vfs_featureset[i] = 0;
564 	}
565 }
566 
567 /*
568  * Release the vfs_impl_t structure, if it exists. Some unbundled
569  * filesystems may not use the newer version of vfs and thus
570  * would not contain this implementation private data structure.
571  */
572 void
573 vfsimpl_teardown(vfs_t *vfsp)
574 {
575 	vfs_impl_t	*vip = vfsp->vfs_implp;
576 
577 	if (vip == NULL)
578 		return;
579 
580 	kmem_free(vfsp->vfs_implp, sizeof (vfs_impl_t));
581 	vfsp->vfs_implp = NULL;
582 }
583 
584 /*
585  * VFS system calls: mount, umount, syssync, statfs, fstatfs, statvfs,
586  * fstatvfs, and sysfs moved to common/syscall.
587  */
588 
589 /*
590  * Update every mounted file system.  We call the vfs_sync operation of
591  * each file system type, passing it a NULL vfsp to indicate that all
592  * mounted file systems of that type should be updated.
593  */
594 void
595 vfs_sync(int flag)
596 {
597 	struct vfssw *vswp;
598 	RLOCK_VFSSW();
599 	for (vswp = &vfssw[1]; vswp < &vfssw[nfstype]; vswp++) {
600 		if (ALLOCATED_VFSSW(vswp) && VFS_INSTALLED(vswp)) {
601 			vfs_refvfssw(vswp);
602 			RUNLOCK_VFSSW();
603 			(void) (*vswp->vsw_vfsops.vfs_sync)(NULL, flag,
604 			    CRED());
605 			vfs_unrefvfssw(vswp);
606 			RLOCK_VFSSW();
607 		}
608 	}
609 	RUNLOCK_VFSSW();
610 }
611 
612 void
613 sync(void)
614 {
615 	vfs_sync(0);
616 }
617 
618 /*
619  * compare function for vfs_by_dev avl tree. compare dev first, then mntix
620  */
621 static int
622 vfs_cmp_dev(const void *aa, const void *bb)
623 {
624 	const vfs_t *a = aa;
625 	const vfs_t *b = bb;
626 
627 	if (a->vfs_dev < b->vfs_dev)
628 		return (-1);
629 	if (a->vfs_dev > b->vfs_dev)
630 		return (1);
631 	if (a->vfs_mntix < b->vfs_mntix)
632 		return (-1);
633 	if (a->vfs_mntix > b->vfs_mntix)
634 		return (1);
635 	return (0);
636 }
637 
638 /*
639  * compare function for vfs_by_mntpnt avl tree. compare mntpnt first, then mntix
640  */
641 static int
642 vfs_cmp_mntpnt(const void *aa, const void *bb)
643 {
644 	const vfs_t *a = aa;
645 	const vfs_t *b = bb;
646 	int ret;
647 
648 	ret = strcmp(refstr_value(a->vfs_mntpt), refstr_value(b->vfs_mntpt));
649 	if (ret < 0)
650 		return (-1);
651 	if (ret > 0)
652 		return (1);
653 	if (a->vfs_mntix < b->vfs_mntix)
654 		return (-1);
655 	if (a->vfs_mntix > b->vfs_mntix)
656 		return (1);
657 	return (0);
658 }
659 
660 /*
661  * External routines.
662  */
663 
664 krwlock_t vfssw_lock;	/* lock accesses to vfssw */
665 
666 /*
667  * Lock for accessing the vfs linked list.  Initialized in vfs_mountroot(),
668  * but otherwise should be accessed only via vfs_list_lock() and
669  * vfs_list_unlock().  Also used to protect the timestamp for mods to the list.
670  */
671 static krwlock_t vfslist;
672 
673 /*
674  * Mount devfs on /devices. This is done right after root is mounted
675  * to provide device access support for the system
676  */
677 static void
678 vfs_mountdevices(void)
679 {
680 	struct vfssw *vsw;
681 	struct vnode *mvp;
682 	struct mounta mounta = {	/* fake mounta for devfs_mount() */
683 		NULL,
684 		NULL,
685 		MS_SYSSPACE,
686 		NULL,
687 		NULL,
688 		0,
689 		NULL,
690 		0
691 	};
692 
693 	/*
694 	 * _init devfs module to fill in the vfssw
695 	 */
696 	if (modload("fs", "devfs") == -1)
697 		panic("Cannot _init devfs module");
698 
699 	/*
700 	 * Hold vfs
701 	 */
702 	RLOCK_VFSSW();
703 	vsw = vfs_getvfsswbyname("devfs");
704 	VFS_INIT(&devices, &vsw->vsw_vfsops, NULL);
705 	VFS_HOLD(&devices);
706 
707 	/*
708 	 * Locate mount point
709 	 */
710 	if (lookupname("/devices", UIO_SYSSPACE, FOLLOW, NULLVPP, &mvp))
711 		panic("Cannot find /devices");
712 
713 	/*
714 	 * Perform the mount of /devices
715 	 */
716 	if (VFS_MOUNT(&devices, mvp, &mounta, CRED()))
717 		panic("Cannot mount /devices");
718 
719 	RUNLOCK_VFSSW();
720 
721 	/*
722 	 * Set appropriate members and add to vfs list for mnttab display
723 	 */
724 	vfs_setresource(&devices, "/devices", 0);
725 	vfs_setmntpoint(&devices, "/devices", 0);
726 
727 	/*
728 	 * Hold the root of /devices so it won't go away
729 	 */
730 	if (VFS_ROOT(&devices, &devicesdir))
731 		panic("vfs_mountdevices: not devices root");
732 
733 	if (vfs_lock(&devices) != 0) {
734 		VN_RELE(devicesdir);
735 		cmn_err(CE_NOTE, "Cannot acquire vfs_lock of /devices");
736 		return;
737 	}
738 
739 	if (vn_vfswlock(mvp) != 0) {
740 		vfs_unlock(&devices);
741 		VN_RELE(devicesdir);
742 		cmn_err(CE_NOTE, "Cannot acquire vfswlock of /devices");
743 		return;
744 	}
745 
746 	vfs_add(mvp, &devices, 0);
747 	vn_vfsunlock(mvp);
748 	vfs_unlock(&devices);
749 	VN_RELE(devicesdir);
750 }
751 
752 /*
753  * mount the first instance of /dev  to root and remain mounted
754  */
755 static void
756 vfs_mountdev1(void)
757 {
758 	struct vfssw *vsw;
759 	struct vnode *mvp;
760 	struct mounta mounta = {	/* fake mounta for sdev_mount() */
761 		NULL,
762 		NULL,
763 		MS_SYSSPACE | MS_OVERLAY,
764 		NULL,
765 		NULL,
766 		0,
767 		NULL,
768 		0
769 	};
770 
771 	/*
772 	 * _init dev module to fill in the vfssw
773 	 */
774 	if (modload("fs", "dev") == -1)
775 		cmn_err(CE_PANIC, "Cannot _init dev module\n");
776 
777 	/*
778 	 * Hold vfs
779 	 */
780 	RLOCK_VFSSW();
781 	vsw = vfs_getvfsswbyname("dev");
782 	VFS_INIT(&dev, &vsw->vsw_vfsops, NULL);
783 	VFS_HOLD(&dev);
784 
785 	/*
786 	 * Locate mount point
787 	 */
788 	if (lookupname("/dev", UIO_SYSSPACE, FOLLOW, NULLVPP, &mvp))
789 		cmn_err(CE_PANIC, "Cannot find /dev\n");
790 
791 	/*
792 	 * Perform the mount of /dev
793 	 */
794 	if (VFS_MOUNT(&dev, mvp, &mounta, CRED()))
795 		cmn_err(CE_PANIC, "Cannot mount /dev 1\n");
796 
797 	RUNLOCK_VFSSW();
798 
799 	/*
800 	 * Set appropriate members and add to vfs list for mnttab display
801 	 */
802 	vfs_setresource(&dev, "/dev", 0);
803 	vfs_setmntpoint(&dev, "/dev", 0);
804 
805 	/*
806 	 * Hold the root of /dev so it won't go away
807 	 */
808 	if (VFS_ROOT(&dev, &devdir))
809 		cmn_err(CE_PANIC, "vfs_mountdev1: not dev root");
810 
811 	if (vfs_lock(&dev) != 0) {
812 		VN_RELE(devdir);
813 		cmn_err(CE_NOTE, "Cannot acquire vfs_lock of /dev");
814 		return;
815 	}
816 
817 	if (vn_vfswlock(mvp) != 0) {
818 		vfs_unlock(&dev);
819 		VN_RELE(devdir);
820 		cmn_err(CE_NOTE, "Cannot acquire vfswlock of /dev");
821 		return;
822 	}
823 
824 	vfs_add(mvp, &dev, 0);
825 	vn_vfsunlock(mvp);
826 	vfs_unlock(&dev);
827 	VN_RELE(devdir);
828 }
829 
830 /*
831  * Mount required filesystem. This is done right after root is mounted.
832  */
833 static void
834 vfs_mountfs(char *module, char *spec, char *path)
835 {
836 	struct vnode *mvp;
837 	struct mounta mounta;
838 	vfs_t *vfsp;
839 
840 	bzero(&mounta, sizeof (mounta));
841 	mounta.flags = MS_SYSSPACE | MS_DATA;
842 	mounta.fstype = module;
843 	mounta.spec = spec;
844 	mounta.dir = path;
845 	if (lookupname(path, UIO_SYSSPACE, FOLLOW, NULLVPP, &mvp)) {
846 		cmn_err(CE_WARN, "Cannot find %s", path);
847 		return;
848 	}
849 	if (domount(NULL, &mounta, mvp, CRED(), &vfsp))
850 		cmn_err(CE_WARN, "Cannot mount %s", path);
851 	else
852 		VFS_RELE(vfsp);
853 	VN_RELE(mvp);
854 }
855 
856 /*
857  * vfs_mountroot is called by main() to mount the root filesystem.
858  */
859 void
860 vfs_mountroot(void)
861 {
862 	struct vnode	*rvp = NULL;
863 	char		*path;
864 	size_t		plen;
865 	struct vfssw	*vswp;
866 	proc_t		*p;
867 
868 	rw_init(&vfssw_lock, NULL, RW_DEFAULT, NULL);
869 	rw_init(&vfslist, NULL, RW_DEFAULT, NULL);
870 
871 	/*
872 	 * Alloc the avl trees for quick indexing via dev and mountpoint
873 	 */
874 	avl_create(&vfs_by_dev, vfs_cmp_dev, sizeof(vfs_t),
875 	    offsetof(vfs_t, vfs_avldev));
876 	avl_create(&vfs_by_mntpnt, vfs_cmp_mntpnt, sizeof(vfs_t),
877 	    offsetof(vfs_t, vfs_avlmntpnt));
878 
879 	/*
880 	 * Alloc the vfs hash bucket array and locks
881 	 */
882 	rvfs_list = kmem_zalloc(vfshsz * sizeof (rvfs_t), KM_SLEEP);
883 
884 	/*
885 	 * Call machine-dependent routine "rootconf" to choose a root
886 	 * file system type.
887 	 */
888 	if (rootconf())
889 		panic("vfs_mountroot: cannot mount root");
890 	/*
891 	 * Get vnode for '/'.  Set up rootdir, u.u_rdir and u.u_cdir
892 	 * to point to it.  These are used by lookuppn() so that it
893 	 * knows where to start from ('/' or '.').
894 	 */
895 	vfs_setmntpoint(rootvfs, "/", 0);
896 	if (VFS_ROOT(rootvfs, &rootdir))
897 		panic("vfs_mountroot: no root vnode");
898 
899 	/*
900 	 * At this point, the process tree consists of p0 and possibly some
901 	 * direct children of p0.  (i.e. there are no grandchildren)
902 	 *
903 	 * Walk through them all, setting their current directory.
904 	 */
905 	mutex_enter(&pidlock);
906 	for (p = practive; p != NULL; p = p->p_next) {
907 		ASSERT(p == &p0 || p->p_parent == &p0);
908 
909 		PTOU(p)->u_cdir = rootdir;
910 		VN_HOLD(PTOU(p)->u_cdir);
911 		PTOU(p)->u_rdir = NULL;
912 	}
913 	mutex_exit(&pidlock);
914 
915 	/*
916 	 * Setup the global zone's rootvp, now that it exists.
917 	 */
918 	global_zone->zone_rootvp = rootdir;
919 	VN_HOLD(global_zone->zone_rootvp);
920 
921 	/*
922 	 * Notify the module code that it can begin using the
923 	 * root filesystem instead of the boot program's services.
924 	 */
925 	modrootloaded = 1;
926 
927 	/*
928 	 * Special handling for a ZFS root file system.
929 	 */
930 	zfs_boot_init();
931 
932 	/*
933 	 * Set up mnttab information for root
934 	 */
935 	vfs_setresource(rootvfs, rootfs.bo_name, 0);
936 
937 	/*
938 	 * Notify cluster software that the root filesystem is available.
939 	 */
940 	clboot_mountroot();
941 
942 	/* Now that we're all done with the root FS, set up its vopstats */
943 	if ((vswp = vfs_getvfsswbyvfsops(vfs_getops(rootvfs))) != NULL) {
944 		/* Set flag for statistics collection */
945 		if (vswp->vsw_flag & VSW_STATS) {
946 			initialize_vopstats(&rootvfs->vfs_vopstats);
947 			rootvfs->vfs_flag |= VFS_STATS;
948 			rootvfs->vfs_fstypevsp =
949 			    get_fstype_vopstats(rootvfs, vswp);
950 			rootvfs->vfs_vskap = get_vskstat_anchor(rootvfs);
951 		}
952 		vfs_unrefvfssw(vswp);
953 	}
954 
955 	/*
956 	 * Mount /devices, /dev instance 1, /system/contract, /etc/mnttab,
957 	 * /etc/svc/volatile, /etc/dfs/sharetab, /system/object, and /proc.
958 	 */
959 	vfs_mountdevices();
960 	vfs_mountdev1();
961 
962 	vfs_mountfs("ctfs", "ctfs", CTFS_ROOT);
963 	vfs_mountfs("proc", "/proc", "/proc");
964 	vfs_mountfs("mntfs", "/etc/mnttab", "/etc/mnttab");
965 	vfs_mountfs("tmpfs", "/etc/svc/volatile", "/etc/svc/volatile");
966 	vfs_mountfs("objfs", "objfs", OBJFS_ROOT);
967 	vfs_mountfs("bootfs", "bootfs", "/system/boot");
968 
969 	if (getzoneid() == GLOBAL_ZONEID) {
970 		vfs_mountfs("sharefs", "sharefs", "/etc/dfs/sharetab");
971 	}
972 
973 #ifdef __sparc
974 	/*
975 	 * This bit of magic can go away when we convert sparc to
976 	 * the new boot architecture based on ramdisk.
977 	 *
978 	 * Booting off a mirrored root volume:
979 	 * At this point, we have booted and mounted root on a
980 	 * single component of the mirror.  Complete the boot
981 	 * by configuring SVM and converting the root to the
982 	 * dev_t of the mirrored root device.  This dev_t conversion
983 	 * only works because the underlying device doesn't change.
984 	 */
985 	if (root_is_svm) {
986 		if (svm_rootconf()) {
987 			panic("vfs_mountroot: cannot remount root");
988 		}
989 
990 		/*
991 		 * mnttab should reflect the new root device
992 		 */
993 		vfs_lock_wait(rootvfs);
994 		vfs_setresource(rootvfs, rootfs.bo_name, 0);
995 		vfs_unlock(rootvfs);
996 	}
997 #endif /* __sparc */
998 
999 	if (strcmp(rootfs.bo_fstype, "zfs") != 0) {
1000 		/*
1001 		 * Look up the root device via devfs so that a dv_node is
1002 		 * created for it. The vnode is never VN_RELE()ed.
1003 		 * We allocate more than MAXPATHLEN so that the
1004 		 * buffer passed to i_ddi_prompath_to_devfspath() is
1005 		 * exactly MAXPATHLEN (the function expects a buffer
1006 		 * of that length).
1007 		 */
1008 		plen = strlen("/devices");
1009 		path = kmem_alloc(plen + MAXPATHLEN, KM_SLEEP);
1010 		(void) strcpy(path, "/devices");
1011 
1012 		if (i_ddi_prompath_to_devfspath(rootfs.bo_name, path + plen)
1013 		    != DDI_SUCCESS ||
1014 		    lookupname(path, UIO_SYSSPACE, FOLLOW, NULLVPP, &rvp)) {
1015 
1016 			/* NUL terminate in case "path" has garbage */
1017 			path[plen + MAXPATHLEN - 1] = '\0';
1018 #ifdef	DEBUG
1019 			cmn_err(CE_WARN, "!Cannot lookup root device: %s",
1020 			    path);
1021 #endif
1022 		}
1023 		kmem_free(path, plen + MAXPATHLEN);
1024 	}
1025 
1026 	vfs_mnttabvp_setup();
1027 }
1028 
1029 /*
1030  * Check to see if our "block device" is actually a file.  If so,
1031  * automatically add a lofi device, and keep track of this fact.
1032  */
1033 static int
1034 lofi_add(const char *fsname, struct vfs *vfsp,
1035     mntopts_t *mntopts, struct mounta *uap)
1036 {
1037 	int fromspace = (uap->flags & MS_SYSSPACE) ?
1038 	    UIO_SYSSPACE : UIO_USERSPACE;
1039 	struct lofi_ioctl *li = NULL;
1040 	struct vnode *vp = NULL;
1041 	struct pathname	pn = { NULL };
1042 	ldi_ident_t ldi_id;
1043 	ldi_handle_t ldi_hdl;
1044 	vfssw_t *vfssw;
1045 	int minor;
1046 	int err = 0;
1047 
1048 	if ((vfssw = vfs_getvfssw(fsname)) == NULL)
1049 		return (0);
1050 
1051 	if (!(vfssw->vsw_flag & VSW_CANLOFI)) {
1052 		vfs_unrefvfssw(vfssw);
1053 		return (0);
1054 	}
1055 
1056 	vfs_unrefvfssw(vfssw);
1057 	vfssw = NULL;
1058 
1059 	if (pn_get(uap->spec, fromspace, &pn) != 0)
1060 		return (0);
1061 
1062 	if (lookupname(uap->spec, fromspace, FOLLOW, NULL, &vp) != 0)
1063 		goto out;
1064 
1065 	if (vp->v_type != VREG)
1066 		goto out;
1067 
1068 	/* OK, this is a lofi mount. */
1069 
1070 	if ((uap->flags & (MS_REMOUNT|MS_GLOBAL)) ||
1071 	    vfs_optionisset_nolock(mntopts, MNTOPT_SUID, NULL) ||
1072 	    vfs_optionisset_nolock(mntopts, MNTOPT_SETUID, NULL) ||
1073 	    vfs_optionisset_nolock(mntopts, MNTOPT_DEVICES, NULL)) {
1074 		err = EINVAL;
1075 		goto out;
1076 	}
1077 
1078 	ldi_id = ldi_ident_from_anon();
1079 	li = kmem_zalloc(sizeof (*li), KM_SLEEP);
1080 	(void) strlcpy(li->li_filename, pn.pn_path, MAXPATHLEN);
1081 
1082 	err = ldi_open_by_name("/dev/lofictl", FREAD | FWRITE, kcred,
1083 	    &ldi_hdl, ldi_id);
1084 
1085 	if (err)
1086 		goto out2;
1087 
1088 	err = ldi_ioctl(ldi_hdl, LOFI_MAP_FILE, (intptr_t)li,
1089 	    FREAD | FWRITE | FKIOCTL, kcred, &minor);
1090 
1091 	(void) ldi_close(ldi_hdl, FREAD | FWRITE, kcred);
1092 
1093 	if (!err)
1094 		vfsp->vfs_lofi_minor = minor;
1095 
1096 out2:
1097 	ldi_ident_release(ldi_id);
1098 out:
1099 	if (li != NULL)
1100 		kmem_free(li, sizeof (*li));
1101 	if (vp != NULL)
1102 		VN_RELE(vp);
1103 	pn_free(&pn);
1104 	return (err);
1105 }
1106 
1107 static void
1108 lofi_remove(struct vfs *vfsp)
1109 {
1110 	struct lofi_ioctl *li = NULL;
1111 	ldi_ident_t ldi_id;
1112 	ldi_handle_t ldi_hdl;
1113 	int err;
1114 
1115 	if (vfsp->vfs_lofi_minor == 0)
1116 		return;
1117 
1118 	ldi_id = ldi_ident_from_anon();
1119 
1120 	li = kmem_zalloc(sizeof (*li), KM_SLEEP);
1121 	li->li_minor = vfsp->vfs_lofi_minor;
1122 	li->li_cleanup = B_TRUE;
1123 
1124 	err = ldi_open_by_name("/dev/lofictl", FREAD | FWRITE, kcred,
1125 	    &ldi_hdl, ldi_id);
1126 
1127 	if (err)
1128 		goto out;
1129 
1130 	err = ldi_ioctl(ldi_hdl, LOFI_UNMAP_FILE_MINOR, (intptr_t)li,
1131 	    FREAD | FWRITE | FKIOCTL, kcred, NULL);
1132 
1133 	(void) ldi_close(ldi_hdl, FREAD | FWRITE, kcred);
1134 
1135 	if (!err)
1136 		vfsp->vfs_lofi_minor = 0;
1137 
1138 out:
1139 	ldi_ident_release(ldi_id);
1140 	if (li != NULL)
1141 		kmem_free(li, sizeof (*li));
1142 }
1143 
1144 /*
1145  * Common mount code.  Called from the system call entry point, from autofs,
1146  * nfsv4 trigger mounts, and from pxfs.
1147  *
1148  * Takes the effective file system type, mount arguments, the mount point
1149  * vnode, flags specifying whether the mount is a remount and whether it
1150  * should be entered into the vfs list, and credentials.  Fills in its vfspp
1151  * parameter with the mounted file system instance's vfs.
1152  *
1153  * Note that the effective file system type is specified as a string.  It may
1154  * be null, in which case it's determined from the mount arguments, and may
1155  * differ from the type specified in the mount arguments; this is a hook to
1156  * allow interposition when instantiating file system instances.
1157  *
1158  * The caller is responsible for releasing its own hold on the mount point
1159  * vp (this routine does its own hold when necessary).
1160  * Also note that for remounts, the mount point vp should be the vnode for
1161  * the root of the file system rather than the vnode that the file system
1162  * is mounted on top of.
1163  */
1164 int
1165 domount(char *fsname, struct mounta *uap, vnode_t *vp, struct cred *credp,
1166 	struct vfs **vfspp)
1167 {
1168 	struct vfssw	*vswp;
1169 	vfsops_t	*vfsops;
1170 	struct vfs	*vfsp;
1171 	struct vnode	*bvp;
1172 	dev_t		bdev = 0;
1173 	mntopts_t	mnt_mntopts;
1174 	int		error = 0;
1175 	int		copyout_error = 0;
1176 	int		ovflags;
1177 	char		*opts = uap->optptr;
1178 	char		*inargs = opts;
1179 	int		optlen = uap->optlen;
1180 	int		remount;
1181 	int		rdonly;
1182 	int		nbmand = 0;
1183 	int		delmip = 0;
1184 	int		addmip = 0;
1185 	int		splice = ((uap->flags & MS_NOSPLICE) == 0);
1186 	int		fromspace = (uap->flags & MS_SYSSPACE) ?
1187 	    UIO_SYSSPACE : UIO_USERSPACE;
1188 	char		*resource = NULL, *mountpt = NULL;
1189 	refstr_t	*oldresource, *oldmntpt;
1190 	struct pathname	pn, rpn;
1191 	vsk_anchor_t	*vskap;
1192 	char fstname[FSTYPSZ];
1193 	zone_t		*zone;
1194 
1195 	/*
1196 	 * The v_flag value for the mount point vp is permanently set
1197 	 * to VVFSLOCK so that no one bypasses the vn_vfs*locks routine
1198 	 * for mount point locking.
1199 	 */
1200 	mutex_enter(&vp->v_lock);
1201 	vp->v_flag |= VVFSLOCK;
1202 	mutex_exit(&vp->v_lock);
1203 
1204 	mnt_mntopts.mo_count = 0;
1205 	/*
1206 	 * Find the ops vector to use to invoke the file system-specific mount
1207 	 * method.  If the fsname argument is non-NULL, use it directly.
1208 	 * Otherwise, dig the file system type information out of the mount
1209 	 * arguments.
1210 	 *
1211 	 * A side effect is to hold the vfssw entry.
1212 	 *
1213 	 * Mount arguments can be specified in several ways, which are
1214 	 * distinguished by flag bit settings.  The preferred way is to set
1215 	 * MS_OPTIONSTR, indicating an 8 argument mount with the file system
1216 	 * type supplied as a character string and the last two arguments
1217 	 * being a pointer to a character buffer and the size of the buffer.
1218 	 * On entry, the buffer holds a null terminated list of options; on
1219 	 * return, the string is the list of options the file system
1220 	 * recognized. If MS_DATA is set arguments five and six point to a
1221 	 * block of binary data which the file system interprets.
1222 	 * A further wrinkle is that some callers don't set MS_FSS and MS_DATA
1223 	 * consistently with these conventions.  To handle them, we check to
1224 	 * see whether the pointer to the file system name has a numeric value
1225 	 * less than 256.  If so, we treat it as an index.
1226 	 */
1227 	if (fsname != NULL) {
1228 		if ((vswp = vfs_getvfssw(fsname)) == NULL) {
1229 			return (EINVAL);
1230 		}
1231 	} else if (uap->flags & (MS_OPTIONSTR | MS_DATA | MS_FSS)) {
1232 		size_t n;
1233 		uint_t fstype;
1234 
1235 		fsname = fstname;
1236 
1237 		if ((fstype = (uintptr_t)uap->fstype) < 256) {
1238 			RLOCK_VFSSW();
1239 			if (fstype == 0 || fstype >= nfstype ||
1240 			    !ALLOCATED_VFSSW(&vfssw[fstype])) {
1241 				RUNLOCK_VFSSW();
1242 				return (EINVAL);
1243 			}
1244 			(void) strcpy(fsname, vfssw[fstype].vsw_name);
1245 			RUNLOCK_VFSSW();
1246 			if ((vswp = vfs_getvfssw(fsname)) == NULL)
1247 				return (EINVAL);
1248 		} else {
1249 			/*
1250 			 * Handle either kernel or user address space.
1251 			 */
1252 			if (uap->flags & MS_SYSSPACE) {
1253 				error = copystr(uap->fstype, fsname,
1254 				    FSTYPSZ, &n);
1255 			} else {
1256 				error = copyinstr(uap->fstype, fsname,
1257 				    FSTYPSZ, &n);
1258 			}
1259 			if (error) {
1260 				if (error == ENAMETOOLONG)
1261 					return (EINVAL);
1262 				return (error);
1263 			}
1264 			if ((vswp = vfs_getvfssw(fsname)) == NULL)
1265 				return (EINVAL);
1266 		}
1267 	} else {
1268 		if ((vswp = vfs_getvfsswbyvfsops(vfs_getops(rootvfs))) == NULL)
1269 			return (EINVAL);
1270 		fsname = vswp->vsw_name;
1271 	}
1272 	if (!VFS_INSTALLED(vswp))
1273 		return (EINVAL);
1274 
1275 	if ((error = secpolicy_fs_allowed_mount(fsname)) != 0)  {
1276 		vfs_unrefvfssw(vswp);
1277 		return (error);
1278 	}
1279 
1280 	vfsops = &vswp->vsw_vfsops;
1281 
1282 	vfs_copyopttbl(&vswp->vsw_optproto, &mnt_mntopts);
1283 	/*
1284 	 * Fetch mount options and parse them for generic vfs options
1285 	 */
1286 	if (uap->flags & MS_OPTIONSTR) {
1287 		/*
1288 		 * Limit the buffer size
1289 		 */
1290 		if (optlen < 0 || optlen > MAX_MNTOPT_STR) {
1291 			error = EINVAL;
1292 			goto errout;
1293 		}
1294 		if ((uap->flags & MS_SYSSPACE) == 0) {
1295 			inargs = kmem_alloc(MAX_MNTOPT_STR, KM_SLEEP);
1296 			inargs[0] = '\0';
1297 			if (optlen) {
1298 				error = copyinstr(opts, inargs, (size_t)optlen,
1299 				    NULL);
1300 				if (error) {
1301 					goto errout;
1302 				}
1303 			}
1304 		}
1305 		vfs_parsemntopts(&mnt_mntopts, inargs, 0);
1306 	}
1307 	/*
1308 	 * Flag bits override the options string.
1309 	 */
1310 	if (uap->flags & MS_REMOUNT)
1311 		vfs_setmntopt_nolock(&mnt_mntopts, MNTOPT_REMOUNT, NULL, 0, 0);
1312 	if (uap->flags & MS_RDONLY)
1313 		vfs_setmntopt_nolock(&mnt_mntopts, MNTOPT_RO, NULL, 0, 0);
1314 	if (uap->flags & MS_NOSUID)
1315 		vfs_setmntopt_nolock(&mnt_mntopts, MNTOPT_NOSUID, NULL, 0, 0);
1316 
1317 	/*
1318 	 * Check if this is a remount; must be set in the option string and
1319 	 * the file system must support a remount option.
1320 	 */
1321 	if (remount = vfs_optionisset_nolock(&mnt_mntopts,
1322 	    MNTOPT_REMOUNT, NULL)) {
1323 		if (!(vswp->vsw_flag & VSW_CANREMOUNT)) {
1324 			error = ENOTSUP;
1325 			goto errout;
1326 		}
1327 		uap->flags |= MS_REMOUNT;
1328 	}
1329 
1330 	/*
1331 	 * uap->flags and vfs_optionisset() should agree.
1332 	 */
1333 	if (rdonly = vfs_optionisset_nolock(&mnt_mntopts, MNTOPT_RO, NULL)) {
1334 		uap->flags |= MS_RDONLY;
1335 	}
1336 	if (vfs_optionisset_nolock(&mnt_mntopts, MNTOPT_NOSUID, NULL)) {
1337 		uap->flags |= MS_NOSUID;
1338 	}
1339 	nbmand = vfs_optionisset_nolock(&mnt_mntopts, MNTOPT_NBMAND, NULL);
1340 	ASSERT(splice || !remount);
1341 	/*
1342 	 * If we are splicing the fs into the namespace,
1343 	 * perform mount point checks.
1344 	 *
1345 	 * We want to resolve the path for the mount point to eliminate
1346 	 * '.' and ".." and symlinks in mount points; we can't do the
1347 	 * same for the resource string, since it would turn
1348 	 * "/dev/dsk/c0t0d0s0" into "/devices/pci@...".  We need to do
1349 	 * this before grabbing vn_vfswlock(), because otherwise we
1350 	 * would deadlock with lookuppn().
1351 	 */
1352 	if (splice) {
1353 		ASSERT(vp->v_count > 0);
1354 
1355 		/*
1356 		 * Pick up mount point and device from appropriate space.
1357 		 */
1358 		if (pn_get(uap->spec, fromspace, &pn) == 0) {
1359 			resource = kmem_alloc(pn.pn_pathlen + 1,
1360 			    KM_SLEEP);
1361 			(void) strcpy(resource, pn.pn_path);
1362 			pn_free(&pn);
1363 		}
1364 		/*
1365 		 * Do a lookupname prior to taking the
1366 		 * writelock. Mark this as completed if
1367 		 * successful for later cleanup and addition to
1368 		 * the mount in progress table.
1369 		 */
1370 		if ((uap->flags & MS_GLOBAL) == 0 &&
1371 		    lookupname(uap->spec, fromspace,
1372 		    FOLLOW, NULL, &bvp) == 0) {
1373 			addmip = 1;
1374 		}
1375 
1376 		if ((error = pn_get(uap->dir, fromspace, &pn)) == 0) {
1377 			pathname_t *pnp;
1378 
1379 			if (*pn.pn_path != '/') {
1380 				error = EINVAL;
1381 				pn_free(&pn);
1382 				goto errout;
1383 			}
1384 			pn_alloc(&rpn);
1385 			/*
1386 			 * Kludge to prevent autofs from deadlocking with
1387 			 * itself when it calls domount().
1388 			 *
1389 			 * If autofs is calling, it is because it is doing
1390 			 * (autofs) mounts in the process of an NFS mount.  A
1391 			 * lookuppn() here would cause us to block waiting for
1392 			 * said NFS mount to complete, which can't since this
1393 			 * is the thread that was supposed to doing it.
1394 			 */
1395 			if (fromspace == UIO_USERSPACE) {
1396 				if ((error = lookuppn(&pn, &rpn, FOLLOW, NULL,
1397 				    NULL)) == 0) {
1398 					pnp = &rpn;
1399 				} else {
1400 					/*
1401 					 * The file disappeared or otherwise
1402 					 * became inaccessible since we opened
1403 					 * it; might as well fail the mount
1404 					 * since the mount point is no longer
1405 					 * accessible.
1406 					 */
1407 					pn_free(&rpn);
1408 					pn_free(&pn);
1409 					goto errout;
1410 				}
1411 			} else {
1412 				pnp = &pn;
1413 			}
1414 			mountpt = kmem_alloc(pnp->pn_pathlen + 1, KM_SLEEP);
1415 			(void) strcpy(mountpt, pnp->pn_path);
1416 
1417 			/*
1418 			 * If the addition of the zone's rootpath
1419 			 * would push us over a total path length
1420 			 * of MAXPATHLEN, we fail the mount with
1421 			 * ENAMETOOLONG, which is what we would have
1422 			 * gotten if we were trying to perform the same
1423 			 * mount in the global zone.
1424 			 *
1425 			 * strlen() doesn't count the trailing
1426 			 * '\0', but zone_rootpathlen counts both a
1427 			 * trailing '/' and the terminating '\0'.
1428 			 */
1429 			if ((curproc->p_zone->zone_rootpathlen - 1 +
1430 			    strlen(mountpt)) > MAXPATHLEN ||
1431 			    (resource != NULL &&
1432 			    (curproc->p_zone->zone_rootpathlen - 1 +
1433 			    strlen(resource)) > MAXPATHLEN)) {
1434 				error = ENAMETOOLONG;
1435 			}
1436 
1437 			pn_free(&rpn);
1438 			pn_free(&pn);
1439 		}
1440 
1441 		if (error)
1442 			goto errout;
1443 
1444 		/*
1445 		 * Prevent path name resolution from proceeding past
1446 		 * the mount point.
1447 		 */
1448 		if (vn_vfswlock(vp) != 0) {
1449 			error = EBUSY;
1450 			goto errout;
1451 		}
1452 
1453 		/*
1454 		 * Verify that it's legitimate to establish a mount on
1455 		 * the prospective mount point.
1456 		 */
1457 		if (vn_mountedvfs(vp) != NULL) {
1458 			/*
1459 			 * The mount point lock was obtained after some
1460 			 * other thread raced through and established a mount.
1461 			 */
1462 			vn_vfsunlock(vp);
1463 			error = EBUSY;
1464 			goto errout;
1465 		}
1466 		if (vp->v_flag & VNOMOUNT) {
1467 			vn_vfsunlock(vp);
1468 			error = EINVAL;
1469 			goto errout;
1470 		}
1471 	}
1472 	if ((uap->flags & (MS_DATA | MS_OPTIONSTR)) == 0) {
1473 		uap->dataptr = NULL;
1474 		uap->datalen = 0;
1475 	}
1476 
1477 	/*
1478 	 * If this is a remount, we don't want to create a new VFS.
1479 	 * Instead, we pass the existing one with a remount flag.
1480 	 */
1481 	if (remount) {
1482 		/*
1483 		 * Confirm that the mount point is the root vnode of the
1484 		 * file system that is being remounted.
1485 		 * This can happen if the user specifies a different
1486 		 * mount point directory pathname in the (re)mount command.
1487 		 *
1488 		 * Code below can only be reached if splice is true, so it's
1489 		 * safe to do vn_vfsunlock() here.
1490 		 */
1491 		if ((vp->v_flag & VROOT) == 0) {
1492 			vn_vfsunlock(vp);
1493 			error = ENOENT;
1494 			goto errout;
1495 		}
1496 		/*
1497 		 * Disallow making file systems read-only unless file system
1498 		 * explicitly allows it in its vfssw.  Ignore other flags.
1499 		 */
1500 		if (rdonly && vn_is_readonly(vp) == 0 &&
1501 		    (vswp->vsw_flag & VSW_CANRWRO) == 0) {
1502 			vn_vfsunlock(vp);
1503 			error = EINVAL;
1504 			goto errout;
1505 		}
1506 		/*
1507 		 * Disallow changing the NBMAND disposition of the file
1508 		 * system on remounts.
1509 		 */
1510 		if ((nbmand && ((vp->v_vfsp->vfs_flag & VFS_NBMAND) == 0)) ||
1511 		    (!nbmand && (vp->v_vfsp->vfs_flag & VFS_NBMAND))) {
1512 			vn_vfsunlock(vp);
1513 			error = EINVAL;
1514 			goto errout;
1515 		}
1516 		vfsp = vp->v_vfsp;
1517 		ovflags = vfsp->vfs_flag;
1518 		vfsp->vfs_flag |= VFS_REMOUNT;
1519 		vfsp->vfs_flag &= ~VFS_RDONLY;
1520 	} else {
1521 		vfsp = vfs_alloc(KM_SLEEP);
1522 		VFS_INIT(vfsp, vfsops, NULL);
1523 	}
1524 
1525 	VFS_HOLD(vfsp);
1526 
1527 	if ((error = lofi_add(fsname, vfsp, &mnt_mntopts, uap)) != 0) {
1528 		if (!remount) {
1529 			if (splice)
1530 				vn_vfsunlock(vp);
1531 			vfs_free(vfsp);
1532 		} else {
1533 			vn_vfsunlock(vp);
1534 			VFS_RELE(vfsp);
1535 		}
1536 		goto errout;
1537 	}
1538 
1539 	/*
1540 	 * PRIV_SYS_MOUNT doesn't mean you can become root.
1541 	 */
1542 	if (vfsp->vfs_lofi_minor != 0) {
1543 		uap->flags |= MS_NOSUID;
1544 		vfs_setmntopt_nolock(&mnt_mntopts, MNTOPT_NOSUID, NULL, 0, 0);
1545 	}
1546 
1547 	/*
1548 	 * The vfs_reflock is not used anymore the code below explicitly
1549 	 * holds it preventing others accesing it directly.
1550 	 */
1551 	if ((sema_tryp(&vfsp->vfs_reflock) == 0) &&
1552 	    !(vfsp->vfs_flag & VFS_REMOUNT))
1553 		cmn_err(CE_WARN,
1554 		    "mount type %s couldn't get vfs_reflock", vswp->vsw_name);
1555 
1556 	/*
1557 	 * Lock the vfs. If this is a remount we want to avoid spurious umount
1558 	 * failures that happen as a side-effect of fsflush() and other mount
1559 	 * and unmount operations that might be going on simultaneously and
1560 	 * may have locked the vfs currently. To not return EBUSY immediately
1561 	 * here we use vfs_lock_wait() instead vfs_lock() for the remount case.
1562 	 */
1563 	if (!remount) {
1564 		if (error = vfs_lock(vfsp)) {
1565 			vfsp->vfs_flag = ovflags;
1566 
1567 			lofi_remove(vfsp);
1568 
1569 			if (splice)
1570 				vn_vfsunlock(vp);
1571 			vfs_free(vfsp);
1572 			goto errout;
1573 		}
1574 	} else {
1575 		vfs_lock_wait(vfsp);
1576 	}
1577 
1578 	/*
1579 	 * Add device to mount in progress table, global mounts require special
1580 	 * handling. It is possible that we have already done the lookupname
1581 	 * on a spliced, non-global fs. If so, we don't want to do it again
1582 	 * since we cannot do a lookupname after taking the
1583 	 * wlock above. This case is for a non-spliced, non-global filesystem.
1584 	 */
1585 	if (!addmip) {
1586 		if ((uap->flags & MS_GLOBAL) == 0 &&
1587 		    lookupname(uap->spec, fromspace, FOLLOW, NULL, &bvp) == 0) {
1588 			addmip = 1;
1589 		}
1590 	}
1591 
1592 	if (addmip) {
1593 		vnode_t *lvp = NULL;
1594 
1595 		error = vfs_get_lofi(vfsp, &lvp);
1596 		if (error > 0) {
1597 			lofi_remove(vfsp);
1598 
1599 			if (splice)
1600 				vn_vfsunlock(vp);
1601 			vfs_unlock(vfsp);
1602 
1603 			if (remount) {
1604 				VFS_RELE(vfsp);
1605 			} else {
1606 				vfs_free(vfsp);
1607 			}
1608 
1609 			goto errout;
1610 		} else if (error == -1) {
1611 			bdev = bvp->v_rdev;
1612 			VN_RELE(bvp);
1613 		} else {
1614 			bdev = lvp->v_rdev;
1615 			VN_RELE(lvp);
1616 			VN_RELE(bvp);
1617 		}
1618 
1619 		vfs_addmip(bdev, vfsp);
1620 		addmip = 0;
1621 		delmip = 1;
1622 	}
1623 	/*
1624 	 * Invalidate cached entry for the mount point.
1625 	 */
1626 	if (splice)
1627 		dnlc_purge_vp(vp);
1628 
1629 	/*
1630 	 * If have an option string but the filesystem doesn't supply a
1631 	 * prototype options table, create a table with the global
1632 	 * options and sufficient room to accept all the options in the
1633 	 * string.  Then parse the passed in option string
1634 	 * accepting all the options in the string.  This gives us an
1635 	 * option table with all the proper cancel properties for the
1636 	 * global options.
1637 	 *
1638 	 * Filesystems that supply a prototype options table are handled
1639 	 * earlier in this function.
1640 	 */
1641 	if (uap->flags & MS_OPTIONSTR) {
1642 		if (!(vswp->vsw_flag & VSW_HASPROTO)) {
1643 			mntopts_t tmp_mntopts;
1644 
1645 			tmp_mntopts.mo_count = 0;
1646 			vfs_createopttbl_extend(&tmp_mntopts, inargs,
1647 			    &mnt_mntopts);
1648 			vfs_parsemntopts(&tmp_mntopts, inargs, 1);
1649 			vfs_swapopttbl_nolock(&mnt_mntopts, &tmp_mntopts);
1650 			vfs_freeopttbl(&tmp_mntopts);
1651 		}
1652 	}
1653 
1654 	/*
1655 	 * Serialize with zone state transitions.
1656 	 * See vfs_list_add; zone mounted into is:
1657 	 * 	zone_find_by_path(refstr_value(vfsp->vfs_mntpt))
1658 	 * not the zone doing the mount (curproc->p_zone), but if we're already
1659 	 * inside a NGZ, then we know what zone we are.
1660 	 */
1661 	if (INGLOBALZONE(curproc)) {
1662 		zone = zone_find_by_path(mountpt);
1663 		ASSERT(zone != NULL);
1664 	} else {
1665 		zone = curproc->p_zone;
1666 		/*
1667 		 * zone_find_by_path does a hold, so do one here too so that
1668 		 * we can do a zone_rele after mount_completed.
1669 		 */
1670 		zone_hold(zone);
1671 	}
1672 	mount_in_progress(zone);
1673 	/*
1674 	 * Instantiate (or reinstantiate) the file system.  If appropriate,
1675 	 * splice it into the file system name space.
1676 	 *
1677 	 * We want VFS_MOUNT() to be able to override the vfs_resource
1678 	 * string if necessary (ie, mntfs), and also for a remount to
1679 	 * change the same (necessary when remounting '/' during boot).
1680 	 * So we set up vfs_mntpt and vfs_resource to what we think they
1681 	 * should be, then hand off control to VFS_MOUNT() which can
1682 	 * override this.
1683 	 *
1684 	 * For safety's sake, when changing vfs_resource or vfs_mntpt of
1685 	 * a vfs which is on the vfs list (i.e. during a remount), we must
1686 	 * never set those fields to NULL. Several bits of code make
1687 	 * assumptions that the fields are always valid.
1688 	 */
1689 	vfs_swapopttbl(&mnt_mntopts, &vfsp->vfs_mntopts);
1690 	if (remount) {
1691 		if ((oldresource = vfsp->vfs_resource) != NULL)
1692 			refstr_hold(oldresource);
1693 		if ((oldmntpt = vfsp->vfs_mntpt) != NULL)
1694 			refstr_hold(oldmntpt);
1695 	}
1696 	vfs_setresource(vfsp, resource, 0);
1697 	vfs_setmntpoint(vfsp, mountpt, 0);
1698 
1699 	/*
1700 	 * going to mount on this vnode, so notify.
1701 	 */
1702 	vnevent_mountedover(vp, NULL);
1703 	error = VFS_MOUNT(vfsp, vp, uap, credp);
1704 
1705 	if (uap->flags & MS_RDONLY)
1706 		vfs_setmntopt(vfsp, MNTOPT_RO, NULL, 0);
1707 	if (uap->flags & MS_NOSUID)
1708 		vfs_setmntopt(vfsp, MNTOPT_NOSUID, NULL, 0);
1709 	if (uap->flags & MS_GLOBAL)
1710 		vfs_setmntopt(vfsp, MNTOPT_GLOBAL, NULL, 0);
1711 
1712 	if (error) {
1713 		lofi_remove(vfsp);
1714 
1715 		if (remount) {
1716 			/* put back pre-remount options */
1717 			vfs_swapopttbl(&mnt_mntopts, &vfsp->vfs_mntopts);
1718 			vfs_setmntpoint(vfsp, refstr_value(oldmntpt),
1719 			    VFSSP_VERBATIM);
1720 			if (oldmntpt)
1721 				refstr_rele(oldmntpt);
1722 			vfs_setresource(vfsp, refstr_value(oldresource),
1723 			    VFSSP_VERBATIM);
1724 			if (oldresource)
1725 				refstr_rele(oldresource);
1726 			vfsp->vfs_flag = ovflags;
1727 			vfs_unlock(vfsp);
1728 			VFS_RELE(vfsp);
1729 		} else {
1730 			vfs_unlock(vfsp);
1731 			vfs_freemnttab(vfsp);
1732 			vfs_free(vfsp);
1733 		}
1734 	} else {
1735 		/*
1736 		 * Set the mount time to now
1737 		 */
1738 		vfsp->vfs_mtime = ddi_get_time();
1739 		if (remount) {
1740 			vfsp->vfs_flag &= ~VFS_REMOUNT;
1741 			if (oldresource)
1742 				refstr_rele(oldresource);
1743 			if (oldmntpt)
1744 				refstr_rele(oldmntpt);
1745 		} else if (splice) {
1746 			/*
1747 			 * Link vfsp into the name space at the mount
1748 			 * point. Vfs_add() is responsible for
1749 			 * holding the mount point which will be
1750 			 * released when vfs_remove() is called.
1751 			 */
1752 			vfs_add(vp, vfsp, uap->flags);
1753 		} else {
1754 			/*
1755 			 * Hold the reference to file system which is
1756 			 * not linked into the name space.
1757 			 */
1758 			vfsp->vfs_zone = NULL;
1759 			VFS_HOLD(vfsp);
1760 			vfsp->vfs_vnodecovered = NULL;
1761 		}
1762 		/*
1763 		 * Set flags for global options encountered
1764 		 */
1765 		if (vfs_optionisset(vfsp, MNTOPT_RO, NULL))
1766 			vfsp->vfs_flag |= VFS_RDONLY;
1767 		else
1768 			vfsp->vfs_flag &= ~VFS_RDONLY;
1769 		if (vfs_optionisset(vfsp, MNTOPT_NOSUID, NULL)) {
1770 			vfsp->vfs_flag |= (VFS_NOSETUID|VFS_NODEVICES);
1771 		} else {
1772 			if (vfs_optionisset(vfsp, MNTOPT_NODEVICES, NULL))
1773 				vfsp->vfs_flag |= VFS_NODEVICES;
1774 			else
1775 				vfsp->vfs_flag &= ~VFS_NODEVICES;
1776 			if (vfs_optionisset(vfsp, MNTOPT_NOSETUID, NULL))
1777 				vfsp->vfs_flag |= VFS_NOSETUID;
1778 			else
1779 				vfsp->vfs_flag &= ~VFS_NOSETUID;
1780 		}
1781 		if (vfs_optionisset(vfsp, MNTOPT_NBMAND, NULL))
1782 			vfsp->vfs_flag |= VFS_NBMAND;
1783 		else
1784 			vfsp->vfs_flag &= ~VFS_NBMAND;
1785 
1786 		if (vfs_optionisset(vfsp, MNTOPT_XATTR, NULL))
1787 			vfsp->vfs_flag |= VFS_XATTR;
1788 		else
1789 			vfsp->vfs_flag &= ~VFS_XATTR;
1790 
1791 		if (vfs_optionisset(vfsp, MNTOPT_NOEXEC, NULL))
1792 			vfsp->vfs_flag |= VFS_NOEXEC;
1793 		else
1794 			vfsp->vfs_flag &= ~VFS_NOEXEC;
1795 
1796 		/*
1797 		 * Now construct the output option string of options
1798 		 * we recognized.
1799 		 */
1800 		if (uap->flags & MS_OPTIONSTR) {
1801 			vfs_list_read_lock();
1802 			copyout_error = vfs_buildoptionstr(
1803 			    &vfsp->vfs_mntopts, inargs, optlen);
1804 			vfs_list_unlock();
1805 			if (copyout_error == 0 &&
1806 			    (uap->flags & MS_SYSSPACE) == 0) {
1807 				copyout_error = copyoutstr(inargs, opts,
1808 				    optlen, NULL);
1809 			}
1810 		}
1811 
1812 		/*
1813 		 * If this isn't a remount, set up the vopstats before
1814 		 * anyone can touch this. We only allow spliced file
1815 		 * systems (file systems which are in the namespace) to
1816 		 * have the VFS_STATS flag set.
1817 		 * NOTE: PxFS mounts the underlying file system with
1818 		 * MS_NOSPLICE set and copies those vfs_flags to its private
1819 		 * vfs structure. As a result, PxFS should never have
1820 		 * the VFS_STATS flag or else we might access the vfs
1821 		 * statistics-related fields prior to them being
1822 		 * properly initialized.
1823 		 */
1824 		if (!remount && (vswp->vsw_flag & VSW_STATS) && splice) {
1825 			initialize_vopstats(&vfsp->vfs_vopstats);
1826 			/*
1827 			 * We need to set vfs_vskap to NULL because there's
1828 			 * a chance it won't be set below.  This is checked
1829 			 * in teardown_vopstats() so we can't have garbage.
1830 			 */
1831 			vfsp->vfs_vskap = NULL;
1832 			vfsp->vfs_flag |= VFS_STATS;
1833 			vfsp->vfs_fstypevsp = get_fstype_vopstats(vfsp, vswp);
1834 		}
1835 
1836 		if (vswp->vsw_flag & VSW_XID)
1837 			vfsp->vfs_flag |= VFS_XID;
1838 
1839 		vfs_unlock(vfsp);
1840 	}
1841 	mount_completed(zone);
1842 	zone_rele(zone);
1843 	if (splice)
1844 		vn_vfsunlock(vp);
1845 
1846 	if ((error == 0) && (copyout_error == 0)) {
1847 		if (!remount) {
1848 			/*
1849 			 * Don't call get_vskstat_anchor() while holding
1850 			 * locks since it allocates memory and calls
1851 			 * VFS_STATVFS().  For NFS, the latter can generate
1852 			 * an over-the-wire call.
1853 			 */
1854 			vskap = get_vskstat_anchor(vfsp);
1855 			/* Only take the lock if we have something to do */
1856 			if (vskap != NULL) {
1857 				vfs_lock_wait(vfsp);
1858 				if (vfsp->vfs_flag & VFS_STATS) {
1859 					vfsp->vfs_vskap = vskap;
1860 				}
1861 				vfs_unlock(vfsp);
1862 			}
1863 		}
1864 		/* Return vfsp to caller. */
1865 		*vfspp = vfsp;
1866 	}
1867 errout:
1868 	vfs_freeopttbl(&mnt_mntopts);
1869 	if (resource != NULL)
1870 		kmem_free(resource, strlen(resource) + 1);
1871 	if (mountpt != NULL)
1872 		kmem_free(mountpt, strlen(mountpt) + 1);
1873 	/*
1874 	 * It is possible we errored prior to adding to mount in progress
1875 	 * table. Must free vnode we acquired with successful lookupname.
1876 	 */
1877 	if (addmip)
1878 		VN_RELE(bvp);
1879 	if (delmip)
1880 		vfs_delmip(vfsp);
1881 	ASSERT(vswp != NULL);
1882 	vfs_unrefvfssw(vswp);
1883 	if (inargs != opts)
1884 		kmem_free(inargs, MAX_MNTOPT_STR);
1885 	if (copyout_error) {
1886 		lofi_remove(vfsp);
1887 		VFS_RELE(vfsp);
1888 		error = copyout_error;
1889 	}
1890 	return (error);
1891 }
1892 
1893 static void
1894 vfs_setpath(
1895     struct vfs *vfsp,		/* vfs being updated */
1896     refstr_t **refp,		/* Ref-count string to contain the new path */
1897     const char *newpath,	/* Path to add to refp (above) */
1898     uint32_t flag)		/* flag */
1899 {
1900 	size_t len;
1901 	refstr_t *ref;
1902 	zone_t *zone = curproc->p_zone;
1903 	char *sp;
1904 	int have_list_lock = 0;
1905 
1906 	ASSERT(!VFS_ON_LIST(vfsp) || vfs_lock_held(vfsp));
1907 
1908 	/*
1909 	 * New path must be less than MAXPATHLEN because mntfs
1910 	 * will only display up to MAXPATHLEN bytes. This is currently
1911 	 * safe, because domount() uses pn_get(), and other callers
1912 	 * similarly cap the size to fewer than MAXPATHLEN bytes.
1913 	 */
1914 
1915 	ASSERT(strlen(newpath) < MAXPATHLEN);
1916 
1917 	/* mntfs requires consistency while vfs list lock is held */
1918 
1919 	if (VFS_ON_LIST(vfsp)) {
1920 		have_list_lock = 1;
1921 		vfs_list_lock();
1922 	}
1923 
1924 	if (*refp != NULL)
1925 		refstr_rele(*refp);
1926 
1927 	/*
1928 	 * If we are in a non-global zone then we prefix the supplied path,
1929 	 * newpath, with the zone's root path, with two exceptions. The first
1930 	 * is where we have been explicitly directed to avoid doing so; this
1931 	 * will be the case following a failed remount, where the path supplied
1932 	 * will be a saved version which must now be restored. The second
1933 	 * exception is where newpath is not a pathname but a descriptive name,
1934 	 * e.g. "procfs".
1935 	 */
1936 	if (zone == global_zone || (flag & VFSSP_VERBATIM) || *newpath != '/') {
1937 		ref = refstr_alloc(newpath);
1938 		goto out;
1939 	}
1940 
1941 	/*
1942 	 * Truncate the trailing '/' in the zoneroot, and merge
1943 	 * in the zone's rootpath with the "newpath" (resource
1944 	 * or mountpoint) passed in.
1945 	 *
1946 	 * The size of the required buffer is thus the size of
1947 	 * the buffer required for the passed-in newpath
1948 	 * (strlen(newpath) + 1), plus the size of the buffer
1949 	 * required to hold zone_rootpath (zone_rootpathlen)
1950 	 * minus one for one of the now-superfluous NUL
1951 	 * terminations, minus one for the trailing '/'.
1952 	 *
1953 	 * That gives us:
1954 	 *
1955 	 * (strlen(newpath) + 1) + zone_rootpathlen - 1 - 1
1956 	 *
1957 	 * Which is what we have below.
1958 	 */
1959 
1960 	len = strlen(newpath) + zone->zone_rootpathlen - 1;
1961 	sp = kmem_alloc(len, KM_SLEEP);
1962 
1963 	/*
1964 	 * Copy everything including the trailing slash, which
1965 	 * we then overwrite with the NUL character.
1966 	 */
1967 
1968 	(void) strcpy(sp, zone->zone_rootpath);
1969 	sp[zone->zone_rootpathlen - 2] = '\0';
1970 	(void) strcat(sp, newpath);
1971 
1972 	ref = refstr_alloc(sp);
1973 	kmem_free(sp, len);
1974 out:
1975 	*refp = ref;
1976 
1977 	if (have_list_lock) {
1978 		vfs_mnttab_modtimeupd();
1979 		vfs_list_unlock();
1980 	}
1981 }
1982 
1983 /*
1984  * Record a mounted resource name in a vfs structure.
1985  * If vfsp is already mounted, caller must hold the vfs lock.
1986  */
1987 void
1988 vfs_setresource(struct vfs *vfsp, const char *resource, uint32_t flag)
1989 {
1990 	if (resource == NULL || resource[0] == '\0')
1991 		resource = VFS_NORESOURCE;
1992 	vfs_setpath(vfsp, &vfsp->vfs_resource, resource, flag);
1993 }
1994 
1995 /*
1996  * Record a mount point name in a vfs structure.
1997  * If vfsp is already mounted, caller must hold the vfs lock.
1998  */
1999 void
2000 vfs_setmntpoint(struct vfs *vfsp, const char *mntpt, uint32_t flag)
2001 {
2002 	if (mntpt == NULL || mntpt[0] == '\0')
2003 		mntpt = VFS_NOMNTPT;
2004 	vfs_setpath(vfsp, &vfsp->vfs_mntpt, mntpt, flag);
2005 }
2006 
2007 /* Returns the vfs_resource. Caller must call refstr_rele() when finished. */
2008 
2009 refstr_t *
2010 vfs_getresource(const struct vfs *vfsp)
2011 {
2012 	refstr_t *resource;
2013 
2014 	vfs_list_read_lock();
2015 	resource = vfsp->vfs_resource;
2016 	refstr_hold(resource);
2017 	vfs_list_unlock();
2018 
2019 	return (resource);
2020 }
2021 
2022 /* Returns the vfs_mntpt. Caller must call refstr_rele() when finished. */
2023 
2024 refstr_t *
2025 vfs_getmntpoint(const struct vfs *vfsp)
2026 {
2027 	refstr_t *mntpt;
2028 
2029 	vfs_list_read_lock();
2030 	mntpt = vfsp->vfs_mntpt;
2031 	refstr_hold(mntpt);
2032 	vfs_list_unlock();
2033 
2034 	return (mntpt);
2035 }
2036 
2037 /*
2038  * Create an empty options table with enough empty slots to hold all
2039  * The options in the options string passed as an argument.
2040  * Potentially prepend another options table.
2041  *
2042  * Note: caller is responsible for locking the vfs list, if needed,
2043  *       to protect mops.
2044  */
2045 static void
2046 vfs_createopttbl_extend(mntopts_t *mops, const char *opts,
2047     const mntopts_t *mtmpl)
2048 {
2049 	const char *s = opts;
2050 	uint_t count;
2051 
2052 	if (opts == NULL || *opts == '\0') {
2053 		count = 0;
2054 	} else {
2055 		count = 1;
2056 
2057 		/*
2058 		 * Count number of options in the string
2059 		 */
2060 		for (s = strchr(s, ','); s != NULL; s = strchr(s, ',')) {
2061 			count++;
2062 			s++;
2063 		}
2064 	}
2065 	vfs_copyopttbl_extend(mtmpl, mops, count);
2066 }
2067 
2068 /*
2069  * Create an empty options table with enough empty slots to hold all
2070  * The options in the options string passed as an argument.
2071  *
2072  * This function is *not* for general use by filesystems.
2073  *
2074  * Note: caller is responsible for locking the vfs list, if needed,
2075  *       to protect mops.
2076  */
2077 void
2078 vfs_createopttbl(mntopts_t *mops, const char *opts)
2079 {
2080 	vfs_createopttbl_extend(mops, opts, NULL);
2081 }
2082 
2083 
2084 /*
2085  * Swap two mount options tables
2086  */
2087 static void
2088 vfs_swapopttbl_nolock(mntopts_t *optbl1, mntopts_t *optbl2)
2089 {
2090 	uint_t tmpcnt;
2091 	mntopt_t *tmplist;
2092 
2093 	tmpcnt = optbl2->mo_count;
2094 	tmplist = optbl2->mo_list;
2095 	optbl2->mo_count = optbl1->mo_count;
2096 	optbl2->mo_list = optbl1->mo_list;
2097 	optbl1->mo_count = tmpcnt;
2098 	optbl1->mo_list = tmplist;
2099 }
2100 
2101 static void
2102 vfs_swapopttbl(mntopts_t *optbl1, mntopts_t *optbl2)
2103 {
2104 	vfs_list_lock();
2105 	vfs_swapopttbl_nolock(optbl1, optbl2);
2106 	vfs_mnttab_modtimeupd();
2107 	vfs_list_unlock();
2108 }
2109 
2110 static char **
2111 vfs_copycancelopt_extend(char **const moc, int extend)
2112 {
2113 	int i = 0;
2114 	int j;
2115 	char **result;
2116 
2117 	if (moc != NULL) {
2118 		for (; moc[i] != NULL; i++)
2119 			/* count number of options to cancel */;
2120 	}
2121 
2122 	if (i + extend == 0)
2123 		return (NULL);
2124 
2125 	result = kmem_alloc((i + extend + 1) * sizeof (char *), KM_SLEEP);
2126 
2127 	for (j = 0; j < i; j++) {
2128 		result[j] = kmem_alloc(strlen(moc[j]) + 1, KM_SLEEP);
2129 		(void) strcpy(result[j], moc[j]);
2130 	}
2131 	for (; j <= i + extend; j++)
2132 		result[j] = NULL;
2133 
2134 	return (result);
2135 }
2136 
2137 static void
2138 vfs_copyopt(const mntopt_t *s, mntopt_t *d)
2139 {
2140 	char *sp, *dp;
2141 
2142 	d->mo_flags = s->mo_flags;
2143 	d->mo_data = s->mo_data;
2144 	sp = s->mo_name;
2145 	if (sp != NULL) {
2146 		dp = kmem_alloc(strlen(sp) + 1, KM_SLEEP);
2147 		(void) strcpy(dp, sp);
2148 		d->mo_name = dp;
2149 	} else {
2150 		d->mo_name = NULL; /* should never happen */
2151 	}
2152 
2153 	d->mo_cancel = vfs_copycancelopt_extend(s->mo_cancel, 0);
2154 
2155 	sp = s->mo_arg;
2156 	if (sp != NULL) {
2157 		dp = kmem_alloc(strlen(sp) + 1, KM_SLEEP);
2158 		(void) strcpy(dp, sp);
2159 		d->mo_arg = dp;
2160 	} else {
2161 		d->mo_arg = NULL;
2162 	}
2163 }
2164 
2165 /*
2166  * Copy a mount options table, possibly allocating some spare
2167  * slots at the end.  It is permissible to copy_extend the NULL table.
2168  */
2169 static void
2170 vfs_copyopttbl_extend(const mntopts_t *smo, mntopts_t *dmo, int extra)
2171 {
2172 	uint_t i, count;
2173 	mntopt_t *motbl;
2174 
2175 	/*
2176 	 * Clear out any existing stuff in the options table being initialized
2177 	 */
2178 	vfs_freeopttbl(dmo);
2179 	count = (smo == NULL) ? 0 : smo->mo_count;
2180 	if ((count + extra) == 0)	/* nothing to do */
2181 		return;
2182 	dmo->mo_count = count + extra;
2183 	motbl = kmem_zalloc((count + extra) * sizeof (mntopt_t), KM_SLEEP);
2184 	dmo->mo_list = motbl;
2185 	for (i = 0; i < count; i++) {
2186 		vfs_copyopt(&smo->mo_list[i], &motbl[i]);
2187 	}
2188 	for (i = count; i < count + extra; i++) {
2189 		motbl[i].mo_flags = MO_EMPTY;
2190 	}
2191 }
2192 
2193 /*
2194  * Copy a mount options table.
2195  *
2196  * This function is *not* for general use by filesystems.
2197  *
2198  * Note: caller is responsible for locking the vfs list, if needed,
2199  *       to protect smo and dmo.
2200  */
2201 void
2202 vfs_copyopttbl(const mntopts_t *smo, mntopts_t *dmo)
2203 {
2204 	vfs_copyopttbl_extend(smo, dmo, 0);
2205 }
2206 
2207 static char **
2208 vfs_mergecancelopts(const mntopt_t *mop1, const mntopt_t *mop2)
2209 {
2210 	int c1 = 0;
2211 	int c2 = 0;
2212 	char **result;
2213 	char **sp1, **sp2, **dp;
2214 
2215 	/*
2216 	 * First we count both lists of cancel options.
2217 	 * If either is NULL or has no elements, we return a copy of
2218 	 * the other.
2219 	 */
2220 	if (mop1->mo_cancel != NULL) {
2221 		for (; mop1->mo_cancel[c1] != NULL; c1++)
2222 			/* count cancel options in mop1 */;
2223 	}
2224 
2225 	if (c1 == 0)
2226 		return (vfs_copycancelopt_extend(mop2->mo_cancel, 0));
2227 
2228 	if (mop2->mo_cancel != NULL) {
2229 		for (; mop2->mo_cancel[c2] != NULL; c2++)
2230 			/* count cancel options in mop2 */;
2231 	}
2232 
2233 	result = vfs_copycancelopt_extend(mop1->mo_cancel, c2);
2234 
2235 	if (c2 == 0)
2236 		return (result);
2237 
2238 	/*
2239 	 * When we get here, we've got two sets of cancel options;
2240 	 * we need to merge the two sets.  We know that the result
2241 	 * array has "c1+c2+1" entries and in the end we might shrink
2242 	 * it.
2243 	 * Result now has a copy of the c1 entries from mop1; we'll
2244 	 * now lookup all the entries of mop2 in mop1 and copy it if
2245 	 * it is unique.
2246 	 * This operation is O(n^2) but it's only called once per
2247 	 * filesystem per duplicate option.  This is a situation
2248 	 * which doesn't arise with the filesystems in ON and
2249 	 * n is generally 1.
2250 	 */
2251 
2252 	dp = &result[c1];
2253 	for (sp2 = mop2->mo_cancel; *sp2 != NULL; sp2++) {
2254 		for (sp1 = mop1->mo_cancel; *sp1 != NULL; sp1++) {
2255 			if (strcmp(*sp1, *sp2) == 0)
2256 				break;
2257 		}
2258 		if (*sp1 == NULL) {
2259 			/*
2260 			 * Option *sp2 not found in mop1, so copy it.
2261 			 * The calls to vfs_copycancelopt_extend()
2262 			 * guarantee that there's enough room.
2263 			 */
2264 			*dp = kmem_alloc(strlen(*sp2) + 1, KM_SLEEP);
2265 			(void) strcpy(*dp++, *sp2);
2266 		}
2267 	}
2268 	if (dp != &result[c1+c2]) {
2269 		size_t bytes = (dp - result + 1) * sizeof (char *);
2270 		char **nres = kmem_alloc(bytes, KM_SLEEP);
2271 
2272 		bcopy(result, nres, bytes);
2273 		kmem_free(result, (c1 + c2 + 1) * sizeof (char *));
2274 		result = nres;
2275 	}
2276 	return (result);
2277 }
2278 
2279 /*
2280  * Merge two mount option tables (outer and inner) into one.  This is very
2281  * similar to "merging" global variables and automatic variables in C.
2282  *
2283  * This isn't (and doesn't have to be) fast.
2284  *
2285  * This function is *not* for general use by filesystems.
2286  *
2287  * Note: caller is responsible for locking the vfs list, if needed,
2288  *       to protect omo, imo & dmo.
2289  */
2290 void
2291 vfs_mergeopttbl(const mntopts_t *omo, const mntopts_t *imo, mntopts_t *dmo)
2292 {
2293 	uint_t i, count;
2294 	mntopt_t *mop, *motbl;
2295 	uint_t freeidx;
2296 
2297 	/*
2298 	 * First determine how much space we need to allocate.
2299 	 */
2300 	count = omo->mo_count;
2301 	for (i = 0; i < imo->mo_count; i++) {
2302 		if (imo->mo_list[i].mo_flags & MO_EMPTY)
2303 			continue;
2304 		if (vfs_hasopt(omo, imo->mo_list[i].mo_name) == NULL)
2305 			count++;
2306 	}
2307 	ASSERT(count >= omo->mo_count &&
2308 	    count <= omo->mo_count + imo->mo_count);
2309 	motbl = kmem_alloc(count * sizeof (mntopt_t), KM_SLEEP);
2310 	for (i = 0; i < omo->mo_count; i++)
2311 		vfs_copyopt(&omo->mo_list[i], &motbl[i]);
2312 	freeidx = omo->mo_count;
2313 	for (i = 0; i < imo->mo_count; i++) {
2314 		if (imo->mo_list[i].mo_flags & MO_EMPTY)
2315 			continue;
2316 		if ((mop = vfs_hasopt(omo, imo->mo_list[i].mo_name)) != NULL) {
2317 			char **newcanp;
2318 			uint_t index = mop - omo->mo_list;
2319 
2320 			newcanp = vfs_mergecancelopts(mop, &motbl[index]);
2321 
2322 			vfs_freeopt(&motbl[index]);
2323 			vfs_copyopt(&imo->mo_list[i], &motbl[index]);
2324 
2325 			vfs_freecancelopt(motbl[index].mo_cancel);
2326 			motbl[index].mo_cancel = newcanp;
2327 		} else {
2328 			/*
2329 			 * If it's a new option, just copy it over to the first
2330 			 * free location.
2331 			 */
2332 			vfs_copyopt(&imo->mo_list[i], &motbl[freeidx++]);
2333 		}
2334 	}
2335 	dmo->mo_count = count;
2336 	dmo->mo_list = motbl;
2337 }
2338 
2339 /*
2340  * Functions to set and clear mount options in a mount options table.
2341  */
2342 
2343 /*
2344  * Clear a mount option, if it exists.
2345  *
2346  * The update_mnttab arg indicates whether mops is part of a vfs that is on
2347  * the vfs list.
2348  */
2349 static void
2350 vfs_clearmntopt_nolock(mntopts_t *mops, const char *opt, int update_mnttab)
2351 {
2352 	struct mntopt *mop;
2353 	uint_t i, count;
2354 
2355 	ASSERT(!update_mnttab || RW_WRITE_HELD(&vfslist));
2356 
2357 	count = mops->mo_count;
2358 	for (i = 0; i < count; i++) {
2359 		mop = &mops->mo_list[i];
2360 
2361 		if (mop->mo_flags & MO_EMPTY)
2362 			continue;
2363 		if (strcmp(opt, mop->mo_name))
2364 			continue;
2365 		mop->mo_flags &= ~MO_SET;
2366 		if (mop->mo_arg != NULL) {
2367 			kmem_free(mop->mo_arg, strlen(mop->mo_arg) + 1);
2368 		}
2369 		mop->mo_arg = NULL;
2370 		if (update_mnttab)
2371 			vfs_mnttab_modtimeupd();
2372 		break;
2373 	}
2374 }
2375 
2376 void
2377 vfs_clearmntopt(struct vfs *vfsp, const char *opt)
2378 {
2379 	int gotlock = 0;
2380 
2381 	if (VFS_ON_LIST(vfsp)) {
2382 		gotlock = 1;
2383 		vfs_list_lock();
2384 	}
2385 	vfs_clearmntopt_nolock(&vfsp->vfs_mntopts, opt, gotlock);
2386 	if (gotlock)
2387 		vfs_list_unlock();
2388 }
2389 
2390 
2391 /*
2392  * Set a mount option on.  If it's not found in the table, it's silently
2393  * ignored.  If the option has MO_IGNORE set, it is still set unless the
2394  * VFS_NOFORCEOPT bit is set in the flags.  Also, VFS_DISPLAY/VFS_NODISPLAY flag
2395  * bits can be used to toggle the MO_NODISPLAY bit for the option.
2396  * If the VFS_CREATEOPT flag bit is set then the first option slot with
2397  * MO_EMPTY set is created as the option passed in.
2398  *
2399  * The update_mnttab arg indicates whether mops is part of a vfs that is on
2400  * the vfs list.
2401  */
2402 static void
2403 vfs_setmntopt_nolock(mntopts_t *mops, const char *opt,
2404     const char *arg, int flags, int update_mnttab)
2405 {
2406 	mntopt_t *mop;
2407 	uint_t i, count;
2408 	char *sp;
2409 
2410 	ASSERT(!update_mnttab || RW_WRITE_HELD(&vfslist));
2411 
2412 	if (flags & VFS_CREATEOPT) {
2413 		if (vfs_hasopt(mops, opt) != NULL) {
2414 			flags &= ~VFS_CREATEOPT;
2415 		}
2416 	}
2417 	count = mops->mo_count;
2418 	for (i = 0; i < count; i++) {
2419 		mop = &mops->mo_list[i];
2420 
2421 		if (mop->mo_flags & MO_EMPTY) {
2422 			if ((flags & VFS_CREATEOPT) == 0)
2423 				continue;
2424 			sp = kmem_alloc(strlen(opt) + 1, KM_SLEEP);
2425 			(void) strcpy(sp, opt);
2426 			mop->mo_name = sp;
2427 			if (arg != NULL)
2428 				mop->mo_flags = MO_HASVALUE;
2429 			else
2430 				mop->mo_flags = 0;
2431 		} else if (strcmp(opt, mop->mo_name)) {
2432 			continue;
2433 		}
2434 		if ((mop->mo_flags & MO_IGNORE) && (flags & VFS_NOFORCEOPT))
2435 			break;
2436 		if (arg != NULL && (mop->mo_flags & MO_HASVALUE) != 0) {
2437 			sp = kmem_alloc(strlen(arg) + 1, KM_SLEEP);
2438 			(void) strcpy(sp, arg);
2439 		} else {
2440 			sp = NULL;
2441 		}
2442 		if (mop->mo_arg != NULL)
2443 			kmem_free(mop->mo_arg, strlen(mop->mo_arg) + 1);
2444 		mop->mo_arg = sp;
2445 		if (flags & VFS_DISPLAY)
2446 			mop->mo_flags &= ~MO_NODISPLAY;
2447 		if (flags & VFS_NODISPLAY)
2448 			mop->mo_flags |= MO_NODISPLAY;
2449 		mop->mo_flags |= MO_SET;
2450 		if (mop->mo_cancel != NULL) {
2451 			char **cp;
2452 
2453 			for (cp = mop->mo_cancel; *cp != NULL; cp++)
2454 				vfs_clearmntopt_nolock(mops, *cp, 0);
2455 		}
2456 		if (update_mnttab)
2457 			vfs_mnttab_modtimeupd();
2458 		break;
2459 	}
2460 }
2461 
2462 void
2463 vfs_setmntopt(struct vfs *vfsp, const char *opt, const char *arg, int flags)
2464 {
2465 	int gotlock = 0;
2466 
2467 	if (VFS_ON_LIST(vfsp)) {
2468 		gotlock = 1;
2469 		vfs_list_lock();
2470 	}
2471 	vfs_setmntopt_nolock(&vfsp->vfs_mntopts, opt, arg, flags, gotlock);
2472 	if (gotlock)
2473 		vfs_list_unlock();
2474 }
2475 
2476 
2477 /*
2478  * Add a "tag" option to a mounted file system's options list.
2479  *
2480  * Note: caller is responsible for locking the vfs list, if needed,
2481  *       to protect mops.
2482  */
2483 static mntopt_t *
2484 vfs_addtag(mntopts_t *mops, const char *tag)
2485 {
2486 	uint_t count;
2487 	mntopt_t *mop, *motbl;
2488 
2489 	count = mops->mo_count + 1;
2490 	motbl = kmem_zalloc(count * sizeof (mntopt_t), KM_SLEEP);
2491 	if (mops->mo_count) {
2492 		size_t len = (count - 1) * sizeof (mntopt_t);
2493 
2494 		bcopy(mops->mo_list, motbl, len);
2495 		kmem_free(mops->mo_list, len);
2496 	}
2497 	mops->mo_count = count;
2498 	mops->mo_list = motbl;
2499 	mop = &motbl[count - 1];
2500 	mop->mo_flags = MO_TAG;
2501 	mop->mo_name = kmem_alloc(strlen(tag) + 1, KM_SLEEP);
2502 	(void) strcpy(mop->mo_name, tag);
2503 	return (mop);
2504 }
2505 
2506 /*
2507  * Allow users to set arbitrary "tags" in a vfs's mount options.
2508  * Broader use within the kernel is discouraged.
2509  */
2510 int
2511 vfs_settag(uint_t major, uint_t minor, const char *mntpt, const char *tag,
2512     cred_t *cr)
2513 {
2514 	vfs_t *vfsp;
2515 	mntopts_t *mops;
2516 	mntopt_t *mop;
2517 	int found = 0;
2518 	dev_t dev = makedevice(major, minor);
2519 	int err = 0;
2520 	char *buf = kmem_alloc(MAX_MNTOPT_STR, KM_SLEEP);
2521 
2522 	/*
2523 	 * Find the desired mounted file system
2524 	 */
2525 	vfs_list_lock();
2526 	vfsp = rootvfs;
2527 	do {
2528 		if (vfsp->vfs_dev == dev &&
2529 		    strcmp(mntpt, refstr_value(vfsp->vfs_mntpt)) == 0) {
2530 			found = 1;
2531 			break;
2532 		}
2533 		vfsp = vfsp->vfs_next;
2534 	} while (vfsp != rootvfs);
2535 
2536 	if (!found) {
2537 		err = EINVAL;
2538 		goto out;
2539 	}
2540 	err = secpolicy_fs_config(cr, vfsp);
2541 	if (err != 0)
2542 		goto out;
2543 
2544 	mops = &vfsp->vfs_mntopts;
2545 	/*
2546 	 * Add tag if it doesn't already exist
2547 	 */
2548 	if ((mop = vfs_hasopt(mops, tag)) == NULL) {
2549 		int len;
2550 
2551 		(void) vfs_buildoptionstr(mops, buf, MAX_MNTOPT_STR);
2552 		len = strlen(buf);
2553 		if (len + strlen(tag) + 2 > MAX_MNTOPT_STR) {
2554 			err = ENAMETOOLONG;
2555 			goto out;
2556 		}
2557 		mop = vfs_addtag(mops, tag);
2558 	}
2559 	if ((mop->mo_flags & MO_TAG) == 0) {
2560 		err = EINVAL;
2561 		goto out;
2562 	}
2563 	vfs_setmntopt_nolock(mops, tag, NULL, 0, 1);
2564 out:
2565 	vfs_list_unlock();
2566 	kmem_free(buf, MAX_MNTOPT_STR);
2567 	return (err);
2568 }
2569 
2570 /*
2571  * Allow users to remove arbitrary "tags" in a vfs's mount options.
2572  * Broader use within the kernel is discouraged.
2573  */
2574 int
2575 vfs_clrtag(uint_t major, uint_t minor, const char *mntpt, const char *tag,
2576     cred_t *cr)
2577 {
2578 	vfs_t *vfsp;
2579 	mntopt_t *mop;
2580 	int found = 0;
2581 	dev_t dev = makedevice(major, minor);
2582 	int err = 0;
2583 
2584 	/*
2585 	 * Find the desired mounted file system
2586 	 */
2587 	vfs_list_lock();
2588 	vfsp = rootvfs;
2589 	do {
2590 		if (vfsp->vfs_dev == dev &&
2591 		    strcmp(mntpt, refstr_value(vfsp->vfs_mntpt)) == 0) {
2592 			found = 1;
2593 			break;
2594 		}
2595 		vfsp = vfsp->vfs_next;
2596 	} while (vfsp != rootvfs);
2597 
2598 	if (!found) {
2599 		err = EINVAL;
2600 		goto out;
2601 	}
2602 	err = secpolicy_fs_config(cr, vfsp);
2603 	if (err != 0)
2604 		goto out;
2605 
2606 	if ((mop = vfs_hasopt(&vfsp->vfs_mntopts, tag)) == NULL) {
2607 		err = EINVAL;
2608 		goto out;
2609 	}
2610 	if ((mop->mo_flags & MO_TAG) == 0) {
2611 		err = EINVAL;
2612 		goto out;
2613 	}
2614 	vfs_clearmntopt_nolock(&vfsp->vfs_mntopts, tag, 1);
2615 out:
2616 	vfs_list_unlock();
2617 	return (err);
2618 }
2619 
2620 /*
2621  * Function to parse an option string and fill in a mount options table.
2622  * Unknown options are silently ignored.  The input option string is modified
2623  * by replacing separators with nulls.  If the create flag is set, options
2624  * not found in the table are just added on the fly.  The table must have
2625  * an option slot marked MO_EMPTY to add an option on the fly.
2626  *
2627  * This function is *not* for general use by filesystems.
2628  *
2629  * Note: caller is responsible for locking the vfs list, if needed,
2630  *       to protect mops..
2631  */
2632 void
2633 vfs_parsemntopts(mntopts_t *mops, char *osp, int create)
2634 {
2635 	char *s = osp, *p, *nextop, *valp, *cp, *ep;
2636 	int setflg = VFS_NOFORCEOPT;
2637 
2638 	if (osp == NULL)
2639 		return;
2640 	while (*s != '\0') {
2641 		p = strchr(s, ',');	/* find next option */
2642 		if (p == NULL) {
2643 			cp = NULL;
2644 			p = s + strlen(s);
2645 		} else {
2646 			cp = p;		/* save location of comma */
2647 			*p++ = '\0';	/* mark end and point to next option */
2648 		}
2649 		nextop = p;
2650 		p = strchr(s, '=');	/* look for value */
2651 		if (p == NULL) {
2652 			valp = NULL;	/* no value supplied */
2653 		} else {
2654 			ep = p;		/* save location of equals */
2655 			*p++ = '\0';	/* end option and point to value */
2656 			valp = p;
2657 		}
2658 		/*
2659 		 * set option into options table
2660 		 */
2661 		if (create)
2662 			setflg |= VFS_CREATEOPT;
2663 		vfs_setmntopt_nolock(mops, s, valp, setflg, 0);
2664 		if (cp != NULL)
2665 			*cp = ',';	/* restore the comma */
2666 		if (valp != NULL)
2667 			*ep = '=';	/* restore the equals */
2668 		s = nextop;
2669 	}
2670 }
2671 
2672 /*
2673  * Function to inquire if an option exists in a mount options table.
2674  * Returns a pointer to the option if it exists, else NULL.
2675  *
2676  * This function is *not* for general use by filesystems.
2677  *
2678  * Note: caller is responsible for locking the vfs list, if needed,
2679  *       to protect mops.
2680  */
2681 struct mntopt *
2682 vfs_hasopt(const mntopts_t *mops, const char *opt)
2683 {
2684 	struct mntopt *mop;
2685 	uint_t i, count;
2686 
2687 	count = mops->mo_count;
2688 	for (i = 0; i < count; i++) {
2689 		mop = &mops->mo_list[i];
2690 
2691 		if (mop->mo_flags & MO_EMPTY)
2692 			continue;
2693 		if (strcmp(opt, mop->mo_name) == 0)
2694 			return (mop);
2695 	}
2696 	return (NULL);
2697 }
2698 
2699 /*
2700  * Function to inquire if an option is set in a mount options table.
2701  * Returns non-zero if set and fills in the arg pointer with a pointer to
2702  * the argument string or NULL if there is no argument string.
2703  */
2704 static int
2705 vfs_optionisset_nolock(const mntopts_t *mops, const char *opt, char **argp)
2706 {
2707 	struct mntopt *mop;
2708 	uint_t i, count;
2709 
2710 	count = mops->mo_count;
2711 	for (i = 0; i < count; i++) {
2712 		mop = &mops->mo_list[i];
2713 
2714 		if (mop->mo_flags & MO_EMPTY)
2715 			continue;
2716 		if (strcmp(opt, mop->mo_name))
2717 			continue;
2718 		if ((mop->mo_flags & MO_SET) == 0)
2719 			return (0);
2720 		if (argp != NULL && (mop->mo_flags & MO_HASVALUE) != 0)
2721 			*argp = mop->mo_arg;
2722 		return (1);
2723 	}
2724 	return (0);
2725 }
2726 
2727 
2728 int
2729 vfs_optionisset(const struct vfs *vfsp, const char *opt, char **argp)
2730 {
2731 	int ret;
2732 
2733 	vfs_list_read_lock();
2734 	ret = vfs_optionisset_nolock(&vfsp->vfs_mntopts, opt, argp);
2735 	vfs_list_unlock();
2736 	return (ret);
2737 }
2738 
2739 
2740 /*
2741  * Construct a comma separated string of the options set in the given
2742  * mount table, return the string in the given buffer.  Return non-zero if
2743  * the buffer would overflow.
2744  *
2745  * This function is *not* for general use by filesystems.
2746  *
2747  * Note: caller is responsible for locking the vfs list, if needed,
2748  *       to protect mp.
2749  */
2750 int
2751 vfs_buildoptionstr(const mntopts_t *mp, char *buf, int len)
2752 {
2753 	char *cp;
2754 	uint_t i;
2755 
2756 	buf[0] = '\0';
2757 	cp = buf;
2758 	for (i = 0; i < mp->mo_count; i++) {
2759 		struct mntopt *mop;
2760 
2761 		mop = &mp->mo_list[i];
2762 		if (mop->mo_flags & MO_SET) {
2763 			int optlen, comma = 0;
2764 
2765 			if (buf[0] != '\0')
2766 				comma = 1;
2767 			optlen = strlen(mop->mo_name);
2768 			if (strlen(buf) + comma + optlen + 1 > len)
2769 				goto err;
2770 			if (comma)
2771 				*cp++ = ',';
2772 			(void) strcpy(cp, mop->mo_name);
2773 			cp += optlen;
2774 			/*
2775 			 * Append option value if there is one
2776 			 */
2777 			if (mop->mo_arg != NULL) {
2778 				int arglen;
2779 
2780 				arglen = strlen(mop->mo_arg);
2781 				if (strlen(buf) + arglen + 2 > len)
2782 					goto err;
2783 				*cp++ = '=';
2784 				(void) strcpy(cp, mop->mo_arg);
2785 				cp += arglen;
2786 			}
2787 		}
2788 	}
2789 	return (0);
2790 err:
2791 	return (EOVERFLOW);
2792 }
2793 
2794 static void
2795 vfs_freecancelopt(char **moc)
2796 {
2797 	if (moc != NULL) {
2798 		int ccnt = 0;
2799 		char **cp;
2800 
2801 		for (cp = moc; *cp != NULL; cp++) {
2802 			kmem_free(*cp, strlen(*cp) + 1);
2803 			ccnt++;
2804 		}
2805 		kmem_free(moc, (ccnt + 1) * sizeof (char *));
2806 	}
2807 }
2808 
2809 static void
2810 vfs_freeopt(mntopt_t *mop)
2811 {
2812 	if (mop->mo_name != NULL)
2813 		kmem_free(mop->mo_name, strlen(mop->mo_name) + 1);
2814 
2815 	vfs_freecancelopt(mop->mo_cancel);
2816 
2817 	if (mop->mo_arg != NULL)
2818 		kmem_free(mop->mo_arg, strlen(mop->mo_arg) + 1);
2819 }
2820 
2821 /*
2822  * Free a mount options table
2823  *
2824  * This function is *not* for general use by filesystems.
2825  *
2826  * Note: caller is responsible for locking the vfs list, if needed,
2827  *       to protect mp.
2828  */
2829 void
2830 vfs_freeopttbl(mntopts_t *mp)
2831 {
2832 	uint_t i, count;
2833 
2834 	count = mp->mo_count;
2835 	for (i = 0; i < count; i++) {
2836 		vfs_freeopt(&mp->mo_list[i]);
2837 	}
2838 	if (count) {
2839 		kmem_free(mp->mo_list, sizeof (mntopt_t) * count);
2840 		mp->mo_count = 0;
2841 		mp->mo_list = NULL;
2842 	}
2843 }
2844 
2845 
2846 /* ARGSUSED */
2847 static int
2848 vfs_mntdummyread(vnode_t *vp, uio_t *uio, int ioflag, cred_t *cred,
2849 	caller_context_t *ct)
2850 {
2851 	return (0);
2852 }
2853 
2854 /* ARGSUSED */
2855 static int
2856 vfs_mntdummywrite(vnode_t *vp, uio_t *uio, int ioflag, cred_t *cred,
2857 	caller_context_t *ct)
2858 {
2859 	return (0);
2860 }
2861 
2862 /*
2863  * The dummy vnode is currently used only by file events notification
2864  * module which is just interested in the timestamps.
2865  */
2866 /* ARGSUSED */
2867 static int
2868 vfs_mntdummygetattr(vnode_t *vp, vattr_t *vap, int flags, cred_t *cr,
2869     caller_context_t *ct)
2870 {
2871 	bzero(vap, sizeof (vattr_t));
2872 	vap->va_type = VREG;
2873 	vap->va_nlink = 1;
2874 	vap->va_ctime = vfs_mnttab_ctime;
2875 	/*
2876 	 * it is ok to just copy mtime as the time will be monotonically
2877 	 * increasing.
2878 	 */
2879 	vap->va_mtime = vfs_mnttab_mtime;
2880 	vap->va_atime = vap->va_mtime;
2881 	return (0);
2882 }
2883 
2884 static void
2885 vfs_mnttabvp_setup(void)
2886 {
2887 	vnode_t *tvp;
2888 	vnodeops_t *vfs_mntdummyvnops;
2889 	const fs_operation_def_t mnt_dummyvnodeops_template[] = {
2890 		VOPNAME_READ, 		{ .vop_read = vfs_mntdummyread },
2891 		VOPNAME_WRITE, 		{ .vop_write = vfs_mntdummywrite },
2892 		VOPNAME_GETATTR,	{ .vop_getattr = vfs_mntdummygetattr },
2893 		VOPNAME_VNEVENT,	{ .vop_vnevent = fs_vnevent_support },
2894 		NULL,			NULL
2895 	};
2896 
2897 	if (vn_make_ops("mnttab", mnt_dummyvnodeops_template,
2898 	    &vfs_mntdummyvnops) != 0) {
2899 		cmn_err(CE_WARN, "vfs_mnttabvp_setup: vn_make_ops failed");
2900 		/* Shouldn't happen, but not bad enough to panic */
2901 		return;
2902 	}
2903 
2904 	/*
2905 	 * A global dummy vnode is allocated to represent mntfs files.
2906 	 * The mntfs file (/etc/mnttab) can be monitored for file events
2907 	 * and receive an event when mnttab changes. Dummy VOP calls
2908 	 * will be made on this vnode. The file events notification module
2909 	 * intercepts this vnode and delivers relevant events.
2910 	 */
2911 	tvp = vn_alloc(KM_SLEEP);
2912 	tvp->v_flag = VNOMOUNT|VNOMAP|VNOSWAP|VNOCACHE;
2913 	vn_setops(tvp, vfs_mntdummyvnops);
2914 	tvp->v_type = VREG;
2915 	/*
2916 	 * The mnt dummy ops do not reference v_data.
2917 	 * No other module intercepting this vnode should either.
2918 	 * Just set it to point to itself.
2919 	 */
2920 	tvp->v_data = (caddr_t)tvp;
2921 	tvp->v_vfsp = rootvfs;
2922 	vfs_mntdummyvp = tvp;
2923 }
2924 
2925 /*
2926  * performs fake read/write ops
2927  */
2928 static void
2929 vfs_mnttab_rwop(int rw)
2930 {
2931 	struct uio	uio;
2932 	struct iovec	iov;
2933 	char	buf[1];
2934 
2935 	if (vfs_mntdummyvp == NULL)
2936 		return;
2937 
2938 	bzero(&uio, sizeof (uio));
2939 	bzero(&iov, sizeof (iov));
2940 	iov.iov_base = buf;
2941 	iov.iov_len = 0;
2942 	uio.uio_iov = &iov;
2943 	uio.uio_iovcnt = 1;
2944 	uio.uio_loffset = 0;
2945 	uio.uio_segflg = UIO_SYSSPACE;
2946 	uio.uio_resid = 0;
2947 	if (rw) {
2948 		(void) VOP_WRITE(vfs_mntdummyvp, &uio, 0, kcred, NULL);
2949 	} else {
2950 		(void) VOP_READ(vfs_mntdummyvp, &uio, 0, kcred, NULL);
2951 	}
2952 }
2953 
2954 /*
2955  * Generate a write operation.
2956  */
2957 void
2958 vfs_mnttab_writeop(void)
2959 {
2960 	vfs_mnttab_rwop(1);
2961 }
2962 
2963 /*
2964  * Generate a read operation.
2965  */
2966 void
2967 vfs_mnttab_readop(void)
2968 {
2969 	vfs_mnttab_rwop(0);
2970 }
2971 
2972 /*
2973  * Free any mnttab information recorded in the vfs struct.
2974  * The vfs must not be on the vfs list.
2975  */
2976 static void
2977 vfs_freemnttab(struct vfs *vfsp)
2978 {
2979 	ASSERT(!VFS_ON_LIST(vfsp));
2980 
2981 	/*
2982 	 * Free device and mount point information
2983 	 */
2984 	if (vfsp->vfs_mntpt != NULL) {
2985 		refstr_rele(vfsp->vfs_mntpt);
2986 		vfsp->vfs_mntpt = NULL;
2987 	}
2988 	if (vfsp->vfs_resource != NULL) {
2989 		refstr_rele(vfsp->vfs_resource);
2990 		vfsp->vfs_resource = NULL;
2991 	}
2992 	/*
2993 	 * Now free mount options information
2994 	 */
2995 	vfs_freeopttbl(&vfsp->vfs_mntopts);
2996 }
2997 
2998 /*
2999  * Return the last mnttab modification time
3000  */
3001 void
3002 vfs_mnttab_modtime(timespec_t *ts)
3003 {
3004 	ASSERT(RW_LOCK_HELD(&vfslist));
3005 	*ts = vfs_mnttab_mtime;
3006 }
3007 
3008 /*
3009  * See if mnttab is changed
3010  */
3011 void
3012 vfs_mnttab_poll(timespec_t *old, struct pollhead **phpp)
3013 {
3014 	int changed;
3015 
3016 	*phpp = (struct pollhead *)NULL;
3017 
3018 	/*
3019 	 * Note: don't grab vfs list lock before accessing vfs_mnttab_mtime.
3020 	 * Can lead to deadlock against vfs_mnttab_modtimeupd(). It is safe
3021 	 * to not grab the vfs list lock because tv_sec is monotonically
3022 	 * increasing.
3023 	 */
3024 
3025 	changed = (old->tv_nsec != vfs_mnttab_mtime.tv_nsec) ||
3026 	    (old->tv_sec != vfs_mnttab_mtime.tv_sec);
3027 	if (!changed) {
3028 		*phpp = &vfs_pollhd;
3029 	}
3030 }
3031 
3032 /* Provide a unique and monotonically-increasing timestamp. */
3033 void
3034 vfs_mono_time(timespec_t *ts)
3035 {
3036 	static volatile hrtime_t hrt;		/* The saved time. */
3037 	hrtime_t	newhrt, oldhrt;		/* For effecting the CAS. */
3038 	timespec_t	newts;
3039 
3040 	/*
3041 	 * Try gethrestime() first, but be prepared to fabricate a sensible
3042 	 * answer at the first sign of any trouble.
3043 	 */
3044 	gethrestime(&newts);
3045 	newhrt = ts2hrt(&newts);
3046 	for (;;) {
3047 		oldhrt = hrt;
3048 		if (newhrt <= hrt)
3049 			newhrt = hrt + 1;
3050 		if (atomic_cas_64((uint64_t *)&hrt, oldhrt, newhrt) == oldhrt)
3051 			break;
3052 	}
3053 	hrt2ts(newhrt, ts);
3054 }
3055 
3056 /*
3057  * Update the mnttab modification time and wake up any waiters for
3058  * mnttab changes
3059  */
3060 void
3061 vfs_mnttab_modtimeupd()
3062 {
3063 	hrtime_t oldhrt, newhrt;
3064 
3065 	ASSERT(RW_WRITE_HELD(&vfslist));
3066 	oldhrt = ts2hrt(&vfs_mnttab_mtime);
3067 	gethrestime(&vfs_mnttab_mtime);
3068 	newhrt = ts2hrt(&vfs_mnttab_mtime);
3069 	if (oldhrt == (hrtime_t)0)
3070 		vfs_mnttab_ctime = vfs_mnttab_mtime;
3071 	/*
3072 	 * Attempt to provide unique mtime (like uniqtime but not).
3073 	 */
3074 	if (newhrt == oldhrt) {
3075 		newhrt++;
3076 		hrt2ts(newhrt, &vfs_mnttab_mtime);
3077 	}
3078 	pollwakeup(&vfs_pollhd, (short)POLLRDBAND);
3079 	vfs_mnttab_writeop();
3080 }
3081 
3082 int
3083 dounmount(struct vfs *vfsp, int flag, cred_t *cr)
3084 {
3085 	vnode_t *coveredvp;
3086 	int error;
3087 	extern void teardown_vopstats(vfs_t *);
3088 
3089 	/*
3090 	 * Get covered vnode. This will be NULL if the vfs is not linked
3091 	 * into the file system name space (i.e., domount() with MNT_NOSPICE).
3092 	 */
3093 	coveredvp = vfsp->vfs_vnodecovered;
3094 	ASSERT(coveredvp == NULL || vn_vfswlock_held(coveredvp));
3095 
3096 	/*
3097 	 * Purge all dnlc entries for this vfs.
3098 	 */
3099 	(void) dnlc_purge_vfsp(vfsp, 0);
3100 
3101 	/* For forcible umount, skip VFS_SYNC() since it may hang */
3102 	if ((flag & MS_FORCE) == 0)
3103 		(void) VFS_SYNC(vfsp, 0, cr);
3104 
3105 	/*
3106 	 * Lock the vfs to maintain fs status quo during unmount.  This
3107 	 * has to be done after the sync because ufs_update tries to acquire
3108 	 * the vfs_reflock.
3109 	 */
3110 	vfs_lock_wait(vfsp);
3111 
3112 	if (error = VFS_UNMOUNT(vfsp, flag, cr)) {
3113 		vfs_unlock(vfsp);
3114 		if (coveredvp != NULL)
3115 			vn_vfsunlock(coveredvp);
3116 	} else if (coveredvp != NULL) {
3117 		teardown_vopstats(vfsp);
3118 		/*
3119 		 * vfs_remove() will do a VN_RELE(vfsp->vfs_vnodecovered)
3120 		 * when it frees vfsp so we do a VN_HOLD() so we can
3121 		 * continue to use coveredvp afterwards.
3122 		 */
3123 		VN_HOLD(coveredvp);
3124 		vfs_remove(vfsp);
3125 		vn_vfsunlock(coveredvp);
3126 		VN_RELE(coveredvp);
3127 	} else {
3128 		teardown_vopstats(vfsp);
3129 		/*
3130 		 * Release the reference to vfs that is not linked
3131 		 * into the name space.
3132 		 */
3133 		vfs_unlock(vfsp);
3134 		VFS_RELE(vfsp);
3135 	}
3136 	return (error);
3137 }
3138 
3139 
3140 /*
3141  * Vfs_unmountall() is called by uadmin() to unmount all
3142  * mounted file systems (except the root file system) during shutdown.
3143  * It follows the existing locking protocol when traversing the vfs list
3144  * to sync and unmount vfses. Even though there should be no
3145  * other thread running while the system is shutting down, it is prudent
3146  * to still follow the locking protocol.
3147  */
3148 void
3149 vfs_unmountall(void)
3150 {
3151 	struct vfs *vfsp;
3152 	struct vfs *prev_vfsp = NULL;
3153 	int error;
3154 
3155 	/*
3156 	 * Toss all dnlc entries now so that the per-vfs sync
3157 	 * and unmount operations don't have to slog through
3158 	 * a bunch of uninteresting vnodes over and over again.
3159 	 */
3160 	dnlc_purge();
3161 
3162 	vfs_list_lock();
3163 	for (vfsp = rootvfs->vfs_prev; vfsp != rootvfs; vfsp = prev_vfsp) {
3164 		prev_vfsp = vfsp->vfs_prev;
3165 
3166 		if (vfs_lock(vfsp) != 0)
3167 			continue;
3168 		error = vn_vfswlock(vfsp->vfs_vnodecovered);
3169 		vfs_unlock(vfsp);
3170 		if (error)
3171 			continue;
3172 
3173 		vfs_list_unlock();
3174 
3175 		(void) VFS_SYNC(vfsp, SYNC_CLOSE, CRED());
3176 		(void) dounmount(vfsp, 0, CRED());
3177 
3178 		/*
3179 		 * Since we dropped the vfslist lock above we must
3180 		 * verify that next_vfsp still exists, else start over.
3181 		 */
3182 		vfs_list_lock();
3183 		for (vfsp = rootvfs->vfs_prev;
3184 		    vfsp != rootvfs; vfsp = vfsp->vfs_prev)
3185 			if (vfsp == prev_vfsp)
3186 				break;
3187 		if (vfsp == rootvfs && prev_vfsp != rootvfs)
3188 			prev_vfsp = rootvfs->vfs_prev;
3189 	}
3190 	vfs_list_unlock();
3191 }
3192 
3193 /*
3194  * Called to add an entry to the end of the vfs mount in progress list
3195  */
3196 void
3197 vfs_addmip(dev_t dev, struct vfs *vfsp)
3198 {
3199 	struct ipmnt *mipp;
3200 
3201 	mipp = (struct ipmnt *)kmem_alloc(sizeof (struct ipmnt), KM_SLEEP);
3202 	mipp->mip_next = NULL;
3203 	mipp->mip_dev = dev;
3204 	mipp->mip_vfsp = vfsp;
3205 	mutex_enter(&vfs_miplist_mutex);
3206 	if (vfs_miplist_end != NULL)
3207 		vfs_miplist_end->mip_next = mipp;
3208 	else
3209 		vfs_miplist = mipp;
3210 	vfs_miplist_end = mipp;
3211 	mutex_exit(&vfs_miplist_mutex);
3212 }
3213 
3214 /*
3215  * Called to remove an entry from the mount in progress list
3216  * Either because the mount completed or it failed.
3217  */
3218 void
3219 vfs_delmip(struct vfs *vfsp)
3220 {
3221 	struct ipmnt *mipp, *mipprev;
3222 
3223 	mutex_enter(&vfs_miplist_mutex);
3224 	mipprev = NULL;
3225 	for (mipp = vfs_miplist;
3226 	    mipp && mipp->mip_vfsp != vfsp; mipp = mipp->mip_next) {
3227 		mipprev = mipp;
3228 	}
3229 	if (mipp == NULL)
3230 		return; /* shouldn't happen */
3231 	if (mipp == vfs_miplist_end)
3232 		vfs_miplist_end = mipprev;
3233 	if (mipprev == NULL)
3234 		vfs_miplist = mipp->mip_next;
3235 	else
3236 		mipprev->mip_next = mipp->mip_next;
3237 	mutex_exit(&vfs_miplist_mutex);
3238 	kmem_free(mipp, sizeof (struct ipmnt));
3239 }
3240 
3241 /*
3242  * vfs_add is called by a specific filesystem's mount routine to add
3243  * the new vfs into the vfs list/hash and to cover the mounted-on vnode.
3244  * The vfs should already have been locked by the caller.
3245  *
3246  * coveredvp is NULL if this is the root.
3247  */
3248 void
3249 vfs_add(vnode_t *coveredvp, struct vfs *vfsp, int mflag)
3250 {
3251 	int newflag;
3252 
3253 	ASSERT(vfs_lock_held(vfsp));
3254 	VFS_HOLD(vfsp);
3255 	newflag = vfsp->vfs_flag;
3256 	if (mflag & MS_RDONLY)
3257 		newflag |= VFS_RDONLY;
3258 	else
3259 		newflag &= ~VFS_RDONLY;
3260 	if (mflag & MS_NOSUID)
3261 		newflag |= (VFS_NOSETUID|VFS_NODEVICES);
3262 	else
3263 		newflag &= ~(VFS_NOSETUID|VFS_NODEVICES);
3264 	if (mflag & MS_NOMNTTAB)
3265 		newflag |= VFS_NOMNTTAB;
3266 	else
3267 		newflag &= ~VFS_NOMNTTAB;
3268 
3269 	if (coveredvp != NULL) {
3270 		ASSERT(vn_vfswlock_held(coveredvp));
3271 		coveredvp->v_vfsmountedhere = vfsp;
3272 		VN_HOLD(coveredvp);
3273 	}
3274 	vfsp->vfs_vnodecovered = coveredvp;
3275 	vfsp->vfs_flag = newflag;
3276 
3277 	vfs_list_add(vfsp);
3278 }
3279 
3280 /*
3281  * Remove a vfs from the vfs list, null out the pointer from the
3282  * covered vnode to the vfs (v_vfsmountedhere), and null out the pointer
3283  * from the vfs to the covered vnode (vfs_vnodecovered). Release the
3284  * reference to the vfs and to the covered vnode.
3285  *
3286  * Called from dounmount after it's confirmed with the file system
3287  * that the unmount is legal.
3288  */
3289 void
3290 vfs_remove(struct vfs *vfsp)
3291 {
3292 	vnode_t *vp;
3293 
3294 	ASSERT(vfs_lock_held(vfsp));
3295 
3296 	/*
3297 	 * Can't unmount root.  Should never happen because fs will
3298 	 * be busy.
3299 	 */
3300 	if (vfsp == rootvfs)
3301 		panic("vfs_remove: unmounting root");
3302 
3303 	vfs_list_remove(vfsp);
3304 
3305 	/*
3306 	 * Unhook from the file system name space.
3307 	 */
3308 	vp = vfsp->vfs_vnodecovered;
3309 	ASSERT(vn_vfswlock_held(vp));
3310 	vp->v_vfsmountedhere = NULL;
3311 	vfsp->vfs_vnodecovered = NULL;
3312 	VN_RELE(vp);
3313 
3314 	/*
3315 	 * Release lock and wakeup anybody waiting.
3316 	 */
3317 	vfs_unlock(vfsp);
3318 	VFS_RELE(vfsp);
3319 }
3320 
3321 /*
3322  * Lock a filesystem to prevent access to it while mounting,
3323  * unmounting and syncing.  Return EBUSY immediately if lock
3324  * can't be acquired.
3325  */
3326 int
3327 vfs_lock(vfs_t *vfsp)
3328 {
3329 	vn_vfslocks_entry_t *vpvfsentry;
3330 
3331 	vpvfsentry = vn_vfslocks_getlock(vfsp);
3332 	if (rwst_tryenter(&vpvfsentry->ve_lock, RW_WRITER))
3333 		return (0);
3334 
3335 	vn_vfslocks_rele(vpvfsentry);
3336 	return (EBUSY);
3337 }
3338 
3339 int
3340 vfs_rlock(vfs_t *vfsp)
3341 {
3342 	vn_vfslocks_entry_t *vpvfsentry;
3343 
3344 	vpvfsentry = vn_vfslocks_getlock(vfsp);
3345 
3346 	if (rwst_tryenter(&vpvfsentry->ve_lock, RW_READER))
3347 		return (0);
3348 
3349 	vn_vfslocks_rele(vpvfsentry);
3350 	return (EBUSY);
3351 }
3352 
3353 void
3354 vfs_lock_wait(vfs_t *vfsp)
3355 {
3356 	vn_vfslocks_entry_t *vpvfsentry;
3357 
3358 	vpvfsentry = vn_vfslocks_getlock(vfsp);
3359 	rwst_enter(&vpvfsentry->ve_lock, RW_WRITER);
3360 }
3361 
3362 void
3363 vfs_rlock_wait(vfs_t *vfsp)
3364 {
3365 	vn_vfslocks_entry_t *vpvfsentry;
3366 
3367 	vpvfsentry = vn_vfslocks_getlock(vfsp);
3368 	rwst_enter(&vpvfsentry->ve_lock, RW_READER);
3369 }
3370 
3371 /*
3372  * Unlock a locked filesystem.
3373  */
3374 void
3375 vfs_unlock(vfs_t *vfsp)
3376 {
3377 	vn_vfslocks_entry_t *vpvfsentry;
3378 
3379 	/*
3380 	 * vfs_unlock will mimic sema_v behaviour to fix 4748018.
3381 	 * And these changes should remain for the patch changes as it is.
3382 	 */
3383 	if (panicstr)
3384 		return;
3385 
3386 	/*
3387 	 * ve_refcount needs to be dropped twice here.
3388 	 * 1. To release refernce after a call to vfs_locks_getlock()
3389 	 * 2. To release the reference from the locking routines like
3390 	 *    vfs_rlock_wait/vfs_wlock_wait/vfs_wlock etc,.
3391 	 */
3392 
3393 	vpvfsentry = vn_vfslocks_getlock(vfsp);
3394 	vn_vfslocks_rele(vpvfsentry);
3395 
3396 	rwst_exit(&vpvfsentry->ve_lock);
3397 	vn_vfslocks_rele(vpvfsentry);
3398 }
3399 
3400 /*
3401  * Utility routine that allows a filesystem to construct its
3402  * fsid in "the usual way" - by munging some underlying dev_t and
3403  * the filesystem type number into the 64-bit fsid.  Note that
3404  * this implicitly relies on dev_t persistence to make filesystem
3405  * id's persistent.
3406  *
3407  * There's nothing to prevent an individual fs from constructing its
3408  * fsid in a different way, and indeed they should.
3409  *
3410  * Since we want fsids to be 32-bit quantities (so that they can be
3411  * exported identically by either 32-bit or 64-bit APIs, as well as
3412  * the fact that fsid's are "known" to NFS), we compress the device
3413  * number given down to 32-bits, and panic if that isn't possible.
3414  */
3415 void
3416 vfs_make_fsid(fsid_t *fsi, dev_t dev, int val)
3417 {
3418 	if (!cmpldev((dev32_t *)&fsi->val[0], dev))
3419 		panic("device number too big for fsid!");
3420 	fsi->val[1] = val;
3421 }
3422 
3423 int
3424 vfs_lock_held(vfs_t *vfsp)
3425 {
3426 	int held;
3427 	vn_vfslocks_entry_t *vpvfsentry;
3428 
3429 	/*
3430 	 * vfs_lock_held will mimic sema_held behaviour
3431 	 * if panicstr is set. And these changes should remain
3432 	 * for the patch changes as it is.
3433 	 */
3434 	if (panicstr)
3435 		return (1);
3436 
3437 	vpvfsentry = vn_vfslocks_getlock(vfsp);
3438 	held = rwst_lock_held(&vpvfsentry->ve_lock, RW_WRITER);
3439 
3440 	vn_vfslocks_rele(vpvfsentry);
3441 	return (held);
3442 }
3443 
3444 struct _kthread *
3445 vfs_lock_owner(vfs_t *vfsp)
3446 {
3447 	struct _kthread *owner;
3448 	vn_vfslocks_entry_t *vpvfsentry;
3449 
3450 	/*
3451 	 * vfs_wlock_held will mimic sema_held behaviour
3452 	 * if panicstr is set. And these changes should remain
3453 	 * for the patch changes as it is.
3454 	 */
3455 	if (panicstr)
3456 		return (NULL);
3457 
3458 	vpvfsentry = vn_vfslocks_getlock(vfsp);
3459 	owner = rwst_owner(&vpvfsentry->ve_lock);
3460 
3461 	vn_vfslocks_rele(vpvfsentry);
3462 	return (owner);
3463 }
3464 
3465 /*
3466  * vfs list locking.
3467  *
3468  * Rather than manipulate the vfslist lock directly, we abstract into lock
3469  * and unlock routines to allow the locking implementation to be changed for
3470  * clustering.
3471  *
3472  * Whenever the vfs list is modified through its hash links, the overall list
3473  * lock must be obtained before locking the relevant hash bucket.  But to see
3474  * whether a given vfs is on the list, it suffices to obtain the lock for the
3475  * hash bucket without getting the overall list lock.  (See getvfs() below.)
3476  */
3477 
3478 void
3479 vfs_list_lock()
3480 {
3481 	rw_enter(&vfslist, RW_WRITER);
3482 }
3483 
3484 void
3485 vfs_list_read_lock()
3486 {
3487 	rw_enter(&vfslist, RW_READER);
3488 }
3489 
3490 void
3491 vfs_list_unlock()
3492 {
3493 	rw_exit(&vfslist);
3494 }
3495 
3496 /*
3497  * Low level worker routines for adding entries to and removing entries from
3498  * the vfs list.
3499  */
3500 
3501 static void
3502 vfs_hash_add(struct vfs *vfsp, int insert_at_head)
3503 {
3504 	int vhno;
3505 	struct vfs **hp;
3506 	dev_t dev;
3507 
3508 	ASSERT(RW_WRITE_HELD(&vfslist));
3509 
3510 	dev = expldev(vfsp->vfs_fsid.val[0]);
3511 	vhno = VFSHASH(getmajor(dev), getminor(dev));
3512 
3513 	mutex_enter(&rvfs_list[vhno].rvfs_lock);
3514 
3515 	/*
3516 	 * Link into the hash table, inserting it at the end, so that LOFS
3517 	 * with the same fsid as UFS (or other) file systems will not hide the
3518 	 * UFS.
3519 	 */
3520 	if (insert_at_head) {
3521 		vfsp->vfs_hash = rvfs_list[vhno].rvfs_head;
3522 		rvfs_list[vhno].rvfs_head = vfsp;
3523 	} else {
3524 		for (hp = &rvfs_list[vhno].rvfs_head; *hp != NULL;
3525 		    hp = &(*hp)->vfs_hash)
3526 			continue;
3527 		/*
3528 		 * hp now contains the address of the pointer to update
3529 		 * to effect the insertion.
3530 		 */
3531 		vfsp->vfs_hash = NULL;
3532 		*hp = vfsp;
3533 	}
3534 
3535 	rvfs_list[vhno].rvfs_len++;
3536 	mutex_exit(&rvfs_list[vhno].rvfs_lock);
3537 }
3538 
3539 
3540 static void
3541 vfs_hash_remove(struct vfs *vfsp)
3542 {
3543 	int vhno;
3544 	struct vfs *tvfsp;
3545 	dev_t dev;
3546 
3547 	ASSERT(RW_WRITE_HELD(&vfslist));
3548 
3549 	dev = expldev(vfsp->vfs_fsid.val[0]);
3550 	vhno = VFSHASH(getmajor(dev), getminor(dev));
3551 
3552 	mutex_enter(&rvfs_list[vhno].rvfs_lock);
3553 
3554 	/*
3555 	 * Remove from hash.
3556 	 */
3557 	if (rvfs_list[vhno].rvfs_head == vfsp) {
3558 		rvfs_list[vhno].rvfs_head = vfsp->vfs_hash;
3559 		rvfs_list[vhno].rvfs_len--;
3560 		goto foundit;
3561 	}
3562 	for (tvfsp = rvfs_list[vhno].rvfs_head; tvfsp != NULL;
3563 	    tvfsp = tvfsp->vfs_hash) {
3564 		if (tvfsp->vfs_hash == vfsp) {
3565 			tvfsp->vfs_hash = vfsp->vfs_hash;
3566 			rvfs_list[vhno].rvfs_len--;
3567 			goto foundit;
3568 		}
3569 	}
3570 	cmn_err(CE_WARN, "vfs_list_remove: vfs not found in hash");
3571 
3572 foundit:
3573 
3574 	mutex_exit(&rvfs_list[vhno].rvfs_lock);
3575 }
3576 
3577 
3578 void
3579 vfs_list_add(struct vfs *vfsp)
3580 {
3581 	zone_t *zone;
3582 
3583 	/*
3584 	 * Typically, the vfs_t will have been created on behalf of the file
3585 	 * system in vfs_init, where it will have been provided with a
3586 	 * vfs_impl_t. This, however, might be lacking if the vfs_t was created
3587 	 * by an unbundled file system. We therefore check for such an example
3588 	 * before stamping the vfs_t with its creation time for the benefit of
3589 	 * mntfs.
3590 	 */
3591 	if (vfsp->vfs_implp == NULL)
3592 		vfsimpl_setup(vfsp);
3593 	vfs_mono_time(&vfsp->vfs_hrctime);
3594 
3595 	/*
3596 	 * The zone that owns the mount is the one that performed the mount.
3597 	 * Note that this isn't necessarily the same as the zone mounted into.
3598 	 * The corresponding zone_rele_ref() will be done when the vfs_t
3599 	 * is being free'd.
3600 	 */
3601 	vfsp->vfs_zone = curproc->p_zone;
3602 	zone_init_ref(&vfsp->vfs_implp->vi_zone_ref);
3603 	zone_hold_ref(vfsp->vfs_zone, &vfsp->vfs_implp->vi_zone_ref,
3604 	    ZONE_REF_VFS);
3605 
3606 	/*
3607 	 * Find the zone mounted into, and put this mount on its vfs list.
3608 	 */
3609 	zone = zone_find_by_path(refstr_value(vfsp->vfs_mntpt));
3610 	ASSERT(zone != NULL);
3611 	/*
3612 	 * Special casing for the root vfs.  This structure is allocated
3613 	 * statically and hooked onto rootvfs at link time.  During the
3614 	 * vfs_mountroot call at system startup time, the root file system's
3615 	 * VFS_MOUNTROOT routine will call vfs_add with this root vfs struct
3616 	 * as argument.  The code below must detect and handle this special
3617 	 * case.  The only apparent justification for this special casing is
3618 	 * to ensure that the root file system appears at the head of the
3619 	 * list.
3620 	 *
3621 	 * XXX:	I'm assuming that it's ok to do normal list locking when
3622 	 *	adding the entry for the root file system (this used to be
3623 	 *	done with no locks held).
3624 	 */
3625 	vfs_list_lock();
3626 	/*
3627 	 * Link into the vfs list proper.
3628 	 */
3629 	if (vfsp == &root) {
3630 		/*
3631 		 * Assert: This vfs is already on the list as its first entry.
3632 		 * Thus, there's nothing to do.
3633 		 */
3634 		ASSERT(rootvfs == vfsp);
3635 		/*
3636 		 * Add it to the head of the global zone's vfslist.
3637 		 */
3638 		ASSERT(zone == global_zone);
3639 		ASSERT(zone->zone_vfslist == NULL);
3640 		zone->zone_vfslist = vfsp;
3641 	} else {
3642 		/*
3643 		 * Link to end of list using vfs_prev (as rootvfs is now a
3644 		 * doubly linked circular list) so list is in mount order for
3645 		 * mnttab use.
3646 		 */
3647 		rootvfs->vfs_prev->vfs_next = vfsp;
3648 		vfsp->vfs_prev = rootvfs->vfs_prev;
3649 		rootvfs->vfs_prev = vfsp;
3650 		vfsp->vfs_next = rootvfs;
3651 
3652 		/*
3653 		 * Do it again for the zone-private list (which may be NULL).
3654 		 */
3655 		if (zone->zone_vfslist == NULL) {
3656 			ASSERT(zone != global_zone);
3657 			zone->zone_vfslist = vfsp;
3658 		} else {
3659 			zone->zone_vfslist->vfs_zone_prev->vfs_zone_next = vfsp;
3660 			vfsp->vfs_zone_prev = zone->zone_vfslist->vfs_zone_prev;
3661 			zone->zone_vfslist->vfs_zone_prev = vfsp;
3662 			vfsp->vfs_zone_next = zone->zone_vfslist;
3663 		}
3664 	}
3665 
3666 	/*
3667 	 * Link into the hash table, inserting it at the end, so that LOFS
3668 	 * with the same fsid as UFS (or other) file systems will not hide
3669 	 * the UFS.
3670 	 */
3671 	vfs_hash_add(vfsp, 0);
3672 
3673 	/*
3674 	 * Link into tree indexed by mntpoint, for vfs_mntpoint2vfsp
3675 	 * mntix discerns entries with the same key
3676 	 */
3677 	vfsp->vfs_mntix = ++vfs_curr_mntix;
3678 	avl_add(&vfs_by_dev, vfsp);
3679 
3680 	/*
3681 	 * Link into tree indexed by dev, for vfs_devismounted
3682 	 */
3683 	avl_add(&vfs_by_mntpnt, vfsp);
3684 
3685 	/*
3686 	 * update the mnttab modification time
3687 	 */
3688 	vfs_mnttab_modtimeupd();
3689 	vfs_list_unlock();
3690 	zone_rele(zone);
3691 }
3692 
3693 void
3694 vfs_list_remove(struct vfs *vfsp)
3695 {
3696 	zone_t *zone;
3697 
3698 	zone = zone_find_by_path(refstr_value(vfsp->vfs_mntpt));
3699 	ASSERT(zone != NULL);
3700 	/*
3701 	 * Callers are responsible for preventing attempts to unmount the
3702 	 * root.
3703 	 */
3704 	ASSERT(vfsp != rootvfs);
3705 
3706 	vfs_list_lock();
3707 
3708 	/*
3709 	 * Remove from avl trees
3710 	 */
3711 	avl_remove(&vfs_by_mntpnt, vfsp);
3712 	avl_remove(&vfs_by_dev, vfsp);
3713 
3714 	/*
3715 	 * Remove from hash.
3716 	 */
3717 	vfs_hash_remove(vfsp);
3718 
3719 	/*
3720 	 * Remove from vfs list.
3721 	 */
3722 	vfsp->vfs_prev->vfs_next = vfsp->vfs_next;
3723 	vfsp->vfs_next->vfs_prev = vfsp->vfs_prev;
3724 	vfsp->vfs_next = vfsp->vfs_prev = NULL;
3725 
3726 	/*
3727 	 * Remove from zone-specific vfs list.
3728 	 */
3729 	if (zone->zone_vfslist == vfsp)
3730 		zone->zone_vfslist = vfsp->vfs_zone_next;
3731 
3732 	if (vfsp->vfs_zone_next == vfsp) {
3733 		ASSERT(vfsp->vfs_zone_prev == vfsp);
3734 		ASSERT(zone->zone_vfslist == vfsp);
3735 		zone->zone_vfslist = NULL;
3736 	}
3737 
3738 	vfsp->vfs_zone_prev->vfs_zone_next = vfsp->vfs_zone_next;
3739 	vfsp->vfs_zone_next->vfs_zone_prev = vfsp->vfs_zone_prev;
3740 	vfsp->vfs_zone_next = vfsp->vfs_zone_prev = NULL;
3741 
3742 	/*
3743 	 * update the mnttab modification time
3744 	 */
3745 	vfs_mnttab_modtimeupd();
3746 	vfs_list_unlock();
3747 	zone_rele(zone);
3748 }
3749 
3750 struct vfs *
3751 getvfs(fsid_t *fsid)
3752 {
3753 	struct vfs *vfsp;
3754 	int val0 = fsid->val[0];
3755 	int val1 = fsid->val[1];
3756 	dev_t dev = expldev(val0);
3757 	int vhno = VFSHASH(getmajor(dev), getminor(dev));
3758 	kmutex_t *hmp = &rvfs_list[vhno].rvfs_lock;
3759 
3760 	mutex_enter(hmp);
3761 	for (vfsp = rvfs_list[vhno].rvfs_head; vfsp; vfsp = vfsp->vfs_hash) {
3762 		if (vfsp->vfs_fsid.val[0] == val0 &&
3763 		    vfsp->vfs_fsid.val[1] == val1) {
3764 			VFS_HOLD(vfsp);
3765 			mutex_exit(hmp);
3766 			return (vfsp);
3767 		}
3768 	}
3769 	mutex_exit(hmp);
3770 	return (NULL);
3771 }
3772 
3773 /*
3774  * Search the vfs mount in progress list for a specified device/vfs entry.
3775  * Returns 0 if the first entry in the list that the device matches has the
3776  * given vfs pointer as well.  If the device matches but a different vfs
3777  * pointer is encountered in the list before the given vfs pointer then
3778  * a 1 is returned.
3779  */
3780 
3781 int
3782 vfs_devmounting(dev_t dev, struct vfs *vfsp)
3783 {
3784 	int retval = 0;
3785 	struct ipmnt *mipp;
3786 
3787 	mutex_enter(&vfs_miplist_mutex);
3788 	for (mipp = vfs_miplist; mipp != NULL; mipp = mipp->mip_next) {
3789 		if (mipp->mip_dev == dev) {
3790 			if (mipp->mip_vfsp != vfsp)
3791 				retval = 1;
3792 			break;
3793 		}
3794 	}
3795 	mutex_exit(&vfs_miplist_mutex);
3796 	return (retval);
3797 }
3798 
3799 /*
3800  * Search the vfs list for a specified device.  Returns 1, if entry is found
3801  * or 0 if no suitable entry is found.
3802  */
3803 
3804 int
3805 vfs_devismounted(dev_t dev)
3806 {
3807 	struct vfs *vfsp;
3808 	int found = 0;
3809 	struct vfs search;
3810 	avl_index_t index;
3811 
3812 	search.vfs_dev = dev;
3813 	search.vfs_mntix = 0;
3814 
3815 	vfs_list_read_lock();
3816 
3817 	/*
3818 	 * there might be several entries with the same dev in the tree,
3819 	 * only discerned by mntix. To find the first, we start with a mntix
3820 	 * of 0. The search will fail. The following avl_nearest will give
3821 	 * us the actual first entry.
3822 	 */
3823 	VERIFY(avl_find(&vfs_by_dev, &search, &index) == NULL);
3824 	vfsp = avl_nearest(&vfs_by_dev, index, AVL_AFTER);
3825 
3826 	if (vfsp != NULL && vfsp->vfs_dev == dev)
3827 		found = 1;
3828 
3829 	vfs_list_unlock();
3830 	return (found);
3831 }
3832 
3833 /*
3834  * Search the vfs list for a specified device.  Returns a pointer to it
3835  * or NULL if no suitable entry is found. The caller of this routine
3836  * is responsible for releasing the returned vfs pointer.
3837  */
3838 struct vfs *
3839 vfs_dev2vfsp(dev_t dev)
3840 {
3841 	struct vfs *vfsp;
3842 	int found;
3843 	struct vfs search;
3844 	avl_index_t index;
3845 
3846 	search.vfs_dev = dev;
3847 	search.vfs_mntix = 0;
3848 
3849 	vfs_list_read_lock();
3850 
3851 	/*
3852 	 * there might be several entries with the same dev in the tree,
3853 	 * only discerned by mntix. To find the first, we start with a mntix
3854 	 * of 0. The search will fail. The following avl_nearest will give
3855 	 * us the actual first entry.
3856 	 */
3857 	VERIFY(avl_find(&vfs_by_dev, &search, &index) == NULL);
3858 	vfsp = avl_nearest(&vfs_by_dev, index, AVL_AFTER);
3859 
3860 	found = 0;
3861 	while (vfsp != NULL && vfsp->vfs_dev == dev) {
3862 		/*
3863 		 * The following could be made more efficient by making
3864 		 * the entire loop use vfs_zone_next if the call is from
3865 		 * a zone.  The only callers, however, ustat(2) and
3866 		 * umount2(2), don't seem to justify the added
3867 		 * complexity at present.
3868 		 */
3869 		if (ZONE_PATH_VISIBLE(refstr_value(vfsp->vfs_mntpt),
3870 		    curproc->p_zone)) {
3871 			VFS_HOLD(vfsp);
3872 			found = 1;
3873 			break;
3874 		}
3875 		vfsp = AVL_NEXT(&vfs_by_dev, vfsp);
3876 	}
3877 	vfs_list_unlock();
3878 	return (found ? vfsp : NULL);
3879 }
3880 
3881 /*
3882  * Search the vfs list for a specified mntpoint.  Returns a pointer to it
3883  * or NULL if no suitable entry is found. The caller of this routine
3884  * is responsible for releasing the returned vfs pointer.
3885  *
3886  * Note that if multiple mntpoints match, the last one matching is
3887  * returned in an attempt to return the "top" mount when overlay
3888  * mounts are covering the same mount point.  This is accomplished by starting
3889  * at the end of the list and working our way backwards, stopping at the first
3890  * matching mount.
3891  */
3892 struct vfs *
3893 vfs_mntpoint2vfsp(const char *mp)
3894 {
3895 	struct vfs *vfsp;
3896 	struct vfs *retvfsp = NULL;
3897 	zone_t *zone = curproc->p_zone;
3898 	struct vfs *list;
3899 
3900 	vfs_list_read_lock();
3901 	if (getzoneid() == GLOBAL_ZONEID) {
3902 		/*
3903 		 * The global zone may see filesystems in any zone.
3904 		 */
3905 		struct vfs search;
3906 		search.vfs_mntpt = refstr_alloc(mp);
3907 		search.vfs_mntix = UINT64_MAX;
3908 		avl_index_t index;
3909 
3910 		/*
3911 		 * there might be several entries with the same mntpnt in the
3912 		 * tree, only discerned by mntix. To find the last, we start
3913 		 * with a mntix of UINT64_MAX. The search will fail. The
3914 		 * following avl_nearest will give  us the actual last entry
3915 		 * matching the mntpnt.
3916 		 */
3917 		VERIFY(avl_find(&vfs_by_mntpnt, &search, &index) == 0);
3918 		vfsp = avl_nearest(&vfs_by_mntpnt, index, AVL_BEFORE);
3919 
3920 		refstr_rele(search.vfs_mntpt);
3921 
3922 		if (vfsp != NULL &&
3923 		    strcmp(refstr_value(vfsp->vfs_mntpt), mp) == 0)
3924 			retvfsp = vfsp;
3925 	} else if ((list = zone->zone_vfslist) != NULL) {
3926 		const char *mntpt;
3927 
3928 		vfsp = list->vfs_zone_prev;
3929 		do {
3930 			mntpt = refstr_value(vfsp->vfs_mntpt);
3931 			mntpt = ZONE_PATH_TRANSLATE(mntpt, zone);
3932 			if (strcmp(mntpt, mp) == 0) {
3933 				retvfsp = vfsp;
3934 				break;
3935 			}
3936 			vfsp = vfsp->vfs_zone_prev;
3937 		} while (vfsp != list->vfs_zone_prev);
3938 	}
3939 	if (retvfsp)
3940 		VFS_HOLD(retvfsp);
3941 	vfs_list_unlock();
3942 	return (retvfsp);
3943 }
3944 
3945 /*
3946  * Search the vfs list for a specified vfsops.
3947  * if vfs entry is found then return 1, else 0.
3948  */
3949 int
3950 vfs_opsinuse(vfsops_t *ops)
3951 {
3952 	struct vfs *vfsp;
3953 	int found;
3954 
3955 	vfs_list_read_lock();
3956 	vfsp = rootvfs;
3957 	found = 0;
3958 	do {
3959 		if (vfs_getops(vfsp) == ops) {
3960 			found = 1;
3961 			break;
3962 		}
3963 		vfsp = vfsp->vfs_next;
3964 	} while (vfsp != rootvfs);
3965 	vfs_list_unlock();
3966 	return (found);
3967 }
3968 
3969 /*
3970  * Allocate an entry in vfssw for a file system type
3971  */
3972 struct vfssw *
3973 allocate_vfssw(const char *type)
3974 {
3975 	struct vfssw *vswp;
3976 
3977 	if (type[0] == '\0' || strlen(type) + 1 > _ST_FSTYPSZ) {
3978 		/*
3979 		 * The vfssw table uses the empty string to identify an
3980 		 * available entry; we cannot add any type which has
3981 		 * a leading NUL. The string length is limited to
3982 		 * the size of the st_fstype array in struct stat.
3983 		 */
3984 		return (NULL);
3985 	}
3986 
3987 	ASSERT(VFSSW_WRITE_LOCKED());
3988 	for (vswp = &vfssw[1]; vswp < &vfssw[nfstype]; vswp++)
3989 		if (!ALLOCATED_VFSSW(vswp)) {
3990 			vswp->vsw_name = kmem_alloc(strlen(type) + 1, KM_SLEEP);
3991 			(void) strcpy(vswp->vsw_name, type);
3992 			ASSERT(vswp->vsw_count == 0);
3993 			vswp->vsw_count = 1;
3994 			mutex_init(&vswp->vsw_lock, NULL, MUTEX_DEFAULT, NULL);
3995 			return (vswp);
3996 		}
3997 	return (NULL);
3998 }
3999 
4000 /*
4001  * Impose additional layer of translation between vfstype names
4002  * and module names in the filesystem.
4003  */
4004 static const char *
4005 vfs_to_modname(const char *vfstype)
4006 {
4007 	if (strcmp(vfstype, "proc") == 0) {
4008 		vfstype = "procfs";
4009 	} else if (strcmp(vfstype, "fd") == 0) {
4010 		vfstype = "fdfs";
4011 	} else if (strncmp(vfstype, "nfs", 3) == 0) {
4012 		vfstype = "nfs";
4013 	}
4014 
4015 	return (vfstype);
4016 }
4017 
4018 /*
4019  * Find a vfssw entry given a file system type name.
4020  * Try to autoload the filesystem if it's not found.
4021  * If it's installed, return the vfssw locked to prevent unloading.
4022  */
4023 struct vfssw *
4024 vfs_getvfssw(const char *type)
4025 {
4026 	struct vfssw *vswp;
4027 	const char *modname;
4028 
4029 	RLOCK_VFSSW();
4030 	vswp = vfs_getvfsswbyname(type);
4031 	modname = vfs_to_modname(type);
4032 
4033 	if (rootdir == NULL) {
4034 		/*
4035 		 * If we haven't yet loaded the root file system, then our
4036 		 * _init won't be called until later. Allocate vfssw entry,
4037 		 * because mod_installfs won't be called.
4038 		 */
4039 		if (vswp == NULL) {
4040 			RUNLOCK_VFSSW();
4041 			WLOCK_VFSSW();
4042 			if ((vswp = vfs_getvfsswbyname(type)) == NULL) {
4043 				if ((vswp = allocate_vfssw(type)) == NULL) {
4044 					WUNLOCK_VFSSW();
4045 					return (NULL);
4046 				}
4047 			}
4048 			WUNLOCK_VFSSW();
4049 			RLOCK_VFSSW();
4050 		}
4051 		if (!VFS_INSTALLED(vswp)) {
4052 			RUNLOCK_VFSSW();
4053 			(void) modloadonly("fs", modname);
4054 		} else
4055 			RUNLOCK_VFSSW();
4056 		return (vswp);
4057 	}
4058 
4059 	/*
4060 	 * Try to load the filesystem.  Before calling modload(), we drop
4061 	 * our lock on the VFS switch table, and pick it up after the
4062 	 * module is loaded.  However, there is a potential race:  the
4063 	 * module could be unloaded after the call to modload() completes
4064 	 * but before we pick up the lock and drive on.  Therefore,
4065 	 * we keep reloading the module until we've loaded the module
4066 	 * _and_ we have the lock on the VFS switch table.
4067 	 */
4068 	while (vswp == NULL || !VFS_INSTALLED(vswp)) {
4069 		RUNLOCK_VFSSW();
4070 		if (modload("fs", modname) == -1)
4071 			return (NULL);
4072 		RLOCK_VFSSW();
4073 		if (vswp == NULL)
4074 			if ((vswp = vfs_getvfsswbyname(type)) == NULL)
4075 				break;
4076 	}
4077 	RUNLOCK_VFSSW();
4078 
4079 	return (vswp);
4080 }
4081 
4082 /*
4083  * Find a vfssw entry given a file system type name.
4084  */
4085 struct vfssw *
4086 vfs_getvfsswbyname(const char *type)
4087 {
4088 	struct vfssw *vswp;
4089 
4090 	ASSERT(VFSSW_LOCKED());
4091 	if (type == NULL || *type == '\0')
4092 		return (NULL);
4093 
4094 	for (vswp = &vfssw[1]; vswp < &vfssw[nfstype]; vswp++) {
4095 		if (strcmp(type, vswp->vsw_name) == 0) {
4096 			vfs_refvfssw(vswp);
4097 			return (vswp);
4098 		}
4099 	}
4100 
4101 	return (NULL);
4102 }
4103 
4104 /*
4105  * Find a vfssw entry given a set of vfsops.
4106  */
4107 struct vfssw *
4108 vfs_getvfsswbyvfsops(vfsops_t *vfsops)
4109 {
4110 	struct vfssw *vswp;
4111 
4112 	RLOCK_VFSSW();
4113 	for (vswp = &vfssw[1]; vswp < &vfssw[nfstype]; vswp++) {
4114 		if (ALLOCATED_VFSSW(vswp) && &vswp->vsw_vfsops == vfsops) {
4115 			vfs_refvfssw(vswp);
4116 			RUNLOCK_VFSSW();
4117 			return (vswp);
4118 		}
4119 	}
4120 	RUNLOCK_VFSSW();
4121 
4122 	return (NULL);
4123 }
4124 
4125 /*
4126  * Reference a vfssw entry.
4127  */
4128 void
4129 vfs_refvfssw(struct vfssw *vswp)
4130 {
4131 
4132 	mutex_enter(&vswp->vsw_lock);
4133 	vswp->vsw_count++;
4134 	mutex_exit(&vswp->vsw_lock);
4135 }
4136 
4137 /*
4138  * Unreference a vfssw entry.
4139  */
4140 void
4141 vfs_unrefvfssw(struct vfssw *vswp)
4142 {
4143 
4144 	mutex_enter(&vswp->vsw_lock);
4145 	vswp->vsw_count--;
4146 	mutex_exit(&vswp->vsw_lock);
4147 }
4148 
4149 int sync_timeout = 30;		/* timeout for syncing a page during panic */
4150 int sync_timeleft;		/* portion of sync_timeout remaining */
4151 
4152 static int sync_retries = 20;	/* number of retries when not making progress */
4153 static int sync_triesleft;	/* portion of sync_retries remaining */
4154 
4155 static pgcnt_t old_pgcnt, new_pgcnt;
4156 static int new_bufcnt, old_bufcnt;
4157 
4158 /*
4159  * Sync all of the mounted filesystems, and then wait for the actual i/o to
4160  * complete.  We wait by counting the number of dirty pages and buffers,
4161  * pushing them out using bio_busy() and page_busy(), and then counting again.
4162  * This routine is used during both the uadmin A_SHUTDOWN code as well as
4163  * the SYNC phase of the panic code (see comments in panic.c).  It should only
4164  * be used after some higher-level mechanism has quiesced the system so that
4165  * new writes are not being initiated while we are waiting for completion.
4166  *
4167  * To ensure finite running time, our algorithm uses two timeout mechanisms:
4168  * sync_timeleft (a timer implemented by the omnipresent deadman() cyclic), and
4169  * sync_triesleft (a progress counter used by the vfs_syncall() loop below).
4170  * Together these ensure that syncing completes if our i/o paths are stuck.
4171  * The counters are declared above so they can be found easily in the debugger.
4172  *
4173  * The sync_timeleft counter is reset by bio_busy() and page_busy() using the
4174  * vfs_syncprogress() subroutine whenever we make progress through the lists of
4175  * pages and buffers.  It is decremented and expired by the deadman() cyclic.
4176  * When vfs_syncall() decides it is done, we disable the deadman() counter by
4177  * setting sync_timeleft to zero.  This timer guards against vfs_syncall()
4178  * deadlocking or hanging inside of a broken filesystem or driver routine.
4179  *
4180  * The sync_triesleft counter is updated by vfs_syncall() itself.  If we make
4181  * sync_retries consecutive calls to bio_busy() and page_busy() without
4182  * decreasing either the number of dirty buffers or dirty pages below the
4183  * lowest count we have seen so far, we give up and return from vfs_syncall().
4184  *
4185  * Each loop iteration ends with a call to delay() one second to allow time for
4186  * i/o completion and to permit the user time to read our progress messages.
4187  */
4188 void
4189 vfs_syncall(void)
4190 {
4191 	if (rootdir == NULL && !modrootloaded)
4192 		return; /* panic during boot - no filesystems yet */
4193 
4194 	printf("syncing file systems...");
4195 	vfs_syncprogress();
4196 	sync();
4197 
4198 	vfs_syncprogress();
4199 	sync_triesleft = sync_retries;
4200 
4201 	old_bufcnt = new_bufcnt = INT_MAX;
4202 	old_pgcnt = new_pgcnt = ULONG_MAX;
4203 
4204 	while (sync_triesleft > 0) {
4205 		old_bufcnt = MIN(old_bufcnt, new_bufcnt);
4206 		old_pgcnt = MIN(old_pgcnt, new_pgcnt);
4207 
4208 		new_bufcnt = bio_busy(B_TRUE);
4209 		new_pgcnt = page_busy(B_TRUE);
4210 		vfs_syncprogress();
4211 
4212 		if (new_bufcnt == 0 && new_pgcnt == 0)
4213 			break;
4214 
4215 		if (new_bufcnt < old_bufcnt || new_pgcnt < old_pgcnt)
4216 			sync_triesleft = sync_retries;
4217 		else
4218 			sync_triesleft--;
4219 
4220 		if (new_bufcnt)
4221 			printf(" [%d]", new_bufcnt);
4222 		if (new_pgcnt)
4223 			printf(" %lu", new_pgcnt);
4224 
4225 		delay(hz);
4226 	}
4227 
4228 	if (new_bufcnt != 0 || new_pgcnt != 0)
4229 		printf(" done (not all i/o completed)\n");
4230 	else
4231 		printf(" done\n");
4232 
4233 	sync_timeleft = 0;
4234 	delay(hz);
4235 }
4236 
4237 /*
4238  * If we are in the middle of the sync phase of panic, reset sync_timeleft to
4239  * sync_timeout to indicate that we are making progress and the deadman()
4240  * omnipresent cyclic should not yet time us out.  Note that it is safe to
4241  * store to sync_timeleft here since the deadman() is firing at high-level
4242  * on top of us.  If we are racing with the deadman(), either the deadman()
4243  * will decrement the old value and then we will reset it, or we will
4244  * reset it and then the deadman() will immediately decrement it.  In either
4245  * case, correct behavior results.
4246  */
4247 void
4248 vfs_syncprogress(void)
4249 {
4250 	if (panicstr)
4251 		sync_timeleft = sync_timeout;
4252 }
4253 
4254 /*
4255  * Map VFS flags to statvfs flags.  These shouldn't really be separate
4256  * flags at all.
4257  */
4258 uint_t
4259 vf_to_stf(uint_t vf)
4260 {
4261 	uint_t stf = 0;
4262 
4263 	if (vf & VFS_RDONLY)
4264 		stf |= ST_RDONLY;
4265 	if (vf & VFS_NOSETUID)
4266 		stf |= ST_NOSUID;
4267 	if (vf & VFS_NOTRUNC)
4268 		stf |= ST_NOTRUNC;
4269 
4270 	return (stf);
4271 }
4272 
4273 /*
4274  * Entries for (illegal) fstype 0.
4275  */
4276 /* ARGSUSED */
4277 int
4278 vfsstray_sync(struct vfs *vfsp, short arg, struct cred *cr)
4279 {
4280 	cmn_err(CE_PANIC, "stray vfs operation");
4281 	return (0);
4282 }
4283 
4284 /*
4285  * Entries for (illegal) fstype 0.
4286  */
4287 int
4288 vfsstray(void)
4289 {
4290 	cmn_err(CE_PANIC, "stray vfs operation");
4291 	return (0);
4292 }
4293 
4294 /*
4295  * Support for dealing with forced UFS unmount and its interaction with
4296  * LOFS. Could be used by any filesystem.
4297  * See bug 1203132.
4298  */
4299 int
4300 vfs_EIO(void)
4301 {
4302 	return (EIO);
4303 }
4304 
4305 /*
4306  * We've gotta define the op for sync separately, since the compiler gets
4307  * confused if we mix and match ANSI and normal style prototypes when
4308  * a "short" argument is present and spits out a warning.
4309  */
4310 /*ARGSUSED*/
4311 int
4312 vfs_EIO_sync(struct vfs *vfsp, short arg, struct cred *cr)
4313 {
4314 	return (EIO);
4315 }
4316 
4317 vfs_t EIO_vfs;
4318 vfsops_t *EIO_vfsops;
4319 
4320 /*
4321  * Called from startup() to initialize all loaded vfs's
4322  */
4323 void
4324 vfsinit(void)
4325 {
4326 	struct vfssw *vswp;
4327 	int error;
4328 	extern int vopstats_enabled;
4329 	extern void vopstats_startup();
4330 
4331 	static const fs_operation_def_t EIO_vfsops_template[] = {
4332 		VFSNAME_MOUNT,		{ .error = vfs_EIO },
4333 		VFSNAME_UNMOUNT,	{ .error = vfs_EIO },
4334 		VFSNAME_ROOT,		{ .error = vfs_EIO },
4335 		VFSNAME_STATVFS,	{ .error = vfs_EIO },
4336 		VFSNAME_SYNC, 		{ .vfs_sync = vfs_EIO_sync },
4337 		VFSNAME_VGET,		{ .error = vfs_EIO },
4338 		VFSNAME_MOUNTROOT,	{ .error = vfs_EIO },
4339 		VFSNAME_FREEVFS,	{ .error = vfs_EIO },
4340 		VFSNAME_VNSTATE,	{ .error = vfs_EIO },
4341 		NULL, NULL
4342 	};
4343 
4344 	static const fs_operation_def_t stray_vfsops_template[] = {
4345 		VFSNAME_MOUNT,		{ .error = vfsstray },
4346 		VFSNAME_UNMOUNT,	{ .error = vfsstray },
4347 		VFSNAME_ROOT,		{ .error = vfsstray },
4348 		VFSNAME_STATVFS,	{ .error = vfsstray },
4349 		VFSNAME_SYNC, 		{ .vfs_sync = vfsstray_sync },
4350 		VFSNAME_VGET,		{ .error = vfsstray },
4351 		VFSNAME_MOUNTROOT,	{ .error = vfsstray },
4352 		VFSNAME_FREEVFS,	{ .error = vfsstray },
4353 		VFSNAME_VNSTATE,	{ .error = vfsstray },
4354 		NULL, NULL
4355 	};
4356 
4357 	/* Create vfs cache */
4358 	vfs_cache = kmem_cache_create("vfs_cache", sizeof (struct vfs),
4359 	    sizeof (uintptr_t), NULL, NULL, NULL, NULL, NULL, 0);
4360 
4361 	/* Initialize the vnode cache (file systems may use it during init). */
4362 	vn_create_cache();
4363 
4364 	/* Setup event monitor framework */
4365 	fem_init();
4366 
4367 	/* Initialize the dummy stray file system type. */
4368 	error = vfs_setfsops(0, stray_vfsops_template, NULL);
4369 
4370 	/* Initialize the dummy EIO file system. */
4371 	error = vfs_makefsops(EIO_vfsops_template, &EIO_vfsops);
4372 	if (error != 0) {
4373 		cmn_err(CE_WARN, "vfsinit: bad EIO vfs ops template");
4374 		/* Shouldn't happen, but not bad enough to panic */
4375 	}
4376 
4377 	VFS_INIT(&EIO_vfs, EIO_vfsops, (caddr_t)NULL);
4378 
4379 	/*
4380 	 * Default EIO_vfs.vfs_flag to VFS_UNMOUNTED so a lookup
4381 	 * on this vfs can immediately notice it's invalid.
4382 	 */
4383 	EIO_vfs.vfs_flag |= VFS_UNMOUNTED;
4384 
4385 	/*
4386 	 * Call the init routines of non-loadable filesystems only.
4387 	 * Filesystems which are loaded as separate modules will be
4388 	 * initialized by the module loading code instead.
4389 	 */
4390 
4391 	for (vswp = &vfssw[1]; vswp < &vfssw[nfstype]; vswp++) {
4392 		RLOCK_VFSSW();
4393 		if (vswp->vsw_init != NULL)
4394 			(*vswp->vsw_init)(vswp - vfssw, vswp->vsw_name);
4395 		RUNLOCK_VFSSW();
4396 	}
4397 
4398 	vopstats_startup();
4399 
4400 	if (vopstats_enabled) {
4401 		/* EIO_vfs can collect stats, but we don't retrieve them */
4402 		initialize_vopstats(&EIO_vfs.vfs_vopstats);
4403 		EIO_vfs.vfs_fstypevsp = NULL;
4404 		EIO_vfs.vfs_vskap = NULL;
4405 		EIO_vfs.vfs_flag |= VFS_STATS;
4406 	}
4407 
4408 	xattr_init();
4409 
4410 	reparse_point_init();
4411 }
4412 
4413 vfs_t *
4414 vfs_alloc(int kmflag)
4415 {
4416 	vfs_t *vfsp;
4417 
4418 	vfsp = kmem_cache_alloc(vfs_cache, kmflag);
4419 
4420 	/*
4421 	 * Do the simplest initialization here.
4422 	 * Everything else gets done in vfs_init()
4423 	 */
4424 	bzero(vfsp, sizeof (vfs_t));
4425 	return (vfsp);
4426 }
4427 
4428 void
4429 vfs_free(vfs_t *vfsp)
4430 {
4431 	/*
4432 	 * One would be tempted to assert that "vfsp->vfs_count == 0".
4433 	 * The problem is that this gets called out of domount() with
4434 	 * a partially initialized vfs and a vfs_count of 1.  This is
4435 	 * also called from vfs_rele() with a vfs_count of 0.  We can't
4436 	 * call VFS_RELE() from domount() if VFS_MOUNT() hasn't successfully
4437 	 * returned.  This is because VFS_MOUNT() fully initializes the
4438 	 * vfs structure and its associated data.  VFS_RELE() will call
4439 	 * VFS_FREEVFS() which may panic the system if the data structures
4440 	 * aren't fully initialized from a successful VFS_MOUNT()).
4441 	 */
4442 
4443 	/* If FEM was in use, make sure everything gets cleaned up */
4444 	if (vfsp->vfs_femhead) {
4445 		ASSERT(vfsp->vfs_femhead->femh_list == NULL);
4446 		mutex_destroy(&vfsp->vfs_femhead->femh_lock);
4447 		kmem_free(vfsp->vfs_femhead, sizeof (*(vfsp->vfs_femhead)));
4448 		vfsp->vfs_femhead = NULL;
4449 	}
4450 
4451 	if (vfsp->vfs_implp)
4452 		vfsimpl_teardown(vfsp);
4453 	sema_destroy(&vfsp->vfs_reflock);
4454 	kmem_cache_free(vfs_cache, vfsp);
4455 }
4456 
4457 /*
4458  * Increments the vfs reference count by one atomically.
4459  */
4460 void
4461 vfs_hold(vfs_t *vfsp)
4462 {
4463 	atomic_inc_32(&vfsp->vfs_count);
4464 	ASSERT(vfsp->vfs_count != 0);
4465 }
4466 
4467 /*
4468  * Decrements the vfs reference count by one atomically. When
4469  * vfs reference count becomes zero, it calls the file system
4470  * specific vfs_freevfs() to free up the resources.
4471  */
4472 void
4473 vfs_rele(vfs_t *vfsp)
4474 {
4475 	ASSERT(vfsp->vfs_count != 0);
4476 	if (atomic_dec_32_nv(&vfsp->vfs_count) == 0) {
4477 		VFS_FREEVFS(vfsp);
4478 		lofi_remove(vfsp);
4479 		if (vfsp->vfs_zone)
4480 			zone_rele_ref(&vfsp->vfs_implp->vi_zone_ref,
4481 			    ZONE_REF_VFS);
4482 		vfs_freemnttab(vfsp);
4483 		vfs_free(vfsp);
4484 	}
4485 }
4486 
4487 /*
4488  * Generic operations vector support.
4489  *
4490  * This is used to build operations vectors for both the vfs and vnode.
4491  * It's normally called only when a file system is loaded.
4492  *
4493  * There are many possible algorithms for this, including the following:
4494  *
4495  *   (1) scan the list of known operations; for each, see if the file system
4496  *       includes an entry for it, and fill it in as appropriate.
4497  *
4498  *   (2) set up defaults for all known operations.  scan the list of ops
4499  *       supplied by the file system; for each which is both supplied and
4500  *       known, fill it in.
4501  *
4502  *   (3) sort the lists of known ops & supplied ops; scan the list, filling
4503  *       in entries as we go.
4504  *
4505  * we choose (1) for simplicity, and because performance isn't critical here.
4506  * note that (2) could be sped up using a precomputed hash table on known ops.
4507  * (3) could be faster than either, but only if the lists were very large or
4508  * supplied in sorted order.
4509  *
4510  */
4511 
4512 int
4513 fs_build_vector(void *vector, int *unused_ops,
4514     const fs_operation_trans_def_t *translation,
4515     const fs_operation_def_t *operations)
4516 {
4517 	int i, num_trans, num_ops, used;
4518 
4519 	/*
4520 	 * Count the number of translations and the number of supplied
4521 	 * operations.
4522 	 */
4523 
4524 	{
4525 		const fs_operation_trans_def_t *p;
4526 
4527 		for (num_trans = 0, p = translation;
4528 		    p->name != NULL;
4529 		    num_trans++, p++)
4530 			;
4531 	}
4532 
4533 	{
4534 		const fs_operation_def_t *p;
4535 
4536 		for (num_ops = 0, p = operations;
4537 		    p->name != NULL;
4538 		    num_ops++, p++)
4539 			;
4540 	}
4541 
4542 	/* Walk through each operation known to our caller.  There will be */
4543 	/* one entry in the supplied "translation table" for each. */
4544 
4545 	used = 0;
4546 
4547 	for (i = 0; i < num_trans; i++) {
4548 		int j, found;
4549 		char *curname;
4550 		fs_generic_func_p result;
4551 		fs_generic_func_p *location;
4552 
4553 		curname = translation[i].name;
4554 
4555 		/* Look for a matching operation in the list supplied by the */
4556 		/* file system. */
4557 
4558 		found = 0;
4559 
4560 		for (j = 0; j < num_ops; j++) {
4561 			if (strcmp(operations[j].name, curname) == 0) {
4562 				used++;
4563 				found = 1;
4564 				break;
4565 			}
4566 		}
4567 
4568 		/*
4569 		 * If the file system is using a "placeholder" for default
4570 		 * or error functions, grab the appropriate function out of
4571 		 * the translation table.  If the file system didn't supply
4572 		 * this operation at all, use the default function.
4573 		 */
4574 
4575 		if (found) {
4576 			result = operations[j].func.fs_generic;
4577 			if (result == fs_default) {
4578 				result = translation[i].defaultFunc;
4579 			} else if (result == fs_error) {
4580 				result = translation[i].errorFunc;
4581 			} else if (result == NULL) {
4582 				/* Null values are PROHIBITED */
4583 				return (EINVAL);
4584 			}
4585 		} else {
4586 			result = translation[i].defaultFunc;
4587 		}
4588 
4589 		/* Now store the function into the operations vector. */
4590 
4591 		location = (fs_generic_func_p *)
4592 		    (((char *)vector) + translation[i].offset);
4593 
4594 		*location = result;
4595 	}
4596 
4597 	*unused_ops = num_ops - used;
4598 
4599 	return (0);
4600 }
4601 
4602 /* Placeholder functions, should never be called. */
4603 
4604 int
4605 fs_error(void)
4606 {
4607 	cmn_err(CE_PANIC, "fs_error called");
4608 	return (0);
4609 }
4610 
4611 int
4612 fs_default(void)
4613 {
4614 	cmn_err(CE_PANIC, "fs_default called");
4615 	return (0);
4616 }
4617 
4618 #ifdef __sparc
4619 
4620 /*
4621  * Part of the implementation of booting off a mirrored root
4622  * involves a change of dev_t for the root device.  To
4623  * accomplish this, first remove the existing hash table
4624  * entry for the root device, convert to the new dev_t,
4625  * then re-insert in the hash table at the head of the list.
4626  */
4627 void
4628 vfs_root_redev(vfs_t *vfsp, dev_t ndev, int fstype)
4629 {
4630 	vfs_list_lock();
4631 
4632 	vfs_hash_remove(vfsp);
4633 
4634 	vfsp->vfs_dev = ndev;
4635 	vfs_make_fsid(&vfsp->vfs_fsid, ndev, fstype);
4636 
4637 	vfs_hash_add(vfsp, 1);
4638 
4639 	vfs_list_unlock();
4640 }
4641 
4642 #else /* x86 NEWBOOT */
4643 
4644 #if defined(__x86)
4645 extern int hvmboot_rootconf();
4646 #endif /* __x86 */
4647 
4648 extern ib_boot_prop_t *iscsiboot_prop;
4649 
4650 int
4651 rootconf()
4652 {
4653 	int error;
4654 	struct vfssw *vsw;
4655 	extern void pm_init();
4656 	char *fstyp, *fsmod;
4657 	int ret = -1;
4658 
4659 	getrootfs(&fstyp, &fsmod);
4660 
4661 #if defined(__x86)
4662 	/*
4663 	 * hvmboot_rootconf() is defined in the hvm_bootstrap misc module,
4664 	 * which lives in /platform/i86hvm, and hence is only available when
4665 	 * booted in an x86 hvm environment.  If the hvm_bootstrap misc module
4666 	 * is not available then the modstub for this function will return 0.
4667 	 * If the hvm_bootstrap misc module is available it will be loaded
4668 	 * and hvmboot_rootconf() will be invoked.
4669 	 */
4670 	if (error = hvmboot_rootconf())
4671 		return (error);
4672 #endif /* __x86 */
4673 
4674 	if (error = clboot_rootconf())
4675 		return (error);
4676 
4677 	if (modload("fs", fsmod) == -1)
4678 		panic("Cannot _init %s module", fsmod);
4679 
4680 	RLOCK_VFSSW();
4681 	vsw = vfs_getvfsswbyname(fstyp);
4682 	RUNLOCK_VFSSW();
4683 	if (vsw == NULL) {
4684 		cmn_err(CE_CONT, "Cannot find %s filesystem\n", fstyp);
4685 		return (ENXIO);
4686 	}
4687 	VFS_INIT(rootvfs, &vsw->vsw_vfsops, 0);
4688 	VFS_HOLD(rootvfs);
4689 
4690 	/* always mount readonly first */
4691 	rootvfs->vfs_flag |= VFS_RDONLY;
4692 
4693 	pm_init();
4694 
4695 	if (netboot && iscsiboot_prop) {
4696 		cmn_err(CE_WARN, "NFS boot and iSCSI boot"
4697 		    " shouldn't happen in the same time");
4698 		return (EINVAL);
4699 	}
4700 
4701 	if (netboot || iscsiboot_prop) {
4702 		ret = strplumb();
4703 		if (ret != 0) {
4704 			cmn_err(CE_WARN, "Cannot plumb network device %d", ret);
4705 			return (EFAULT);
4706 		}
4707 	}
4708 
4709 	if ((ret == 0) && iscsiboot_prop) {
4710 		ret = modload("drv", "iscsi");
4711 		/* -1 indicates fail */
4712 		if (ret == -1) {
4713 			cmn_err(CE_WARN, "Failed to load iscsi module");
4714 			iscsi_boot_prop_free();
4715 			return (EINVAL);
4716 		} else {
4717 			if (!i_ddi_attach_pseudo_node("iscsi")) {
4718 				cmn_err(CE_WARN,
4719 				    "Failed to attach iscsi driver");
4720 				iscsi_boot_prop_free();
4721 				return (ENODEV);
4722 			}
4723 		}
4724 	}
4725 
4726 	error = VFS_MOUNTROOT(rootvfs, ROOT_INIT);
4727 	vfs_unrefvfssw(vsw);
4728 	rootdev = rootvfs->vfs_dev;
4729 
4730 	if (error)
4731 		cmn_err(CE_CONT, "Cannot mount root on %s fstype %s\n",
4732 		    rootfs.bo_name, fstyp);
4733 	else
4734 		cmn_err(CE_CONT, "?root on %s fstype %s\n",
4735 		    rootfs.bo_name, fstyp);
4736 	return (error);
4737 }
4738 
4739 /*
4740  * XXX this is called by nfs only and should probably be removed
4741  * If booted with ASKNAME, prompt on the console for a filesystem
4742  * name and return it.
4743  */
4744 void
4745 getfsname(char *askfor, char *name, size_t namelen)
4746 {
4747 	if (boothowto & RB_ASKNAME) {
4748 		printf("%s name: ", askfor);
4749 		console_gets(name, namelen);
4750 	}
4751 }
4752 
4753 /*
4754  * Init the root filesystem type (rootfs.bo_fstype) from the "fstype"
4755  * property.
4756  *
4757  * Filesystem types starting with the prefix "nfs" are diskless clients;
4758  * init the root filename name (rootfs.bo_name), too.
4759  *
4760  * If we are booting via NFS we currently have these options:
4761  *	nfs -	dynamically choose NFS V2, V3, or V4 (default)
4762  *	nfs2 -	force NFS V2
4763  *	nfs3 -	force NFS V3
4764  *	nfs4 -	force NFS V4
4765  * Because we need to maintain backward compatibility with the naming
4766  * convention that the NFS V2 filesystem name is "nfs" (see vfs_conf.c)
4767  * we need to map "nfs" => "nfsdyn" and "nfs2" => "nfs".  The dynamic
4768  * nfs module will map the type back to either "nfs", "nfs3", or "nfs4".
4769  * This is only for root filesystems, all other uses will expect
4770  * that "nfs" == NFS V2.
4771  */
4772 static void
4773 getrootfs(char **fstypp, char **fsmodp)
4774 {
4775 	extern char *strplumb_get_netdev_path(void);
4776 	char *propstr = NULL;
4777 
4778 	/*
4779 	 * Check fstype property; for diskless it should be one of "nfs",
4780 	 * "nfs2", "nfs3" or "nfs4".
4781 	 */
4782 	if (ddi_prop_lookup_string(DDI_DEV_T_ANY, ddi_root_node(),
4783 	    DDI_PROP_DONTPASS, "fstype", &propstr)
4784 	    == DDI_SUCCESS) {
4785 		(void) strncpy(rootfs.bo_fstype, propstr, BO_MAXFSNAME);
4786 		ddi_prop_free(propstr);
4787 
4788 	/*
4789 	 * if the boot property 'fstype' is not set, but 'zfs-bootfs' is set,
4790 	 * assume the type of this root filesystem is 'zfs'.
4791 	 */
4792 	} else if (ddi_prop_lookup_string(DDI_DEV_T_ANY, ddi_root_node(),
4793 	    DDI_PROP_DONTPASS, "zfs-bootfs", &propstr)
4794 	    == DDI_SUCCESS) {
4795 		(void) strncpy(rootfs.bo_fstype, "zfs", BO_MAXFSNAME);
4796 		ddi_prop_free(propstr);
4797 	}
4798 
4799 	if (strncmp(rootfs.bo_fstype, "nfs", 3) != 0) {
4800 		*fstypp = *fsmodp = rootfs.bo_fstype;
4801 		return;
4802 	}
4803 
4804 	++netboot;
4805 
4806 	if (strcmp(rootfs.bo_fstype, "nfs2") == 0)
4807 		(void) strcpy(rootfs.bo_fstype, "nfs");
4808 	else if (strcmp(rootfs.bo_fstype, "nfs") == 0)
4809 		(void) strcpy(rootfs.bo_fstype, "nfsdyn");
4810 
4811 	/*
4812 	 * check if path to network interface is specified in bootpath
4813 	 * or by a hypervisor domain configuration file.
4814 	 * XXPV - enable strlumb_get_netdev_path()
4815 	 */
4816 	if (ddi_prop_exists(DDI_DEV_T_ANY, ddi_root_node(), DDI_PROP_DONTPASS,
4817 	    "xpv-nfsroot")) {
4818 		(void) strcpy(rootfs.bo_name, "/xpvd/xnf@0");
4819 	} else if (ddi_prop_lookup_string(DDI_DEV_T_ANY, ddi_root_node(),
4820 	    DDI_PROP_DONTPASS, "bootpath", &propstr)
4821 	    == DDI_SUCCESS) {
4822 		(void) strncpy(rootfs.bo_name, propstr, BO_MAXOBJNAME);
4823 		ddi_prop_free(propstr);
4824 	} else {
4825 		/* attempt to determine netdev_path via boot_mac address */
4826 		netdev_path = strplumb_get_netdev_path();
4827 		if (netdev_path == NULL)
4828 			panic("cannot find boot network interface");
4829 		(void) strncpy(rootfs.bo_name, netdev_path, BO_MAXOBJNAME);
4830 	}
4831 	*fstypp = rootfs.bo_fstype;
4832 	*fsmodp = "nfs";
4833 }
4834 #endif
4835 
4836 /*
4837  * VFS feature routines
4838  */
4839 
4840 #define	VFTINDEX(feature)	(((feature) >> 32) & 0xFFFFFFFF)
4841 #define	VFTBITS(feature)	((feature) & 0xFFFFFFFFLL)
4842 
4843 /* Register a feature in the vfs */
4844 void
4845 vfs_set_feature(vfs_t *vfsp, vfs_feature_t feature)
4846 {
4847 	/* Note that vfs_featureset[] is found in *vfsp->vfs_implp */
4848 	if (vfsp->vfs_implp == NULL)
4849 		return;
4850 
4851 	vfsp->vfs_featureset[VFTINDEX(feature)] |= VFTBITS(feature);
4852 }
4853 
4854 void
4855 vfs_clear_feature(vfs_t *vfsp, vfs_feature_t feature)
4856 {
4857 	/* Note that vfs_featureset[] is found in *vfsp->vfs_implp */
4858 	if (vfsp->vfs_implp == NULL)
4859 		return;
4860 	vfsp->vfs_featureset[VFTINDEX(feature)] &= VFTBITS(~feature);
4861 }
4862 
4863 /*
4864  * Query a vfs for a feature.
4865  * Returns 1 if feature is present, 0 if not
4866  */
4867 int
4868 vfs_has_feature(vfs_t *vfsp, vfs_feature_t feature)
4869 {
4870 	int	ret = 0;
4871 
4872 	/* Note that vfs_featureset[] is found in *vfsp->vfs_implp */
4873 	if (vfsp->vfs_implp == NULL)
4874 		return (ret);
4875 
4876 	if (vfsp->vfs_featureset[VFTINDEX(feature)] & VFTBITS(feature))
4877 		ret = 1;
4878 
4879 	return (ret);
4880 }
4881 
4882 /*
4883  * Propagate feature set from one vfs to another
4884  */
4885 void
4886 vfs_propagate_features(vfs_t *from, vfs_t *to)
4887 {
4888 	int i;
4889 
4890 	if (to->vfs_implp == NULL || from->vfs_implp == NULL)
4891 		return;
4892 
4893 	for (i = 1; i <= to->vfs_featureset[0]; i++) {
4894 		to->vfs_featureset[i] = from->vfs_featureset[i];
4895 	}
4896 }
4897 
4898 #define	LOFINODE_PATH "/dev/lofi/%d"
4899 
4900 /*
4901  * Return the vnode for the lofi node if there's a lofi mount in place.
4902  * Returns -1 when there's no lofi node, 0 on success, and > 0 on
4903  * failure.
4904  */
4905 int
4906 vfs_get_lofi(vfs_t *vfsp, vnode_t **vpp)
4907 {
4908 	char *path = NULL;
4909 	int strsize;
4910 	int err;
4911 
4912 	if (vfsp->vfs_lofi_minor == 0) {
4913 		*vpp = NULL;
4914 		return (-1);
4915 	}
4916 
4917 	strsize = snprintf(NULL, 0, LOFINODE_PATH, vfsp->vfs_lofi_minor);
4918 	path = kmem_alloc(strsize + 1, KM_SLEEP);
4919 	(void) snprintf(path, strsize + 1, LOFINODE_PATH, vfsp->vfs_lofi_minor);
4920 
4921 	/*
4922 	 * We may be inside a zone, so we need to use the /dev path, but
4923 	 * it's created asynchronously, so we wait here.
4924 	 */
4925 	for (;;) {
4926 		err = lookupname(path, UIO_SYSSPACE, FOLLOW, NULLVPP, vpp);
4927 
4928 		if (err != ENOENT)
4929 			break;
4930 
4931 		if ((err = delay_sig(hz / 8)) == EINTR)
4932 			break;
4933 	}
4934 
4935 	if (err)
4936 		*vpp = NULL;
4937 
4938 	kmem_free(path, strsize + 1);
4939 	return (err);
4940 }
4941