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