xref: /freebsd/sys/contrib/openzfs/lib/libzfs/libzfs_mount.c (revision 3332f1b444d4a73238e9f59cca27bfc95fe936bd)
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 /*
23  * Copyright 2015 Nexenta Systems, Inc.  All rights reserved.
24  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
25  * Copyright (c) 2014, 2021 by Delphix. All rights reserved.
26  * Copyright 2016 Igor Kozhukhov <ikozhukhov@gmail.com>
27  * Copyright 2017 RackTop Systems.
28  * Copyright (c) 2018 Datto Inc.
29  * Copyright 2018 OmniOS Community Edition (OmniOSce) Association.
30  */
31 
32 /*
33  * Routines to manage ZFS mounts.  We separate all the nasty routines that have
34  * to deal with the OS.  The following functions are the main entry points --
35  * they are used by mount and unmount and when changing a filesystem's
36  * mountpoint.
37  *
38  *	zfs_is_mounted()
39  *	zfs_mount()
40  *	zfs_mount_at()
41  *	zfs_unmount()
42  *	zfs_unmountall()
43  *
44  * This file also contains the functions used to manage sharing filesystems via
45  * NFS and iSCSI:
46  *
47  *	zfs_is_shared()
48  *	zfs_share()
49  *	zfs_unshare()
50  *
51  *	zfs_is_shared_nfs()
52  *	zfs_is_shared_smb()
53  *	zfs_share_proto()
54  *	zfs_shareall();
55  *	zfs_unshare_nfs()
56  *	zfs_unshare_smb()
57  *	zfs_unshareall_nfs()
58  *	zfs_unshareall_smb()
59  *	zfs_unshareall()
60  *	zfs_unshareall_bypath()
61  *
62  * The following functions are available for pool consumers, and will
63  * mount/unmount and share/unshare all datasets within pool:
64  *
65  *	zpool_enable_datasets()
66  *	zpool_disable_datasets()
67  */
68 
69 #include <dirent.h>
70 #include <dlfcn.h>
71 #include <errno.h>
72 #include <fcntl.h>
73 #include <libgen.h>
74 #include <libintl.h>
75 #include <stdio.h>
76 #include <stdlib.h>
77 #include <strings.h>
78 #include <unistd.h>
79 #include <zone.h>
80 #include <sys/mntent.h>
81 #include <sys/mount.h>
82 #include <sys/stat.h>
83 #include <sys/vfs.h>
84 #include <sys/dsl_crypt.h>
85 
86 #include <libzfs.h>
87 
88 #include "libzfs_impl.h"
89 #include <thread_pool.h>
90 
91 #include <libshare.h>
92 #include <sys/systeminfo.h>
93 #define	MAXISALEN	257	/* based on sysinfo(2) man page */
94 
95 static int mount_tp_nthr = 512;	/* tpool threads for multi-threaded mounting */
96 
97 static void zfs_mount_task(void *);
98 static zfs_share_type_t zfs_is_shared_proto(zfs_handle_t *, char **,
99     zfs_share_proto_t);
100 
101 /*
102  * The share protocols table must be in the same order as the zfs_share_proto_t
103  * enum in libzfs_impl.h
104  */
105 proto_table_t proto_table[PROTO_END] = {
106 	{ZFS_PROP_SHARENFS, "nfs", EZFS_SHARENFSFAILED, EZFS_UNSHARENFSFAILED},
107 	{ZFS_PROP_SHARESMB, "smb", EZFS_SHARESMBFAILED, EZFS_UNSHARESMBFAILED},
108 };
109 
110 static zfs_share_proto_t nfs_only[] = {
111 	PROTO_NFS,
112 	PROTO_END
113 };
114 
115 static zfs_share_proto_t smb_only[] = {
116 	PROTO_SMB,
117 	PROTO_END
118 };
119 static zfs_share_proto_t share_all_proto[] = {
120 	PROTO_NFS,
121 	PROTO_SMB,
122 	PROTO_END
123 };
124 
125 
126 
127 static boolean_t
128 dir_is_empty_stat(const char *dirname)
129 {
130 	struct stat st;
131 
132 	/*
133 	 * We only want to return false if the given path is a non empty
134 	 * directory, all other errors are handled elsewhere.
135 	 */
136 	if (stat(dirname, &st) < 0 || !S_ISDIR(st.st_mode)) {
137 		return (B_TRUE);
138 	}
139 
140 	/*
141 	 * An empty directory will still have two entries in it, one
142 	 * entry for each of "." and "..".
143 	 */
144 	if (st.st_size > 2) {
145 		return (B_FALSE);
146 	}
147 
148 	return (B_TRUE);
149 }
150 
151 static boolean_t
152 dir_is_empty_readdir(const char *dirname)
153 {
154 	DIR *dirp;
155 	struct dirent64 *dp;
156 	int dirfd;
157 
158 	if ((dirfd = openat(AT_FDCWD, dirname,
159 	    O_RDONLY | O_NDELAY | O_LARGEFILE | O_CLOEXEC, 0)) < 0) {
160 		return (B_TRUE);
161 	}
162 
163 	if ((dirp = fdopendir(dirfd)) == NULL) {
164 		(void) close(dirfd);
165 		return (B_TRUE);
166 	}
167 
168 	while ((dp = readdir64(dirp)) != NULL) {
169 
170 		if (strcmp(dp->d_name, ".") == 0 ||
171 		    strcmp(dp->d_name, "..") == 0)
172 			continue;
173 
174 		(void) closedir(dirp);
175 		return (B_FALSE);
176 	}
177 
178 	(void) closedir(dirp);
179 	return (B_TRUE);
180 }
181 
182 /*
183  * Returns true if the specified directory is empty.  If we can't open the
184  * directory at all, return true so that the mount can fail with a more
185  * informative error message.
186  */
187 static boolean_t
188 dir_is_empty(const char *dirname)
189 {
190 	struct statfs64 st;
191 
192 	/*
193 	 * If the statvfs call fails or the filesystem is not a ZFS
194 	 * filesystem, fall back to the slow path which uses readdir.
195 	 */
196 	if ((statfs64(dirname, &st) != 0) ||
197 	    (st.f_type != ZFS_SUPER_MAGIC)) {
198 		return (dir_is_empty_readdir(dirname));
199 	}
200 
201 	/*
202 	 * At this point, we know the provided path is on a ZFS
203 	 * filesystem, so we can use stat instead of readdir to
204 	 * determine if the directory is empty or not. We try to avoid
205 	 * using readdir because that requires opening "dirname"; this
206 	 * open file descriptor can potentially end up in a child
207 	 * process if there's a concurrent fork, thus preventing the
208 	 * zfs_mount() from otherwise succeeding (the open file
209 	 * descriptor inherited by the child process will cause the
210 	 * parent's mount to fail with EBUSY). The performance
211 	 * implications of replacing the open, read, and close with a
212 	 * single stat is nice; but is not the main motivation for the
213 	 * added complexity.
214 	 */
215 	return (dir_is_empty_stat(dirname));
216 }
217 
218 /*
219  * Checks to see if the mount is active.  If the filesystem is mounted, we fill
220  * in 'where' with the current mountpoint, and return 1.  Otherwise, we return
221  * 0.
222  */
223 boolean_t
224 is_mounted(libzfs_handle_t *zfs_hdl, const char *special, char **where)
225 {
226 	struct mnttab entry;
227 
228 	if (libzfs_mnttab_find(zfs_hdl, special, &entry) != 0)
229 		return (B_FALSE);
230 
231 	if (where != NULL)
232 		*where = zfs_strdup(zfs_hdl, entry.mnt_mountp);
233 
234 	return (B_TRUE);
235 }
236 
237 boolean_t
238 zfs_is_mounted(zfs_handle_t *zhp, char **where)
239 {
240 	return (is_mounted(zhp->zfs_hdl, zfs_get_name(zhp), where));
241 }
242 
243 /*
244  * Checks any higher order concerns about whether the given dataset is
245  * mountable, false otherwise.  zfs_is_mountable_internal specifically assumes
246  * that the caller has verified the sanity of mounting the dataset at
247  * mountpoint to the extent the caller wants.
248  */
249 static boolean_t
250 zfs_is_mountable_internal(zfs_handle_t *zhp, const char *mountpoint)
251 {
252 
253 	if (zfs_prop_get_int(zhp, ZFS_PROP_ZONED) &&
254 	    getzoneid() == GLOBAL_ZONEID)
255 		return (B_FALSE);
256 
257 	return (B_TRUE);
258 }
259 
260 /*
261  * Returns true if the given dataset is mountable, false otherwise.  Returns the
262  * mountpoint in 'buf'.
263  */
264 boolean_t
265 zfs_is_mountable(zfs_handle_t *zhp, char *buf, size_t buflen,
266     zprop_source_t *source, int flags)
267 {
268 	char sourceloc[MAXNAMELEN];
269 	zprop_source_t sourcetype;
270 
271 	if (!zfs_prop_valid_for_type(ZFS_PROP_MOUNTPOINT, zhp->zfs_type,
272 	    B_FALSE))
273 		return (B_FALSE);
274 
275 	verify(zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT, buf, buflen,
276 	    &sourcetype, sourceloc, sizeof (sourceloc), B_FALSE) == 0);
277 
278 	if (strcmp(buf, ZFS_MOUNTPOINT_NONE) == 0 ||
279 	    strcmp(buf, ZFS_MOUNTPOINT_LEGACY) == 0)
280 		return (B_FALSE);
281 
282 	if (zfs_prop_get_int(zhp, ZFS_PROP_CANMOUNT) == ZFS_CANMOUNT_OFF)
283 		return (B_FALSE);
284 
285 	if (!zfs_is_mountable_internal(zhp, buf))
286 		return (B_FALSE);
287 
288 	if (zfs_prop_get_int(zhp, ZFS_PROP_REDACTED) && !(flags & MS_FORCE))
289 		return (B_FALSE);
290 
291 	if (source)
292 		*source = sourcetype;
293 
294 	return (B_TRUE);
295 }
296 
297 /*
298  * The filesystem is mounted by invoking the system mount utility rather
299  * than by the system call mount(2).  This ensures that the /etc/mtab
300  * file is correctly locked for the update.  Performing our own locking
301  * and /etc/mtab update requires making an unsafe assumption about how
302  * the mount utility performs its locking.  Unfortunately, this also means
303  * in the case of a mount failure we do not have the exact errno.  We must
304  * make due with return value from the mount process.
305  *
306  * In the long term a shared library called libmount is under development
307  * which provides a common API to address the locking and errno issues.
308  * Once the standard mount utility has been updated to use this library
309  * we can add an autoconf check to conditionally use it.
310  *
311  * http://www.kernel.org/pub/linux/utils/util-linux/libmount-docs/index.html
312  */
313 
314 static int
315 zfs_add_option(zfs_handle_t *zhp, char *options, int len,
316     zfs_prop_t prop, char *on, char *off)
317 {
318 	char *source;
319 	uint64_t value;
320 
321 	/* Skip adding duplicate default options */
322 	if ((strstr(options, on) != NULL) || (strstr(options, off) != NULL))
323 		return (0);
324 
325 	/*
326 	 * zfs_prop_get_int() is not used to ensure our mount options
327 	 * are not influenced by the current /proc/self/mounts contents.
328 	 */
329 	value = getprop_uint64(zhp, prop, &source);
330 
331 	(void) strlcat(options, ",", len);
332 	(void) strlcat(options, value ? on : off, len);
333 
334 	return (0);
335 }
336 
337 static int
338 zfs_add_options(zfs_handle_t *zhp, char *options, int len)
339 {
340 	int error = 0;
341 
342 	error = zfs_add_option(zhp, options, len,
343 	    ZFS_PROP_ATIME, MNTOPT_ATIME, MNTOPT_NOATIME);
344 	/*
345 	 * don't add relatime/strictatime when atime=off, otherwise strictatime
346 	 * will force atime=on
347 	 */
348 	if (strstr(options, MNTOPT_NOATIME) == NULL) {
349 		error = zfs_add_option(zhp, options, len,
350 		    ZFS_PROP_RELATIME, MNTOPT_RELATIME, MNTOPT_STRICTATIME);
351 	}
352 	error = error ? error : zfs_add_option(zhp, options, len,
353 	    ZFS_PROP_DEVICES, MNTOPT_DEVICES, MNTOPT_NODEVICES);
354 	error = error ? error : zfs_add_option(zhp, options, len,
355 	    ZFS_PROP_EXEC, MNTOPT_EXEC, MNTOPT_NOEXEC);
356 	error = error ? error : zfs_add_option(zhp, options, len,
357 	    ZFS_PROP_READONLY, MNTOPT_RO, MNTOPT_RW);
358 	error = error ? error : zfs_add_option(zhp, options, len,
359 	    ZFS_PROP_SETUID, MNTOPT_SETUID, MNTOPT_NOSETUID);
360 	error = error ? error : zfs_add_option(zhp, options, len,
361 	    ZFS_PROP_NBMAND, MNTOPT_NBMAND, MNTOPT_NONBMAND);
362 
363 	return (error);
364 }
365 
366 int
367 zfs_mount(zfs_handle_t *zhp, const char *options, int flags)
368 {
369 	char mountpoint[ZFS_MAXPROPLEN];
370 
371 	if (!zfs_is_mountable(zhp, mountpoint, sizeof (mountpoint), NULL,
372 	    flags))
373 		return (0);
374 
375 	return (zfs_mount_at(zhp, options, flags, mountpoint));
376 }
377 
378 /*
379  * Mount the given filesystem.
380  */
381 int
382 zfs_mount_at(zfs_handle_t *zhp, const char *options, int flags,
383     const char *mountpoint)
384 {
385 	struct stat buf;
386 	char mntopts[MNT_LINE_MAX];
387 	char overlay[ZFS_MAXPROPLEN];
388 	char prop_encroot[MAXNAMELEN];
389 	boolean_t is_encroot;
390 	zfs_handle_t *encroot_hp = zhp;
391 	libzfs_handle_t *hdl = zhp->zfs_hdl;
392 	uint64_t keystatus;
393 	int remount = 0, rc;
394 
395 	if (options == NULL) {
396 		(void) strlcpy(mntopts, MNTOPT_DEFAULTS, sizeof (mntopts));
397 	} else {
398 		(void) strlcpy(mntopts, options, sizeof (mntopts));
399 	}
400 
401 	if (strstr(mntopts, MNTOPT_REMOUNT) != NULL)
402 		remount = 1;
403 
404 	/* Potentially duplicates some checks if invoked by zfs_mount(). */
405 	if (!zfs_is_mountable_internal(zhp, mountpoint))
406 		return (0);
407 
408 	/*
409 	 * If the pool is imported read-only then all mounts must be read-only
410 	 */
411 	if (zpool_get_prop_int(zhp->zpool_hdl, ZPOOL_PROP_READONLY, NULL))
412 		(void) strlcat(mntopts, "," MNTOPT_RO, sizeof (mntopts));
413 
414 	/*
415 	 * Append default mount options which apply to the mount point.
416 	 * This is done because under Linux (unlike Solaris) multiple mount
417 	 * points may reference a single super block.  This means that just
418 	 * given a super block there is no back reference to update the per
419 	 * mount point options.
420 	 */
421 	rc = zfs_add_options(zhp, mntopts, sizeof (mntopts));
422 	if (rc) {
423 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
424 		    "default options unavailable"));
425 		return (zfs_error_fmt(hdl, EZFS_MOUNTFAILED,
426 		    dgettext(TEXT_DOMAIN, "cannot mount '%s'"),
427 		    mountpoint));
428 	}
429 
430 	/*
431 	 * If the filesystem is encrypted the key must be loaded  in order to
432 	 * mount. If the key isn't loaded, the MS_CRYPT flag decides whether
433 	 * or not we attempt to load the keys. Note: we must call
434 	 * zfs_refresh_properties() here since some callers of this function
435 	 * (most notably zpool_enable_datasets()) may implicitly load our key
436 	 * by loading the parent's key first.
437 	 */
438 	if (zfs_prop_get_int(zhp, ZFS_PROP_ENCRYPTION) != ZIO_CRYPT_OFF) {
439 		zfs_refresh_properties(zhp);
440 		keystatus = zfs_prop_get_int(zhp, ZFS_PROP_KEYSTATUS);
441 
442 		/*
443 		 * If the key is unavailable and MS_CRYPT is set give the
444 		 * user a chance to enter the key. Otherwise just fail
445 		 * immediately.
446 		 */
447 		if (keystatus == ZFS_KEYSTATUS_UNAVAILABLE) {
448 			if (flags & MS_CRYPT) {
449 				rc = zfs_crypto_get_encryption_root(zhp,
450 				    &is_encroot, prop_encroot);
451 				if (rc) {
452 					zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
453 					    "Failed to get encryption root for "
454 					    "'%s'."), zfs_get_name(zhp));
455 					return (rc);
456 				}
457 
458 				if (!is_encroot) {
459 					encroot_hp = zfs_open(hdl, prop_encroot,
460 					    ZFS_TYPE_DATASET);
461 					if (encroot_hp == NULL)
462 						return (hdl->libzfs_error);
463 				}
464 
465 				rc = zfs_crypto_load_key(encroot_hp,
466 				    B_FALSE, NULL);
467 
468 				if (!is_encroot)
469 					zfs_close(encroot_hp);
470 				if (rc)
471 					return (rc);
472 			} else {
473 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
474 				    "encryption key not loaded"));
475 				return (zfs_error_fmt(hdl, EZFS_MOUNTFAILED,
476 				    dgettext(TEXT_DOMAIN, "cannot mount '%s'"),
477 				    mountpoint));
478 			}
479 		}
480 
481 	}
482 
483 	/*
484 	 * Append zfsutil option so the mount helper allow the mount
485 	 */
486 	strlcat(mntopts, "," MNTOPT_ZFSUTIL, sizeof (mntopts));
487 
488 	/* Create the directory if it doesn't already exist */
489 	if (lstat(mountpoint, &buf) != 0) {
490 		if (mkdirp(mountpoint, 0755) != 0) {
491 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
492 			    "failed to create mountpoint: %s"),
493 			    strerror(errno));
494 			return (zfs_error_fmt(hdl, EZFS_MOUNTFAILED,
495 			    dgettext(TEXT_DOMAIN, "cannot mount '%s'"),
496 			    mountpoint));
497 		}
498 	}
499 
500 	/*
501 	 * Overlay mounts are enabled by default but may be disabled
502 	 * via the 'overlay' property. The -O flag remains for compatibility.
503 	 */
504 	if (!(flags & MS_OVERLAY)) {
505 		if (zfs_prop_get(zhp, ZFS_PROP_OVERLAY, overlay,
506 		    sizeof (overlay), NULL, NULL, 0, B_FALSE) == 0) {
507 			if (strcmp(overlay, "on") == 0) {
508 				flags |= MS_OVERLAY;
509 			}
510 		}
511 	}
512 
513 	/*
514 	 * Determine if the mountpoint is empty.  If so, refuse to perform the
515 	 * mount.  We don't perform this check if 'remount' is
516 	 * specified or if overlay option (-O) is given
517 	 */
518 	if ((flags & MS_OVERLAY) == 0 && !remount &&
519 	    !dir_is_empty(mountpoint)) {
520 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
521 		    "directory is not empty"));
522 		return (zfs_error_fmt(hdl, EZFS_MOUNTFAILED,
523 		    dgettext(TEXT_DOMAIN, "cannot mount '%s'"), mountpoint));
524 	}
525 
526 	/* perform the mount */
527 	rc = do_mount(zhp, mountpoint, mntopts, flags);
528 	if (rc) {
529 		/*
530 		 * Generic errors are nasty, but there are just way too many
531 		 * from mount(), and they're well-understood.  We pick a few
532 		 * common ones to improve upon.
533 		 */
534 		if (rc == EBUSY) {
535 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
536 			    "mountpoint or dataset is busy"));
537 		} else if (rc == EPERM) {
538 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
539 			    "Insufficient privileges"));
540 		} else if (rc == ENOTSUP) {
541 			int spa_version;
542 
543 			VERIFY(zfs_spa_version(zhp, &spa_version) == 0);
544 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
545 			    "Can't mount a version %llu "
546 			    "file system on a version %d pool. Pool must be"
547 			    " upgraded to mount this file system."),
548 			    (u_longlong_t)zfs_prop_get_int(zhp,
549 			    ZFS_PROP_VERSION), spa_version);
550 		} else {
551 			zfs_error_aux(hdl, "%s", strerror(rc));
552 		}
553 		return (zfs_error_fmt(hdl, EZFS_MOUNTFAILED,
554 		    dgettext(TEXT_DOMAIN, "cannot mount '%s'"),
555 		    zhp->zfs_name));
556 	}
557 
558 	/* remove the mounted entry before re-adding on remount */
559 	if (remount)
560 		libzfs_mnttab_remove(hdl, zhp->zfs_name);
561 
562 	/* add the mounted entry into our cache */
563 	libzfs_mnttab_add(hdl, zfs_get_name(zhp), mountpoint, mntopts);
564 	return (0);
565 }
566 
567 /*
568  * Unmount a single filesystem.
569  */
570 static int
571 unmount_one(zfs_handle_t *zhp, const char *mountpoint, int flags)
572 {
573 	int error;
574 
575 	error = do_unmount(zhp, mountpoint, flags);
576 	if (error != 0) {
577 		int libzfs_err;
578 
579 		switch (error) {
580 		case EBUSY:
581 			libzfs_err = EZFS_BUSY;
582 			break;
583 		case EIO:
584 			libzfs_err = EZFS_IO;
585 			break;
586 		case ENOENT:
587 			libzfs_err = EZFS_NOENT;
588 			break;
589 		case ENOMEM:
590 			libzfs_err = EZFS_NOMEM;
591 			break;
592 		case EPERM:
593 			libzfs_err = EZFS_PERM;
594 			break;
595 		default:
596 			libzfs_err = EZFS_UMOUNTFAILED;
597 		}
598 		return (zfs_error_fmt(zhp->zfs_hdl, libzfs_err,
599 		    dgettext(TEXT_DOMAIN, "cannot unmount '%s'"),
600 		    mountpoint));
601 	}
602 
603 	return (0);
604 }
605 
606 /*
607  * Unmount the given filesystem.
608  */
609 int
610 zfs_unmount(zfs_handle_t *zhp, const char *mountpoint, int flags)
611 {
612 	libzfs_handle_t *hdl = zhp->zfs_hdl;
613 	struct mnttab entry;
614 	char *mntpt = NULL;
615 	boolean_t encroot, unmounted = B_FALSE;
616 
617 	/* check to see if we need to unmount the filesystem */
618 	if (mountpoint != NULL || ((zfs_get_type(zhp) == ZFS_TYPE_FILESYSTEM) &&
619 	    libzfs_mnttab_find(hdl, zhp->zfs_name, &entry) == 0)) {
620 		/*
621 		 * mountpoint may have come from a call to
622 		 * getmnt/getmntany if it isn't NULL. If it is NULL,
623 		 * we know it comes from libzfs_mnttab_find which can
624 		 * then get freed later. We strdup it to play it safe.
625 		 */
626 		if (mountpoint == NULL)
627 			mntpt = zfs_strdup(hdl, entry.mnt_mountp);
628 		else
629 			mntpt = zfs_strdup(hdl, mountpoint);
630 
631 		/*
632 		 * Unshare and unmount the filesystem
633 		 */
634 		if (zfs_unshare_proto(zhp, mntpt, share_all_proto) != 0) {
635 			free(mntpt);
636 			return (-1);
637 		}
638 		zfs_commit_all_shares();
639 
640 		if (unmount_one(zhp, mntpt, flags) != 0) {
641 			free(mntpt);
642 			(void) zfs_shareall(zhp);
643 			zfs_commit_all_shares();
644 			return (-1);
645 		}
646 
647 		libzfs_mnttab_remove(hdl, zhp->zfs_name);
648 		free(mntpt);
649 		unmounted = B_TRUE;
650 	}
651 
652 	/*
653 	 * If the MS_CRYPT flag is provided we must ensure we attempt to
654 	 * unload the dataset's key regardless of whether we did any work
655 	 * to unmount it. We only do this for encryption roots.
656 	 */
657 	if ((flags & MS_CRYPT) != 0 &&
658 	    zfs_prop_get_int(zhp, ZFS_PROP_ENCRYPTION) != ZIO_CRYPT_OFF) {
659 		zfs_refresh_properties(zhp);
660 
661 		if (zfs_crypto_get_encryption_root(zhp, &encroot, NULL) != 0 &&
662 		    unmounted) {
663 			(void) zfs_mount(zhp, NULL, 0);
664 			return (-1);
665 		}
666 
667 		if (encroot && zfs_prop_get_int(zhp, ZFS_PROP_KEYSTATUS) ==
668 		    ZFS_KEYSTATUS_AVAILABLE &&
669 		    zfs_crypto_unload_key(zhp) != 0) {
670 			(void) zfs_mount(zhp, NULL, 0);
671 			return (-1);
672 		}
673 	}
674 
675 	zpool_disable_volume_os(zhp->zfs_name);
676 
677 	return (0);
678 }
679 
680 /*
681  * Unmount this filesystem and any children inheriting the mountpoint property.
682  * To do this, just act like we're changing the mountpoint property, but don't
683  * remount the filesystems afterwards.
684  */
685 int
686 zfs_unmountall(zfs_handle_t *zhp, int flags)
687 {
688 	prop_changelist_t *clp;
689 	int ret;
690 
691 	clp = changelist_gather(zhp, ZFS_PROP_MOUNTPOINT,
692 	    CL_GATHER_ITER_MOUNTED, flags);
693 	if (clp == NULL)
694 		return (-1);
695 
696 	ret = changelist_prefix(clp);
697 	changelist_free(clp);
698 
699 	return (ret);
700 }
701 
702 boolean_t
703 zfs_is_shared(zfs_handle_t *zhp)
704 {
705 	zfs_share_type_t rc = 0;
706 	zfs_share_proto_t *curr_proto;
707 
708 	if (ZFS_IS_VOLUME(zhp))
709 		return (B_FALSE);
710 
711 	for (curr_proto = share_all_proto; *curr_proto != PROTO_END;
712 	    curr_proto++)
713 		rc |= zfs_is_shared_proto(zhp, NULL, *curr_proto);
714 
715 	return (rc ? B_TRUE : B_FALSE);
716 }
717 
718 /*
719  * Unshare a filesystem by mountpoint.
720  */
721 int
722 unshare_one(libzfs_handle_t *hdl, const char *name, const char *mountpoint,
723     zfs_share_proto_t proto)
724 {
725 	int err;
726 
727 	err = sa_disable_share(mountpoint, proto_table[proto].p_name);
728 	if (err != SA_OK) {
729 		return (zfs_error_fmt(hdl, proto_table[proto].p_unshare_err,
730 		    dgettext(TEXT_DOMAIN, "cannot unshare '%s': %s"),
731 		    name, sa_errorstr(err)));
732 	}
733 	return (0);
734 }
735 
736 /*
737  * Query libshare for the given mountpoint and protocol, returning
738  * a zfs_share_type_t value.
739  */
740 zfs_share_type_t
741 is_shared(const char *mountpoint, zfs_share_proto_t proto)
742 {
743 	if (sa_is_shared(mountpoint, proto_table[proto].p_name)) {
744 		switch (proto) {
745 		case PROTO_NFS:
746 			return (SHARED_NFS);
747 		case PROTO_SMB:
748 			return (SHARED_SMB);
749 		default:
750 			return (SHARED_NOT_SHARED);
751 		}
752 	}
753 	return (SHARED_NOT_SHARED);
754 }
755 
756 /*
757  * Share the given filesystem according to the options in the specified
758  * protocol specific properties (sharenfs, sharesmb).  We rely
759  * on "libshare" to do the dirty work for us.
760  */
761 int
762 zfs_share_proto(zfs_handle_t *zhp, zfs_share_proto_t *proto)
763 {
764 	char mountpoint[ZFS_MAXPROPLEN];
765 	char shareopts[ZFS_MAXPROPLEN];
766 	char sourcestr[ZFS_MAXPROPLEN];
767 	zfs_share_proto_t *curr_proto;
768 	zprop_source_t sourcetype;
769 	int err = 0;
770 
771 	if (!zfs_is_mountable(zhp, mountpoint, sizeof (mountpoint), NULL, 0))
772 		return (0);
773 
774 	for (curr_proto = proto; *curr_proto != PROTO_END; curr_proto++) {
775 		/*
776 		 * Return success if there are no share options.
777 		 */
778 		if (zfs_prop_get(zhp, proto_table[*curr_proto].p_prop,
779 		    shareopts, sizeof (shareopts), &sourcetype, sourcestr,
780 		    ZFS_MAXPROPLEN, B_FALSE) != 0 ||
781 		    strcmp(shareopts, "off") == 0)
782 			continue;
783 
784 		/*
785 		 * If the 'zoned' property is set, then zfs_is_mountable()
786 		 * will have already bailed out if we are in the global zone.
787 		 * But local zones cannot be NFS servers, so we ignore it for
788 		 * local zones as well.
789 		 */
790 		if (zfs_prop_get_int(zhp, ZFS_PROP_ZONED))
791 			continue;
792 
793 		err = sa_enable_share(zfs_get_name(zhp), mountpoint, shareopts,
794 		    proto_table[*curr_proto].p_name);
795 		if (err != SA_OK) {
796 			return (zfs_error_fmt(zhp->zfs_hdl,
797 			    proto_table[*curr_proto].p_share_err,
798 			    dgettext(TEXT_DOMAIN, "cannot share '%s: %s'"),
799 			    zfs_get_name(zhp), sa_errorstr(err)));
800 		}
801 
802 	}
803 	return (0);
804 }
805 
806 int
807 zfs_share(zfs_handle_t *zhp)
808 {
809 	assert(!ZFS_IS_VOLUME(zhp));
810 	return (zfs_share_proto(zhp, share_all_proto));
811 }
812 
813 int
814 zfs_unshare(zfs_handle_t *zhp)
815 {
816 	assert(!ZFS_IS_VOLUME(zhp));
817 	return (zfs_unshareall(zhp));
818 }
819 
820 /*
821  * Check to see if the filesystem is currently shared.
822  */
823 static zfs_share_type_t
824 zfs_is_shared_proto(zfs_handle_t *zhp, char **where, zfs_share_proto_t proto)
825 {
826 	char *mountpoint;
827 	zfs_share_type_t rc;
828 
829 	if (!zfs_is_mounted(zhp, &mountpoint))
830 		return (SHARED_NOT_SHARED);
831 
832 	if ((rc = is_shared(mountpoint, proto))
833 	    != SHARED_NOT_SHARED) {
834 		if (where != NULL)
835 			*where = mountpoint;
836 		else
837 			free(mountpoint);
838 		return (rc);
839 	} else {
840 		free(mountpoint);
841 		return (SHARED_NOT_SHARED);
842 	}
843 }
844 
845 boolean_t
846 zfs_is_shared_nfs(zfs_handle_t *zhp, char **where)
847 {
848 	return (zfs_is_shared_proto(zhp, where,
849 	    PROTO_NFS) != SHARED_NOT_SHARED);
850 }
851 
852 boolean_t
853 zfs_is_shared_smb(zfs_handle_t *zhp, char **where)
854 {
855 	return (zfs_is_shared_proto(zhp, where,
856 	    PROTO_SMB) != SHARED_NOT_SHARED);
857 }
858 
859 /*
860  * zfs_parse_options(options, proto)
861  *
862  * Call the legacy parse interface to get the protocol specific
863  * options using the NULL arg to indicate that this is a "parse" only.
864  */
865 int
866 zfs_parse_options(char *options, zfs_share_proto_t proto)
867 {
868 	return (sa_validate_shareopts(options, proto_table[proto].p_name));
869 }
870 
871 void
872 zfs_commit_proto(zfs_share_proto_t *proto)
873 {
874 	zfs_share_proto_t *curr_proto;
875 	for (curr_proto = proto; *curr_proto != PROTO_END; curr_proto++) {
876 		sa_commit_shares(proto_table[*curr_proto].p_name);
877 	}
878 }
879 
880 void
881 zfs_commit_nfs_shares(void)
882 {
883 	zfs_commit_proto(nfs_only);
884 }
885 
886 void
887 zfs_commit_smb_shares(void)
888 {
889 	zfs_commit_proto(smb_only);
890 }
891 
892 void
893 zfs_commit_all_shares(void)
894 {
895 	zfs_commit_proto(share_all_proto);
896 }
897 
898 void
899 zfs_commit_shares(const char *proto)
900 {
901 	if (proto == NULL)
902 		zfs_commit_proto(share_all_proto);
903 	else if (strcmp(proto, "nfs") == 0)
904 		zfs_commit_proto(nfs_only);
905 	else if (strcmp(proto, "smb") == 0)
906 		zfs_commit_proto(smb_only);
907 }
908 
909 int
910 zfs_share_nfs(zfs_handle_t *zhp)
911 {
912 	return (zfs_share_proto(zhp, nfs_only));
913 }
914 
915 int
916 zfs_share_smb(zfs_handle_t *zhp)
917 {
918 	return (zfs_share_proto(zhp, smb_only));
919 }
920 
921 int
922 zfs_shareall(zfs_handle_t *zhp)
923 {
924 	return (zfs_share_proto(zhp, share_all_proto));
925 }
926 
927 /*
928  * Unshare the given filesystem.
929  */
930 int
931 zfs_unshare_proto(zfs_handle_t *zhp, const char *mountpoint,
932     zfs_share_proto_t *proto)
933 {
934 	libzfs_handle_t *hdl = zhp->zfs_hdl;
935 	struct mnttab entry;
936 	char *mntpt = NULL;
937 
938 	/* check to see if need to unmount the filesystem */
939 	if (mountpoint != NULL)
940 		mntpt = zfs_strdup(hdl, mountpoint);
941 
942 	if (mountpoint != NULL || ((zfs_get_type(zhp) == ZFS_TYPE_FILESYSTEM) &&
943 	    libzfs_mnttab_find(hdl, zfs_get_name(zhp), &entry) == 0)) {
944 		zfs_share_proto_t *curr_proto;
945 
946 		if (mountpoint == NULL)
947 			mntpt = zfs_strdup(zhp->zfs_hdl, entry.mnt_mountp);
948 
949 		for (curr_proto = proto; *curr_proto != PROTO_END;
950 		    curr_proto++) {
951 
952 			if (is_shared(mntpt, *curr_proto)) {
953 				if (unshare_one(hdl, zhp->zfs_name,
954 				    mntpt, *curr_proto) != 0) {
955 					if (mntpt != NULL)
956 						free(mntpt);
957 					return (-1);
958 				}
959 			}
960 		}
961 	}
962 	if (mntpt != NULL)
963 		free(mntpt);
964 
965 	return (0);
966 }
967 
968 int
969 zfs_unshare_nfs(zfs_handle_t *zhp, const char *mountpoint)
970 {
971 	return (zfs_unshare_proto(zhp, mountpoint, nfs_only));
972 }
973 
974 int
975 zfs_unshare_smb(zfs_handle_t *zhp, const char *mountpoint)
976 {
977 	return (zfs_unshare_proto(zhp, mountpoint, smb_only));
978 }
979 
980 /*
981  * Same as zfs_unmountall(), but for NFS and SMB unshares.
982  */
983 static int
984 zfs_unshareall_proto(zfs_handle_t *zhp, zfs_share_proto_t *proto)
985 {
986 	prop_changelist_t *clp;
987 	int ret;
988 
989 	clp = changelist_gather(zhp, ZFS_PROP_SHARENFS, 0, 0);
990 	if (clp == NULL)
991 		return (-1);
992 
993 	ret = changelist_unshare(clp, proto);
994 	changelist_free(clp);
995 
996 	return (ret);
997 }
998 
999 int
1000 zfs_unshareall_nfs(zfs_handle_t *zhp)
1001 {
1002 	return (zfs_unshareall_proto(zhp, nfs_only));
1003 }
1004 
1005 int
1006 zfs_unshareall_smb(zfs_handle_t *zhp)
1007 {
1008 	return (zfs_unshareall_proto(zhp, smb_only));
1009 }
1010 
1011 int
1012 zfs_unshareall(zfs_handle_t *zhp)
1013 {
1014 	return (zfs_unshareall_proto(zhp, share_all_proto));
1015 }
1016 
1017 int
1018 zfs_unshareall_bypath(zfs_handle_t *zhp, const char *mountpoint)
1019 {
1020 	return (zfs_unshare_proto(zhp, mountpoint, share_all_proto));
1021 }
1022 
1023 int
1024 zfs_unshareall_bytype(zfs_handle_t *zhp, const char *mountpoint,
1025     const char *proto)
1026 {
1027 	if (proto == NULL)
1028 		return (zfs_unshare_proto(zhp, mountpoint, share_all_proto));
1029 	if (strcmp(proto, "nfs") == 0)
1030 		return (zfs_unshare_proto(zhp, mountpoint, nfs_only));
1031 	else if (strcmp(proto, "smb") == 0)
1032 		return (zfs_unshare_proto(zhp, mountpoint, smb_only));
1033 	else
1034 		return (1);
1035 }
1036 
1037 /*
1038  * Remove the mountpoint associated with the current dataset, if necessary.
1039  * We only remove the underlying directory if:
1040  *
1041  *	- The mountpoint is not 'none' or 'legacy'
1042  *	- The mountpoint is non-empty
1043  *	- The mountpoint is the default or inherited
1044  *	- The 'zoned' property is set, or we're in a local zone
1045  *
1046  * Any other directories we leave alone.
1047  */
1048 void
1049 remove_mountpoint(zfs_handle_t *zhp)
1050 {
1051 	char mountpoint[ZFS_MAXPROPLEN];
1052 	zprop_source_t source;
1053 
1054 	if (!zfs_is_mountable(zhp, mountpoint, sizeof (mountpoint),
1055 	    &source, 0))
1056 		return;
1057 
1058 	if (source == ZPROP_SRC_DEFAULT ||
1059 	    source == ZPROP_SRC_INHERITED) {
1060 		/*
1061 		 * Try to remove the directory, silently ignoring any errors.
1062 		 * The filesystem may have since been removed or moved around,
1063 		 * and this error isn't really useful to the administrator in
1064 		 * any way.
1065 		 */
1066 		(void) rmdir(mountpoint);
1067 	}
1068 }
1069 
1070 /*
1071  * Add the given zfs handle to the cb_handles array, dynamically reallocating
1072  * the array if it is out of space.
1073  */
1074 void
1075 libzfs_add_handle(get_all_cb_t *cbp, zfs_handle_t *zhp)
1076 {
1077 	if (cbp->cb_alloc == cbp->cb_used) {
1078 		size_t newsz;
1079 		zfs_handle_t **newhandles;
1080 
1081 		newsz = cbp->cb_alloc != 0 ? cbp->cb_alloc * 2 : 64;
1082 		newhandles = zfs_realloc(zhp->zfs_hdl,
1083 		    cbp->cb_handles, cbp->cb_alloc * sizeof (zfs_handle_t *),
1084 		    newsz * sizeof (zfs_handle_t *));
1085 		cbp->cb_handles = newhandles;
1086 		cbp->cb_alloc = newsz;
1087 	}
1088 	cbp->cb_handles[cbp->cb_used++] = zhp;
1089 }
1090 
1091 /*
1092  * Recursive helper function used during file system enumeration
1093  */
1094 static int
1095 zfs_iter_cb(zfs_handle_t *zhp, void *data)
1096 {
1097 	get_all_cb_t *cbp = data;
1098 
1099 	if (!(zfs_get_type(zhp) & ZFS_TYPE_FILESYSTEM)) {
1100 		zfs_close(zhp);
1101 		return (0);
1102 	}
1103 
1104 	if (zfs_prop_get_int(zhp, ZFS_PROP_CANMOUNT) == ZFS_CANMOUNT_NOAUTO) {
1105 		zfs_close(zhp);
1106 		return (0);
1107 	}
1108 
1109 	if (zfs_prop_get_int(zhp, ZFS_PROP_KEYSTATUS) ==
1110 	    ZFS_KEYSTATUS_UNAVAILABLE) {
1111 		zfs_close(zhp);
1112 		return (0);
1113 	}
1114 
1115 	/*
1116 	 * If this filesystem is inconsistent and has a receive resume
1117 	 * token, we can not mount it.
1118 	 */
1119 	if (zfs_prop_get_int(zhp, ZFS_PROP_INCONSISTENT) &&
1120 	    zfs_prop_get(zhp, ZFS_PROP_RECEIVE_RESUME_TOKEN,
1121 	    NULL, 0, NULL, NULL, 0, B_TRUE) == 0) {
1122 		zfs_close(zhp);
1123 		return (0);
1124 	}
1125 
1126 	libzfs_add_handle(cbp, zhp);
1127 	if (zfs_iter_filesystems(zhp, zfs_iter_cb, cbp) != 0) {
1128 		zfs_close(zhp);
1129 		return (-1);
1130 	}
1131 	return (0);
1132 }
1133 
1134 /*
1135  * Sort comparator that compares two mountpoint paths. We sort these paths so
1136  * that subdirectories immediately follow their parents. This means that we
1137  * effectively treat the '/' character as the lowest value non-nul char.
1138  * Since filesystems from non-global zones can have the same mountpoint
1139  * as other filesystems, the comparator sorts global zone filesystems to
1140  * the top of the list. This means that the global zone will traverse the
1141  * filesystem list in the correct order and can stop when it sees the
1142  * first zoned filesystem. In a non-global zone, only the delegated
1143  * filesystems are seen.
1144  *
1145  * An example sorted list using this comparator would look like:
1146  *
1147  * /foo
1148  * /foo/bar
1149  * /foo/bar/baz
1150  * /foo/baz
1151  * /foo.bar
1152  * /foo (NGZ1)
1153  * /foo (NGZ2)
1154  *
1155  * The mounting code depends on this ordering to deterministically iterate
1156  * over filesystems in order to spawn parallel mount tasks.
1157  */
1158 static int
1159 mountpoint_cmp(const void *arga, const void *argb)
1160 {
1161 	zfs_handle_t *const *zap = arga;
1162 	zfs_handle_t *za = *zap;
1163 	zfs_handle_t *const *zbp = argb;
1164 	zfs_handle_t *zb = *zbp;
1165 	char mounta[MAXPATHLEN];
1166 	char mountb[MAXPATHLEN];
1167 	const char *a = mounta;
1168 	const char *b = mountb;
1169 	boolean_t gota, gotb;
1170 	uint64_t zoneda, zonedb;
1171 
1172 	zoneda = zfs_prop_get_int(za, ZFS_PROP_ZONED);
1173 	zonedb = zfs_prop_get_int(zb, ZFS_PROP_ZONED);
1174 	if (zoneda && !zonedb)
1175 		return (1);
1176 	if (!zoneda && zonedb)
1177 		return (-1);
1178 
1179 	gota = (zfs_get_type(za) == ZFS_TYPE_FILESYSTEM);
1180 	if (gota) {
1181 		verify(zfs_prop_get(za, ZFS_PROP_MOUNTPOINT, mounta,
1182 		    sizeof (mounta), NULL, NULL, 0, B_FALSE) == 0);
1183 	}
1184 	gotb = (zfs_get_type(zb) == ZFS_TYPE_FILESYSTEM);
1185 	if (gotb) {
1186 		verify(zfs_prop_get(zb, ZFS_PROP_MOUNTPOINT, mountb,
1187 		    sizeof (mountb), NULL, NULL, 0, B_FALSE) == 0);
1188 	}
1189 
1190 	if (gota && gotb) {
1191 		while (*a != '\0' && (*a == *b)) {
1192 			a++;
1193 			b++;
1194 		}
1195 		if (*a == *b)
1196 			return (0);
1197 		if (*a == '\0')
1198 			return (-1);
1199 		if (*b == '\0')
1200 			return (1);
1201 		if (*a == '/')
1202 			return (-1);
1203 		if (*b == '/')
1204 			return (1);
1205 		return (*a < *b ? -1 : *a > *b);
1206 	}
1207 
1208 	if (gota)
1209 		return (-1);
1210 	if (gotb)
1211 		return (1);
1212 
1213 	/*
1214 	 * If neither filesystem has a mountpoint, revert to sorting by
1215 	 * dataset name.
1216 	 */
1217 	return (strcmp(zfs_get_name(za), zfs_get_name(zb)));
1218 }
1219 
1220 /*
1221  * Return true if path2 is a child of path1 or path2 equals path1 or
1222  * path1 is "/" (path2 is always a child of "/").
1223  */
1224 static boolean_t
1225 libzfs_path_contains(const char *path1, const char *path2)
1226 {
1227 	return (strcmp(path1, path2) == 0 || strcmp(path1, "/") == 0 ||
1228 	    (strstr(path2, path1) == path2 && path2[strlen(path1)] == '/'));
1229 }
1230 
1231 /*
1232  * Given a mountpoint specified by idx in the handles array, find the first
1233  * non-descendent of that mountpoint and return its index. Descendant paths
1234  * start with the parent's path. This function relies on the ordering
1235  * enforced by mountpoint_cmp().
1236  */
1237 static int
1238 non_descendant_idx(zfs_handle_t **handles, size_t num_handles, int idx)
1239 {
1240 	char parent[ZFS_MAXPROPLEN];
1241 	char child[ZFS_MAXPROPLEN];
1242 	int i;
1243 
1244 	verify(zfs_prop_get(handles[idx], ZFS_PROP_MOUNTPOINT, parent,
1245 	    sizeof (parent), NULL, NULL, 0, B_FALSE) == 0);
1246 
1247 	for (i = idx + 1; i < num_handles; i++) {
1248 		verify(zfs_prop_get(handles[i], ZFS_PROP_MOUNTPOINT, child,
1249 		    sizeof (child), NULL, NULL, 0, B_FALSE) == 0);
1250 		if (!libzfs_path_contains(parent, child))
1251 			break;
1252 	}
1253 	return (i);
1254 }
1255 
1256 typedef struct mnt_param {
1257 	libzfs_handle_t	*mnt_hdl;
1258 	tpool_t		*mnt_tp;
1259 	zfs_handle_t	**mnt_zhps; /* filesystems to mount */
1260 	size_t		mnt_num_handles;
1261 	int		mnt_idx;	/* Index of selected entry to mount */
1262 	zfs_iter_f	mnt_func;
1263 	void		*mnt_data;
1264 } mnt_param_t;
1265 
1266 /*
1267  * Allocate and populate the parameter struct for mount function, and
1268  * schedule mounting of the entry selected by idx.
1269  */
1270 static void
1271 zfs_dispatch_mount(libzfs_handle_t *hdl, zfs_handle_t **handles,
1272     size_t num_handles, int idx, zfs_iter_f func, void *data, tpool_t *tp)
1273 {
1274 	mnt_param_t *mnt_param = zfs_alloc(hdl, sizeof (mnt_param_t));
1275 
1276 	mnt_param->mnt_hdl = hdl;
1277 	mnt_param->mnt_tp = tp;
1278 	mnt_param->mnt_zhps = handles;
1279 	mnt_param->mnt_num_handles = num_handles;
1280 	mnt_param->mnt_idx = idx;
1281 	mnt_param->mnt_func = func;
1282 	mnt_param->mnt_data = data;
1283 
1284 	(void) tpool_dispatch(tp, zfs_mount_task, (void*)mnt_param);
1285 }
1286 
1287 /*
1288  * This is the structure used to keep state of mounting or sharing operations
1289  * during a call to zpool_enable_datasets().
1290  */
1291 typedef struct mount_state {
1292 	/*
1293 	 * ms_mntstatus is set to -1 if any mount fails. While multiple threads
1294 	 * could update this variable concurrently, no synchronization is
1295 	 * needed as it's only ever set to -1.
1296 	 */
1297 	int		ms_mntstatus;
1298 	int		ms_mntflags;
1299 	const char	*ms_mntopts;
1300 } mount_state_t;
1301 
1302 static int
1303 zfs_mount_one(zfs_handle_t *zhp, void *arg)
1304 {
1305 	mount_state_t *ms = arg;
1306 	int ret = 0;
1307 
1308 	/*
1309 	 * don't attempt to mount encrypted datasets with
1310 	 * unloaded keys
1311 	 */
1312 	if (zfs_prop_get_int(zhp, ZFS_PROP_KEYSTATUS) ==
1313 	    ZFS_KEYSTATUS_UNAVAILABLE)
1314 		return (0);
1315 
1316 	if (zfs_mount(zhp, ms->ms_mntopts, ms->ms_mntflags) != 0)
1317 		ret = ms->ms_mntstatus = -1;
1318 	return (ret);
1319 }
1320 
1321 static int
1322 zfs_share_one(zfs_handle_t *zhp, void *arg)
1323 {
1324 	mount_state_t *ms = arg;
1325 	int ret = 0;
1326 
1327 	if (zfs_share(zhp) != 0)
1328 		ret = ms->ms_mntstatus = -1;
1329 	return (ret);
1330 }
1331 
1332 /*
1333  * Thread pool function to mount one file system. On completion, it finds and
1334  * schedules its children to be mounted. This depends on the sorting done in
1335  * zfs_foreach_mountpoint(). Note that the degenerate case (chain of entries
1336  * each descending from the previous) will have no parallelism since we always
1337  * have to wait for the parent to finish mounting before we can schedule
1338  * its children.
1339  */
1340 static void
1341 zfs_mount_task(void *arg)
1342 {
1343 	mnt_param_t *mp = arg;
1344 	int idx = mp->mnt_idx;
1345 	zfs_handle_t **handles = mp->mnt_zhps;
1346 	size_t num_handles = mp->mnt_num_handles;
1347 	char mountpoint[ZFS_MAXPROPLEN];
1348 
1349 	verify(zfs_prop_get(handles[idx], ZFS_PROP_MOUNTPOINT, mountpoint,
1350 	    sizeof (mountpoint), NULL, NULL, 0, B_FALSE) == 0);
1351 
1352 	if (mp->mnt_func(handles[idx], mp->mnt_data) != 0)
1353 		return;
1354 
1355 	/*
1356 	 * We dispatch tasks to mount filesystems with mountpoints underneath
1357 	 * this one. We do this by dispatching the next filesystem with a
1358 	 * descendant mountpoint of the one we just mounted, then skip all of
1359 	 * its descendants, dispatch the next descendant mountpoint, and so on.
1360 	 * The non_descendant_idx() function skips over filesystems that are
1361 	 * descendants of the filesystem we just dispatched.
1362 	 */
1363 	for (int i = idx + 1; i < num_handles;
1364 	    i = non_descendant_idx(handles, num_handles, i)) {
1365 		char child[ZFS_MAXPROPLEN];
1366 		verify(zfs_prop_get(handles[i], ZFS_PROP_MOUNTPOINT,
1367 		    child, sizeof (child), NULL, NULL, 0, B_FALSE) == 0);
1368 
1369 		if (!libzfs_path_contains(mountpoint, child))
1370 			break; /* not a descendant, return */
1371 		zfs_dispatch_mount(mp->mnt_hdl, handles, num_handles, i,
1372 		    mp->mnt_func, mp->mnt_data, mp->mnt_tp);
1373 	}
1374 	free(mp);
1375 }
1376 
1377 /*
1378  * Issue the func callback for each ZFS handle contained in the handles
1379  * array. This function is used to mount all datasets, and so this function
1380  * guarantees that filesystems for parent mountpoints are called before their
1381  * children. As such, before issuing any callbacks, we first sort the array
1382  * of handles by mountpoint.
1383  *
1384  * Callbacks are issued in one of two ways:
1385  *
1386  * 1. Sequentially: If the parallel argument is B_FALSE or the ZFS_SERIAL_MOUNT
1387  *    environment variable is set, then we issue callbacks sequentially.
1388  *
1389  * 2. In parallel: If the parallel argument is B_TRUE and the ZFS_SERIAL_MOUNT
1390  *    environment variable is not set, then we use a tpool to dispatch threads
1391  *    to mount filesystems in parallel. This function dispatches tasks to mount
1392  *    the filesystems at the top-level mountpoints, and these tasks in turn
1393  *    are responsible for recursively mounting filesystems in their children
1394  *    mountpoints.
1395  */
1396 void
1397 zfs_foreach_mountpoint(libzfs_handle_t *hdl, zfs_handle_t **handles,
1398     size_t num_handles, zfs_iter_f func, void *data, boolean_t parallel)
1399 {
1400 	zoneid_t zoneid = getzoneid();
1401 
1402 	/*
1403 	 * The ZFS_SERIAL_MOUNT environment variable is an undocumented
1404 	 * variable that can be used as a convenience to do a/b comparison
1405 	 * of serial vs. parallel mounting.
1406 	 */
1407 	boolean_t serial_mount = !parallel ||
1408 	    (getenv("ZFS_SERIAL_MOUNT") != NULL);
1409 
1410 	/*
1411 	 * Sort the datasets by mountpoint. See mountpoint_cmp for details
1412 	 * of how these are sorted.
1413 	 */
1414 	qsort(handles, num_handles, sizeof (zfs_handle_t *), mountpoint_cmp);
1415 
1416 	if (serial_mount) {
1417 		for (int i = 0; i < num_handles; i++) {
1418 			func(handles[i], data);
1419 		}
1420 		return;
1421 	}
1422 
1423 	/*
1424 	 * Issue the callback function for each dataset using a parallel
1425 	 * algorithm that uses a thread pool to manage threads.
1426 	 */
1427 	tpool_t *tp = tpool_create(1, mount_tp_nthr, 0, NULL);
1428 
1429 	/*
1430 	 * There may be multiple "top level" mountpoints outside of the pool's
1431 	 * root mountpoint, e.g.: /foo /bar. Dispatch a mount task for each of
1432 	 * these.
1433 	 */
1434 	for (int i = 0; i < num_handles;
1435 	    i = non_descendant_idx(handles, num_handles, i)) {
1436 		/*
1437 		 * Since the mountpoints have been sorted so that the zoned
1438 		 * filesystems are at the end, a zoned filesystem seen from
1439 		 * the global zone means that we're done.
1440 		 */
1441 		if (zoneid == GLOBAL_ZONEID &&
1442 		    zfs_prop_get_int(handles[i], ZFS_PROP_ZONED))
1443 			break;
1444 		zfs_dispatch_mount(hdl, handles, num_handles, i, func, data,
1445 		    tp);
1446 	}
1447 
1448 	tpool_wait(tp);	/* wait for all scheduled mounts to complete */
1449 	tpool_destroy(tp);
1450 }
1451 
1452 /*
1453  * Mount and share all datasets within the given pool.  This assumes that no
1454  * datasets within the pool are currently mounted.
1455  */
1456 int
1457 zpool_enable_datasets(zpool_handle_t *zhp, const char *mntopts, int flags)
1458 {
1459 	get_all_cb_t cb = { 0 };
1460 	mount_state_t ms = { 0 };
1461 	zfs_handle_t *zfsp;
1462 	int ret = 0;
1463 
1464 	if ((zfsp = zfs_open(zhp->zpool_hdl, zhp->zpool_name,
1465 	    ZFS_TYPE_DATASET)) == NULL)
1466 		goto out;
1467 
1468 	/*
1469 	 * Gather all non-snapshot datasets within the pool. Start by adding
1470 	 * the root filesystem for this pool to the list, and then iterate
1471 	 * over all child filesystems.
1472 	 */
1473 	libzfs_add_handle(&cb, zfsp);
1474 	if (zfs_iter_filesystems(zfsp, zfs_iter_cb, &cb) != 0)
1475 		goto out;
1476 
1477 	/*
1478 	 * Mount all filesystems
1479 	 */
1480 	ms.ms_mntopts = mntopts;
1481 	ms.ms_mntflags = flags;
1482 	zfs_foreach_mountpoint(zhp->zpool_hdl, cb.cb_handles, cb.cb_used,
1483 	    zfs_mount_one, &ms, B_TRUE);
1484 	if (ms.ms_mntstatus != 0)
1485 		ret = ms.ms_mntstatus;
1486 
1487 	/*
1488 	 * Share all filesystems that need to be shared. This needs to be
1489 	 * a separate pass because libshare is not mt-safe, and so we need
1490 	 * to share serially.
1491 	 */
1492 	ms.ms_mntstatus = 0;
1493 	zfs_foreach_mountpoint(zhp->zpool_hdl, cb.cb_handles, cb.cb_used,
1494 	    zfs_share_one, &ms, B_FALSE);
1495 	if (ms.ms_mntstatus != 0)
1496 		ret = ms.ms_mntstatus;
1497 	else
1498 		zfs_commit_all_shares();
1499 
1500 out:
1501 	for (int i = 0; i < cb.cb_used; i++)
1502 		zfs_close(cb.cb_handles[i]);
1503 	free(cb.cb_handles);
1504 
1505 	return (ret);
1506 }
1507 
1508 struct sets_s {
1509 	char *mountpoint;
1510 	zfs_handle_t *dataset;
1511 };
1512 
1513 static int
1514 mountpoint_compare(const void *a, const void *b)
1515 {
1516 	const struct sets_s *mounta = (struct sets_s *)a;
1517 	const struct sets_s *mountb = (struct sets_s *)b;
1518 
1519 	return (strcmp(mountb->mountpoint, mounta->mountpoint));
1520 }
1521 
1522 /*
1523  * Unshare and unmount all datasets within the given pool.  We don't want to
1524  * rely on traversing the DSL to discover the filesystems within the pool,
1525  * because this may be expensive (if not all of them are mounted), and can fail
1526  * arbitrarily (on I/O error, for example).  Instead, we walk /proc/self/mounts
1527  * and gather all the filesystems that are currently mounted.
1528  */
1529 int
1530 zpool_disable_datasets(zpool_handle_t *zhp, boolean_t force)
1531 {
1532 	int used, alloc;
1533 	FILE *mnttab;
1534 	struct mnttab entry;
1535 	size_t namelen;
1536 	struct sets_s *sets = NULL;
1537 	libzfs_handle_t *hdl = zhp->zpool_hdl;
1538 	int i;
1539 	int ret = -1;
1540 	int flags = (force ? MS_FORCE : 0);
1541 
1542 	namelen = strlen(zhp->zpool_name);
1543 
1544 	if ((mnttab = fopen(MNTTAB, "re")) == NULL)
1545 		return (ENOENT);
1546 
1547 	used = alloc = 0;
1548 	while (getmntent(mnttab, &entry) == 0) {
1549 		/*
1550 		 * Ignore non-ZFS entries.
1551 		 */
1552 		if (entry.mnt_fstype == NULL ||
1553 		    strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0)
1554 			continue;
1555 
1556 		/*
1557 		 * Ignore filesystems not within this pool.
1558 		 */
1559 		if (entry.mnt_mountp == NULL ||
1560 		    strncmp(entry.mnt_special, zhp->zpool_name, namelen) != 0 ||
1561 		    (entry.mnt_special[namelen] != '/' &&
1562 		    entry.mnt_special[namelen] != '\0'))
1563 			continue;
1564 
1565 		/*
1566 		 * At this point we've found a filesystem within our pool.  Add
1567 		 * it to our growing list.
1568 		 */
1569 		if (used == alloc) {
1570 			if (alloc == 0) {
1571 
1572 				if ((sets = zfs_alloc(hdl,
1573 				    8 * sizeof (struct sets_s))) == NULL)
1574 					goto out;
1575 
1576 				alloc = 8;
1577 			} else {
1578 				void *ptr;
1579 
1580 				if ((ptr = zfs_realloc(hdl, sets,
1581 				    alloc * sizeof (struct sets_s),
1582 				    alloc * 2 * sizeof (struct sets_s)))
1583 				    == NULL)
1584 					goto out;
1585 				sets = ptr;
1586 
1587 				alloc *= 2;
1588 			}
1589 		}
1590 
1591 		if ((sets[used].mountpoint = zfs_strdup(hdl,
1592 		    entry.mnt_mountp)) == NULL)
1593 			goto out;
1594 
1595 		/*
1596 		 * This is allowed to fail, in case there is some I/O error.  It
1597 		 * is only used to determine if we need to remove the underlying
1598 		 * mountpoint, so failure is not fatal.
1599 		 */
1600 		sets[used].dataset = make_dataset_handle(hdl,
1601 		    entry.mnt_special);
1602 
1603 		used++;
1604 	}
1605 
1606 	/*
1607 	 * At this point, we have the entire list of filesystems, so sort it by
1608 	 * mountpoint.
1609 	 */
1610 	qsort(sets, used, sizeof (struct sets_s), mountpoint_compare);
1611 
1612 	/*
1613 	 * Walk through and first unshare everything.
1614 	 */
1615 	for (i = 0; i < used; i++) {
1616 		zfs_share_proto_t *curr_proto;
1617 		for (curr_proto = share_all_proto; *curr_proto != PROTO_END;
1618 		    curr_proto++) {
1619 			if (is_shared(sets[i].mountpoint, *curr_proto) &&
1620 			    unshare_one(hdl, sets[i].mountpoint,
1621 			    sets[i].mountpoint, *curr_proto) != 0)
1622 				goto out;
1623 		}
1624 	}
1625 	zfs_commit_all_shares();
1626 
1627 	/*
1628 	 * Now unmount everything, removing the underlying directories as
1629 	 * appropriate.
1630 	 */
1631 	for (i = 0; i < used; i++) {
1632 		if (unmount_one(sets[i].dataset, sets[i].mountpoint,
1633 		    flags) != 0)
1634 			goto out;
1635 	}
1636 
1637 	for (i = 0; i < used; i++) {
1638 		if (sets[i].dataset)
1639 			remove_mountpoint(sets[i].dataset);
1640 	}
1641 
1642 	zpool_disable_datasets_os(zhp, force);
1643 
1644 	ret = 0;
1645 out:
1646 	(void) fclose(mnttab);
1647 	for (i = 0; i < used; i++) {
1648 		if (sets[i].dataset)
1649 			zfs_close(sets[i].dataset);
1650 		free(sets[i].mountpoint);
1651 	}
1652 	free(sets);
1653 
1654 	return (ret);
1655 }
1656