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 2009 Sun Microsystems, Inc.  All rights reserved.
  24  * Use is subject to license terms.
  25  */
  26 
  27 #include <assert.h>
  28 #include <ctype.h>
  29 #include <errno.h>
  30 #include <libgen.h>
  31 #include <libintl.h>
  32 #include <libuutil.h>
  33 #include <libnvpair.h>
  34 #include <locale.h>
  35 #include <stddef.h>
  36 #include <stdio.h>
  37 #include <stdlib.h>
  38 #include <strings.h>
  39 #include <unistd.h>
  40 #include <fcntl.h>
  41 #include <zone.h>
  42 #include <sys/mkdev.h>
  43 #include <sys/mntent.h>
  44 #include <sys/mnttab.h>
  45 #include <sys/mount.h>
  46 #include <sys/stat.h>
  47 #include <sys/avl.h>
  48 
  49 #include <libzfs.h>
  50 #include <libuutil.h>
  51 
  52 #include "zfs_iter.h"
  53 #include "zfs_util.h"
  54 
  55 libzfs_handle_t *g_zfs;
  56 
  57 static FILE *mnttab_file;
  58 static char history_str[HIS_MAX_RECORD_LEN];
  59 
  60 static int zfs_do_clone(int argc, char **argv);
  61 static int zfs_do_create(int argc, char **argv);
  62 static int zfs_do_destroy(int argc, char **argv);
  63 static int zfs_do_get(int argc, char **argv);
  64 static int zfs_do_inherit(int argc, char **argv);
  65 static int zfs_do_list(int argc, char **argv);
  66 static int zfs_do_mount(int argc, char **argv);
  67 static int zfs_do_rename(int argc, char **argv);
  68 static int zfs_do_rollback(int argc, char **argv);
  69 static int zfs_do_set(int argc, char **argv);
  70 static int zfs_do_upgrade(int argc, char **argv);
  71 static int zfs_do_snapshot(int argc, char **argv);
  72 static int zfs_do_unmount(int argc, char **argv);
  73 static int zfs_do_share(int argc, char **argv);
  74 static int zfs_do_unshare(int argc, char **argv);
  75 static int zfs_do_send(int argc, char **argv);
  76 static int zfs_do_receive(int argc, char **argv);
  77 static int zfs_do_promote(int argc, char **argv);
  78 static int zfs_do_allow(int argc, char **argv);
  79 static int zfs_do_unallow(int argc, char **argv);
  80 static int zfs_do_key(int argc, char **argv);
  81 
  82 /*
  83  * Enable a reasonable set of defaults for libumem debugging on DEBUG builds.
  84  */
  85 
  86 #ifdef DEBUG
  87 const char *
  88 _umem_debug_init(void)
  89 {
  90         return ("default,verbose"); /* $UMEM_DEBUG setting */
  91 }
  92 
  93 const char *
  94 _umem_logging_init(void)
  95 {
  96         return ("fail,contents"); /* $UMEM_LOGGING setting */
  97 }
  98 #endif
  99 
 100 typedef enum {
 101         HELP_CLONE,
 102         HELP_CREATE,
 103         HELP_DESTROY,
 104         HELP_GET,
 105         HELP_INHERIT,
 106         HELP_UPGRADE,
 107         HELP_LIST,
 108         HELP_MOUNT,
 109         HELP_PROMOTE,
 110         HELP_RECEIVE,
 111         HELP_RENAME,
 112         HELP_ROLLBACK,
 113         HELP_SEND,
 114         HELP_SET,
 115         HELP_SHARE,
 116         HELP_SNAPSHOT,
 117         HELP_UNMOUNT,
 118         HELP_UNSHARE,
 119         HELP_ALLOW,
 120         HELP_UNALLOW,
 121         HELP_KEY
 122 } zfs_help_t;
 123 
 124 typedef struct zfs_command {
 125         const char      *name;
 126         int             (*func)(int argc, char **argv);
 127         zfs_help_t      usage;
 128 } zfs_command_t;
 129 
 130 /*
 131  * Master command table.  Each ZFS command has a name, associated function, and
 132  * usage message.  The usage messages need to be internationalized, so we have
 133  * to have a function to return the usage message based on a command index.
 134  *
 135  * These commands are organized according to how they are displayed in the usage
 136  * message.  An empty command (one with a NULL name) indicates an empty line in
 137  * the generic usage message.
 138  */
 139 static zfs_command_t command_table[] = {
 140         { "create",     zfs_do_create,          HELP_CREATE             },
 141         { "destroy",    zfs_do_destroy,         HELP_DESTROY            },
 142         { NULL },
 143         { "snapshot",   zfs_do_snapshot,        HELP_SNAPSHOT           },
 144         { "rollback",   zfs_do_rollback,        HELP_ROLLBACK           },
 145         { "clone",      zfs_do_clone,           HELP_CLONE              },
 146         { "promote",    zfs_do_promote,         HELP_PROMOTE            },
 147         { "rename",     zfs_do_rename,          HELP_RENAME             },
 148         { NULL },
 149         { "list",       zfs_do_list,            HELP_LIST               },
 150         { NULL },
 151         { "set",        zfs_do_set,             HELP_SET                },
 152         { "get",        zfs_do_get,             HELP_GET                },
 153         { "inherit",    zfs_do_inherit,         HELP_INHERIT            },
 154         { "upgrade",    zfs_do_upgrade,         HELP_UPGRADE            },
 155         { NULL },
 156         { "mount",      zfs_do_mount,           HELP_MOUNT              },
 157         { "unmount",    zfs_do_unmount,         HELP_UNMOUNT            },
 158         { "share",      zfs_do_share,           HELP_SHARE              },
 159         { "unshare",    zfs_do_unshare,         HELP_UNSHARE            },
 160         { NULL },
 161         { "send",       zfs_do_send,            HELP_SEND               },
 162         { "receive",    zfs_do_receive,         HELP_RECEIVE            },
 163         { NULL },
 164         { "allow",      zfs_do_allow,           HELP_ALLOW              },
 165         { NULL },
 166         { "unallow",    zfs_do_unallow,         HELP_UNALLOW            },
 167         { NULL },
 168         { "key",        zfs_do_key,             HELP_KEY                },
 169 };
 170 
 171 #define NCOMMAND        (sizeof (command_table) / sizeof (command_table[0]))
 172 
 173 zfs_command_t *current_command;
 174 
 175 static const char *
 176 get_usage(zfs_help_t idx)
 177 {
 178         switch (idx) {
 179         case HELP_CLONE:
 180                 return (gettext("\tclone [-p] [-o property=value] ... "
 181                     "<snapshot> <filesystem|volume>\n"));
 182         case HELP_CREATE:
 183                 return (gettext("\tcreate [-p] [-o property=value] ... "
 184                     "<filesystem>\n"
 185                     "\tcreate [-ps] [-b blocksize] [-o property=value] ... "
 186                     "-V <size> <volume>\n"));
 187         case HELP_DESTROY:
 188                 return (gettext("\tdestroy [-rRf] "
 189                     "<filesystem|volume|snapshot>\n"));
 190         case HELP_GET:
 191                 return (gettext("\tget [-rHp] [-o field[,...]] "
 192                     "[-s source[,...]]\n"
 193                     "\t    <\"all\" | property[,...]> "
 194                     "[filesystem|volume|snapshot] ...\n"));
 195         case HELP_INHERIT:
 196                 return (gettext("\tinherit [-r] <property> "
 197                     "<filesystem|volume|snapshot> ...\n"));
 198         case HELP_UPGRADE:
 199                 return (gettext("\tupgrade [-v]\n"
 200                     "\tupgrade [-r] [-V version] <-a | filesystem ...>\n"));
 201         case HELP_LIST:
 202                 return (gettext("\tlist [-rH] [-o property[,...]] "
 203                     "[-t type[,...]] [-s property] ...\n"
 204                     "\t    [-S property] ... "
 205                     "[filesystem|volume|snapshot] ...\n"));
 206         case HELP_MOUNT:
 207                 return (gettext("\tmount\n"
 208                     "\tmount [-vO] [-o opts] <-a | filesystem>\n"));
 209         case HELP_PROMOTE:
 210                 return (gettext("\tpromote <clone-filesystem>\n"));
 211         case HELP_RECEIVE:
 212                 return (gettext("\treceive [-vnF] <filesystem|volume|"
 213                 "snapshot>\n"
 214                 "\treceive [-vnF] -d <filesystem>\n"));
 215         case HELP_RENAME:
 216                 return (gettext("\trename <filesystem|volume|snapshot> "
 217                     "<filesystem|volume|snapshot>\n"
 218                     "\trename -p <filesystem|volume> <filesystem|volume>\n"
 219                     "\trename -r <snapshot> <snapshot>"));
 220         case HELP_ROLLBACK:
 221                 return (gettext("\trollback [-rRf] <snapshot>\n"));
 222         case HELP_SEND:
 223                 return (gettext("\tsend [-R] [-[iI] snapshot] <snapshot>\n"));
 224         case HELP_SET:
 225                 return (gettext("\tset <property=value> "
 226                     "<filesystem|volume|snapshot> ...\n"));
 227         case HELP_SHARE:
 228                 return (gettext("\tshare <-a | filesystem>\n"));
 229         case HELP_SNAPSHOT:
 230                 return (gettext("\tsnapshot [-r] [-o property=value] ... "
 231                     "<filesystem@snapname|volume@snapname>\n"));
 232         case HELP_UNMOUNT:
 233                 return (gettext("\tunmount [-f] "
 234                     "<-a | filesystem|mountpoint>\n"));
 235         case HELP_UNSHARE:
 236                 return (gettext("\tunshare [-f] "
 237                     "<-a | filesystem|mountpoint>\n"));
 238         case HELP_ALLOW:
 239                 return (gettext("\tallow [-ldug] "
 240                     "<\"everyone\"|user|group>[,...] <perm|@setname>[,...]\n"
 241                     "\t    <filesystem|volume>\n"
 242                     "\tallow [-ld] -e <perm|@setname>[,...] "
 243                     "<filesystem|volume>\n"
 244                     "\tallow -c <perm|@setname>[,...] <filesystem|volume>\n"
 245                     "\tallow -s @setname <perm|@setname>[,...] "
 246                     "<filesystem|volume>\n"));
 247         case HELP_UNALLOW:
 248                 return (gettext("\tunallow [-rldug] "
 249                     "<\"everyone\"|user|group>[,...]\n"
 250                     "\t    [<perm|@setname>[,...]] <filesystem|volume>\n"
 251                     "\tunallow [-rld] -e [<perm|@setname>[,...]] "
 252                     "<filesystem|volume>\n"
 253                     "\tunallow [-r] -c [<perm|@setname>[,...]] "
 254                     "<filesystem|volume>\n"
 255                     "\tunallow [-r] -s @setname [<perm|@setname>[,...]] "
 256                     "<filesystem|volume>\n"));
 257         case HELP_KEY:
 258                 return (gettext("\tkey <-l | -u | -c [ -o <property=value>]> "
 259                     "<-a | filesystem>\n"));
 260         }
 261 
 262         abort();
 263         /* NOTREACHED */
 264 }
 265 
 266 /*
 267  * Utility function to guarantee malloc() success.
 268  */
 269 void *
 270 safe_malloc(size_t size)
 271 {
 272         void *data;
 273 
 274         if ((data = calloc(1, size)) == NULL) {
 275                 (void) fprintf(stderr, "internal error: out of memory\n");
 276                 exit(1);
 277         }
 278 
 279         return (data);
 280 }
 281 
 282 /*
 283  * Callback routine that will print out information for each of
 284  * the properties.
 285  */
 286 static int
 287 usage_prop_cb(int prop, void *cb)
 288 {
 289         FILE *fp = cb;
 290 
 291         (void) fprintf(fp, "\t%-15s ", zfs_prop_to_name(prop));
 292 
 293         if (zfs_prop_readonly(prop))
 294                 (void) fprintf(fp, " NO    ");
 295         else
 296                 (void) fprintf(fp, "YES    ");
 297 
 298         if (zfs_prop_inheritable(prop))
 299                 (void) fprintf(fp, "  YES   ");
 300         else
 301                 (void) fprintf(fp, "   NO   ");
 302 
 303         if (zfs_prop_values(prop) == NULL)
 304                 (void) fprintf(fp, "-\n");
 305         else
 306                 (void) fprintf(fp, "%s\n", zfs_prop_values(prop));
 307 
 308         return (ZPROP_CONT);
 309 }
 310 
 311 /*
 312  * Display usage message.  If we're inside a command, display only the usage for
 313  * that command.  Otherwise, iterate over the entire command table and display
 314  * a complete usage message.
 315  */
 316 static void
 317 usage(boolean_t requested)
 318 {
 319         int i;
 320         boolean_t show_properties = B_FALSE;
 321         boolean_t show_permissions = B_FALSE;
 322         FILE *fp = requested ? stdout : stderr;
 323 
 324         if (current_command == NULL) {
 325 
 326                 (void) fprintf(fp, gettext("usage: zfs command args ...\n"));
 327                 (void) fprintf(fp,
 328                     gettext("where 'command' is one of the following:\n\n"));
 329 
 330                 for (i = 0; i < NCOMMAND; i++) {
 331                         if (command_table[i].name == NULL)
 332                                 (void) fprintf(fp, "\n");
 333                         else
 334                                 (void) fprintf(fp, "%s",
 335                                     get_usage(command_table[i].usage));
 336                 }
 337 
 338                 (void) fprintf(fp, gettext("\nEach dataset is of the form: "
 339                     "pool/[dataset/]*dataset[@name]\n"));
 340         } else {
 341                 (void) fprintf(fp, gettext("usage:\n"));
 342                 (void) fprintf(fp, "%s", get_usage(current_command->usage));
 343         }
 344 
 345         if (current_command != NULL &&
 346             (strcmp(current_command->name, "set") == 0 ||
 347             strcmp(current_command->name, "get") == 0 ||
 348             strcmp(current_command->name, "inherit") == 0 ||
 349             strcmp(current_command->name, "list") == 0))
 350                 show_properties = B_TRUE;
 351 
 352         if (current_command != NULL &&
 353             (strcmp(current_command->name, "allow") == 0 ||
 354             strcmp(current_command->name, "unallow") == 0))
 355                 show_permissions = B_TRUE;
 356 
 357         if (show_properties) {
 358 
 359                 (void) fprintf(fp,
 360                     gettext("\nThe following properties are supported:\n"));
 361 
 362                 (void) fprintf(fp, "\n\t%-14s %s  %s   %s\n\n",
 363                     "PROPERTY", "EDIT", "INHERIT", "VALUES");
 364 
 365                 /* Iterate over all properties */
 366                 (void) zprop_iter(usage_prop_cb, fp, B_FALSE, B_TRUE,
 367                     ZFS_TYPE_DATASET);
 368 
 369                 (void) fprintf(fp, gettext("\nSizes are specified in bytes "
 370                     "with standard units such as K, M, G, etc.\n"));
 371                 (void) fprintf(fp, gettext("\nUser-defined properties can "
 372                     "be specified by using a name containing a colon (:).\n"));
 373 
 374         } else if (show_permissions) {
 375                 (void) fprintf(fp,
 376                     gettext("\nThe following permissions are supported:\n"));
 377 
 378                 zfs_deleg_permissions();
 379         } else {
 380                 (void) fprintf(fp,
 381                     gettext("\nFor the property list, run: %s\n"),
 382                     "zfs set|get");
 383                 (void) fprintf(fp,
 384                     gettext("\nFor the delegated permission list, run: %s\n"),
 385                     "zfs allow|unallow");
 386         }
 387 
 388         /*
 389          * See comments at end of main().
 390          */
 391         if (getenv("ZFS_ABORT") != NULL) {
 392                 (void) printf("dumping core by request\n");
 393                 abort();
 394         }
 395 
 396         exit(requested ? 0 : 2);
 397 }
 398 
 399 static int
 400 parseprop(nvlist_t *props)
 401 {
 402         char *propname = optarg;
 403         char *propval, *strval;
 404 
 405         if ((propval = strchr(propname, '=')) == NULL) {
 406                 (void) fprintf(stderr, gettext("missing "
 407                     "'=' for -o option\n"));
 408                 return (-1);
 409         }
 410         *propval = '\0';
 411         propval++;
 412         if (nvlist_lookup_string(props, propname, &strval) == 0) {
 413                 (void) fprintf(stderr, gettext("property '%s' "
 414                     "specified multiple times\n"), propname);
 415                 return (-1);
 416         }
 417         if (nvlist_add_string(props, propname, propval) != 0) {
 418                 (void) fprintf(stderr, gettext("internal "
 419                     "error: out of memory\n"));
 420                 return (-1);
 421         }
 422         return (0);
 423 }
 424 
 425 /*
 426  * zfs clone [-p] [-o prop=value] ... <snap> <fs | vol>
 427  *
 428  * Given an existing dataset, create a writable copy whose initial contents
 429  * are the same as the source.  The newly created dataset maintains a
 430  * dependency on the original; the original cannot be destroyed so long as
 431  * the clone exists.
 432  *
 433  * The '-p' flag creates all the non-existing ancestors of the target first.
 434  */
 435 static int
 436 zfs_do_clone(int argc, char **argv)
 437 {
 438         zfs_handle_t *zhp = NULL;
 439         boolean_t parents = B_FALSE;
 440         nvlist_t *props;
 441         int ret;
 442         int c;
 443 
 444         if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0) {
 445                 (void) fprintf(stderr, gettext("internal error: "
 446                     "out of memory\n"));
 447                 return (1);
 448         }
 449 
 450         /* check options */
 451         while ((c = getopt(argc, argv, "o:p")) != -1) {
 452                 switch (c) {
 453                 case 'o':
 454                         if (parseprop(props))
 455                                 return (1);
 456                         break;
 457                 case 'p':
 458                         parents = B_TRUE;
 459                         break;
 460                 case '?':
 461                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
 462                             optopt);
 463                         goto usage;
 464                 }
 465         }
 466 
 467         argc -= optind;
 468         argv += optind;
 469 
 470         /* check number of arguments */
 471         if (argc < 1) {
 472                 (void) fprintf(stderr, gettext("missing source dataset "
 473                     "argument\n"));
 474                 goto usage;
 475         }
 476         if (argc < 2) {
 477                 (void) fprintf(stderr, gettext("missing target dataset "
 478                     "argument\n"));
 479                 goto usage;
 480         }
 481         if (argc > 2) {
 482                 (void) fprintf(stderr, gettext("too many arguments\n"));
 483                 goto usage;
 484         }
 485 
 486         /* open the source dataset */
 487         if ((zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_SNAPSHOT)) == NULL)
 488                 return (1);
 489 
 490         if (parents && zfs_name_valid(argv[1], ZFS_TYPE_FILESYSTEM |
 491             ZFS_TYPE_VOLUME)) {
 492                 /*
 493                  * Now create the ancestors of the target dataset.  If the
 494                  * target already exists and '-p' option was used we should not
 495                  * complain.
 496                  */
 497                 if (zfs_dataset_exists(g_zfs, argv[1], ZFS_TYPE_FILESYSTEM |
 498                     ZFS_TYPE_VOLUME))
 499                         return (0);
 500                 if (zfs_create_ancestors(g_zfs, argv[1]) != 0)
 501                         return (1);
 502         }
 503 
 504         /* pass to libzfs */
 505         ret = zfs_clone(zhp, argv[1], props);
 506 
 507         /* create the mountpoint if necessary */
 508         if (ret == 0) {
 509                 zfs_handle_t *clone;
 510 
 511                 clone = zfs_open(g_zfs, argv[1], ZFS_TYPE_DATASET);
 512                 if (clone != NULL) {
 513                         if ((ret = zfs_mount(clone, NULL, 0)) == 0)
 514                                 ret = zfs_share(clone);
 515                         zfs_close(clone);
 516                 }
 517         }
 518 
 519         zfs_close(zhp);
 520         nvlist_free(props);
 521 
 522         return (!!ret);
 523 
 524 usage:
 525         if (zhp)
 526                 zfs_close(zhp);
 527         nvlist_free(props);
 528         usage(B_FALSE);
 529         return (-1);
 530 }
 531 
 532 /*
 533  * zfs create [-p] [-o prop=value] ... fs
 534  * zfs create [-ps] [-b blocksize] [-o prop=value] ... -V vol size
 535  *
 536  * Create a new dataset.  This command can be used to create filesystems
 537  * and volumes.  Snapshot creation is handled by 'zfs snapshot'.
 538  * For volumes, the user must specify a size to be used.
 539  *
 540  * The '-s' flag applies only to volumes, and indicates that we should not try
 541  * to set the reservation for this volume.  By default we set a reservation
 542  * equal to the size for any volume.  For pools with SPA_VERSION >=
 543  * SPA_VERSION_REFRESERVATION, we set a refreservation instead.
 544  *
 545  * The '-p' flag creates all the non-existing ancestors of the target first.
 546  */
 547 static int
 548 zfs_do_create(int argc, char **argv)
 549 {
 550         zfs_type_t type = ZFS_TYPE_FILESYSTEM;
 551         zfs_handle_t *zhp = NULL;
 552         uint64_t volsize;
 553         int c;
 554         boolean_t noreserve = B_FALSE;
 555         boolean_t bflag = B_FALSE;
 556         boolean_t parents = B_FALSE;
 557         int ret = 1;
 558         nvlist_t *props;
 559         uint64_t intval;
 560         int canmount;
 561 
 562         if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0) {
 563                 (void) fprintf(stderr, gettext("internal error: "
 564                     "out of memory\n"));
 565                 return (1);
 566         }
 567 
 568         /* check options */
 569         while ((c = getopt(argc, argv, ":V:b:so:p")) != -1) {
 570                 switch (c) {
 571                 case 'V':
 572                         type = ZFS_TYPE_VOLUME;
 573                         if (zfs_nicestrtonum(g_zfs, optarg, &intval) != 0) {
 574                                 (void) fprintf(stderr, gettext("bad volume "
 575                                     "size '%s': %s\n"), optarg,
 576                                     libzfs_error_description(g_zfs));
 577                                 goto error;
 578                         }
 579 
 580                         if (nvlist_add_uint64(props,
 581                             zfs_prop_to_name(ZFS_PROP_VOLSIZE),
 582                             intval) != 0) {
 583                                 (void) fprintf(stderr, gettext("internal "
 584                                     "error: out of memory\n"));
 585                                 goto error;
 586                         }
 587                         volsize = intval;
 588                         break;
 589                 case 'p':
 590                         parents = B_TRUE;
 591                         break;
 592                 case 'b':
 593                         bflag = B_TRUE;
 594                         if (zfs_nicestrtonum(g_zfs, optarg, &intval) != 0) {
 595                                 (void) fprintf(stderr, gettext("bad volume "
 596                                     "block size '%s': %s\n"), optarg,
 597                                     libzfs_error_description(g_zfs));
 598                                 goto error;
 599                         }
 600 
 601                         if (nvlist_add_uint64(props,
 602                             zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE),
 603                             intval) != 0) {
 604                                 (void) fprintf(stderr, gettext("internal "
 605                                     "error: out of memory\n"));
 606                                 goto error;
 607                         }
 608                         break;
 609                 case 'o':
 610                         if (parseprop(props))
 611                                 goto error;
 612                         break;
 613                 case 's':
 614                         noreserve = B_TRUE;
 615                         break;
 616                 case ':':
 617                         (void) fprintf(stderr, gettext("missing size "
 618                             "argument\n"));
 619                         goto badusage;
 620                         break;
 621                 case '?':
 622                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
 623                             optopt);
 624                         goto badusage;
 625                 }
 626         }
 627 
 628         if ((bflag || noreserve) && type != ZFS_TYPE_VOLUME) {
 629                 (void) fprintf(stderr, gettext("'-s' and '-b' can only be "
 630                     "used when creating a volume\n"));
 631                 goto badusage;
 632         }
 633 
 634         argc -= optind;
 635         argv += optind;
 636 
 637         /* check number of arguments */
 638         if (argc == 0) {
 639                 (void) fprintf(stderr, gettext("missing %s argument\n"),
 640                     zfs_type_to_name(type));
 641                 goto badusage;
 642         }
 643         if (argc > 1) {
 644                 (void) fprintf(stderr, gettext("too many arguments\n"));
 645                 goto badusage;
 646         }
 647 
 648         if (type == ZFS_TYPE_VOLUME && !noreserve) {
 649                 zpool_handle_t *zpool_handle;
 650                 uint64_t spa_version;
 651                 char *p;
 652                 zfs_prop_t resv_prop;
 653                 char *strval;
 654 
 655                 if (p = strchr(argv[0], '/'))
 656                         *p = '\0';
 657                 zpool_handle = zpool_open(g_zfs, argv[0]);
 658                 if (p != NULL)
 659                         *p = '/';
 660                 if (zpool_handle == NULL)
 661                         goto error;
 662                 spa_version = zpool_get_prop_int(zpool_handle,
 663                     ZPOOL_PROP_VERSION, NULL);
 664                 zpool_close(zpool_handle);
 665                 if (spa_version >= SPA_VERSION_REFRESERVATION)
 666                         resv_prop = ZFS_PROP_REFRESERVATION;
 667                 else
 668                         resv_prop = ZFS_PROP_RESERVATION;
 669 
 670                 if (nvlist_lookup_string(props, zfs_prop_to_name(resv_prop),
 671                     &strval) != 0) {
 672                         if (nvlist_add_uint64(props,
 673                             zfs_prop_to_name(resv_prop), volsize) != 0) {
 674                                 (void) fprintf(stderr, gettext("internal "
 675                                     "error: out of memory\n"));
 676                                 nvlist_free(props);
 677                                 return (1);
 678                         }
 679                 }
 680         }
 681 
 682         if (parents && zfs_name_valid(argv[0], type)) {
 683                 /*
 684                  * Now create the ancestors of target dataset.  If the target
 685                  * already exists and '-p' option was used we should not
 686                  * complain.
 687                  */
 688                 if (zfs_dataset_exists(g_zfs, argv[0], type)) {
 689                         ret = 0;
 690                         goto error;
 691                 }
 692                 if (zfs_create_ancestors(g_zfs, argv[0]) != 0)
 693                         goto error;
 694         }
 695 
 696         /* pass to libzfs */
 697         if (zfs_create(g_zfs, argv[0], type, props) != 0)
 698                 goto error;
 699 
 700         if ((zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_DATASET)) == NULL)
 701                 goto error;
 702         /*
 703          * if the user doesn't want the dataset automatically mounted,
 704          * then skip the mount/share step
 705          */
 706 
 707         canmount = zfs_prop_get_int(zhp, ZFS_PROP_CANMOUNT);
 708 
 709         /*
 710          * Mount and/or share the new filesystem as appropriate.  We provide a
 711          * verbose error message to let the user know that their filesystem was
 712          * in fact created, even if we failed to mount or share it.
 713          */
 714         ret = 0;
 715         if (canmount == ZFS_CANMOUNT_ON) {
 716                 if (zfs_mount(zhp, NULL, 0) != 0) {
 717                         (void) fprintf(stderr, gettext("filesystem "
 718                             "successfully created, but not mounted\n"));
 719                         ret = 1;
 720                 } else if (zfs_share(zhp) != 0) {
 721                         (void) fprintf(stderr, gettext("filesystem "
 722                             "successfully created, but not shared\n"));
 723                         ret = 1;
 724                 }
 725         }
 726 
 727 error:
 728         if (zhp)
 729                 zfs_close(zhp);
 730         nvlist_free(props);
 731         return (ret);
 732 badusage:
 733         nvlist_free(props);
 734         usage(B_FALSE);
 735         return (2);
 736 }
 737 
 738 /*
 739  * zfs destroy [-rf] <fs, snap, vol>
 740  *
 741  *      -r      Recursively destroy all children
 742  *      -R      Recursively destroy all dependents, including clones
 743  *      -f      Force unmounting of any dependents
 744  *
 745  * Destroys the given dataset.  By default, it will unmount any filesystems,
 746  * and refuse to destroy a dataset that has any dependents.  A dependent can
 747  * either be a child, or a clone of a child.
 748  */
 749 typedef struct destroy_cbdata {
 750         boolean_t       cb_first;
 751         int             cb_force;
 752         int             cb_recurse;
 753         int             cb_error;
 754         int             cb_needforce;
 755         int             cb_doclones;
 756         boolean_t       cb_closezhp;
 757         zfs_handle_t    *cb_target;
 758         char            *cb_snapname;
 759 } destroy_cbdata_t;
 760 
 761 /*
 762  * Check for any dependents based on the '-r' or '-R' flags.
 763  */
 764 static int
 765 destroy_check_dependent(zfs_handle_t *zhp, void *data)
 766 {
 767         destroy_cbdata_t *cbp = data;
 768         const char *tname = zfs_get_name(cbp->cb_target);
 769         const char *name = zfs_get_name(zhp);
 770 
 771         if (strncmp(tname, name, strlen(tname)) == 0 &&
 772             (name[strlen(tname)] == '/' || name[strlen(tname)] == '@')) {
 773                 /*
 774                  * This is a direct descendant, not a clone somewhere else in
 775                  * the hierarchy.
 776                  */
 777                 if (cbp->cb_recurse)
 778                         goto out;
 779 
 780                 if (cbp->cb_first) {
 781                         (void) fprintf(stderr, gettext("cannot destroy '%s': "
 782                             "%s has children\n"),
 783                             zfs_get_name(cbp->cb_target),
 784                             zfs_type_to_name(zfs_get_type(cbp->cb_target)));
 785                         (void) fprintf(stderr, gettext("use '-r' to destroy "
 786                             "the following datasets:\n"));
 787                         cbp->cb_first = B_FALSE;
 788                         cbp->cb_error = 1;
 789                 }
 790 
 791                 (void) fprintf(stderr, "%s\n", zfs_get_name(zhp));
 792         } else {
 793                 /*
 794                  * This is a clone.  We only want to report this if the '-r'
 795                  * wasn't specified, or the target is a snapshot.
 796                  */
 797                 if (!cbp->cb_recurse &&
 798                     zfs_get_type(cbp->cb_target) != ZFS_TYPE_SNAPSHOT)
 799                         goto out;
 800 
 801                 if (cbp->cb_first) {
 802                         (void) fprintf(stderr, gettext("cannot destroy '%s': "
 803                             "%s has dependent clones\n"),
 804                             zfs_get_name(cbp->cb_target),
 805                             zfs_type_to_name(zfs_get_type(cbp->cb_target)));
 806                         (void) fprintf(stderr, gettext("use '-R' to destroy "
 807                             "the following datasets:\n"));
 808                         cbp->cb_first = B_FALSE;
 809                         cbp->cb_error = 1;
 810                 }
 811 
 812                 (void) fprintf(stderr, "%s\n", zfs_get_name(zhp));
 813         }
 814 
 815 out:
 816         zfs_close(zhp);
 817         return (0);
 818 }
 819 
 820 static int
 821 destroy_callback(zfs_handle_t *zhp, void *data)
 822 {
 823         destroy_cbdata_t *cbp = data;
 824 
 825         /*
 826          * Ignore pools (which we've already flagged as an error before getting
 827          * here.
 828          */
 829         if (strchr(zfs_get_name(zhp), '/') == NULL &&
 830             zfs_get_type(zhp) == ZFS_TYPE_FILESYSTEM) {
 831                 zfs_close(zhp);
 832                 return (0);
 833         }
 834 
 835         /*
 836          * Bail out on the first error.
 837          */
 838         if (zfs_unmount(zhp, NULL, cbp->cb_force ? MS_FORCE : 0) != 0 ||
 839             zfs_destroy(zhp) != 0) {
 840                 zfs_close(zhp);
 841                 return (-1);
 842         }
 843 
 844         zfs_close(zhp);
 845         return (0);
 846 }
 847 
 848 static int
 849 destroy_snap_clones(zfs_handle_t *zhp, void *arg)
 850 {
 851         destroy_cbdata_t *cbp = arg;
 852         char thissnap[MAXPATHLEN];
 853         zfs_handle_t *szhp;
 854         boolean_t closezhp = cbp->cb_closezhp;
 855         int rv;
 856 
 857         (void) snprintf(thissnap, sizeof (thissnap),
 858             "%s@%s", zfs_get_name(zhp), cbp->cb_snapname);
 859 
 860         libzfs_print_on_error(g_zfs, B_FALSE);
 861         szhp = zfs_open(g_zfs, thissnap, ZFS_TYPE_SNAPSHOT);
 862         libzfs_print_on_error(g_zfs, B_TRUE);
 863         if (szhp) {
 864                 /*
 865                  * Destroy any clones of this snapshot
 866                  */
 867                 if (zfs_iter_dependents(szhp, B_FALSE, destroy_callback,
 868                     cbp) != 0) {
 869                         zfs_close(szhp);
 870                         if (closezhp)
 871                                 zfs_close(zhp);
 872                         return (-1);
 873                 }
 874                 zfs_close(szhp);
 875         }
 876 
 877         cbp->cb_closezhp = B_TRUE;
 878         rv = zfs_iter_filesystems(zhp, destroy_snap_clones, arg);
 879         if (closezhp)
 880                 zfs_close(zhp);
 881         return (rv);
 882 }
 883 
 884 static int
 885 zfs_do_destroy(int argc, char **argv)
 886 {
 887         destroy_cbdata_t cb = { 0 };
 888         int c;
 889         zfs_handle_t *zhp;
 890         char *cp;
 891 
 892         /* check options */
 893         while ((c = getopt(argc, argv, "frR")) != -1) {
 894                 switch (c) {
 895                 case 'f':
 896                         cb.cb_force = 1;
 897                         break;
 898                 case 'r':
 899                         cb.cb_recurse = 1;
 900                         break;
 901                 case 'R':
 902                         cb.cb_recurse = 1;
 903                         cb.cb_doclones = 1;
 904                         break;
 905                 case '?':
 906                 default:
 907                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
 908                             optopt);
 909                         usage(B_FALSE);
 910                 }
 911         }
 912 
 913         argc -= optind;
 914         argv += optind;
 915 
 916         /* check number of arguments */
 917         if (argc == 0) {
 918                 (void) fprintf(stderr, gettext("missing path argument\n"));
 919                 usage(B_FALSE);
 920         }
 921         if (argc > 1) {
 922                 (void) fprintf(stderr, gettext("too many arguments\n"));
 923                 usage(B_FALSE);
 924         }
 925 
 926         /*
 927          * If we are doing recursive destroy of a snapshot, then the
 928          * named snapshot may not exist.  Go straight to libzfs.
 929          */
 930         if (cb.cb_recurse && (cp = strchr(argv[0], '@'))) {
 931                 int ret;
 932 
 933                 *cp = '\0';
 934                 if ((zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_DATASET)) == NULL)
 935                         return (1);
 936                 *cp = '@';
 937                 cp++;
 938 
 939                 if (cb.cb_doclones) {
 940                         cb.cb_snapname = cp;
 941                         if (destroy_snap_clones(zhp, &cb) != 0) {
 942                                 zfs_close(zhp);
 943                                 return (1);
 944                         }
 945                 }
 946 
 947                 ret = zfs_destroy_snaps(zhp, cp);
 948                 zfs_close(zhp);
 949                 if (ret) {
 950                         (void) fprintf(stderr,
 951                             gettext("no snapshots destroyed\n"));
 952                 }
 953                 return (ret != 0);
 954         }
 955 
 956 
 957         /* Open the given dataset */
 958         if ((zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_DATASET)) == NULL)
 959                 return (1);
 960 
 961         cb.cb_target = zhp;
 962 
 963         /*
 964          * Perform an explicit check for pools before going any further.
 965          */
 966         if (!cb.cb_recurse && strchr(zfs_get_name(zhp), '/') == NULL &&
 967             zfs_get_type(zhp) == ZFS_TYPE_FILESYSTEM) {
 968                 (void) fprintf(stderr, gettext("cannot destroy '%s': "
 969                     "operation does not apply to pools\n"),
 970                     zfs_get_name(zhp));
 971                 (void) fprintf(stderr, gettext("use 'zfs destroy -r "
 972                     "%s' to destroy all datasets in the pool\n"),
 973                     zfs_get_name(zhp));
 974                 (void) fprintf(stderr, gettext("use 'zpool destroy %s' "
 975                     "to destroy the pool itself\n"), zfs_get_name(zhp));
 976                 zfs_close(zhp);
 977                 return (1);
 978         }
 979 
 980         /*
 981          * Check for any dependents and/or clones.
 982          */
 983         cb.cb_first = B_TRUE;
 984         if (!cb.cb_doclones &&
 985             zfs_iter_dependents(zhp, B_TRUE, destroy_check_dependent,
 986             &cb) != 0) {
 987                 zfs_close(zhp);
 988                 return (1);
 989         }
 990 
 991         if (cb.cb_error ||
 992             zfs_iter_dependents(zhp, B_FALSE, destroy_callback, &cb) != 0) {
 993                 zfs_close(zhp);
 994                 return (1);
 995         }
 996 
 997         /*
 998          * Do the real thing.  The callback will close the handle regardless of
 999          * whether it succeeds or not.
1000          */
1001 
1002         if (destroy_callback(zhp, &cb) != 0)
1003                 return (1);
1004 
1005 
1006         return (0);
1007 }
1008 
1009 /*
1010  * zfs get [-rHp] [-o field[,field]...] [-s source[,source]...]
1011  *      < all | property[,property]... > < fs | snap | vol > ...
1012  *
1013  *      -r      recurse over any child datasets
1014  *      -H      scripted mode.  Headers are stripped, and fields are separated
1015  *              by tabs instead of spaces.
1016  *      -o      Set of fields to display.  One of "name,property,value,source".
1017  *              Default is all four.
1018  *      -s      Set of sources to allow.  One of
1019  *              "local,default,inherited,temporary,none".  Default is all
1020  *              five.
1021  *      -p      Display values in parsable (literal) format.
1022  *
1023  *  Prints properties for the given datasets.  The user can control which
1024  *  columns to display as well as which property types to allow.
1025  */
1026 
1027 /*
1028  * Invoked to display the properties for a single dataset.
1029  */
1030 static int
1031 get_callback(zfs_handle_t *zhp, void *data)
1032 {
1033         char buf[ZFS_MAXPROPLEN];
1034         zprop_source_t sourcetype;
1035         char source[ZFS_MAXNAMELEN];
1036         zprop_get_cbdata_t *cbp = data;
1037         nvlist_t *userprop = zfs_get_user_props(zhp);
1038         zprop_list_t *pl = cbp->cb_proplist;
1039         nvlist_t *propval;
1040         char *strval;
1041         char *sourceval;
1042 
1043         for (; pl != NULL; pl = pl->pl_next) {
1044                 /*
1045                  * Skip the special fake placeholder.  This will also skip over
1046                  * the name property when 'all' is specified.
1047                  */
1048                 if (pl->pl_prop == ZFS_PROP_NAME &&
1049                     pl == cbp->cb_proplist)
1050                         continue;
1051 
1052                 if (pl->pl_prop != ZPROP_INVAL) {
1053                         if (zfs_prop_get(zhp, pl->pl_prop, buf,
1054                             sizeof (buf), &sourcetype, source,
1055                             sizeof (source),
1056                             cbp->cb_literal) != 0) {
1057                                 if (pl->pl_all)
1058                                         continue;
1059                                 if (!zfs_prop_valid_for_type(pl->pl_prop,
1060                                     ZFS_TYPE_DATASET)) {
1061                                         (void) fprintf(stderr,
1062                                             gettext("No such property '%s'\n"),
1063                                             zfs_prop_to_name(pl->pl_prop));
1064                                         continue;
1065                                 }
1066                                 sourcetype = ZPROP_SRC_NONE;
1067                                 (void) strlcpy(buf, "-", sizeof (buf));
1068                         }
1069 
1070                         zprop_print_one_property(zfs_get_name(zhp), cbp,
1071                             zfs_prop_to_name(pl->pl_prop),
1072                             buf, sourcetype, source);
1073                 } else {
1074                         if (nvlist_lookup_nvlist(userprop,
1075                             pl->pl_user_prop, &propval) != 0) {
1076                                 if (pl->pl_all)
1077                                         continue;
1078                                 sourcetype = ZPROP_SRC_NONE;
1079                                 strval = "-";
1080                         } else {
1081                                 verify(nvlist_lookup_string(propval,
1082                                     ZPROP_VALUE, &strval) == 0);
1083                                 verify(nvlist_lookup_string(propval,
1084                                     ZPROP_SOURCE, &sourceval) == 0);
1085 
1086                                 if (strcmp(sourceval,
1087                                     zfs_get_name(zhp)) == 0) {
1088                                         sourcetype = ZPROP_SRC_LOCAL;
1089                                 } else {
1090                                         sourcetype = ZPROP_SRC_INHERITED;
1091                                         (void) strlcpy(source,
1092                                             sourceval, sizeof (source));
1093                                 }
1094                         }
1095 
1096                         zprop_print_one_property(zfs_get_name(zhp), cbp,
1097                             pl->pl_user_prop, strval, sourcetype,
1098                             source);
1099                 }
1100         }
1101 
1102         return (0);
1103 }
1104 
1105 static int
1106 zfs_do_get(int argc, char **argv)
1107 {
1108         zprop_get_cbdata_t cb = { 0 };
1109         int i, c, flags = 0;
1110         char *value, *fields;
1111         int ret;
1112         zprop_list_t fake_name = { 0 };
1113 
1114         /*
1115          * Set up default columns and sources.
1116          */
1117         cb.cb_sources = ZPROP_SRC_ALL;
1118         cb.cb_columns[0] = GET_COL_NAME;
1119         cb.cb_columns[1] = GET_COL_PROPERTY;
1120         cb.cb_columns[2] = GET_COL_VALUE;
1121         cb.cb_columns[3] = GET_COL_SOURCE;
1122         cb.cb_type = ZFS_TYPE_DATASET;
1123 
1124         /* check options */
1125         while ((c = getopt(argc, argv, ":o:s:rHp")) != -1) {
1126                 switch (c) {
1127                 case 'p':
1128                         cb.cb_literal = B_TRUE;
1129                         break;
1130                 case 'r':
1131                         flags |= ZFS_ITER_RECURSE;
1132                         break;
1133                 case 'H':
1134                         cb.cb_scripted = B_TRUE;
1135                         break;
1136                 case ':':
1137                         (void) fprintf(stderr, gettext("missing argument for "
1138                             "'%c' option\n"), optopt);
1139                         usage(B_FALSE);
1140                         break;
1141                 case 'o':
1142                         /*
1143                          * Process the set of columns to display.  We zero out
1144                          * the structure to give us a blank slate.
1145                          */
1146                         bzero(&cb.cb_columns, sizeof (cb.cb_columns));
1147                         i = 0;
1148                         while (*optarg != '\0') {
1149                                 static char *col_subopts[] =
1150                                     { "name", "property", "value", "source",
1151                                     NULL };
1152 
1153                                 if (i == 4) {
1154                                         (void) fprintf(stderr, gettext("too "
1155                                             "many fields given to -o "
1156                                             "option\n"));
1157                                         usage(B_FALSE);
1158                                 }
1159 
1160                                 switch (getsubopt(&optarg, col_subopts,
1161                                     &value)) {
1162                                 case 0:
1163                                         cb.cb_columns[i++] = GET_COL_NAME;
1164                                         break;
1165                                 case 1:
1166                                         cb.cb_columns[i++] = GET_COL_PROPERTY;
1167                                         break;
1168                                 case 2:
1169                                         cb.cb_columns[i++] = GET_COL_VALUE;
1170                                         break;
1171                                 case 3:
1172                                         cb.cb_columns[i++] = GET_COL_SOURCE;
1173                                         break;
1174                                 default:
1175                                         (void) fprintf(stderr,
1176                                             gettext("invalid column name "
1177                                             "'%s'\n"), value);
1178                                         usage(B_FALSE);
1179                                 }
1180                         }
1181                         break;
1182 
1183                 case 's':
1184                         cb.cb_sources = 0;
1185                         while (*optarg != '\0') {
1186                                 static char *source_subopts[] = {
1187                                         "local", "default", "inherited",
1188                                         "temporary", "none", NULL };
1189 
1190                                 switch (getsubopt(&optarg, source_subopts,
1191                                     &value)) {
1192                                 case 0:
1193                                         cb.cb_sources |= ZPROP_SRC_LOCAL;
1194                                         break;
1195                                 case 1:
1196                                         cb.cb_sources |= ZPROP_SRC_DEFAULT;
1197                                         break;
1198                                 case 2:
1199                                         cb.cb_sources |= ZPROP_SRC_INHERITED;
1200                                         break;
1201                                 case 3:
1202                                         cb.cb_sources |= ZPROP_SRC_TEMPORARY;
1203                                         break;
1204                                 case 4:
1205                                         cb.cb_sources |= ZPROP_SRC_NONE;
1206                                         break;
1207                                 default:
1208                                         (void) fprintf(stderr,
1209                                             gettext("invalid source "
1210                                             "'%s'\n"), value);
1211                                         usage(B_FALSE);
1212                                 }
1213                         }
1214                         break;
1215 
1216                 case '?':
1217                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
1218                             optopt);
1219                         usage(B_FALSE);
1220                 }
1221         }
1222 
1223         argc -= optind;
1224         argv += optind;
1225 
1226         if (argc < 1) {
1227                 (void) fprintf(stderr, gettext("missing property "
1228                     "argument\n"));
1229                 usage(B_FALSE);
1230         }
1231 
1232         fields = argv[0];
1233 
1234         if (zprop_get_list(g_zfs, fields, &cb.cb_proplist, ZFS_TYPE_DATASET)
1235             != 0)
1236                 usage(B_FALSE);
1237 
1238         argc--;
1239         argv++;
1240 
1241         /*
1242          * As part of zfs_expand_proplist(), we keep track of the maximum column
1243          * width for each property.  For the 'NAME' (and 'SOURCE') columns, we
1244          * need to know the maximum name length.  However, the user likely did
1245          * not specify 'name' as one of the properties to fetch, so we need to
1246          * make sure we always include at least this property for
1247          * print_get_headers() to work properly.
1248          */
1249         if (cb.cb_proplist != NULL) {
1250                 fake_name.pl_prop = ZFS_PROP_NAME;
1251                 fake_name.pl_width = strlen(gettext("NAME"));
1252                 fake_name.pl_next = cb.cb_proplist;
1253                 cb.cb_proplist = &fake_name;
1254         }
1255 
1256         cb.cb_first = B_TRUE;
1257 
1258         /* run for each object */
1259         ret = zfs_for_each(argc, argv, flags, ZFS_TYPE_DATASET, NULL,
1260             &cb.cb_proplist, get_callback, &cb);
1261 
1262         if (cb.cb_proplist == &fake_name)
1263                 zprop_free_list(fake_name.pl_next);
1264         else
1265                 zprop_free_list(cb.cb_proplist);
1266 
1267         return (ret);
1268 }
1269 
1270 /*
1271  * inherit [-r] <property> <fs|vol> ...
1272  *
1273  *      -r      Recurse over all children
1274  *
1275  * For each dataset specified on the command line, inherit the given property
1276  * from its parent.  Inheriting a property at the pool level will cause it to
1277  * use the default value.  The '-r' flag will recurse over all children, and is
1278  * useful for setting a property on a hierarchy-wide basis, regardless of any
1279  * local modifications for each dataset.
1280  */
1281 
1282 static int
1283 inherit_recurse_cb(zfs_handle_t *zhp, void *data)
1284 {
1285         char *propname = data;
1286         zfs_prop_t prop = zfs_name_to_prop(propname);
1287 
1288         /*
1289          * If we're doing it recursively, then ignore properties that
1290          * are not valid for this type of dataset.
1291          */
1292         if (prop != ZPROP_INVAL &&
1293             !zfs_prop_valid_for_type(prop, zfs_get_type(zhp)))
1294                 return (0);
1295 
1296         return (zfs_prop_inherit(zhp, propname) != 0);
1297 }
1298 
1299 static int
1300 inherit_cb(zfs_handle_t *zhp, void *data)
1301 {
1302         char *propname = data;
1303 
1304         return (zfs_prop_inherit(zhp, propname) != 0);
1305 }
1306 
1307 static int
1308 zfs_do_inherit(int argc, char **argv)
1309 {
1310         int c;
1311         zfs_prop_t prop;
1312         char *propname;
1313         int ret;
1314         int flags = 0;
1315 
1316         /* check options */
1317         while ((c = getopt(argc, argv, "r")) != -1) {
1318                 switch (c) {
1319                 case 'r':
1320                         flags |= ZFS_ITER_RECURSE;
1321                         break;
1322                 case '?':
1323                 default:
1324                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
1325                             optopt);
1326                         usage(B_FALSE);
1327                 }
1328         }
1329 
1330         argc -= optind;
1331         argv += optind;
1332 
1333         /* check number of arguments */
1334         if (argc < 1) {
1335                 (void) fprintf(stderr, gettext("missing property argument\n"));
1336                 usage(B_FALSE);
1337         }
1338         if (argc < 2) {
1339                 (void) fprintf(stderr, gettext("missing dataset argument\n"));
1340                 usage(B_FALSE);
1341         }
1342 
1343         propname = argv[0];
1344         argc--;
1345         argv++;
1346 
1347         if ((prop = zfs_name_to_prop(propname)) != ZPROP_INVAL) {
1348                 if (zfs_prop_readonly(prop)) {
1349                         (void) fprintf(stderr, gettext(
1350                             "%s property is read-only\n"),
1351                             propname);
1352                         return (1);
1353                 }
1354                 if (!zfs_prop_inheritable(prop)) {
1355                         (void) fprintf(stderr, gettext("'%s' property cannot "
1356                             "be inherited\n"), propname);
1357                         if (prop == ZFS_PROP_QUOTA ||
1358                             prop == ZFS_PROP_RESERVATION ||
1359                             prop == ZFS_PROP_REFQUOTA ||
1360                             prop == ZFS_PROP_REFRESERVATION)
1361                                 (void) fprintf(stderr, gettext("use 'zfs set "
1362                                     "%s=none' to clear\n"), propname);
1363                         return (1);
1364                 }
1365         } else if (!zfs_prop_user(propname)) {
1366                 (void) fprintf(stderr, gettext("invalid property '%s'\n"),
1367                     propname);
1368                 usage(B_FALSE);
1369         }
1370 
1371         if (flags & ZFS_ITER_RECURSE) {
1372                 ret = zfs_for_each(argc, argv, flags, ZFS_TYPE_DATASET,
1373                     NULL, NULL, inherit_recurse_cb, propname);
1374         } else {
1375                 ret = zfs_for_each(argc, argv, flags, ZFS_TYPE_DATASET,
1376                     NULL, NULL, inherit_cb, propname);
1377         }
1378 
1379         return (ret);
1380 }
1381 
1382 typedef struct upgrade_cbdata {
1383         uint64_t cb_numupgraded;
1384         uint64_t cb_numsamegraded;
1385         uint64_t cb_numfailed;
1386         uint64_t cb_version;
1387         boolean_t cb_newer;
1388         boolean_t cb_foundone;
1389         char cb_lastfs[ZFS_MAXNAMELEN];
1390 } upgrade_cbdata_t;
1391 
1392 static int
1393 same_pool(zfs_handle_t *zhp, const char *name)
1394 {
1395         int len1 = strcspn(name, "/@");
1396         const char *zhname = zfs_get_name(zhp);
1397         int len2 = strcspn(zhname, "/@");
1398 
1399         if (len1 != len2)
1400                 return (B_FALSE);
1401         return (strncmp(name, zhname, len1) == 0);
1402 }
1403 
1404 static int
1405 upgrade_list_callback(zfs_handle_t *zhp, void *data)
1406 {
1407         upgrade_cbdata_t *cb = data;
1408         int version = zfs_prop_get_int(zhp, ZFS_PROP_VERSION);
1409 
1410         /* list if it's old/new */
1411         if ((!cb->cb_newer && version < ZPL_VERSION) ||
1412             (cb->cb_newer && version > ZPL_VERSION)) {
1413                 char *str;
1414                 if (cb->cb_newer) {
1415                         str = gettext("The following filesystems are "
1416                             "formatted using a newer software version and\n"
1417                             "cannot be accessed on the current system.\n\n");
1418                 } else {
1419                         str = gettext("The following filesystems are "
1420                             "out of date, and can be upgraded.  After being\n"
1421                             "upgraded, these filesystems (and any 'zfs send' "
1422                             "streams generated from\n"
1423                             "subsequent snapshots) will no longer be "
1424                             "accessible by older software versions.\n\n");
1425                 }
1426 
1427                 if (!cb->cb_foundone) {
1428                         (void) puts(str);
1429                         (void) printf(gettext("VER  FILESYSTEM\n"));
1430                         (void) printf(gettext("---  ------------\n"));
1431                         cb->cb_foundone = B_TRUE;
1432                 }
1433 
1434                 (void) printf("%2u   %s\n", version, zfs_get_name(zhp));
1435         }
1436 
1437         return (0);
1438 }
1439 
1440 static int
1441 upgrade_set_callback(zfs_handle_t *zhp, void *data)
1442 {
1443         upgrade_cbdata_t *cb = data;
1444         int version = zfs_prop_get_int(zhp, ZFS_PROP_VERSION);
1445 
1446         if (cb->cb_version >= ZPL_VERSION_FUID) {
1447                 int spa_version;
1448 
1449                 if (zfs_spa_version(zhp, &spa_version) < 0)
1450                         return (-1);
1451 
1452                 if (spa_version < SPA_VERSION_FUID) {
1453                         /* can't upgrade */
1454                         (void) printf(gettext("%s: can not be upgraded; "
1455                             "the pool version needs to first be upgraded\nto "
1456                             "version %d\n\n"),
1457                             zfs_get_name(zhp), SPA_VERSION_FUID);
1458                         cb->cb_numfailed++;
1459                         return (0);
1460                 }
1461         }
1462 
1463         /* upgrade */
1464         if (version < cb->cb_version) {
1465                 char verstr[16];
1466                 (void) snprintf(verstr, sizeof (verstr),
1467                     "%llu", cb->cb_version);
1468                 if (cb->cb_lastfs[0] && !same_pool(zhp, cb->cb_lastfs)) {
1469                         /*
1470                          * If they did "zfs upgrade -a", then we could
1471                          * be doing ioctls to different pools.  We need
1472                          * to log this history once to each pool.
1473                          */
1474                         verify(zpool_stage_history(g_zfs, history_str) == 0);
1475                 }
1476                 if (zfs_prop_set(zhp, "version", verstr) == 0)
1477                         cb->cb_numupgraded++;
1478                 else
1479                         cb->cb_numfailed++;
1480                 (void) strcpy(cb->cb_lastfs, zfs_get_name(zhp));
1481         } else if (version > cb->cb_version) {
1482                 /* can't downgrade */
1483                 (void) printf(gettext("%s: can not be downgraded; "
1484                     "it is already at version %u\n"),
1485                     zfs_get_name(zhp), version);
1486                 cb->cb_numfailed++;
1487         } else {
1488                 cb->cb_numsamegraded++;
1489         }
1490         return (0);
1491 }
1492 
1493 /*
1494  * zfs upgrade
1495  * zfs upgrade -v
1496  * zfs upgrade [-r] [-V <version>] <-a | filesystem>
1497  */
1498 static int
1499 zfs_do_upgrade(int argc, char **argv)
1500 {
1501         boolean_t all = B_FALSE;
1502         boolean_t showversions = B_FALSE;
1503         int ret;
1504         upgrade_cbdata_t cb = { 0 };
1505         char c;
1506         int flags = ZFS_ITER_ARGS_CAN_BE_PATHS;
1507 
1508         /* check options */
1509         while ((c = getopt(argc, argv, "rvV:a")) != -1) {
1510                 switch (c) {
1511                 case 'r':
1512                         flags |= ZFS_ITER_RECURSE;
1513                         break;
1514                 case 'v':
1515                         showversions = B_TRUE;
1516                         break;
1517                 case 'V':
1518                         if (zfs_prop_string_to_index(ZFS_PROP_VERSION,
1519                             optarg, &cb.cb_version) != 0) {
1520                                 (void) fprintf(stderr,
1521                                     gettext("invalid version %s\n"), optarg);
1522                                 usage(B_FALSE);
1523                         }
1524                         break;
1525                 case 'a':
1526                         all = B_TRUE;
1527                         break;
1528                 case '?':
1529                 default:
1530                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
1531                             optopt);
1532                         usage(B_FALSE);
1533                 }
1534         }
1535 
1536         argc -= optind;
1537         argv += optind;
1538 
1539         if ((!all && !argc) && ((flags & ZFS_ITER_RECURSE) | cb.cb_version))
1540                 usage(B_FALSE);
1541         if (showversions && (flags & ZFS_ITER_RECURSE || all ||
1542             cb.cb_version || argc))
1543                 usage(B_FALSE);
1544         if ((all || argc) && (showversions))
1545                 usage(B_FALSE);
1546         if (all && argc)
1547                 usage(B_FALSE);
1548 
1549         if (showversions) {
1550                 /* Show info on available versions. */
1551                 (void) printf(gettext("The following filesystem versions are "
1552                     "supported:\n\n"));
1553                 (void) printf(gettext("VER  DESCRIPTION\n"));
1554                 (void) printf("---  -----------------------------------------"
1555                     "---------------\n");
1556                 (void) printf(gettext(" 1   Initial ZFS filesystem version\n"));
1557                 (void) printf(gettext(" 2   Enhanced directory entries\n"));
1558                 (void) printf(gettext(" 3   Case insensitive and File system "
1559                     "unique identifer (FUID)\n"));
1560                 (void) printf(gettext("\nFor more information on a particular "
1561                     "version, including supported releases, see:\n\n"));
1562                 (void) printf("http://www.opensolaris.org/os/community/zfs/"
1563                     "version/zpl/N\n\n");
1564                 (void) printf(gettext("Where 'N' is the version number.\n"));
1565                 ret = 0;
1566         } else if (argc || all) {
1567                 /* Upgrade filesystems */
1568                 if (cb.cb_version == 0)
1569                         cb.cb_version = ZPL_VERSION;
1570                 ret = zfs_for_each(argc, argv, flags, ZFS_TYPE_FILESYSTEM,
1571                     NULL, NULL, upgrade_set_callback, &cb);
1572                 (void) printf(gettext("%llu filesystems upgraded\n"),
1573                     cb.cb_numupgraded);
1574                 if (cb.cb_numsamegraded) {
1575                         (void) printf(gettext("%llu filesystems already at "
1576                             "this version\n"),
1577                             cb.cb_numsamegraded);
1578                 }
1579                 if (cb.cb_numfailed != 0)
1580                         ret = 1;
1581         } else {
1582                 /* List old-version filesytems */
1583                 boolean_t found;
1584                 (void) printf(gettext("This system is currently running "
1585                     "ZFS filesystem version %llu.\n\n"), ZPL_VERSION);
1586 
1587                 flags |= ZFS_ITER_RECURSE;
1588                 ret = zfs_for_each(0, NULL, flags, ZFS_TYPE_FILESYSTEM,
1589                     NULL, NULL, upgrade_list_callback, &cb);
1590 
1591                 found = cb.cb_foundone;
1592                 cb.cb_foundone = B_FALSE;
1593                 cb.cb_newer = B_TRUE;
1594 
1595                 ret = zfs_for_each(0, NULL, flags, ZFS_TYPE_FILESYSTEM,
1596                     NULL, NULL, upgrade_list_callback, &cb);
1597 
1598                 if (!cb.cb_foundone && !found) {
1599                         (void) printf(gettext("All filesystems are "
1600                             "formatted with the current version.\n"));
1601                 }
1602         }
1603 
1604         return (ret);
1605 }
1606 
1607 /*
1608  * list [-rH] [-o property[,property]...] [-t type[,type]...]
1609  *      [-s property [-s property]...] [-S property [-S property]...]
1610  *      <dataset> ...
1611  *
1612  *      -r      Recurse over all children
1613  *      -H      Scripted mode; elide headers and separate columns by tabs
1614  *      -o      Control which fields to display.
1615  *      -t      Control which object types to display.
1616  *      -s      Specify sort columns, descending order.
1617  *      -S      Specify sort columns, ascending order.
1618  *
1619  * When given no arguments, lists all filesystems in the system.
1620  * Otherwise, list the specified datasets, optionally recursing down them if
1621  * '-r' is specified.
1622  */
1623 typedef struct list_cbdata {
1624         boolean_t       cb_first;
1625         boolean_t       cb_scripted;
1626         zprop_list_t    *cb_proplist;
1627 } list_cbdata_t;
1628 
1629 /*
1630  * Given a list of columns to display, output appropriate headers for each one.
1631  */
1632 static void
1633 print_header(zprop_list_t *pl)
1634 {
1635         char headerbuf[ZFS_MAXPROPLEN];
1636         const char *header;
1637         int i;
1638         boolean_t first = B_TRUE;
1639         boolean_t right_justify;
1640 
1641         for (; pl != NULL; pl = pl->pl_next) {
1642                 if (!first) {
1643                         (void) printf("  ");
1644                 } else {
1645                         first = B_FALSE;
1646                 }
1647 
1648                 right_justify = B_FALSE;
1649                 if (pl->pl_prop != ZPROP_INVAL) {
1650                         header = zfs_prop_column_name(pl->pl_prop);
1651                         right_justify = zfs_prop_align_right(pl->pl_prop);
1652                 } else {
1653                         for (i = 0; pl->pl_user_prop[i] != '\0'; i++)
1654                                 headerbuf[i] = toupper(pl->pl_user_prop[i]);
1655                         headerbuf[i] = '\0';
1656                         header = headerbuf;
1657                 }
1658 
1659                 if (pl->pl_next == NULL && !right_justify)
1660                         (void) printf("%s", header);
1661                 else if (right_justify)
1662                         (void) printf("%*s", pl->pl_width, header);
1663                 else
1664                         (void) printf("%-*s", pl->pl_width, header);
1665         }
1666 
1667         (void) printf("\n");
1668 }
1669 
1670 /*
1671  * Given a dataset and a list of fields, print out all the properties according
1672  * to the described layout.
1673  */
1674 static void
1675 print_dataset(zfs_handle_t *zhp, zprop_list_t *pl, boolean_t scripted)
1676 {
1677         boolean_t first = B_TRUE;
1678         char property[ZFS_MAXPROPLEN];
1679         nvlist_t *userprops = zfs_get_user_props(zhp);
1680         nvlist_t *propval;
1681         char *propstr;
1682         boolean_t right_justify;
1683         int width;
1684 
1685         for (; pl != NULL; pl = pl->pl_next) {
1686                 if (!first) {
1687                         if (scripted)
1688                                 (void) printf("\t");
1689                         else
1690                                 (void) printf("  ");
1691                 } else {
1692                         first = B_FALSE;
1693                 }
1694 
1695                 right_justify = B_FALSE;
1696                 if (pl->pl_prop != ZPROP_INVAL) {
1697                         if (zfs_prop_get(zhp, pl->pl_prop, property,
1698                             sizeof (property), NULL, NULL, 0, B_FALSE) != 0)
1699                                 propstr = "-";
1700                         else
1701                                 propstr = property;
1702 
1703                         right_justify = zfs_prop_align_right(pl->pl_prop);
1704                 } else {
1705                         if (nvlist_lookup_nvlist(userprops,
1706                             pl->pl_user_prop, &propval) != 0)
1707                                 propstr = "-";
1708                         else
1709                                 verify(nvlist_lookup_string(propval,
1710                                     ZPROP_VALUE, &propstr) == 0);
1711                 }
1712 
1713                 width = pl->pl_width;
1714 
1715                 /*
1716                  * If this is being called in scripted mode, or if this is the
1717                  * last column and it is left-justified, don't include a width
1718                  * format specifier.
1719                  */
1720                 if (scripted || (pl->pl_next == NULL && !right_justify))
1721                         (void) printf("%s", propstr);
1722                 else if (right_justify)
1723                         (void) printf("%*s", width, propstr);
1724                 else
1725                         (void) printf("%-*s", width, propstr);
1726         }
1727 
1728         (void) printf("\n");
1729 }
1730 
1731 /*
1732  * Generic callback function to list a dataset or snapshot.
1733  */
1734 static int
1735 list_callback(zfs_handle_t *zhp, void *data)
1736 {
1737         list_cbdata_t *cbp = data;
1738 
1739         if (cbp->cb_first) {
1740                 if (!cbp->cb_scripted)
1741                         print_header(cbp->cb_proplist);
1742                 cbp->cb_first = B_FALSE;
1743         }
1744 
1745         print_dataset(zhp, cbp->cb_proplist, cbp->cb_scripted);
1746 
1747         return (0);
1748 }
1749 
1750 static int
1751 zfs_do_list(int argc, char **argv)
1752 {
1753         int c;
1754         boolean_t scripted = B_FALSE;
1755         static char default_fields[] =
1756             "name,used,available,referenced,mountpoint";
1757         int types = ZFS_TYPE_DATASET;
1758         boolean_t types_specified = B_FALSE;
1759         char *fields = NULL;
1760         list_cbdata_t cb = { 0 };
1761         char *value;
1762         int ret;
1763         zfs_sort_column_t *sortcol = NULL;
1764         int flags = ZFS_ITER_PROP_LISTSNAPS | ZFS_ITER_ARGS_CAN_BE_PATHS;
1765 
1766         /* check options */
1767         while ((c = getopt(argc, argv, ":o:rt:Hs:S:")) != -1) {
1768                 switch (c) {
1769                 case 'o':
1770                         fields = optarg;
1771                         break;
1772                 case 'r':
1773                         flags |= ZFS_ITER_RECURSE;
1774                         break;
1775                 case 'H':
1776                         scripted = B_TRUE;
1777                         break;
1778                 case 's':
1779                         if (zfs_add_sort_column(&sortcol, optarg,
1780                             B_FALSE) != 0) {
1781                                 (void) fprintf(stderr,
1782                                     gettext("invalid property '%s'\n"), optarg);
1783                                 usage(B_FALSE);
1784                         }
1785                         break;
1786                 case 'S':
1787                         if (zfs_add_sort_column(&sortcol, optarg,
1788                             B_TRUE) != 0) {
1789                                 (void) fprintf(stderr,
1790                                     gettext("invalid property '%s'\n"), optarg);
1791                                 usage(B_FALSE);
1792                         }
1793                         break;
1794                 case 't':
1795                         types = 0;
1796                         types_specified = B_TRUE;
1797                         flags &= ~ZFS_ITER_PROP_LISTSNAPS;
1798                         while (*optarg != '\0') {
1799                                 static char *type_subopts[] = { "filesystem",
1800                                     "volume", "snapshot", "all", NULL };
1801 
1802                                 switch (getsubopt(&optarg, type_subopts,
1803                                     &value)) {
1804                                 case 0:
1805                                         types |= ZFS_TYPE_FILESYSTEM;
1806                                         break;
1807                                 case 1:
1808                                         types |= ZFS_TYPE_VOLUME;
1809                                         break;
1810                                 case 2:
1811                                         types |= ZFS_TYPE_SNAPSHOT;
1812                                         break;
1813                                 case 3:
1814                                         types = ZFS_TYPE_DATASET;
1815                                         break;
1816 
1817                                 default:
1818                                         (void) fprintf(stderr,
1819                                             gettext("invalid type '%s'\n"),
1820                                             value);
1821                                         usage(B_FALSE);
1822                                 }
1823                         }
1824                         break;
1825                 case ':':
1826                         (void) fprintf(stderr, gettext("missing argument for "
1827                             "'%c' option\n"), optopt);
1828                         usage(B_FALSE);
1829                         break;
1830                 case '?':
1831                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
1832                             optopt);
1833                         usage(B_FALSE);
1834                 }
1835         }
1836 
1837         argc -= optind;
1838         argv += optind;
1839 
1840         if (fields == NULL)
1841                 fields = default_fields;
1842 
1843         /*
1844          * If "-o space" and no types were specified, don't display snapshots.
1845          */
1846         if (strcmp(fields, "space") == 0 && types_specified == B_FALSE)
1847                 types &= ~ZFS_TYPE_SNAPSHOT;
1848 
1849         /*
1850          * If the user specifies '-o all', the zprop_get_list() doesn't
1851          * normally include the name of the dataset.  For 'zfs list', we always
1852          * want this property to be first.
1853          */
1854         if (zprop_get_list(g_zfs, fields, &cb.cb_proplist, ZFS_TYPE_DATASET)
1855             != 0)
1856                 usage(B_FALSE);
1857 
1858         cb.cb_scripted = scripted;
1859         cb.cb_first = B_TRUE;
1860 
1861         ret = zfs_for_each(argc, argv, flags, types, sortcol, &cb.cb_proplist,
1862             list_callback, &cb);
1863 
1864         zprop_free_list(cb.cb_proplist);
1865         zfs_free_sort_columns(sortcol);
1866 
1867         if (ret == 0 && cb.cb_first && !cb.cb_scripted)
1868                 (void) printf(gettext("no datasets available\n"));
1869 
1870         return (ret);
1871 }
1872 
1873 /*
1874  * zfs rename <fs | snap | vol> <fs | snap | vol>
1875  * zfs rename -p <fs | vol> <fs | vol>
1876  * zfs rename -r <snap> <snap>
1877  *
1878  * Renames the given dataset to another of the same type.
1879  *
1880  * The '-p' flag creates all the non-existing ancestors of the target first.
1881  */
1882 /* ARGSUSED */
1883 static int
1884 zfs_do_rename(int argc, char **argv)
1885 {
1886         zfs_handle_t *zhp;
1887         int c;
1888         int ret;
1889         boolean_t recurse = B_FALSE;
1890         boolean_t parents = B_FALSE;
1891 
1892         /* check options */
1893         while ((c = getopt(argc, argv, "pr")) != -1) {
1894                 switch (c) {
1895                 case 'p':
1896                         parents = B_TRUE;
1897                         break;
1898                 case 'r':
1899                         recurse = B_TRUE;
1900                         break;
1901                 case '?':
1902                 default:
1903                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
1904                             optopt);
1905                         usage(B_FALSE);
1906                 }
1907         }
1908 
1909         argc -= optind;
1910         argv += optind;
1911 
1912         /* check number of arguments */
1913         if (argc < 1) {
1914                 (void) fprintf(stderr, gettext("missing source dataset "
1915                     "argument\n"));
1916                 usage(B_FALSE);
1917         }
1918         if (argc < 2) {
1919                 (void) fprintf(stderr, gettext("missing target dataset "
1920                     "argument\n"));
1921                 usage(B_FALSE);
1922         }
1923         if (argc > 2) {
1924                 (void) fprintf(stderr, gettext("too many arguments\n"));
1925                 usage(B_FALSE);
1926         }
1927 
1928         if (recurse && parents) {
1929                 (void) fprintf(stderr, gettext("-p and -r options are mutually "
1930                     "exclusive\n"));
1931                 usage(B_FALSE);
1932         }
1933 
1934         if (recurse && strchr(argv[0], '@') == 0) {
1935                 (void) fprintf(stderr, gettext("source dataset for recursive "
1936                     "rename must be a snapshot\n"));
1937                 usage(B_FALSE);
1938         }
1939 
1940         if ((zhp = zfs_open(g_zfs, argv[0], parents ? ZFS_TYPE_FILESYSTEM |
1941             ZFS_TYPE_VOLUME : ZFS_TYPE_DATASET)) == NULL)
1942                 return (1);
1943 
1944         /* If we were asked and the name looks good, try to create ancestors. */
1945         if (parents && zfs_name_valid(argv[1], zfs_get_type(zhp)) &&
1946             zfs_create_ancestors(g_zfs, argv[1]) != 0) {
1947                 zfs_close(zhp);
1948                 return (1);
1949         }
1950 
1951         ret = (zfs_rename(zhp, argv[1], recurse) != 0);
1952 
1953         zfs_close(zhp);
1954         return (ret);
1955 }
1956 
1957 /*
1958  * zfs promote <fs>
1959  *
1960  * Promotes the given clone fs to be the parent
1961  */
1962 /* ARGSUSED */
1963 static int
1964 zfs_do_promote(int argc, char **argv)
1965 {
1966         zfs_handle_t *zhp;
1967         int ret;
1968 
1969         /* check options */
1970         if (argc > 1 && argv[1][0] == '-') {
1971                 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
1972                     argv[1][1]);
1973                 usage(B_FALSE);
1974         }
1975 
1976         /* check number of arguments */
1977         if (argc < 2) {
1978                 (void) fprintf(stderr, gettext("missing clone filesystem"
1979                     " argument\n"));
1980                 usage(B_FALSE);
1981         }
1982         if (argc > 2) {
1983                 (void) fprintf(stderr, gettext("too many arguments\n"));
1984                 usage(B_FALSE);
1985         }
1986 
1987         zhp = zfs_open(g_zfs, argv[1], ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
1988         if (zhp == NULL)
1989                 return (1);
1990 
1991         ret = (zfs_promote(zhp) != 0);
1992 
1993 
1994         zfs_close(zhp);
1995         return (ret);
1996 }
1997 
1998 /*
1999  * zfs rollback [-rRf] <snapshot>
2000  *
2001  *      -r      Delete any intervening snapshots before doing rollback
2002  *      -R      Delete any snapshots and their clones
2003  *      -f      ignored for backwards compatability
2004  *
2005  * Given a filesystem, rollback to a specific snapshot, discarding any changes
2006  * since then and making it the active dataset.  If more recent snapshots exist,
2007  * the command will complain unless the '-r' flag is given.
2008  */
2009 typedef struct rollback_cbdata {
2010         uint64_t        cb_create;
2011         boolean_t       cb_first;
2012         int             cb_doclones;
2013         char            *cb_target;
2014         int             cb_error;
2015         boolean_t       cb_recurse;
2016         boolean_t       cb_dependent;
2017 } rollback_cbdata_t;
2018 
2019 /*
2020  * Report any snapshots more recent than the one specified.  Used when '-r' is
2021  * not specified.  We reuse this same callback for the snapshot dependents - if
2022  * 'cb_dependent' is set, then this is a dependent and we should report it
2023  * without checking the transaction group.
2024  */
2025 static int
2026 rollback_check(zfs_handle_t *zhp, void *data)
2027 {
2028         rollback_cbdata_t *cbp = data;
2029 
2030         if (cbp->cb_doclones) {
2031                 zfs_close(zhp);
2032                 return (0);
2033         }
2034 
2035         if (!cbp->cb_dependent) {
2036                 if (strcmp(zfs_get_name(zhp), cbp->cb_target) != 0 &&
2037                     zfs_get_type(zhp) == ZFS_TYPE_SNAPSHOT &&
2038                     zfs_prop_get_int(zhp, ZFS_PROP_CREATETXG) >
2039                     cbp->cb_create) {
2040 
2041                         if (cbp->cb_first && !cbp->cb_recurse) {
2042                                 (void) fprintf(stderr, gettext("cannot "
2043                                     "rollback to '%s': more recent snapshots "
2044                                     "exist\n"),
2045                                     cbp->cb_target);
2046                                 (void) fprintf(stderr, gettext("use '-r' to "
2047                                     "force deletion of the following "
2048                                     "snapshots:\n"));
2049                                 cbp->cb_first = 0;
2050                                 cbp->cb_error = 1;
2051                         }
2052 
2053                         if (cbp->cb_recurse) {
2054                                 cbp->cb_dependent = B_TRUE;
2055                                 if (zfs_iter_dependents(zhp, B_TRUE,
2056                                     rollback_check, cbp) != 0) {
2057                                         zfs_close(zhp);
2058                                         return (-1);
2059                                 }
2060                                 cbp->cb_dependent = B_FALSE;
2061                         } else {
2062                                 (void) fprintf(stderr, "%s\n",
2063                                     zfs_get_name(zhp));
2064                         }
2065                 }
2066         } else {
2067                 if (cbp->cb_first && cbp->cb_recurse) {
2068                         (void) fprintf(stderr, gettext("cannot rollback to "
2069                             "'%s': clones of previous snapshots exist\n"),
2070                             cbp->cb_target);
2071                         (void) fprintf(stderr, gettext("use '-R' to "
2072                             "force deletion of the following clones and "
2073                             "dependents:\n"));
2074                         cbp->cb_first = 0;
2075                         cbp->cb_error = 1;
2076                 }
2077 
2078                 (void) fprintf(stderr, "%s\n", zfs_get_name(zhp));
2079         }
2080 
2081         zfs_close(zhp);
2082         return (0);
2083 }
2084 
2085 static int
2086 zfs_do_rollback(int argc, char **argv)
2087 {
2088         int ret;
2089         int c;
2090         boolean_t force = B_FALSE;
2091         rollback_cbdata_t cb = { 0 };
2092         zfs_handle_t *zhp, *snap;
2093         char parentname[ZFS_MAXNAMELEN];
2094         char *delim;
2095 
2096         /* check options */
2097         while ((c = getopt(argc, argv, "rRf")) != -1) {
2098                 switch (c) {
2099                 case 'r':
2100                         cb.cb_recurse = 1;
2101                         break;
2102                 case 'R':
2103                         cb.cb_recurse = 1;
2104                         cb.cb_doclones = 1;
2105                         break;
2106                 case 'f':
2107                         force = B_TRUE;
2108                         break;
2109                 case '?':
2110                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
2111                             optopt);
2112                         usage(B_FALSE);
2113                 }
2114         }
2115 
2116         argc -= optind;
2117         argv += optind;
2118 
2119         /* check number of arguments */
2120         if (argc < 1) {
2121                 (void) fprintf(stderr, gettext("missing dataset argument\n"));
2122                 usage(B_FALSE);
2123         }
2124         if (argc > 1) {
2125                 (void) fprintf(stderr, gettext("too many arguments\n"));
2126                 usage(B_FALSE);
2127         }
2128 
2129         /* open the snapshot */
2130         if ((snap = zfs_open(g_zfs, argv[0], ZFS_TYPE_SNAPSHOT)) == NULL)
2131                 return (1);
2132 
2133         /* open the parent dataset */
2134         (void) strlcpy(parentname, argv[0], sizeof (parentname));
2135         verify((delim = strrchr(parentname, '@')) != NULL);
2136         *delim = '\0';
2137         if ((zhp = zfs_open(g_zfs, parentname, ZFS_TYPE_DATASET)) == NULL) {
2138                 zfs_close(snap);
2139                 return (1);
2140         }
2141 
2142         /*
2143          * Check for more recent snapshots and/or clones based on the presence
2144          * of '-r' and '-R'.
2145          */
2146         cb.cb_target = argv[0];
2147         cb.cb_create = zfs_prop_get_int(snap, ZFS_PROP_CREATETXG);
2148         cb.cb_first = B_TRUE;
2149         cb.cb_error = 0;
2150         if ((ret = zfs_iter_children(zhp, rollback_check, &cb)) != 0)
2151                 goto out;
2152 
2153         if ((ret = cb.cb_error) != 0)
2154                 goto out;
2155 
2156         /*
2157          * Rollback parent to the given snapshot.
2158          */
2159         ret = zfs_rollback(zhp, snap, force);
2160 
2161 out:
2162         zfs_close(snap);
2163         zfs_close(zhp);
2164 
2165         if (ret == 0)
2166                 return (0);
2167         else
2168                 return (1);
2169 }
2170 
2171 /*
2172  * zfs set property=value { fs | snap | vol } ...
2173  *
2174  * Sets the given property for all datasets specified on the command line.
2175  */
2176 typedef struct set_cbdata {
2177         char            *cb_propname;
2178         char            *cb_value;
2179 } set_cbdata_t;
2180 
2181 static int
2182 set_callback(zfs_handle_t *zhp, void *data)
2183 {
2184         set_cbdata_t *cbp = data;
2185 
2186         if (zfs_prop_set(zhp, cbp->cb_propname, cbp->cb_value) != 0) {
2187                 switch (libzfs_errno(g_zfs)) {
2188                 case EZFS_MOUNTFAILED:
2189                         (void) fprintf(stderr, gettext("property may be set "
2190                             "but unable to remount filesystem\n"));
2191                         break;
2192                 case EZFS_SHARENFSFAILED:
2193                         (void) fprintf(stderr, gettext("property may be set "
2194                             "but unable to reshare filesystem\n"));
2195                         break;
2196                 }
2197                 return (1);
2198         }
2199         return (0);
2200 }
2201 
2202 static int
2203 zfs_do_set(int argc, char **argv)
2204 {
2205         set_cbdata_t cb;
2206         int ret;
2207 
2208         /* check for options */
2209         if (argc > 1 && argv[1][0] == '-') {
2210                 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
2211                     argv[1][1]);
2212                 usage(B_FALSE);
2213         }
2214 
2215         /* check number of arguments */
2216         if (argc < 2) {
2217                 (void) fprintf(stderr, gettext("missing property=value "
2218                     "argument\n"));
2219                 usage(B_FALSE);
2220         }
2221         if (argc < 3) {
2222                 (void) fprintf(stderr, gettext("missing dataset name\n"));
2223                 usage(B_FALSE);
2224         }
2225 
2226         /* validate property=value argument */
2227         cb.cb_propname = argv[1];
2228         if (((cb.cb_value = strchr(cb.cb_propname, '=')) == NULL) ||
2229             (cb.cb_value[1] == '\0')) {
2230                 (void) fprintf(stderr, gettext("missing value in "
2231                     "property=value argument\n"));
2232                 usage(B_FALSE);
2233         }
2234 
2235         *cb.cb_value = '\0';
2236         cb.cb_value++;
2237 
2238         if (*cb.cb_propname == '\0') {
2239                 (void) fprintf(stderr,
2240                     gettext("missing property in property=value argument\n"));
2241                 usage(B_FALSE);
2242         }
2243 
2244         ret = zfs_for_each(argc - 2, argv + 2, NULL,
2245             ZFS_TYPE_DATASET, NULL, NULL, set_callback, &cb);
2246 
2247         return (ret);
2248 }
2249 
2250 /*
2251  * zfs snapshot [-r] [-o prop=value] ... <fs@snap>
2252  *
2253  * Creates a snapshot with the given name.  While functionally equivalent to
2254  * 'zfs create', it is a separate command to differentiate intent.
2255  */
2256 static int
2257 zfs_do_snapshot(int argc, char **argv)
2258 {
2259         boolean_t recursive = B_FALSE;
2260         int ret;
2261         char c;
2262         nvlist_t *props;
2263 
2264         if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0) {
2265                 (void) fprintf(stderr, gettext("internal error: "
2266                     "out of memory\n"));
2267                 return (1);
2268         }
2269 
2270         /* check options */
2271         while ((c = getopt(argc, argv, "ro:")) != -1) {
2272                 switch (c) {
2273                 case 'o':
2274                         if (parseprop(props))
2275                                 return (1);
2276                         break;
2277                 case 'r':
2278                         recursive = B_TRUE;
2279                         break;
2280                 case '?':
2281                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
2282                             optopt);
2283                         goto usage;
2284                 }
2285         }
2286 
2287         argc -= optind;
2288         argv += optind;
2289 
2290         /* check number of arguments */
2291         if (argc < 1) {
2292                 (void) fprintf(stderr, gettext("missing snapshot argument\n"));
2293                 goto usage;
2294         }
2295         if (argc > 1) {
2296                 (void) fprintf(stderr, gettext("too many arguments\n"));
2297                 goto usage;
2298         }
2299 
2300         ret = zfs_snapshot(g_zfs, argv[0], recursive, props);
2301         nvlist_free(props);
2302         if (ret && recursive)
2303                 (void) fprintf(stderr, gettext("no snapshots were created\n"));
2304         return (ret != 0);
2305 
2306 usage:
2307         nvlist_free(props);
2308         usage(B_FALSE);
2309         return (-1);
2310 }
2311 
2312 /*
2313  * zfs send [-v] -R [-i|-I <@snap>] <fs@snap>
2314  * zfs send [-v] [-i|-I <@snap>] <fs@snap>
2315  *
2316  * Send a backup stream to stdout.
2317  */
2318 static int
2319 zfs_do_send(int argc, char **argv)
2320 {
2321         char *fromname = NULL;
2322         char *toname = NULL;
2323         char *cp;
2324         zfs_handle_t *zhp;
2325         boolean_t doall = B_FALSE;
2326         boolean_t replicate = B_FALSE;
2327         boolean_t fromorigin = B_FALSE;
2328         boolean_t verbose = B_FALSE;
2329         int c, err;
2330 
2331         /* check options */
2332         while ((c = getopt(argc, argv, ":i:I:Rv")) != -1) {
2333                 switch (c) {
2334                 case 'i':
2335                         if (fromname)
2336                                 usage(B_FALSE);
2337                         fromname = optarg;
2338                         break;
2339                 case 'I':
2340                         if (fromname)
2341                                 usage(B_FALSE);
2342                         fromname = optarg;
2343                         doall = B_TRUE;
2344                         break;
2345                 case 'R':
2346                         replicate = B_TRUE;
2347                         break;
2348                 case 'v':
2349                         verbose = B_TRUE;
2350                         break;
2351                 case ':':
2352                         (void) fprintf(stderr, gettext("missing argument for "
2353                             "'%c' option\n"), optopt);
2354                         usage(B_FALSE);
2355                         break;
2356                 case '?':
2357                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
2358                             optopt);
2359                         usage(B_FALSE);
2360                 }
2361         }
2362 
2363         argc -= optind;
2364         argv += optind;
2365 
2366         /* check number of arguments */
2367         if (argc < 1) {
2368                 (void) fprintf(stderr, gettext("missing snapshot argument\n"));
2369                 usage(B_FALSE);
2370         }
2371         if (argc > 1) {
2372                 (void) fprintf(stderr, gettext("too many arguments\n"));
2373                 usage(B_FALSE);
2374         }
2375 
2376         if (isatty(STDOUT_FILENO)) {
2377                 (void) fprintf(stderr,
2378                     gettext("Error: Stream can not be written to a terminal.\n"
2379                     "You must redirect standard output.\n"));
2380                 return (1);
2381         }
2382 
2383         cp = strchr(argv[0], '@');
2384         if (cp == NULL) {
2385                 (void) fprintf(stderr,
2386                     gettext("argument must be a snapshot\n"));
2387                 usage(B_FALSE);
2388         }
2389         *cp = '\0';
2390         toname = cp + 1;
2391         zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
2392         if (zhp == NULL)
2393                 return (1);
2394 
2395         /*
2396          * If they specified the full path to the snapshot, chop off
2397          * everything except the short name of the snapshot, but special
2398          * case if they specify the origin.
2399          */
2400         if (fromname && (cp = strchr(fromname, '@')) != NULL) {
2401                 char origin[ZFS_MAXNAMELEN];
2402                 zprop_source_t src;
2403 
2404                 (void) zfs_prop_get(zhp, ZFS_PROP_ORIGIN,
2405                     origin, sizeof (origin), &src, NULL, 0, B_FALSE);
2406 
2407                 if (strcmp(origin, fromname) == 0) {
2408                         fromname = NULL;
2409                         fromorigin = B_TRUE;
2410                 } else {
2411                         *cp = '\0';
2412                         if (cp != fromname && strcmp(argv[0], fromname)) {
2413                                 (void) fprintf(stderr,
2414                                     gettext("incremental source must be "
2415                                     "in same filesystem\n"));
2416                                 usage(B_FALSE);
2417                         }
2418                         fromname = cp + 1;
2419                         if (strchr(fromname, '@') || strchr(fromname, '/')) {
2420                                 (void) fprintf(stderr,
2421                                     gettext("invalid incremental source\n"));
2422                                 usage(B_FALSE);
2423                         }
2424                 }
2425         }
2426 
2427         if (replicate && fromname == NULL)
2428                 doall = B_TRUE;
2429 
2430         err = zfs_send(zhp, fromname, toname, replicate, doall, fromorigin,
2431             verbose, STDOUT_FILENO);
2432         zfs_close(zhp);
2433 
2434         return (err != 0);
2435 }
2436 
2437 /*
2438  * zfs receive [-dnvF] <fs@snap>
2439  *
2440  * Restore a backup stream from stdin.
2441  */
2442 static int
2443 zfs_do_receive(int argc, char **argv)
2444 {
2445         int c, err;
2446         recvflags_t flags;
2447 
2448         bzero(&flags, sizeof (recvflags_t));
2449         /* check options */
2450         while ((c = getopt(argc, argv, ":dnuvF")) != -1) {
2451                 switch (c) {
2452                 case 'd':
2453                         flags.isprefix = B_TRUE;
2454                         break;
2455                 case 'n':
2456                         flags.dryrun = B_TRUE;
2457                         break;
2458                 case 'u':
2459                         flags.nomount = B_TRUE;
2460                         break;
2461                 case 'v':
2462                         flags.verbose = B_TRUE;
2463                         break;
2464                 case 'F':
2465                         flags.force = B_TRUE;
2466                         break;
2467                 case ':':
2468                         (void) fprintf(stderr, gettext("missing argument for "
2469                             "'%c' option\n"), optopt);
2470                         usage(B_FALSE);
2471                         break;
2472                 case '?':
2473                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
2474                             optopt);
2475                         usage(B_FALSE);
2476                 }
2477         }
2478 
2479         argc -= optind;
2480         argv += optind;
2481 
2482         /* check number of arguments */
2483         if (argc < 1) {
2484                 (void) fprintf(stderr, gettext("missing snapshot argument\n"));
2485                 usage(B_FALSE);
2486         }
2487         if (argc > 1) {
2488                 (void) fprintf(stderr, gettext("too many arguments\n"));
2489                 usage(B_FALSE);
2490         }
2491 
2492         if (isatty(STDIN_FILENO)) {
2493                 (void) fprintf(stderr,
2494                     gettext("Error: Backup stream can not be read "
2495                     "from a terminal.\n"
2496                     "You must redirect standard input.\n"));
2497                 return (1);
2498         }
2499 
2500         err = zfs_receive(g_zfs, argv[0], flags, STDIN_FILENO, NULL);
2501 
2502         return (err != 0);
2503 }
2504 
2505 typedef struct allow_cb {
2506         int  a_permcnt;
2507         size_t a_treeoffset;
2508 } allow_cb_t;
2509 
2510 static void
2511 zfs_print_perms(avl_tree_t *tree)
2512 {
2513         zfs_perm_node_t *permnode;
2514 
2515         permnode = avl_first(tree);
2516         while (permnode != NULL) {
2517                 (void) printf("%s", permnode->z_pname);
2518                 permnode = AVL_NEXT(tree, permnode);
2519                 if (permnode)
2520                         (void) printf(",");
2521                 else
2522                         (void) printf("\n");
2523         }
2524 }
2525 
2526 /*
2527  * Iterate over user/groups/everyone/... and the call perm_iter
2528  * function to print actual permission when tree has >0 nodes.
2529  */
2530 static void
2531 zfs_iter_perms(avl_tree_t *tree, const char *banner, allow_cb_t *cb)
2532 {
2533         zfs_allow_node_t *item;
2534         avl_tree_t *ptree;
2535 
2536         item = avl_first(tree);
2537         while (item) {
2538                 ptree = (void *)((char *)item + cb->a_treeoffset);
2539                 if (avl_numnodes(ptree)) {
2540                         if (cb->a_permcnt++ == 0)
2541                                 (void) printf("%s\n", banner);
2542                         (void) printf("\t%s", item->z_key);
2543                         /*
2544                          * Avoid an extra space being printed
2545                          * for "everyone" which is keyed with a null
2546                          * string
2547                          */
2548                         if (item->z_key[0] != '\0')
2549                                 (void) printf(" ");
2550                         zfs_print_perms(ptree);
2551                 }
2552                 item = AVL_NEXT(tree, item);
2553         }
2554 }
2555 
2556 #define LINES "-------------------------------------------------------------\n"
2557 static int
2558 zfs_print_allows(char *ds)
2559 {
2560         zfs_allow_t *curperms, *perms;
2561         zfs_handle_t *zhp;
2562         allow_cb_t allowcb = { 0 };
2563         char banner[MAXPATHLEN];
2564 
2565         if (ds[0] == '-')
2566                 usage(B_FALSE);
2567 
2568         if (strrchr(ds, '@')) {
2569                 (void) fprintf(stderr, gettext("Snapshots don't have 'allow'"
2570                     " permissions\n"));
2571                 return (1);
2572         }
2573         if ((zhp = zfs_open(g_zfs, ds, ZFS_TYPE_DATASET)) == NULL)
2574                 return (1);
2575 
2576         if (zfs_perm_get(zhp, &perms)) {
2577                 (void) fprintf(stderr,
2578                     gettext("Failed to retrieve 'allows' on %s\n"), ds);
2579                 zfs_close(zhp);
2580                 return (1);
2581         }
2582 
2583         zfs_close(zhp);
2584 
2585         if (perms != NULL)
2586                 (void) printf("%s", LINES);
2587         for (curperms = perms; curperms; curperms = curperms->z_next) {
2588 
2589                 (void) snprintf(banner, sizeof (banner),
2590                     gettext("Permission sets on (%s)"), curperms->z_setpoint);
2591                 allowcb.a_treeoffset =
2592                     offsetof(zfs_allow_node_t, z_localdescend);
2593                 allowcb.a_permcnt = 0;
2594                 zfs_iter_perms(&curperms->z_sets, banner, &allowcb);
2595 
2596                 (void) snprintf(banner, sizeof (banner),
2597                     gettext("Create time permissions on (%s)"),
2598                     curperms->z_setpoint);
2599                 allowcb.a_treeoffset =
2600                     offsetof(zfs_allow_node_t, z_localdescend);
2601                 allowcb.a_permcnt = 0;
2602                 zfs_iter_perms(&curperms->z_crperms, banner, &allowcb);
2603 
2604 
2605                 (void) snprintf(banner, sizeof (banner),
2606                     gettext("Local permissions on (%s)"), curperms->z_setpoint);
2607                 allowcb.a_treeoffset = offsetof(zfs_allow_node_t, z_local);
2608                 allowcb.a_permcnt = 0;
2609                 zfs_iter_perms(&curperms->z_user, banner, &allowcb);
2610                 zfs_iter_perms(&curperms->z_group, banner, &allowcb);
2611                 zfs_iter_perms(&curperms->z_everyone, banner, &allowcb);
2612 
2613                 (void) snprintf(banner, sizeof (banner),
2614                     gettext("Descendent permissions on (%s)"),
2615                     curperms->z_setpoint);
2616                 allowcb.a_treeoffset = offsetof(zfs_allow_node_t, z_descend);
2617                 allowcb.a_permcnt = 0;
2618                 zfs_iter_perms(&curperms->z_user, banner, &allowcb);
2619                 zfs_iter_perms(&curperms->z_group, banner, &allowcb);
2620                 zfs_iter_perms(&curperms->z_everyone, banner, &allowcb);
2621 
2622                 (void) snprintf(banner, sizeof (banner),
2623                     gettext("Local+Descendent permissions on (%s)"),
2624                     curperms->z_setpoint);
2625                 allowcb.a_treeoffset =
2626                     offsetof(zfs_allow_node_t, z_localdescend);
2627                 allowcb.a_permcnt = 0;
2628                 zfs_iter_perms(&curperms->z_user, banner, &allowcb);
2629                 zfs_iter_perms(&curperms->z_group, banner, &allowcb);
2630                 zfs_iter_perms(&curperms->z_everyone, banner, &allowcb);
2631 
2632                 (void) printf("%s", LINES);
2633         }
2634         zfs_free_allows(perms);
2635         return (0);
2636 }
2637 
2638 #define ALLOWOPTIONS "ldcsu:g:e"
2639 #define UNALLOWOPTIONS "ldcsu:g:er"
2640 
2641 /*
2642  * Validate options, and build necessary datastructure to display/remove/add
2643  * permissions.
2644  * Returns 0 - If permissions should be added/removed
2645  * Returns 1 - If permissions should be displayed.
2646  * Returns -1 - on failure
2647  */
2648 int
2649 parse_allow_args(int *argc, char **argv[], boolean_t unallow,
2650     char **ds, int *recurse, nvlist_t **zperms)
2651 {
2652         int c;
2653         char *options = unallow ? UNALLOWOPTIONS : ALLOWOPTIONS;
2654         zfs_deleg_inherit_t deleg_type = ZFS_DELEG_NONE;
2655         zfs_deleg_who_type_t who_type = ZFS_DELEG_WHO_UNKNOWN;
2656         char *who = NULL;
2657         char *perms = NULL;
2658         zfs_handle_t *zhp;
2659 
2660         while ((c = getopt(*argc, *argv, options)) != -1) {
2661                 switch (c) {
2662                 case 'l':
2663                         if (who_type == ZFS_DELEG_CREATE ||
2664                             who_type == ZFS_DELEG_NAMED_SET)
2665                                 usage(B_FALSE);
2666 
2667                         deleg_type |= ZFS_DELEG_PERM_LOCAL;
2668                         break;
2669                 case 'd':
2670                         if (who_type == ZFS_DELEG_CREATE ||
2671                             who_type == ZFS_DELEG_NAMED_SET)
2672                                 usage(B_FALSE);
2673 
2674                         deleg_type |= ZFS_DELEG_PERM_DESCENDENT;
2675                         break;
2676                 case 'r':
2677                         *recurse = B_TRUE;
2678                         break;
2679                 case 'c':
2680                         if (who_type != ZFS_DELEG_WHO_UNKNOWN)
2681                                 usage(B_FALSE);
2682                         if (deleg_type)
2683                                 usage(B_FALSE);
2684                         who_type = ZFS_DELEG_CREATE;
2685                         break;
2686                 case 's':
2687                         if (who_type != ZFS_DELEG_WHO_UNKNOWN)
2688                                 usage(B_FALSE);
2689                         if (deleg_type)
2690                                 usage(B_FALSE);
2691                         who_type = ZFS_DELEG_NAMED_SET;
2692                         break;
2693                 case 'u':
2694                         if (who_type != ZFS_DELEG_WHO_UNKNOWN)
2695                                 usage(B_FALSE);
2696                         who_type = ZFS_DELEG_USER;
2697                         who = optarg;
2698                         break;
2699                 case 'g':
2700                         if (who_type != ZFS_DELEG_WHO_UNKNOWN)
2701                                 usage(B_FALSE);
2702                         who_type = ZFS_DELEG_GROUP;
2703                         who = optarg;
2704                         break;
2705                 case 'e':
2706                         if (who_type != ZFS_DELEG_WHO_UNKNOWN)
2707                                 usage(B_FALSE);
2708                         who_type = ZFS_DELEG_EVERYONE;
2709                         break;
2710                 default:
2711                         usage(B_FALSE);
2712                         break;
2713                 }
2714         }
2715 
2716         if (deleg_type == 0)
2717                 deleg_type = ZFS_DELEG_PERM_LOCALDESCENDENT;
2718 
2719         *argc -= optind;
2720         *argv += optind;
2721 
2722         if (unallow == B_FALSE && *argc == 1) {
2723                 /*
2724                  * Only print permissions if no options were processed
2725                  */
2726                 if (optind == 1)
2727                         return (1);
2728                 else
2729                         usage(B_FALSE);
2730         }
2731 
2732         /*
2733          * initialize variables for zfs_build_perms based on number
2734          * of arguments.
2735          * 3 arguments ==>   zfs [un]allow joe perm,perm,perm <dataset> or
2736          *                      zfs [un]allow -s @set1 perm,perm <dataset>
2737          * 2 arguments ==>   zfs [un]allow -c perm,perm <dataset> or
2738          *                      zfs [un]allow -u|-g <name> perm <dataset> or
2739          *                      zfs [un]allow -e perm,perm <dataset>
2740          *                      zfs unallow joe <dataset>
2741          *                      zfs unallow -s @set1 <dataset>
2742          * 1 argument  ==>   zfs [un]allow -e <dataset> or
2743          *                      zfs [un]allow -c <dataset>
2744          */
2745 
2746         switch (*argc) {
2747         case 3:
2748                 perms = (*argv)[1];
2749                 who = (*argv)[0];
2750                 *ds = (*argv)[2];
2751 
2752                 /*
2753                  * advance argc/argv for do_allow cases.
2754                  * for do_allow case make sure who have a know who type
2755                  * and its not a permission set.
2756                  */
2757                 if (unallow == B_TRUE) {
2758                         *argc -= 2;
2759                         *argv += 2;
2760                 } else if (who_type != ZFS_DELEG_WHO_UNKNOWN &&
2761                     who_type != ZFS_DELEG_NAMED_SET)
2762                         usage(B_FALSE);
2763                 break;
2764 
2765         case 2:
2766                 if (unallow == B_TRUE && (who_type == ZFS_DELEG_EVERYONE ||
2767                     who_type == ZFS_DELEG_CREATE || who != NULL)) {
2768                         perms = (*argv)[0];
2769                         *ds = (*argv)[1];
2770                 } else {
2771                         if (unallow == B_FALSE &&
2772                             (who_type == ZFS_DELEG_WHO_UNKNOWN ||
2773                             who_type == ZFS_DELEG_NAMED_SET))
2774                                 usage(B_FALSE);
2775                         else if (who_type == ZFS_DELEG_WHO_UNKNOWN ||
2776                             who_type == ZFS_DELEG_NAMED_SET)
2777                                 who = (*argv)[0];
2778                         else if (who_type != ZFS_DELEG_NAMED_SET)
2779                                 perms = (*argv)[0];
2780                         *ds = (*argv)[1];
2781                 }
2782                 if (unallow == B_TRUE) {
2783                         (*argc)--;
2784                         (*argv)++;
2785                 }
2786                 break;
2787 
2788         case 1:
2789                 if (unallow == B_FALSE)
2790                         usage(B_FALSE);
2791                 if (who == NULL && who_type != ZFS_DELEG_CREATE &&
2792                     who_type != ZFS_DELEG_EVERYONE)
2793                         usage(B_FALSE);
2794                 *ds = (*argv)[0];
2795                 break;
2796 
2797         default:
2798                 usage(B_FALSE);
2799         }
2800 
2801         if (strrchr(*ds, '@')) {
2802                 (void) fprintf(stderr,
2803                     gettext("Can't set or remove 'allow' permissions "
2804                     "on snapshots.\n"));
2805                         return (-1);
2806         }
2807 
2808         if ((zhp = zfs_open(g_zfs, *ds, ZFS_TYPE_DATASET)) == NULL)
2809                 return (-1);
2810 
2811         if ((zfs_build_perms(zhp, who, perms,
2812             who_type, deleg_type, zperms)) != 0) {
2813                 zfs_close(zhp);
2814                 return (-1);
2815         }
2816         zfs_close(zhp);
2817         return (0);
2818 }
2819 
2820 static int
2821 zfs_do_allow(int argc, char **argv)
2822 {
2823         char *ds;
2824         nvlist_t *zperms = NULL;
2825         zfs_handle_t *zhp;
2826         int unused;
2827         int ret;
2828 
2829         if ((ret = parse_allow_args(&argc, &argv, B_FALSE, &ds,
2830             &unused, &zperms)) == -1)
2831                 return (1);
2832 
2833         if (ret == 1)
2834                 return (zfs_print_allows(argv[0]));
2835 
2836         if ((zhp = zfs_open(g_zfs, ds, ZFS_TYPE_DATASET)) == NULL)
2837                 return (1);
2838 
2839         if (zfs_perm_set(zhp, zperms)) {
2840                 zfs_close(zhp);
2841                 nvlist_free(zperms);
2842                 return (1);
2843         }
2844         nvlist_free(zperms);
2845         zfs_close(zhp);
2846 
2847         return (0);
2848 }
2849 
2850 static int
2851 unallow_callback(zfs_handle_t *zhp, void *data)
2852 {
2853         nvlist_t *nvp = (nvlist_t *)data;
2854         int error;
2855 
2856         error = zfs_perm_remove(zhp, nvp);
2857         if (error) {
2858                 (void) fprintf(stderr, gettext("Failed to remove permissions "
2859                     "on %s\n"), zfs_get_name(zhp));
2860         }
2861         return (error);
2862 }
2863 
2864 static int
2865 zfs_do_unallow(int argc, char **argv)
2866 {
2867         int recurse = B_FALSE;
2868         char *ds;
2869         int error;
2870         nvlist_t *zperms = NULL;
2871         int flags = 0;
2872 
2873         if (parse_allow_args(&argc, &argv, B_TRUE,
2874             &ds, &recurse, &zperms) == -1)
2875                 return (1);
2876 
2877         if (recurse)
2878                 flags |= ZFS_ITER_RECURSE;
2879         error = zfs_for_each(argc, argv, flags,
2880             ZFS_TYPE_FILESYSTEM|ZFS_TYPE_VOLUME, NULL,
2881             NULL, unallow_callback, (void *)zperms);
2882 
2883         if (zperms)
2884                 nvlist_free(zperms);
2885 
2886         return (error);
2887 }
2888 
2889 typedef struct get_all_cbdata {
2890         zfs_handle_t    **cb_handles;
2891         size_t          cb_alloc;
2892         size_t          cb_used;
2893         uint_t          cb_types;
2894         boolean_t       cb_verbose;
2895 } get_all_cbdata_t;
2896 
2897 #define CHECK_SPINNER 30
2898 #define SPINNER_TIME 3          /* seconds */
2899 #define MOUNT_TIME 5            /* seconds */
2900 
2901 static int
2902 get_one_dataset(zfs_handle_t *zhp, void *data)
2903 {
2904         static char spin[] = { '-', '\\', '|', '/' };
2905         static int spinval = 0;
2906         static int spincheck = 0;
2907         static time_t last_spin_time = (time_t)0;
2908         get_all_cbdata_t *cbp = data;
2909         zfs_type_t type = zfs_get_type(zhp);
2910 
2911         if (cbp->cb_verbose) {
2912                 if (--spincheck < 0) {
2913                         time_t now = time(NULL);
2914                         if (last_spin_time + SPINNER_TIME < now) {
2915                                 (void) printf("\b%c", spin[spinval++ % 4]);
2916                                 (void) fflush(stdout);
2917                                 last_spin_time = now;
2918                         }
2919                         spincheck = CHECK_SPINNER;
2920                 }
2921         }
2922 
2923         /*
2924          * Interate over any nested datasets.
2925          */
2926         if (type == ZFS_TYPE_FILESYSTEM &&
2927             zfs_iter_filesystems(zhp, get_one_dataset, data) != 0) {
2928                 zfs_close(zhp);
2929                 return (1);
2930         }
2931 
2932         /*
2933          * Skip any datasets whose type does not match.
2934          */
2935         if ((type & cbp->cb_types) == 0) {
2936                 zfs_close(zhp);
2937                 return (0);
2938         }
2939 
2940         if (cbp->cb_alloc == cbp->cb_used) {
2941                 zfs_handle_t **handles;
2942 
2943                 if (cbp->cb_alloc == 0)
2944                         cbp->cb_alloc = 64;
2945                 else
2946                         cbp->cb_alloc *= 2;
2947 
2948                 handles = safe_malloc(cbp->cb_alloc * sizeof (void *));
2949 
2950                 if (cbp->cb_handles) {
2951                         bcopy(cbp->cb_handles, handles,
2952                             cbp->cb_used * sizeof (void *));
2953                         free(cbp->cb_handles);
2954                 }
2955 
2956                 cbp->cb_handles = handles;
2957         }
2958 
2959         cbp->cb_handles[cbp->cb_used++] = zhp;
2960 
2961         return (0);
2962 }
2963 
2964 static void
2965 get_all_datasets(uint_t types, zfs_handle_t ***dslist, size_t *count,
2966     boolean_t verbose)
2967 {
2968         get_all_cbdata_t cb = { 0 };
2969         cb.cb_types = types;
2970         cb.cb_verbose = verbose;
2971 
2972         if (verbose) {
2973                 (void) printf("%s: *", gettext("Reading ZFS config"));
2974                 (void) fflush(stdout);
2975         }
2976 
2977         (void) zfs_iter_root(g_zfs, get_one_dataset, &cb);
2978 
2979         *dslist = cb.cb_handles;
2980         *count = cb.cb_used;
2981 
2982         if (verbose) {
2983                 (void) printf("\b%s\n", gettext("done."));
2984         }
2985 }
2986 
2987 static int
2988 dataset_cmp(const void *a, const void *b)
2989 {
2990         zfs_handle_t **za = (zfs_handle_t **)a;
2991         zfs_handle_t **zb = (zfs_handle_t **)b;
2992         char mounta[MAXPATHLEN];
2993         char mountb[MAXPATHLEN];
2994         boolean_t gota, gotb;
2995 
2996         if ((gota = (zfs_get_type(*za) == ZFS_TYPE_FILESYSTEM)) != 0)
2997                 verify(zfs_prop_get(*za, ZFS_PROP_MOUNTPOINT, mounta,
2998                     sizeof (mounta), NULL, NULL, 0, B_FALSE) == 0);
2999         if ((gotb = (zfs_get_type(*zb) == ZFS_TYPE_FILESYSTEM)) != 0)
3000                 verify(zfs_prop_get(*zb, ZFS_PROP_MOUNTPOINT, mountb,
3001                     sizeof (mountb), NULL, NULL, 0, B_FALSE) == 0);
3002 
3003         if (gota && gotb)
3004                 return (strcmp(mounta, mountb));
3005 
3006         if (gota)
3007                 return (-1);
3008         if (gotb)
3009                 return (1);
3010 
3011         return (strcmp(zfs_get_name(a), zfs_get_name(b)));
3012 }
3013 
3014 /*
3015  * Generic callback for sharing or mounting filesystems.  Because the code is so
3016  * similar, we have a common function with an extra parameter to determine which
3017  * mode we are using.
3018  */
3019 #define OP_SHARE        0x1
3020 #define OP_MOUNT        0x2
3021 
3022 /*
3023  * Share or mount a dataset.
3024  */
3025 static int
3026 share_mount_one(zfs_handle_t *zhp, int op, int flags, char *protocol,
3027     boolean_t explicit, const char *options)
3028 {
3029         char mountpoint[ZFS_MAXPROPLEN];
3030         char shareopts[ZFS_MAXPROPLEN];
3031         char smbshareopts[ZFS_MAXPROPLEN];
3032         const char *cmdname = op == OP_SHARE ? "share" : "mount";
3033         struct mnttab mnt;
3034         uint64_t zoned, canmount;
3035         zfs_type_t type = zfs_get_type(zhp);
3036         boolean_t shared_nfs, shared_smb;
3037 
3038         assert(type & (ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME));
3039 
3040         if (type == ZFS_TYPE_FILESYSTEM) {
3041                 /*
3042                  * Check to make sure we can mount/share this dataset.  If we
3043                  * are in the global zone and the filesystem is exported to a
3044                  * local zone, or if we are in a local zone and the
3045                  * filesystem is not exported, then it is an error.
3046                  */
3047                 zoned = zfs_prop_get_int(zhp, ZFS_PROP_ZONED);
3048 
3049                 if (zoned && getzoneid() == GLOBAL_ZONEID) {
3050                         if (!explicit)
3051                                 return (0);
3052 
3053                         (void) fprintf(stderr, gettext("cannot %s '%s': "
3054                             "dataset is exported to a local zone\n"), cmdname,
3055                             zfs_get_name(zhp));
3056                         return (1);
3057 
3058                 } else if (!zoned && getzoneid() != GLOBAL_ZONEID) {
3059                         if (!explicit)
3060                                 return (0);
3061 
3062                         (void) fprintf(stderr, gettext("cannot %s '%s': "
3063                             "permission denied\n"), cmdname,
3064                             zfs_get_name(zhp));
3065                         return (1);
3066                 }
3067 
3068                 /*
3069                  * Ignore any filesystems which don't apply to us. This
3070                  * includes those with a legacy mountpoint, or those with
3071                  * legacy share options.  We also have to ignore those
3072                  * that are encrypted that don't currently have their
3073                  * key available.
3074                  */
3075                 verify(zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT, mountpoint,
3076                     sizeof (mountpoint), NULL, NULL, 0, B_FALSE) == 0);
3077                 verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS, shareopts,
3078                     sizeof (shareopts), NULL, NULL, 0, B_FALSE) == 0);
3079                 verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB, smbshareopts,
3080                     sizeof (smbshareopts), NULL, NULL, 0, B_FALSE) == 0);
3081 
3082                 if (op == OP_SHARE && strcmp(shareopts, "off") == 0 &&
3083                     strcmp(smbshareopts, "off") == 0) {
3084                         if (!explicit)
3085                                 return (0);
3086 
3087                         (void) fprintf(stderr, gettext("cannot share '%s': "
3088                             "legacy share\n"), zfs_get_name(zhp));
3089                         (void) fprintf(stderr, gettext("use share(1M) to "
3090                             "share this filesystem, or set "
3091                             "sharenfs property on\n"));
3092                         return (1);
3093                 }
3094 
3095                 /*
3096                  * We cannot share or mount legacy filesystems. If the
3097                  * shareopts is non-legacy but the mountpoint is legacy, we
3098                  * treat it as a legacy share.
3099                  */
3100                 if (strcmp(mountpoint, "legacy") == 0) {
3101                         if (!explicit)
3102                                 return (0);
3103 
3104                         (void) fprintf(stderr, gettext("cannot %s '%s': "
3105                             "legacy mountpoint\n"), cmdname, zfs_get_name(zhp));
3106                         (void) fprintf(stderr, gettext("use %s(1M) to "
3107                             "%s this filesystem\n"), cmdname, cmdname);
3108                         return (1);
3109                 }
3110 
3111                 if (strcmp(mountpoint, "none") == 0) {
3112                         if (!explicit)
3113                                 return (0);
3114 
3115                         (void) fprintf(stderr, gettext("cannot %s '%s': no "
3116                             "mountpoint set\n"), cmdname, zfs_get_name(zhp));
3117                         return (1);
3118                 }
3119 
3120                 /*
3121                  * canmount     explicit        outcome
3122                  * on           no              pass through
3123                  * on           yes             pass through
3124                  * off          no              return 0
3125                  * off          yes             display error, return 1
3126                  * noauto       no              return 0
3127                  * noauto       yes             pass through
3128                  */
3129                 canmount = zfs_prop_get_int(zhp, ZFS_PROP_CANMOUNT);
3130                 if (canmount == ZFS_CANMOUNT_OFF) {
3131                         if (!explicit)
3132                                 return (0);
3133 
3134                         (void) fprintf(stderr, gettext("cannot %s '%s': "
3135                             "'canmount' property is set to 'off'\n"), cmdname,
3136                             zfs_get_name(zhp));
3137                         return (1);
3138                 } else if (canmount == ZFS_CANMOUNT_NOAUTO && !explicit) {
3139                         return (0);
3140                 }
3141 
3142 
3143                 /*
3144                  * Only need to check for ZFS_CRYPT_KEY_UNAVAILABLE since
3145                  * datasets that aren't encrypted have a keystatus of
3146                  * ZFS_CRYPT_KEY_UNDEFINED.
3147                  */
3148                 if (zfs_mount_crypto_check(zhp) != 0) {
3149                         if (!explicit)
3150                                 return (0);
3151 
3152                         (void) fprintf(stderr, gettext("cannot %s '%s': "
3153                             "encryption key unavailable\n"), cmdname,
3154                             zfs_get_name(zhp));
3155                         return (1);
3156                 }
3157 
3158                 /*
3159                  * At this point, we have verified that the mountpoint and/or
3160                  * shareopts are appropriate for auto management. If the
3161                  * filesystem is already mounted or shared, return (failing
3162                  * for explicit requests); otherwise mount or share the
3163                  * filesystem.
3164                  */
3165                 switch (op) {
3166                 case OP_SHARE:
3167 
3168                         shared_nfs = zfs_is_shared_nfs(zhp, NULL);
3169                         shared_smb = zfs_is_shared_smb(zhp, NULL);
3170 
3171                         if (shared_nfs && shared_smb ||
3172                             (shared_nfs && strcmp(shareopts, "on") == 0 &&
3173                             strcmp(smbshareopts, "off") == 0) ||
3174                             (shared_smb && strcmp(smbshareopts, "on") == 0 &&
3175                             strcmp(shareopts, "off") == 0)) {
3176                                 if (!explicit)
3177                                         return (0);
3178 
3179                                 (void) fprintf(stderr, gettext("cannot share "
3180                                     "'%s': filesystem already shared\n"),
3181                                     zfs_get_name(zhp));
3182                                 return (1);
3183                         }
3184 
3185                         if (!zfs_is_mounted(zhp, NULL) &&
3186                             zfs_mount(zhp, NULL, 0) != 0)
3187                                 return (1);
3188 
3189                         if (protocol == NULL) {
3190                                 if (zfs_shareall(zhp) != 0)
3191                                         return (1);
3192                         } else if (strcmp(protocol, "nfs") == 0) {
3193                                 if (zfs_share_nfs(zhp))
3194                                         return (1);
3195                         } else if (strcmp(protocol, "smb") == 0) {
3196                                 if (zfs_share_smb(zhp))
3197                                         return (1);
3198                         } else {
3199                                 (void) fprintf(stderr, gettext("cannot share "
3200                                     "'%s': invalid share type '%s' "
3201                                     "specified\n"),
3202                                     zfs_get_name(zhp), protocol);
3203                                 return (1);
3204                         }
3205 
3206                         break;
3207 
3208                 case OP_MOUNT:
3209                         if (options == NULL)
3210                                 mnt.mnt_mntopts = "";
3211                         else
3212                                 mnt.mnt_mntopts = (char *)options;
3213 
3214                         if (!hasmntopt(&mnt, MNTOPT_REMOUNT) &&
3215                             zfs_is_mounted(zhp, NULL)) {
3216                                 if (!explicit)
3217                                         return (0);
3218 
3219                                 (void) fprintf(stderr, gettext("cannot mount "
3220                                     "'%s': filesystem already mounted\n"),
3221                                     zfs_get_name(zhp));
3222                                 return (1);
3223                         }
3224 
3225                         if (zfs_mount(zhp, options, flags) != 0)
3226                                 return (1);
3227                         break;
3228                 }
3229         } else {
3230                 assert(op == OP_SHARE);
3231 
3232                 /*
3233                  * Ignore any volumes that aren't shared.
3234                  */
3235                 verify(zfs_prop_get(zhp, ZFS_PROP_SHAREISCSI, shareopts,
3236                     sizeof (shareopts), NULL, NULL, 0, B_FALSE) == 0);
3237 
3238                 if (strcmp(shareopts, "off") == 0) {
3239                         if (!explicit)
3240                                 return (0);
3241 
3242                         (void) fprintf(stderr, gettext("cannot share '%s': "
3243                             "'shareiscsi' property not set\n"),
3244                             zfs_get_name(zhp));
3245                         (void) fprintf(stderr, gettext("set 'shareiscsi' "
3246                             "property or use iscsitadm(1M) to share this "
3247                             "volume\n"));
3248                         return (1);
3249                 }
3250 
3251                 if (zfs_is_shared_iscsi(zhp)) {
3252                         if (!explicit)
3253                                 return (0);
3254 
3255                         (void) fprintf(stderr, gettext("cannot share "
3256                             "'%s': volume already shared\n"),
3257                             zfs_get_name(zhp));
3258                         return (1);
3259                 }
3260 
3261                 if (zfs_share_iscsi(zhp) != 0)
3262                         return (1);
3263         }
3264 
3265         return (0);
3266 }
3267 
3268 /*
3269  * Reports progress in the form "(current/total)".  Not thread-safe.
3270  */
3271 static void
3272 report_mount_progress(int current, int total)
3273 {
3274         static int len;
3275         static char *reverse = "\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b"
3276             "\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b";
3277         static time_t last_progress_time;
3278         time_t now = time(NULL);
3279 
3280         /* report 1..n instead of 0..n-1 */
3281         ++current;
3282 
3283         /* display header if we're here for the first time */
3284         if (current == 1) {
3285                 (void) printf(gettext("Mounting ZFS filesystems: "));
3286                 len = 0;
3287         } else if (current != total && last_progress_time + MOUNT_TIME >= now) {
3288                 /* too soon to report again */
3289                 return;
3290         }
3291 
3292         last_progress_time = now;
3293 
3294         /* back up to prepare for overwriting */
3295         if (len)
3296                 (void) printf("%*.*s", len, len, reverse);
3297 
3298         /* We put a newline at the end if this is the last one.  */
3299         len = printf("(%d/%d)%s", current, total, current == total ? "\n" : "");
3300         (void) fflush(stdout);
3301 }
3302 
3303 static void
3304 append_options(char *mntopts, char *newopts)
3305 {
3306         int len = strlen(mntopts);
3307 
3308         /* original length plus new string to append plus 1 for the comma */
3309         if (len + 1 + strlen(newopts) >= MNT_LINE_MAX) {
3310                 (void) fprintf(stderr, gettext("the opts argument for "
3311                     "'%c' option is too long (more than %d chars)\n"),
3312                     "-o", MNT_LINE_MAX);
3313                 usage(B_FALSE);
3314         }
3315 
3316         if (*mntopts)
3317                 mntopts[len++] = ',';
3318 
3319         (void) strcpy(&mntopts[len], newopts);
3320 }
3321 
3322 static int
3323 share_mount(int op, int argc, char **argv)
3324 {
3325         int do_all = 0;
3326         boolean_t verbose = B_FALSE;
3327         int c, ret = 0;
3328         char *options = NULL;
3329         int types, flags = 0;
3330 
3331         /* check options */
3332         while ((c = getopt(argc, argv, op == OP_MOUNT ? ":avo:O" : "a"))
3333             != -1) {
3334                 switch (c) {
3335                 case 'a':
3336                         do_all = 1;
3337                         break;
3338                 case 'v':
3339                         verbose = B_TRUE;
3340                         break;
3341                 case 'o':
3342                         if (*optarg == '\0') {
3343                                 (void) fprintf(stderr, gettext("empty mount "
3344                                     "options (-o) specified\n"));
3345                                 usage(B_FALSE);
3346                         }
3347 
3348                         if (options == NULL)
3349                                 options = safe_malloc(MNT_LINE_MAX + 1);
3350 
3351                         /* option validation is done later */
3352                         append_options(options, optarg);
3353                         break;
3354 
3355                 case 'O':
3356                         flags |= MS_OVERLAY;
3357                         break;
3358                 case ':':
3359                         (void) fprintf(stderr, gettext("missing argument for "
3360                             "'%c' option\n"), optopt);
3361                         usage(B_FALSE);
3362                         break;
3363                 case '?':
3364                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3365                             optopt);
3366                         usage(B_FALSE);
3367                 }
3368         }
3369 
3370         argc -= optind;
3371         argv += optind;
3372 
3373         /* check number of arguments */
3374         if (do_all) {
3375                 zfs_handle_t **dslist = NULL;
3376                 size_t i, count = 0;
3377                 char *protocol = NULL;
3378                 char bypass[ZPOOL_MAXPROPLEN] = { 0 };
3379 
3380 
3381                 if (op == OP_MOUNT) {
3382                         types = ZFS_TYPE_FILESYSTEM;
3383                 } else if (argc > 0) {
3384                         if (strcmp(argv[0], "nfs") == 0 ||
3385                             strcmp(argv[0], "smb") == 0) {
3386                                 types = ZFS_TYPE_FILESYSTEM;
3387                         } else if (strcmp(argv[0], "iscsi") == 0) {
3388                                 types = ZFS_TYPE_VOLUME;
3389                         } else {
3390                                 (void) fprintf(stderr, gettext("share type "
3391                                     "must be 'nfs', 'smb' or 'iscsi'\n"));
3392                                 usage(B_FALSE);
3393                         }
3394                         protocol = argv[0];
3395                         argc--;
3396                         argv++;
3397                 } else {
3398                         types = ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME;
3399                 }
3400 
3401                 if (argc != 0) {
3402                         (void) fprintf(stderr, gettext("too many arguments\n"));
3403                         usage(B_FALSE);
3404                 }
3405 
3406                 get_all_datasets(types, &dslist, &count, verbose);
3407 
3408                 if (count == 0)
3409                         return (0);
3410 
3411                 qsort(dslist, count, sizeof (void *), dataset_cmp);
3412 
3413                 for (i = 0; i < count; i++) {
3414 
3415                         if (verbose)
3416                                 report_mount_progress(i, count);
3417 
3418                         /*
3419                          * If bypass has a dataset value, then we need to skip
3420                          * any datasets that are underneath it.
3421                          */
3422                         if (bypass[0] != NULL) {
3423                                 int len = strlen(bypass);
3424                                 char *ds_name = (char *)zfs_get_name(dslist[i]);
3425 
3426                                 if (strncmp(bypass, ds_name, len) == 0 &&
3427                                     (strlen(ds_name) > len) &&
3428                                     ds_name[len] == '/') {
3429                                         zfs_close(dslist[i]);
3430                                         continue;
3431                                 } else
3432                                         bypass[0] = '\0';
3433                         }
3434 
3435                         /*
3436                          * Check if the dataset has a key before loading, if
3437                          * no, then store it in 'bypass'.
3438                          */
3439                         if (zfs_mount_crypto_check(dslist[i])) {
3440                                 (void) strlcpy(bypass, zfs_get_name(dslist[i]),
3441                                     ZPOOL_MAXPROPLEN);
3442                         } else {
3443                                 if (share_mount_one(dslist[i], op, flags,
3444                                     protocol, B_FALSE, options) != 0) {
3445                                         ret = 1;
3446                                 }
3447                         }
3448 
3449                         zfs_close(dslist[i]);
3450                 }
3451 
3452                 free(dslist);
3453         } else if (argc == 0) {
3454                 struct mnttab entry;
3455 
3456                 if ((op == OP_SHARE) || (options != NULL)) {
3457                         (void) fprintf(stderr, gettext("missing filesystem "
3458                             "argument (specify -a for all)\n"));
3459                         usage(B_FALSE);
3460                 }
3461 
3462                 /*
3463                  * When mount is given no arguments, go through /etc/mnttab and
3464                  * display any active ZFS mounts.  We hide any snapshots, since
3465                  * they are controlled automatically.
3466                  */
3467                 rewind(mnttab_file);
3468                 while (getmntent(mnttab_file, &entry) == 0) {
3469                         if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0 ||
3470                             strchr(entry.mnt_special, '@') != NULL)
3471                                 continue;
3472 
3473                         (void) printf("%-30s  %s\n", entry.mnt_special,
3474                             entry.mnt_mountp);
3475                 }
3476 
3477         } else {
3478                 zfs_handle_t *zhp;
3479 
3480                 types = ZFS_TYPE_FILESYSTEM;
3481                 if (op == OP_SHARE)
3482                         types |= ZFS_TYPE_VOLUME;
3483 
3484                 if (argc > 1) {
3485                         (void) fprintf(stderr,
3486                             gettext("too many arguments\n"));
3487                         usage(B_FALSE);
3488                 }
3489 
3490                 if ((zhp = zfs_open(g_zfs, argv[0], types)) == NULL) {
3491                         ret = 1;
3492                 } else {
3493                         ret = share_mount_one(zhp, op, flags, NULL, B_TRUE,
3494                             options);
3495                         zfs_close(zhp);
3496                 }
3497         }
3498 
3499         return (ret);
3500 }
3501 
3502 /*
3503  * zfs mount -a [nfs | iscsi]
3504  * zfs mount filesystem
3505  *
3506  * Mount all filesystems, or mount the given filesystem.
3507  */
3508 static int
3509 zfs_do_mount(int argc, char **argv)
3510 {
3511         return (share_mount(OP_MOUNT, argc, argv));
3512 }
3513 
3514 /*
3515  * zfs share -a [nfs | iscsi | smb]
3516  * zfs share filesystem
3517  *
3518  * Share all filesystems, or share the given filesystem.
3519  */
3520 static int
3521 zfs_do_share(int argc, char **argv)
3522 {
3523         return (share_mount(OP_SHARE, argc, argv));
3524 }
3525 
3526 typedef struct unshare_unmount_node {
3527         zfs_handle_t    *un_zhp;
3528         char            *un_mountp;
3529         uu_avl_node_t   un_avlnode;
3530 } unshare_unmount_node_t;
3531 
3532 /* ARGSUSED */
3533 static int
3534 unshare_unmount_compare(const void *larg, const void *rarg, void *unused)
3535 {
3536         const unshare_unmount_node_t *l = larg;
3537         const unshare_unmount_node_t *r = rarg;
3538 
3539         return (strcmp(l->un_mountp, r->un_mountp));
3540 }
3541 
3542 /*
3543  * Convenience routine used by zfs_do_umount() and manual_unmount().  Given an
3544  * absolute path, find the entry /etc/mnttab, verify that its a ZFS filesystem,
3545  * and unmount it appropriately.
3546  */
3547 static int
3548 unshare_unmount_path(int op, char *path, int flags, boolean_t is_manual)
3549 {
3550         zfs_handle_t *zhp;
3551         int ret;
3552         struct stat64 statbuf;
3553         struct extmnttab entry;
3554         const char *cmdname = (op == OP_SHARE) ? "unshare" : "unmount";
3555         ino_t path_inode;
3556 
3557         /*
3558          * Search for the path in /etc/mnttab.  Rather than looking for the
3559          * specific path, which can be fooled by non-standard paths (i.e. ".."
3560          * or "//"), we stat() the path and search for the corresponding
3561          * (major,minor) device pair.
3562          */
3563         if (stat64(path, &statbuf) != 0) {
3564                 (void) fprintf(stderr, gettext("cannot %s '%s': %s\n"),
3565                     cmdname, path, strerror(errno));
3566                 return (1);
3567         }
3568         path_inode = statbuf.st_ino;
3569 
3570         /*
3571          * Search for the given (major,minor) pair in the mount table.
3572          */
3573         rewind(mnttab_file);
3574         while ((ret = getextmntent(mnttab_file, &entry, 0)) == 0) {
3575                 if (entry.mnt_major == major(statbuf.st_dev) &&
3576                     entry.mnt_minor == minor(statbuf.st_dev))
3577                         break;
3578         }
3579         if (ret != 0) {
3580                 if (op == OP_SHARE) {
3581                         (void) fprintf(stderr, gettext("cannot %s '%s': not "
3582                             "currently mounted\n"), cmdname, path);
3583                         return (1);
3584                 }
3585                 (void) fprintf(stderr, gettext("warning: %s not in mnttab\n"),
3586                     path);
3587                 if ((ret = umount2(path, flags)) != 0)
3588                         (void) fprintf(stderr, gettext("%s: %s\n"), path,
3589                             strerror(errno));
3590                 return (ret != 0);
3591         }
3592 
3593         if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0) {
3594                 (void) fprintf(stderr, gettext("cannot %s '%s': not a ZFS "
3595                     "filesystem\n"), cmdname, path);
3596                 return (1);
3597         }
3598 
3599         if ((zhp = zfs_open(g_zfs, entry.mnt_special,
3600             ZFS_TYPE_FILESYSTEM)) == NULL)
3601                 return (1);
3602 
3603         ret = 1;
3604         if (stat64(entry.mnt_mountp, &statbuf) != 0) {
3605                 (void) fprintf(stderr, gettext("cannot %s '%s': %s\n"),
3606                     cmdname, path, strerror(errno));
3607                 goto out;
3608         } else if (statbuf.st_ino != path_inode) {
3609                 (void) fprintf(stderr, gettext("cannot "
3610                     "%s '%s': not a mountpoint\n"), cmdname, path);
3611                 goto out;
3612         }
3613 
3614         if (op == OP_SHARE) {
3615                 char nfs_mnt_prop[ZFS_MAXPROPLEN];
3616                 char smbshare_prop[ZFS_MAXPROPLEN];
3617 
3618                 verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS, nfs_mnt_prop,
3619                     sizeof (nfs_mnt_prop), NULL, NULL, 0, B_FALSE) == 0);
3620                 verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB, smbshare_prop,
3621                     sizeof (smbshare_prop), NULL, NULL, 0, B_FALSE) == 0);
3622 
3623                 if (strcmp(nfs_mnt_prop, "off") == 0 &&
3624                     strcmp(smbshare_prop, "off") == 0) {
3625                         (void) fprintf(stderr, gettext("cannot unshare "
3626                             "'%s': legacy share\n"), path);
3627                         (void) fprintf(stderr, gettext("use "
3628                             "unshare(1M) to unshare this filesystem\n"));
3629                 } else if (!zfs_is_shared(zhp)) {
3630                         (void) fprintf(stderr, gettext("cannot unshare '%s': "
3631                             "not currently shared\n"), path);
3632                 } else {
3633                         ret = zfs_unshareall_bypath(zhp, path);
3634                 }
3635         } else {
3636                 char mtpt_prop[ZFS_MAXPROPLEN];
3637 
3638                 verify(zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT, mtpt_prop,
3639                     sizeof (mtpt_prop), NULL, NULL, 0, B_FALSE) == 0);
3640 
3641                 if (is_manual) {
3642                         ret = zfs_unmount(zhp, NULL, flags);
3643                 } else if (strcmp(mtpt_prop, "legacy") == 0) {
3644                         (void) fprintf(stderr, gettext("cannot unmount "
3645                             "'%s': legacy mountpoint\n"),
3646                             zfs_get_name(zhp));
3647                         (void) fprintf(stderr, gettext("use umount(1M) "
3648                             "to unmount this filesystem\n"));
3649                 } else {
3650                         ret = zfs_unmountall(zhp, flags);
3651                 }
3652         }
3653 
3654 out:
3655         zfs_close(zhp);
3656 
3657         return (ret != 0);
3658 }
3659 
3660 /*
3661  * Generic callback for unsharing or unmounting a filesystem.
3662  */
3663 static int
3664 unshare_unmount(int op, int argc, char **argv)
3665 {
3666         int do_all = 0;
3667         int flags = 0;
3668         int ret = 0;
3669         int types, c;
3670         zfs_handle_t *zhp;
3671         char nfsiscsi_mnt_prop[ZFS_MAXPROPLEN];
3672         char sharesmb[ZFS_MAXPROPLEN];
3673 
3674         /* check options */
3675         while ((c = getopt(argc, argv, op == OP_SHARE ? "a" : "af")) != -1) {
3676                 switch (c) {
3677                 case 'a':
3678                         do_all = 1;
3679                         break;
3680                 case 'f':
3681                         flags = MS_FORCE;
3682                         break;
3683                 case '?':
3684                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3685                             optopt);
3686                         usage(B_FALSE);
3687                 }
3688         }
3689 
3690         argc -= optind;
3691         argv += optind;
3692 
3693         if (do_all) {
3694                 /*
3695                  * We could make use of zfs_for_each() to walk all datasets in
3696                  * the system, but this would be very inefficient, especially
3697                  * since we would have to linearly search /etc/mnttab for each
3698                  * one.  Instead, do one pass through /etc/mnttab looking for
3699                  * zfs entries and call zfs_unmount() for each one.
3700                  *
3701                  * Things get a little tricky if the administrator has created
3702                  * mountpoints beneath other ZFS filesystems.  In this case, we
3703                  * have to unmount the deepest filesystems first.  To accomplish
3704                  * this, we place all the mountpoints in an AVL tree sorted by
3705                  * the special type (dataset name), and walk the result in
3706                  * reverse to make sure to get any snapshots first.
3707                  */
3708                 struct mnttab entry;
3709                 uu_avl_pool_t *pool;
3710                 uu_avl_t *tree;
3711                 unshare_unmount_node_t *node;
3712                 uu_avl_index_t idx;
3713                 uu_avl_walk_t *walk;
3714 
3715                 if (argc != 0) {
3716                         (void) fprintf(stderr, gettext("too many arguments\n"));
3717                         usage(B_FALSE);
3718                 }
3719 
3720                 if ((pool = uu_avl_pool_create("unmount_pool",
3721                     sizeof (unshare_unmount_node_t),
3722                     offsetof(unshare_unmount_node_t, un_avlnode),
3723                     unshare_unmount_compare,
3724                     UU_DEFAULT)) == NULL) {
3725                         (void) fprintf(stderr, gettext("internal error: "
3726                             "out of memory\n"));
3727                         exit(1);
3728                 }
3729 
3730                 if ((tree = uu_avl_create(pool, NULL, UU_DEFAULT)) == NULL) {
3731                         (void) fprintf(stderr, gettext("internal error: "
3732                             "out of memory\n"));
3733                         exit(1);
3734                 }
3735 
3736                 rewind(mnttab_file);
3737                 while (getmntent(mnttab_file, &entry) == 0) {
3738 
3739                         /* ignore non-ZFS entries */
3740                         if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0)
3741                                 continue;
3742 
3743                         /* ignore snapshots */
3744                         if (strchr(entry.mnt_special, '@') != NULL)
3745                                 continue;
3746 
3747                         if ((zhp = zfs_open(g_zfs, entry.mnt_special,
3748                             ZFS_TYPE_FILESYSTEM)) == NULL) {
3749                                 ret = 1;
3750                                 continue;
3751                         }
3752 
3753                         switch (op) {
3754                         case OP_SHARE:
3755                                 verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS,
3756                                     nfsiscsi_mnt_prop,
3757                                     sizeof (nfsiscsi_mnt_prop),
3758                                     NULL, NULL, 0, B_FALSE) == 0);
3759                                 if (strcmp(nfsiscsi_mnt_prop, "off") != 0)
3760                                         break;
3761                                 verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB,
3762                                     nfsiscsi_mnt_prop,
3763                                     sizeof (nfsiscsi_mnt_prop),
3764                                     NULL, NULL, 0, B_FALSE) == 0);
3765                                 if (strcmp(nfsiscsi_mnt_prop, "off") == 0)
3766                                         continue;
3767                                 break;
3768                         case OP_MOUNT:
3769                                 /* Ignore legacy mounts */
3770                                 verify(zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT,
3771                                     nfsiscsi_mnt_prop,
3772                                     sizeof (nfsiscsi_mnt_prop),
3773                                     NULL, NULL, 0, B_FALSE) == 0);
3774                                 if (strcmp(nfsiscsi_mnt_prop, "legacy") == 0)
3775                                         continue;
3776                                 /* Ignore canmount=noauto mounts */
3777                                 if (zfs_prop_get_int(zhp, ZFS_PROP_CANMOUNT) ==
3778                                     ZFS_CANMOUNT_NOAUTO)
3779                                         continue;
3780                         default:
3781                                 break;
3782                         }
3783 
3784                         node = safe_malloc(sizeof (unshare_unmount_node_t));
3785                         node->un_zhp = zhp;
3786 
3787                         if ((node->un_mountp = strdup(entry.mnt_mountp)) ==
3788                             NULL) {
3789                                 (void) fprintf(stderr, gettext("internal error:"
3790                                     " out of memory\n"));
3791                                 exit(1);
3792                         }
3793 
3794                         uu_avl_node_init(node, &node->un_avlnode, pool);
3795 
3796                         if (uu_avl_find(tree, node, NULL, &idx) == NULL) {
3797                                 uu_avl_insert(tree, node, idx);
3798                         } else {
3799                                 zfs_close(node->un_zhp);
3800                                 free(node->un_mountp);
3801                                 free(node);
3802                         }
3803                 }
3804 
3805                 /*
3806                  * Walk the AVL tree in reverse, unmounting each filesystem and
3807                  * removing it from the AVL tree in the process.
3808                  */
3809                 if ((walk = uu_avl_walk_start(tree,
3810                     UU_WALK_REVERSE | UU_WALK_ROBUST)) == NULL) {
3811                         (void) fprintf(stderr,
3812                             gettext("internal error: out of memory"));
3813                         exit(1);
3814                 }
3815 
3816                 while ((node = uu_avl_walk_next(walk)) != NULL) {
3817                         uu_avl_remove(tree, node);
3818 
3819                         switch (op) {
3820                         case OP_SHARE:
3821                                 if (zfs_unshareall_bypath(node->un_zhp,
3822                                     node->un_mountp) != 0)
3823                                         ret = 1;
3824                                 break;
3825 
3826                         case OP_MOUNT:
3827                                 if (zfs_unmount(node->un_zhp,
3828                                     node->un_mountp, flags) != 0)
3829                                         ret = 1;
3830                                 break;
3831                         }
3832 
3833                         zfs_close(node->un_zhp);
3834                         free(node->un_mountp);
3835                         free(node);
3836                 }
3837 
3838                 uu_avl_walk_end(walk);
3839                 uu_avl_destroy(tree);
3840                 uu_avl_pool_destroy(pool);
3841 
3842                 if (op == OP_SHARE) {
3843                         /*
3844                          * Finally, unshare any volumes shared via iSCSI.
3845                          */
3846                         zfs_handle_t **dslist = NULL;
3847                         size_t i, count = 0;
3848 
3849                         get_all_datasets(ZFS_TYPE_VOLUME, &dslist, &count,
3850                             B_FALSE);
3851 
3852                         if (count != 0) {
3853                                 qsort(dslist, count, sizeof (void *),
3854                                     dataset_cmp);
3855 
3856                                 for (i = 0; i < count; i++) {
3857                                         if (zfs_unshare_iscsi(dslist[i]) != 0)
3858                                                 ret = 1;
3859                                         zfs_close(dslist[i]);
3860                                 }
3861 
3862                                 free(dslist);
3863                         }
3864                 }
3865         } else {
3866                 if (argc != 1) {
3867                         if (argc == 0)
3868                                 (void) fprintf(stderr,
3869                                     gettext("missing filesystem argument\n"));
3870                         else
3871                                 (void) fprintf(stderr,
3872                                     gettext("too many arguments\n"));
3873                         usage(B_FALSE);
3874                 }
3875 
3876                 /*
3877                  * We have an argument, but it may be a full path or a ZFS
3878                  * filesystem.  Pass full paths off to unmount_path() (shared by
3879                  * manual_unmount), otherwise open the filesystem and pass to
3880                  * zfs_unmount().
3881                  */
3882                 if (argv[0][0] == '/')
3883                         return (unshare_unmount_path(op, argv[0],
3884                             flags, B_FALSE));
3885 
3886                 types = ZFS_TYPE_FILESYSTEM;
3887                 if (op == OP_SHARE)
3888                         types |= ZFS_TYPE_VOLUME;
3889 
3890                 if ((zhp = zfs_open(g_zfs, argv[0], types)) == NULL)
3891                         return (1);
3892 
3893                 if (zfs_get_type(zhp) == ZFS_TYPE_FILESYSTEM) {
3894                         verify(zfs_prop_get(zhp, op == OP_SHARE ?
3895                             ZFS_PROP_SHARENFS : ZFS_PROP_MOUNTPOINT,
3896                             nfsiscsi_mnt_prop, sizeof (nfsiscsi_mnt_prop), NULL,
3897                             NULL, 0, B_FALSE) == 0);
3898 
3899                         switch (op) {
3900                         case OP_SHARE:
3901                                 verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS,
3902                                     nfsiscsi_mnt_prop,
3903                                     sizeof (nfsiscsi_mnt_prop),
3904                                     NULL, NULL, 0, B_FALSE) == 0);
3905                                 verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB,
3906                                     sharesmb, sizeof (sharesmb), NULL, NULL,
3907                                     0, B_FALSE) == 0);
3908 
3909                                 if (strcmp(nfsiscsi_mnt_prop, "off") == 0 &&
3910                                     strcmp(sharesmb, "off") == 0) {
3911                                         (void) fprintf(stderr, gettext("cannot "
3912                                             "unshare '%s': legacy share\n"),
3913                                             zfs_get_name(zhp));
3914                                         (void) fprintf(stderr, gettext("use "
3915                                             "unshare(1M) to unshare this "
3916                                             "filesystem\n"));
3917                                         ret = 1;
3918                                 } else if (!zfs_is_shared(zhp)) {
3919                                         (void) fprintf(stderr, gettext("cannot "
3920                                             "unshare '%s': not currently "
3921                                             "shared\n"), zfs_get_name(zhp));
3922                                         ret = 1;
3923                                 } else if (zfs_unshareall(zhp) != 0) {
3924                                         ret = 1;
3925                                 }
3926                                 break;
3927 
3928                         case OP_MOUNT:
3929                                 if (strcmp(nfsiscsi_mnt_prop, "legacy") == 0) {
3930                                         (void) fprintf(stderr, gettext("cannot "
3931                                             "unmount '%s': legacy "
3932                                             "mountpoint\n"), zfs_get_name(zhp));
3933                                         (void) fprintf(stderr, gettext("use "
3934                                             "umount(1M) to unmount this "
3935                                             "filesystem\n"));
3936                                         ret = 1;
3937                                 } else if (!zfs_is_mounted(zhp, NULL)) {
3938                                         (void) fprintf(stderr, gettext("cannot "
3939                                             "unmount '%s': not currently "
3940                                             "mounted\n"),
3941                                             zfs_get_name(zhp));
3942                                         ret = 1;
3943                                 } else if (zfs_unmountall(zhp, flags) != 0) {
3944                                         ret = 1;
3945                                 }
3946                                 break;
3947                         }
3948                 } else {
3949                         assert(op == OP_SHARE);
3950 
3951                         verify(zfs_prop_get(zhp, ZFS_PROP_SHAREISCSI,
3952                             nfsiscsi_mnt_prop, sizeof (nfsiscsi_mnt_prop),
3953                             NULL, NULL, 0, B_FALSE) == 0);
3954 
3955                         if (strcmp(nfsiscsi_mnt_prop, "off") == 0) {
3956                                 (void) fprintf(stderr, gettext("cannot unshare "
3957                                     "'%s': 'shareiscsi' property not set\n"),
3958                                     zfs_get_name(zhp));
3959                                 (void) fprintf(stderr, gettext("set "
3960                                     "'shareiscsi' property or use "
3961                                     "iscsitadm(1M) to share this volume\n"));
3962                                 ret = 1;
3963                         } else if (!zfs_is_shared_iscsi(zhp)) {
3964                                 (void) fprintf(stderr, gettext("cannot "
3965                                     "unshare '%s': not currently shared\n"),
3966                                     zfs_get_name(zhp));
3967                                 ret = 1;
3968                         } else if (zfs_unshare_iscsi(zhp) != 0) {
3969                                 ret = 1;
3970                         }
3971                 }
3972 
3973                 zfs_close(zhp);
3974         }
3975 
3976         return (ret);
3977 }
3978 
3979 /*
3980  * zfs unmount -a
3981  * zfs unmount filesystem
3982  *
3983  * Unmount all filesystems, or a specific ZFS filesystem.
3984  */
3985 static int
3986 zfs_do_unmount(int argc, char **argv)
3987 {
3988         return (unshare_unmount(OP_MOUNT, argc, argv));
3989 }
3990 
3991 /*
3992  * zfs unshare -a
3993  * zfs unshare filesystem
3994  *
3995  * Unshare all filesystems, or a specific ZFS filesystem.
3996  */
3997 static int
3998 zfs_do_unshare(int argc, char **argv)
3999 {
4000         return (unshare_unmount(OP_SHARE, argc, argv));
4001 }
4002 
4003 /*
4004  * Called when invoked as /etc/fs/zfs/mount.  Do the mount if the mountpoint is
4005  * 'legacy'.  Otherwise, complain that use should be using 'zfs mount'.
4006  */
4007 static int
4008 manual_mount(int argc, char **argv)
4009 {
4010         zfs_handle_t *zhp;
4011         char mountpoint[ZFS_MAXPROPLEN];
4012         char mntopts[MNT_LINE_MAX] = { '\0' };
4013         int ret;
4014         int c;
4015         int flags = 0;
4016         char *dataset, *path;
4017 
4018         /* check options */
4019         while ((c = getopt(argc, argv, ":mo:O")) != -1) {
4020                 switch (c) {
4021                 case 'o':
4022                         (void) strlcpy(mntopts, optarg, sizeof (mntopts));
4023                         break;
4024                 case 'O':
4025                         flags |= MS_OVERLAY;
4026                         break;
4027                 case 'm':
4028                         flags |= MS_NOMNTTAB;
4029                         break;
4030                 case ':':
4031                         (void) fprintf(stderr, gettext("missing argument for "
4032                             "'%c' option\n"), optopt);
4033                         usage(B_FALSE);
4034                         break;
4035                 case '?':
4036                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
4037                             optopt);
4038                         (void) fprintf(stderr, gettext("usage: mount [-o opts] "
4039                             "<path>\n"));
4040                         return (2);
4041                 }
4042         }
4043 
4044         argc -= optind;
4045         argv += optind;
4046 
4047         /* check that we only have two arguments */
4048         if (argc != 2) {
4049                 if (argc == 0)
4050                         (void) fprintf(stderr, gettext("missing dataset "
4051                             "argument\n"));
4052                 else if (argc == 1)
4053                         (void) fprintf(stderr,
4054                             gettext("missing mountpoint argument\n"));
4055                 else
4056                         (void) fprintf(stderr, gettext("too many arguments\n"));
4057                 (void) fprintf(stderr, "usage: mount <dataset> <mountpoint>\n");
4058                 return (2);
4059         }
4060 
4061         dataset = argv[0];
4062         path = argv[1];
4063 
4064         /* try to open the dataset */
4065         if ((zhp = zfs_open(g_zfs, dataset, ZFS_TYPE_FILESYSTEM)) == NULL)
4066                 return (1);
4067 
4068         (void) zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT, mountpoint,
4069             sizeof (mountpoint), NULL, NULL, 0, B_FALSE);
4070 
4071         /* check for legacy mountpoint and complain appropriately */
4072         ret = 0;
4073         if (strcmp(mountpoint, ZFS_MOUNTPOINT_LEGACY) == 0) {
4074                 if (mount(dataset, path, MS_OPTIONSTR | flags, MNTTYPE_ZFS,
4075                     NULL, 0, mntopts, sizeof (mntopts)) != 0) {
4076                         (void) fprintf(stderr, gettext("mount failed: %s\n"),
4077                             strerror(errno));
4078                         ret = 1;
4079                 }
4080         } else {
4081                 (void) fprintf(stderr, gettext("filesystem '%s' cannot be "
4082                     "mounted using 'mount -F zfs'\n"), dataset);
4083                 (void) fprintf(stderr, gettext("Use 'zfs set mountpoint=%s' "
4084                     "instead.\n"), path);
4085                 (void) fprintf(stderr, gettext("If you must use 'mount -F zfs' "
4086                     "or /etc/vfstab, use 'zfs set mountpoint=legacy'.\n"));
4087                 (void) fprintf(stderr, gettext("See zfs(1M) for more "
4088                     "information.\n"));
4089                 ret = 1;
4090         }
4091 
4092         return (ret);
4093 }
4094 
4095 /*
4096  * Called when invoked as /etc/fs/zfs/umount.  Unlike a manual mount, we allow
4097  * unmounts of non-legacy filesystems, as this is the dominant administrative
4098  * interface.
4099  */
4100 static int
4101 manual_unmount(int argc, char **argv)
4102 {
4103         int flags = 0;
4104         int c;
4105 
4106         /* check options */
4107         while ((c = getopt(argc, argv, "f")) != -1) {
4108                 switch (c) {
4109                 case 'f':
4110                         flags = MS_FORCE;
4111                         break;
4112                 case '?':
4113                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
4114                             optopt);
4115                         (void) fprintf(stderr, gettext("usage: unmount [-f] "
4116                             "<path>\n"));
4117                         return (2);
4118                 }
4119         }
4120 
4121         argc -= optind;
4122         argv += optind;
4123 
4124         /* check arguments */
4125         if (argc != 1) {
4126                 if (argc == 0)
4127                         (void) fprintf(stderr, gettext("missing path "
4128                             "argument\n"));
4129                 else
4130                         (void) fprintf(stderr, gettext("too many arguments\n"));
4131                 (void) fprintf(stderr, gettext("usage: unmount [-f] <path>\n"));
4132                 return (2);
4133         }
4134 
4135         return (unshare_unmount_path(OP_MOUNT, argv[0], flags, B_TRUE));
4136 }
4137 
4138 int
4139 zfs_do_key(int argc, char **argv)
4140 {
4141         int error = 1, options = 0;
4142         nvlist_t *props = NULL;
4143         char c, *propname, *propval = NULL;
4144         boolean_t load = B_FALSE, unload = B_FALSE, change = B_FALSE;
4145         boolean_t do_all = B_FALSE;
4146         char *strval;
4147         zfs_handle_t **dslist = NULL, *zhp = NULL;
4148         uint_t count;
4149         zfs_prop_t zprop;
4150 
4151         while ((c = getopt(argc, argv, "aluco:")) != -1) {
4152                 switch (c) {
4153                 case 'a':
4154                         do_all = B_TRUE;
4155                         break;
4156 
4157                 case 'l':
4158                         load = B_TRUE;
4159                         break;
4160 
4161                 case 'u':
4162                         unload = B_TRUE;
4163                         break;
4164 
4165                 case 'c':
4166                         change = B_TRUE;
4167                         break;
4168 
4169                 case 'o':
4170                         /* Key change is the only command that allows options */
4171                         if (change != B_TRUE) {
4172                                 (void) fprintf(stderr, gettext("Property "
4173                                     "options only allowed during key "
4174                                     "change.\n"));
4175                                 usage(B_FALSE);
4176                                 goto error;
4177                         }
4178 
4179                         propname = optarg;
4180                         if ((propval = strchr(optarg, '=')) == NULL) {
4181                                 (void) fprintf(stderr, gettext("missing "
4182                                     "'=' for -o option\n"));
4183                                 goto error;
4184                         }
4185 
4186                         *propval = '\0';
4187                         propval++;
4188 
4189                         zprop = zfs_name_to_prop(propname);
4190                         switch (zprop) {
4191                         case ZFS_PROP_KEYSOURCE:
4192                         case ZFS_PROP_KEYSCOPE:
4193                                 break;
4194 
4195                         default:
4196                                 (void) fprintf(stderr, gettext("Invalid "
4197                                     "property for key operation: '%s'\n"),
4198                                     propname);
4199                                 goto error;
4200                         };
4201 
4202                         if (props == NULL &&
4203                             nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0) {
4204                                 (void) fprintf(stderr, gettext("internal "
4205                                     "error: out of memory\n"));
4206                                 goto error;
4207                         }
4208 
4209                         if (nvlist_lookup_string(props, propname,
4210                             &strval) == 0) {
4211                                 (void) fprintf(stderr, gettext("property '%s' "
4212                                     "specified multiple times\n"), propname);
4213                                 goto error;
4214                         }
4215                         if (nvlist_add_string(props, propname, propval) != 0) {
4216                                 (void) fprintf(stderr, gettext("internal "
4217                                     "error: out of memory\n"));
4218                                 goto error;
4219                         }
4220 
4221                         options += 2;
4222                         break;
4223 
4224                 case '?':
4225                 default:
4226                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
4227                             optopt);
4228                         usage(B_FALSE);
4229 
4230                 }
4231         }
4232 
4233         if (!change && props != NULL)
4234                 (void) fprintf(stderr, gettext("Properties are not allowed to "
4235                     "be used in this command.\n"));
4236 
4237         if (((load || unload) && (argc > 3)) ||
4238             (change && ((argc - options) > 3))) {
4239                         (void) fprintf(stderr,
4240                             gettext("too many arguments\n"));
4241                         usage(B_FALSE);
4242                         goto error;
4243         } else if ((load || unload) && (argc < 3)) {
4244                         (void) fprintf(stderr, gettext("missing dataset "
4245                             "argument (specify -a for all)\n"));
4246                         usage(B_FALSE);
4247                         goto error;
4248         } else if (change && ((argc - options) < 3)) {
4249                         (void) fprintf(stderr, gettext("missing dataset "
4250                             "argument\n"));
4251                         usage(B_FALSE);
4252                         goto error;
4253         }
4254 
4255         if (do_all == B_FALSE) {
4256                 zhp = zfs_open(g_zfs, argv[argc - 1],
4257                     ZFS_TYPE_FILESYSTEM|ZFS_TYPE_VOLUME);
4258                 if (zhp == NULL)
4259                         goto error;
4260 
4261         } else if (change) {
4262                 /* We don't support do_all in a change operation */
4263 
4264                 (void) fprintf(stderr, gettext("cannot use '-a' with "
4265                     "change operation.\n"));
4266                 usage(B_FALSE);
4267                 goto error;
4268 
4269         } else {
4270                 get_all_datasets(ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME,
4271                     &dslist, &count, B_FALSE);
4272                 if (count == 0)
4273                         return (0);
4274 
4275                 qsort(dslist, count, sizeof (void *), dataset_cmp);
4276         }
4277 
4278         if (load) {
4279                 if (do_all) {
4280                         int i;
4281                         zfs_crypt_t *cry = NULL;
4282 
4283                         cry = calloc(1, sizeof (zfs_crypt_t));
4284                         for (i = 0; i < count; i++) {
4285                                 if (zfs_is_encrypted(dslist[i])) {
4286                                         zfs_set_libzfs_cry(dslist[i], cry);
4287                                         (void) zfs_load_key(dslist[i]);
4288                                         bzero(cry, sizeof (zfs_crypt_t));
4289                                 }
4290                                 zfs_close(dslist[i]);
4291                         }
4292 
4293                         free(cry);
4294                         free(dslist);
4295                         error = 0;
4296 
4297                 } else
4298                         error = zfs_cmd_key_load(zhp);
4299 
4300         } else if (unload) {
4301                 if (do_all) {
4302                         int i;
4303 
4304                         /* Do in reverse order so we can unmount easily */
4305                         for (i = count - 1; i > 0; i--) {
4306                                 if (zfs_is_encrypted(dslist[i]))
4307                                         (void) zfs_unload_key(dslist[i]);
4308 
4309                                 zfs_close(dslist[i]);
4310                         }
4311 
4312                         free(dslist);
4313                         error = 0;
4314 
4315                 } else
4316                         error = zfs_cmd_key_unload(zhp);
4317 
4318         } else if (change) {
4319                 error = zfs_cmd_key_change(zhp, props);
4320 
4321         } else
4322                 usage(B_FALSE);
4323 
4324         if (zhp != NULL)
4325                 zfs_close(zhp);
4326 
4327 error:
4328         if (props != NULL) {
4329                 nvlist_free(props);
4330         }
4331         return (error);
4332 }
4333 
4334 
4335 static int
4336 volcheck(zpool_handle_t *zhp, void *data)
4337 {
4338         boolean_t isinit = *((boolean_t *)data);
4339 
4340         if (isinit)
4341                 return (zpool_create_zvol_links(zhp));
4342         else
4343                 return (zpool_remove_zvol_links(zhp));
4344 }
4345 
4346 /*
4347  * Iterate over all pools in the system and either create or destroy /dev/zvol
4348  * links, depending on the value of 'isinit'.
4349  */
4350 static int
4351 do_volcheck(boolean_t isinit)
4352 {
4353         return (zpool_iter(g_zfs, volcheck, &isinit) ? 1 : 0);
4354 }
4355 
4356 static int
4357 find_command_idx(char *command, int *idx)
4358 {
4359         int i;
4360 
4361         for (i = 0; i < NCOMMAND; i++) {
4362                 if (command_table[i].name == NULL)
4363                         continue;
4364 
4365                 if (strcmp(command, command_table[i].name) == 0) {
4366                         *idx = i;
4367                         return (0);
4368                 }
4369         }
4370         return (1);
4371 }
4372 
4373 int
4374 main(int argc, char **argv)
4375 {
4376         int ret;
4377         int i;
4378         char *progname;
4379         char *cmdname;
4380 
4381         (void) setlocale(LC_ALL, "");
4382         (void) textdomain(TEXT_DOMAIN);
4383 
4384         opterr = 0;
4385 
4386         if ((g_zfs = libzfs_init()) == NULL) {
4387                 (void) fprintf(stderr, gettext("internal error: failed to "
4388                     "initialize ZFS library\n"));
4389                 return (1);
4390         }
4391 
4392         zpool_set_history_str("zfs", argc, argv, history_str);
4393         verify(zpool_stage_history(g_zfs, history_str) == 0);
4394 
4395         libzfs_print_on_error(g_zfs, B_TRUE);
4396 
4397         if ((mnttab_file = fopen(MNTTAB, "r")) == NULL) {
4398                 (void) fprintf(stderr, gettext("internal error: unable to "
4399                     "open %s\n"), MNTTAB);
4400                 return (1);
4401         }
4402 
4403         /*
4404          * This command also doubles as the /etc/fs mount and unmount program.
4405          * Determine if we should take this behavior based on argv[0].
4406          */
4407         progname = basename(argv[0]);
4408         if (strcmp(progname, "mount") == 0) {
4409                 ret = manual_mount(argc, argv);
4410         } else if (strcmp(progname, "umount") == 0) {
4411                 ret = manual_unmount(argc, argv);
4412         } else {
4413                 /*
4414                  * Make sure the user has specified some command.
4415                  */
4416                 if (argc < 2) {
4417                         (void) fprintf(stderr, gettext("missing command\n"));
4418                         usage(B_FALSE);
4419                 }
4420 
4421                 cmdname = argv[1];
4422 
4423                 /*
4424                  * The 'umount' command is an alias for 'unmount'
4425                  */
4426                 if (strcmp(cmdname, "umount") == 0)
4427                         cmdname = "unmount";
4428 
4429                 /*
4430                  * The 'recv' command is an alias for 'receive'
4431                  */
4432                 if (strcmp(cmdname, "recv") == 0)
4433                         cmdname = "receive";
4434 
4435                 /*
4436                  * Special case '-?'
4437                  */
4438                 if (strcmp(cmdname, "-?") == 0)
4439                         usage(B_TRUE);
4440 
4441                 /*
4442                  * 'volinit' and 'volfini' do not appear in the usage message,
4443                  * so we have to special case them here.
4444                  */
4445                 if (strcmp(cmdname, "volinit") == 0)
4446                         return (do_volcheck(B_TRUE));
4447                 else if (strcmp(cmdname, "volfini") == 0)
4448                         return (do_volcheck(B_FALSE));
4449 
4450                 /*
4451                  * Run the appropriate command.
4452                  */
4453                 if (find_command_idx(cmdname, &i) == 0) {
4454                         current_command = &command_table[i];
4455                         ret = command_table[i].func(argc - 1, argv + 1);
4456                 } else if (strchr(cmdname, '=') != NULL) {
4457                         verify(find_command_idx("set", &i) == 0);
4458                         current_command = &command_table[i];
4459                         ret = command_table[i].func(argc, argv);
4460                 } else {
4461                         (void) fprintf(stderr, gettext("unrecognized "
4462                             "command '%s'\n"), cmdname);
4463                         usage(B_FALSE);
4464                 }
4465         }
4466 
4467         (void) fclose(mnttab_file);
4468 
4469         libzfs_fini(g_zfs);
4470 
4471         /*
4472          * The 'ZFS_ABORT' environment variable causes us to dump core on exit
4473          * for the purposes of running ::findleaks.
4474          */
4475         if (getenv("ZFS_ABORT") != NULL) {
4476                 (void) printf("dumping core by request\n");
4477                 abort();
4478         }
4479 
4480         return (ret);
4481 }