xref: /illumos-gate/usr/src/uts/common/fs/zfs/zfs_vfsops.c (revision 27dd1e87cd3d939264769dd4af7e6a529cde001f)
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) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
23  */
24 
25 #include <sys/types.h>
26 #include <sys/param.h>
27 #include <sys/systm.h>
28 #include <sys/sysmacros.h>
29 #include <sys/kmem.h>
30 #include <sys/pathname.h>
31 #include <sys/vnode.h>
32 #include <sys/vfs.h>
33 #include <sys/vfs_opreg.h>
34 #include <sys/mntent.h>
35 #include <sys/mount.h>
36 #include <sys/cmn_err.h>
37 #include "fs/fs_subr.h"
38 #include <sys/zfs_znode.h>
39 #include <sys/zfs_dir.h>
40 #include <sys/zil.h>
41 #include <sys/fs/zfs.h>
42 #include <sys/dmu.h>
43 #include <sys/dsl_prop.h>
44 #include <sys/dsl_dataset.h>
45 #include <sys/dsl_deleg.h>
46 #include <sys/spa.h>
47 #include <sys/zap.h>
48 #include <sys/sa.h>
49 #include <sys/varargs.h>
50 #include <sys/policy.h>
51 #include <sys/atomic.h>
52 #include <sys/mkdev.h>
53 #include <sys/modctl.h>
54 #include <sys/refstr.h>
55 #include <sys/zfs_ioctl.h>
56 #include <sys/zfs_ctldir.h>
57 #include <sys/zfs_fuid.h>
58 #include <sys/bootconf.h>
59 #include <sys/sunddi.h>
60 #include <sys/dnlc.h>
61 #include <sys/dmu_objset.h>
62 #include <sys/spa_boot.h>
63 #include <sys/sa.h>
64 #include "zfs_comutil.h"
65 
66 int zfsfstype;
67 vfsops_t *zfs_vfsops = NULL;
68 static major_t zfs_major;
69 static minor_t zfs_minor;
70 static kmutex_t	zfs_dev_mtx;
71 
72 extern int sys_shutdown;
73 
74 static int zfs_mount(vfs_t *vfsp, vnode_t *mvp, struct mounta *uap, cred_t *cr);
75 static int zfs_umount(vfs_t *vfsp, int fflag, cred_t *cr);
76 static int zfs_mountroot(vfs_t *vfsp, enum whymountroot);
77 static int zfs_root(vfs_t *vfsp, vnode_t **vpp);
78 static int zfs_statvfs(vfs_t *vfsp, struct statvfs64 *statp);
79 static int zfs_vget(vfs_t *vfsp, vnode_t **vpp, fid_t *fidp);
80 static void zfs_freevfs(vfs_t *vfsp);
81 
82 static const fs_operation_def_t zfs_vfsops_template[] = {
83 	VFSNAME_MOUNT,		{ .vfs_mount = zfs_mount },
84 	VFSNAME_MOUNTROOT,	{ .vfs_mountroot = zfs_mountroot },
85 	VFSNAME_UNMOUNT,	{ .vfs_unmount = zfs_umount },
86 	VFSNAME_ROOT,		{ .vfs_root = zfs_root },
87 	VFSNAME_STATVFS,	{ .vfs_statvfs = zfs_statvfs },
88 	VFSNAME_SYNC,		{ .vfs_sync = zfs_sync },
89 	VFSNAME_VGET,		{ .vfs_vget = zfs_vget },
90 	VFSNAME_FREEVFS,	{ .vfs_freevfs = zfs_freevfs },
91 	NULL,			NULL
92 };
93 
94 static const fs_operation_def_t zfs_vfsops_eio_template[] = {
95 	VFSNAME_FREEVFS,	{ .vfs_freevfs =  zfs_freevfs },
96 	NULL,			NULL
97 };
98 
99 /*
100  * We need to keep a count of active fs's.
101  * This is necessary to prevent our module
102  * from being unloaded after a umount -f
103  */
104 static uint32_t	zfs_active_fs_count = 0;
105 
106 static char *noatime_cancel[] = { MNTOPT_ATIME, NULL };
107 static char *atime_cancel[] = { MNTOPT_NOATIME, NULL };
108 static char *noxattr_cancel[] = { MNTOPT_XATTR, NULL };
109 static char *xattr_cancel[] = { MNTOPT_NOXATTR, NULL };
110 
111 /*
112  * MO_DEFAULT is not used since the default value is determined
113  * by the equivalent property.
114  */
115 static mntopt_t mntopts[] = {
116 	{ MNTOPT_NOXATTR, noxattr_cancel, NULL, 0, NULL },
117 	{ MNTOPT_XATTR, xattr_cancel, NULL, 0, NULL },
118 	{ MNTOPT_NOATIME, noatime_cancel, NULL, 0, NULL },
119 	{ MNTOPT_ATIME, atime_cancel, NULL, 0, NULL }
120 };
121 
122 static mntopts_t zfs_mntopts = {
123 	sizeof (mntopts) / sizeof (mntopt_t),
124 	mntopts
125 };
126 
127 /*ARGSUSED*/
128 int
129 zfs_sync(vfs_t *vfsp, short flag, cred_t *cr)
130 {
131 	/*
132 	 * Data integrity is job one.  We don't want a compromised kernel
133 	 * writing to the storage pool, so we never sync during panic.
134 	 */
135 	if (panicstr)
136 		return (0);
137 
138 	/*
139 	 * SYNC_ATTR is used by fsflush() to force old filesystems like UFS
140 	 * to sync metadata, which they would otherwise cache indefinitely.
141 	 * Semantically, the only requirement is that the sync be initiated.
142 	 * The DMU syncs out txgs frequently, so there's nothing to do.
143 	 */
144 	if (flag & SYNC_ATTR)
145 		return (0);
146 
147 	if (vfsp != NULL) {
148 		/*
149 		 * Sync a specific filesystem.
150 		 */
151 		zfsvfs_t *zfsvfs = vfsp->vfs_data;
152 		dsl_pool_t *dp;
153 
154 		ZFS_ENTER(zfsvfs);
155 		dp = dmu_objset_pool(zfsvfs->z_os);
156 
157 		/*
158 		 * If the system is shutting down, then skip any
159 		 * filesystems which may exist on a suspended pool.
160 		 */
161 		if (sys_shutdown && spa_suspended(dp->dp_spa)) {
162 			ZFS_EXIT(zfsvfs);
163 			return (0);
164 		}
165 
166 		if (zfsvfs->z_log != NULL)
167 			zil_commit(zfsvfs->z_log, UINT64_MAX, 0);
168 		else
169 			txg_wait_synced(dp, 0);
170 		ZFS_EXIT(zfsvfs);
171 	} else {
172 		/*
173 		 * Sync all ZFS filesystems.  This is what happens when you
174 		 * run sync(1M).  Unlike other filesystems, ZFS honors the
175 		 * request by waiting for all pools to commit all dirty data.
176 		 */
177 		spa_sync_allpools();
178 	}
179 
180 	return (0);
181 }
182 
183 static int
184 zfs_create_unique_device(dev_t *dev)
185 {
186 	major_t new_major;
187 
188 	do {
189 		ASSERT3U(zfs_minor, <=, MAXMIN32);
190 		minor_t start = zfs_minor;
191 		do {
192 			mutex_enter(&zfs_dev_mtx);
193 			if (zfs_minor >= MAXMIN32) {
194 				/*
195 				 * If we're still using the real major
196 				 * keep out of /dev/zfs and /dev/zvol minor
197 				 * number space.  If we're using a getudev()'ed
198 				 * major number, we can use all of its minors.
199 				 */
200 				if (zfs_major == ddi_name_to_major(ZFS_DRIVER))
201 					zfs_minor = ZFS_MIN_MINOR;
202 				else
203 					zfs_minor = 0;
204 			} else {
205 				zfs_minor++;
206 			}
207 			*dev = makedevice(zfs_major, zfs_minor);
208 			mutex_exit(&zfs_dev_mtx);
209 		} while (vfs_devismounted(*dev) && zfs_minor != start);
210 		if (zfs_minor == start) {
211 			/*
212 			 * We are using all ~262,000 minor numbers for the
213 			 * current major number.  Create a new major number.
214 			 */
215 			if ((new_major = getudev()) == (major_t)-1) {
216 				cmn_err(CE_WARN,
217 				    "zfs_mount: Can't get unique major "
218 				    "device number.");
219 				return (-1);
220 			}
221 			mutex_enter(&zfs_dev_mtx);
222 			zfs_major = new_major;
223 			zfs_minor = 0;
224 
225 			mutex_exit(&zfs_dev_mtx);
226 		} else {
227 			break;
228 		}
229 		/* CONSTANTCONDITION */
230 	} while (1);
231 
232 	return (0);
233 }
234 
235 static void
236 atime_changed_cb(void *arg, uint64_t newval)
237 {
238 	zfsvfs_t *zfsvfs = arg;
239 
240 	if (newval == TRUE) {
241 		zfsvfs->z_atime = TRUE;
242 		vfs_clearmntopt(zfsvfs->z_vfs, MNTOPT_NOATIME);
243 		vfs_setmntopt(zfsvfs->z_vfs, MNTOPT_ATIME, NULL, 0);
244 	} else {
245 		zfsvfs->z_atime = FALSE;
246 		vfs_clearmntopt(zfsvfs->z_vfs, MNTOPT_ATIME);
247 		vfs_setmntopt(zfsvfs->z_vfs, MNTOPT_NOATIME, NULL, 0);
248 	}
249 }
250 
251 static void
252 xattr_changed_cb(void *arg, uint64_t newval)
253 {
254 	zfsvfs_t *zfsvfs = arg;
255 
256 	if (newval == TRUE) {
257 		/* XXX locking on vfs_flag? */
258 		zfsvfs->z_vfs->vfs_flag |= VFS_XATTR;
259 		vfs_clearmntopt(zfsvfs->z_vfs, MNTOPT_NOXATTR);
260 		vfs_setmntopt(zfsvfs->z_vfs, MNTOPT_XATTR, NULL, 0);
261 	} else {
262 		/* XXX locking on vfs_flag? */
263 		zfsvfs->z_vfs->vfs_flag &= ~VFS_XATTR;
264 		vfs_clearmntopt(zfsvfs->z_vfs, MNTOPT_XATTR);
265 		vfs_setmntopt(zfsvfs->z_vfs, MNTOPT_NOXATTR, NULL, 0);
266 	}
267 }
268 
269 static void
270 blksz_changed_cb(void *arg, uint64_t newval)
271 {
272 	zfsvfs_t *zfsvfs = arg;
273 
274 	if (newval < SPA_MINBLOCKSIZE ||
275 	    newval > SPA_MAXBLOCKSIZE || !ISP2(newval))
276 		newval = SPA_MAXBLOCKSIZE;
277 
278 	zfsvfs->z_max_blksz = newval;
279 	zfsvfs->z_vfs->vfs_bsize = newval;
280 }
281 
282 static void
283 readonly_changed_cb(void *arg, uint64_t newval)
284 {
285 	zfsvfs_t *zfsvfs = arg;
286 
287 	if (newval) {
288 		/* XXX locking on vfs_flag? */
289 		zfsvfs->z_vfs->vfs_flag |= VFS_RDONLY;
290 		vfs_clearmntopt(zfsvfs->z_vfs, MNTOPT_RW);
291 		vfs_setmntopt(zfsvfs->z_vfs, MNTOPT_RO, NULL, 0);
292 	} else {
293 		/* XXX locking on vfs_flag? */
294 		zfsvfs->z_vfs->vfs_flag &= ~VFS_RDONLY;
295 		vfs_clearmntopt(zfsvfs->z_vfs, MNTOPT_RO);
296 		vfs_setmntopt(zfsvfs->z_vfs, MNTOPT_RW, NULL, 0);
297 	}
298 }
299 
300 static void
301 devices_changed_cb(void *arg, uint64_t newval)
302 {
303 	zfsvfs_t *zfsvfs = arg;
304 
305 	if (newval == FALSE) {
306 		zfsvfs->z_vfs->vfs_flag |= VFS_NODEVICES;
307 		vfs_clearmntopt(zfsvfs->z_vfs, MNTOPT_DEVICES);
308 		vfs_setmntopt(zfsvfs->z_vfs, MNTOPT_NODEVICES, NULL, 0);
309 	} else {
310 		zfsvfs->z_vfs->vfs_flag &= ~VFS_NODEVICES;
311 		vfs_clearmntopt(zfsvfs->z_vfs, MNTOPT_NODEVICES);
312 		vfs_setmntopt(zfsvfs->z_vfs, MNTOPT_DEVICES, NULL, 0);
313 	}
314 }
315 
316 static void
317 setuid_changed_cb(void *arg, uint64_t newval)
318 {
319 	zfsvfs_t *zfsvfs = arg;
320 
321 	if (newval == FALSE) {
322 		zfsvfs->z_vfs->vfs_flag |= VFS_NOSETUID;
323 		vfs_clearmntopt(zfsvfs->z_vfs, MNTOPT_SETUID);
324 		vfs_setmntopt(zfsvfs->z_vfs, MNTOPT_NOSETUID, NULL, 0);
325 	} else {
326 		zfsvfs->z_vfs->vfs_flag &= ~VFS_NOSETUID;
327 		vfs_clearmntopt(zfsvfs->z_vfs, MNTOPT_NOSETUID);
328 		vfs_setmntopt(zfsvfs->z_vfs, MNTOPT_SETUID, NULL, 0);
329 	}
330 }
331 
332 static void
333 exec_changed_cb(void *arg, uint64_t newval)
334 {
335 	zfsvfs_t *zfsvfs = arg;
336 
337 	if (newval == FALSE) {
338 		zfsvfs->z_vfs->vfs_flag |= VFS_NOEXEC;
339 		vfs_clearmntopt(zfsvfs->z_vfs, MNTOPT_EXEC);
340 		vfs_setmntopt(zfsvfs->z_vfs, MNTOPT_NOEXEC, NULL, 0);
341 	} else {
342 		zfsvfs->z_vfs->vfs_flag &= ~VFS_NOEXEC;
343 		vfs_clearmntopt(zfsvfs->z_vfs, MNTOPT_NOEXEC);
344 		vfs_setmntopt(zfsvfs->z_vfs, MNTOPT_EXEC, NULL, 0);
345 	}
346 }
347 
348 /*
349  * The nbmand mount option can be changed at mount time.
350  * We can't allow it to be toggled on live file systems or incorrect
351  * behavior may be seen from cifs clients
352  *
353  * This property isn't registered via dsl_prop_register(), but this callback
354  * will be called when a file system is first mounted
355  */
356 static void
357 nbmand_changed_cb(void *arg, uint64_t newval)
358 {
359 	zfsvfs_t *zfsvfs = arg;
360 	if (newval == FALSE) {
361 		vfs_clearmntopt(zfsvfs->z_vfs, MNTOPT_NBMAND);
362 		vfs_setmntopt(zfsvfs->z_vfs, MNTOPT_NONBMAND, NULL, 0);
363 	} else {
364 		vfs_clearmntopt(zfsvfs->z_vfs, MNTOPT_NONBMAND);
365 		vfs_setmntopt(zfsvfs->z_vfs, MNTOPT_NBMAND, NULL, 0);
366 	}
367 }
368 
369 static void
370 snapdir_changed_cb(void *arg, uint64_t newval)
371 {
372 	zfsvfs_t *zfsvfs = arg;
373 
374 	zfsvfs->z_show_ctldir = newval;
375 }
376 
377 static void
378 vscan_changed_cb(void *arg, uint64_t newval)
379 {
380 	zfsvfs_t *zfsvfs = arg;
381 
382 	zfsvfs->z_vscan = newval;
383 }
384 
385 static void
386 acl_inherit_changed_cb(void *arg, uint64_t newval)
387 {
388 	zfsvfs_t *zfsvfs = arg;
389 
390 	zfsvfs->z_acl_inherit = newval;
391 }
392 
393 static int
394 zfs_register_callbacks(vfs_t *vfsp)
395 {
396 	struct dsl_dataset *ds = NULL;
397 	objset_t *os = NULL;
398 	zfsvfs_t *zfsvfs = NULL;
399 	uint64_t nbmand;
400 	int readonly, do_readonly = B_FALSE;
401 	int setuid, do_setuid = B_FALSE;
402 	int exec, do_exec = B_FALSE;
403 	int devices, do_devices = B_FALSE;
404 	int xattr, do_xattr = B_FALSE;
405 	int atime, do_atime = B_FALSE;
406 	int error = 0;
407 
408 	ASSERT(vfsp);
409 	zfsvfs = vfsp->vfs_data;
410 	ASSERT(zfsvfs);
411 	os = zfsvfs->z_os;
412 
413 	/*
414 	 * The act of registering our callbacks will destroy any mount
415 	 * options we may have.  In order to enable temporary overrides
416 	 * of mount options, we stash away the current values and
417 	 * restore them after we register the callbacks.
418 	 */
419 	if (vfs_optionisset(vfsp, MNTOPT_RO, NULL)) {
420 		readonly = B_TRUE;
421 		do_readonly = B_TRUE;
422 	} else if (vfs_optionisset(vfsp, MNTOPT_RW, NULL)) {
423 		readonly = B_FALSE;
424 		do_readonly = B_TRUE;
425 	}
426 	if (vfs_optionisset(vfsp, MNTOPT_NOSUID, NULL)) {
427 		devices = B_FALSE;
428 		setuid = B_FALSE;
429 		do_devices = B_TRUE;
430 		do_setuid = B_TRUE;
431 	} else {
432 		if (vfs_optionisset(vfsp, MNTOPT_NODEVICES, NULL)) {
433 			devices = B_FALSE;
434 			do_devices = B_TRUE;
435 		} else if (vfs_optionisset(vfsp, MNTOPT_DEVICES, NULL)) {
436 			devices = B_TRUE;
437 			do_devices = B_TRUE;
438 		}
439 
440 		if (vfs_optionisset(vfsp, MNTOPT_NOSETUID, NULL)) {
441 			setuid = B_FALSE;
442 			do_setuid = B_TRUE;
443 		} else if (vfs_optionisset(vfsp, MNTOPT_SETUID, NULL)) {
444 			setuid = B_TRUE;
445 			do_setuid = B_TRUE;
446 		}
447 	}
448 	if (vfs_optionisset(vfsp, MNTOPT_NOEXEC, NULL)) {
449 		exec = B_FALSE;
450 		do_exec = B_TRUE;
451 	} else if (vfs_optionisset(vfsp, MNTOPT_EXEC, NULL)) {
452 		exec = B_TRUE;
453 		do_exec = B_TRUE;
454 	}
455 	if (vfs_optionisset(vfsp, MNTOPT_NOXATTR, NULL)) {
456 		xattr = B_FALSE;
457 		do_xattr = B_TRUE;
458 	} else if (vfs_optionisset(vfsp, MNTOPT_XATTR, NULL)) {
459 		xattr = B_TRUE;
460 		do_xattr = B_TRUE;
461 	}
462 	if (vfs_optionisset(vfsp, MNTOPT_NOATIME, NULL)) {
463 		atime = B_FALSE;
464 		do_atime = B_TRUE;
465 	} else if (vfs_optionisset(vfsp, MNTOPT_ATIME, NULL)) {
466 		atime = B_TRUE;
467 		do_atime = B_TRUE;
468 	}
469 
470 	/*
471 	 * nbmand is a special property.  It can only be changed at
472 	 * mount time.
473 	 *
474 	 * This is weird, but it is documented to only be changeable
475 	 * at mount time.
476 	 */
477 	if (vfs_optionisset(vfsp, MNTOPT_NONBMAND, NULL)) {
478 		nbmand = B_FALSE;
479 	} else if (vfs_optionisset(vfsp, MNTOPT_NBMAND, NULL)) {
480 		nbmand = B_TRUE;
481 	} else {
482 		char osname[MAXNAMELEN];
483 
484 		dmu_objset_name(os, osname);
485 		if (error = dsl_prop_get_integer(osname, "nbmand", &nbmand,
486 		    NULL)) {
487 			return (error);
488 		}
489 	}
490 
491 	/*
492 	 * Register property callbacks.
493 	 *
494 	 * It would probably be fine to just check for i/o error from
495 	 * the first prop_register(), but I guess I like to go
496 	 * overboard...
497 	 */
498 	ds = dmu_objset_ds(os);
499 	error = dsl_prop_register(ds, "atime", atime_changed_cb, zfsvfs);
500 	error = error ? error : dsl_prop_register(ds,
501 	    "xattr", xattr_changed_cb, zfsvfs);
502 	error = error ? error : dsl_prop_register(ds,
503 	    "recordsize", blksz_changed_cb, zfsvfs);
504 	error = error ? error : dsl_prop_register(ds,
505 	    "readonly", readonly_changed_cb, zfsvfs);
506 	error = error ? error : dsl_prop_register(ds,
507 	    "devices", devices_changed_cb, zfsvfs);
508 	error = error ? error : dsl_prop_register(ds,
509 	    "setuid", setuid_changed_cb, zfsvfs);
510 	error = error ? error : dsl_prop_register(ds,
511 	    "exec", exec_changed_cb, zfsvfs);
512 	error = error ? error : dsl_prop_register(ds,
513 	    "snapdir", snapdir_changed_cb, zfsvfs);
514 	error = error ? error : dsl_prop_register(ds,
515 	    "aclinherit", acl_inherit_changed_cb, zfsvfs);
516 	error = error ? error : dsl_prop_register(ds,
517 	    "vscan", vscan_changed_cb, zfsvfs);
518 	if (error)
519 		goto unregister;
520 
521 	/*
522 	 * Invoke our callbacks to restore temporary mount options.
523 	 */
524 	if (do_readonly)
525 		readonly_changed_cb(zfsvfs, readonly);
526 	if (do_setuid)
527 		setuid_changed_cb(zfsvfs, setuid);
528 	if (do_exec)
529 		exec_changed_cb(zfsvfs, exec);
530 	if (do_devices)
531 		devices_changed_cb(zfsvfs, devices);
532 	if (do_xattr)
533 		xattr_changed_cb(zfsvfs, xattr);
534 	if (do_atime)
535 		atime_changed_cb(zfsvfs, atime);
536 
537 	nbmand_changed_cb(zfsvfs, nbmand);
538 
539 	return (0);
540 
541 unregister:
542 	/*
543 	 * We may attempt to unregister some callbacks that are not
544 	 * registered, but this is OK; it will simply return ENOMSG,
545 	 * which we will ignore.
546 	 */
547 	(void) dsl_prop_unregister(ds, "atime", atime_changed_cb, zfsvfs);
548 	(void) dsl_prop_unregister(ds, "xattr", xattr_changed_cb, zfsvfs);
549 	(void) dsl_prop_unregister(ds, "recordsize", blksz_changed_cb, zfsvfs);
550 	(void) dsl_prop_unregister(ds, "readonly", readonly_changed_cb, zfsvfs);
551 	(void) dsl_prop_unregister(ds, "devices", devices_changed_cb, zfsvfs);
552 	(void) dsl_prop_unregister(ds, "setuid", setuid_changed_cb, zfsvfs);
553 	(void) dsl_prop_unregister(ds, "exec", exec_changed_cb, zfsvfs);
554 	(void) dsl_prop_unregister(ds, "snapdir", snapdir_changed_cb, zfsvfs);
555 	(void) dsl_prop_unregister(ds, "aclinherit", acl_inherit_changed_cb,
556 	    zfsvfs);
557 	(void) dsl_prop_unregister(ds, "vscan", vscan_changed_cb, zfsvfs);
558 	return (error);
559 
560 }
561 
562 static void
563 uidacct(objset_t *os, boolean_t isgroup, uint64_t fuid,
564     int64_t delta, dmu_tx_t *tx)
565 {
566 	uint64_t used = 0;
567 	char buf[32];
568 	int err;
569 	uint64_t obj = isgroup ? DMU_GROUPUSED_OBJECT : DMU_USERUSED_OBJECT;
570 
571 	if (delta == 0)
572 		return;
573 
574 	(void) snprintf(buf, sizeof (buf), "%llx", (longlong_t)fuid);
575 	err = zap_lookup(os, obj, buf, 8, 1, &used);
576 
577 	ASSERT(err == 0 || err == ENOENT);
578 	/* no underflow/overflow */
579 	ASSERT(delta > 0 || used >= -delta);
580 	ASSERT(delta < 0 || used + delta > used);
581 	used += delta;
582 	if (used == 0)
583 		err = zap_remove(os, obj, buf, tx);
584 	else
585 		err = zap_update(os, obj, buf, 8, 1, &used, tx);
586 	ASSERT(err == 0);
587 
588 }
589 
590 static int
591 zfs_space_delta_cb(dmu_object_type_t bonustype, void *data,
592     uint64_t *userp, uint64_t *groupp)
593 {
594 	znode_phys_t *znp = data;
595 	int error = 0;
596 
597 	if (bonustype != DMU_OT_ZNODE && bonustype != DMU_OT_SA)
598 		return (ENOENT);
599 
600 	if (bonustype == DMU_OT_ZNODE) {
601 		*userp = znp->zp_uid;
602 		*groupp = znp->zp_gid;
603 	} else {
604 		int hdrsize;
605 
606 		ASSERT(bonustype == DMU_OT_SA);
607 		hdrsize = sa_hdrsize(data);
608 
609 		if (hdrsize != 0) {
610 			*userp = *((uint64_t *)((uintptr_t)data + hdrsize +
611 			    SA_UID_OFFSET));
612 			*groupp = *((uint64_t *)((uintptr_t)data + hdrsize +
613 			    SA_GID_OFFSET));
614 		} else {
615 			error = ENOENT;
616 		}
617 	}
618 	return (error);
619 }
620 
621 static void
622 fuidstr_to_sid(zfsvfs_t *zfsvfs, const char *fuidstr,
623     char *domainbuf, int buflen, uid_t *ridp)
624 {
625 	uint64_t fuid;
626 	const char *domain;
627 
628 	fuid = strtonum(fuidstr, NULL);
629 
630 	domain = zfs_fuid_find_by_idx(zfsvfs, FUID_INDEX(fuid));
631 	if (domain)
632 		(void) strlcpy(domainbuf, domain, buflen);
633 	else
634 		domainbuf[0] = '\0';
635 	*ridp = FUID_RID(fuid);
636 }
637 
638 static uint64_t
639 zfs_userquota_prop_to_obj(zfsvfs_t *zfsvfs, zfs_userquota_prop_t type)
640 {
641 	switch (type) {
642 	case ZFS_PROP_USERUSED:
643 		return (DMU_USERUSED_OBJECT);
644 	case ZFS_PROP_GROUPUSED:
645 		return (DMU_GROUPUSED_OBJECT);
646 	case ZFS_PROP_USERQUOTA:
647 		return (zfsvfs->z_userquota_obj);
648 	case ZFS_PROP_GROUPQUOTA:
649 		return (zfsvfs->z_groupquota_obj);
650 	}
651 	return (0);
652 }
653 
654 int
655 zfs_userspace_many(zfsvfs_t *zfsvfs, zfs_userquota_prop_t type,
656     uint64_t *cookiep, void *vbuf, uint64_t *bufsizep)
657 {
658 	int error;
659 	zap_cursor_t zc;
660 	zap_attribute_t za;
661 	zfs_useracct_t *buf = vbuf;
662 	uint64_t obj;
663 
664 	if (!dmu_objset_userspace_present(zfsvfs->z_os))
665 		return (ENOTSUP);
666 
667 	obj = zfs_userquota_prop_to_obj(zfsvfs, type);
668 	if (obj == 0) {
669 		*bufsizep = 0;
670 		return (0);
671 	}
672 
673 	for (zap_cursor_init_serialized(&zc, zfsvfs->z_os, obj, *cookiep);
674 	    (error = zap_cursor_retrieve(&zc, &za)) == 0;
675 	    zap_cursor_advance(&zc)) {
676 		if ((uintptr_t)buf - (uintptr_t)vbuf + sizeof (zfs_useracct_t) >
677 		    *bufsizep)
678 			break;
679 
680 		fuidstr_to_sid(zfsvfs, za.za_name,
681 		    buf->zu_domain, sizeof (buf->zu_domain), &buf->zu_rid);
682 
683 		buf->zu_space = za.za_first_integer;
684 		buf++;
685 	}
686 	if (error == ENOENT)
687 		error = 0;
688 
689 	ASSERT3U((uintptr_t)buf - (uintptr_t)vbuf, <=, *bufsizep);
690 	*bufsizep = (uintptr_t)buf - (uintptr_t)vbuf;
691 	*cookiep = zap_cursor_serialize(&zc);
692 	zap_cursor_fini(&zc);
693 	return (error);
694 }
695 
696 /*
697  * buf must be big enough (eg, 32 bytes)
698  */
699 static int
700 id_to_fuidstr(zfsvfs_t *zfsvfs, const char *domain, uid_t rid,
701     char *buf, boolean_t addok)
702 {
703 	uint64_t fuid;
704 	int domainid = 0;
705 
706 	if (domain && domain[0]) {
707 		domainid = zfs_fuid_find_by_domain(zfsvfs, domain, NULL, addok);
708 		if (domainid == -1)
709 			return (ENOENT);
710 	}
711 	fuid = FUID_ENCODE(domainid, rid);
712 	(void) sprintf(buf, "%llx", (longlong_t)fuid);
713 	return (0);
714 }
715 
716 int
717 zfs_userspace_one(zfsvfs_t *zfsvfs, zfs_userquota_prop_t type,
718     const char *domain, uint64_t rid, uint64_t *valp)
719 {
720 	char buf[32];
721 	int err;
722 	uint64_t obj;
723 
724 	*valp = 0;
725 
726 	if (!dmu_objset_userspace_present(zfsvfs->z_os))
727 		return (ENOTSUP);
728 
729 	obj = zfs_userquota_prop_to_obj(zfsvfs, type);
730 	if (obj == 0)
731 		return (0);
732 
733 	err = id_to_fuidstr(zfsvfs, domain, rid, buf, B_FALSE);
734 	if (err)
735 		return (err);
736 
737 	err = zap_lookup(zfsvfs->z_os, obj, buf, 8, 1, valp);
738 	if (err == ENOENT)
739 		err = 0;
740 	return (err);
741 }
742 
743 int
744 zfs_set_userquota(zfsvfs_t *zfsvfs, zfs_userquota_prop_t type,
745     const char *domain, uint64_t rid, uint64_t quota)
746 {
747 	char buf[32];
748 	int err;
749 	dmu_tx_t *tx;
750 	uint64_t *objp;
751 	boolean_t fuid_dirtied;
752 
753 	if (type != ZFS_PROP_USERQUOTA && type != ZFS_PROP_GROUPQUOTA)
754 		return (EINVAL);
755 
756 	if (zfsvfs->z_version < ZPL_VERSION_USERSPACE)
757 		return (ENOTSUP);
758 
759 	objp = (type == ZFS_PROP_USERQUOTA) ? &zfsvfs->z_userquota_obj :
760 	    &zfsvfs->z_groupquota_obj;
761 
762 	err = id_to_fuidstr(zfsvfs, domain, rid, buf, B_TRUE);
763 	if (err)
764 		return (err);
765 	fuid_dirtied = zfsvfs->z_fuid_dirty;
766 
767 	tx = dmu_tx_create(zfsvfs->z_os);
768 	dmu_tx_hold_zap(tx, *objp ? *objp : DMU_NEW_OBJECT, B_TRUE, NULL);
769 	if (*objp == 0) {
770 		dmu_tx_hold_zap(tx, MASTER_NODE_OBJ, B_TRUE,
771 		    zfs_userquota_prop_prefixes[type]);
772 	}
773 	if (fuid_dirtied)
774 		zfs_fuid_txhold(zfsvfs, tx);
775 	err = dmu_tx_assign(tx, TXG_WAIT);
776 	if (err) {
777 		dmu_tx_abort(tx);
778 		return (err);
779 	}
780 
781 	mutex_enter(&zfsvfs->z_lock);
782 	if (*objp == 0) {
783 		*objp = zap_create(zfsvfs->z_os, DMU_OT_USERGROUP_QUOTA,
784 		    DMU_OT_NONE, 0, tx);
785 		VERIFY(0 == zap_add(zfsvfs->z_os, MASTER_NODE_OBJ,
786 		    zfs_userquota_prop_prefixes[type], 8, 1, objp, tx));
787 	}
788 	mutex_exit(&zfsvfs->z_lock);
789 
790 	if (quota == 0) {
791 		err = zap_remove(zfsvfs->z_os, *objp, buf, tx);
792 		if (err == ENOENT)
793 			err = 0;
794 	} else {
795 		err = zap_update(zfsvfs->z_os, *objp, buf, 8, 1, &quota, tx);
796 	}
797 	ASSERT(err == 0);
798 	if (fuid_dirtied)
799 		zfs_fuid_sync(zfsvfs, tx);
800 	dmu_tx_commit(tx);
801 	return (err);
802 }
803 
804 boolean_t
805 zfs_fuid_overquota(zfsvfs_t *zfsvfs, boolean_t isgroup, uint64_t fuid)
806 {
807 	char buf[32];
808 	uint64_t used, quota, usedobj, quotaobj;
809 	int err;
810 
811 	usedobj = isgroup ? DMU_GROUPUSED_OBJECT : DMU_USERUSED_OBJECT;
812 	quotaobj = isgroup ? zfsvfs->z_groupquota_obj : zfsvfs->z_userquota_obj;
813 
814 	if (quotaobj == 0 || zfsvfs->z_replay)
815 		return (B_FALSE);
816 
817 	(void) sprintf(buf, "%llx", (longlong_t)fuid);
818 	err = zap_lookup(zfsvfs->z_os, quotaobj, buf, 8, 1, &quota);
819 	if (err != 0)
820 		return (B_FALSE);
821 
822 	err = zap_lookup(zfsvfs->z_os, usedobj, buf, 8, 1, &used);
823 	if (err != 0)
824 		return (B_FALSE);
825 	return (used >= quota);
826 }
827 
828 boolean_t
829 zfs_owner_overquota(zfsvfs_t *zfsvfs, znode_t *zp, boolean_t isgroup)
830 {
831 	uint64_t fuid;
832 	uint64_t quotaobj;
833 	uid_t id;
834 
835 	quotaobj = isgroup ? zfsvfs->z_groupquota_obj : zfsvfs->z_userquota_obj;
836 
837 	id = isgroup ? zp->z_gid : zp->z_uid;
838 
839 	if (quotaobj == 0 || zfsvfs->z_replay)
840 		return (B_FALSE);
841 
842 	if (IS_EPHEMERAL(id)) {
843 		VERIFY(0 == sa_lookup(zp->z_sa_hdl,
844 		    isgroup ? SA_ZPL_GID(zfsvfs) : SA_ZPL_UID(zfsvfs),
845 		    &fuid, sizeof (fuid)));
846 	} else {
847 		fuid = (uint64_t)id;
848 	}
849 
850 	return (zfs_fuid_overquota(zfsvfs, isgroup, fuid));
851 }
852 
853 int
854 zfsvfs_create(const char *osname, zfsvfs_t **zfvp)
855 {
856 	objset_t *os;
857 	zfsvfs_t *zfsvfs;
858 	uint64_t zval;
859 	int i, error;
860 	uint64_t sa_obj;
861 
862 	zfsvfs = kmem_zalloc(sizeof (zfsvfs_t), KM_SLEEP);
863 
864 	/*
865 	 * We claim to always be readonly so we can open snapshots;
866 	 * other ZPL code will prevent us from writing to snapshots.
867 	 */
868 	error = dmu_objset_own(osname, DMU_OST_ZFS, B_TRUE, zfsvfs, &os);
869 	if (error) {
870 		kmem_free(zfsvfs, sizeof (zfsvfs_t));
871 		return (error);
872 	}
873 
874 	/*
875 	 * Initialize the zfs-specific filesystem structure.
876 	 * Should probably make this a kmem cache, shuffle fields,
877 	 * and just bzero up to z_hold_mtx[].
878 	 */
879 	zfsvfs->z_vfs = NULL;
880 	zfsvfs->z_parent = zfsvfs;
881 	zfsvfs->z_max_blksz = SPA_MAXBLOCKSIZE;
882 	zfsvfs->z_show_ctldir = ZFS_SNAPDIR_VISIBLE;
883 	zfsvfs->z_os = os;
884 
885 	error = zfs_get_zplprop(os, ZFS_PROP_VERSION, &zfsvfs->z_version);
886 	if (error) {
887 		goto out;
888 	} else if (zfsvfs->z_version >
889 	    zfs_zpl_version_map(spa_version(dmu_objset_spa(os)))) {
890 		(void) printf("Can't mount a version %lld file system "
891 		    "on a version %lld pool\n. Pool must be upgraded to mount "
892 		    "this file system.", (u_longlong_t)zfsvfs->z_version,
893 		    (u_longlong_t)spa_version(dmu_objset_spa(os)));
894 		error = ENOTSUP;
895 		goto out;
896 	}
897 	if ((error = zfs_get_zplprop(os, ZFS_PROP_NORMALIZE, &zval)) != 0)
898 		goto out;
899 	zfsvfs->z_norm = (int)zval;
900 
901 	if ((error = zfs_get_zplprop(os, ZFS_PROP_UTF8ONLY, &zval)) != 0)
902 		goto out;
903 	zfsvfs->z_utf8 = (zval != 0);
904 
905 	if ((error = zfs_get_zplprop(os, ZFS_PROP_CASE, &zval)) != 0)
906 		goto out;
907 	zfsvfs->z_case = (uint_t)zval;
908 
909 	/*
910 	 * Fold case on file systems that are always or sometimes case
911 	 * insensitive.
912 	 */
913 	if (zfsvfs->z_case == ZFS_CASE_INSENSITIVE ||
914 	    zfsvfs->z_case == ZFS_CASE_MIXED)
915 		zfsvfs->z_norm |= U8_TEXTPREP_TOUPPER;
916 
917 	zfsvfs->z_use_fuids = USE_FUIDS(zfsvfs->z_version, zfsvfs->z_os);
918 	zfsvfs->z_use_sa = USE_SA(zfsvfs->z_version, zfsvfs->z_os);
919 
920 	if (zfsvfs->z_use_sa) {
921 		/* should either have both of these objects or none */
922 		error = zap_lookup(os, MASTER_NODE_OBJ, ZFS_SA_ATTRS, 8, 1,
923 		    &sa_obj);
924 		if (error)
925 			return (error);
926 	} else {
927 		/*
928 		 * Pre SA versions file systems should never touch
929 		 * either the attribute registration or layout objects.
930 		 */
931 		sa_obj = 0;
932 	}
933 
934 	zfsvfs->z_attr_table = sa_setup(os, sa_obj, zfs_attr_table, ZPL_END);
935 
936 	if (zfsvfs->z_version >= ZPL_VERSION_SA)
937 		sa_register_update_callback(os, zfs_sa_upgrade);
938 
939 	error = zap_lookup(os, MASTER_NODE_OBJ, ZFS_ROOT_OBJ, 8, 1,
940 	    &zfsvfs->z_root);
941 	if (error)
942 		goto out;
943 	ASSERT(zfsvfs->z_root != 0);
944 
945 	error = zap_lookup(os, MASTER_NODE_OBJ, ZFS_UNLINKED_SET, 8, 1,
946 	    &zfsvfs->z_unlinkedobj);
947 	if (error)
948 		goto out;
949 
950 	error = zap_lookup(os, MASTER_NODE_OBJ,
951 	    zfs_userquota_prop_prefixes[ZFS_PROP_USERQUOTA],
952 	    8, 1, &zfsvfs->z_userquota_obj);
953 	if (error && error != ENOENT)
954 		goto out;
955 
956 	error = zap_lookup(os, MASTER_NODE_OBJ,
957 	    zfs_userquota_prop_prefixes[ZFS_PROP_GROUPQUOTA],
958 	    8, 1, &zfsvfs->z_groupquota_obj);
959 	if (error && error != ENOENT)
960 		goto out;
961 
962 	error = zap_lookup(os, MASTER_NODE_OBJ, ZFS_FUID_TABLES, 8, 1,
963 	    &zfsvfs->z_fuid_obj);
964 	if (error && error != ENOENT)
965 		goto out;
966 
967 	error = zap_lookup(os, MASTER_NODE_OBJ, ZFS_SHARES_DIR, 8, 1,
968 	    &zfsvfs->z_shares_dir);
969 	if (error && error != ENOENT)
970 		goto out;
971 
972 	mutex_init(&zfsvfs->z_znodes_lock, NULL, MUTEX_DEFAULT, NULL);
973 	mutex_init(&zfsvfs->z_lock, NULL, MUTEX_DEFAULT, NULL);
974 	list_create(&zfsvfs->z_all_znodes, sizeof (znode_t),
975 	    offsetof(znode_t, z_link_node));
976 	rrw_init(&zfsvfs->z_teardown_lock);
977 	rw_init(&zfsvfs->z_teardown_inactive_lock, NULL, RW_DEFAULT, NULL);
978 	rw_init(&zfsvfs->z_fuid_lock, NULL, RW_DEFAULT, NULL);
979 	for (i = 0; i != ZFS_OBJ_MTX_SZ; i++)
980 		mutex_init(&zfsvfs->z_hold_mtx[i], NULL, MUTEX_DEFAULT, NULL);
981 
982 	*zfvp = zfsvfs;
983 	return (0);
984 
985 out:
986 	dmu_objset_disown(os, zfsvfs);
987 	*zfvp = NULL;
988 	kmem_free(zfsvfs, sizeof (zfsvfs_t));
989 	return (error);
990 }
991 
992 static int
993 zfsvfs_setup(zfsvfs_t *zfsvfs, boolean_t mounting)
994 {
995 	int error;
996 
997 	error = zfs_register_callbacks(zfsvfs->z_vfs);
998 	if (error)
999 		return (error);
1000 
1001 	/*
1002 	 * Set the objset user_ptr to track its zfsvfs.
1003 	 */
1004 	mutex_enter(&zfsvfs->z_os->os_user_ptr_lock);
1005 	dmu_objset_set_user(zfsvfs->z_os, zfsvfs);
1006 	mutex_exit(&zfsvfs->z_os->os_user_ptr_lock);
1007 
1008 	zfsvfs->z_log = zil_open(zfsvfs->z_os, zfs_get_data);
1009 	if (zil_disable) {
1010 		zil_destroy(zfsvfs->z_log, B_FALSE);
1011 		zfsvfs->z_log = NULL;
1012 	}
1013 
1014 	/*
1015 	 * If we are not mounting (ie: online recv), then we don't
1016 	 * have to worry about replaying the log as we blocked all
1017 	 * operations out since we closed the ZIL.
1018 	 */
1019 	if (mounting) {
1020 		boolean_t readonly;
1021 
1022 		/*
1023 		 * During replay we remove the read only flag to
1024 		 * allow replays to succeed.
1025 		 */
1026 		readonly = zfsvfs->z_vfs->vfs_flag & VFS_RDONLY;
1027 		if (readonly != 0)
1028 			zfsvfs->z_vfs->vfs_flag &= ~VFS_RDONLY;
1029 		else
1030 			zfs_unlinked_drain(zfsvfs);
1031 
1032 		if (zfsvfs->z_log) {
1033 			/*
1034 			 * Parse and replay the intent log.
1035 			 *
1036 			 * Because of ziltest, this must be done after
1037 			 * zfs_unlinked_drain().  (Further note: ziltest
1038 			 * doesn't use readonly mounts, where
1039 			 * zfs_unlinked_drain() isn't called.)  This is because
1040 			 * ziltest causes spa_sync() to think it's committed,
1041 			 * but actually it is not, so the intent log contains
1042 			 * many txg's worth of changes.
1043 			 *
1044 			 * In particular, if object N is in the unlinked set in
1045 			 * the last txg to actually sync, then it could be
1046 			 * actually freed in a later txg and then reallocated
1047 			 * in a yet later txg.  This would write a "create
1048 			 * object N" record to the intent log.  Normally, this
1049 			 * would be fine because the spa_sync() would have
1050 			 * written out the fact that object N is free, before
1051 			 * we could write the "create object N" intent log
1052 			 * record.
1053 			 *
1054 			 * But when we are in ziltest mode, we advance the "open
1055 			 * txg" without actually spa_sync()-ing the changes to
1056 			 * disk.  So we would see that object N is still
1057 			 * allocated and in the unlinked set, and there is an
1058 			 * intent log record saying to allocate it.
1059 			 */
1060 			zfsvfs->z_replay = B_TRUE;
1061 			zil_replay(zfsvfs->z_os, zfsvfs, zfs_replay_vector);
1062 			zfsvfs->z_replay = B_FALSE;
1063 		}
1064 		zfsvfs->z_vfs->vfs_flag |= readonly; /* restore readonly bit */
1065 	}
1066 
1067 	return (0);
1068 }
1069 
1070 void
1071 zfsvfs_free(zfsvfs_t *zfsvfs)
1072 {
1073 	int i;
1074 	extern krwlock_t zfsvfs_lock; /* in zfs_znode.c */
1075 
1076 	/*
1077 	 * This is a barrier to prevent the filesystem from going away in
1078 	 * zfs_znode_move() until we can safely ensure that the filesystem is
1079 	 * not unmounted. We consider the filesystem valid before the barrier
1080 	 * and invalid after the barrier.
1081 	 */
1082 	rw_enter(&zfsvfs_lock, RW_READER);
1083 	rw_exit(&zfsvfs_lock);
1084 
1085 	zfs_fuid_destroy(zfsvfs);
1086 
1087 	mutex_destroy(&zfsvfs->z_znodes_lock);
1088 	mutex_destroy(&zfsvfs->z_lock);
1089 	list_destroy(&zfsvfs->z_all_znodes);
1090 	rrw_destroy(&zfsvfs->z_teardown_lock);
1091 	rw_destroy(&zfsvfs->z_teardown_inactive_lock);
1092 	rw_destroy(&zfsvfs->z_fuid_lock);
1093 	for (i = 0; i != ZFS_OBJ_MTX_SZ; i++)
1094 		mutex_destroy(&zfsvfs->z_hold_mtx[i]);
1095 	kmem_free(zfsvfs, sizeof (zfsvfs_t));
1096 }
1097 
1098 static void
1099 zfs_set_fuid_feature(zfsvfs_t *zfsvfs)
1100 {
1101 	zfsvfs->z_use_fuids = USE_FUIDS(zfsvfs->z_version, zfsvfs->z_os);
1102 	if (zfsvfs->z_use_fuids && zfsvfs->z_vfs) {
1103 		vfs_set_feature(zfsvfs->z_vfs, VFSFT_XVATTR);
1104 		vfs_set_feature(zfsvfs->z_vfs, VFSFT_SYSATTR_VIEWS);
1105 		vfs_set_feature(zfsvfs->z_vfs, VFSFT_ACEMASKONACCESS);
1106 		vfs_set_feature(zfsvfs->z_vfs, VFSFT_ACLONCREATE);
1107 		vfs_set_feature(zfsvfs->z_vfs, VFSFT_ACCESS_FILTER);
1108 		vfs_set_feature(zfsvfs->z_vfs, VFSFT_REPARSE);
1109 	}
1110 	zfsvfs->z_use_sa = USE_SA(zfsvfs->z_version, zfsvfs->z_os);
1111 }
1112 
1113 static int
1114 zfs_domount(vfs_t *vfsp, char *osname)
1115 {
1116 	dev_t mount_dev;
1117 	uint64_t recordsize, fsid_guid;
1118 	int error = 0;
1119 	zfsvfs_t *zfsvfs;
1120 
1121 	ASSERT(vfsp);
1122 	ASSERT(osname);
1123 
1124 	error = zfsvfs_create(osname, &zfsvfs);
1125 	if (error)
1126 		return (error);
1127 	zfsvfs->z_vfs = vfsp;
1128 
1129 	/* Initialize the generic filesystem structure. */
1130 	vfsp->vfs_bcount = 0;
1131 	vfsp->vfs_data = NULL;
1132 
1133 	if (zfs_create_unique_device(&mount_dev) == -1) {
1134 		error = ENODEV;
1135 		goto out;
1136 	}
1137 	ASSERT(vfs_devismounted(mount_dev) == 0);
1138 
1139 	if (error = dsl_prop_get_integer(osname, "recordsize", &recordsize,
1140 	    NULL))
1141 		goto out;
1142 
1143 	vfsp->vfs_dev = mount_dev;
1144 	vfsp->vfs_fstype = zfsfstype;
1145 	vfsp->vfs_bsize = recordsize;
1146 	vfsp->vfs_flag |= VFS_NOTRUNC;
1147 	vfsp->vfs_data = zfsvfs;
1148 
1149 	/*
1150 	 * The fsid is 64 bits, composed of an 8-bit fs type, which
1151 	 * separates our fsid from any other filesystem types, and a
1152 	 * 56-bit objset unique ID.  The objset unique ID is unique to
1153 	 * all objsets open on this system, provided by unique_create().
1154 	 * The 8-bit fs type must be put in the low bits of fsid[1]
1155 	 * because that's where other Solaris filesystems put it.
1156 	 */
1157 	fsid_guid = dmu_objset_fsid_guid(zfsvfs->z_os);
1158 	ASSERT((fsid_guid & ~((1ULL<<56)-1)) == 0);
1159 	vfsp->vfs_fsid.val[0] = fsid_guid;
1160 	vfsp->vfs_fsid.val[1] = ((fsid_guid>>32) << 8) |
1161 	    zfsfstype & 0xFF;
1162 
1163 	/*
1164 	 * Set features for file system.
1165 	 */
1166 	zfs_set_fuid_feature(zfsvfs);
1167 	if (zfsvfs->z_case == ZFS_CASE_INSENSITIVE) {
1168 		vfs_set_feature(vfsp, VFSFT_DIRENTFLAGS);
1169 		vfs_set_feature(vfsp, VFSFT_CASEINSENSITIVE);
1170 		vfs_set_feature(vfsp, VFSFT_NOCASESENSITIVE);
1171 	} else if (zfsvfs->z_case == ZFS_CASE_MIXED) {
1172 		vfs_set_feature(vfsp, VFSFT_DIRENTFLAGS);
1173 		vfs_set_feature(vfsp, VFSFT_CASEINSENSITIVE);
1174 	}
1175 	vfs_set_feature(vfsp, VFSFT_ZEROCOPY_SUPPORTED);
1176 
1177 	if (dmu_objset_is_snapshot(zfsvfs->z_os)) {
1178 		uint64_t pval;
1179 
1180 		atime_changed_cb(zfsvfs, B_FALSE);
1181 		readonly_changed_cb(zfsvfs, B_TRUE);
1182 		if (error = dsl_prop_get_integer(osname, "xattr", &pval, NULL))
1183 			goto out;
1184 		xattr_changed_cb(zfsvfs, pval);
1185 		zfsvfs->z_issnap = B_TRUE;
1186 
1187 		mutex_enter(&zfsvfs->z_os->os_user_ptr_lock);
1188 		dmu_objset_set_user(zfsvfs->z_os, zfsvfs);
1189 		mutex_exit(&zfsvfs->z_os->os_user_ptr_lock);
1190 	} else {
1191 		error = zfsvfs_setup(zfsvfs, B_TRUE);
1192 	}
1193 
1194 	if (!zfsvfs->z_issnap)
1195 		zfsctl_create(zfsvfs);
1196 out:
1197 	if (error) {
1198 		dmu_objset_disown(zfsvfs->z_os, zfsvfs);
1199 		zfsvfs_free(zfsvfs);
1200 	} else {
1201 		atomic_add_32(&zfs_active_fs_count, 1);
1202 	}
1203 
1204 	return (error);
1205 }
1206 
1207 void
1208 zfs_unregister_callbacks(zfsvfs_t *zfsvfs)
1209 {
1210 	objset_t *os = zfsvfs->z_os;
1211 	struct dsl_dataset *ds;
1212 
1213 	/*
1214 	 * Unregister properties.
1215 	 */
1216 	if (!dmu_objset_is_snapshot(os)) {
1217 		ds = dmu_objset_ds(os);
1218 		VERIFY(dsl_prop_unregister(ds, "atime", atime_changed_cb,
1219 		    zfsvfs) == 0);
1220 
1221 		VERIFY(dsl_prop_unregister(ds, "xattr", xattr_changed_cb,
1222 		    zfsvfs) == 0);
1223 
1224 		VERIFY(dsl_prop_unregister(ds, "recordsize", blksz_changed_cb,
1225 		    zfsvfs) == 0);
1226 
1227 		VERIFY(dsl_prop_unregister(ds, "readonly", readonly_changed_cb,
1228 		    zfsvfs) == 0);
1229 
1230 		VERIFY(dsl_prop_unregister(ds, "devices", devices_changed_cb,
1231 		    zfsvfs) == 0);
1232 
1233 		VERIFY(dsl_prop_unregister(ds, "setuid", setuid_changed_cb,
1234 		    zfsvfs) == 0);
1235 
1236 		VERIFY(dsl_prop_unregister(ds, "exec", exec_changed_cb,
1237 		    zfsvfs) == 0);
1238 
1239 		VERIFY(dsl_prop_unregister(ds, "snapdir", snapdir_changed_cb,
1240 		    zfsvfs) == 0);
1241 
1242 		VERIFY(dsl_prop_unregister(ds, "aclinherit",
1243 		    acl_inherit_changed_cb, zfsvfs) == 0);
1244 
1245 		VERIFY(dsl_prop_unregister(ds, "vscan",
1246 		    vscan_changed_cb, zfsvfs) == 0);
1247 	}
1248 }
1249 
1250 /*
1251  * Convert a decimal digit string to a uint64_t integer.
1252  */
1253 static int
1254 str_to_uint64(char *str, uint64_t *objnum)
1255 {
1256 	uint64_t num = 0;
1257 
1258 	while (*str) {
1259 		if (*str < '0' || *str > '9')
1260 			return (EINVAL);
1261 
1262 		num = num*10 + *str++ - '0';
1263 	}
1264 
1265 	*objnum = num;
1266 	return (0);
1267 }
1268 
1269 /*
1270  * The boot path passed from the boot loader is in the form of
1271  * "rootpool-name/root-filesystem-object-number'. Convert this
1272  * string to a dataset name: "rootpool-name/root-filesystem-name".
1273  */
1274 static int
1275 zfs_parse_bootfs(char *bpath, char *outpath)
1276 {
1277 	char *slashp;
1278 	uint64_t objnum;
1279 	int error;
1280 
1281 	if (*bpath == 0 || *bpath == '/')
1282 		return (EINVAL);
1283 
1284 	(void) strcpy(outpath, bpath);
1285 
1286 	slashp = strchr(bpath, '/');
1287 
1288 	/* if no '/', just return the pool name */
1289 	if (slashp == NULL) {
1290 		return (0);
1291 	}
1292 
1293 	/* if not a number, just return the root dataset name */
1294 	if (str_to_uint64(slashp+1, &objnum)) {
1295 		return (0);
1296 	}
1297 
1298 	*slashp = '\0';
1299 	error = dsl_dsobj_to_dsname(bpath, objnum, outpath);
1300 	*slashp = '/';
1301 
1302 	return (error);
1303 }
1304 
1305 /*
1306  * zfs_check_global_label:
1307  *	Check that the hex label string is appropriate for the dataset
1308  *	being mounted into the global_zone proper.
1309  *
1310  *	Return an error if the hex label string is not default or
1311  *	admin_low/admin_high.  For admin_low labels, the corresponding
1312  *	dataset must be readonly.
1313  */
1314 int
1315 zfs_check_global_label(const char *dsname, const char *hexsl)
1316 {
1317 	if (strcasecmp(hexsl, ZFS_MLSLABEL_DEFAULT) == 0)
1318 		return (0);
1319 	if (strcasecmp(hexsl, ADMIN_HIGH) == 0)
1320 		return (0);
1321 	if (strcasecmp(hexsl, ADMIN_LOW) == 0) {
1322 		/* must be readonly */
1323 		uint64_t rdonly;
1324 
1325 		if (dsl_prop_get_integer(dsname,
1326 		    zfs_prop_to_name(ZFS_PROP_READONLY), &rdonly, NULL))
1327 			return (EACCES);
1328 		return (rdonly ? 0 : EACCES);
1329 	}
1330 	return (EACCES);
1331 }
1332 
1333 /*
1334  * zfs_mount_label_policy:
1335  *	Determine whether the mount is allowed according to MAC check.
1336  *	by comparing (where appropriate) label of the dataset against
1337  *	the label of the zone being mounted into.  If the dataset has
1338  *	no label, create one.
1339  *
1340  *	Returns:
1341  *		 0 :	access allowed
1342  *		>0 :	error code, such as EACCES
1343  */
1344 static int
1345 zfs_mount_label_policy(vfs_t *vfsp, char *osname)
1346 {
1347 	int		error, retv;
1348 	zone_t		*mntzone = NULL;
1349 	ts_label_t	*mnt_tsl;
1350 	bslabel_t	*mnt_sl;
1351 	bslabel_t	ds_sl;
1352 	char		ds_hexsl[MAXNAMELEN];
1353 
1354 	retv = EACCES;				/* assume the worst */
1355 
1356 	/*
1357 	 * Start by getting the dataset label if it exists.
1358 	 */
1359 	error = dsl_prop_get(osname, zfs_prop_to_name(ZFS_PROP_MLSLABEL),
1360 	    1, sizeof (ds_hexsl), &ds_hexsl, NULL);
1361 	if (error)
1362 		return (EACCES);
1363 
1364 	/*
1365 	 * If labeling is NOT enabled, then disallow the mount of datasets
1366 	 * which have a non-default label already.  No other label checks
1367 	 * are needed.
1368 	 */
1369 	if (!is_system_labeled()) {
1370 		if (strcasecmp(ds_hexsl, ZFS_MLSLABEL_DEFAULT) == 0)
1371 			return (0);
1372 		return (EACCES);
1373 	}
1374 
1375 	/*
1376 	 * Get the label of the mountpoint.  If mounting into the global
1377 	 * zone (i.e. mountpoint is not within an active zone and the
1378 	 * zoned property is off), the label must be default or
1379 	 * admin_low/admin_high only; no other checks are needed.
1380 	 */
1381 	mntzone = zone_find_by_any_path(refstr_value(vfsp->vfs_mntpt), B_FALSE);
1382 	if (mntzone->zone_id == GLOBAL_ZONEID) {
1383 		uint64_t zoned;
1384 
1385 		zone_rele(mntzone);
1386 
1387 		if (dsl_prop_get_integer(osname,
1388 		    zfs_prop_to_name(ZFS_PROP_ZONED), &zoned, NULL))
1389 			return (EACCES);
1390 		if (!zoned)
1391 			return (zfs_check_global_label(osname, ds_hexsl));
1392 		else
1393 			/*
1394 			 * This is the case of a zone dataset being mounted
1395 			 * initially, before the zone has been fully created;
1396 			 * allow this mount into global zone.
1397 			 */
1398 			return (0);
1399 	}
1400 
1401 	mnt_tsl = mntzone->zone_slabel;
1402 	ASSERT(mnt_tsl != NULL);
1403 	label_hold(mnt_tsl);
1404 	mnt_sl = label2bslabel(mnt_tsl);
1405 
1406 	if (strcasecmp(ds_hexsl, ZFS_MLSLABEL_DEFAULT) == 0) {
1407 		/*
1408 		 * The dataset doesn't have a real label, so fabricate one.
1409 		 */
1410 		char *str = NULL;
1411 
1412 		if (l_to_str_internal(mnt_sl, &str) == 0 &&
1413 		    dsl_prop_set(osname, zfs_prop_to_name(ZFS_PROP_MLSLABEL),
1414 		    ZPROP_SRC_LOCAL, 1, strlen(str) + 1, str) == 0)
1415 			retv = 0;
1416 		if (str != NULL)
1417 			kmem_free(str, strlen(str) + 1);
1418 	} else if (hexstr_to_label(ds_hexsl, &ds_sl) == 0) {
1419 		/*
1420 		 * Now compare labels to complete the MAC check.  If the
1421 		 * labels are equal then allow access.  If the mountpoint
1422 		 * label dominates the dataset label, allow readonly access.
1423 		 * Otherwise, access is denied.
1424 		 */
1425 		if (blequal(mnt_sl, &ds_sl))
1426 			retv = 0;
1427 		else if (bldominates(mnt_sl, &ds_sl)) {
1428 			vfs_setmntopt(vfsp, MNTOPT_RO, NULL, 0);
1429 			retv = 0;
1430 		}
1431 	}
1432 
1433 	label_rele(mnt_tsl);
1434 	zone_rele(mntzone);
1435 	return (retv);
1436 }
1437 
1438 static int
1439 zfs_mountroot(vfs_t *vfsp, enum whymountroot why)
1440 {
1441 	int error = 0;
1442 	static int zfsrootdone = 0;
1443 	zfsvfs_t *zfsvfs = NULL;
1444 	znode_t *zp = NULL;
1445 	vnode_t *vp = NULL;
1446 	char *zfs_bootfs;
1447 	char *zfs_devid;
1448 
1449 	ASSERT(vfsp);
1450 
1451 	/*
1452 	 * The filesystem that we mount as root is defined in the
1453 	 * boot property "zfs-bootfs" with a format of
1454 	 * "poolname/root-dataset-objnum".
1455 	 */
1456 	if (why == ROOT_INIT) {
1457 		if (zfsrootdone++)
1458 			return (EBUSY);
1459 		/*
1460 		 * the process of doing a spa_load will require the
1461 		 * clock to be set before we could (for example) do
1462 		 * something better by looking at the timestamp on
1463 		 * an uberblock, so just set it to -1.
1464 		 */
1465 		clkset(-1);
1466 
1467 		if ((zfs_bootfs = spa_get_bootprop("zfs-bootfs")) == NULL) {
1468 			cmn_err(CE_NOTE, "spa_get_bootfs: can not get "
1469 			    "bootfs name");
1470 			return (EINVAL);
1471 		}
1472 		zfs_devid = spa_get_bootprop("diskdevid");
1473 		error = spa_import_rootpool(rootfs.bo_name, zfs_devid);
1474 		if (zfs_devid)
1475 			spa_free_bootprop(zfs_devid);
1476 		if (error) {
1477 			spa_free_bootprop(zfs_bootfs);
1478 			cmn_err(CE_NOTE, "spa_import_rootpool: error %d",
1479 			    error);
1480 			return (error);
1481 		}
1482 		if (error = zfs_parse_bootfs(zfs_bootfs, rootfs.bo_name)) {
1483 			spa_free_bootprop(zfs_bootfs);
1484 			cmn_err(CE_NOTE, "zfs_parse_bootfs: error %d",
1485 			    error);
1486 			return (error);
1487 		}
1488 
1489 		spa_free_bootprop(zfs_bootfs);
1490 
1491 		if (error = vfs_lock(vfsp))
1492 			return (error);
1493 
1494 		if (error = zfs_domount(vfsp, rootfs.bo_name)) {
1495 			cmn_err(CE_NOTE, "zfs_domount: error %d", error);
1496 			goto out;
1497 		}
1498 
1499 		zfsvfs = (zfsvfs_t *)vfsp->vfs_data;
1500 		ASSERT(zfsvfs);
1501 		if (error = zfs_zget(zfsvfs, zfsvfs->z_root, &zp)) {
1502 			cmn_err(CE_NOTE, "zfs_zget: error %d", error);
1503 			goto out;
1504 		}
1505 
1506 		vp = ZTOV(zp);
1507 		mutex_enter(&vp->v_lock);
1508 		vp->v_flag |= VROOT;
1509 		mutex_exit(&vp->v_lock);
1510 		rootvp = vp;
1511 
1512 		/*
1513 		 * Leave rootvp held.  The root file system is never unmounted.
1514 		 */
1515 
1516 		vfs_add((struct vnode *)0, vfsp,
1517 		    (vfsp->vfs_flag & VFS_RDONLY) ? MS_RDONLY : 0);
1518 out:
1519 		vfs_unlock(vfsp);
1520 		return (error);
1521 	} else if (why == ROOT_REMOUNT) {
1522 		readonly_changed_cb(vfsp->vfs_data, B_FALSE);
1523 		vfsp->vfs_flag |= VFS_REMOUNT;
1524 
1525 		/* refresh mount options */
1526 		zfs_unregister_callbacks(vfsp->vfs_data);
1527 		return (zfs_register_callbacks(vfsp));
1528 
1529 	} else if (why == ROOT_UNMOUNT) {
1530 		zfs_unregister_callbacks((zfsvfs_t *)vfsp->vfs_data);
1531 		(void) zfs_sync(vfsp, 0, 0);
1532 		return (0);
1533 	}
1534 
1535 	/*
1536 	 * if "why" is equal to anything else other than ROOT_INIT,
1537 	 * ROOT_REMOUNT, or ROOT_UNMOUNT, we do not support it.
1538 	 */
1539 	return (ENOTSUP);
1540 }
1541 
1542 /*ARGSUSED*/
1543 static int
1544 zfs_mount(vfs_t *vfsp, vnode_t *mvp, struct mounta *uap, cred_t *cr)
1545 {
1546 	char		*osname;
1547 	pathname_t	spn;
1548 	int		error = 0;
1549 	uio_seg_t	fromspace = (uap->flags & MS_SYSSPACE) ?
1550 	    UIO_SYSSPACE : UIO_USERSPACE;
1551 	int		canwrite;
1552 
1553 	if (mvp->v_type != VDIR)
1554 		return (ENOTDIR);
1555 
1556 	mutex_enter(&mvp->v_lock);
1557 	if ((uap->flags & MS_REMOUNT) == 0 &&
1558 	    (uap->flags & MS_OVERLAY) == 0 &&
1559 	    (mvp->v_count != 1 || (mvp->v_flag & VROOT))) {
1560 		mutex_exit(&mvp->v_lock);
1561 		return (EBUSY);
1562 	}
1563 	mutex_exit(&mvp->v_lock);
1564 
1565 	/*
1566 	 * ZFS does not support passing unparsed data in via MS_DATA.
1567 	 * Users should use the MS_OPTIONSTR interface; this means
1568 	 * that all option parsing is already done and the options struct
1569 	 * can be interrogated.
1570 	 */
1571 	if ((uap->flags & MS_DATA) && uap->datalen > 0)
1572 		return (EINVAL);
1573 
1574 	/*
1575 	 * Get the objset name (the "special" mount argument).
1576 	 */
1577 	if (error = pn_get(uap->spec, fromspace, &spn))
1578 		return (error);
1579 
1580 	osname = spn.pn_path;
1581 
1582 	/*
1583 	 * Check for mount privilege?
1584 	 *
1585 	 * If we don't have privilege then see if
1586 	 * we have local permission to allow it
1587 	 */
1588 	error = secpolicy_fs_mount(cr, mvp, vfsp);
1589 	if (error) {
1590 		if (dsl_deleg_access(osname, ZFS_DELEG_PERM_MOUNT, cr) == 0) {
1591 			vattr_t		vattr;
1592 
1593 			/*
1594 			 * Make sure user is the owner of the mount point
1595 			 * or has sufficient privileges.
1596 			 */
1597 
1598 			vattr.va_mask = AT_UID;
1599 
1600 			if (VOP_GETATTR(mvp, &vattr, 0, cr, NULL)) {
1601 				goto out;
1602 			}
1603 
1604 			if (secpolicy_vnode_owner(cr, vattr.va_uid) != 0 &&
1605 			    VOP_ACCESS(mvp, VWRITE, 0, cr, NULL) != 0) {
1606 				goto out;
1607 			}
1608 			secpolicy_fs_mount_clearopts(cr, vfsp);
1609 		} else {
1610 			goto out;
1611 		}
1612 	}
1613 
1614 	/*
1615 	 * Refuse to mount a filesystem if we are in a local zone and the
1616 	 * dataset is not visible.
1617 	 */
1618 	if (!INGLOBALZONE(curproc) &&
1619 	    (!zone_dataset_visible(osname, &canwrite) || !canwrite)) {
1620 		error = EPERM;
1621 		goto out;
1622 	}
1623 
1624 	error = zfs_mount_label_policy(vfsp, osname);
1625 	if (error)
1626 		goto out;
1627 
1628 	/*
1629 	 * When doing a remount, we simply refresh our temporary properties
1630 	 * according to those options set in the current VFS options.
1631 	 */
1632 	if (uap->flags & MS_REMOUNT) {
1633 		/* refresh mount options */
1634 		zfs_unregister_callbacks(vfsp->vfs_data);
1635 		error = zfs_register_callbacks(vfsp);
1636 		goto out;
1637 	}
1638 
1639 	error = zfs_domount(vfsp, osname);
1640 
1641 	/*
1642 	 * Add an extra VFS_HOLD on our parent vfs so that it can't
1643 	 * disappear due to a forced unmount.
1644 	 */
1645 	if (error == 0 && ((zfsvfs_t *)vfsp->vfs_data)->z_issnap)
1646 		VFS_HOLD(mvp->v_vfsp);
1647 
1648 out:
1649 	pn_free(&spn);
1650 	return (error);
1651 }
1652 
1653 static int
1654 zfs_statvfs(vfs_t *vfsp, struct statvfs64 *statp)
1655 {
1656 	zfsvfs_t *zfsvfs = vfsp->vfs_data;
1657 	dev32_t d32;
1658 	uint64_t refdbytes, availbytes, usedobjs, availobjs;
1659 
1660 	ZFS_ENTER(zfsvfs);
1661 
1662 	dmu_objset_space(zfsvfs->z_os,
1663 	    &refdbytes, &availbytes, &usedobjs, &availobjs);
1664 
1665 	/*
1666 	 * The underlying storage pool actually uses multiple block sizes.
1667 	 * We report the fragsize as the smallest block size we support,
1668 	 * and we report our blocksize as the filesystem's maximum blocksize.
1669 	 */
1670 	statp->f_frsize = 1UL << SPA_MINBLOCKSHIFT;
1671 	statp->f_bsize = zfsvfs->z_max_blksz;
1672 
1673 	/*
1674 	 * The following report "total" blocks of various kinds in the
1675 	 * file system, but reported in terms of f_frsize - the
1676 	 * "fragment" size.
1677 	 */
1678 
1679 	statp->f_blocks = (refdbytes + availbytes) >> SPA_MINBLOCKSHIFT;
1680 	statp->f_bfree = availbytes >> SPA_MINBLOCKSHIFT;
1681 	statp->f_bavail = statp->f_bfree; /* no root reservation */
1682 
1683 	/*
1684 	 * statvfs() should really be called statufs(), because it assumes
1685 	 * static metadata.  ZFS doesn't preallocate files, so the best
1686 	 * we can do is report the max that could possibly fit in f_files,
1687 	 * and that minus the number actually used in f_ffree.
1688 	 * For f_ffree, report the smaller of the number of object available
1689 	 * and the number of blocks (each object will take at least a block).
1690 	 */
1691 	statp->f_ffree = MIN(availobjs, statp->f_bfree);
1692 	statp->f_favail = statp->f_ffree;	/* no "root reservation" */
1693 	statp->f_files = statp->f_ffree + usedobjs;
1694 
1695 	(void) cmpldev(&d32, vfsp->vfs_dev);
1696 	statp->f_fsid = d32;
1697 
1698 	/*
1699 	 * We're a zfs filesystem.
1700 	 */
1701 	(void) strcpy(statp->f_basetype, vfssw[vfsp->vfs_fstype].vsw_name);
1702 
1703 	statp->f_flag = vf_to_stf(vfsp->vfs_flag);
1704 
1705 	statp->f_namemax = ZFS_MAXNAMELEN;
1706 
1707 	/*
1708 	 * We have all of 32 characters to stuff a string here.
1709 	 * Is there anything useful we could/should provide?
1710 	 */
1711 	bzero(statp->f_fstr, sizeof (statp->f_fstr));
1712 
1713 	ZFS_EXIT(zfsvfs);
1714 	return (0);
1715 }
1716 
1717 static int
1718 zfs_root(vfs_t *vfsp, vnode_t **vpp)
1719 {
1720 	zfsvfs_t *zfsvfs = vfsp->vfs_data;
1721 	znode_t *rootzp;
1722 	int error;
1723 
1724 	ZFS_ENTER(zfsvfs);
1725 
1726 	error = zfs_zget(zfsvfs, zfsvfs->z_root, &rootzp);
1727 	if (error == 0)
1728 		*vpp = ZTOV(rootzp);
1729 
1730 	ZFS_EXIT(zfsvfs);
1731 	return (error);
1732 }
1733 
1734 /*
1735  * Teardown the zfsvfs::z_os.
1736  *
1737  * Note, if 'unmounting' if FALSE, we return with the 'z_teardown_lock'
1738  * and 'z_teardown_inactive_lock' held.
1739  */
1740 static int
1741 zfsvfs_teardown(zfsvfs_t *zfsvfs, boolean_t unmounting)
1742 {
1743 	znode_t	*zp;
1744 
1745 	rrw_enter(&zfsvfs->z_teardown_lock, RW_WRITER, FTAG);
1746 
1747 	if (!unmounting) {
1748 		/*
1749 		 * We purge the parent filesystem's vfsp as the parent
1750 		 * filesystem and all of its snapshots have their vnode's
1751 		 * v_vfsp set to the parent's filesystem's vfsp.  Note,
1752 		 * 'z_parent' is self referential for non-snapshots.
1753 		 */
1754 		(void) dnlc_purge_vfsp(zfsvfs->z_parent->z_vfs, 0);
1755 	}
1756 
1757 	/*
1758 	 * Close the zil. NB: Can't close the zil while zfs_inactive
1759 	 * threads are blocked as zil_close can call zfs_inactive.
1760 	 */
1761 	if (zfsvfs->z_log) {
1762 		zil_close(zfsvfs->z_log);
1763 		zfsvfs->z_log = NULL;
1764 	}
1765 
1766 	rw_enter(&zfsvfs->z_teardown_inactive_lock, RW_WRITER);
1767 
1768 	/*
1769 	 * If we are not unmounting (ie: online recv) and someone already
1770 	 * unmounted this file system while we were doing the switcheroo,
1771 	 * or a reopen of z_os failed then just bail out now.
1772 	 */
1773 	if (!unmounting && (zfsvfs->z_unmounted || zfsvfs->z_os == NULL)) {
1774 		rw_exit(&zfsvfs->z_teardown_inactive_lock);
1775 		rrw_exit(&zfsvfs->z_teardown_lock, FTAG);
1776 		return (EIO);
1777 	}
1778 
1779 	/*
1780 	 * At this point there are no vops active, and any new vops will
1781 	 * fail with EIO since we have z_teardown_lock for writer (only
1782 	 * relavent for forced unmount).
1783 	 *
1784 	 * Release all holds on dbufs.
1785 	 */
1786 	mutex_enter(&zfsvfs->z_znodes_lock);
1787 	for (zp = list_head(&zfsvfs->z_all_znodes); zp != NULL;
1788 	    zp = list_next(&zfsvfs->z_all_znodes, zp))
1789 		if (zp->z_sa_hdl) {
1790 			ASSERT(ZTOV(zp)->v_count > 0);
1791 			zfs_znode_dmu_fini(zp);
1792 		}
1793 	mutex_exit(&zfsvfs->z_znodes_lock);
1794 
1795 	/*
1796 	 * If we are unmounting, set the unmounted flag and let new vops
1797 	 * unblock.  zfs_inactive will have the unmounted behavior, and all
1798 	 * other vops will fail with EIO.
1799 	 */
1800 	if (unmounting) {
1801 		zfsvfs->z_unmounted = B_TRUE;
1802 		rrw_exit(&zfsvfs->z_teardown_lock, FTAG);
1803 		rw_exit(&zfsvfs->z_teardown_inactive_lock);
1804 	}
1805 
1806 	/*
1807 	 * z_os will be NULL if there was an error in attempting to reopen
1808 	 * zfsvfs, so just return as the properties had already been
1809 	 * unregistered and cached data had been evicted before.
1810 	 */
1811 	if (zfsvfs->z_os == NULL)
1812 		return (0);
1813 
1814 	/*
1815 	 * Unregister properties.
1816 	 */
1817 	zfs_unregister_callbacks(zfsvfs);
1818 
1819 	/*
1820 	 * Evict cached data
1821 	 */
1822 	if (dmu_objset_evict_dbufs(zfsvfs->z_os)) {
1823 		txg_wait_synced(dmu_objset_pool(zfsvfs->z_os), 0);
1824 		(void) dmu_objset_evict_dbufs(zfsvfs->z_os);
1825 	}
1826 
1827 	return (0);
1828 }
1829 
1830 /*ARGSUSED*/
1831 static int
1832 zfs_umount(vfs_t *vfsp, int fflag, cred_t *cr)
1833 {
1834 	zfsvfs_t *zfsvfs = vfsp->vfs_data;
1835 	objset_t *os;
1836 	int ret;
1837 
1838 	ret = secpolicy_fs_unmount(cr, vfsp);
1839 	if (ret) {
1840 		if (dsl_deleg_access((char *)refstr_value(vfsp->vfs_resource),
1841 		    ZFS_DELEG_PERM_MOUNT, cr))
1842 			return (ret);
1843 	}
1844 
1845 	/*
1846 	 * We purge the parent filesystem's vfsp as the parent filesystem
1847 	 * and all of its snapshots have their vnode's v_vfsp set to the
1848 	 * parent's filesystem's vfsp.  Note, 'z_parent' is self
1849 	 * referential for non-snapshots.
1850 	 */
1851 	(void) dnlc_purge_vfsp(zfsvfs->z_parent->z_vfs, 0);
1852 
1853 	/*
1854 	 * Unmount any snapshots mounted under .zfs before unmounting the
1855 	 * dataset itself.
1856 	 */
1857 	if (zfsvfs->z_ctldir != NULL &&
1858 	    (ret = zfsctl_umount_snapshots(vfsp, fflag, cr)) != 0) {
1859 		return (ret);
1860 	}
1861 
1862 	if (!(fflag & MS_FORCE)) {
1863 		/*
1864 		 * Check the number of active vnodes in the file system.
1865 		 * Our count is maintained in the vfs structure, but the
1866 		 * number is off by 1 to indicate a hold on the vfs
1867 		 * structure itself.
1868 		 *
1869 		 * The '.zfs' directory maintains a reference of its
1870 		 * own, and any active references underneath are
1871 		 * reflected in the vnode count.
1872 		 */
1873 		if (zfsvfs->z_ctldir == NULL) {
1874 			if (vfsp->vfs_count > 1)
1875 				return (EBUSY);
1876 		} else {
1877 			if (vfsp->vfs_count > 2 ||
1878 			    zfsvfs->z_ctldir->v_count > 1)
1879 				return (EBUSY);
1880 		}
1881 	}
1882 
1883 	vfsp->vfs_flag |= VFS_UNMOUNTED;
1884 
1885 	VERIFY(zfsvfs_teardown(zfsvfs, B_TRUE) == 0);
1886 	os = zfsvfs->z_os;
1887 
1888 	/*
1889 	 * z_os will be NULL if there was an error in
1890 	 * attempting to reopen zfsvfs.
1891 	 */
1892 	if (os != NULL) {
1893 		/*
1894 		 * Unset the objset user_ptr.
1895 		 */
1896 		mutex_enter(&os->os_user_ptr_lock);
1897 		dmu_objset_set_user(os, NULL);
1898 		mutex_exit(&os->os_user_ptr_lock);
1899 
1900 		/*
1901 		 * Finally release the objset
1902 		 */
1903 		dmu_objset_disown(os, zfsvfs);
1904 	}
1905 
1906 	/*
1907 	 * We can now safely destroy the '.zfs' directory node.
1908 	 */
1909 	if (zfsvfs->z_ctldir != NULL)
1910 		zfsctl_destroy(zfsvfs);
1911 
1912 	return (0);
1913 }
1914 
1915 static int
1916 zfs_vget(vfs_t *vfsp, vnode_t **vpp, fid_t *fidp)
1917 {
1918 	zfsvfs_t	*zfsvfs = vfsp->vfs_data;
1919 	znode_t		*zp;
1920 	uint64_t	object = 0;
1921 	uint64_t	fid_gen = 0;
1922 	uint64_t	gen_mask;
1923 	uint64_t	zp_gen;
1924 	int 		i, err;
1925 
1926 	*vpp = NULL;
1927 
1928 	ZFS_ENTER(zfsvfs);
1929 
1930 	if (fidp->fid_len == LONG_FID_LEN) {
1931 		zfid_long_t	*zlfid = (zfid_long_t *)fidp;
1932 		uint64_t	objsetid = 0;
1933 		uint64_t	setgen = 0;
1934 
1935 		for (i = 0; i < sizeof (zlfid->zf_setid); i++)
1936 			objsetid |= ((uint64_t)zlfid->zf_setid[i]) << (8 * i);
1937 
1938 		for (i = 0; i < sizeof (zlfid->zf_setgen); i++)
1939 			setgen |= ((uint64_t)zlfid->zf_setgen[i]) << (8 * i);
1940 
1941 		ZFS_EXIT(zfsvfs);
1942 
1943 		err = zfsctl_lookup_objset(vfsp, objsetid, &zfsvfs);
1944 		if (err)
1945 			return (EINVAL);
1946 		ZFS_ENTER(zfsvfs);
1947 	}
1948 
1949 	if (fidp->fid_len == SHORT_FID_LEN || fidp->fid_len == LONG_FID_LEN) {
1950 		zfid_short_t	*zfid = (zfid_short_t *)fidp;
1951 
1952 		for (i = 0; i < sizeof (zfid->zf_object); i++)
1953 			object |= ((uint64_t)zfid->zf_object[i]) << (8 * i);
1954 
1955 		for (i = 0; i < sizeof (zfid->zf_gen); i++)
1956 			fid_gen |= ((uint64_t)zfid->zf_gen[i]) << (8 * i);
1957 	} else {
1958 		ZFS_EXIT(zfsvfs);
1959 		return (EINVAL);
1960 	}
1961 
1962 	/* A zero fid_gen means we are in the .zfs control directories */
1963 	if (fid_gen == 0 &&
1964 	    (object == ZFSCTL_INO_ROOT || object == ZFSCTL_INO_SNAPDIR)) {
1965 		*vpp = zfsvfs->z_ctldir;
1966 		ASSERT(*vpp != NULL);
1967 		if (object == ZFSCTL_INO_SNAPDIR) {
1968 			VERIFY(zfsctl_root_lookup(*vpp, "snapshot", vpp, NULL,
1969 			    0, NULL, NULL, NULL, NULL, NULL) == 0);
1970 		} else {
1971 			VN_HOLD(*vpp);
1972 		}
1973 		ZFS_EXIT(zfsvfs);
1974 		return (0);
1975 	}
1976 
1977 	gen_mask = -1ULL >> (64 - 8 * i);
1978 
1979 	dprintf("getting %llu [%u mask %llx]\n", object, fid_gen, gen_mask);
1980 	if (err = zfs_zget(zfsvfs, object, &zp)) {
1981 		ZFS_EXIT(zfsvfs);
1982 		return (err);
1983 	}
1984 	(void) sa_lookup(zp->z_sa_hdl, SA_ZPL_GEN(zfsvfs), &zp_gen,
1985 	    sizeof (uint64_t));
1986 	zp_gen = zp_gen & gen_mask;
1987 	if (zp_gen == 0)
1988 		zp_gen = 1;
1989 	if (zp->z_unlinked || zp_gen != fid_gen) {
1990 		dprintf("znode gen (%u) != fid gen (%u)\n", zp_gen, fid_gen);
1991 		VN_RELE(ZTOV(zp));
1992 		ZFS_EXIT(zfsvfs);
1993 		return (EINVAL);
1994 	}
1995 
1996 	*vpp = ZTOV(zp);
1997 	ZFS_EXIT(zfsvfs);
1998 	return (0);
1999 }
2000 
2001 /*
2002  * Block out VOPs and close zfsvfs_t::z_os
2003  *
2004  * Note, if successful, then we return with the 'z_teardown_lock' and
2005  * 'z_teardown_inactive_lock' write held.
2006  */
2007 int
2008 zfs_suspend_fs(zfsvfs_t *zfsvfs)
2009 {
2010 	int error;
2011 
2012 	if ((error = zfsvfs_teardown(zfsvfs, B_FALSE)) != 0)
2013 		return (error);
2014 	dmu_objset_disown(zfsvfs->z_os, zfsvfs);
2015 
2016 	return (0);
2017 }
2018 
2019 /*
2020  * Reopen zfsvfs_t::z_os and release VOPs.
2021  */
2022 int
2023 zfs_resume_fs(zfsvfs_t *zfsvfs, const char *osname)
2024 {
2025 	int err, err2;
2026 
2027 	ASSERT(RRW_WRITE_HELD(&zfsvfs->z_teardown_lock));
2028 	ASSERT(RW_WRITE_HELD(&zfsvfs->z_teardown_inactive_lock));
2029 
2030 	err = dmu_objset_own(osname, DMU_OST_ZFS, B_FALSE, zfsvfs,
2031 	    &zfsvfs->z_os);
2032 	if (err) {
2033 		zfsvfs->z_os = NULL;
2034 	} else {
2035 		znode_t *zp;
2036 		uint64_t sa_obj = 0;
2037 
2038 		err2 = zap_lookup(zfsvfs->z_os, MASTER_NODE_OBJ,
2039 		    ZFS_SA_ATTRS, 8, 1, &sa_obj);
2040 
2041 		if ((err || err2) && zfsvfs->z_version >= ZPL_VERSION_SA)
2042 			goto bail;
2043 
2044 
2045 		zfsvfs->z_attr_table = sa_setup(zfsvfs->z_os, sa_obj,
2046 		    zfs_attr_table,  ZPL_END);
2047 
2048 		VERIFY(zfsvfs_setup(zfsvfs, B_FALSE) == 0);
2049 
2050 		/*
2051 		 * Attempt to re-establish all the active znodes with
2052 		 * their dbufs.  If a zfs_rezget() fails, then we'll let
2053 		 * any potential callers discover that via ZFS_ENTER_VERIFY_VP
2054 		 * when they try to use their znode.
2055 		 */
2056 		mutex_enter(&zfsvfs->z_znodes_lock);
2057 		for (zp = list_head(&zfsvfs->z_all_znodes); zp;
2058 		    zp = list_next(&zfsvfs->z_all_znodes, zp)) {
2059 			(void) zfs_rezget(zp);
2060 		}
2061 		mutex_exit(&zfsvfs->z_znodes_lock);
2062 
2063 	}
2064 
2065 bail:
2066 	/* release the VOPs */
2067 	rw_exit(&zfsvfs->z_teardown_inactive_lock);
2068 	rrw_exit(&zfsvfs->z_teardown_lock, FTAG);
2069 
2070 	if (err) {
2071 		/*
2072 		 * Since we couldn't reopen zfsvfs::z_os, force
2073 		 * unmount this file system.
2074 		 */
2075 		if (vn_vfswlock(zfsvfs->z_vfs->vfs_vnodecovered) == 0)
2076 			(void) dounmount(zfsvfs->z_vfs, MS_FORCE, CRED());
2077 	}
2078 	return (err);
2079 }
2080 
2081 static void
2082 zfs_freevfs(vfs_t *vfsp)
2083 {
2084 	zfsvfs_t *zfsvfs = vfsp->vfs_data;
2085 
2086 	/*
2087 	 * If this is a snapshot, we have an extra VFS_HOLD on our parent
2088 	 * from zfs_mount().  Release it here.  If we came through
2089 	 * zfs_mountroot() instead, we didn't grab an extra hold, so
2090 	 * skip the VFS_RELE for rootvfs.
2091 	 */
2092 	if (zfsvfs->z_issnap && (vfsp != rootvfs))
2093 		VFS_RELE(zfsvfs->z_parent->z_vfs);
2094 
2095 	zfsvfs_free(zfsvfs);
2096 
2097 	atomic_add_32(&zfs_active_fs_count, -1);
2098 }
2099 
2100 /*
2101  * VFS_INIT() initialization.  Note that there is no VFS_FINI(),
2102  * so we can't safely do any non-idempotent initialization here.
2103  * Leave that to zfs_init() and zfs_fini(), which are called
2104  * from the module's _init() and _fini() entry points.
2105  */
2106 /*ARGSUSED*/
2107 static int
2108 zfs_vfsinit(int fstype, char *name)
2109 {
2110 	int error;
2111 
2112 	zfsfstype = fstype;
2113 
2114 	/*
2115 	 * Setup vfsops and vnodeops tables.
2116 	 */
2117 	error = vfs_setfsops(fstype, zfs_vfsops_template, &zfs_vfsops);
2118 	if (error != 0) {
2119 		cmn_err(CE_WARN, "zfs: bad vfs ops template");
2120 	}
2121 
2122 	error = zfs_create_op_tables();
2123 	if (error) {
2124 		zfs_remove_op_tables();
2125 		cmn_err(CE_WARN, "zfs: bad vnode ops template");
2126 		(void) vfs_freevfsops_by_type(zfsfstype);
2127 		return (error);
2128 	}
2129 
2130 	mutex_init(&zfs_dev_mtx, NULL, MUTEX_DEFAULT, NULL);
2131 
2132 	/*
2133 	 * Unique major number for all zfs mounts.
2134 	 * If we run out of 32-bit minors, we'll getudev() another major.
2135 	 */
2136 	zfs_major = ddi_name_to_major(ZFS_DRIVER);
2137 	zfs_minor = ZFS_MIN_MINOR;
2138 
2139 	return (0);
2140 }
2141 
2142 void
2143 zfs_init(void)
2144 {
2145 	/*
2146 	 * Initialize .zfs directory structures
2147 	 */
2148 	zfsctl_init();
2149 
2150 	/*
2151 	 * Initialize znode cache, vnode ops, etc...
2152 	 */
2153 	zfs_znode_init();
2154 
2155 	dmu_objset_register_type(DMU_OST_ZFS, zfs_space_delta_cb);
2156 }
2157 
2158 void
2159 zfs_fini(void)
2160 {
2161 	zfsctl_fini();
2162 	zfs_znode_fini();
2163 }
2164 
2165 int
2166 zfs_busy(void)
2167 {
2168 	return (zfs_active_fs_count != 0);
2169 }
2170 
2171 int
2172 zfs_set_version(zfsvfs_t *zfsvfs, uint64_t newvers)
2173 {
2174 	int error;
2175 	objset_t *os = zfsvfs->z_os;
2176 	dmu_tx_t *tx;
2177 
2178 	if (newvers < ZPL_VERSION_INITIAL || newvers > ZPL_VERSION)
2179 		return (EINVAL);
2180 
2181 	if (newvers < zfsvfs->z_version)
2182 		return (EINVAL);
2183 
2184 	if (zfs_spa_version_map(newvers) >
2185 	    spa_version(dmu_objset_spa(zfsvfs->z_os)))
2186 		return (ENOTSUP);
2187 
2188 	tx = dmu_tx_create(os);
2189 	dmu_tx_hold_zap(tx, MASTER_NODE_OBJ, B_FALSE, ZPL_VERSION_STR);
2190 	if (newvers >= ZPL_VERSION_SA && !zfsvfs->z_use_sa) {
2191 		dmu_tx_hold_zap(tx, MASTER_NODE_OBJ, B_TRUE,
2192 		    ZFS_SA_ATTRS);
2193 		dmu_tx_hold_zap(tx, DMU_NEW_OBJECT, FALSE, NULL);
2194 	}
2195 	error = dmu_tx_assign(tx, TXG_WAIT);
2196 	if (error) {
2197 		dmu_tx_abort(tx);
2198 		return (error);
2199 	}
2200 
2201 	error = zap_update(os, MASTER_NODE_OBJ, ZPL_VERSION_STR,
2202 	    8, 1, &newvers, tx);
2203 
2204 	if (error) {
2205 		dmu_tx_commit(tx);
2206 		return (error);
2207 	}
2208 
2209 	if (newvers >= ZPL_VERSION_SA && !zfsvfs->z_use_sa) {
2210 		uint64_t sa_obj;
2211 
2212 		ASSERT3U(spa_version(dmu_objset_spa(zfsvfs->z_os)), >=,
2213 		    SPA_VERSION_SA);
2214 		sa_obj = zap_create(os, DMU_OT_SA_MASTER_NODE,
2215 		    DMU_OT_NONE, 0, tx);
2216 
2217 		error = zap_add(os, MASTER_NODE_OBJ,
2218 		    ZFS_SA_ATTRS, 8, 1, &sa_obj, tx);
2219 		ASSERT3U(error, ==, 0);
2220 
2221 		VERIFY(0 == sa_set_sa_object(os, sa_obj));
2222 		sa_register_update_callback(os, zfs_sa_upgrade);
2223 	}
2224 
2225 	spa_history_internal_log(LOG_DS_UPGRADE,
2226 	    dmu_objset_spa(os), tx, CRED(),
2227 	    "oldver=%llu newver=%llu dataset = %llu",
2228 	    zfsvfs->z_version, newvers, dmu_objset_id(os));
2229 
2230 	dmu_tx_commit(tx);
2231 
2232 	zfsvfs->z_version = newvers;
2233 
2234 	if (zfsvfs->z_version >= ZPL_VERSION_FUID)
2235 		zfs_set_fuid_feature(zfsvfs);
2236 
2237 	return (0);
2238 }
2239 
2240 /*
2241  * Read a property stored within the master node.
2242  */
2243 int
2244 zfs_get_zplprop(objset_t *os, zfs_prop_t prop, uint64_t *value)
2245 {
2246 	const char *pname;
2247 	int error = ENOENT;
2248 
2249 	/*
2250 	 * Look up the file system's value for the property.  For the
2251 	 * version property, we look up a slightly different string.
2252 	 */
2253 	if (prop == ZFS_PROP_VERSION)
2254 		pname = ZPL_VERSION_STR;
2255 	else
2256 		pname = zfs_prop_to_name(prop);
2257 
2258 	if (os != NULL)
2259 		error = zap_lookup(os, MASTER_NODE_OBJ, pname, 8, 1, value);
2260 
2261 	if (error == ENOENT) {
2262 		/* No value set, use the default value */
2263 		switch (prop) {
2264 		case ZFS_PROP_VERSION:
2265 			*value = ZPL_VERSION;
2266 			break;
2267 		case ZFS_PROP_NORMALIZE:
2268 		case ZFS_PROP_UTF8ONLY:
2269 			*value = 0;
2270 			break;
2271 		case ZFS_PROP_CASE:
2272 			*value = ZFS_CASE_SENSITIVE;
2273 			break;
2274 		default:
2275 			return (error);
2276 		}
2277 		error = 0;
2278 	}
2279 	return (error);
2280 }
2281 
2282 static vfsdef_t vfw = {
2283 	VFSDEF_VERSION,
2284 	MNTTYPE_ZFS,
2285 	zfs_vfsinit,
2286 	VSW_HASPROTO|VSW_CANRWRO|VSW_CANREMOUNT|VSW_VOLATILEDEV|VSW_STATS|
2287 	    VSW_XID,
2288 	&zfs_mntopts
2289 };
2290 
2291 struct modlfs zfs_modlfs = {
2292 	&mod_fsops, "ZFS filesystem version " SPA_VERSION_STRING, &vfw
2293 };
2294