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