xref: /illumos-gate/usr/src/lib/libzfs/common/libzfs_mount.c (revision ba6e7e6505150388de6dc6a88741164118a421bf)
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, 2016 by Delphix. All rights reserved.
26  * Copyright 2016 Igor Kozhukhov <ikozhukhov@gmail.com>
27  * Copyright 2017 RackTop Systems.
28  */
29 
30 /*
31  * Routines to manage ZFS mounts.  We separate all the nasty routines that have
32  * to deal with the OS.  The following functions are the main entry points --
33  * they are used by mount and unmount and when changing a filesystem's
34  * mountpoint.
35  *
36  * 	zfs_is_mounted()
37  * 	zfs_mount()
38  * 	zfs_unmount()
39  * 	zfs_unmountall()
40  *
41  * This file also contains the functions used to manage sharing filesystems via
42  * NFS and iSCSI:
43  *
44  * 	zfs_is_shared()
45  * 	zfs_share()
46  * 	zfs_unshare()
47  *
48  * 	zfs_is_shared_nfs()
49  * 	zfs_is_shared_smb()
50  * 	zfs_share_proto()
51  * 	zfs_shareall();
52  * 	zfs_unshare_nfs()
53  * 	zfs_unshare_smb()
54  * 	zfs_unshareall_nfs()
55  *	zfs_unshareall_smb()
56  *	zfs_unshareall()
57  *	zfs_unshareall_bypath()
58  *
59  * The following functions are available for pool consumers, and will
60  * mount/unmount and share/unshare all datasets within pool:
61  *
62  * 	zpool_enable_datasets()
63  * 	zpool_disable_datasets()
64  */
65 
66 #include <dirent.h>
67 #include <dlfcn.h>
68 #include <errno.h>
69 #include <fcntl.h>
70 #include <libgen.h>
71 #include <libintl.h>
72 #include <stdio.h>
73 #include <stdlib.h>
74 #include <strings.h>
75 #include <unistd.h>
76 #include <zone.h>
77 #include <sys/mntent.h>
78 #include <sys/mount.h>
79 #include <sys/stat.h>
80 #include <sys/statvfs.h>
81 
82 #include <libzfs.h>
83 
84 #include "libzfs_impl.h"
85 
86 #include <libshare.h>
87 #include <sys/systeminfo.h>
88 #define	MAXISALEN	257	/* based on sysinfo(2) man page */
89 
90 static int zfs_share_proto(zfs_handle_t *, zfs_share_proto_t *);
91 zfs_share_type_t zfs_is_shared_proto(zfs_handle_t *, char **,
92     zfs_share_proto_t);
93 
94 /*
95  * The share protocols table must be in the same order as the zfs_share_proto_t
96  * enum in libzfs_impl.h
97  */
98 typedef struct {
99 	zfs_prop_t p_prop;
100 	char *p_name;
101 	int p_share_err;
102 	int p_unshare_err;
103 } proto_table_t;
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 zfs_share_proto_t nfs_only[] = {
111 	PROTO_NFS,
112 	PROTO_END
113 };
114 
115 zfs_share_proto_t smb_only[] = {
116 	PROTO_SMB,
117 	PROTO_END
118 };
119 zfs_share_proto_t share_all_proto[] = {
120 	PROTO_NFS,
121 	PROTO_SMB,
122 	PROTO_END
123 };
124 
125 /*
126  * Search the sharetab for the given mountpoint and protocol, returning
127  * a zfs_share_type_t value.
128  */
129 static zfs_share_type_t
130 is_shared(libzfs_handle_t *hdl, const char *mountpoint, zfs_share_proto_t proto)
131 {
132 	char buf[MAXPATHLEN], *tab;
133 	char *ptr;
134 
135 	if (hdl->libzfs_sharetab == NULL)
136 		return (SHARED_NOT_SHARED);
137 
138 	(void) fseek(hdl->libzfs_sharetab, 0, SEEK_SET);
139 
140 	while (fgets(buf, sizeof (buf), hdl->libzfs_sharetab) != NULL) {
141 
142 		/* the mountpoint is the first entry on each line */
143 		if ((tab = strchr(buf, '\t')) == NULL)
144 			continue;
145 
146 		*tab = '\0';
147 		if (strcmp(buf, mountpoint) == 0) {
148 			/*
149 			 * the protocol field is the third field
150 			 * skip over second field
151 			 */
152 			ptr = ++tab;
153 			if ((tab = strchr(ptr, '\t')) == NULL)
154 				continue;
155 			ptr = ++tab;
156 			if ((tab = strchr(ptr, '\t')) == NULL)
157 				continue;
158 			*tab = '\0';
159 			if (strcmp(ptr,
160 			    proto_table[proto].p_name) == 0) {
161 				switch (proto) {
162 				case PROTO_NFS:
163 					return (SHARED_NFS);
164 				case PROTO_SMB:
165 					return (SHARED_SMB);
166 				default:
167 					return (0);
168 				}
169 			}
170 		}
171 	}
172 
173 	return (SHARED_NOT_SHARED);
174 }
175 
176 static boolean_t
177 dir_is_empty_stat(const char *dirname)
178 {
179 	struct stat st;
180 
181 	/*
182 	 * We only want to return false if the given path is a non empty
183 	 * directory, all other errors are handled elsewhere.
184 	 */
185 	if (stat(dirname, &st) < 0 || !S_ISDIR(st.st_mode)) {
186 		return (B_TRUE);
187 	}
188 
189 	/*
190 	 * An empty directory will still have two entries in it, one
191 	 * entry for each of "." and "..".
192 	 */
193 	if (st.st_size > 2) {
194 		return (B_FALSE);
195 	}
196 
197 	return (B_TRUE);
198 }
199 
200 static boolean_t
201 dir_is_empty_readdir(const char *dirname)
202 {
203 	DIR *dirp;
204 	struct dirent64 *dp;
205 	int dirfd;
206 
207 	if ((dirfd = openat(AT_FDCWD, dirname,
208 	    O_RDONLY | O_NDELAY | O_LARGEFILE | O_CLOEXEC, 0)) < 0) {
209 		return (B_TRUE);
210 	}
211 
212 	if ((dirp = fdopendir(dirfd)) == NULL) {
213 		(void) close(dirfd);
214 		return (B_TRUE);
215 	}
216 
217 	while ((dp = readdir64(dirp)) != NULL) {
218 
219 		if (strcmp(dp->d_name, ".") == 0 ||
220 		    strcmp(dp->d_name, "..") == 0)
221 			continue;
222 
223 		(void) closedir(dirp);
224 		return (B_FALSE);
225 	}
226 
227 	(void) closedir(dirp);
228 	return (B_TRUE);
229 }
230 
231 /*
232  * Returns true if the specified directory is empty.  If we can't open the
233  * directory at all, return true so that the mount can fail with a more
234  * informative error message.
235  */
236 static boolean_t
237 dir_is_empty(const char *dirname)
238 {
239 	struct statvfs64 st;
240 
241 	/*
242 	 * If the statvfs call fails or the filesystem is not a ZFS
243 	 * filesystem, fall back to the slow path which uses readdir.
244 	 */
245 	if ((statvfs64(dirname, &st) != 0) ||
246 	    (strcmp(st.f_basetype, "zfs") != 0)) {
247 		return (dir_is_empty_readdir(dirname));
248 	}
249 
250 	/*
251 	 * At this point, we know the provided path is on a ZFS
252 	 * filesystem, so we can use stat instead of readdir to
253 	 * determine if the directory is empty or not. We try to avoid
254 	 * using readdir because that requires opening "dirname"; this
255 	 * open file descriptor can potentially end up in a child
256 	 * process if there's a concurrent fork, thus preventing the
257 	 * zfs_mount() from otherwise succeeding (the open file
258 	 * descriptor inherited by the child process will cause the
259 	 * parent's mount to fail with EBUSY). The performance
260 	 * implications of replacing the open, read, and close with a
261 	 * single stat is nice; but is not the main motivation for the
262 	 * added complexity.
263 	 */
264 	return (dir_is_empty_stat(dirname));
265 }
266 
267 /*
268  * Checks to see if the mount is active.  If the filesystem is mounted, we fill
269  * in 'where' with the current mountpoint, and return 1.  Otherwise, we return
270  * 0.
271  */
272 boolean_t
273 is_mounted(libzfs_handle_t *zfs_hdl, const char *special, char **where)
274 {
275 	struct mnttab entry;
276 
277 	if (libzfs_mnttab_find(zfs_hdl, special, &entry) != 0)
278 		return (B_FALSE);
279 
280 	if (where != NULL)
281 		*where = zfs_strdup(zfs_hdl, entry.mnt_mountp);
282 
283 	return (B_TRUE);
284 }
285 
286 boolean_t
287 zfs_is_mounted(zfs_handle_t *zhp, char **where)
288 {
289 	return (is_mounted(zhp->zfs_hdl, zfs_get_name(zhp), where));
290 }
291 
292 /*
293  * Returns true if the given dataset is mountable, false otherwise.  Returns the
294  * mountpoint in 'buf'.
295  */
296 static boolean_t
297 zfs_is_mountable(zfs_handle_t *zhp, char *buf, size_t buflen,
298     zprop_source_t *source)
299 {
300 	char sourceloc[MAXNAMELEN];
301 	zprop_source_t sourcetype;
302 
303 	if (!zfs_prop_valid_for_type(ZFS_PROP_MOUNTPOINT, zhp->zfs_type))
304 		return (B_FALSE);
305 
306 	verify(zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT, buf, buflen,
307 	    &sourcetype, sourceloc, sizeof (sourceloc), B_FALSE) == 0);
308 
309 	if (strcmp(buf, ZFS_MOUNTPOINT_NONE) == 0 ||
310 	    strcmp(buf, ZFS_MOUNTPOINT_LEGACY) == 0)
311 		return (B_FALSE);
312 
313 	if (zfs_prop_get_int(zhp, ZFS_PROP_CANMOUNT) == ZFS_CANMOUNT_OFF)
314 		return (B_FALSE);
315 
316 	if (zfs_prop_get_int(zhp, ZFS_PROP_ZONED) &&
317 	    getzoneid() == GLOBAL_ZONEID)
318 		return (B_FALSE);
319 
320 	if (source)
321 		*source = sourcetype;
322 
323 	return (B_TRUE);
324 }
325 
326 /*
327  * Mount the given filesystem.
328  */
329 int
330 zfs_mount(zfs_handle_t *zhp, const char *options, int flags)
331 {
332 	struct stat buf;
333 	char mountpoint[ZFS_MAXPROPLEN];
334 	char mntopts[MNT_LINE_MAX];
335 	libzfs_handle_t *hdl = zhp->zfs_hdl;
336 
337 	if (options == NULL)
338 		mntopts[0] = '\0';
339 	else
340 		(void) strlcpy(mntopts, options, sizeof (mntopts));
341 
342 	/*
343 	 * If the pool is imported read-only then all mounts must be read-only
344 	 */
345 	if (zpool_get_prop_int(zhp->zpool_hdl, ZPOOL_PROP_READONLY, NULL))
346 		flags |= MS_RDONLY;
347 
348 	if (!zfs_is_mountable(zhp, mountpoint, sizeof (mountpoint), NULL))
349 		return (0);
350 
351 	/* Create the directory if it doesn't already exist */
352 	if (lstat(mountpoint, &buf) != 0) {
353 		if (mkdirp(mountpoint, 0755) != 0) {
354 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
355 			    "failed to create mountpoint"));
356 			return (zfs_error_fmt(hdl, EZFS_MOUNTFAILED,
357 			    dgettext(TEXT_DOMAIN, "cannot mount '%s'"),
358 			    mountpoint));
359 		}
360 	}
361 
362 	/*
363 	 * Determine if the mountpoint is empty.  If so, refuse to perform the
364 	 * mount.  We don't perform this check if MS_OVERLAY is specified, which
365 	 * would defeat the point.  We also avoid this check if 'remount' is
366 	 * specified.
367 	 */
368 	if ((flags & MS_OVERLAY) == 0 &&
369 	    strstr(mntopts, MNTOPT_REMOUNT) == NULL &&
370 	    !dir_is_empty(mountpoint)) {
371 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
372 		    "directory is not empty"));
373 		return (zfs_error_fmt(hdl, EZFS_MOUNTFAILED,
374 		    dgettext(TEXT_DOMAIN, "cannot mount '%s'"), mountpoint));
375 	}
376 
377 	/* perform the mount */
378 	if (mount(zfs_get_name(zhp), mountpoint, MS_OPTIONSTR | flags,
379 	    MNTTYPE_ZFS, NULL, 0, mntopts, sizeof (mntopts)) != 0) {
380 		/*
381 		 * Generic errors are nasty, but there are just way too many
382 		 * from mount(), and they're well-understood.  We pick a few
383 		 * common ones to improve upon.
384 		 */
385 		if (errno == EBUSY) {
386 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
387 			    "mountpoint or dataset is busy"));
388 		} else if (errno == EPERM) {
389 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
390 			    "Insufficient privileges"));
391 		} else if (errno == ENOTSUP) {
392 			char buf[256];
393 			int spa_version;
394 
395 			VERIFY(zfs_spa_version(zhp, &spa_version) == 0);
396 			(void) snprintf(buf, sizeof (buf),
397 			    dgettext(TEXT_DOMAIN, "Can't mount a version %lld "
398 			    "file system on a version %d pool. Pool must be"
399 			    " upgraded to mount this file system."),
400 			    (u_longlong_t)zfs_prop_get_int(zhp,
401 			    ZFS_PROP_VERSION), spa_version);
402 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, buf));
403 		} else {
404 			zfs_error_aux(hdl, strerror(errno));
405 		}
406 		return (zfs_error_fmt(hdl, EZFS_MOUNTFAILED,
407 		    dgettext(TEXT_DOMAIN, "cannot mount '%s'"),
408 		    zhp->zfs_name));
409 	}
410 
411 	/* add the mounted entry into our cache */
412 	libzfs_mnttab_add(hdl, zfs_get_name(zhp), mountpoint,
413 	    mntopts);
414 	return (0);
415 }
416 
417 /*
418  * Unmount a single filesystem.
419  */
420 static int
421 unmount_one(libzfs_handle_t *hdl, const char *mountpoint, int flags)
422 {
423 	if (umount2(mountpoint, flags) != 0) {
424 		zfs_error_aux(hdl, strerror(errno));
425 		return (zfs_error_fmt(hdl, EZFS_UMOUNTFAILED,
426 		    dgettext(TEXT_DOMAIN, "cannot unmount '%s'"),
427 		    mountpoint));
428 	}
429 
430 	return (0);
431 }
432 
433 /*
434  * Unmount the given filesystem.
435  */
436 int
437 zfs_unmount(zfs_handle_t *zhp, const char *mountpoint, int flags)
438 {
439 	libzfs_handle_t *hdl = zhp->zfs_hdl;
440 	struct mnttab entry;
441 	char *mntpt = NULL;
442 
443 	/* check to see if we need to unmount the filesystem */
444 	if (mountpoint != NULL || ((zfs_get_type(zhp) == ZFS_TYPE_FILESYSTEM) &&
445 	    libzfs_mnttab_find(hdl, zhp->zfs_name, &entry) == 0)) {
446 		/*
447 		 * mountpoint may have come from a call to
448 		 * getmnt/getmntany if it isn't NULL. If it is NULL,
449 		 * we know it comes from libzfs_mnttab_find which can
450 		 * then get freed later. We strdup it to play it safe.
451 		 */
452 		if (mountpoint == NULL)
453 			mntpt = zfs_strdup(hdl, entry.mnt_mountp);
454 		else
455 			mntpt = zfs_strdup(hdl, mountpoint);
456 
457 		/*
458 		 * Unshare and unmount the filesystem
459 		 */
460 		if (zfs_unshare_proto(zhp, mntpt, share_all_proto) != 0)
461 			return (-1);
462 
463 		if (unmount_one(hdl, mntpt, flags) != 0) {
464 			free(mntpt);
465 			(void) zfs_shareall(zhp);
466 			return (-1);
467 		}
468 		libzfs_mnttab_remove(hdl, zhp->zfs_name);
469 		free(mntpt);
470 	}
471 
472 	return (0);
473 }
474 
475 /*
476  * Unmount this filesystem and any children inheriting the mountpoint property.
477  * To do this, just act like we're changing the mountpoint property, but don't
478  * remount the filesystems afterwards.
479  */
480 int
481 zfs_unmountall(zfs_handle_t *zhp, int flags)
482 {
483 	prop_changelist_t *clp;
484 	int ret;
485 
486 	clp = changelist_gather(zhp, ZFS_PROP_MOUNTPOINT, 0, flags);
487 	if (clp == NULL)
488 		return (-1);
489 
490 	ret = changelist_prefix(clp);
491 	changelist_free(clp);
492 
493 	return (ret);
494 }
495 
496 boolean_t
497 zfs_is_shared(zfs_handle_t *zhp)
498 {
499 	zfs_share_type_t rc = 0;
500 	zfs_share_proto_t *curr_proto;
501 
502 	if (ZFS_IS_VOLUME(zhp))
503 		return (B_FALSE);
504 
505 	for (curr_proto = share_all_proto; *curr_proto != PROTO_END;
506 	    curr_proto++)
507 		rc |= zfs_is_shared_proto(zhp, NULL, *curr_proto);
508 
509 	return (rc ? B_TRUE : B_FALSE);
510 }
511 
512 int
513 zfs_share(zfs_handle_t *zhp)
514 {
515 	assert(!ZFS_IS_VOLUME(zhp));
516 	return (zfs_share_proto(zhp, share_all_proto));
517 }
518 
519 int
520 zfs_unshare(zfs_handle_t *zhp)
521 {
522 	assert(!ZFS_IS_VOLUME(zhp));
523 	return (zfs_unshareall(zhp));
524 }
525 
526 /*
527  * Check to see if the filesystem is currently shared.
528  */
529 zfs_share_type_t
530 zfs_is_shared_proto(zfs_handle_t *zhp, char **where, zfs_share_proto_t proto)
531 {
532 	char *mountpoint;
533 	zfs_share_type_t rc;
534 
535 	if (!zfs_is_mounted(zhp, &mountpoint))
536 		return (SHARED_NOT_SHARED);
537 
538 	if ((rc = is_shared(zhp->zfs_hdl, mountpoint, proto))
539 	    != SHARED_NOT_SHARED) {
540 		if (where != NULL)
541 			*where = mountpoint;
542 		else
543 			free(mountpoint);
544 		return (rc);
545 	} else {
546 		free(mountpoint);
547 		return (SHARED_NOT_SHARED);
548 	}
549 }
550 
551 boolean_t
552 zfs_is_shared_nfs(zfs_handle_t *zhp, char **where)
553 {
554 	return (zfs_is_shared_proto(zhp, where,
555 	    PROTO_NFS) != SHARED_NOT_SHARED);
556 }
557 
558 boolean_t
559 zfs_is_shared_smb(zfs_handle_t *zhp, char **where)
560 {
561 	return (zfs_is_shared_proto(zhp, where,
562 	    PROTO_SMB) != SHARED_NOT_SHARED);
563 }
564 
565 /*
566  * Make sure things will work if libshare isn't installed by using
567  * wrapper functions that check to see that the pointers to functions
568  * initialized in _zfs_init_libshare() are actually present.
569  */
570 
571 static sa_handle_t (*_sa_init)(int);
572 static sa_handle_t (*_sa_init_arg)(int, void *);
573 static void (*_sa_fini)(sa_handle_t);
574 static sa_share_t (*_sa_find_share)(sa_handle_t, char *);
575 static int (*_sa_enable_share)(sa_share_t, char *);
576 static int (*_sa_disable_share)(sa_share_t, char *);
577 static char *(*_sa_errorstr)(int);
578 static int (*_sa_parse_legacy_options)(sa_group_t, char *, char *);
579 static boolean_t (*_sa_needs_refresh)(sa_handle_t *);
580 static libzfs_handle_t *(*_sa_get_zfs_handle)(sa_handle_t);
581 static int (*_sa_zfs_process_share)(sa_handle_t, sa_group_t, sa_share_t,
582     char *, char *, zprop_source_t, char *, char *, char *);
583 static void (*_sa_update_sharetab_ts)(sa_handle_t);
584 
585 /*
586  * _zfs_init_libshare()
587  *
588  * Find the libshare.so.1 entry points that we use here and save the
589  * values to be used later. This is triggered by the runtime loader.
590  * Make sure the correct ISA version is loaded.
591  */
592 
593 #pragma init(_zfs_init_libshare)
594 static void
595 _zfs_init_libshare(void)
596 {
597 	void *libshare;
598 	char path[MAXPATHLEN];
599 	char isa[MAXISALEN];
600 
601 #if defined(_LP64)
602 	if (sysinfo(SI_ARCHITECTURE_64, isa, MAXISALEN) == -1)
603 		isa[0] = '\0';
604 #else
605 	isa[0] = '\0';
606 #endif
607 	(void) snprintf(path, MAXPATHLEN,
608 	    "/usr/lib/%s/libshare.so.1", isa);
609 
610 	if ((libshare = dlopen(path, RTLD_LAZY | RTLD_GLOBAL)) != NULL) {
611 		_sa_init = (sa_handle_t (*)(int))dlsym(libshare, "sa_init");
612 		_sa_init_arg = (sa_handle_t (*)(int, void *))dlsym(libshare,
613 		    "sa_init_arg");
614 		_sa_fini = (void (*)(sa_handle_t))dlsym(libshare, "sa_fini");
615 		_sa_find_share = (sa_share_t (*)(sa_handle_t, char *))
616 		    dlsym(libshare, "sa_find_share");
617 		_sa_enable_share = (int (*)(sa_share_t, char *))dlsym(libshare,
618 		    "sa_enable_share");
619 		_sa_disable_share = (int (*)(sa_share_t, char *))dlsym(libshare,
620 		    "sa_disable_share");
621 		_sa_errorstr = (char *(*)(int))dlsym(libshare, "sa_errorstr");
622 		_sa_parse_legacy_options = (int (*)(sa_group_t, char *, char *))
623 		    dlsym(libshare, "sa_parse_legacy_options");
624 		_sa_needs_refresh = (boolean_t (*)(sa_handle_t *))
625 		    dlsym(libshare, "sa_needs_refresh");
626 		_sa_get_zfs_handle = (libzfs_handle_t *(*)(sa_handle_t))
627 		    dlsym(libshare, "sa_get_zfs_handle");
628 		_sa_zfs_process_share = (int (*)(sa_handle_t, sa_group_t,
629 		    sa_share_t, char *, char *, zprop_source_t, char *,
630 		    char *, char *))dlsym(libshare, "sa_zfs_process_share");
631 		_sa_update_sharetab_ts = (void (*)(sa_handle_t))
632 		    dlsym(libshare, "sa_update_sharetab_ts");
633 		if (_sa_init == NULL || _sa_init_arg == NULL ||
634 		    _sa_fini == NULL || _sa_find_share == NULL ||
635 		    _sa_enable_share == NULL || _sa_disable_share == NULL ||
636 		    _sa_errorstr == NULL || _sa_parse_legacy_options == NULL ||
637 		    _sa_needs_refresh == NULL || _sa_get_zfs_handle == NULL ||
638 		    _sa_zfs_process_share == NULL ||
639 		    _sa_update_sharetab_ts == NULL) {
640 			_sa_init = NULL;
641 			_sa_init_arg = NULL;
642 			_sa_fini = NULL;
643 			_sa_disable_share = NULL;
644 			_sa_enable_share = NULL;
645 			_sa_errorstr = NULL;
646 			_sa_parse_legacy_options = NULL;
647 			(void) dlclose(libshare);
648 			_sa_needs_refresh = NULL;
649 			_sa_get_zfs_handle = NULL;
650 			_sa_zfs_process_share = NULL;
651 			_sa_update_sharetab_ts = NULL;
652 		}
653 	}
654 }
655 
656 /*
657  * zfs_init_libshare(zhandle, service)
658  *
659  * Initialize the libshare API if it hasn't already been initialized.
660  * In all cases it returns 0 if it succeeded and an error if not. The
661  * service value is which part(s) of the API to initialize and is a
662  * direct map to the libshare sa_init(service) interface.
663  */
664 static int
665 zfs_init_libshare_impl(libzfs_handle_t *zhandle, int service, void *arg)
666 {
667 	if (_sa_init == NULL)
668 		return (SA_CONFIG_ERR);
669 
670 	/*
671 	 * Attempt to refresh libshare. This is necessary if there was a cache
672 	 * miss for a new ZFS dataset that was just created, or if state of the
673 	 * sharetab file has changed since libshare was last initialized. We
674 	 * want to make sure so check timestamps to see if a different process
675 	 * has updated any of the configuration. If there was some non-ZFS
676 	 * change, we need to re-initialize the internal cache.
677 	 */
678 	if (_sa_needs_refresh != NULL &&
679 	    _sa_needs_refresh(zhandle->libzfs_sharehdl)) {
680 		zfs_uninit_libshare(zhandle);
681 		zhandle->libzfs_sharehdl = _sa_init_arg(service, arg);
682 	}
683 
684 	if (zhandle && zhandle->libzfs_sharehdl == NULL)
685 		zhandle->libzfs_sharehdl = _sa_init_arg(service, arg);
686 
687 	if (zhandle->libzfs_sharehdl == NULL)
688 		return (SA_NO_MEMORY);
689 
690 	return (SA_OK);
691 }
692 int
693 zfs_init_libshare(libzfs_handle_t *zhandle, int service)
694 {
695 	return (zfs_init_libshare_impl(zhandle, service, NULL));
696 }
697 
698 int
699 zfs_init_libshare_arg(libzfs_handle_t *zhandle, int service, void *arg)
700 {
701 	return (zfs_init_libshare_impl(zhandle, service, arg));
702 }
703 
704 
705 /*
706  * zfs_uninit_libshare(zhandle)
707  *
708  * Uninitialize the libshare API if it hasn't already been
709  * uninitialized. It is OK to call multiple times.
710  */
711 void
712 zfs_uninit_libshare(libzfs_handle_t *zhandle)
713 {
714 	if (zhandle != NULL && zhandle->libzfs_sharehdl != NULL) {
715 		if (_sa_fini != NULL)
716 			_sa_fini(zhandle->libzfs_sharehdl);
717 		zhandle->libzfs_sharehdl = NULL;
718 	}
719 }
720 
721 /*
722  * zfs_parse_options(options, proto)
723  *
724  * Call the legacy parse interface to get the protocol specific
725  * options using the NULL arg to indicate that this is a "parse" only.
726  */
727 int
728 zfs_parse_options(char *options, zfs_share_proto_t proto)
729 {
730 	if (_sa_parse_legacy_options != NULL) {
731 		return (_sa_parse_legacy_options(NULL, options,
732 		    proto_table[proto].p_name));
733 	}
734 	return (SA_CONFIG_ERR);
735 }
736 
737 /*
738  * zfs_sa_find_share(handle, path)
739  *
740  * wrapper around sa_find_share to find a share path in the
741  * configuration.
742  */
743 static sa_share_t
744 zfs_sa_find_share(sa_handle_t handle, char *path)
745 {
746 	if (_sa_find_share != NULL)
747 		return (_sa_find_share(handle, path));
748 	return (NULL);
749 }
750 
751 /*
752  * zfs_sa_enable_share(share, proto)
753  *
754  * Wrapper for sa_enable_share which enables a share for a specified
755  * protocol.
756  */
757 static int
758 zfs_sa_enable_share(sa_share_t share, char *proto)
759 {
760 	if (_sa_enable_share != NULL)
761 		return (_sa_enable_share(share, proto));
762 	return (SA_CONFIG_ERR);
763 }
764 
765 /*
766  * zfs_sa_disable_share(share, proto)
767  *
768  * Wrapper for sa_enable_share which disables a share for a specified
769  * protocol.
770  */
771 static int
772 zfs_sa_disable_share(sa_share_t share, char *proto)
773 {
774 	if (_sa_disable_share != NULL)
775 		return (_sa_disable_share(share, proto));
776 	return (SA_CONFIG_ERR);
777 }
778 
779 /*
780  * Share the given filesystem according to the options in the specified
781  * protocol specific properties (sharenfs, sharesmb).  We rely
782  * on "libshare" to the dirty work for us.
783  */
784 static int
785 zfs_share_proto(zfs_handle_t *zhp, zfs_share_proto_t *proto)
786 {
787 	char mountpoint[ZFS_MAXPROPLEN];
788 	char shareopts[ZFS_MAXPROPLEN];
789 	char sourcestr[ZFS_MAXPROPLEN];
790 	libzfs_handle_t *hdl = zhp->zfs_hdl;
791 	sa_share_t share;
792 	zfs_share_proto_t *curr_proto;
793 	zprop_source_t sourcetype;
794 	int ret;
795 
796 	if (!zfs_is_mountable(zhp, mountpoint, sizeof (mountpoint), NULL))
797 		return (0);
798 
799 	for (curr_proto = proto; *curr_proto != PROTO_END; curr_proto++) {
800 		/*
801 		 * Return success if there are no share options.
802 		 */
803 		if (zfs_prop_get(zhp, proto_table[*curr_proto].p_prop,
804 		    shareopts, sizeof (shareopts), &sourcetype, sourcestr,
805 		    ZFS_MAXPROPLEN, B_FALSE) != 0 ||
806 		    strcmp(shareopts, "off") == 0)
807 			continue;
808 		ret = zfs_init_libshare_arg(hdl, SA_INIT_ONE_SHARE_FROM_HANDLE,
809 		    zhp);
810 		if (ret != SA_OK) {
811 			(void) zfs_error_fmt(hdl, EZFS_SHARENFSFAILED,
812 			    dgettext(TEXT_DOMAIN, "cannot share '%s': %s"),
813 			    zfs_get_name(zhp), _sa_errorstr != NULL ?
814 			    _sa_errorstr(ret) : "");
815 			return (-1);
816 		}
817 
818 		/*
819 		 * If the 'zoned' property is set, then zfs_is_mountable()
820 		 * will have already bailed out if we are in the global zone.
821 		 * But local zones cannot be NFS servers, so we ignore it for
822 		 * local zones as well.
823 		 */
824 		if (zfs_prop_get_int(zhp, ZFS_PROP_ZONED))
825 			continue;
826 
827 		share = zfs_sa_find_share(hdl->libzfs_sharehdl, mountpoint);
828 		if (share == NULL) {
829 			/*
830 			 * This may be a new file system that was just
831 			 * created so isn't in the internal cache
832 			 * (second time through). Rather than
833 			 * reloading the entire configuration, we can
834 			 * assume ZFS has done the checking and it is
835 			 * safe to add this to the internal
836 			 * configuration.
837 			 */
838 			if (_sa_zfs_process_share(hdl->libzfs_sharehdl,
839 			    NULL, NULL, mountpoint,
840 			    proto_table[*curr_proto].p_name, sourcetype,
841 			    shareopts, sourcestr, zhp->zfs_name) != SA_OK) {
842 				(void) zfs_error_fmt(hdl,
843 				    proto_table[*curr_proto].p_share_err,
844 				    dgettext(TEXT_DOMAIN, "cannot share '%s'"),
845 				    zfs_get_name(zhp));
846 				return (-1);
847 			}
848 			share = zfs_sa_find_share(hdl->libzfs_sharehdl,
849 			    mountpoint);
850 		}
851 		if (share != NULL) {
852 			int err;
853 			err = zfs_sa_enable_share(share,
854 			    proto_table[*curr_proto].p_name);
855 			if (err != SA_OK) {
856 				(void) zfs_error_fmt(hdl,
857 				    proto_table[*curr_proto].p_share_err,
858 				    dgettext(TEXT_DOMAIN, "cannot share '%s'"),
859 				    zfs_get_name(zhp));
860 				return (-1);
861 			}
862 		} else {
863 			(void) zfs_error_fmt(hdl,
864 			    proto_table[*curr_proto].p_share_err,
865 			    dgettext(TEXT_DOMAIN, "cannot share '%s'"),
866 			    zfs_get_name(zhp));
867 			return (-1);
868 		}
869 
870 	}
871 	return (0);
872 }
873 
874 
875 int
876 zfs_share_nfs(zfs_handle_t *zhp)
877 {
878 	return (zfs_share_proto(zhp, nfs_only));
879 }
880 
881 int
882 zfs_share_smb(zfs_handle_t *zhp)
883 {
884 	return (zfs_share_proto(zhp, smb_only));
885 }
886 
887 int
888 zfs_shareall(zfs_handle_t *zhp)
889 {
890 	return (zfs_share_proto(zhp, share_all_proto));
891 }
892 
893 /*
894  * Unshare a filesystem by mountpoint.
895  */
896 static int
897 unshare_one(libzfs_handle_t *hdl, const char *name, const char *mountpoint,
898     zfs_share_proto_t proto)
899 {
900 	sa_share_t share;
901 	int err;
902 	char *mntpt;
903 
904 	/*
905 	 * Mountpoint could get trashed if libshare calls getmntany
906 	 * which it does during API initialization, so strdup the
907 	 * value.
908 	 */
909 	mntpt = zfs_strdup(hdl, mountpoint);
910 
911 	/*
912 	 * make sure libshare initialized, initialize everything because we
913 	 * don't know what other unsharing may happen later. Functions up the
914 	 * stack are allowed to initialize instead a subset of shares at the
915 	 * time the set is known.
916 	 */
917 	if ((err = zfs_init_libshare_arg(hdl, SA_INIT_ONE_SHARE_FROM_NAME,
918 	    (void *)name)) != SA_OK) {
919 		free(mntpt);	/* don't need the copy anymore */
920 		return (zfs_error_fmt(hdl, proto_table[proto].p_unshare_err,
921 		    dgettext(TEXT_DOMAIN, "cannot unshare '%s': %s"),
922 		    name, _sa_errorstr(err)));
923 	}
924 
925 	share = zfs_sa_find_share(hdl->libzfs_sharehdl, mntpt);
926 	free(mntpt);	/* don't need the copy anymore */
927 
928 	if (share != NULL) {
929 		err = zfs_sa_disable_share(share, proto_table[proto].p_name);
930 		if (err != SA_OK) {
931 			return (zfs_error_fmt(hdl,
932 			    proto_table[proto].p_unshare_err,
933 			    dgettext(TEXT_DOMAIN, "cannot unshare '%s': %s"),
934 			    name, _sa_errorstr(err)));
935 		}
936 	} else {
937 		return (zfs_error_fmt(hdl, proto_table[proto].p_unshare_err,
938 		    dgettext(TEXT_DOMAIN, "cannot unshare '%s': not found"),
939 		    name));
940 	}
941 	return (0);
942 }
943 
944 /*
945  * Unshare the given filesystem.
946  */
947 int
948 zfs_unshare_proto(zfs_handle_t *zhp, const char *mountpoint,
949     zfs_share_proto_t *proto)
950 {
951 	libzfs_handle_t *hdl = zhp->zfs_hdl;
952 	struct mnttab entry;
953 	char *mntpt = NULL;
954 
955 	/* check to see if need to unmount the filesystem */
956 	rewind(zhp->zfs_hdl->libzfs_mnttab);
957 	if (mountpoint != NULL)
958 		mountpoint = mntpt = zfs_strdup(hdl, mountpoint);
959 
960 	if (mountpoint != NULL || ((zfs_get_type(zhp) == ZFS_TYPE_FILESYSTEM) &&
961 	    libzfs_mnttab_find(hdl, zfs_get_name(zhp), &entry) == 0)) {
962 		zfs_share_proto_t *curr_proto;
963 
964 		if (mountpoint == NULL)
965 			mntpt = zfs_strdup(zhp->zfs_hdl, entry.mnt_mountp);
966 
967 		for (curr_proto = proto; *curr_proto != PROTO_END;
968 		    curr_proto++) {
969 
970 			if (is_shared(hdl, mntpt, *curr_proto) &&
971 			    unshare_one(hdl, zhp->zfs_name,
972 			    mntpt, *curr_proto) != 0) {
973 				if (mntpt != NULL)
974 					free(mntpt);
975 				return (-1);
976 			}
977 		}
978 	}
979 	if (mntpt != NULL)
980 		free(mntpt);
981 
982 	return (0);
983 }
984 
985 int
986 zfs_unshare_nfs(zfs_handle_t *zhp, const char *mountpoint)
987 {
988 	return (zfs_unshare_proto(zhp, mountpoint, nfs_only));
989 }
990 
991 int
992 zfs_unshare_smb(zfs_handle_t *zhp, const char *mountpoint)
993 {
994 	return (zfs_unshare_proto(zhp, mountpoint, smb_only));
995 }
996 
997 /*
998  * Same as zfs_unmountall(), but for NFS and SMB unshares.
999  */
1000 int
1001 zfs_unshareall_proto(zfs_handle_t *zhp, zfs_share_proto_t *proto)
1002 {
1003 	prop_changelist_t *clp;
1004 	int ret;
1005 
1006 	clp = changelist_gather(zhp, ZFS_PROP_SHARENFS, 0, 0);
1007 	if (clp == NULL)
1008 		return (-1);
1009 
1010 	ret = changelist_unshare(clp, proto);
1011 	changelist_free(clp);
1012 
1013 	return (ret);
1014 }
1015 
1016 int
1017 zfs_unshareall_nfs(zfs_handle_t *zhp)
1018 {
1019 	return (zfs_unshareall_proto(zhp, nfs_only));
1020 }
1021 
1022 int
1023 zfs_unshareall_smb(zfs_handle_t *zhp)
1024 {
1025 	return (zfs_unshareall_proto(zhp, smb_only));
1026 }
1027 
1028 int
1029 zfs_unshareall(zfs_handle_t *zhp)
1030 {
1031 	return (zfs_unshareall_proto(zhp, share_all_proto));
1032 }
1033 
1034 int
1035 zfs_unshareall_bypath(zfs_handle_t *zhp, const char *mountpoint)
1036 {
1037 	return (zfs_unshare_proto(zhp, mountpoint, share_all_proto));
1038 }
1039 
1040 /*
1041  * Remove the mountpoint associated with the current dataset, if necessary.
1042  * We only remove the underlying directory if:
1043  *
1044  *	- The mountpoint is not 'none' or 'legacy'
1045  *	- The mountpoint is non-empty
1046  *	- The mountpoint is the default or inherited
1047  *	- The 'zoned' property is set, or we're in a local zone
1048  *
1049  * Any other directories we leave alone.
1050  */
1051 void
1052 remove_mountpoint(zfs_handle_t *zhp)
1053 {
1054 	char mountpoint[ZFS_MAXPROPLEN];
1055 	zprop_source_t source;
1056 
1057 	if (!zfs_is_mountable(zhp, mountpoint, sizeof (mountpoint),
1058 	    &source))
1059 		return;
1060 
1061 	if (source == ZPROP_SRC_DEFAULT ||
1062 	    source == ZPROP_SRC_INHERITED) {
1063 		/*
1064 		 * Try to remove the directory, silently ignoring any errors.
1065 		 * The filesystem may have since been removed or moved around,
1066 		 * and this error isn't really useful to the administrator in
1067 		 * any way.
1068 		 */
1069 		(void) rmdir(mountpoint);
1070 	}
1071 }
1072 
1073 void
1074 libzfs_add_handle(get_all_cb_t *cbp, zfs_handle_t *zhp)
1075 {
1076 	if (cbp->cb_alloc == cbp->cb_used) {
1077 		size_t newsz;
1078 		void *ptr;
1079 
1080 		newsz = cbp->cb_alloc ? cbp->cb_alloc * 2 : 64;
1081 		ptr = zfs_realloc(zhp->zfs_hdl,
1082 		    cbp->cb_handles, cbp->cb_alloc * sizeof (void *),
1083 		    newsz * sizeof (void *));
1084 		cbp->cb_handles = ptr;
1085 		cbp->cb_alloc = newsz;
1086 	}
1087 	cbp->cb_handles[cbp->cb_used++] = zhp;
1088 }
1089 
1090 static int
1091 mount_cb(zfs_handle_t *zhp, void *data)
1092 {
1093 	get_all_cb_t *cbp = data;
1094 
1095 	if (!(zfs_get_type(zhp) & ZFS_TYPE_FILESYSTEM)) {
1096 		zfs_close(zhp);
1097 		return (0);
1098 	}
1099 
1100 	if (zfs_prop_get_int(zhp, ZFS_PROP_CANMOUNT) == ZFS_CANMOUNT_NOAUTO) {
1101 		zfs_close(zhp);
1102 		return (0);
1103 	}
1104 
1105 	/*
1106 	 * If this filesystem is inconsistent and has a receive resume
1107 	 * token, we can not mount it.
1108 	 */
1109 	if (zfs_prop_get_int(zhp, ZFS_PROP_INCONSISTENT) &&
1110 	    zfs_prop_get(zhp, ZFS_PROP_RECEIVE_RESUME_TOKEN,
1111 	    NULL, 0, NULL, NULL, 0, B_TRUE) == 0) {
1112 		zfs_close(zhp);
1113 		return (0);
1114 	}
1115 
1116 	libzfs_add_handle(cbp, zhp);
1117 	if (zfs_iter_filesystems(zhp, mount_cb, cbp) != 0) {
1118 		zfs_close(zhp);
1119 		return (-1);
1120 	}
1121 	return (0);
1122 }
1123 
1124 int
1125 libzfs_dataset_cmp(const void *a, const void *b)
1126 {
1127 	zfs_handle_t **za = (zfs_handle_t **)a;
1128 	zfs_handle_t **zb = (zfs_handle_t **)b;
1129 	char mounta[MAXPATHLEN];
1130 	char mountb[MAXPATHLEN];
1131 	boolean_t gota, gotb;
1132 
1133 	if ((gota = (zfs_get_type(*za) == ZFS_TYPE_FILESYSTEM)) != 0)
1134 		verify(zfs_prop_get(*za, ZFS_PROP_MOUNTPOINT, mounta,
1135 		    sizeof (mounta), NULL, NULL, 0, B_FALSE) == 0);
1136 	if ((gotb = (zfs_get_type(*zb) == ZFS_TYPE_FILESYSTEM)) != 0)
1137 		verify(zfs_prop_get(*zb, ZFS_PROP_MOUNTPOINT, mountb,
1138 		    sizeof (mountb), NULL, NULL, 0, B_FALSE) == 0);
1139 
1140 	if (gota && gotb)
1141 		return (strcmp(mounta, mountb));
1142 
1143 	if (gota)
1144 		return (-1);
1145 	if (gotb)
1146 		return (1);
1147 
1148 	return (strcmp(zfs_get_name(a), zfs_get_name(b)));
1149 }
1150 
1151 /*
1152  * Mount and share all datasets within the given pool.  This assumes that no
1153  * datasets within the pool are currently mounted.  Because users can create
1154  * complicated nested hierarchies of mountpoints, we first gather all the
1155  * datasets and mountpoints within the pool, and sort them by mountpoint.  Once
1156  * we have the list of all filesystems, we iterate over them in order and mount
1157  * and/or share each one.
1158  */
1159 #pragma weak zpool_mount_datasets = zpool_enable_datasets
1160 int
1161 zpool_enable_datasets(zpool_handle_t *zhp, const char *mntopts, int flags)
1162 {
1163 	get_all_cb_t cb = { 0 };
1164 	libzfs_handle_t *hdl = zhp->zpool_hdl;
1165 	zfs_handle_t *zfsp;
1166 	int i, ret = -1;
1167 	int *good;
1168 
1169 	/*
1170 	 * Gather all non-snap datasets within the pool.
1171 	 */
1172 	if ((zfsp = zfs_open(hdl, zhp->zpool_name, ZFS_TYPE_DATASET)) == NULL)
1173 		goto out;
1174 
1175 	libzfs_add_handle(&cb, zfsp);
1176 	if (zfs_iter_filesystems(zfsp, mount_cb, &cb) != 0)
1177 		goto out;
1178 	/*
1179 	 * Sort the datasets by mountpoint.
1180 	 */
1181 	qsort(cb.cb_handles, cb.cb_used, sizeof (void *),
1182 	    libzfs_dataset_cmp);
1183 
1184 	/*
1185 	 * And mount all the datasets, keeping track of which ones
1186 	 * succeeded or failed.
1187 	 */
1188 	if ((good = zfs_alloc(zhp->zpool_hdl,
1189 	    cb.cb_used * sizeof (int))) == NULL)
1190 		goto out;
1191 
1192 	ret = 0;
1193 	for (i = 0; i < cb.cb_used; i++) {
1194 		if (zfs_mount(cb.cb_handles[i], mntopts, flags) != 0)
1195 			ret = -1;
1196 		else
1197 			good[i] = 1;
1198 	}
1199 
1200 	/*
1201 	 * Then share all the ones that need to be shared. This needs
1202 	 * to be a separate pass in order to avoid excessive reloading
1203 	 * of the configuration. Good should never be NULL since
1204 	 * zfs_alloc is supposed to exit if memory isn't available.
1205 	 */
1206 	for (i = 0; i < cb.cb_used; i++) {
1207 		if (good[i] && zfs_share(cb.cb_handles[i]) != 0)
1208 			ret = -1;
1209 	}
1210 
1211 	free(good);
1212 
1213 out:
1214 	for (i = 0; i < cb.cb_used; i++)
1215 		zfs_close(cb.cb_handles[i]);
1216 	free(cb.cb_handles);
1217 
1218 	return (ret);
1219 }
1220 
1221 static int
1222 mountpoint_compare(const void *a, const void *b)
1223 {
1224 	const char *mounta = *((char **)a);
1225 	const char *mountb = *((char **)b);
1226 
1227 	return (strcmp(mountb, mounta));
1228 }
1229 
1230 /* alias for 2002/240 */
1231 #pragma weak zpool_unmount_datasets = zpool_disable_datasets
1232 /*
1233  * Unshare and unmount all datasets within the given pool.  We don't want to
1234  * rely on traversing the DSL to discover the filesystems within the pool,
1235  * because this may be expensive (if not all of them are mounted), and can fail
1236  * arbitrarily (on I/O error, for example).  Instead, we walk /etc/mnttab and
1237  * gather all the filesystems that are currently mounted.
1238  */
1239 int
1240 zpool_disable_datasets(zpool_handle_t *zhp, boolean_t force)
1241 {
1242 	int used, alloc;
1243 	struct mnttab entry;
1244 	size_t namelen;
1245 	char **mountpoints = NULL;
1246 	zfs_handle_t **datasets = NULL;
1247 	libzfs_handle_t *hdl = zhp->zpool_hdl;
1248 	int i;
1249 	int ret = -1;
1250 	int flags = (force ? MS_FORCE : 0);
1251 	sa_init_selective_arg_t sharearg;
1252 
1253 	namelen = strlen(zhp->zpool_name);
1254 
1255 	rewind(hdl->libzfs_mnttab);
1256 	used = alloc = 0;
1257 	while (getmntent(hdl->libzfs_mnttab, &entry) == 0) {
1258 		/*
1259 		 * Ignore non-ZFS entries.
1260 		 */
1261 		if (entry.mnt_fstype == NULL ||
1262 		    strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0)
1263 			continue;
1264 
1265 		/*
1266 		 * Ignore filesystems not within this pool.
1267 		 */
1268 		if (entry.mnt_mountp == NULL ||
1269 		    strncmp(entry.mnt_special, zhp->zpool_name, namelen) != 0 ||
1270 		    (entry.mnt_special[namelen] != '/' &&
1271 		    entry.mnt_special[namelen] != '\0'))
1272 			continue;
1273 
1274 		/*
1275 		 * At this point we've found a filesystem within our pool.  Add
1276 		 * it to our growing list.
1277 		 */
1278 		if (used == alloc) {
1279 			if (alloc == 0) {
1280 				if ((mountpoints = zfs_alloc(hdl,
1281 				    8 * sizeof (void *))) == NULL)
1282 					goto out;
1283 
1284 				if ((datasets = zfs_alloc(hdl,
1285 				    8 * sizeof (void *))) == NULL)
1286 					goto out;
1287 
1288 				alloc = 8;
1289 			} else {
1290 				void *ptr;
1291 
1292 				if ((ptr = zfs_realloc(hdl, mountpoints,
1293 				    alloc * sizeof (void *),
1294 				    alloc * 2 * sizeof (void *))) == NULL)
1295 					goto out;
1296 				mountpoints = ptr;
1297 
1298 				if ((ptr = zfs_realloc(hdl, datasets,
1299 				    alloc * sizeof (void *),
1300 				    alloc * 2 * sizeof (void *))) == NULL)
1301 					goto out;
1302 				datasets = ptr;
1303 
1304 				alloc *= 2;
1305 			}
1306 		}
1307 
1308 		if ((mountpoints[used] = zfs_strdup(hdl,
1309 		    entry.mnt_mountp)) == NULL)
1310 			goto out;
1311 
1312 		/*
1313 		 * This is allowed to fail, in case there is some I/O error.  It
1314 		 * is only used to determine if we need to remove the underlying
1315 		 * mountpoint, so failure is not fatal.
1316 		 */
1317 		datasets[used] = make_dataset_handle(hdl, entry.mnt_special);
1318 
1319 		used++;
1320 	}
1321 
1322 	/*
1323 	 * At this point, we have the entire list of filesystems, so sort it by
1324 	 * mountpoint.
1325 	 */
1326 	sharearg.zhandle_arr = datasets;
1327 	sharearg.zhandle_len = used;
1328 	ret = zfs_init_libshare_arg(hdl, SA_INIT_SHARE_API_SELECTIVE,
1329 	    &sharearg);
1330 	if (ret != 0)
1331 		goto out;
1332 	qsort(mountpoints, used, sizeof (char *), mountpoint_compare);
1333 
1334 	/*
1335 	 * Walk through and first unshare everything.
1336 	 */
1337 	for (i = 0; i < used; i++) {
1338 		zfs_share_proto_t *curr_proto;
1339 		for (curr_proto = share_all_proto; *curr_proto != PROTO_END;
1340 		    curr_proto++) {
1341 			if (is_shared(hdl, mountpoints[i], *curr_proto) &&
1342 			    unshare_one(hdl, mountpoints[i],
1343 			    mountpoints[i], *curr_proto) != 0)
1344 				goto out;
1345 		}
1346 	}
1347 
1348 	/*
1349 	 * Now unmount everything, removing the underlying directories as
1350 	 * appropriate.
1351 	 */
1352 	for (i = 0; i < used; i++) {
1353 		if (unmount_one(hdl, mountpoints[i], flags) != 0)
1354 			goto out;
1355 	}
1356 
1357 	for (i = 0; i < used; i++) {
1358 		if (datasets[i])
1359 			remove_mountpoint(datasets[i]);
1360 	}
1361 
1362 	ret = 0;
1363 out:
1364 	for (i = 0; i < used; i++) {
1365 		if (datasets[i])
1366 			zfs_close(datasets[i]);
1367 		free(mountpoints[i]);
1368 	}
1369 	free(datasets);
1370 	free(mountpoints);
1371 
1372 	return (ret);
1373 }
1374