1 /*
   2  * CDDL HEADER START
   3  *
   4  * The contents of this file are subject to the terms of the
   5  * Common Development and Distribution License (the "License").
   6  * You may not use this file except in compliance with the License.
   7  *
   8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
   9  * or http://www.opensolaris.org/os/licensing.
  10  * See the License for the specific language governing permissions
  11  * and limitations under the License.
  12  *
  13  * When distributing Covered Code, include this CDDL HEADER in each
  14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
  15  * If applicable, add the following below this CDDL HEADER, with the
  16  * fields enclosed by brackets "[]" replaced with your own identifying
  17  * information: Portions Copyright [yyyy] [name of copyright owner]
  18  *
  19  * CDDL HEADER END
  20  */
  21 
  22 /*
  23  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
  24  * Copyright 2012 Nexenta Systems, Inc. All rights reserved.
  25  * Copyright (c) 2012 by Delphix. All rights reserved.
  26  * Copyright 2012 Milan Jurik. All rights reserved.
  27  * Copyright (c) 2012, Joyent, Inc. All rights reserved.
  28  */
  29 
  30 #include <assert.h>
  31 #include <ctype.h>
  32 #include <errno.h>
  33 #include <libgen.h>
  34 #include <libintl.h>
  35 #include <libuutil.h>
  36 #include <libnvpair.h>
  37 #include <locale.h>
  38 #include <stddef.h>
  39 #include <stdio.h>
  40 #include <stdlib.h>
  41 #include <strings.h>
  42 #include <unistd.h>
  43 #include <fcntl.h>
  44 #include <zone.h>
  45 #include <grp.h>
  46 #include <pwd.h>
  47 #include <signal.h>
  48 #include <sys/list.h>
  49 #include <sys/mkdev.h>
  50 #include <sys/mntent.h>
  51 #include <sys/mnttab.h>
  52 #include <sys/mount.h>
  53 #include <sys/stat.h>
  54 #include <sys/fs/zfs.h>
  55 #include <sys/types.h>
  56 #include <time.h>
  57 
  58 #include <libzfs.h>
  59 #include <libzfs_core.h>
  60 #include <zfs_prop.h>
  61 #include <zfs_deleg.h>
  62 #include <libuutil.h>
  63 #include <aclutils.h>
  64 #include <directory.h>
  65 
  66 #include "zfs_iter.h"
  67 #include "zfs_util.h"
  68 #include "zfs_comutil.h"
  69 
  70 libzfs_handle_t *g_zfs;
  71 
  72 static FILE *mnttab_file;
  73 static char history_str[HIS_MAX_RECORD_LEN];
  74 static boolean_t log_history = B_TRUE;
  75 
  76 static int zfs_do_clone(int argc, char **argv);
  77 static int zfs_do_create(int argc, char **argv);
  78 static int zfs_do_destroy(int argc, char **argv);
  79 static int zfs_do_get(int argc, char **argv);
  80 static int zfs_do_inherit(int argc, char **argv);
  81 static int zfs_do_list(int argc, char **argv);
  82 static int zfs_do_mount(int argc, char **argv);
  83 static int zfs_do_rename(int argc, char **argv);
  84 static int zfs_do_rollback(int argc, char **argv);
  85 static int zfs_do_set(int argc, char **argv);
  86 static int zfs_do_upgrade(int argc, char **argv);
  87 static int zfs_do_snapshot(int argc, char **argv);
  88 static int zfs_do_unmount(int argc, char **argv);
  89 static int zfs_do_share(int argc, char **argv);
  90 static int zfs_do_unshare(int argc, char **argv);
  91 static int zfs_do_send(int argc, char **argv);
  92 static int zfs_do_receive(int argc, char **argv);
  93 static int zfs_do_promote(int argc, char **argv);
  94 static int zfs_do_userspace(int argc, char **argv);
  95 static int zfs_do_allow(int argc, char **argv);
  96 static int zfs_do_unallow(int argc, char **argv);
  97 static int zfs_do_hold(int argc, char **argv);
  98 static int zfs_do_holds(int argc, char **argv);
  99 static int zfs_do_release(int argc, char **argv);
 100 static int zfs_do_diff(int argc, char **argv);
 101 
 102 /*
 103  * Enable a reasonable set of defaults for libumem debugging on DEBUG builds.
 104  */
 105 
 106 #ifdef DEBUG
 107 const char *
 108 _umem_debug_init(void)
 109 {
 110         return ("default,verbose"); /* $UMEM_DEBUG setting */
 111 }
 112 
 113 const char *
 114 _umem_logging_init(void)
 115 {
 116         return ("fail,contents"); /* $UMEM_LOGGING setting */
 117 }
 118 #endif
 119 
 120 typedef enum {
 121         HELP_CLONE,
 122         HELP_CREATE,
 123         HELP_DESTROY,
 124         HELP_GET,
 125         HELP_INHERIT,
 126         HELP_UPGRADE,
 127         HELP_LIST,
 128         HELP_MOUNT,
 129         HELP_PROMOTE,
 130         HELP_RECEIVE,
 131         HELP_RENAME,
 132         HELP_ROLLBACK,
 133         HELP_SEND,
 134         HELP_SET,
 135         HELP_SHARE,
 136         HELP_SNAPSHOT,
 137         HELP_UNMOUNT,
 138         HELP_UNSHARE,
 139         HELP_ALLOW,
 140         HELP_UNALLOW,
 141         HELP_USERSPACE,
 142         HELP_GROUPSPACE,
 143         HELP_HOLD,
 144         HELP_HOLDS,
 145         HELP_RELEASE,
 146         HELP_DIFF,
 147 } zfs_help_t;
 148 
 149 typedef struct zfs_command {
 150         const char      *name;
 151         int             (*func)(int argc, char **argv);
 152         zfs_help_t      usage;
 153 } zfs_command_t;
 154 
 155 /*
 156  * Master command table.  Each ZFS command has a name, associated function, and
 157  * usage message.  The usage messages need to be internationalized, so we have
 158  * to have a function to return the usage message based on a command index.
 159  *
 160  * These commands are organized according to how they are displayed in the usage
 161  * message.  An empty command (one with a NULL name) indicates an empty line in
 162  * the generic usage message.
 163  */
 164 static zfs_command_t command_table[] = {
 165         { "create",     zfs_do_create,          HELP_CREATE             },
 166         { "destroy",    zfs_do_destroy,         HELP_DESTROY            },
 167         { NULL },
 168         { "snapshot",   zfs_do_snapshot,        HELP_SNAPSHOT           },
 169         { "rollback",   zfs_do_rollback,        HELP_ROLLBACK           },
 170         { "clone",      zfs_do_clone,           HELP_CLONE              },
 171         { "promote",    zfs_do_promote,         HELP_PROMOTE            },
 172         { "rename",     zfs_do_rename,          HELP_RENAME             },
 173         { NULL },
 174         { "list",       zfs_do_list,            HELP_LIST               },
 175         { NULL },
 176         { "set",        zfs_do_set,             HELP_SET                },
 177         { "get",        zfs_do_get,             HELP_GET                },
 178         { "inherit",    zfs_do_inherit,         HELP_INHERIT            },
 179         { "upgrade",    zfs_do_upgrade,         HELP_UPGRADE            },
 180         { "userspace",  zfs_do_userspace,       HELP_USERSPACE          },
 181         { "groupspace", zfs_do_userspace,       HELP_GROUPSPACE         },
 182         { NULL },
 183         { "mount",      zfs_do_mount,           HELP_MOUNT              },
 184         { "unmount",    zfs_do_unmount,         HELP_UNMOUNT            },
 185         { "share",      zfs_do_share,           HELP_SHARE              },
 186         { "unshare",    zfs_do_unshare,         HELP_UNSHARE            },
 187         { NULL },
 188         { "send",       zfs_do_send,            HELP_SEND               },
 189         { "receive",    zfs_do_receive,         HELP_RECEIVE            },
 190         { NULL },
 191         { "allow",      zfs_do_allow,           HELP_ALLOW              },
 192         { NULL },
 193         { "unallow",    zfs_do_unallow,         HELP_UNALLOW            },
 194         { NULL },
 195         { "hold",       zfs_do_hold,            HELP_HOLD               },
 196         { "holds",      zfs_do_holds,           HELP_HOLDS              },
 197         { "release",    zfs_do_release,         HELP_RELEASE            },
 198         { "diff",       zfs_do_diff,            HELP_DIFF               },
 199 };
 200 
 201 #define NCOMMAND        (sizeof (command_table) / sizeof (command_table[0]))
 202 
 203 zfs_command_t *current_command;
 204 
 205 static const char *
 206 get_usage(zfs_help_t idx)
 207 {
 208         switch (idx) {
 209         case HELP_CLONE:
 210                 return (gettext("\tclone [-p] [-o property=value] ... "
 211                     "<snapshot> <filesystem|volume>\n"));
 212         case HELP_CREATE:
 213                 return (gettext("\tcreate [-p] [-o property=value] ... "
 214                     "<filesystem>\n"
 215                     "\tcreate [-ps] [-b blocksize] [-o property=value] ... "
 216                     "-V <size> <volume>\n"));
 217         case HELP_DESTROY:
 218                 return (gettext("\tdestroy [-fnpRrv] <filesystem|volume>\n"
 219                     "\tdestroy [-dnpRrv] "
 220                     "<filesystem|volume>@<snap>[%<snap>][,...]\n"));
 221         case HELP_GET:
 222                 return (gettext("\tget [-rHp] [-d max] "
 223                     "[-o \"all\" | field[,...]] [-t type[,...]] "
 224                     "[-s source[,...]]\n"
 225                     "\t    <\"all\" | property[,...]> "
 226                     "[filesystem|volume|snapshot] ...\n"));
 227         case HELP_INHERIT:
 228                 return (gettext("\tinherit [-rS] <property> "
 229                     "<filesystem|volume|snapshot> ...\n"));
 230         case HELP_UPGRADE:
 231                 return (gettext("\tupgrade [-v]\n"
 232                     "\tupgrade [-r] [-V version] <-a | filesystem ...>\n"));
 233         case HELP_LIST:
 234                 return (gettext("\tlist [-rH][-d max] "
 235                     "[-o property[,...]] [-t type[,...]] [-s property] ...\n"
 236                     "\t    [-S property] ... "
 237                     "[filesystem|volume|snapshot] ...\n"));
 238         case HELP_MOUNT:
 239                 return (gettext("\tmount\n"
 240                     "\tmount [-vO] [-o opts] <-a | filesystem>\n"));
 241         case HELP_PROMOTE:
 242                 return (gettext("\tpromote <clone-filesystem>\n"));
 243         case HELP_RECEIVE:
 244                 return (gettext("\treceive [-vnFu] <filesystem|volume|"
 245                 "snapshot>\n"
 246                 "\treceive [-vnFu] [-d | -e] <filesystem>\n"));
 247         case HELP_RENAME:
 248                 return (gettext("\trename [-f] <filesystem|volume|snapshot> "
 249                     "<filesystem|volume|snapshot>\n"
 250                     "\trename [-f] -p <filesystem|volume> <filesystem|volume>\n"
 251                     "\trename -r <snapshot> <snapshot>"));
 252         case HELP_ROLLBACK:
 253                 return (gettext("\trollback [-rRf] <snapshot>\n"));
 254         case HELP_SEND:
 255                 return (gettext("\tsend [-DnPpRrvs] [-[iI] snapshot] "
 256                     "<snapshot>\n"));
 257         case HELP_SET:
 258                 return (gettext("\tset <property=value> "
 259                     "<filesystem|volume|snapshot> ...\n"));
 260         case HELP_SHARE:
 261                 return (gettext("\tshare <-a | filesystem>\n"));
 262         case HELP_SNAPSHOT:
 263                 return (gettext("\tsnapshot [-r] [-o property=value] ... "
 264                     "<filesystem@snapname|volume@snapname> ...\n"));
 265         case HELP_UNMOUNT:
 266                 return (gettext("\tunmount [-f] "
 267                     "<-a | filesystem|mountpoint>\n"));
 268         case HELP_UNSHARE:
 269                 return (gettext("\tunshare "
 270                     "<-a | filesystem|mountpoint>\n"));
 271         case HELP_ALLOW:
 272                 return (gettext("\tallow <filesystem|volume>\n"
 273                     "\tallow [-ldug] "
 274                     "<\"everyone\"|user|group>[,...] <perm|@setname>[,...]\n"
 275                     "\t    <filesystem|volume>\n"
 276                     "\tallow [-ld] -e <perm|@setname>[,...] "
 277                     "<filesystem|volume>\n"
 278                     "\tallow -c <perm|@setname>[,...] <filesystem|volume>\n"
 279                     "\tallow -s @setname <perm|@setname>[,...] "
 280                     "<filesystem|volume>\n"));
 281         case HELP_UNALLOW:
 282                 return (gettext("\tunallow [-rldug] "
 283                     "<\"everyone\"|user|group>[,...]\n"
 284                     "\t    [<perm|@setname>[,...]] <filesystem|volume>\n"
 285                     "\tunallow [-rld] -e [<perm|@setname>[,...]] "
 286                     "<filesystem|volume>\n"
 287                     "\tunallow [-r] -c [<perm|@setname>[,...]] "
 288                     "<filesystem|volume>\n"
 289                     "\tunallow [-r] -s @setname [<perm|@setname>[,...]] "
 290                     "<filesystem|volume>\n"));
 291         case HELP_USERSPACE:
 292                 return (gettext("\tuserspace [-hniHp] [-o field[,...]] "
 293                     "[-sS field] ... [-t type[,...]]\n"
 294                     "\t    <filesystem|snapshot>\n"));
 295         case HELP_GROUPSPACE:
 296                 return (gettext("\tgroupspace [-hniHpU] [-o field[,...]] "
 297                     "[-sS field] ... [-t type[,...]]\n"
 298                     "\t    <filesystem|snapshot>\n"));
 299         case HELP_HOLD:
 300                 return (gettext("\thold [-r] <tag> <snapshot> ...\n"));
 301         case HELP_HOLDS:
 302                 return (gettext("\tholds [-r] <snapshot> ...\n"));
 303         case HELP_RELEASE:
 304                 return (gettext("\trelease [-r] <tag> <snapshot> ...\n"));
 305         case HELP_DIFF:
 306                 return (gettext("\tdiff [-FHt] <snapshot> "
 307                     "[snapshot|filesystem]\n"));
 308         }
 309 
 310         abort();
 311         /* NOTREACHED */
 312 }
 313 
 314 void
 315 nomem(void)
 316 {
 317         (void) fprintf(stderr, gettext("internal error: out of memory\n"));
 318         exit(1);
 319 }
 320 
 321 /*
 322  * Utility function to guarantee malloc() success.
 323  */
 324 
 325 void *
 326 safe_malloc(size_t size)
 327 {
 328         void *data;
 329 
 330         if ((data = calloc(1, size)) == NULL)
 331                 nomem();
 332 
 333         return (data);
 334 }
 335 
 336 static char *
 337 safe_strdup(char *str)
 338 {
 339         char *dupstr = strdup(str);
 340 
 341         if (dupstr == NULL)
 342                 nomem();
 343 
 344         return (dupstr);
 345 }
 346 
 347 /*
 348  * Callback routine that will print out information for each of
 349  * the properties.
 350  */
 351 static int
 352 usage_prop_cb(int prop, void *cb)
 353 {
 354         FILE *fp = cb;
 355 
 356         (void) fprintf(fp, "\t%-15s ", zfs_prop_to_name(prop));
 357 
 358         if (zfs_prop_readonly(prop))
 359                 (void) fprintf(fp, " NO    ");
 360         else
 361                 (void) fprintf(fp, "YES    ");
 362 
 363         if (zfs_prop_inheritable(prop))
 364                 (void) fprintf(fp, "  YES   ");
 365         else
 366                 (void) fprintf(fp, "   NO   ");
 367 
 368         if (zfs_prop_values(prop) == NULL)
 369                 (void) fprintf(fp, "-\n");
 370         else
 371                 (void) fprintf(fp, "%s\n", zfs_prop_values(prop));
 372 
 373         return (ZPROP_CONT);
 374 }
 375 
 376 /*
 377  * Display usage message.  If we're inside a command, display only the usage for
 378  * that command.  Otherwise, iterate over the entire command table and display
 379  * a complete usage message.
 380  */
 381 static void
 382 usage(boolean_t requested)
 383 {
 384         int i;
 385         boolean_t show_properties = B_FALSE;
 386         FILE *fp = requested ? stdout : stderr;
 387 
 388         if (current_command == NULL) {
 389 
 390                 (void) fprintf(fp, gettext("usage: zfs command args ...\n"));
 391                 (void) fprintf(fp,
 392                     gettext("where 'command' is one of the following:\n\n"));
 393 
 394                 for (i = 0; i < NCOMMAND; i++) {
 395                         if (command_table[i].name == NULL)
 396                                 (void) fprintf(fp, "\n");
 397                         else
 398                                 (void) fprintf(fp, "%s",
 399                                     get_usage(command_table[i].usage));
 400                 }
 401 
 402                 (void) fprintf(fp, gettext("\nEach dataset is of the form: "
 403                     "pool/[dataset/]*dataset[@name]\n"));
 404         } else {
 405                 (void) fprintf(fp, gettext("usage:\n"));
 406                 (void) fprintf(fp, "%s", get_usage(current_command->usage));
 407         }
 408 
 409         if (current_command != NULL &&
 410             (strcmp(current_command->name, "set") == 0 ||
 411             strcmp(current_command->name, "get") == 0 ||
 412             strcmp(current_command->name, "inherit") == 0 ||
 413             strcmp(current_command->name, "list") == 0))
 414                 show_properties = B_TRUE;
 415 
 416         if (show_properties) {
 417                 (void) fprintf(fp,
 418                     gettext("\nThe following properties are supported:\n"));
 419 
 420                 (void) fprintf(fp, "\n\t%-14s %s  %s   %s\n\n",
 421                     "PROPERTY", "EDIT", "INHERIT", "VALUES");
 422 
 423                 /* Iterate over all properties */
 424                 (void) zprop_iter(usage_prop_cb, fp, B_FALSE, B_TRUE,
 425                     ZFS_TYPE_DATASET);
 426 
 427                 (void) fprintf(fp, "\t%-15s ", "userused@...");
 428                 (void) fprintf(fp, " NO       NO   <size>\n");
 429                 (void) fprintf(fp, "\t%-15s ", "groupused@...");
 430                 (void) fprintf(fp, " NO       NO   <size>\n");
 431                 (void) fprintf(fp, "\t%-15s ", "userquota@...");
 432                 (void) fprintf(fp, "YES       NO   <size> | none\n");
 433                 (void) fprintf(fp, "\t%-15s ", "groupquota@...");
 434                 (void) fprintf(fp, "YES       NO   <size> | none\n");
 435                 (void) fprintf(fp, "\t%-15s ", "written@<snap>");
 436                 (void) fprintf(fp, " NO       NO   <size>\n");
 437 
 438                 (void) fprintf(fp, gettext("\nSizes are specified in bytes "
 439                     "with standard units such as K, M, G, etc.\n"));
 440                 (void) fprintf(fp, gettext("\nUser-defined properties can "
 441                     "be specified by using a name containing a colon (:).\n"));
 442                 (void) fprintf(fp, gettext("\nThe {user|group}{used|quota}@ "
 443                     "properties must be appended with\n"
 444                     "a user or group specifier of one of these forms:\n"
 445                     "    POSIX name      (eg: \"matt\")\n"
 446                     "    POSIX id        (eg: \"126829\")\n"
 447                     "    SMB name@domain (eg: \"matt@sun\")\n"
 448                     "    SMB SID         (eg: \"S-1-234-567-89\")\n"));
 449         } else {
 450                 (void) fprintf(fp,
 451                     gettext("\nFor the property list, run: %s\n"),
 452                     "zfs set|get");
 453                 (void) fprintf(fp,
 454                     gettext("\nFor the delegated permission list, run: %s\n"),
 455                     "zfs allow|unallow");
 456         }
 457 
 458         /*
 459          * See comments at end of main().
 460          */
 461         if (getenv("ZFS_ABORT") != NULL) {
 462                 (void) printf("dumping core by request\n");
 463                 abort();
 464         }
 465 
 466         exit(requested ? 0 : 2);
 467 }
 468 
 469 static int
 470 parseprop(nvlist_t *props)
 471 {
 472         char *propname = optarg;
 473         char *propval, *strval;
 474 
 475         if ((propval = strchr(propname, '=')) == NULL) {
 476                 (void) fprintf(stderr, gettext("missing "
 477                     "'=' for -o option\n"));
 478                 return (-1);
 479         }
 480         *propval = '\0';
 481         propval++;
 482         if (nvlist_lookup_string(props, propname, &strval) == 0) {
 483                 (void) fprintf(stderr, gettext("property '%s' "
 484                     "specified multiple times\n"), propname);
 485                 return (-1);
 486         }
 487         if (nvlist_add_string(props, propname, propval) != 0)
 488                 nomem();
 489         return (0);
 490 }
 491 
 492 static int
 493 parse_depth(char *opt, int *flags)
 494 {
 495         char *tmp;
 496         int depth;
 497 
 498         depth = (int)strtol(opt, &tmp, 0);
 499         if (*tmp) {
 500                 (void) fprintf(stderr,
 501                     gettext("%s is not an integer\n"), optarg);
 502                 usage(B_FALSE);
 503         }
 504         if (depth < 0) {
 505                 (void) fprintf(stderr,
 506                     gettext("Depth can not be negative.\n"));
 507                 usage(B_FALSE);
 508         }
 509         *flags |= (ZFS_ITER_DEPTH_LIMIT|ZFS_ITER_RECURSE);
 510         return (depth);
 511 }
 512 
 513 #define PROGRESS_DELAY 2                /* seconds */
 514 
 515 static char *pt_reverse = "\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b";
 516 static time_t pt_begin;
 517 static char *pt_header = NULL;
 518 static boolean_t pt_shown;
 519 
 520 static void
 521 start_progress_timer(void)
 522 {
 523         pt_begin = time(NULL) + PROGRESS_DELAY;
 524         pt_shown = B_FALSE;
 525 }
 526 
 527 static void
 528 set_progress_header(char *header)
 529 {
 530         assert(pt_header == NULL);
 531         pt_header = safe_strdup(header);
 532         if (pt_shown) {
 533                 (void) printf("%s: ", header);
 534                 (void) fflush(stdout);
 535         }
 536 }
 537 
 538 static void
 539 update_progress(char *update)
 540 {
 541         if (!pt_shown && time(NULL) > pt_begin) {
 542                 int len = strlen(update);
 543 
 544                 (void) printf("%s: %s%*.*s", pt_header, update, len, len,
 545                     pt_reverse);
 546                 (void) fflush(stdout);
 547                 pt_shown = B_TRUE;
 548         } else if (pt_shown) {
 549                 int len = strlen(update);
 550 
 551                 (void) printf("%s%*.*s", update, len, len, pt_reverse);
 552                 (void) fflush(stdout);
 553         }
 554 }
 555 
 556 static void
 557 finish_progress(char *done)
 558 {
 559         if (pt_shown) {
 560                 (void) printf("%s\n", done);
 561                 (void) fflush(stdout);
 562         }
 563         free(pt_header);
 564         pt_header = NULL;
 565 }
 566 /*
 567  * zfs clone [-p] [-o prop=value] ... <snap> <fs | vol>
 568  *
 569  * Given an existing dataset, create a writable copy whose initial contents
 570  * are the same as the source.  The newly created dataset maintains a
 571  * dependency on the original; the original cannot be destroyed so long as
 572  * the clone exists.
 573  *
 574  * The '-p' flag creates all the non-existing ancestors of the target first.
 575  */
 576 static int
 577 zfs_do_clone(int argc, char **argv)
 578 {
 579         zfs_handle_t *zhp = NULL;
 580         boolean_t parents = B_FALSE;
 581         nvlist_t *props;
 582         int ret = 0;
 583         int c;
 584 
 585         if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0)
 586                 nomem();
 587 
 588         /* check options */
 589         while ((c = getopt(argc, argv, "o:p")) != -1) {
 590                 switch (c) {
 591                 case 'o':
 592                         if (parseprop(props))
 593                                 return (1);
 594                         break;
 595                 case 'p':
 596                         parents = B_TRUE;
 597                         break;
 598                 case '?':
 599                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
 600                             optopt);
 601                         goto usage;
 602                 }
 603         }
 604 
 605         argc -= optind;
 606         argv += optind;
 607 
 608         /* check number of arguments */
 609         if (argc < 1) {
 610                 (void) fprintf(stderr, gettext("missing source dataset "
 611                     "argument\n"));
 612                 goto usage;
 613         }
 614         if (argc < 2) {
 615                 (void) fprintf(stderr, gettext("missing target dataset "
 616                     "argument\n"));
 617                 goto usage;
 618         }
 619         if (argc > 2) {
 620                 (void) fprintf(stderr, gettext("too many arguments\n"));
 621                 goto usage;
 622         }
 623 
 624         /* open the source dataset */
 625         if ((zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_SNAPSHOT)) == NULL)
 626                 return (1);
 627 
 628         if (parents && zfs_name_valid(argv[1], ZFS_TYPE_FILESYSTEM |
 629             ZFS_TYPE_VOLUME)) {
 630                 /*
 631                  * Now create the ancestors of the target dataset.  If the
 632                  * target already exists and '-p' option was used we should not
 633                  * complain.
 634                  */
 635                 if (zfs_dataset_exists(g_zfs, argv[1], ZFS_TYPE_FILESYSTEM |
 636                     ZFS_TYPE_VOLUME))
 637                         return (0);
 638                 if (zfs_create_ancestors(g_zfs, argv[1]) != 0)
 639                         return (1);
 640         }
 641 
 642         /* pass to libzfs */
 643         ret = zfs_clone(zhp, argv[1], props);
 644 
 645         /* create the mountpoint if necessary */
 646         if (ret == 0) {
 647                 zfs_handle_t *clone;
 648 
 649                 clone = zfs_open(g_zfs, argv[1], ZFS_TYPE_DATASET);
 650                 if (clone != NULL) {
 651                         if (zfs_get_type(clone) != ZFS_TYPE_VOLUME)
 652                                 if ((ret = zfs_mount(clone, NULL, 0)) == 0)
 653                                         ret = zfs_share(clone);
 654                         zfs_close(clone);
 655                 }
 656         }
 657 
 658         zfs_close(zhp);
 659         nvlist_free(props);
 660 
 661         return (!!ret);
 662 
 663 usage:
 664         if (zhp)
 665                 zfs_close(zhp);
 666         nvlist_free(props);
 667         usage(B_FALSE);
 668         return (-1);
 669 }
 670 
 671 /*
 672  * zfs create [-p] [-o prop=value] ... fs
 673  * zfs create [-ps] [-b blocksize] [-o prop=value] ... -V vol size
 674  *
 675  * Create a new dataset.  This command can be used to create filesystems
 676  * and volumes.  Snapshot creation is handled by 'zfs snapshot'.
 677  * For volumes, the user must specify a size to be used.
 678  *
 679  * The '-s' flag applies only to volumes, and indicates that we should not try
 680  * to set the reservation for this volume.  By default we set a reservation
 681  * equal to the size for any volume.  For pools with SPA_VERSION >=
 682  * SPA_VERSION_REFRESERVATION, we set a refreservation instead.
 683  *
 684  * The '-p' flag creates all the non-existing ancestors of the target first.
 685  */
 686 static int
 687 zfs_do_create(int argc, char **argv)
 688 {
 689         zfs_type_t type = ZFS_TYPE_FILESYSTEM;
 690         zfs_handle_t *zhp = NULL;
 691         uint64_t volsize;
 692         int c;
 693         boolean_t noreserve = B_FALSE;
 694         boolean_t bflag = B_FALSE;
 695         boolean_t parents = B_FALSE;
 696         int ret = 1;
 697         nvlist_t *props;
 698         uint64_t intval;
 699         int canmount = ZFS_CANMOUNT_OFF;
 700 
 701         if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0)
 702                 nomem();
 703 
 704         /* check options */
 705         while ((c = getopt(argc, argv, ":V:b:so:p")) != -1) {
 706                 switch (c) {
 707                 case 'V':
 708                         type = ZFS_TYPE_VOLUME;
 709                         if (zfs_nicestrtonum(g_zfs, optarg, &intval) != 0) {
 710                                 (void) fprintf(stderr, gettext("bad volume "
 711                                     "size '%s': %s\n"), optarg,
 712                                     libzfs_error_description(g_zfs));
 713                                 goto error;
 714                         }
 715 
 716                         if (nvlist_add_uint64(props,
 717                             zfs_prop_to_name(ZFS_PROP_VOLSIZE), intval) != 0)
 718                                 nomem();
 719                         volsize = intval;
 720                         break;
 721                 case 'p':
 722                         parents = B_TRUE;
 723                         break;
 724                 case 'b':
 725                         bflag = B_TRUE;
 726                         if (zfs_nicestrtonum(g_zfs, optarg, &intval) != 0) {
 727                                 (void) fprintf(stderr, gettext("bad volume "
 728                                     "block size '%s': %s\n"), optarg,
 729                                     libzfs_error_description(g_zfs));
 730                                 goto error;
 731                         }
 732 
 733                         if (nvlist_add_uint64(props,
 734                             zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE),
 735                             intval) != 0)
 736                                 nomem();
 737                         break;
 738                 case 'o':
 739                         if (parseprop(props))
 740                                 goto error;
 741                         break;
 742                 case 's':
 743                         noreserve = B_TRUE;
 744                         break;
 745                 case ':':
 746                         (void) fprintf(stderr, gettext("missing size "
 747                             "argument\n"));
 748                         goto badusage;
 749                 case '?':
 750                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
 751                             optopt);
 752                         goto badusage;
 753                 }
 754         }
 755 
 756         if ((bflag || noreserve) && type != ZFS_TYPE_VOLUME) {
 757                 (void) fprintf(stderr, gettext("'-s' and '-b' can only be "
 758                     "used when creating a volume\n"));
 759                 goto badusage;
 760         }
 761 
 762         argc -= optind;
 763         argv += optind;
 764 
 765         /* check number of arguments */
 766         if (argc == 0) {
 767                 (void) fprintf(stderr, gettext("missing %s argument\n"),
 768                     zfs_type_to_name(type));
 769                 goto badusage;
 770         }
 771         if (argc > 1) {
 772                 (void) fprintf(stderr, gettext("too many arguments\n"));
 773                 goto badusage;
 774         }
 775 
 776         if (type == ZFS_TYPE_VOLUME && !noreserve) {
 777                 zpool_handle_t *zpool_handle;
 778                 uint64_t spa_version;
 779                 char *p;
 780                 zfs_prop_t resv_prop;
 781                 char *strval;
 782 
 783                 if (p = strchr(argv[0], '/'))
 784                         *p = '\0';
 785                 zpool_handle = zpool_open(g_zfs, argv[0]);
 786                 if (p != NULL)
 787                         *p = '/';
 788                 if (zpool_handle == NULL)
 789                         goto error;
 790                 spa_version = zpool_get_prop_int(zpool_handle,
 791                     ZPOOL_PROP_VERSION, NULL);
 792                 zpool_close(zpool_handle);
 793                 if (spa_version >= SPA_VERSION_REFRESERVATION)
 794                         resv_prop = ZFS_PROP_REFRESERVATION;
 795                 else
 796                         resv_prop = ZFS_PROP_RESERVATION;
 797                 volsize = zvol_volsize_to_reservation(volsize, props);
 798 
 799                 if (nvlist_lookup_string(props, zfs_prop_to_name(resv_prop),
 800                     &strval) != 0) {
 801                         if (nvlist_add_uint64(props,
 802                             zfs_prop_to_name(resv_prop), volsize) != 0) {
 803                                 nvlist_free(props);
 804                                 nomem();
 805                         }
 806                 }
 807         }
 808 
 809         if (parents && zfs_name_valid(argv[0], type)) {
 810                 /*
 811                  * Now create the ancestors of target dataset.  If the target
 812                  * already exists and '-p' option was used we should not
 813                  * complain.
 814                  */
 815                 if (zfs_dataset_exists(g_zfs, argv[0], type)) {
 816                         ret = 0;
 817                         goto error;
 818                 }
 819                 if (zfs_create_ancestors(g_zfs, argv[0]) != 0)
 820                         goto error;
 821         }
 822 
 823         /* pass to libzfs */
 824         if (zfs_create(g_zfs, argv[0], type, props) != 0)
 825                 goto error;
 826 
 827         if ((zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_DATASET)) == NULL)
 828                 goto error;
 829 
 830         ret = 0;
 831         /*
 832          * if the user doesn't want the dataset automatically mounted,
 833          * then skip the mount/share step
 834          */
 835         if (zfs_prop_valid_for_type(ZFS_PROP_CANMOUNT, type))
 836                 canmount = zfs_prop_get_int(zhp, ZFS_PROP_CANMOUNT);
 837 
 838         /*
 839          * Mount and/or share the new filesystem as appropriate.  We provide a
 840          * verbose error message to let the user know that their filesystem was
 841          * in fact created, even if we failed to mount or share it.
 842          */
 843         if (canmount == ZFS_CANMOUNT_ON) {
 844                 if (zfs_mount(zhp, NULL, 0) != 0) {
 845                         (void) fprintf(stderr, gettext("filesystem "
 846                             "successfully created, but not mounted\n"));
 847                         ret = 1;
 848                 } else if (zfs_share(zhp) != 0) {
 849                         (void) fprintf(stderr, gettext("filesystem "
 850                             "successfully created, but not shared\n"));
 851                         ret = 1;
 852                 }
 853         }
 854 
 855 error:
 856         if (zhp)
 857                 zfs_close(zhp);
 858         nvlist_free(props);
 859         return (ret);
 860 badusage:
 861         nvlist_free(props);
 862         usage(B_FALSE);
 863         return (2);
 864 }
 865 
 866 /*
 867  * zfs destroy [-rRf] <fs, vol>
 868  * zfs destroy [-rRd] <snap>
 869  *
 870  *      -r      Recursively destroy all children
 871  *      -R      Recursively destroy all dependents, including clones
 872  *      -f      Force unmounting of any dependents
 873  *      -d      If we can't destroy now, mark for deferred destruction
 874  *
 875  * Destroys the given dataset.  By default, it will unmount any filesystems,
 876  * and refuse to destroy a dataset that has any dependents.  A dependent can
 877  * either be a child, or a clone of a child.
 878  */
 879 typedef struct destroy_cbdata {
 880         boolean_t       cb_first;
 881         boolean_t       cb_force;
 882         boolean_t       cb_recurse;
 883         boolean_t       cb_error;
 884         boolean_t       cb_doclones;
 885         zfs_handle_t    *cb_target;
 886         boolean_t       cb_defer_destroy;
 887         boolean_t       cb_verbose;
 888         boolean_t       cb_parsable;
 889         boolean_t       cb_dryrun;
 890         nvlist_t        *cb_nvl;
 891 
 892         /* first snap in contiguous run */
 893         char            *cb_firstsnap;
 894         /* previous snap in contiguous run */
 895         char            *cb_prevsnap;
 896         int64_t         cb_snapused;
 897         char            *cb_snapspec;
 898 } destroy_cbdata_t;
 899 
 900 /*
 901  * Check for any dependents based on the '-r' or '-R' flags.
 902  */
 903 static int
 904 destroy_check_dependent(zfs_handle_t *zhp, void *data)
 905 {
 906         destroy_cbdata_t *cbp = data;
 907         const char *tname = zfs_get_name(cbp->cb_target);
 908         const char *name = zfs_get_name(zhp);
 909 
 910         if (strncmp(tname, name, strlen(tname)) == 0 &&
 911             (name[strlen(tname)] == '/' || name[strlen(tname)] == '@')) {
 912                 /*
 913                  * This is a direct descendant, not a clone somewhere else in
 914                  * the hierarchy.
 915                  */
 916                 if (cbp->cb_recurse)
 917                         goto out;
 918 
 919                 if (cbp->cb_first) {
 920                         (void) fprintf(stderr, gettext("cannot destroy '%s': "
 921                             "%s has children\n"),
 922                             zfs_get_name(cbp->cb_target),
 923                             zfs_type_to_name(zfs_get_type(cbp->cb_target)));
 924                         (void) fprintf(stderr, gettext("use '-r' to destroy "
 925                             "the following datasets:\n"));
 926                         cbp->cb_first = B_FALSE;
 927                         cbp->cb_error = B_TRUE;
 928                 }
 929 
 930                 (void) fprintf(stderr, "%s\n", zfs_get_name(zhp));
 931         } else {
 932                 /*
 933                  * This is a clone.  We only want to report this if the '-r'
 934                  * wasn't specified, or the target is a snapshot.
 935                  */
 936                 if (!cbp->cb_recurse &&
 937                     zfs_get_type(cbp->cb_target) != ZFS_TYPE_SNAPSHOT)
 938                         goto out;
 939 
 940                 if (cbp->cb_first) {
 941                         (void) fprintf(stderr, gettext("cannot destroy '%s': "
 942                             "%s has dependent clones\n"),
 943                             zfs_get_name(cbp->cb_target),
 944                             zfs_type_to_name(zfs_get_type(cbp->cb_target)));
 945                         (void) fprintf(stderr, gettext("use '-R' to destroy "
 946                             "the following datasets:\n"));
 947                         cbp->cb_first = B_FALSE;
 948                         cbp->cb_error = B_TRUE;
 949                         cbp->cb_dryrun = B_TRUE;
 950                 }
 951 
 952                 (void) fprintf(stderr, "%s\n", zfs_get_name(zhp));
 953         }
 954 
 955 out:
 956         zfs_close(zhp);
 957         return (0);
 958 }
 959 
 960 static int
 961 destroy_callback(zfs_handle_t *zhp, void *data)
 962 {
 963         destroy_cbdata_t *cb = data;
 964         const char *name = zfs_get_name(zhp);
 965 
 966         if (cb->cb_verbose) {
 967                 if (cb->cb_parsable) {
 968                         (void) printf("destroy\t%s\n", name);
 969                 } else if (cb->cb_dryrun) {
 970                         (void) printf(gettext("would destroy %s\n"),
 971                             name);
 972                 } else {
 973                         (void) printf(gettext("will destroy %s\n"),
 974                             name);
 975                 }
 976         }
 977 
 978         /*
 979          * Ignore pools (which we've already flagged as an error before getting
 980          * here).
 981          */
 982         if (strchr(zfs_get_name(zhp), '/') == NULL &&
 983             zfs_get_type(zhp) == ZFS_TYPE_FILESYSTEM) {
 984                 zfs_close(zhp);
 985                 return (0);
 986         }
 987 
 988         if (!cb->cb_dryrun) {
 989                 if (zfs_unmount(zhp, NULL, cb->cb_force ? MS_FORCE : 0) != 0 ||
 990                     zfs_destroy(zhp, cb->cb_defer_destroy) != 0) {
 991                         zfs_close(zhp);
 992                         return (-1);
 993                 }
 994         }
 995 
 996         zfs_close(zhp);
 997         return (0);
 998 }
 999 
1000 static int
1001 destroy_print_cb(zfs_handle_t *zhp, void *arg)
1002 {
1003         destroy_cbdata_t *cb = arg;
1004         const char *name = zfs_get_name(zhp);
1005         int err = 0;
1006 
1007         if (nvlist_exists(cb->cb_nvl, name)) {
1008                 if (cb->cb_firstsnap == NULL)
1009                         cb->cb_firstsnap = strdup(name);
1010                 if (cb->cb_prevsnap != NULL)
1011                         free(cb->cb_prevsnap);
1012                 /* this snap continues the current range */
1013                 cb->cb_prevsnap = strdup(name);
1014                 if (cb->cb_firstsnap == NULL || cb->cb_prevsnap == NULL)
1015                         nomem();
1016                 if (cb->cb_verbose) {
1017                         if (cb->cb_parsable) {
1018                                 (void) printf("destroy\t%s\n", name);
1019                         } else if (cb->cb_dryrun) {
1020                                 (void) printf(gettext("would destroy %s\n"),
1021                                     name);
1022                         } else {
1023                                 (void) printf(gettext("will destroy %s\n"),
1024                                     name);
1025                         }
1026                 }
1027         } else if (cb->cb_firstsnap != NULL) {
1028                 /* end of this range */
1029                 uint64_t used = 0;
1030                 err = lzc_snaprange_space(cb->cb_firstsnap,
1031                     cb->cb_prevsnap, &used);
1032                 cb->cb_snapused += used;
1033                 free(cb->cb_firstsnap);
1034                 cb->cb_firstsnap = NULL;
1035                 free(cb->cb_prevsnap);
1036                 cb->cb_prevsnap = NULL;
1037         }
1038         zfs_close(zhp);
1039         return (err);
1040 }
1041 
1042 static int
1043 destroy_print_snapshots(zfs_handle_t *fs_zhp, destroy_cbdata_t *cb)
1044 {
1045         int err = 0;
1046         assert(cb->cb_firstsnap == NULL);
1047         assert(cb->cb_prevsnap == NULL);
1048         err = zfs_iter_snapshots_sorted(fs_zhp, destroy_print_cb, cb);
1049         if (cb->cb_firstsnap != NULL) {
1050                 uint64_t used = 0;
1051                 if (err == 0) {
1052                         err = lzc_snaprange_space(cb->cb_firstsnap,
1053                             cb->cb_prevsnap, &used);
1054                 }
1055                 cb->cb_snapused += used;
1056                 free(cb->cb_firstsnap);
1057                 cb->cb_firstsnap = NULL;
1058                 free(cb->cb_prevsnap);
1059                 cb->cb_prevsnap = NULL;
1060         }
1061         return (err);
1062 }
1063 
1064 static int
1065 snapshot_to_nvl_cb(zfs_handle_t *zhp, void *arg)
1066 {
1067         destroy_cbdata_t *cb = arg;
1068         int err = 0;
1069 
1070         /* Check for clones. */
1071         if (!cb->cb_doclones && !cb->cb_defer_destroy) {
1072                 cb->cb_target = zhp;
1073                 cb->cb_first = B_TRUE;
1074                 err = zfs_iter_dependents(zhp, B_TRUE,
1075                     destroy_check_dependent, cb);
1076         }
1077 
1078         if (err == 0) {
1079                 if (nvlist_add_boolean(cb->cb_nvl, zfs_get_name(zhp)))
1080                         nomem();
1081         }
1082         zfs_close(zhp);
1083         return (err);
1084 }
1085 
1086 static int
1087 gather_snapshots(zfs_handle_t *zhp, void *arg)
1088 {
1089         destroy_cbdata_t *cb = arg;
1090         int err = 0;
1091 
1092         err = zfs_iter_snapspec(zhp, cb->cb_snapspec, snapshot_to_nvl_cb, cb);
1093         if (err == ENOENT)
1094                 err = 0;
1095         if (err != 0)
1096                 goto out;
1097 
1098         if (cb->cb_verbose) {
1099                 err = destroy_print_snapshots(zhp, cb);
1100                 if (err != 0)
1101                         goto out;
1102         }
1103 
1104         if (cb->cb_recurse)
1105                 err = zfs_iter_filesystems(zhp, gather_snapshots, cb);
1106 
1107 out:
1108         zfs_close(zhp);
1109         return (err);
1110 }
1111 
1112 static int
1113 destroy_clones(destroy_cbdata_t *cb)
1114 {
1115         nvpair_t *pair;
1116         for (pair = nvlist_next_nvpair(cb->cb_nvl, NULL);
1117             pair != NULL;
1118             pair = nvlist_next_nvpair(cb->cb_nvl, pair)) {
1119                 zfs_handle_t *zhp = zfs_open(g_zfs, nvpair_name(pair),
1120                     ZFS_TYPE_SNAPSHOT);
1121                 if (zhp != NULL) {
1122                         boolean_t defer = cb->cb_defer_destroy;
1123                         int err = 0;
1124 
1125                         /*
1126                          * We can't defer destroy non-snapshots, so set it to
1127                          * false while destroying the clones.
1128                          */
1129                         cb->cb_defer_destroy = B_FALSE;
1130                         err = zfs_iter_dependents(zhp, B_FALSE,
1131                             destroy_callback, cb);
1132                         cb->cb_defer_destroy = defer;
1133                         zfs_close(zhp);
1134                         if (err != 0)
1135                                 return (err);
1136                 }
1137         }
1138         return (0);
1139 }
1140 
1141 static int
1142 zfs_do_destroy(int argc, char **argv)
1143 {
1144         destroy_cbdata_t cb = { 0 };
1145         int c;
1146         zfs_handle_t *zhp;
1147         char *at;
1148         zfs_type_t type = ZFS_TYPE_DATASET;
1149 
1150         /* check options */
1151         while ((c = getopt(argc, argv, "vpndfrR")) != -1) {
1152                 switch (c) {
1153                 case 'v':
1154                         cb.cb_verbose = B_TRUE;
1155                         break;
1156                 case 'p':
1157                         cb.cb_verbose = B_TRUE;
1158                         cb.cb_parsable = B_TRUE;
1159                         break;
1160                 case 'n':
1161                         cb.cb_dryrun = B_TRUE;
1162                         break;
1163                 case 'd':
1164                         cb.cb_defer_destroy = B_TRUE;
1165                         type = ZFS_TYPE_SNAPSHOT;
1166                         break;
1167                 case 'f':
1168                         cb.cb_force = B_TRUE;
1169                         break;
1170                 case 'r':
1171                         cb.cb_recurse = B_TRUE;
1172                         break;
1173                 case 'R':
1174                         cb.cb_recurse = B_TRUE;
1175                         cb.cb_doclones = B_TRUE;
1176                         break;
1177                 case '?':
1178                 default:
1179                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
1180                             optopt);
1181                         usage(B_FALSE);
1182                 }
1183         }
1184 
1185         argc -= optind;
1186         argv += optind;
1187 
1188         /* check number of arguments */
1189         if (argc == 0) {
1190                 (void) fprintf(stderr, gettext("missing dataset argument\n"));
1191                 usage(B_FALSE);
1192         }
1193         if (argc > 1) {
1194                 (void) fprintf(stderr, gettext("too many arguments\n"));
1195                 usage(B_FALSE);
1196         }
1197 
1198         at = strchr(argv[0], '@');
1199         if (at != NULL) {
1200                 int err = 0;
1201 
1202                 /* Build the list of snaps to destroy in cb_nvl. */
1203                 if (nvlist_alloc(&cb.cb_nvl, NV_UNIQUE_NAME, 0) != 0)
1204                         nomem();
1205 
1206                 *at = '\0';
1207                 zhp = zfs_open(g_zfs, argv[0],
1208                     ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
1209                 if (zhp == NULL)
1210                         return (1);
1211 
1212                 cb.cb_snapspec = at + 1;
1213                 if (gather_snapshots(zfs_handle_dup(zhp), &cb) != 0 ||
1214                     cb.cb_error) {
1215                         zfs_close(zhp);
1216                         nvlist_free(cb.cb_nvl);
1217                         return (1);
1218                 }
1219 
1220                 if (nvlist_empty(cb.cb_nvl)) {
1221                         (void) fprintf(stderr, gettext("could not find any "
1222                             "snapshots to destroy; check snapshot names.\n"));
1223                         zfs_close(zhp);
1224                         nvlist_free(cb.cb_nvl);
1225                         return (1);
1226                 }
1227 
1228                 if (cb.cb_verbose) {
1229                         char buf[16];
1230                         zfs_nicenum(cb.cb_snapused, buf, sizeof (buf));
1231                         if (cb.cb_parsable) {
1232                                 (void) printf("reclaim\t%llu\n",
1233                                     cb.cb_snapused);
1234                         } else if (cb.cb_dryrun) {
1235                                 (void) printf(gettext("would reclaim %s\n"),
1236                                     buf);
1237                         } else {
1238                                 (void) printf(gettext("will reclaim %s\n"),
1239                                     buf);
1240                         }
1241                 }
1242 
1243                 if (!cb.cb_dryrun) {
1244                         if (cb.cb_doclones)
1245                                 err = destroy_clones(&cb);
1246                         if (err == 0) {
1247                                 err = zfs_destroy_snaps_nvl(zhp, cb.cb_nvl,
1248                                     cb.cb_defer_destroy);
1249                         }
1250                 }
1251 
1252                 zfs_close(zhp);
1253                 nvlist_free(cb.cb_nvl);
1254                 if (err != 0)
1255                         return (1);
1256         } else {
1257                 /* Open the given dataset */
1258                 if ((zhp = zfs_open(g_zfs, argv[0], type)) == NULL)
1259                         return (1);
1260 
1261                 cb.cb_target = zhp;
1262 
1263                 /*
1264                  * Perform an explicit check for pools before going any further.
1265                  */
1266                 if (!cb.cb_recurse && strchr(zfs_get_name(zhp), '/') == NULL &&
1267                     zfs_get_type(zhp) == ZFS_TYPE_FILESYSTEM) {
1268                         (void) fprintf(stderr, gettext("cannot destroy '%s': "
1269                             "operation does not apply to pools\n"),
1270                             zfs_get_name(zhp));
1271                         (void) fprintf(stderr, gettext("use 'zfs destroy -r "
1272                             "%s' to destroy all datasets in the pool\n"),
1273                             zfs_get_name(zhp));
1274                         (void) fprintf(stderr, gettext("use 'zpool destroy %s' "
1275                             "to destroy the pool itself\n"), zfs_get_name(zhp));
1276                         zfs_close(zhp);
1277                         return (1);
1278                 }
1279 
1280                 /*
1281                  * Check for any dependents and/or clones.
1282                  */
1283                 cb.cb_first = B_TRUE;
1284                 if (!cb.cb_doclones &&
1285                     zfs_iter_dependents(zhp, B_TRUE, destroy_check_dependent,
1286                     &cb) != 0) {
1287                         zfs_close(zhp);
1288                         return (1);
1289                 }
1290 
1291                 if (cb.cb_error) {
1292                         zfs_close(zhp);
1293                         return (1);
1294                 }
1295 
1296                 if (zfs_iter_dependents(zhp, B_FALSE, destroy_callback,
1297                     &cb) != 0) {
1298                         zfs_close(zhp);
1299                         return (1);
1300                 }
1301 
1302                 /*
1303                  * Do the real thing.  The callback will close the
1304                  * handle regardless of whether it succeeds or not.
1305                  */
1306                 if (destroy_callback(zhp, &cb) != 0)
1307                         return (1);
1308         }
1309 
1310         return (0);
1311 }
1312 
1313 static boolean_t
1314 is_recvd_column(zprop_get_cbdata_t *cbp)
1315 {
1316         int i;
1317         zfs_get_column_t col;
1318 
1319         for (i = 0; i < ZFS_GET_NCOLS &&
1320             (col = cbp->cb_columns[i]) != GET_COL_NONE; i++)
1321                 if (col == GET_COL_RECVD)
1322                         return (B_TRUE);
1323         return (B_FALSE);
1324 }
1325 
1326 /*
1327  * zfs get [-rHp] [-o all | field[,field]...] [-s source[,source]...]
1328  *      < all | property[,property]... > < fs | snap | vol > ...
1329  *
1330  *      -r      recurse over any child datasets
1331  *      -H      scripted mode.  Headers are stripped, and fields are separated
1332  *              by tabs instead of spaces.
1333  *      -o      Set of fields to display.  One of "name,property,value,
1334  *              received,source". Default is "name,property,value,source".
1335  *              "all" is an alias for all five.
1336  *      -s      Set of sources to allow.  One of
1337  *              "local,default,inherited,received,temporary,none".  Default is
1338  *              all six.
1339  *      -p      Display values in parsable (literal) format.
1340  *
1341  *  Prints properties for the given datasets.  The user can control which
1342  *  columns to display as well as which property types to allow.
1343  */
1344 
1345 /*
1346  * Invoked to display the properties for a single dataset.
1347  */
1348 static int
1349 get_callback(zfs_handle_t *zhp, void *data)
1350 {
1351         char buf[ZFS_MAXPROPLEN];
1352         char rbuf[ZFS_MAXPROPLEN];
1353         zprop_source_t sourcetype;
1354         char source[ZFS_MAXNAMELEN];
1355         zprop_get_cbdata_t *cbp = data;
1356         nvlist_t *user_props = zfs_get_user_props(zhp);
1357         zprop_list_t *pl = cbp->cb_proplist;
1358         nvlist_t *propval;
1359         char *strval;
1360         char *sourceval;
1361         boolean_t received = is_recvd_column(cbp);
1362 
1363         for (; pl != NULL; pl = pl->pl_next) {
1364                 char *recvdval = NULL;
1365                 /*
1366                  * Skip the special fake placeholder.  This will also skip over
1367                  * the name property when 'all' is specified.
1368                  */
1369                 if (pl->pl_prop == ZFS_PROP_NAME &&
1370                     pl == cbp->cb_proplist)
1371                         continue;
1372 
1373                 if (pl->pl_prop != ZPROP_INVAL) {
1374                         if (zfs_prop_get(zhp, pl->pl_prop, buf,
1375                             sizeof (buf), &sourcetype, source,
1376                             sizeof (source),
1377                             cbp->cb_literal) != 0) {
1378                                 if (pl->pl_all)
1379                                         continue;
1380                                 if (!zfs_prop_valid_for_type(pl->pl_prop,
1381                                     ZFS_TYPE_DATASET)) {
1382                                         (void) fprintf(stderr,
1383                                             gettext("No such property '%s'\n"),
1384                                             zfs_prop_to_name(pl->pl_prop));
1385                                         continue;
1386                                 }
1387                                 sourcetype = ZPROP_SRC_NONE;
1388                                 (void) strlcpy(buf, "-", sizeof (buf));
1389                         }
1390 
1391                         if (received && (zfs_prop_get_recvd(zhp,
1392                             zfs_prop_to_name(pl->pl_prop), rbuf, sizeof (rbuf),
1393                             cbp->cb_literal) == 0))
1394                                 recvdval = rbuf;
1395 
1396                         zprop_print_one_property(zfs_get_name(zhp), cbp,
1397                             zfs_prop_to_name(pl->pl_prop),
1398                             buf, sourcetype, source, recvdval);
1399                 } else if (zfs_prop_userquota(pl->pl_user_prop)) {
1400                         sourcetype = ZPROP_SRC_LOCAL;
1401 
1402                         if (zfs_prop_get_userquota(zhp, pl->pl_user_prop,
1403                             buf, sizeof (buf), cbp->cb_literal) != 0) {
1404                                 sourcetype = ZPROP_SRC_NONE;
1405                                 (void) strlcpy(buf, "-", sizeof (buf));
1406                         }
1407 
1408                         zprop_print_one_property(zfs_get_name(zhp), cbp,
1409                             pl->pl_user_prop, buf, sourcetype, source, NULL);
1410                 } else if (zfs_prop_written(pl->pl_user_prop)) {
1411                         sourcetype = ZPROP_SRC_LOCAL;
1412 
1413                         if (zfs_prop_get_written(zhp, pl->pl_user_prop,
1414                             buf, sizeof (buf), cbp->cb_literal) != 0) {
1415                                 sourcetype = ZPROP_SRC_NONE;
1416                                 (void) strlcpy(buf, "-", sizeof (buf));
1417                         }
1418 
1419                         zprop_print_one_property(zfs_get_name(zhp), cbp,
1420                             pl->pl_user_prop, buf, sourcetype, source, NULL);
1421                 } else {
1422                         if (nvlist_lookup_nvlist(user_props,
1423                             pl->pl_user_prop, &propval) != 0) {
1424                                 if (pl->pl_all)
1425                                         continue;
1426                                 sourcetype = ZPROP_SRC_NONE;
1427                                 strval = "-";
1428                         } else {
1429                                 verify(nvlist_lookup_string(propval,
1430                                     ZPROP_VALUE, &strval) == 0);
1431                                 verify(nvlist_lookup_string(propval,
1432                                     ZPROP_SOURCE, &sourceval) == 0);
1433 
1434                                 if (strcmp(sourceval,
1435                                     zfs_get_name(zhp)) == 0) {
1436                                         sourcetype = ZPROP_SRC_LOCAL;
1437                                 } else if (strcmp(sourceval,
1438                                     ZPROP_SOURCE_VAL_RECVD) == 0) {
1439                                         sourcetype = ZPROP_SRC_RECEIVED;
1440                                 } else {
1441                                         sourcetype = ZPROP_SRC_INHERITED;
1442                                         (void) strlcpy(source,
1443                                             sourceval, sizeof (source));
1444                                 }
1445                         }
1446 
1447                         if (received && (zfs_prop_get_recvd(zhp,
1448                             pl->pl_user_prop, rbuf, sizeof (rbuf),
1449                             cbp->cb_literal) == 0))
1450                                 recvdval = rbuf;
1451 
1452                         zprop_print_one_property(zfs_get_name(zhp), cbp,
1453                             pl->pl_user_prop, strval, sourcetype,
1454                             source, recvdval);
1455                 }
1456         }
1457 
1458         return (0);
1459 }
1460 
1461 static int
1462 zfs_do_get(int argc, char **argv)
1463 {
1464         zprop_get_cbdata_t cb = { 0 };
1465         int i, c, flags = ZFS_ITER_ARGS_CAN_BE_PATHS;
1466         int types = ZFS_TYPE_DATASET;
1467         char *value, *fields;
1468         int ret = 0;
1469         int limit = 0;
1470         zprop_list_t fake_name = { 0 };
1471 
1472         /*
1473          * Set up default columns and sources.
1474          */
1475         cb.cb_sources = ZPROP_SRC_ALL;
1476         cb.cb_columns[0] = GET_COL_NAME;
1477         cb.cb_columns[1] = GET_COL_PROPERTY;
1478         cb.cb_columns[2] = GET_COL_VALUE;
1479         cb.cb_columns[3] = GET_COL_SOURCE;
1480         cb.cb_type = ZFS_TYPE_DATASET;
1481 
1482         /* check options */
1483         while ((c = getopt(argc, argv, ":d:o:s:rt:Hp")) != -1) {
1484                 switch (c) {
1485                 case 'p':
1486                         cb.cb_literal = B_TRUE;
1487                         break;
1488                 case 'd':
1489                         limit = parse_depth(optarg, &flags);
1490                         break;
1491                 case 'r':
1492                         flags |= ZFS_ITER_RECURSE;
1493                         break;
1494                 case 'H':
1495                         cb.cb_scripted = B_TRUE;
1496                         break;
1497                 case ':':
1498                         (void) fprintf(stderr, gettext("missing argument for "
1499                             "'%c' option\n"), optopt);
1500                         usage(B_FALSE);
1501                         break;
1502                 case 'o':
1503                         /*
1504                          * Process the set of columns to display.  We zero out
1505                          * the structure to give us a blank slate.
1506                          */
1507                         bzero(&cb.cb_columns, sizeof (cb.cb_columns));
1508                         i = 0;
1509                         while (*optarg != '\0') {
1510                                 static char *col_subopts[] =
1511                                     { "name", "property", "value", "received",
1512                                     "source", "all", NULL };
1513 
1514                                 if (i == ZFS_GET_NCOLS) {
1515                                         (void) fprintf(stderr, gettext("too "
1516                                             "many fields given to -o "
1517                                             "option\n"));
1518                                         usage(B_FALSE);
1519                                 }
1520 
1521                                 switch (getsubopt(&optarg, col_subopts,
1522                                     &value)) {
1523                                 case 0:
1524                                         cb.cb_columns[i++] = GET_COL_NAME;
1525                                         break;
1526                                 case 1:
1527                                         cb.cb_columns[i++] = GET_COL_PROPERTY;
1528                                         break;
1529                                 case 2:
1530                                         cb.cb_columns[i++] = GET_COL_VALUE;
1531                                         break;
1532                                 case 3:
1533                                         cb.cb_columns[i++] = GET_COL_RECVD;
1534                                         flags |= ZFS_ITER_RECVD_PROPS;
1535                                         break;
1536                                 case 4:
1537                                         cb.cb_columns[i++] = GET_COL_SOURCE;
1538                                         break;
1539                                 case 5:
1540                                         if (i > 0) {
1541                                                 (void) fprintf(stderr,
1542                                                     gettext("\"all\" conflicts "
1543                                                     "with specific fields "
1544                                                     "given to -o option\n"));
1545                                                 usage(B_FALSE);
1546                                         }
1547                                         cb.cb_columns[0] = GET_COL_NAME;
1548                                         cb.cb_columns[1] = GET_COL_PROPERTY;
1549                                         cb.cb_columns[2] = GET_COL_VALUE;
1550                                         cb.cb_columns[3] = GET_COL_RECVD;
1551                                         cb.cb_columns[4] = GET_COL_SOURCE;
1552                                         flags |= ZFS_ITER_RECVD_PROPS;
1553                                         i = ZFS_GET_NCOLS;
1554                                         break;
1555                                 default:
1556                                         (void) fprintf(stderr,
1557                                             gettext("invalid column name "
1558                                             "'%s'\n"), value);
1559                                         usage(B_FALSE);
1560                                 }
1561                         }
1562                         break;
1563 
1564                 case 's':
1565                         cb.cb_sources = 0;
1566                         while (*optarg != '\0') {
1567                                 static char *source_subopts[] = {
1568                                         "local", "default", "inherited",
1569                                         "received", "temporary", "none",
1570                                         NULL };
1571 
1572                                 switch (getsubopt(&optarg, source_subopts,
1573                                     &value)) {
1574                                 case 0:
1575                                         cb.cb_sources |= ZPROP_SRC_LOCAL;
1576                                         break;
1577                                 case 1:
1578                                         cb.cb_sources |= ZPROP_SRC_DEFAULT;
1579                                         break;
1580                                 case 2:
1581                                         cb.cb_sources |= ZPROP_SRC_INHERITED;
1582                                         break;
1583                                 case 3:
1584                                         cb.cb_sources |= ZPROP_SRC_RECEIVED;
1585                                         break;
1586                                 case 4:
1587                                         cb.cb_sources |= ZPROP_SRC_TEMPORARY;
1588                                         break;
1589                                 case 5:
1590                                         cb.cb_sources |= ZPROP_SRC_NONE;
1591                                         break;
1592                                 default:
1593                                         (void) fprintf(stderr,
1594                                             gettext("invalid source "
1595                                             "'%s'\n"), value);
1596                                         usage(B_FALSE);
1597                                 }
1598                         }
1599                         break;
1600 
1601                 case 't':
1602                         types = 0;
1603                         flags &= ~ZFS_ITER_PROP_LISTSNAPS;
1604                         while (*optarg != '\0') {
1605                                 static char *type_subopts[] = { "filesystem",
1606                                     "volume", "snapshot", "all", NULL };
1607 
1608                                 switch (getsubopt(&optarg, type_subopts,
1609                                     &value)) {
1610                                 case 0:
1611                                         types |= ZFS_TYPE_FILESYSTEM;
1612                                         break;
1613                                 case 1:
1614                                         types |= ZFS_TYPE_VOLUME;
1615                                         break;
1616                                 case 2:
1617                                         types |= ZFS_TYPE_SNAPSHOT;
1618                                         break;
1619                                 case 3:
1620                                         types = ZFS_TYPE_DATASET;
1621                                         break;
1622 
1623                                 default:
1624                                         (void) fprintf(stderr,
1625                                             gettext("invalid type '%s'\n"),
1626                                             value);
1627                                         usage(B_FALSE);
1628                                 }
1629                         }
1630                         break;
1631 
1632                 case '?':
1633                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
1634                             optopt);
1635                         usage(B_FALSE);
1636                 }
1637         }
1638 
1639         argc -= optind;
1640         argv += optind;
1641 
1642         if (argc < 1) {
1643                 (void) fprintf(stderr, gettext("missing property "
1644                     "argument\n"));
1645                 usage(B_FALSE);
1646         }
1647 
1648         fields = argv[0];
1649 
1650         if (zprop_get_list(g_zfs, fields, &cb.cb_proplist, ZFS_TYPE_DATASET)
1651             != 0)
1652                 usage(B_FALSE);
1653 
1654         argc--;
1655         argv++;
1656 
1657         /*
1658          * As part of zfs_expand_proplist(), we keep track of the maximum column
1659          * width for each property.  For the 'NAME' (and 'SOURCE') columns, we
1660          * need to know the maximum name length.  However, the user likely did
1661          * not specify 'name' as one of the properties to fetch, so we need to
1662          * make sure we always include at least this property for
1663          * print_get_headers() to work properly.
1664          */
1665         if (cb.cb_proplist != NULL) {
1666                 fake_name.pl_prop = ZFS_PROP_NAME;
1667                 fake_name.pl_width = strlen(gettext("NAME"));
1668                 fake_name.pl_next = cb.cb_proplist;
1669                 cb.cb_proplist = &fake_name;
1670         }
1671 
1672         cb.cb_first = B_TRUE;
1673 
1674         /* run for each object */
1675         ret = zfs_for_each(argc, argv, flags, types, NULL,
1676             &cb.cb_proplist, limit, get_callback, &cb);
1677 
1678         if (cb.cb_proplist == &fake_name)
1679                 zprop_free_list(fake_name.pl_next);
1680         else
1681                 zprop_free_list(cb.cb_proplist);
1682 
1683         return (ret);
1684 }
1685 
1686 /*
1687  * inherit [-rS] <property> <fs|vol> ...
1688  *
1689  *      -r      Recurse over all children
1690  *      -S      Revert to received value, if any
1691  *
1692  * For each dataset specified on the command line, inherit the given property
1693  * from its parent.  Inheriting a property at the pool level will cause it to
1694  * use the default value.  The '-r' flag will recurse over all children, and is
1695  * useful for setting a property on a hierarchy-wide basis, regardless of any
1696  * local modifications for each dataset.
1697  */
1698 
1699 typedef struct inherit_cbdata {
1700         const char *cb_propname;
1701         boolean_t cb_received;
1702 } inherit_cbdata_t;
1703 
1704 static int
1705 inherit_recurse_cb(zfs_handle_t *zhp, void *data)
1706 {
1707         inherit_cbdata_t *cb = data;
1708         zfs_prop_t prop = zfs_name_to_prop(cb->cb_propname);
1709 
1710         /*
1711          * If we're doing it recursively, then ignore properties that
1712          * are not valid for this type of dataset.
1713          */
1714         if (prop != ZPROP_INVAL &&
1715             !zfs_prop_valid_for_type(prop, zfs_get_type(zhp)))
1716                 return (0);
1717 
1718         return (zfs_prop_inherit(zhp, cb->cb_propname, cb->cb_received) != 0);
1719 }
1720 
1721 static int
1722 inherit_cb(zfs_handle_t *zhp, void *data)
1723 {
1724         inherit_cbdata_t *cb = data;
1725 
1726         return (zfs_prop_inherit(zhp, cb->cb_propname, cb->cb_received) != 0);
1727 }
1728 
1729 static int
1730 zfs_do_inherit(int argc, char **argv)
1731 {
1732         int c;
1733         zfs_prop_t prop;
1734         inherit_cbdata_t cb = { 0 };
1735         char *propname;
1736         int ret = 0;
1737         int flags = 0;
1738         boolean_t received = B_FALSE;
1739 
1740         /* check options */
1741         while ((c = getopt(argc, argv, "rS")) != -1) {
1742                 switch (c) {
1743                 case 'r':
1744                         flags |= ZFS_ITER_RECURSE;
1745                         break;
1746                 case 'S':
1747                         received = B_TRUE;
1748                         break;
1749                 case '?':
1750                 default:
1751                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
1752                             optopt);
1753                         usage(B_FALSE);
1754                 }
1755         }
1756 
1757         argc -= optind;
1758         argv += optind;
1759 
1760         /* check number of arguments */
1761         if (argc < 1) {
1762                 (void) fprintf(stderr, gettext("missing property argument\n"));
1763                 usage(B_FALSE);
1764         }
1765         if (argc < 2) {
1766                 (void) fprintf(stderr, gettext("missing dataset argument\n"));
1767                 usage(B_FALSE);
1768         }
1769 
1770         propname = argv[0];
1771         argc--;
1772         argv++;
1773 
1774         if ((prop = zfs_name_to_prop(propname)) != ZPROP_INVAL) {
1775                 if (zfs_prop_readonly(prop)) {
1776                         (void) fprintf(stderr, gettext(
1777                             "%s property is read-only\n"),
1778                             propname);
1779                         return (1);
1780                 }
1781                 if (!zfs_prop_inheritable(prop) && !received) {
1782                         (void) fprintf(stderr, gettext("'%s' property cannot "
1783                             "be inherited\n"), propname);
1784                         if (prop == ZFS_PROP_QUOTA ||
1785                             prop == ZFS_PROP_RESERVATION ||
1786                             prop == ZFS_PROP_REFQUOTA ||
1787                             prop == ZFS_PROP_REFRESERVATION)
1788                                 (void) fprintf(stderr, gettext("use 'zfs set "
1789                                     "%s=none' to clear\n"), propname);
1790                         return (1);
1791                 }
1792                 if (received && (prop == ZFS_PROP_VOLSIZE ||
1793                     prop == ZFS_PROP_VERSION)) {
1794                         (void) fprintf(stderr, gettext("'%s' property cannot "
1795                             "be reverted to a received value\n"), propname);
1796                         return (1);
1797                 }
1798         } else if (!zfs_prop_user(propname)) {
1799                 (void) fprintf(stderr, gettext("invalid property '%s'\n"),
1800                     propname);
1801                 usage(B_FALSE);
1802         }
1803 
1804         cb.cb_propname = propname;
1805         cb.cb_received = received;
1806 
1807         if (flags & ZFS_ITER_RECURSE) {
1808                 ret = zfs_for_each(argc, argv, flags, ZFS_TYPE_DATASET,
1809                     NULL, NULL, 0, inherit_recurse_cb, &cb);
1810         } else {
1811                 ret = zfs_for_each(argc, argv, flags, ZFS_TYPE_DATASET,
1812                     NULL, NULL, 0, inherit_cb, &cb);
1813         }
1814 
1815         return (ret);
1816 }
1817 
1818 typedef struct upgrade_cbdata {
1819         uint64_t cb_numupgraded;
1820         uint64_t cb_numsamegraded;
1821         uint64_t cb_numfailed;
1822         uint64_t cb_version;
1823         boolean_t cb_newer;
1824         boolean_t cb_foundone;
1825         char cb_lastfs[ZFS_MAXNAMELEN];
1826 } upgrade_cbdata_t;
1827 
1828 static int
1829 same_pool(zfs_handle_t *zhp, const char *name)
1830 {
1831         int len1 = strcspn(name, "/@");
1832         const char *zhname = zfs_get_name(zhp);
1833         int len2 = strcspn(zhname, "/@");
1834 
1835         if (len1 != len2)
1836                 return (B_FALSE);
1837         return (strncmp(name, zhname, len1) == 0);
1838 }
1839 
1840 static int
1841 upgrade_list_callback(zfs_handle_t *zhp, void *data)
1842 {
1843         upgrade_cbdata_t *cb = data;
1844         int version = zfs_prop_get_int(zhp, ZFS_PROP_VERSION);
1845 
1846         /* list if it's old/new */
1847         if ((!cb->cb_newer && version < ZPL_VERSION) ||
1848             (cb->cb_newer && version > ZPL_VERSION)) {
1849                 char *str;
1850                 if (cb->cb_newer) {
1851                         str = gettext("The following filesystems are "
1852                             "formatted using a newer software version and\n"
1853                             "cannot be accessed on the current system.\n\n");
1854                 } else {
1855                         str = gettext("The following filesystems are "
1856                             "out of date, and can be upgraded.  After being\n"
1857                             "upgraded, these filesystems (and any 'zfs send' "
1858                             "streams generated from\n"
1859                             "subsequent snapshots) will no longer be "
1860                             "accessible by older software versions.\n\n");
1861                 }
1862 
1863                 if (!cb->cb_foundone) {
1864                         (void) puts(str);
1865                         (void) printf(gettext("VER  FILESYSTEM\n"));
1866                         (void) printf(gettext("---  ------------\n"));
1867                         cb->cb_foundone = B_TRUE;
1868                 }
1869 
1870                 (void) printf("%2u   %s\n", version, zfs_get_name(zhp));
1871         }
1872 
1873         return (0);
1874 }
1875 
1876 static int
1877 upgrade_set_callback(zfs_handle_t *zhp, void *data)
1878 {
1879         upgrade_cbdata_t *cb = data;
1880         int version = zfs_prop_get_int(zhp, ZFS_PROP_VERSION);
1881         int needed_spa_version;
1882         int spa_version;
1883 
1884         if (zfs_spa_version(zhp, &spa_version) < 0)
1885                 return (-1);
1886 
1887         needed_spa_version = zfs_spa_version_map(cb->cb_version);
1888 
1889         if (needed_spa_version < 0)
1890                 return (-1);
1891 
1892         if (spa_version < needed_spa_version) {
1893                 /* can't upgrade */
1894                 (void) printf(gettext("%s: can not be "
1895                     "upgraded; the pool version needs to first "
1896                     "be upgraded\nto version %d\n\n"),
1897                     zfs_get_name(zhp), needed_spa_version);
1898                 cb->cb_numfailed++;
1899                 return (0);
1900         }
1901 
1902         /* upgrade */
1903         if (version < cb->cb_version) {
1904                 char verstr[16];
1905                 (void) snprintf(verstr, sizeof (verstr),
1906                     "%llu", cb->cb_version);
1907                 if (cb->cb_lastfs[0] && !same_pool(zhp, cb->cb_lastfs)) {
1908                         /*
1909                          * If they did "zfs upgrade -a", then we could
1910                          * be doing ioctls to different pools.  We need
1911                          * to log this history once to each pool, and bypass
1912                          * the normal history logging that happens in main().
1913                          */
1914                         (void) zpool_log_history(g_zfs, history_str);
1915                         log_history = B_FALSE;
1916                 }
1917                 if (zfs_prop_set(zhp, "version", verstr) == 0)
1918                         cb->cb_numupgraded++;
1919                 else
1920                         cb->cb_numfailed++;
1921                 (void) strcpy(cb->cb_lastfs, zfs_get_name(zhp));
1922         } else if (version > cb->cb_version) {
1923                 /* can't downgrade */
1924                 (void) printf(gettext("%s: can not be downgraded; "
1925                     "it is already at version %u\n"),
1926                     zfs_get_name(zhp), version);
1927                 cb->cb_numfailed++;
1928         } else {
1929                 cb->cb_numsamegraded++;
1930         }
1931         return (0);
1932 }
1933 
1934 /*
1935  * zfs upgrade
1936  * zfs upgrade -v
1937  * zfs upgrade [-r] [-V <version>] <-a | filesystem>
1938  */
1939 static int
1940 zfs_do_upgrade(int argc, char **argv)
1941 {
1942         boolean_t all = B_FALSE;
1943         boolean_t showversions = B_FALSE;
1944         int ret = 0;
1945         upgrade_cbdata_t cb = { 0 };
1946         char c;
1947         int flags = ZFS_ITER_ARGS_CAN_BE_PATHS;
1948 
1949         /* check options */
1950         while ((c = getopt(argc, argv, "rvV:a")) != -1) {
1951                 switch (c) {
1952                 case 'r':
1953                         flags |= ZFS_ITER_RECURSE;
1954                         break;
1955                 case 'v':
1956                         showversions = B_TRUE;
1957                         break;
1958                 case 'V':
1959                         if (zfs_prop_string_to_index(ZFS_PROP_VERSION,
1960                             optarg, &cb.cb_version) != 0) {
1961                                 (void) fprintf(stderr,
1962                                     gettext("invalid version %s\n"), optarg);
1963                                 usage(B_FALSE);
1964                         }
1965                         break;
1966                 case 'a':
1967                         all = B_TRUE;
1968                         break;
1969                 case '?':
1970                 default:
1971                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
1972                             optopt);
1973                         usage(B_FALSE);
1974                 }
1975         }
1976 
1977         argc -= optind;
1978         argv += optind;
1979 
1980         if ((!all && !argc) && ((flags & ZFS_ITER_RECURSE) | cb.cb_version))
1981                 usage(B_FALSE);
1982         if (showversions && (flags & ZFS_ITER_RECURSE || all ||
1983             cb.cb_version || argc))
1984                 usage(B_FALSE);
1985         if ((all || argc) && (showversions))
1986                 usage(B_FALSE);
1987         if (all && argc)
1988                 usage(B_FALSE);
1989 
1990         if (showversions) {
1991                 /* Show info on available versions. */
1992                 (void) printf(gettext("The following filesystem versions are "
1993                     "supported:\n\n"));
1994                 (void) printf(gettext("VER  DESCRIPTION\n"));
1995                 (void) printf("---  -----------------------------------------"
1996                     "---------------\n");
1997                 (void) printf(gettext(" 1   Initial ZFS filesystem version\n"));
1998                 (void) printf(gettext(" 2   Enhanced directory entries\n"));
1999                 (void) printf(gettext(" 3   Case insensitive and filesystem "
2000                     "user identifier (FUID)\n"));
2001                 (void) printf(gettext(" 4   userquota, groupquota "
2002                     "properties\n"));
2003                 (void) printf(gettext(" 5   System attributes\n"));
2004                 (void) printf(gettext("\nFor more information on a particular "
2005                     "version, including supported releases,\n"));
2006                 (void) printf("see the ZFS Administration Guide.\n\n");
2007                 ret = 0;
2008         } else if (argc || all) {
2009                 /* Upgrade filesystems */
2010                 if (cb.cb_version == 0)
2011                         cb.cb_version = ZPL_VERSION;
2012                 ret = zfs_for_each(argc, argv, flags, ZFS_TYPE_FILESYSTEM,
2013                     NULL, NULL, 0, upgrade_set_callback, &cb);
2014                 (void) printf(gettext("%llu filesystems upgraded\n"),
2015                     cb.cb_numupgraded);
2016                 if (cb.cb_numsamegraded) {
2017                         (void) printf(gettext("%llu filesystems already at "
2018                             "this version\n"),
2019                             cb.cb_numsamegraded);
2020                 }
2021                 if (cb.cb_numfailed != 0)
2022                         ret = 1;
2023         } else {
2024                 /* List old-version filesytems */
2025                 boolean_t found;
2026                 (void) printf(gettext("This system is currently running "
2027                     "ZFS filesystem version %llu.\n\n"), ZPL_VERSION);
2028 
2029                 flags |= ZFS_ITER_RECURSE;
2030                 ret = zfs_for_each(0, NULL, flags, ZFS_TYPE_FILESYSTEM,
2031                     NULL, NULL, 0, upgrade_list_callback, &cb);
2032 
2033                 found = cb.cb_foundone;
2034                 cb.cb_foundone = B_FALSE;
2035                 cb.cb_newer = B_TRUE;
2036 
2037                 ret = zfs_for_each(0, NULL, flags, ZFS_TYPE_FILESYSTEM,
2038                     NULL, NULL, 0, upgrade_list_callback, &cb);
2039 
2040                 if (!cb.cb_foundone && !found) {
2041                         (void) printf(gettext("All filesystems are "
2042                             "formatted with the current version.\n"));
2043                 }
2044         }
2045 
2046         return (ret);
2047 }
2048 
2049 #define USTYPE_USR_BIT (0)
2050 #define USTYPE_GRP_BIT (1)
2051 #define USTYPE_PSX_BIT (2)
2052 #define USTYPE_SMB_BIT (3)
2053 
2054 #define USTYPE_USR (1 << USTYPE_USR_BIT)
2055 #define USTYPE_GRP (1 << USTYPE_GRP_BIT)
2056 
2057 #define USTYPE_PSX (1 << USTYPE_PSX_BIT)
2058 #define USTYPE_SMB (1 << USTYPE_SMB_BIT)
2059 
2060 #define USTYPE_PSX_USR (USTYPE_PSX | USTYPE_USR)
2061 #define USTYPE_SMB_USR (USTYPE_SMB | USTYPE_USR)
2062 #define USTYPE_PSX_GRP (USTYPE_PSX | USTYPE_GRP)
2063 #define USTYPE_SMB_GRP (USTYPE_SMB | USTYPE_GRP)
2064 #define USTYPE_ALL (USTYPE_PSX_USR | USTYPE_SMB_USR \
2065                 | USTYPE_PSX_GRP | USTYPE_SMB_GRP)
2066 
2067 
2068 #define USPROP_USED_BIT (0)
2069 #define USPROP_QUOTA_BIT (1)
2070 
2071 #define USPROP_USED (1 << USPROP_USED_BIT)
2072 #define USPROP_QUOTA (1 << USPROP_QUOTA_BIT)
2073 
2074 typedef struct us_node {
2075         nvlist_t        *usn_nvl;
2076         uu_avl_node_t   usn_avlnode;
2077         uu_list_node_t  usn_listnode;
2078 } us_node_t;
2079 
2080 typedef struct us_cbdata {
2081         nvlist_t                **cb_nvlp;
2082         uu_avl_pool_t           *cb_avl_pool;
2083         uu_avl_t                *cb_avl;
2084         boolean_t               cb_numname;
2085         boolean_t               cb_nicenum;
2086         boolean_t               cb_sid2posix;
2087         zfs_userquota_prop_t    cb_prop;
2088         zfs_sort_column_t       *cb_sortcol;
2089         size_t                  cb_max_typelen;
2090         size_t                  cb_max_namelen;
2091         size_t                  cb_max_usedlen;
2092         size_t                  cb_max_quotalen;
2093 } us_cbdata_t;
2094 
2095 typedef struct {
2096         zfs_sort_column_t *si_sortcol;
2097         boolean_t si_num_name;
2098         boolean_t si_parsable;
2099 } us_sort_info_t;
2100 
2101 static int
2102 us_compare(const void *larg, const void *rarg, void *unused)
2103 {
2104         const us_node_t *l = larg;
2105         const us_node_t *r = rarg;
2106         int rc = 0;
2107         us_sort_info_t *si = (us_sort_info_t *)unused;
2108         zfs_sort_column_t *sortcol = si->si_sortcol;
2109         boolean_t num_name = si->si_num_name;
2110         nvlist_t *lnvl = l->usn_nvl;
2111         nvlist_t *rnvl = r->usn_nvl;
2112 
2113         for (; sortcol != NULL; sortcol = sortcol->sc_next) {
2114                 char *lvstr = "";
2115                 char *rvstr = "";
2116                 uint32_t lv32 = 0;
2117                 uint32_t rv32 = 0;
2118                 uint64_t lv64 = 0;
2119                 uint64_t rv64 = 0;
2120                 zfs_prop_t prop = sortcol->sc_prop;
2121                 const char *propname = NULL;
2122                 boolean_t reverse = sortcol->sc_reverse;
2123 
2124                 switch (prop) {
2125                 case ZFS_PROP_TYPE:
2126                         propname = "type";
2127                         (void) nvlist_lookup_uint32(lnvl, propname, &lv32);
2128                         (void) nvlist_lookup_uint32(rnvl, propname, &rv32);
2129                         if (rv32 != lv32)
2130                                 rc = (rv32 > lv32) ? 1 : -1;
2131                         break;
2132                 case ZFS_PROP_NAME:
2133                         propname = "name";
2134                         if (num_name) {
2135                                 (void) nvlist_lookup_uint32(lnvl, propname,
2136                                     &lv32);
2137                                 (void) nvlist_lookup_uint32(rnvl, propname,
2138                                     &rv32);
2139                                 if (rv32 != lv32)
2140                                         rc = (rv32 > lv32) ? 1 : -1;
2141                         } else {
2142                                 (void) nvlist_lookup_string(lnvl, propname,
2143                                     &lvstr);
2144                                 (void) nvlist_lookup_string(rnvl, propname,
2145                                     &rvstr);
2146                                 rc = strcmp(lvstr, rvstr);
2147                         }
2148                         break;
2149 
2150                 case ZFS_PROP_USED:
2151                 case ZFS_PROP_QUOTA:
2152                         if (ZFS_PROP_USED == prop)
2153                                 propname = "used";
2154                         else
2155                                 propname = "quota";
2156                         (void) nvlist_lookup_uint64(lnvl, propname, &lv64);
2157                         (void) nvlist_lookup_uint64(rnvl, propname, &rv64);
2158                         if (rv64 != lv64)
2159                                 rc = (rv64 > lv64) ? 1 : -1;
2160                 }
2161 
2162                 if (rc)
2163                         if (rc < 0)
2164                                 return (reverse ? 1 : -1);
2165                         else
2166                                 return (reverse ? -1 : 1);
2167         }
2168 
2169         return (rc);
2170 }
2171 
2172 static inline const char *
2173 us_type2str(unsigned field_type)
2174 {
2175         switch (field_type) {
2176         case USTYPE_PSX_USR:
2177                 return ("POSIX User");
2178         case USTYPE_PSX_GRP:
2179                 return ("POSIX Group");
2180         case USTYPE_SMB_USR:
2181                 return ("SMB User");
2182         case USTYPE_SMB_GRP:
2183                 return ("SMB Group");
2184         default:
2185                 return ("Undefined");
2186         }
2187 }
2188 
2189 /*
2190  * zfs userspace
2191  */
2192 static int
2193 userspace_cb(void *arg, const char *domain, uid_t rid, uint64_t space)
2194 {
2195         us_cbdata_t *cb = (us_cbdata_t *)arg;
2196         zfs_userquota_prop_t prop = cb->cb_prop;
2197         char *name = NULL;
2198         char *propname;
2199         char namebuf[32];
2200         char sizebuf[32];
2201         us_node_t *node;
2202         uu_avl_pool_t *avl_pool = cb->cb_avl_pool;
2203         uu_avl_t *avl = cb->cb_avl;
2204         uu_avl_index_t idx;
2205         nvlist_t *props;
2206         us_node_t *n;
2207         zfs_sort_column_t *sortcol = cb->cb_sortcol;
2208         unsigned type;
2209         const char *typestr;
2210         size_t namelen;
2211         size_t typelen;
2212         size_t sizelen;
2213         us_sort_info_t sortinfo = { sortcol, cb->cb_numname };
2214 
2215         if (domain == NULL || domain[0] == '\0') {
2216                 /* POSIX */
2217                 if (prop == ZFS_PROP_GROUPUSED || prop == ZFS_PROP_GROUPQUOTA) {
2218                         type = USTYPE_PSX_GRP;
2219                         struct group *g = getgrgid(rid);
2220                         if (g)
2221                                 name = g->gr_name;
2222                 } else {
2223                         type = USTYPE_PSX_USR;
2224                         struct passwd *p = getpwuid(rid);
2225                         if (p)
2226                                 name = p->pw_name;
2227                 }
2228         } else {
2229                 char sid[ZFS_MAXNAMELEN+32];
2230                 uid_t id;
2231                 uint64_t classes;
2232                 int err = 0;
2233                 directory_error_t e;
2234 
2235                 (void) snprintf(sid, sizeof (sid), "%s-%u", domain, rid);
2236                 /* SMB */
2237                 if (prop == ZFS_PROP_GROUPUSED || prop == ZFS_PROP_GROUPQUOTA) {
2238                         type = USTYPE_SMB_GRP;
2239                         err = sid_to_id(sid, B_FALSE, &id);
2240                 } else {
2241                         type = USTYPE_SMB_USR;
2242                         err = sid_to_id(sid, B_TRUE, &id);
2243                 }
2244 
2245                 if (err == 0) {
2246                         rid = id;
2247 
2248                         e = directory_name_from_sid(NULL, sid, &name, &classes);
2249                         if (e != NULL) {
2250                                 directory_error_free(e);
2251                                 return (NULL);
2252                         }
2253 
2254                         if (name == NULL)
2255                                 name = sid;
2256                 }
2257         }
2258 
2259 /*
2260  *      if (prop == ZFS_PROP_GROUPUSED || prop == ZFS_PROP_GROUPQUOTA)
2261  *              ug = "group";
2262  *      else
2263  *              ug = "user";
2264  */
2265 
2266         if (prop == ZFS_PROP_USERUSED || prop == ZFS_PROP_GROUPUSED)
2267                 propname = "used";
2268         else
2269                 propname = "quota";
2270 
2271         (void) snprintf(namebuf, sizeof (namebuf), "%u", rid);
2272         if (name == NULL)
2273                 name = namebuf;
2274 
2275         if (cb->cb_nicenum)
2276                 zfs_nicenum(space, sizebuf, sizeof (sizebuf));
2277         else
2278                 (void) sprintf(sizebuf, "%llu", space);
2279 
2280         node = safe_malloc(sizeof (us_node_t));
2281         uu_avl_node_init(node, &node->usn_avlnode, avl_pool);
2282 
2283         if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0) {
2284                 free(node);
2285                 return (-1);
2286         }
2287 
2288         if (nvlist_add_uint32(props, "type", type) != 0)
2289                 nomem();
2290 
2291         if (cb->cb_numname) {
2292                 if (nvlist_add_uint32(props, "name", rid) != 0)
2293                         nomem();
2294                 namelen = strlen(namebuf);
2295         } else {
2296                 if (nvlist_add_string(props, "name", name) != 0)
2297                         nomem();
2298                 namelen = strlen(name);
2299         }
2300 
2301         typestr = us_type2str(type);
2302         typelen = strlen(gettext(typestr));
2303         if (typelen > cb->cb_max_typelen)
2304                 cb->cb_max_typelen  = typelen;
2305 
2306         if (namelen > cb->cb_max_namelen)
2307                 cb->cb_max_namelen  = namelen;
2308 
2309         sizelen = strlen(sizebuf);
2310         if (0 == strcmp(propname, "used")) {
2311                 if (sizelen > cb->cb_max_usedlen)
2312                         cb->cb_max_usedlen  = sizelen;
2313         } else {
2314                 if (sizelen > cb->cb_max_quotalen)
2315                         cb->cb_max_quotalen  = sizelen;
2316         }
2317 
2318         node->usn_nvl = props;
2319 
2320         n = uu_avl_find(avl, node, &sortinfo, &idx);
2321         if (n == NULL)
2322                 uu_avl_insert(avl, node, idx);
2323         else {
2324                 nvlist_free(props);
2325                 free(node);
2326                 node = n;
2327                 props = node->usn_nvl;
2328         }
2329 
2330         if (nvlist_add_uint64(props, propname, space) != 0)
2331                 nomem();
2332 
2333         return (0);
2334 }
2335 
2336 static inline boolean_t
2337 usprop_check(zfs_userquota_prop_t p, unsigned types, unsigned props)
2338 {
2339         unsigned type;
2340         unsigned prop;
2341 
2342         switch (p) {
2343         case ZFS_PROP_USERUSED:
2344                 type = USTYPE_USR;
2345                 prop = USPROP_USED;
2346                 break;
2347         case ZFS_PROP_USERQUOTA:
2348                 type = USTYPE_USR;
2349                 prop = USPROP_QUOTA;
2350                 break;
2351         case ZFS_PROP_GROUPUSED:
2352                 type = USTYPE_GRP;
2353                 prop = USPROP_USED;
2354                 break;
2355         case ZFS_PROP_GROUPQUOTA:
2356                 type = USTYPE_GRP;
2357                 prop = USPROP_QUOTA;
2358                 break;
2359         default: /* ALL */
2360                 return (B_TRUE);
2361         };
2362 
2363         return (type & types && prop & props);
2364 }
2365 
2366 #define USFIELD_TYPE (1 << 0)
2367 #define USFIELD_NAME (1 << 1)
2368 #define USFIELD_USED (1 << 2)
2369 #define USFIELD_QUOTA (1 << 3)
2370 #define USFIELD_ALL (USFIELD_TYPE | USFIELD_NAME | USFIELD_USED | USFIELD_QUOTA)
2371 
2372 static int
2373 parsefields(unsigned *fieldsp, char **names, unsigned *bits, size_t len)
2374 {
2375         char *field = optarg;
2376         char *delim;
2377 
2378         do {
2379                 int i;
2380                 boolean_t found = B_FALSE;
2381                 delim = strchr(field, ',');
2382                 if (delim != NULL)
2383                         *delim = '\0';
2384 
2385                 for (i = 0; i < len; i++)
2386                         if (0 == strcmp(field, names[i])) {
2387                                 found = B_TRUE;
2388                                 *fieldsp |= bits[i];
2389                                 break;
2390                         }
2391 
2392                 if (!found) {
2393                         (void) fprintf(stderr, gettext("invalid type '%s'"
2394                             "for -t option\n"), field);
2395                         return (-1);
2396                 }
2397 
2398                 field = delim + 1;
2399         } while (delim);
2400 
2401         return (0);
2402 }
2403 
2404 
2405 static char *type_names[] = { "posixuser", "smbuser", "posixgroup", "smbgroup",
2406         "all" };
2407 static unsigned type_bits[] = {
2408         USTYPE_PSX_USR,
2409         USTYPE_SMB_USR,
2410         USTYPE_PSX_GRP,
2411         USTYPE_SMB_GRP,
2412         USTYPE_ALL
2413 };
2414 
2415 static char *us_field_names[] = { "type", "name", "used", "quota" };
2416 static unsigned us_field_bits[] = {
2417         USFIELD_TYPE,
2418         USFIELD_NAME,
2419         USFIELD_USED,
2420         USFIELD_QUOTA
2421 };
2422 
2423 static void
2424 print_us_node(boolean_t scripted, boolean_t parseable, unsigned fields,
2425                 size_t type_width, size_t name_width, size_t used_width,
2426                 size_t quota_width, us_node_t *node)
2427 {
2428         nvlist_t *nvl = node->usn_nvl;
2429         nvpair_t *nvp = NULL;
2430         char valstr[ZFS_MAXNAMELEN];
2431         boolean_t first = B_TRUE;
2432         boolean_t quota_found = B_FALSE;
2433 
2434         if (fields & USFIELD_QUOTA && !nvlist_exists(nvl, "quota"))
2435                 if (nvlist_add_string(nvl, "quota", "none") != 0)
2436                         nomem();
2437 
2438         while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
2439                 char *pname = nvpair_name(nvp);
2440                 data_type_t type = nvpair_type(nvp);
2441                 uint32_t val32 = 0;
2442                 uint64_t val64 = 0;
2443                 char *strval = NULL;
2444                 unsigned field = 0;
2445                 unsigned width = 0;
2446                 int i;
2447                 for (i = 0; i < 4; i++) {
2448                         if (0 == strcmp(pname, us_field_names[i])) {
2449                                 field = us_field_bits[i];
2450                                 break;
2451                         }
2452                 }
2453 
2454                 if (!(field & fields))
2455                         continue;
2456 
2457                 switch (type) {
2458                 case DATA_TYPE_UINT32:
2459                         (void) nvpair_value_uint32(nvp, &val32);
2460                         break;
2461                 case DATA_TYPE_UINT64:
2462                         (void) nvpair_value_uint64(nvp, &val64);
2463                         break;
2464                 case DATA_TYPE_STRING:
2465                         (void) nvpair_value_string(nvp, &strval);
2466                         break;
2467                 default:
2468                         (void) fprintf(stderr, "Invalid data type\n");
2469                 }
2470 
2471                 if (!first)
2472                         if (scripted)
2473                                 (void) printf("\t");
2474                         else
2475                                 (void) printf("  ");
2476 
2477                 switch (field) {
2478                 case USFIELD_TYPE:
2479                         strval = (char *)us_type2str(val32);
2480                         width = type_width;
2481                         break;
2482                 case USFIELD_NAME:
2483                         if (type == DATA_TYPE_UINT64) {
2484                                 (void) sprintf(valstr, "%llu", val64);
2485                                 strval = valstr;
2486                         }
2487                         width = name_width;
2488                         break;
2489                 case USFIELD_USED:
2490                 case USFIELD_QUOTA:
2491                         if (type == DATA_TYPE_UINT64) {
2492                                 (void) nvpair_value_uint64(nvp, &val64);
2493                                 if (parseable)
2494                                         (void) sprintf(valstr, "%llu", val64);
2495                                 else
2496                                         zfs_nicenum(val64, valstr,
2497                                             sizeof (valstr));
2498                                 strval = valstr;
2499                         }
2500 
2501                         if (field == USFIELD_USED)
2502                                 width = used_width;
2503                         else {
2504                                 quota_found = B_FALSE;
2505                                 width = quota_width;
2506                         }
2507 
2508                         break;
2509                 }
2510 
2511                 if (field == USFIELD_QUOTA && !quota_found)
2512                         (void) printf("%*s", width, strval);
2513                 else {
2514                         if (type == DATA_TYPE_STRING)
2515                                 (void) printf("%-*s", width, strval);
2516                         else
2517                                 (void) printf("%*s", width, strval);
2518                 }
2519 
2520                 first = B_FALSE;
2521 
2522         }
2523 
2524         (void) printf("\n");
2525 }
2526 
2527 static void
2528 print_us(boolean_t scripted, boolean_t parsable, unsigned fields,
2529                 unsigned type_width, unsigned name_width, unsigned used_width,
2530                 unsigned quota_width, boolean_t rmnode, uu_avl_t *avl)
2531 {
2532         static char *us_field_hdr[] = { "TYPE", "NAME", "USED", "QUOTA" };
2533         us_node_t *node;
2534         const char *col;
2535         int i;
2536         size_t width[4] = { type_width, name_width, used_width, quota_width };
2537 
2538         if (!scripted) {
2539                 boolean_t first = B_TRUE;
2540                 for (i = 0; i < 4; i++) {
2541                         unsigned field = us_field_bits[i];
2542                         if (!(field & fields))
2543                                 continue;
2544 
2545                         col = gettext(us_field_hdr[i]);
2546                         if (field == USFIELD_TYPE || field == USFIELD_NAME)
2547                                 (void) printf(first?"%-*s":"  %-*s", width[i],
2548                                     col);
2549                         else
2550                                 (void) printf(first?"%*s":"  %*s", width[i],
2551                                     col);
2552                         first = B_FALSE;
2553                 }
2554                 (void) printf("\n");
2555         }
2556 
2557         for (node = uu_avl_first(avl); node != NULL;
2558             node = uu_avl_next(avl, node)) {
2559                 print_us_node(scripted, parsable, fields, type_width,
2560                     name_width, used_width, used_width, node);
2561                 if (rmnode)
2562                         nvlist_free(node->usn_nvl);
2563         }
2564 }
2565 
2566 static int
2567 zfs_do_userspace(int argc, char **argv)
2568 {
2569         zfs_handle_t *zhp;
2570         zfs_userquota_prop_t p;
2571         uu_avl_pool_t *avl_pool;
2572         uu_avl_t *avl_tree;
2573         uu_avl_walk_t *walk;
2574 
2575         char *cmd;
2576         boolean_t scripted = B_FALSE;
2577         boolean_t prtnum = B_FALSE;
2578         boolean_t parseable = B_FALSE;
2579         boolean_t sid2posix = B_FALSE;
2580         int error = 0;
2581         int c;
2582         zfs_sort_column_t *default_sortcol = NULL;
2583         zfs_sort_column_t *sortcol = NULL;
2584         unsigned types = USTYPE_PSX_USR | USTYPE_SMB_USR;
2585         unsigned fields = 0;
2586         unsigned props = USPROP_USED | USPROP_QUOTA;
2587         us_cbdata_t cb;
2588         us_node_t *node;
2589         boolean_t resort_avl = B_FALSE;
2590 
2591         if (argc < 2)
2592                 usage(B_FALSE);
2593 
2594         cmd = argv[0];
2595         if (0 == strcmp(cmd, "groupspace"))
2596                 /* toggle default group types */
2597                 types = USTYPE_PSX_GRP | USTYPE_SMB_GRP;
2598 
2599         /* check options */
2600         while ((c = getopt(argc, argv, "nHpo:s:S:t:i")) != -1) {
2601                 switch (c) {
2602                 case 'n':
2603                         prtnum = B_TRUE;
2604                         break;
2605                 case 'H':
2606                         scripted = B_TRUE;
2607                         break;
2608                 case 'p':
2609                         parseable = B_TRUE;
2610                         break;
2611                 case 'o':
2612                         if (parsefields(&fields, us_field_names, us_field_bits,
2613                             4) != 0)
2614                                 return (1);
2615                         break;
2616                 case 's':
2617                         if (zfs_add_sort_column(&sortcol, optarg,
2618                             B_FALSE) != 0) {
2619                                 (void) fprintf(stderr,
2620                                     gettext("invalid property '%s'\n"), optarg);
2621                                 usage(B_FALSE);
2622                         }
2623                         break;
2624                 case 'S':
2625                         if (zfs_add_sort_column(&sortcol, optarg,
2626                             B_TRUE) != 0) {
2627                                 (void) fprintf(stderr,
2628                                     gettext("invalid property '%s'\n"), optarg);
2629                                 usage(B_FALSE);
2630                         }
2631                         break;
2632                 case 't':
2633                         if (parsefields(&types, type_names, type_bits, 5))
2634                                 return (1);
2635                         break;
2636                 case 'i':
2637                         sid2posix = B_TRUE;
2638                         break;
2639                 case ':':
2640                         (void) fprintf(stderr, gettext("missing argument for "
2641                             "'%c' option\n"), optopt);
2642                         usage(B_FALSE);
2643                         break;
2644                 case '?':
2645                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
2646                             optopt);
2647                         usage(B_FALSE);
2648                 }
2649         }
2650 
2651         argc -= optind;
2652         argv += optind;
2653 
2654         /* ok, now we have sorted by default colums (type,name) avl tree */
2655         if (sortcol) {
2656                 zfs_sort_column_t *sc;
2657                 for (sc = sortcol; sc; sc = sc->sc_next) {
2658                         if (sc->sc_prop == ZFS_PROP_QUOTA) {
2659                                 resort_avl = B_TRUE;
2660                                 break;
2661                         }
2662                 }
2663         }
2664 
2665         if (!fields)
2666                 fields = USFIELD_ALL;
2667 
2668         if ((zhp = zfs_open(g_zfs, argv[argc-1], ZFS_TYPE_DATASET)) == NULL)
2669                 return (1);
2670 
2671         if ((avl_pool = uu_avl_pool_create("us_avl_pool", sizeof (us_node_t),
2672             offsetof(us_node_t, usn_avlnode),
2673             us_compare, UU_DEFAULT)) == NULL)
2674                 nomem();
2675         if ((avl_tree = uu_avl_create(avl_pool, NULL, UU_DEFAULT)) == NULL)
2676                 nomem();
2677 
2678         if (sortcol && !resort_avl)
2679                 cb.cb_sortcol = sortcol;
2680         else {
2681                 (void) zfs_add_sort_column(&default_sortcol, "type", B_FALSE);
2682                 (void) zfs_add_sort_column(&default_sortcol, "name", B_FALSE);
2683                 cb.cb_sortcol = default_sortcol;
2684         }
2685         cb.cb_numname = prtnum;
2686         cb.cb_nicenum = !parseable;
2687         cb.cb_avl_pool = avl_pool;
2688         cb.cb_avl = avl_tree;
2689         cb.cb_sid2posix = sid2posix;
2690         cb.cb_max_typelen = strlen(gettext("TYPE"));
2691         cb.cb_max_namelen = strlen(gettext("NAME"));
2692         cb.cb_max_usedlen = strlen(gettext("USED"));
2693         cb.cb_max_quotalen = strlen(gettext("QUOTA"));
2694 
2695         for (p = 0; p < ZFS_NUM_USERQUOTA_PROPS; p++) {
2696                 if (!usprop_check(p, types, props))
2697                         continue;
2698 
2699                 cb.cb_prop = p;
2700                 error = zfs_userspace(zhp, p, userspace_cb, &cb);
2701                 if (error)
2702                         break;
2703         }
2704 
2705 
2706         if (resort_avl) {
2707                 us_node_t *node;
2708                 us_node_t *rmnode;
2709                 uu_list_pool_t *listpool;
2710                 uu_list_t *list;
2711                 uu_avl_index_t idx = 0;
2712                 uu_list_index_t idx2 = 0;
2713                 listpool = uu_list_pool_create("tmplist", sizeof (us_node_t),
2714                     offsetof(us_node_t, usn_listnode), NULL,
2715                     UU_DEFAULT);
2716                 list = uu_list_create(listpool, NULL, UU_DEFAULT);
2717 
2718                 node = uu_avl_first(avl_tree);
2719                 uu_list_node_init(node, &node->usn_listnode, listpool);
2720                 while (node != NULL) {
2721                         rmnode = node;
2722                         node = uu_avl_next(avl_tree, node);
2723                         uu_avl_remove(avl_tree, rmnode);
2724                         if (uu_list_find(list, rmnode, NULL, &idx2) == NULL) {
2725                                 uu_list_insert(list, rmnode, idx2);
2726                         }
2727                 }
2728 
2729                 for (node = uu_list_first(list); node != NULL;
2730                     node = uu_list_next(list, node)) {
2731                         us_sort_info_t sortinfo = { sortcol, cb.cb_numname };
2732                         if (uu_avl_find(avl_tree, node, &sortinfo, &idx) ==
2733                             NULL)
2734                         uu_avl_insert(avl_tree, node, idx);
2735                 }
2736 
2737                 uu_list_destroy(list);
2738         }
2739 
2740         /* print & free node`s nvlist memory */
2741         print_us(scripted, parseable, fields, cb.cb_max_typelen,
2742             cb.cb_max_namelen, cb.cb_max_usedlen,
2743             cb.cb_max_quotalen, B_TRUE, cb.cb_avl);
2744 
2745         if (sortcol)
2746                 zfs_free_sort_columns(sortcol);
2747         zfs_free_sort_columns(default_sortcol);
2748 
2749         /*
2750          * Finally, clean up the AVL tree.
2751          */
2752         if ((walk = uu_avl_walk_start(cb.cb_avl, UU_WALK_ROBUST)) == NULL)
2753                 nomem();
2754 
2755         while ((node = uu_avl_walk_next(walk)) != NULL) {
2756                 uu_avl_remove(cb.cb_avl, node);
2757                 free(node);
2758         }
2759 
2760         uu_avl_walk_end(walk);
2761         uu_avl_destroy(avl_tree);
2762         uu_avl_pool_destroy(avl_pool);
2763 
2764         return (error);
2765 }
2766 
2767 /*
2768  * list [-r][-d max] [-H] [-o property[,property]...] [-t type[,type]...]
2769  *      [-s property [-s property]...] [-S property [-S property]...]
2770  *      <dataset> ...
2771  *
2772  *      -r      Recurse over all children
2773  *      -d      Limit recursion by depth.
2774  *      -H      Scripted mode; elide headers and separate columns by tabs
2775  *      -o      Control which fields to display.
2776  *      -t      Control which object types to display.
2777  *      -s      Specify sort columns, descending order.
2778  *      -S      Specify sort columns, ascending order.
2779  *
2780  * When given no arguments, lists all filesystems in the system.
2781  * Otherwise, list the specified datasets, optionally recursing down them if
2782  * '-r' is specified.
2783  */
2784 typedef struct list_cbdata {
2785         boolean_t       cb_first;
2786         boolean_t       cb_scripted;
2787         zprop_list_t    *cb_proplist;
2788 } list_cbdata_t;
2789 
2790 /*
2791  * Given a list of columns to display, output appropriate headers for each one.
2792  */
2793 static void
2794 print_header(zprop_list_t *pl)
2795 {
2796         char headerbuf[ZFS_MAXPROPLEN];
2797         const char *header;
2798         int i;
2799         boolean_t first = B_TRUE;
2800         boolean_t right_justify;
2801 
2802         for (; pl != NULL; pl = pl->pl_next) {
2803                 if (!first) {
2804                         (void) printf("  ");
2805                 } else {
2806                         first = B_FALSE;
2807                 }
2808 
2809                 right_justify = B_FALSE;
2810                 if (pl->pl_prop != ZPROP_INVAL) {
2811                         header = zfs_prop_column_name(pl->pl_prop);
2812                         right_justify = zfs_prop_align_right(pl->pl_prop);
2813                 } else {
2814                         for (i = 0; pl->pl_user_prop[i] != '\0'; i++)
2815                                 headerbuf[i] = toupper(pl->pl_user_prop[i]);
2816                         headerbuf[i] = '\0';
2817                         header = headerbuf;
2818                 }
2819 
2820                 if (pl->pl_next == NULL && !right_justify)
2821                         (void) printf("%s", header);
2822                 else if (right_justify)
2823                         (void) printf("%*s", pl->pl_width, header);
2824                 else
2825                         (void) printf("%-*s", pl->pl_width, header);
2826         }
2827 
2828         (void) printf("\n");
2829 }
2830 
2831 /*
2832  * Given a dataset and a list of fields, print out all the properties according
2833  * to the described layout.
2834  */
2835 static void
2836 print_dataset(zfs_handle_t *zhp, zprop_list_t *pl, boolean_t scripted)
2837 {
2838         boolean_t first = B_TRUE;
2839         char property[ZFS_MAXPROPLEN];
2840         nvlist_t *userprops = zfs_get_user_props(zhp);
2841         nvlist_t *propval;
2842         char *propstr;
2843         boolean_t right_justify;
2844         int width;
2845 
2846         for (; pl != NULL; pl = pl->pl_next) {
2847                 if (!first) {
2848                         if (scripted)
2849                                 (void) printf("\t");
2850                         else
2851                                 (void) printf("  ");
2852                 } else {
2853                         first = B_FALSE;
2854                 }
2855 
2856                 if (pl->pl_prop != ZPROP_INVAL) {
2857                         if (zfs_prop_get(zhp, pl->pl_prop, property,
2858                             sizeof (property), NULL, NULL, 0, B_FALSE) != 0)
2859                                 propstr = "-";
2860                         else
2861                                 propstr = property;
2862 
2863                         right_justify = zfs_prop_align_right(pl->pl_prop);
2864                 } else if (zfs_prop_userquota(pl->pl_user_prop)) {
2865                         if (zfs_prop_get_userquota(zhp, pl->pl_user_prop,
2866                             property, sizeof (property), B_FALSE) != 0)
2867                                 propstr = "-";
2868                         else
2869                                 propstr = property;
2870                         right_justify = B_TRUE;
2871                 } else if (zfs_prop_written(pl->pl_user_prop)) {
2872                         if (zfs_prop_get_written(zhp, pl->pl_user_prop,
2873                             property, sizeof (property), B_FALSE) != 0)
2874                                 propstr = "-";
2875                         else
2876                                 propstr = property;
2877                         right_justify = B_TRUE;
2878                 } else {
2879                         if (nvlist_lookup_nvlist(userprops,
2880                             pl->pl_user_prop, &propval) != 0)
2881                                 propstr = "-";
2882                         else
2883                                 verify(nvlist_lookup_string(propval,
2884                                     ZPROP_VALUE, &propstr) == 0);
2885                         right_justify = B_FALSE;
2886                 }
2887 
2888                 width = pl->pl_width;
2889 
2890                 /*
2891                  * If this is being called in scripted mode, or if this is the
2892                  * last column and it is left-justified, don't include a width
2893                  * format specifier.
2894                  */
2895                 if (scripted || (pl->pl_next == NULL && !right_justify))
2896                         (void) printf("%s", propstr);
2897                 else if (right_justify)
2898                         (void) printf("%*s", width, propstr);
2899                 else
2900                         (void) printf("%-*s", width, propstr);
2901         }
2902 
2903         (void) printf("\n");
2904 }
2905 
2906 /*
2907  * Generic callback function to list a dataset or snapshot.
2908  */
2909 static int
2910 list_callback(zfs_handle_t *zhp, void *data)
2911 {
2912         list_cbdata_t *cbp = data;
2913 
2914         if (cbp->cb_first) {
2915                 if (!cbp->cb_scripted)
2916                         print_header(cbp->cb_proplist);
2917                 cbp->cb_first = B_FALSE;
2918         }
2919 
2920         print_dataset(zhp, cbp->cb_proplist, cbp->cb_scripted);
2921 
2922         return (0);
2923 }
2924 
2925 static int
2926 zfs_do_list(int argc, char **argv)
2927 {
2928         int c;
2929         boolean_t scripted = B_FALSE;
2930         static char default_fields[] =
2931             "name,used,available,referenced,mountpoint";
2932         int types = ZFS_TYPE_DATASET;
2933         boolean_t types_specified = B_FALSE;
2934         char *fields = NULL;
2935         list_cbdata_t cb = { 0 };
2936         char *value;
2937         int limit = 0;
2938         int ret = 0;
2939         zfs_sort_column_t *sortcol = NULL;
2940         int flags = ZFS_ITER_PROP_LISTSNAPS | ZFS_ITER_ARGS_CAN_BE_PATHS;
2941 
2942         /* check options */
2943         while ((c = getopt(argc, argv, ":d:o:rt:Hs:S:")) != -1) {
2944                 switch (c) {
2945                 case 'o':
2946                         fields = optarg;
2947                         break;
2948                 case 'd':
2949                         limit = parse_depth(optarg, &flags);
2950                         break;
2951                 case 'r':
2952                         flags |= ZFS_ITER_RECURSE;
2953                         break;
2954                 case 'H':
2955                         scripted = B_TRUE;
2956                         break;
2957                 case 's':
2958                         if (zfs_add_sort_column(&sortcol, optarg,
2959                             B_FALSE) != 0) {
2960                                 (void) fprintf(stderr,
2961                                     gettext("invalid property '%s'\n"), optarg);
2962                                 usage(B_FALSE);
2963                         }
2964                         break;
2965                 case 'S':
2966                         if (zfs_add_sort_column(&sortcol, optarg,
2967                             B_TRUE) != 0) {
2968                                 (void) fprintf(stderr,
2969                                     gettext("invalid property '%s'\n"), optarg);
2970                                 usage(B_FALSE);
2971                         }
2972                         break;
2973                 case 't':
2974                         types = 0;
2975                         types_specified = B_TRUE;
2976                         flags &= ~ZFS_ITER_PROP_LISTSNAPS;
2977                         while (*optarg != '\0') {
2978                                 static char *type_subopts[] = { "filesystem",
2979                                     "volume", "snapshot", "all", NULL };
2980 
2981                                 switch (getsubopt(&optarg, type_subopts,
2982                                     &value)) {
2983                                 case 0:
2984                                         types |= ZFS_TYPE_FILESYSTEM;
2985                                         break;
2986                                 case 1:
2987                                         types |= ZFS_TYPE_VOLUME;
2988                                         break;
2989                                 case 2:
2990                                         types |= ZFS_TYPE_SNAPSHOT;
2991                                         break;
2992                                 case 3:
2993                                         types = ZFS_TYPE_DATASET;
2994                                         break;
2995 
2996                                 default:
2997                                         (void) fprintf(stderr,
2998                                             gettext("invalid type '%s'\n"),
2999                                             value);
3000                                         usage(B_FALSE);
3001                                 }
3002                         }
3003                         break;
3004                 case ':':
3005                         (void) fprintf(stderr, gettext("missing argument for "
3006                             "'%c' option\n"), optopt);
3007                         usage(B_FALSE);
3008                         break;
3009                 case '?':
3010                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3011                             optopt);
3012                         usage(B_FALSE);
3013                 }
3014         }
3015 
3016         argc -= optind;
3017         argv += optind;
3018 
3019         if (fields == NULL)
3020                 fields = default_fields;
3021 
3022         /*
3023          * If "-o space" and no types were specified, don't display snapshots.
3024          */
3025         if (strcmp(fields, "space") == 0 && types_specified == B_FALSE)
3026                 types &= ~ZFS_TYPE_SNAPSHOT;
3027 
3028         /*
3029          * If the user specifies '-o all', the zprop_get_list() doesn't
3030          * normally include the name of the dataset.  For 'zfs list', we always
3031          * want this property to be first.
3032          */
3033         if (zprop_get_list(g_zfs, fields, &cb.cb_proplist, ZFS_TYPE_DATASET)
3034             != 0)
3035                 usage(B_FALSE);
3036 
3037         cb.cb_scripted = scripted;
3038         cb.cb_first = B_TRUE;
3039 
3040         ret = zfs_for_each(argc, argv, flags, types, sortcol, &cb.cb_proplist,
3041             limit, list_callback, &cb);
3042 
3043         zprop_free_list(cb.cb_proplist);
3044         zfs_free_sort_columns(sortcol);
3045 
3046         if (ret == 0 && cb.cb_first && !cb.cb_scripted)
3047                 (void) printf(gettext("no datasets available\n"));
3048 
3049         return (ret);
3050 }
3051 
3052 /*
3053  * zfs rename [-f] <fs | snap | vol> <fs | snap | vol>
3054  * zfs rename [-f] -p <fs | vol> <fs | vol>
3055  * zfs rename -r <snap> <snap>
3056  *
3057  * Renames the given dataset to another of the same type.
3058  *
3059  * The '-p' flag creates all the non-existing ancestors of the target first.
3060  */
3061 /* ARGSUSED */
3062 static int
3063 zfs_do_rename(int argc, char **argv)
3064 {
3065         zfs_handle_t *zhp;
3066         int c;
3067         int ret = 0;
3068         boolean_t recurse = B_FALSE;
3069         boolean_t parents = B_FALSE;
3070         boolean_t force_unmount = B_FALSE;
3071 
3072         /* check options */
3073         while ((c = getopt(argc, argv, "prf")) != -1) {
3074                 switch (c) {
3075                 case 'p':
3076                         parents = B_TRUE;
3077                         break;
3078                 case 'r':
3079                         recurse = B_TRUE;
3080                         break;
3081                 case 'f':
3082                         force_unmount = B_TRUE;
3083                         break;
3084                 case '?':
3085                 default:
3086                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3087                             optopt);
3088                         usage(B_FALSE);
3089                 }
3090         }
3091 
3092         argc -= optind;
3093         argv += optind;
3094 
3095         /* check number of arguments */
3096         if (argc < 1) {
3097                 (void) fprintf(stderr, gettext("missing source dataset "
3098                     "argument\n"));
3099                 usage(B_FALSE);
3100         }
3101         if (argc < 2) {
3102                 (void) fprintf(stderr, gettext("missing target dataset "
3103                     "argument\n"));
3104                 usage(B_FALSE);
3105         }
3106         if (argc > 2) {
3107                 (void) fprintf(stderr, gettext("too many arguments\n"));
3108                 usage(B_FALSE);
3109         }
3110 
3111         if (recurse && parents) {
3112                 (void) fprintf(stderr, gettext("-p and -r options are mutually "
3113                     "exclusive\n"));
3114                 usage(B_FALSE);
3115         }
3116 
3117         if (recurse && strchr(argv[0], '@') == 0) {
3118                 (void) fprintf(stderr, gettext("source dataset for recursive "
3119                     "rename must be a snapshot\n"));
3120                 usage(B_FALSE);
3121         }
3122 
3123         if ((zhp = zfs_open(g_zfs, argv[0], parents ? ZFS_TYPE_FILESYSTEM |
3124             ZFS_TYPE_VOLUME : ZFS_TYPE_DATASET)) == NULL)
3125                 return (1);
3126 
3127         /* If we were asked and the name looks good, try to create ancestors. */
3128         if (parents && zfs_name_valid(argv[1], zfs_get_type(zhp)) &&
3129             zfs_create_ancestors(g_zfs, argv[1]) != 0) {
3130                 zfs_close(zhp);
3131                 return (1);
3132         }
3133 
3134         ret = (zfs_rename(zhp, argv[1], recurse, force_unmount) != 0);
3135 
3136         zfs_close(zhp);
3137         return (ret);
3138 }
3139 
3140 /*
3141  * zfs promote <fs>
3142  *
3143  * Promotes the given clone fs to be the parent
3144  */
3145 /* ARGSUSED */
3146 static int
3147 zfs_do_promote(int argc, char **argv)
3148 {
3149         zfs_handle_t *zhp;
3150         int ret = 0;
3151 
3152         /* check options */
3153         if (argc > 1 && argv[1][0] == '-') {
3154                 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3155                     argv[1][1]);
3156                 usage(B_FALSE);
3157         }
3158 
3159         /* check number of arguments */
3160         if (argc < 2) {
3161                 (void) fprintf(stderr, gettext("missing clone filesystem"
3162                     " argument\n"));
3163                 usage(B_FALSE);
3164         }
3165         if (argc > 2) {
3166                 (void) fprintf(stderr, gettext("too many arguments\n"));
3167                 usage(B_FALSE);
3168         }
3169 
3170         zhp = zfs_open(g_zfs, argv[1], ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
3171         if (zhp == NULL)
3172                 return (1);
3173 
3174         ret = (zfs_promote(zhp) != 0);
3175 
3176 
3177         zfs_close(zhp);
3178         return (ret);
3179 }
3180 
3181 /*
3182  * zfs rollback [-rRf] <snapshot>
3183  *
3184  *      -r      Delete any intervening snapshots before doing rollback
3185  *      -R      Delete any snapshots and their clones
3186  *      -f      ignored for backwards compatability
3187  *
3188  * Given a filesystem, rollback to a specific snapshot, discarding any changes
3189  * since then and making it the active dataset.  If more recent snapshots exist,
3190  * the command will complain unless the '-r' flag is given.
3191  */
3192 typedef struct rollback_cbdata {
3193         uint64_t        cb_create;
3194         boolean_t       cb_first;
3195         int             cb_doclones;
3196         char            *cb_target;
3197         int             cb_error;
3198         boolean_t       cb_recurse;
3199         boolean_t       cb_dependent;
3200 } rollback_cbdata_t;
3201 
3202 /*
3203  * Report any snapshots more recent than the one specified.  Used when '-r' is
3204  * not specified.  We reuse this same callback for the snapshot dependents - if
3205  * 'cb_dependent' is set, then this is a dependent and we should report it
3206  * without checking the transaction group.
3207  */
3208 static int
3209 rollback_check(zfs_handle_t *zhp, void *data)
3210 {
3211         rollback_cbdata_t *cbp = data;
3212 
3213         if (cbp->cb_doclones) {
3214                 zfs_close(zhp);
3215                 return (0);
3216         }
3217 
3218         if (!cbp->cb_dependent) {
3219                 if (strcmp(zfs_get_name(zhp), cbp->cb_target) != 0 &&
3220                     zfs_get_type(zhp) == ZFS_TYPE_SNAPSHOT &&
3221                     zfs_prop_get_int(zhp, ZFS_PROP_CREATETXG) >
3222                     cbp->cb_create) {
3223 
3224                         if (cbp->cb_first && !cbp->cb_recurse) {
3225                                 (void) fprintf(stderr, gettext("cannot "
3226                                     "rollback to '%s': more recent snapshots "
3227                                     "exist\n"),
3228                                     cbp->cb_target);
3229                                 (void) fprintf(stderr, gettext("use '-r' to "
3230                                     "force deletion of the following "
3231                                     "snapshots:\n"));
3232                                 cbp->cb_first = 0;
3233                                 cbp->cb_error = 1;
3234                         }
3235 
3236                         if (cbp->cb_recurse) {
3237                                 cbp->cb_dependent = B_TRUE;
3238                                 if (zfs_iter_dependents(zhp, B_TRUE,
3239                                     rollback_check, cbp) != 0) {
3240                                         zfs_close(zhp);
3241                                         return (-1);
3242                                 }
3243                                 cbp->cb_dependent = B_FALSE;
3244                         } else {
3245                                 (void) fprintf(stderr, "%s\n",
3246                                     zfs_get_name(zhp));
3247                         }
3248                 }
3249         } else {
3250                 if (cbp->cb_first && cbp->cb_recurse) {
3251                         (void) fprintf(stderr, gettext("cannot rollback to "
3252                             "'%s': clones of previous snapshots exist\n"),
3253                             cbp->cb_target);
3254                         (void) fprintf(stderr, gettext("use '-R' to "
3255                             "force deletion of the following clones and "
3256                             "dependents:\n"));
3257                         cbp->cb_first = 0;
3258                         cbp->cb_error = 1;
3259                 }
3260 
3261                 (void) fprintf(stderr, "%s\n", zfs_get_name(zhp));
3262         }
3263 
3264         zfs_close(zhp);
3265         return (0);
3266 }
3267 
3268 static int
3269 zfs_do_rollback(int argc, char **argv)
3270 {
3271         int ret = 0;
3272         int c;
3273         boolean_t force = B_FALSE;
3274         rollback_cbdata_t cb = { 0 };
3275         zfs_handle_t *zhp, *snap;
3276         char parentname[ZFS_MAXNAMELEN];
3277         char *delim;
3278 
3279         /* check options */
3280         while ((c = getopt(argc, argv, "rRf")) != -1) {
3281                 switch (c) {
3282                 case 'r':
3283                         cb.cb_recurse = 1;
3284                         break;
3285                 case 'R':
3286                         cb.cb_recurse = 1;
3287                         cb.cb_doclones = 1;
3288                         break;
3289                 case 'f':
3290                         force = B_TRUE;
3291                         break;
3292                 case '?':
3293                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3294                             optopt);
3295                         usage(B_FALSE);
3296                 }
3297         }
3298 
3299         argc -= optind;
3300         argv += optind;
3301 
3302         /* check number of arguments */
3303         if (argc < 1) {
3304                 (void) fprintf(stderr, gettext("missing dataset argument\n"));
3305                 usage(B_FALSE);
3306         }
3307         if (argc > 1) {
3308                 (void) fprintf(stderr, gettext("too many arguments\n"));
3309                 usage(B_FALSE);
3310         }
3311 
3312         /* open the snapshot */
3313         if ((snap = zfs_open(g_zfs, argv[0], ZFS_TYPE_SNAPSHOT)) == NULL)
3314                 return (1);
3315 
3316         /* open the parent dataset */
3317         (void) strlcpy(parentname, argv[0], sizeof (parentname));
3318         verify((delim = strrchr(parentname, '@')) != NULL);
3319         *delim = '\0';
3320         if ((zhp = zfs_open(g_zfs, parentname, ZFS_TYPE_DATASET)) == NULL) {
3321                 zfs_close(snap);
3322                 return (1);
3323         }
3324 
3325         /*
3326          * Check for more recent snapshots and/or clones based on the presence
3327          * of '-r' and '-R'.
3328          */
3329         cb.cb_target = argv[0];
3330         cb.cb_create = zfs_prop_get_int(snap, ZFS_PROP_CREATETXG);
3331         cb.cb_first = B_TRUE;
3332         cb.cb_error = 0;
3333         if ((ret = zfs_iter_children(zhp, rollback_check, &cb)) != 0)
3334                 goto out;
3335 
3336         if ((ret = cb.cb_error) != 0)
3337                 goto out;
3338 
3339         /*
3340          * Rollback parent to the given snapshot.
3341          */
3342         ret = zfs_rollback(zhp, snap, force);
3343 
3344 out:
3345         zfs_close(snap);
3346         zfs_close(zhp);
3347 
3348         if (ret == 0)
3349                 return (0);
3350         else
3351                 return (1);
3352 }
3353 
3354 /*
3355  * zfs set property=value { fs | snap | vol } ...
3356  *
3357  * Sets the given property for all datasets specified on the command line.
3358  */
3359 typedef struct set_cbdata {
3360         char            *cb_propname;
3361         char            *cb_value;
3362 } set_cbdata_t;
3363 
3364 static int
3365 set_callback(zfs_handle_t *zhp, void *data)
3366 {
3367         set_cbdata_t *cbp = data;
3368 
3369         if (zfs_prop_set(zhp, cbp->cb_propname, cbp->cb_value) != 0) {
3370                 switch (libzfs_errno(g_zfs)) {
3371                 case EZFS_MOUNTFAILED:
3372                         (void) fprintf(stderr, gettext("property may be set "
3373                             "but unable to remount filesystem\n"));
3374                         break;
3375                 case EZFS_SHARENFSFAILED:
3376                         (void) fprintf(stderr, gettext("property may be set "
3377                             "but unable to reshare filesystem\n"));
3378                         break;
3379                 }
3380                 return (1);
3381         }
3382         return (0);
3383 }
3384 
3385 static int
3386 zfs_do_set(int argc, char **argv)
3387 {
3388         set_cbdata_t cb;
3389         int ret = 0;
3390 
3391         /* check for options */
3392         if (argc > 1 && argv[1][0] == '-') {
3393                 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3394                     argv[1][1]);
3395                 usage(B_FALSE);
3396         }
3397 
3398         /* check number of arguments */
3399         if (argc < 2) {
3400                 (void) fprintf(stderr, gettext("missing property=value "
3401                     "argument\n"));
3402                 usage(B_FALSE);
3403         }
3404         if (argc < 3) {
3405                 (void) fprintf(stderr, gettext("missing dataset name\n"));
3406                 usage(B_FALSE);
3407         }
3408 
3409         /* validate property=value argument */
3410         cb.cb_propname = argv[1];
3411         if (((cb.cb_value = strchr(cb.cb_propname, '=')) == NULL) ||
3412             (cb.cb_value[1] == '\0')) {
3413                 (void) fprintf(stderr, gettext("missing value in "
3414                     "property=value argument\n"));
3415                 usage(B_FALSE);
3416         }
3417 
3418         *cb.cb_value = '\0';
3419         cb.cb_value++;
3420 
3421         if (*cb.cb_propname == '\0') {
3422                 (void) fprintf(stderr,
3423                     gettext("missing property in property=value argument\n"));
3424                 usage(B_FALSE);
3425         }
3426 
3427         ret = zfs_for_each(argc - 2, argv + 2, NULL,
3428             ZFS_TYPE_DATASET, NULL, NULL, 0, set_callback, &cb);
3429 
3430         return (ret);
3431 }
3432 
3433 typedef struct snap_cbdata {
3434         nvlist_t *sd_nvl;
3435         boolean_t sd_recursive;
3436         const char *sd_snapname;
3437 } snap_cbdata_t;
3438 
3439 static int
3440 zfs_snapshot_cb(zfs_handle_t *zhp, void *arg)
3441 {
3442         snap_cbdata_t *sd = arg;
3443         char *name;
3444         int rv = 0;
3445         int error;
3446 
3447         error = asprintf(&name, "%s@%s", zfs_get_name(zhp), sd->sd_snapname);
3448         if (error == -1)
3449                 nomem();
3450         fnvlist_add_boolean(sd->sd_nvl, name);
3451         free(name);
3452 
3453         if (sd->sd_recursive)
3454                 rv = zfs_iter_filesystems(zhp, zfs_snapshot_cb, sd);
3455         zfs_close(zhp);
3456         return (rv);
3457 }
3458 
3459 /*
3460  * zfs snapshot [-r] [-o prop=value] ... <fs@snap>
3461  *
3462  * Creates a snapshot with the given name.  While functionally equivalent to
3463  * 'zfs create', it is a separate command to differentiate intent.
3464  */
3465 static int
3466 zfs_do_snapshot(int argc, char **argv)
3467 {
3468         int ret = 0;
3469         char c;
3470         nvlist_t *props;
3471         snap_cbdata_t sd = { 0 };
3472         boolean_t multiple_snaps = B_FALSE;
3473 
3474         if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0)
3475                 nomem();
3476         if (nvlist_alloc(&sd.sd_nvl, NV_UNIQUE_NAME, 0) != 0)
3477                 nomem();
3478 
3479         /* check options */
3480         while ((c = getopt(argc, argv, "ro:")) != -1) {
3481                 switch (c) {
3482                 case 'o':
3483                         if (parseprop(props))
3484                                 return (1);
3485                         break;
3486                 case 'r':
3487                         sd.sd_recursive = B_TRUE;
3488                         multiple_snaps = B_TRUE;
3489                         break;
3490                 case '?':
3491                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3492                             optopt);
3493                         goto usage;
3494                 }
3495         }
3496 
3497         argc -= optind;
3498         argv += optind;
3499 
3500         /* check number of arguments */
3501         if (argc < 1) {
3502                 (void) fprintf(stderr, gettext("missing snapshot argument\n"));
3503                 goto usage;
3504         }
3505 
3506         if (argc > 1)
3507                 multiple_snaps = B_TRUE;
3508         for (; argc > 0; argc--, argv++) {
3509                 char *atp;
3510                 zfs_handle_t *zhp;
3511 
3512                 atp = strchr(argv[0], '@');
3513                 if (atp == NULL)
3514                         goto usage;
3515                 *atp = '\0';
3516                 sd.sd_snapname = atp + 1;
3517                 zhp = zfs_open(g_zfs, argv[0],
3518                     ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
3519                 if (zhp == NULL)
3520                         goto usage;
3521                 if (zfs_snapshot_cb(zhp, &sd) != 0)
3522                         goto usage;
3523         }
3524 
3525         ret = zfs_snapshot_nvl(g_zfs, sd.sd_nvl, props);
3526         nvlist_free(sd.sd_nvl);
3527         nvlist_free(props);
3528         if (ret != 0 && multiple_snaps)
3529                 (void) fprintf(stderr, gettext("no snapshots were created\n"));
3530         return (ret != 0);
3531 
3532 usage:
3533         nvlist_free(sd.sd_nvl);
3534         nvlist_free(props);
3535         usage(B_FALSE);
3536         return (-1);
3537 }
3538 
3539 /*
3540  * Send a backup stream to stdout.
3541  */
3542 static int
3543 zfs_do_send(int argc, char **argv)
3544 {
3545         char *fromname = NULL;
3546         char *toname = NULL;
3547         char *cp;
3548         zfs_handle_t *zhp;
3549         sendflags_t flags = { 0 };
3550         int c, err;
3551         nvlist_t *dbgnv = NULL;
3552         boolean_t extraverbose = B_FALSE;
3553 
3554         /* check options */
3555         while ((c = getopt(argc, argv, ":i:I:RDpvnPs")) != -1) {
3556                 switch (c) {
3557                 case 'i':
3558                         if (fromname)
3559                                 usage(B_FALSE);
3560                         fromname = optarg;
3561                         break;
3562                 case 'I':
3563                         if (fromname)
3564                                 usage(B_FALSE);
3565                         fromname = optarg;
3566                         flags.doall = B_TRUE;
3567                         break;
3568                 case 'R':
3569                         flags.replicate = B_TRUE;
3570                         break;
3571                 case 'p':
3572                         flags.props = B_TRUE;
3573                         break;
3574                 case 'P':
3575                         flags.parsable = B_TRUE;
3576                         flags.verbose = B_TRUE;
3577                         break;
3578                 case 'v':
3579                         if (flags.verbose)
3580                                 extraverbose = B_TRUE;
3581                         flags.verbose = B_TRUE;
3582                         flags.progress = B_TRUE;
3583                         break;
3584                 case 'D':
3585                         flags.dedup = B_TRUE;
3586                         break;
3587                 case 'n':
3588                         flags.dryrun = B_TRUE;
3589                         break;
3590                 case 's':
3591                         flags.sendsize = B_TRUE;
3592                         break;
3593                 case ':':
3594                         (void) fprintf(stderr, gettext("missing argument for "
3595                             "'%c' option\n"), optopt);
3596                         usage(B_FALSE);
3597                         break;
3598                 case '?':
3599                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3600                             optopt);
3601                         usage(B_FALSE);
3602                 }
3603         }
3604 
3605         argc -= optind;
3606         argv += optind;
3607 
3608         /* check number of arguments */
3609         if (argc < 1) {
3610                 (void) fprintf(stderr, gettext("missing snapshot argument\n"));
3611                 usage(B_FALSE);
3612         }
3613         if (argc > 1) {
3614                 (void) fprintf(stderr, gettext("too many arguments\n"));
3615                 usage(B_FALSE);
3616         }
3617 
3618         if (flags.sendsize) {
3619                 (void) close(STDOUT_FILENO);
3620                 (void) open("/dev/null", O_WRONLY|O_LARGEFILE);
3621         } else if (!flags.dryrun && isatty(STDOUT_FILENO)) {
3622                 (void) fprintf(stderr,
3623                     gettext("Error: Stream can not be written to a terminal.\n"
3624                     "You must redirect standard output.\n"));
3625                 return (1);
3626         }
3627 
3628         cp = strchr(argv[0], '@');
3629         if (cp == NULL) {
3630                 (void) fprintf(stderr,
3631                     gettext("argument must be a snapshot\n"));
3632                 usage(B_FALSE);
3633         }
3634         *cp = '\0';
3635         toname = cp + 1;
3636         zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
3637         if (zhp == NULL)
3638                 return (1);
3639 
3640         /*
3641          * If they specified the full path to the snapshot, chop off
3642          * everything except the short name of the snapshot, but special
3643          * case if they specify the origin.
3644          */
3645         if (fromname && (cp = strchr(fromname, '@')) != NULL) {
3646                 char origin[ZFS_MAXNAMELEN];
3647                 zprop_source_t src;
3648 
3649                 (void) zfs_prop_get(zhp, ZFS_PROP_ORIGIN,
3650                     origin, sizeof (origin), &src, NULL, 0, B_FALSE);
3651 
3652                 if (strcmp(origin, fromname) == 0) {
3653                         fromname = NULL;
3654                         flags.fromorigin = B_TRUE;
3655                 } else {
3656                         *cp = '\0';
3657                         if (cp != fromname && strcmp(argv[0], fromname)) {
3658                                 (void) fprintf(stderr,
3659                                     gettext("incremental source must be "
3660                                     "in same filesystem\n"));
3661                                 usage(B_FALSE);
3662                         }
3663                         fromname = cp + 1;
3664                         if (strchr(fromname, '@') || strchr(fromname, '/')) {
3665                                 (void) fprintf(stderr,
3666                                     gettext("invalid incremental source\n"));
3667                                 usage(B_FALSE);
3668                         }
3669                 }
3670         }
3671 
3672         if (flags.replicate && fromname == NULL)
3673                 flags.doall = B_TRUE;
3674 
3675         err = zfs_send(zhp, fromname, toname, &flags, STDOUT_FILENO, NULL, 0,
3676             extraverbose ? &dbgnv : NULL);
3677 
3678         if (extraverbose && dbgnv != NULL) {
3679                 /*
3680                  * dump_nvlist prints to stdout, but that's been
3681                  * redirected to a file.  Make it print to stderr
3682                  * instead.
3683                  */
3684                 (void) dup2(STDERR_FILENO, STDOUT_FILENO);
3685                 dump_nvlist(dbgnv, 0);
3686                 nvlist_free(dbgnv);
3687         }
3688         zfs_close(zhp);
3689 
3690         return (err != 0);
3691 }
3692 
3693 /*
3694  * zfs receive [-vnFu] [-d | -e] <fs@snap>
3695  *
3696  * Restore a backup stream from stdin.
3697  */
3698 static int
3699 zfs_do_receive(int argc, char **argv)
3700 {
3701         int c, err;
3702         recvflags_t flags = { 0 };
3703 
3704         /* check options */
3705         while ((c = getopt(argc, argv, ":denuvF")) != -1) {
3706                 switch (c) {
3707                 case 'd':
3708                         flags.isprefix = B_TRUE;
3709                         break;
3710                 case 'e':
3711                         flags.isprefix = B_TRUE;
3712                         flags.istail = B_TRUE;
3713                         break;
3714                 case 'n':
3715                         flags.dryrun = B_TRUE;
3716                         break;
3717                 case 'u':
3718                         flags.nomount = B_TRUE;
3719                         break;
3720                 case 'v':
3721                         flags.verbose = B_TRUE;
3722                         break;
3723                 case 'F':
3724                         flags.force = B_TRUE;
3725                         break;
3726                 case ':':
3727                         (void) fprintf(stderr, gettext("missing argument for "
3728                             "'%c' option\n"), optopt);
3729                         usage(B_FALSE);
3730                         break;
3731                 case '?':
3732                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3733                             optopt);
3734                         usage(B_FALSE);
3735                 }
3736         }
3737 
3738         argc -= optind;
3739         argv += optind;
3740 
3741         /* check number of arguments */
3742         if (argc < 1) {
3743                 (void) fprintf(stderr, gettext("missing snapshot argument\n"));
3744                 usage(B_FALSE);
3745         }
3746         if (argc > 1) {
3747                 (void) fprintf(stderr, gettext("too many arguments\n"));
3748                 usage(B_FALSE);
3749         }
3750 
3751         if (isatty(STDIN_FILENO)) {
3752                 (void) fprintf(stderr,
3753                     gettext("Error: Backup stream can not be read "
3754                     "from a terminal.\n"
3755                     "You must redirect standard input.\n"));
3756                 return (1);
3757         }
3758 
3759         err = zfs_receive(g_zfs, argv[0], &flags, STDIN_FILENO, NULL);
3760 
3761         return (err != 0);
3762 }
3763 
3764 /*
3765  * allow/unallow stuff
3766  */
3767 /* copied from zfs/sys/dsl_deleg.h */
3768 #define ZFS_DELEG_PERM_CREATE           "create"
3769 #define ZFS_DELEG_PERM_DESTROY          "destroy"
3770 #define ZFS_DELEG_PERM_SNAPSHOT         "snapshot"
3771 #define ZFS_DELEG_PERM_ROLLBACK         "rollback"
3772 #define ZFS_DELEG_PERM_CLONE            "clone"
3773 #define ZFS_DELEG_PERM_PROMOTE          "promote"
3774 #define ZFS_DELEG_PERM_RENAME           "rename"
3775 #define ZFS_DELEG_PERM_MOUNT            "mount"
3776 #define ZFS_DELEG_PERM_SHARE            "share"
3777 #define ZFS_DELEG_PERM_SEND             "send"
3778 #define ZFS_DELEG_PERM_RECEIVE          "receive"
3779 #define ZFS_DELEG_PERM_ALLOW            "allow"
3780 #define ZFS_DELEG_PERM_USERPROP         "userprop"
3781 #define ZFS_DELEG_PERM_VSCAN            "vscan" /* ??? */
3782 #define ZFS_DELEG_PERM_USERQUOTA        "userquota"
3783 #define ZFS_DELEG_PERM_GROUPQUOTA       "groupquota"
3784 #define ZFS_DELEG_PERM_USERUSED         "userused"
3785 #define ZFS_DELEG_PERM_GROUPUSED        "groupused"
3786 #define ZFS_DELEG_PERM_HOLD             "hold"
3787 #define ZFS_DELEG_PERM_RELEASE          "release"
3788 #define ZFS_DELEG_PERM_DIFF             "diff"
3789 
3790 #define ZFS_NUM_DELEG_NOTES ZFS_DELEG_NOTE_NONE
3791 
3792 static zfs_deleg_perm_tab_t zfs_deleg_perm_tbl[] = {
3793         { ZFS_DELEG_PERM_ALLOW, ZFS_DELEG_NOTE_ALLOW },
3794         { ZFS_DELEG_PERM_CLONE, ZFS_DELEG_NOTE_CLONE },
3795         { ZFS_DELEG_PERM_CREATE, ZFS_DELEG_NOTE_CREATE },
3796         { ZFS_DELEG_PERM_DESTROY, ZFS_DELEG_NOTE_DESTROY },
3797         { ZFS_DELEG_PERM_DIFF, ZFS_DELEG_NOTE_DIFF},
3798         { ZFS_DELEG_PERM_HOLD, ZFS_DELEG_NOTE_HOLD },
3799         { ZFS_DELEG_PERM_MOUNT, ZFS_DELEG_NOTE_MOUNT },
3800         { ZFS_DELEG_PERM_PROMOTE, ZFS_DELEG_NOTE_PROMOTE },
3801         { ZFS_DELEG_PERM_RECEIVE, ZFS_DELEG_NOTE_RECEIVE },
3802         { ZFS_DELEG_PERM_RELEASE, ZFS_DELEG_NOTE_RELEASE },
3803         { ZFS_DELEG_PERM_RENAME, ZFS_DELEG_NOTE_RENAME },
3804         { ZFS_DELEG_PERM_ROLLBACK, ZFS_DELEG_NOTE_ROLLBACK },
3805         { ZFS_DELEG_PERM_SEND, ZFS_DELEG_NOTE_SEND },
3806         { ZFS_DELEG_PERM_SHARE, ZFS_DELEG_NOTE_SHARE },
3807         { ZFS_DELEG_PERM_SNAPSHOT, ZFS_DELEG_NOTE_SNAPSHOT },
3808 
3809         { ZFS_DELEG_PERM_GROUPQUOTA, ZFS_DELEG_NOTE_GROUPQUOTA },
3810         { ZFS_DELEG_PERM_GROUPUSED, ZFS_DELEG_NOTE_GROUPUSED },
3811         { ZFS_DELEG_PERM_USERPROP, ZFS_DELEG_NOTE_USERPROP },
3812         { ZFS_DELEG_PERM_USERQUOTA, ZFS_DELEG_NOTE_USERQUOTA },
3813         { ZFS_DELEG_PERM_USERUSED, ZFS_DELEG_NOTE_USERUSED },
3814         { NULL, ZFS_DELEG_NOTE_NONE }
3815 };
3816 
3817 /* permission structure */
3818 typedef struct deleg_perm {
3819         zfs_deleg_who_type_t    dp_who_type;
3820         const char              *dp_name;
3821         boolean_t               dp_local;
3822         boolean_t               dp_descend;
3823 } deleg_perm_t;
3824 
3825 /* */
3826 typedef struct deleg_perm_node {
3827         deleg_perm_t            dpn_perm;
3828 
3829         uu_avl_node_t           dpn_avl_node;
3830 } deleg_perm_node_t;
3831 
3832 typedef struct fs_perm fs_perm_t;
3833 
3834 /* permissions set */
3835 typedef struct who_perm {
3836         zfs_deleg_who_type_t    who_type;
3837         const char              *who_name;              /* id */
3838         char                    who_ug_name[256];       /* user/group name */
3839         fs_perm_t               *who_fsperm;            /* uplink */
3840 
3841         uu_avl_t                *who_deleg_perm_avl;    /* permissions */
3842 } who_perm_t;
3843 
3844 /* */
3845 typedef struct who_perm_node {
3846         who_perm_t      who_perm;
3847         uu_avl_node_t   who_avl_node;
3848 } who_perm_node_t;
3849 
3850 typedef struct fs_perm_set fs_perm_set_t;
3851 /* fs permissions */
3852 struct fs_perm {
3853         const char              *fsp_name;
3854 
3855         uu_avl_t                *fsp_sc_avl;    /* sets,create */
3856         uu_avl_t                *fsp_uge_avl;   /* user,group,everyone */
3857 
3858         fs_perm_set_t           *fsp_set;       /* uplink */
3859 };
3860 
3861 /* */
3862 typedef struct fs_perm_node {
3863         fs_perm_t       fspn_fsperm;
3864         uu_avl_t        *fspn_avl;
3865 
3866         uu_list_node_t  fspn_list_node;
3867 } fs_perm_node_t;
3868 
3869 /* top level structure */
3870 struct fs_perm_set {
3871         uu_list_pool_t  *fsps_list_pool;
3872         uu_list_t       *fsps_list; /* list of fs_perms */
3873 
3874         uu_avl_pool_t   *fsps_named_set_avl_pool;
3875         uu_avl_pool_t   *fsps_who_perm_avl_pool;
3876         uu_avl_pool_t   *fsps_deleg_perm_avl_pool;
3877 };
3878 
3879 static inline const char *
3880 deleg_perm_type(zfs_deleg_note_t note)
3881 {
3882         /* subcommands */
3883         switch (note) {
3884                 /* SUBCOMMANDS */
3885                 /* OTHER */
3886         case ZFS_DELEG_NOTE_GROUPQUOTA:
3887         case ZFS_DELEG_NOTE_GROUPUSED:
3888         case ZFS_DELEG_NOTE_USERPROP:
3889         case ZFS_DELEG_NOTE_USERQUOTA:
3890         case ZFS_DELEG_NOTE_USERUSED:
3891                 /* other */
3892                 return (gettext("other"));
3893         default:
3894                 return (gettext("subcommand"));
3895         }
3896 }
3897 
3898 static int inline
3899 who_type2weight(zfs_deleg_who_type_t who_type)
3900 {
3901         int res;
3902         switch (who_type) {
3903                 case ZFS_DELEG_NAMED_SET_SETS:
3904                 case ZFS_DELEG_NAMED_SET:
3905                         res = 0;
3906                         break;
3907                 case ZFS_DELEG_CREATE_SETS:
3908                 case ZFS_DELEG_CREATE:
3909                         res = 1;
3910                         break;
3911                 case ZFS_DELEG_USER_SETS:
3912                 case ZFS_DELEG_USER:
3913                         res = 2;
3914                         break;
3915                 case ZFS_DELEG_GROUP_SETS:
3916                 case ZFS_DELEG_GROUP:
3917                         res = 3;
3918                         break;
3919                 case ZFS_DELEG_EVERYONE_SETS:
3920                 case ZFS_DELEG_EVERYONE:
3921                         res = 4;
3922                         break;
3923                 default:
3924                         res = -1;
3925         }
3926 
3927         return (res);
3928 }
3929 
3930 /* ARGSUSED */
3931 static int
3932 who_perm_compare(const void *larg, const void *rarg, void *unused)
3933 {
3934         const who_perm_node_t *l = larg;
3935         const who_perm_node_t *r = rarg;
3936         zfs_deleg_who_type_t ltype = l->who_perm.who_type;
3937         zfs_deleg_who_type_t rtype = r->who_perm.who_type;
3938         int lweight = who_type2weight(ltype);
3939         int rweight = who_type2weight(rtype);
3940         int res = lweight - rweight;
3941         if (res == 0)
3942                 res = strncmp(l->who_perm.who_name, r->who_perm.who_name,
3943                     ZFS_MAX_DELEG_NAME-1);
3944 
3945         if (res == 0)
3946                 return (0);
3947         if (res > 0)
3948                 return (1);
3949         else
3950                 return (-1);
3951 }
3952 
3953 /* ARGSUSED */
3954 static int
3955 deleg_perm_compare(const void *larg, const void *rarg, void *unused)
3956 {
3957         const deleg_perm_node_t *l = larg;
3958         const deleg_perm_node_t *r = rarg;
3959         int res =  strncmp(l->dpn_perm.dp_name, r->dpn_perm.dp_name,
3960             ZFS_MAX_DELEG_NAME-1);
3961 
3962         if (res == 0)
3963                 return (0);
3964 
3965         if (res > 0)
3966                 return (1);
3967         else
3968                 return (-1);
3969 }
3970 
3971 static inline void
3972 fs_perm_set_init(fs_perm_set_t *fspset)
3973 {
3974         bzero(fspset, sizeof (fs_perm_set_t));
3975 
3976         if ((fspset->fsps_list_pool = uu_list_pool_create("fsps_list_pool",
3977             sizeof (fs_perm_node_t), offsetof(fs_perm_node_t, fspn_list_node),
3978             NULL, UU_DEFAULT)) == NULL)
3979                 nomem();
3980         if ((fspset->fsps_list = uu_list_create(fspset->fsps_list_pool, NULL,
3981             UU_DEFAULT)) == NULL)
3982                 nomem();
3983 
3984         if ((fspset->fsps_named_set_avl_pool = uu_avl_pool_create(
3985             "named_set_avl_pool", sizeof (who_perm_node_t), offsetof(
3986             who_perm_node_t, who_avl_node), who_perm_compare,
3987             UU_DEFAULT)) == NULL)
3988                 nomem();
3989 
3990         if ((fspset->fsps_who_perm_avl_pool = uu_avl_pool_create(
3991             "who_perm_avl_pool", sizeof (who_perm_node_t), offsetof(
3992             who_perm_node_t, who_avl_node), who_perm_compare,
3993             UU_DEFAULT)) == NULL)
3994                 nomem();
3995 
3996         if ((fspset->fsps_deleg_perm_avl_pool = uu_avl_pool_create(
3997             "deleg_perm_avl_pool", sizeof (deleg_perm_node_t), offsetof(
3998             deleg_perm_node_t, dpn_avl_node), deleg_perm_compare, UU_DEFAULT))
3999             == NULL)
4000                 nomem();
4001 }
4002 
4003 static inline void fs_perm_fini(fs_perm_t *);
4004 static inline void who_perm_fini(who_perm_t *);
4005 
4006 static inline void
4007 fs_perm_set_fini(fs_perm_set_t *fspset)
4008 {
4009         fs_perm_node_t *node = uu_list_first(fspset->fsps_list);
4010 
4011         while (node != NULL) {
4012                 fs_perm_node_t *next_node =
4013                     uu_list_next(fspset->fsps_list, node);
4014                 fs_perm_t *fsperm = &node->fspn_fsperm;
4015                 fs_perm_fini(fsperm);
4016                 uu_list_remove(fspset->fsps_list, node);
4017                 free(node);
4018                 node = next_node;
4019         }
4020 
4021         uu_avl_pool_destroy(fspset->fsps_named_set_avl_pool);
4022         uu_avl_pool_destroy(fspset->fsps_who_perm_avl_pool);
4023         uu_avl_pool_destroy(fspset->fsps_deleg_perm_avl_pool);
4024 }
4025 
4026 static inline void
4027 deleg_perm_init(deleg_perm_t *deleg_perm, zfs_deleg_who_type_t type,
4028     const char *name)
4029 {
4030         deleg_perm->dp_who_type = type;
4031         deleg_perm->dp_name = name;
4032 }
4033 
4034 static inline void
4035 who_perm_init(who_perm_t *who_perm, fs_perm_t *fsperm,
4036     zfs_deleg_who_type_t type, const char *name)
4037 {
4038         uu_avl_pool_t   *pool;
4039         pool = fsperm->fsp_set->fsps_deleg_perm_avl_pool;
4040 
4041         bzero(who_perm, sizeof (who_perm_t));
4042 
4043         if ((who_perm->who_deleg_perm_avl = uu_avl_create(pool, NULL,
4044             UU_DEFAULT)) == NULL)
4045                 nomem();
4046 
4047         who_perm->who_type = type;
4048         who_perm->who_name = name;
4049         who_perm->who_fsperm = fsperm;
4050 }
4051 
4052 static inline void
4053 who_perm_fini(who_perm_t *who_perm)
4054 {
4055         deleg_perm_node_t *node = uu_avl_first(who_perm->who_deleg_perm_avl);
4056 
4057         while (node != NULL) {
4058                 deleg_perm_node_t *next_node =
4059                     uu_avl_next(who_perm->who_deleg_perm_avl, node);
4060 
4061                 uu_avl_remove(who_perm->who_deleg_perm_avl, node);
4062                 free(node);
4063                 node = next_node;
4064         }
4065 
4066         uu_avl_destroy(who_perm->who_deleg_perm_avl);
4067 }
4068 
4069 static inline void
4070 fs_perm_init(fs_perm_t *fsperm, fs_perm_set_t *fspset, const char *fsname)
4071 {
4072         uu_avl_pool_t   *nset_pool = fspset->fsps_named_set_avl_pool;
4073         uu_avl_pool_t   *who_pool = fspset->fsps_who_perm_avl_pool;
4074 
4075         bzero(fsperm, sizeof (fs_perm_t));
4076 
4077         if ((fsperm->fsp_sc_avl = uu_avl_create(nset_pool, NULL, UU_DEFAULT))
4078             == NULL)
4079                 nomem();
4080 
4081         if ((fsperm->fsp_uge_avl = uu_avl_create(who_pool, NULL, UU_DEFAULT))
4082             == NULL)
4083                 nomem();
4084 
4085         fsperm->fsp_set = fspset;
4086         fsperm->fsp_name = fsname;
4087 }
4088 
4089 static inline void
4090 fs_perm_fini(fs_perm_t *fsperm)
4091 {
4092         who_perm_node_t *node = uu_avl_first(fsperm->fsp_sc_avl);
4093         while (node != NULL) {
4094                 who_perm_node_t *next_node = uu_avl_next(fsperm->fsp_sc_avl,
4095                     node);
4096                 who_perm_t *who_perm = &node->who_perm;
4097                 who_perm_fini(who_perm);
4098                 uu_avl_remove(fsperm->fsp_sc_avl, node);
4099                 free(node);
4100                 node = next_node;
4101         }
4102 
4103         node = uu_avl_first(fsperm->fsp_uge_avl);
4104         while (node != NULL) {
4105                 who_perm_node_t *next_node = uu_avl_next(fsperm->fsp_uge_avl,
4106                     node);
4107                 who_perm_t *who_perm = &node->who_perm;
4108                 who_perm_fini(who_perm);
4109                 uu_avl_remove(fsperm->fsp_uge_avl, node);
4110                 free(node);
4111                 node = next_node;
4112         }
4113 
4114         uu_avl_destroy(fsperm->fsp_sc_avl);
4115         uu_avl_destroy(fsperm->fsp_uge_avl);
4116 }
4117 
4118 static void inline
4119 set_deleg_perm_node(uu_avl_t *avl, deleg_perm_node_t *node,
4120     zfs_deleg_who_type_t who_type, const char *name, char locality)
4121 {
4122         uu_avl_index_t idx = 0;
4123 
4124         deleg_perm_node_t *found_node = NULL;
4125         deleg_perm_t    *deleg_perm = &node->dpn_perm;
4126 
4127         deleg_perm_init(deleg_perm, who_type, name);
4128 
4129         if ((found_node = uu_avl_find(avl, node, NULL, &idx))
4130             == NULL)
4131                 uu_avl_insert(avl, node, idx);
4132         else {
4133                 node = found_node;
4134                 deleg_perm = &node->dpn_perm;
4135         }
4136 
4137 
4138         switch (locality) {
4139         case ZFS_DELEG_LOCAL:
4140                 deleg_perm->dp_local = B_TRUE;
4141                 break;
4142         case ZFS_DELEG_DESCENDENT:
4143                 deleg_perm->dp_descend = B_TRUE;
4144                 break;
4145         case ZFS_DELEG_NA:
4146                 break;
4147         default:
4148                 assert(B_FALSE); /* invalid locality */
4149         }
4150 }
4151 
4152 static inline int
4153 parse_who_perm(who_perm_t *who_perm, nvlist_t *nvl, char locality)
4154 {
4155         nvpair_t *nvp = NULL;
4156         fs_perm_set_t *fspset = who_perm->who_fsperm->fsp_set;
4157         uu_avl_t *avl = who_perm->who_deleg_perm_avl;
4158         zfs_deleg_who_type_t who_type = who_perm->who_type;
4159 
4160         while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
4161                 const char *name = nvpair_name(nvp);
4162                 data_type_t type = nvpair_type(nvp);
4163                 uu_avl_pool_t *avl_pool = fspset->fsps_deleg_perm_avl_pool;
4164                 deleg_perm_node_t *node =
4165                     safe_malloc(sizeof (deleg_perm_node_t));
4166 
4167                 assert(type == DATA_TYPE_BOOLEAN);
4168 
4169                 uu_avl_node_init(node, &node->dpn_avl_node, avl_pool);
4170                 set_deleg_perm_node(avl, node, who_type, name, locality);
4171         }
4172 
4173         return (0);
4174 }
4175 
4176 static inline int
4177 parse_fs_perm(fs_perm_t *fsperm, nvlist_t *nvl)
4178 {
4179         nvpair_t *nvp = NULL;
4180         fs_perm_set_t *fspset = fsperm->fsp_set;
4181 
4182         while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
4183                 nvlist_t *nvl2 = NULL;
4184                 const char *name = nvpair_name(nvp);
4185                 uu_avl_t *avl = NULL;
4186                 uu_avl_pool_t *avl_pool;
4187                 zfs_deleg_who_type_t perm_type = name[0];
4188                 char perm_locality = name[1];
4189                 const char *perm_name = name + 3;
4190                 boolean_t is_set = B_TRUE;
4191                 who_perm_t *who_perm = NULL;
4192 
4193                 assert('$' == name[2]);
4194 
4195                 if (nvpair_value_nvlist(nvp, &nvl2) != 0)
4196                         return (-1);
4197 
4198                 switch (perm_type) {
4199                 case ZFS_DELEG_CREATE:
4200                 case ZFS_DELEG_CREATE_SETS:
4201                 case ZFS_DELEG_NAMED_SET:
4202                 case ZFS_DELEG_NAMED_SET_SETS:
4203                         avl_pool = fspset->fsps_named_set_avl_pool;
4204                         avl = fsperm->fsp_sc_avl;
4205                         break;
4206                 case ZFS_DELEG_USER:
4207                 case ZFS_DELEG_USER_SETS:
4208                 case ZFS_DELEG_GROUP:
4209                 case ZFS_DELEG_GROUP_SETS:
4210                 case ZFS_DELEG_EVERYONE:
4211                 case ZFS_DELEG_EVERYONE_SETS:
4212                         avl_pool = fspset->fsps_who_perm_avl_pool;
4213                         avl = fsperm->fsp_uge_avl;
4214                         break;
4215                 }
4216 
4217                 if (is_set) {
4218                         who_perm_node_t *found_node = NULL;
4219                         who_perm_node_t *node = safe_malloc(
4220                             sizeof (who_perm_node_t));
4221                         who_perm = &node->who_perm;
4222                         uu_avl_index_t idx = 0;
4223 
4224                         uu_avl_node_init(node, &node->who_avl_node, avl_pool);
4225                         who_perm_init(who_perm, fsperm, perm_type, perm_name);
4226 
4227                         if ((found_node = uu_avl_find(avl, node, NULL, &idx))
4228                             == NULL) {
4229                                 if (avl == fsperm->fsp_uge_avl) {
4230                                         uid_t rid = 0;
4231                                         struct passwd *p = NULL;
4232                                         struct group *g = NULL;
4233                                         const char *nice_name = NULL;
4234 
4235                                         switch (perm_type) {
4236                                         case ZFS_DELEG_USER_SETS:
4237                                         case ZFS_DELEG_USER:
4238                                                 rid = atoi(perm_name);
4239                                                 p = getpwuid(rid);
4240                                                 if (p)
4241                                                         nice_name = p->pw_name;
4242                                                 break;
4243                                         case ZFS_DELEG_GROUP_SETS:
4244                                         case ZFS_DELEG_GROUP:
4245                                                 rid = atoi(perm_name);
4246                                                 g = getgrgid(rid);
4247                                                 if (g)
4248                                                         nice_name = g->gr_name;
4249                                                 break;
4250                                         }
4251 
4252                                         if (nice_name != NULL)
4253                                                 (void) strlcpy(
4254                                                     node->who_perm.who_ug_name,
4255                                                     nice_name, 256);
4256                                 }
4257 
4258                                 uu_avl_insert(avl, node, idx);
4259                         } else {
4260                                 node = found_node;
4261                                 who_perm = &node->who_perm;
4262                         }
4263                 }
4264 
4265                 (void) parse_who_perm(who_perm, nvl2, perm_locality);
4266         }
4267 
4268         return (0);
4269 }
4270 
4271 static inline int
4272 parse_fs_perm_set(fs_perm_set_t *fspset, nvlist_t *nvl)
4273 {
4274         nvpair_t *nvp = NULL;
4275         uu_avl_index_t idx = 0;
4276 
4277         while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
4278                 nvlist_t *nvl2 = NULL;
4279                 const char *fsname = nvpair_name(nvp);
4280                 data_type_t type = nvpair_type(nvp);
4281                 fs_perm_t *fsperm = NULL;
4282                 fs_perm_node_t *node = safe_malloc(sizeof (fs_perm_node_t));
4283                 if (node == NULL)
4284                         nomem();
4285 
4286                 fsperm = &node->fspn_fsperm;
4287 
4288                 assert(DATA_TYPE_NVLIST == type);
4289 
4290                 uu_list_node_init(node, &node->fspn_list_node,
4291                     fspset->fsps_list_pool);
4292 
4293                 idx = uu_list_numnodes(fspset->fsps_list);
4294                 fs_perm_init(fsperm, fspset, fsname);
4295 
4296                 if (nvpair_value_nvlist(nvp, &nvl2) != 0)
4297                         return (-1);
4298 
4299                 (void) parse_fs_perm(fsperm, nvl2);
4300 
4301                 uu_list_insert(fspset->fsps_list, node, idx);
4302         }
4303 
4304         return (0);
4305 }
4306 
4307 static inline const char *
4308 deleg_perm_comment(zfs_deleg_note_t note)
4309 {
4310         const char *str = "";
4311 
4312         /* subcommands */
4313         switch (note) {
4314                 /* SUBCOMMANDS */
4315         case ZFS_DELEG_NOTE_ALLOW:
4316                 str = gettext("Must also have the permission that is being"
4317                     "\n\t\t\t\tallowed");
4318                 break;
4319         case ZFS_DELEG_NOTE_CLONE:
4320                 str = gettext("Must also have the 'create' ability and 'mount'"
4321                     "\n\t\t\t\tability in the origin file system");
4322                 break;
4323         case ZFS_DELEG_NOTE_CREATE:
4324                 str = gettext("Must also have the 'mount' ability");
4325                 break;
4326         case ZFS_DELEG_NOTE_DESTROY:
4327                 str = gettext("Must also have the 'mount' ability");
4328                 break;
4329         case ZFS_DELEG_NOTE_DIFF:
4330                 str = gettext("Allows lookup of paths within a dataset;"
4331                     "\n\t\t\t\tgiven an object number. Ordinary users need this"
4332                     "\n\t\t\t\tin order to use zfs diff");
4333                 break;
4334         case ZFS_DELEG_NOTE_HOLD:
4335                 str = gettext("Allows adding a user hold to a snapshot");
4336                 break;
4337         case ZFS_DELEG_NOTE_MOUNT:
4338                 str = gettext("Allows mount/umount of ZFS datasets");
4339                 break;
4340         case ZFS_DELEG_NOTE_PROMOTE:
4341                 str = gettext("Must also have the 'mount'\n\t\t\t\tand"
4342                     " 'promote' ability in the origin file system");
4343                 break;
4344         case ZFS_DELEG_NOTE_RECEIVE:
4345                 str = gettext("Must also have the 'mount' and 'create'"
4346                     " ability");
4347                 break;
4348         case ZFS_DELEG_NOTE_RELEASE:
4349                 str = gettext("Allows releasing a user hold which\n\t\t\t\t"
4350                     "might destroy the snapshot");
4351                 break;
4352         case ZFS_DELEG_NOTE_RENAME:
4353                 str = gettext("Must also have the 'mount' and 'create'"
4354                     "\n\t\t\t\tability in the new parent");
4355                 break;
4356         case ZFS_DELEG_NOTE_ROLLBACK:
4357                 str = gettext("");
4358                 break;
4359         case ZFS_DELEG_NOTE_SEND:
4360                 str = gettext("");
4361                 break;
4362         case ZFS_DELEG_NOTE_SHARE:
4363                 str = gettext("Allows sharing file systems over NFS or SMB"
4364                     "\n\t\t\t\tprotocols");
4365                 break;
4366         case ZFS_DELEG_NOTE_SNAPSHOT:
4367                 str = gettext("");
4368                 break;
4369 /*
4370  *      case ZFS_DELEG_NOTE_VSCAN:
4371  *              str = gettext("");
4372  *              break;
4373  */
4374                 /* OTHER */
4375         case ZFS_DELEG_NOTE_GROUPQUOTA:
4376                 str = gettext("Allows accessing any groupquota@... property");
4377                 break;
4378         case ZFS_DELEG_NOTE_GROUPUSED:
4379                 str = gettext("Allows reading any groupused@... property");
4380                 break;
4381         case ZFS_DELEG_NOTE_USERPROP:
4382                 str = gettext("Allows changing any user property");
4383                 break;
4384         case ZFS_DELEG_NOTE_USERQUOTA:
4385                 str = gettext("Allows accessing any userquota@... property");
4386                 break;
4387         case ZFS_DELEG_NOTE_USERUSED:
4388                 str = gettext("Allows reading any userused@... property");
4389                 break;
4390                 /* other */
4391         default:
4392                 str = "";
4393         }
4394 
4395         return (str);
4396 }
4397 
4398 struct allow_opts {
4399         boolean_t local;
4400         boolean_t descend;
4401         boolean_t user;
4402         boolean_t group;
4403         boolean_t everyone;
4404         boolean_t create;
4405         boolean_t set;
4406         boolean_t recursive; /* unallow only */
4407         boolean_t prt_usage;
4408 
4409         boolean_t prt_perms;
4410         char *who;
4411         char *perms;
4412         const char *dataset;
4413 };
4414 
4415 static inline int
4416 prop_cmp(const void *a, const void *b)
4417 {
4418         const char *str1 = *(const char **)a;
4419         const char *str2 = *(const char **)b;
4420         return (strcmp(str1, str2));
4421 }
4422 
4423 static void
4424 allow_usage(boolean_t un, boolean_t requested, const char *msg)
4425 {
4426         const char *opt_desc[] = {
4427                 "-h", gettext("show this help message and exit"),
4428                 "-l", gettext("set permission locally"),
4429                 "-d", gettext("set permission for descents"),
4430                 "-u", gettext("set permission for user"),
4431                 "-g", gettext("set permission for group"),
4432                 "-e", gettext("set permission for everyone"),
4433                 "-c", gettext("set create time permission"),
4434                 "-s", gettext("define permission set"),
4435                 /* unallow only */
4436                 "-r", gettext("remove permissions recursively"),
4437         };
4438         size_t unallow_size = sizeof (opt_desc) / sizeof (char *);
4439         size_t allow_size = unallow_size - 2;
4440         const char *props[ZFS_NUM_PROPS];
4441         int i;
4442         size_t count = 0;
4443         FILE *fp = requested ? stdout : stderr;
4444         zprop_desc_t *pdtbl = zfs_prop_get_table();
4445         const char *fmt = gettext("%-16s %-14s\t%s\n");
4446 
4447         (void) fprintf(fp, gettext("Usage: %s\n"), get_usage(un ? HELP_UNALLOW :
4448             HELP_ALLOW));
4449         (void) fprintf(fp, gettext("Options:\n"));
4450         for (int i = 0; i < (un ? unallow_size : allow_size); i++) {
4451                 const char *opt = opt_desc[i++];
4452                 const char *optdsc = opt_desc[i];
4453                 (void) fprintf(fp, gettext("  %-10s  %s\n"), opt, optdsc);
4454         }
4455 
4456         (void) fprintf(fp, gettext("\nThe following permissions are "
4457             "supported:\n\n"));
4458         (void) fprintf(fp, fmt, gettext("NAME"), gettext("TYPE"),
4459             gettext("NOTES"));
4460         for (i = 0; i < ZFS_NUM_DELEG_NOTES; i++) {
4461                 const char *perm_name = zfs_deleg_perm_tbl[i].z_perm;
4462                 zfs_deleg_note_t perm_note = zfs_deleg_perm_tbl[i].z_note;
4463                 const char *perm_type = deleg_perm_type(perm_note);
4464                 const char *perm_comment = deleg_perm_comment(perm_note);
4465                 (void) fprintf(fp, fmt, perm_name, perm_type, perm_comment);
4466         }
4467 
4468         for (i = 0; i < ZFS_NUM_PROPS; i++) {
4469                 zprop_desc_t *pd = &pdtbl[i];
4470                 if (pd->pd_visible != B_TRUE)
4471                         continue;
4472 
4473                 if (pd->pd_attr == PROP_READONLY)
4474                         continue;
4475 
4476                 props[count++] = pd->pd_name;
4477         }
4478         props[count] = NULL;
4479 
4480         qsort(props, count, sizeof (char *), prop_cmp);
4481 
4482         for (i = 0; i < count; i++)
4483                 (void) fprintf(fp, fmt, props[i], gettext("property"), "");
4484 
4485         if (msg != NULL)
4486                 (void) fprintf(fp, gettext("\nzfs: error: %s"), msg);
4487 
4488         exit(requested ? 0 : 2);
4489 }
4490 
4491 static inline const char *
4492 munge_args(int argc, char **argv, boolean_t un, size_t expected_argc,
4493     char **permsp)
4494 {
4495         if (un && argc == expected_argc - 1)
4496                 *permsp = NULL;
4497         else if (argc == expected_argc)
4498                 *permsp = argv[argc - 2];
4499         else
4500                 allow_usage(un, B_FALSE,
4501                     gettext("wrong number of parameters\n"));
4502 
4503         return (argv[argc - 1]);
4504 }
4505 
4506 static void
4507 parse_allow_args(int argc, char **argv, boolean_t un, struct allow_opts *opts)
4508 {
4509         int uge_sum = opts->user + opts->group + opts->everyone;
4510         int csuge_sum = opts->create + opts->set + uge_sum;
4511         int ldcsuge_sum = csuge_sum + opts->local + opts->descend;
4512         int all_sum = un ? ldcsuge_sum + opts->recursive : ldcsuge_sum;
4513 
4514         if (uge_sum > 1)
4515                 allow_usage(un, B_FALSE,
4516                     gettext("-u, -g, and -e are mutually exclusive\n"));
4517 
4518         if (opts->prt_usage)
4519                 if (argc == 0 && all_sum == 0)
4520                         allow_usage(un, B_TRUE, NULL);
4521                 else
4522                         usage(B_FALSE);
4523 
4524         if (opts->set) {
4525                 if (csuge_sum > 1)
4526                         allow_usage(un, B_FALSE,
4527                             gettext("invalid options combined with -s\n"));
4528 
4529                 opts->dataset = munge_args(argc, argv, un, 3, &opts->perms);
4530                 if (argv[0][0] != '@')
4531                         allow_usage(un, B_FALSE,
4532                             gettext("invalid set name: missing '@' prefix\n"));
4533                 opts->who = argv[0];
4534         } else if (opts->create) {
4535                 if (ldcsuge_sum > 1)
4536                         allow_usage(un, B_FALSE,
4537                             gettext("invalid options combined with -c\n"));
4538                 opts->dataset = munge_args(argc, argv, un, 2, &opts->perms);
4539         } else if (opts->everyone) {
4540                 if (csuge_sum > 1)
4541                         allow_usage(un, B_FALSE,
4542                             gettext("invalid options combined with -e\n"));
4543                 opts->dataset = munge_args(argc, argv, un, 2, &opts->perms);
4544         } else if (uge_sum == 0 && argc > 0 && strcmp(argv[0], "everyone")
4545             == 0) {
4546                 opts->everyone = B_TRUE;
4547                 argc--;
4548                 argv++;
4549                 opts->dataset = munge_args(argc, argv, un, 2, &opts->perms);
4550         } else if (argc == 1 && !un) {
4551                 opts->prt_perms = B_TRUE;
4552                 opts->dataset = argv[argc-1];
4553         } else {
4554                 opts->dataset = munge_args(argc, argv, un, 3, &opts->perms);
4555                 opts->who = argv[0];
4556         }
4557 
4558         if (!opts->local && !opts->descend) {
4559                 opts->local = B_TRUE;
4560                 opts->descend = B_TRUE;
4561         }
4562 }
4563 
4564 static void
4565 store_allow_perm(zfs_deleg_who_type_t type, boolean_t local, boolean_t descend,
4566     const char *who, char *perms, nvlist_t *top_nvl)
4567 {
4568         int i;
4569         char ld[2] = { '\0', '\0' };
4570         char who_buf[ZFS_MAXNAMELEN+32];
4571         char base_type;
4572         char set_type;
4573         nvlist_t *base_nvl = NULL;
4574         nvlist_t *set_nvl = NULL;
4575         nvlist_t *nvl;
4576 
4577         if (nvlist_alloc(&base_nvl, NV_UNIQUE_NAME, 0) != 0)
4578                 nomem();
4579         if (nvlist_alloc(&set_nvl, NV_UNIQUE_NAME, 0) !=  0)
4580                 nomem();
4581 
4582         switch (type) {
4583         case ZFS_DELEG_NAMED_SET_SETS:
4584         case ZFS_DELEG_NAMED_SET:
4585                 set_type = ZFS_DELEG_NAMED_SET_SETS;
4586                 base_type = ZFS_DELEG_NAMED_SET;
4587                 ld[0] = ZFS_DELEG_NA;
4588                 break;
4589         case ZFS_DELEG_CREATE_SETS:
4590         case ZFS_DELEG_CREATE:
4591                 set_type = ZFS_DELEG_CREATE_SETS;
4592                 base_type = ZFS_DELEG_CREATE;
4593                 ld[0] = ZFS_DELEG_NA;
4594                 break;
4595         case ZFS_DELEG_USER_SETS:
4596         case ZFS_DELEG_USER:
4597                 set_type = ZFS_DELEG_USER_SETS;
4598                 base_type = ZFS_DELEG_USER;
4599                 if (local)
4600                         ld[0] = ZFS_DELEG_LOCAL;
4601                 if (descend)
4602                         ld[1] = ZFS_DELEG_DESCENDENT;
4603                 break;
4604         case ZFS_DELEG_GROUP_SETS:
4605         case ZFS_DELEG_GROUP:
4606                 set_type = ZFS_DELEG_GROUP_SETS;
4607                 base_type = ZFS_DELEG_GROUP;
4608                 if (local)
4609                         ld[0] = ZFS_DELEG_LOCAL;
4610                 if (descend)
4611                         ld[1] = ZFS_DELEG_DESCENDENT;
4612                 break;
4613         case ZFS_DELEG_EVERYONE_SETS:
4614         case ZFS_DELEG_EVERYONE:
4615                 set_type = ZFS_DELEG_EVERYONE_SETS;
4616                 base_type = ZFS_DELEG_EVERYONE;
4617                 if (local)
4618                         ld[0] = ZFS_DELEG_LOCAL;
4619                 if (descend)
4620                         ld[1] = ZFS_DELEG_DESCENDENT;
4621         }
4622 
4623         if (perms != NULL) {
4624                 char *curr = perms;
4625                 char *end = curr + strlen(perms);
4626 
4627                 while (curr < end) {
4628                         char *delim = strchr(curr, ',');
4629                         if (delim == NULL)
4630                                 delim = end;
4631                         else
4632                                 *delim = '\0';
4633 
4634                         if (curr[0] == '@')
4635                                 nvl = set_nvl;
4636                         else
4637                                 nvl = base_nvl;
4638 
4639                         (void) nvlist_add_boolean(nvl, curr);
4640                         if (delim != end)
4641                                 *delim = ',';
4642                         curr = delim + 1;
4643                 }
4644 
4645                 for (i = 0; i < 2; i++) {
4646                         char locality = ld[i];
4647                         if (locality == 0)
4648                                 continue;
4649 
4650                         if (!nvlist_empty(base_nvl)) {
4651                                 if (who != NULL)
4652                                         (void) snprintf(who_buf,
4653                                             sizeof (who_buf), "%c%c$%s",
4654                                             base_type, locality, who);
4655                                 else
4656                                         (void) snprintf(who_buf,
4657                                             sizeof (who_buf), "%c%c$",
4658                                             base_type, locality);
4659 
4660                                 (void) nvlist_add_nvlist(top_nvl, who_buf,
4661                                     base_nvl);
4662                         }
4663 
4664 
4665                         if (!nvlist_empty(set_nvl)) {
4666                                 if (who != NULL)
4667                                         (void) snprintf(who_buf,
4668                                             sizeof (who_buf), "%c%c$%s",
4669                                             set_type, locality, who);
4670                                 else
4671                                         (void) snprintf(who_buf,
4672                                             sizeof (who_buf), "%c%c$",
4673                                             set_type, locality);
4674 
4675                                 (void) nvlist_add_nvlist(top_nvl, who_buf,
4676                                     set_nvl);
4677                         }
4678                 }
4679         } else {
4680                 for (i = 0; i < 2; i++) {
4681                         char locality = ld[i];
4682                         if (locality == 0)
4683                                 continue;
4684 
4685                         if (who != NULL)
4686                                 (void) snprintf(who_buf, sizeof (who_buf),
4687                                     "%c%c$%s", base_type, locality, who);
4688                         else
4689                                 (void) snprintf(who_buf, sizeof (who_buf),
4690                                     "%c%c$", base_type, locality);
4691                         (void) nvlist_add_boolean(top_nvl, who_buf);
4692 
4693                         if (who != NULL)
4694                                 (void) snprintf(who_buf, sizeof (who_buf),
4695                                     "%c%c$%s", set_type, locality, who);
4696                         else
4697                                 (void) snprintf(who_buf, sizeof (who_buf),
4698                                     "%c%c$", set_type, locality);
4699                         (void) nvlist_add_boolean(top_nvl, who_buf);
4700                 }
4701         }
4702 }
4703 
4704 static int
4705 construct_fsacl_list(boolean_t un, struct allow_opts *opts, nvlist_t **nvlp)
4706 {
4707         if (nvlist_alloc(nvlp, NV_UNIQUE_NAME, 0) != 0)
4708                 nomem();
4709 
4710         if (opts->set) {
4711                 store_allow_perm(ZFS_DELEG_NAMED_SET, opts->local,
4712                     opts->descend, opts->who, opts->perms, *nvlp);
4713         } else if (opts->create) {
4714                 store_allow_perm(ZFS_DELEG_CREATE, opts->local,
4715                     opts->descend, NULL, opts->perms, *nvlp);
4716         } else if (opts->everyone) {
4717                 store_allow_perm(ZFS_DELEG_EVERYONE, opts->local,
4718                     opts->descend, NULL, opts->perms, *nvlp);
4719         } else {
4720                 char *curr = opts->who;
4721                 char *end = curr + strlen(curr);
4722 
4723                 while (curr < end) {
4724                         const char *who;
4725                         zfs_deleg_who_type_t who_type;
4726                         char *endch;
4727                         char *delim = strchr(curr, ',');
4728                         char errbuf[256];
4729                         char id[64];
4730                         struct passwd *p = NULL;
4731                         struct group *g = NULL;
4732 
4733                         uid_t rid;
4734                         if (delim == NULL)
4735                                 delim = end;
4736                         else
4737                                 *delim = '\0';
4738 
4739                         rid = (uid_t)strtol(curr, &endch, 0);
4740                         if (opts->user) {
4741                                 who_type = ZFS_DELEG_USER;
4742                                 if (*endch != '\0')
4743                                         p = getpwnam(curr);
4744                                 else
4745                                         p = getpwuid(rid);
4746 
4747                                 if (p != NULL)
4748                                         rid = p->pw_uid;
4749                                 else {
4750                                         (void) snprintf(errbuf, 256, gettext(
4751                                             "invalid user %s"), curr);
4752                                         allow_usage(un, B_TRUE, errbuf);
4753                                 }
4754                         } else if (opts->group) {
4755                                 who_type = ZFS_DELEG_GROUP;
4756                                 if (*endch != '\0')
4757                                         g = getgrnam(curr);
4758                                 else
4759                                         g = getgrgid(rid);
4760 
4761                                 if (g != NULL)
4762                                         rid = g->gr_gid;
4763                                 else {
4764                                         (void) snprintf(errbuf, 256, gettext(
4765                                             "invalid group %s"),  curr);
4766                                         allow_usage(un, B_TRUE, errbuf);
4767                                 }
4768                         } else {
4769                                 if (*endch != '\0') {
4770                                         p = getpwnam(curr);
4771                                 } else {
4772                                         p = getpwuid(rid);
4773                                 }
4774 
4775                                 if (p == NULL)
4776                                         if (*endch != '\0') {
4777                                                 g = getgrnam(curr);
4778                                         } else {
4779                                                 g = getgrgid(rid);
4780                                         }
4781 
4782                                 if (p != NULL) {
4783                                         who_type = ZFS_DELEG_USER;
4784                                         rid = p->pw_uid;
4785                                 } else if (g != NULL) {
4786                                         who_type = ZFS_DELEG_GROUP;
4787                                         rid = g->gr_gid;
4788                                 } else {
4789                                         (void) snprintf(errbuf, 256, gettext(
4790                                             "invalid user/group %s"), curr);
4791                                         allow_usage(un, B_TRUE, errbuf);
4792                                 }
4793                         }
4794 
4795                         (void) sprintf(id, "%u", rid);
4796                         who = id;
4797 
4798                         store_allow_perm(who_type, opts->local,
4799                             opts->descend, who, opts->perms, *nvlp);
4800                         curr = delim + 1;
4801                 }
4802         }
4803 
4804         return (0);
4805 }
4806 
4807 static void
4808 print_set_creat_perms(uu_avl_t *who_avl)
4809 {
4810         const char *sc_title[] = {
4811                 gettext("Permission sets:\n"),
4812                 gettext("Create time permissions:\n"),
4813                 NULL
4814         };
4815         const char **title_ptr = sc_title;
4816         who_perm_node_t *who_node = NULL;
4817         int prev_weight = -1;
4818 
4819         for (who_node = uu_avl_first(who_avl); who_node != NULL;
4820             who_node = uu_avl_next(who_avl, who_node)) {
4821                 uu_avl_t *avl = who_node->who_perm.who_deleg_perm_avl;
4822                 zfs_deleg_who_type_t who_type = who_node->who_perm.who_type;
4823                 const char *who_name = who_node->who_perm.who_name;
4824                 int weight = who_type2weight(who_type);
4825                 boolean_t first = B_TRUE;
4826                 deleg_perm_node_t *deleg_node;
4827 
4828                 if (prev_weight != weight) {
4829                         (void) printf(*title_ptr++);
4830                         prev_weight = weight;
4831                 }
4832 
4833                 if (who_name == NULL || strnlen(who_name, 1) == 0)
4834                         (void) printf("\t");
4835                 else
4836                         (void) printf("\t%s ", who_name);
4837 
4838                 for (deleg_node = uu_avl_first(avl); deleg_node != NULL;
4839                     deleg_node = uu_avl_next(avl, deleg_node)) {
4840                         if (first) {
4841                                 (void) printf("%s",
4842                                     deleg_node->dpn_perm.dp_name);
4843                                 first = B_FALSE;
4844                         } else
4845                                 (void) printf(",%s",
4846                                     deleg_node->dpn_perm.dp_name);
4847                 }
4848 
4849                 (void) printf("\n");
4850         }
4851 }
4852 
4853 static void inline
4854 print_uge_deleg_perms(uu_avl_t *who_avl, boolean_t local, boolean_t descend,
4855     const char *title)
4856 {
4857         who_perm_node_t *who_node = NULL;
4858         boolean_t prt_title = B_TRUE;
4859         uu_avl_walk_t *walk;
4860 
4861         if ((walk = uu_avl_walk_start(who_avl, UU_WALK_ROBUST)) == NULL)
4862                 nomem();
4863 
4864         while ((who_node = uu_avl_walk_next(walk)) != NULL) {
4865                 const char *who_name = who_node->who_perm.who_name;
4866                 const char *nice_who_name = who_node->who_perm.who_ug_name;
4867                 uu_avl_t *avl = who_node->who_perm.who_deleg_perm_avl;
4868                 zfs_deleg_who_type_t who_type = who_node->who_perm.who_type;
4869                 char delim = ' ';
4870                 deleg_perm_node_t *deleg_node;
4871                 boolean_t prt_who = B_TRUE;
4872 
4873                 for (deleg_node = uu_avl_first(avl);
4874                     deleg_node != NULL;
4875                     deleg_node = uu_avl_next(avl, deleg_node)) {
4876                         if (local != deleg_node->dpn_perm.dp_local ||
4877                             descend != deleg_node->dpn_perm.dp_descend)
4878                                 continue;
4879 
4880                         if (prt_who) {
4881                                 const char *who = NULL;
4882                                 if (prt_title) {
4883                                         prt_title = B_FALSE;
4884                                         (void) printf(title);
4885                                 }
4886 
4887                                 switch (who_type) {
4888                                 case ZFS_DELEG_USER_SETS:
4889                                 case ZFS_DELEG_USER:
4890                                         who = gettext("user");
4891                                         if (nice_who_name)
4892                                                 who_name  = nice_who_name;
4893                                         break;
4894                                 case ZFS_DELEG_GROUP_SETS:
4895                                 case ZFS_DELEG_GROUP:
4896                                         who = gettext("group");
4897                                         if (nice_who_name)
4898                                                 who_name  = nice_who_name;
4899                                         break;
4900                                 case ZFS_DELEG_EVERYONE_SETS:
4901                                 case ZFS_DELEG_EVERYONE:
4902                                         who = gettext("everyone");
4903                                         who_name = NULL;
4904                                 }
4905 
4906                                 prt_who = B_FALSE;
4907                                 if (who_name == NULL)
4908                                         (void) printf("\t%s", who);
4909                                 else
4910                                         (void) printf("\t%s %s", who, who_name);
4911                         }
4912 
4913                         (void) printf("%c%s", delim,
4914                             deleg_node->dpn_perm.dp_name);
4915                         delim = ',';
4916                 }
4917 
4918                 if (!prt_who)
4919                         (void) printf("\n");
4920         }
4921 
4922         uu_avl_walk_end(walk);
4923 }
4924 
4925 static void
4926 print_fs_perms(fs_perm_set_t *fspset)
4927 {
4928         fs_perm_node_t *node = NULL;
4929         char buf[ZFS_MAXNAMELEN+32];
4930         const char *dsname = buf;
4931 
4932         for (node = uu_list_first(fspset->fsps_list); node != NULL;
4933             node = uu_list_next(fspset->fsps_list, node)) {
4934                 uu_avl_t *sc_avl = node->fspn_fsperm.fsp_sc_avl;
4935                 uu_avl_t *uge_avl = node->fspn_fsperm.fsp_uge_avl;
4936                 int left = 0;
4937 
4938                 (void) snprintf(buf, ZFS_MAXNAMELEN+32,
4939                     gettext("---- Permissions on %s "),
4940                     node->fspn_fsperm.fsp_name);
4941                 (void) printf(dsname);
4942                 left = 70 - strlen(buf);
4943                 while (left-- > 0)
4944                         (void) printf("-");
4945                 (void) printf("\n");
4946 
4947                 print_set_creat_perms(sc_avl);
4948                 print_uge_deleg_perms(uge_avl, B_TRUE, B_FALSE,
4949                     gettext("Local permissions:\n"));
4950                 print_uge_deleg_perms(uge_avl, B_FALSE, B_TRUE,
4951                     gettext("Descendent permissions:\n"));
4952                 print_uge_deleg_perms(uge_avl, B_TRUE, B_TRUE,
4953                     gettext("Local+Descendent permissions:\n"));
4954         }
4955 }
4956 
4957 static fs_perm_set_t fs_perm_set = { NULL, NULL, NULL, NULL };
4958 
4959 struct deleg_perms {
4960         boolean_t un;
4961         nvlist_t *nvl;
4962 };
4963 
4964 static int
4965 set_deleg_perms(zfs_handle_t *zhp, void *data)
4966 {
4967         struct deleg_perms *perms = (struct deleg_perms *)data;
4968         zfs_type_t zfs_type = zfs_get_type(zhp);
4969 
4970         if (zfs_type != ZFS_TYPE_FILESYSTEM && zfs_type != ZFS_TYPE_VOLUME)
4971                 return (0);
4972 
4973         return (zfs_set_fsacl(zhp, perms->un, perms->nvl));
4974 }
4975 
4976 static int
4977 zfs_do_allow_unallow_impl(int argc, char **argv, boolean_t un)
4978 {
4979         zfs_handle_t *zhp;
4980         nvlist_t *perm_nvl = NULL;
4981         nvlist_t *update_perm_nvl = NULL;
4982         int error = 1;
4983         int c;
4984         struct allow_opts opts = { 0 };
4985 
4986         const char *optstr = un ? "ldugecsrh" : "ldugecsh";
4987 
4988         /* check opts */
4989         while ((c = getopt(argc, argv, optstr)) != -1) {
4990                 switch (c) {
4991                 case 'l':
4992                         opts.local = B_TRUE;
4993                         break;
4994                 case 'd':
4995                         opts.descend = B_TRUE;
4996                         break;
4997                 case 'u':
4998                         opts.user = B_TRUE;
4999                         break;
5000                 case 'g':
5001                         opts.group = B_TRUE;
5002                         break;
5003                 case 'e':
5004                         opts.everyone = B_TRUE;
5005                         break;
5006                 case 's':
5007                         opts.set = B_TRUE;
5008                         break;
5009                 case 'c':
5010                         opts.create = B_TRUE;
5011                         break;
5012                 case 'r':
5013                         opts.recursive = B_TRUE;
5014                         break;
5015                 case ':':
5016                         (void) fprintf(stderr, gettext("missing argument for "
5017                             "'%c' option\n"), optopt);
5018                         usage(B_FALSE);
5019                         break;
5020                 case 'h':
5021                         opts.prt_usage = B_TRUE;
5022                         break;
5023                 case '?':
5024                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
5025                             optopt);
5026                         usage(B_FALSE);
5027                 }
5028         }
5029 
5030         argc -= optind;
5031         argv += optind;
5032 
5033         /* check arguments */
5034         parse_allow_args(argc, argv, un, &opts);
5035 
5036         /* try to open the dataset */
5037         if ((zhp = zfs_open(g_zfs, opts.dataset, ZFS_TYPE_FILESYSTEM |
5038             ZFS_TYPE_VOLUME)) == NULL) {
5039                 (void) fprintf(stderr, "Failed to open dataset: %s\n",
5040                     opts.dataset);
5041                 return (-1);
5042         }
5043 
5044         if (zfs_get_fsacl(zhp, &perm_nvl) != 0)
5045                 goto cleanup2;
5046 
5047         fs_perm_set_init(&fs_perm_set);
5048         if (parse_fs_perm_set(&fs_perm_set, perm_nvl) != 0) {
5049                 (void) fprintf(stderr, "Failed to parse fsacl permissions\n");
5050                 goto cleanup1;
5051         }
5052 
5053         if (opts.prt_perms)
5054                 print_fs_perms(&fs_perm_set);
5055         else {
5056                 (void) construct_fsacl_list(un, &opts, &update_perm_nvl);
5057                 if (zfs_set_fsacl(zhp, un, update_perm_nvl) != 0)
5058                         goto cleanup0;
5059 
5060                 if (un && opts.recursive) {
5061                         struct deleg_perms data = { un, update_perm_nvl };
5062                         if (zfs_iter_filesystems(zhp, set_deleg_perms,
5063                             &data) != 0)
5064                                 goto cleanup0;
5065                 }
5066         }
5067 
5068         error = 0;
5069 
5070 cleanup0:
5071         nvlist_free(perm_nvl);
5072         if (update_perm_nvl != NULL)
5073                 nvlist_free(update_perm_nvl);
5074 cleanup1:
5075         fs_perm_set_fini(&fs_perm_set);
5076 cleanup2:
5077         zfs_close(zhp);
5078 
5079         return (error);
5080 }
5081 
5082 /*
5083  * zfs allow [-r] [-t] <tag> <snap> ...
5084  *
5085  *      -r      Recursively hold
5086  *      -t      Temporary hold (hidden option)
5087  *
5088  * Apply a user-hold with the given tag to the list of snapshots.
5089  */
5090 static int
5091 zfs_do_allow(int argc, char **argv)
5092 {
5093         return (zfs_do_allow_unallow_impl(argc, argv, B_FALSE));
5094 }
5095 
5096 /*
5097  * zfs unallow [-r] [-t] <tag> <snap> ...
5098  *
5099  *      -r      Recursively hold
5100  *      -t      Temporary hold (hidden option)
5101  *
5102  * Apply a user-hold with the given tag to the list of snapshots.
5103  */
5104 static int
5105 zfs_do_unallow(int argc, char **argv)
5106 {
5107         return (zfs_do_allow_unallow_impl(argc, argv, B_TRUE));
5108 }
5109 
5110 static int
5111 zfs_do_hold_rele_impl(int argc, char **argv, boolean_t holding)
5112 {
5113         int errors = 0;
5114         int i;
5115         const char *tag;
5116         boolean_t recursive = B_FALSE;
5117         boolean_t temphold = B_FALSE;
5118         const char *opts = holding ? "rt" : "r";
5119         int c;
5120 
5121         /* check options */
5122         while ((c = getopt(argc, argv, opts)) != -1) {
5123                 switch (c) {
5124                 case 'r':
5125                         recursive = B_TRUE;
5126                         break;
5127                 case 't':
5128                         temphold = B_TRUE;
5129                         break;
5130                 case '?':
5131                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
5132                             optopt);
5133                         usage(B_FALSE);
5134                 }
5135         }
5136 
5137         argc -= optind;
5138         argv += optind;
5139 
5140         /* check number of arguments */
5141         if (argc < 2)
5142                 usage(B_FALSE);
5143 
5144         tag = argv[0];
5145         --argc;
5146         ++argv;
5147 
5148         if (holding && tag[0] == '.') {
5149                 /* tags starting with '.' are reserved for libzfs */
5150                 (void) fprintf(stderr, gettext("tag may not start with '.'\n"));
5151                 usage(B_FALSE);
5152         }
5153 
5154         for (i = 0; i < argc; ++i) {
5155                 zfs_handle_t *zhp;
5156                 char parent[ZFS_MAXNAMELEN];
5157                 const char *delim;
5158                 char *path = argv[i];
5159 
5160                 delim = strchr(path, '@');
5161                 if (delim == NULL) {
5162                         (void) fprintf(stderr,
5163                             gettext("'%s' is not a snapshot\n"), path);
5164                         ++errors;
5165                         continue;
5166                 }
5167                 (void) strncpy(parent, path, delim - path);
5168                 parent[delim - path] = '\0';
5169 
5170                 zhp = zfs_open(g_zfs, parent,
5171                     ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
5172                 if (zhp == NULL) {
5173                         ++errors;
5174                         continue;
5175                 }
5176                 if (holding) {
5177                         if (zfs_hold(zhp, delim+1, tag, recursive,
5178                             temphold, B_FALSE, -1, 0, 0) != 0)
5179                                 ++errors;
5180                 } else {
5181                         if (zfs_release(zhp, delim+1, tag, recursive) != 0)
5182                                 ++errors;
5183                 }
5184                 zfs_close(zhp);
5185         }
5186 
5187         return (errors != 0);
5188 }
5189 
5190 /*
5191  * zfs hold [-r] [-t] <tag> <snap> ...
5192  *
5193  *      -r      Recursively hold
5194  *      -t      Temporary hold (hidden option)
5195  *
5196  * Apply a user-hold with the given tag to the list of snapshots.
5197  */
5198 static int
5199 zfs_do_hold(int argc, char **argv)
5200 {
5201         return (zfs_do_hold_rele_impl(argc, argv, B_TRUE));
5202 }
5203 
5204 /*
5205  * zfs release [-r] <tag> <snap> ...
5206  *
5207  *      -r      Recursively release
5208  *
5209  * Release a user-hold with the given tag from the list of snapshots.
5210  */
5211 static int
5212 zfs_do_release(int argc, char **argv)
5213 {
5214         return (zfs_do_hold_rele_impl(argc, argv, B_FALSE));
5215 }
5216 
5217 typedef struct holds_cbdata {
5218         boolean_t       cb_recursive;
5219         const char      *cb_snapname;
5220         nvlist_t        **cb_nvlp;
5221         size_t          cb_max_namelen;
5222         size_t          cb_max_taglen;
5223 } holds_cbdata_t;
5224 
5225 #define STRFTIME_FMT_STR "%a %b %e %k:%M %Y"
5226 #define DATETIME_BUF_LEN (32)
5227 /*
5228  *
5229  */
5230 static void
5231 print_holds(boolean_t scripted, size_t nwidth, size_t tagwidth, nvlist_t *nvl)
5232 {
5233         int i;
5234         nvpair_t *nvp = NULL;
5235         char *hdr_cols[] = { "NAME", "TAG", "TIMESTAMP" };
5236         const char *col;
5237 
5238         if (!scripted) {
5239                 for (i = 0; i < 3; i++) {
5240                         col = gettext(hdr_cols[i]);
5241                         if (i < 2)
5242                                 (void) printf("%-*s  ", i ? tagwidth : nwidth,
5243                                     col);
5244                         else
5245                                 (void) printf("%s\n", col);
5246                 }
5247         }
5248 
5249         while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
5250                 char *zname = nvpair_name(nvp);
5251                 nvlist_t *nvl2;
5252                 nvpair_t *nvp2 = NULL;
5253                 (void) nvpair_value_nvlist(nvp, &nvl2);
5254                 while ((nvp2 = nvlist_next_nvpair(nvl2, nvp2)) != NULL) {
5255                         char tsbuf[DATETIME_BUF_LEN];
5256                         char *tagname = nvpair_name(nvp2);
5257                         uint64_t val = 0;
5258                         time_t time;
5259                         struct tm t;
5260                         char sep = scripted ? '\t' : ' ';
5261                         size_t sepnum = scripted ? 1 : 2;
5262 
5263                         (void) nvpair_value_uint64(nvp2, &val);
5264                         time = (time_t)val;
5265                         (void) localtime_r(&time, &t);
5266                         (void) strftime(tsbuf, DATETIME_BUF_LEN,
5267                             gettext(STRFTIME_FMT_STR), &t);
5268 
5269                         (void) printf("%-*s%*c%-*s%*c%s\n", nwidth, zname,
5270                             sepnum, sep, tagwidth, tagname, sepnum, sep, tsbuf);
5271                 }
5272         }
5273 }
5274 
5275 /*
5276  * Generic callback function to list a dataset or snapshot.
5277  */
5278 static int
5279 holds_callback(zfs_handle_t *zhp, void *data)
5280 {
5281         holds_cbdata_t *cbp = data;
5282         nvlist_t *top_nvl = *cbp->cb_nvlp;
5283         nvlist_t *nvl = NULL;
5284         nvpair_t *nvp = NULL;
5285         const char *zname = zfs_get_name(zhp);
5286         size_t znamelen = strnlen(zname, ZFS_MAXNAMELEN);
5287 
5288         if (cbp->cb_recursive) {
5289                 const char *snapname;
5290                 char *delim  = strchr(zname, '@');
5291                 if (delim == NULL)
5292                         return (0);
5293 
5294                 snapname = delim + 1;
5295                 if (strcmp(cbp->cb_snapname, snapname))
5296                         return (0);
5297         }
5298 
5299         if (zfs_get_holds(zhp, &nvl) != 0)
5300                 return (-1);
5301 
5302         if (znamelen > cbp->cb_max_namelen)
5303                 cbp->cb_max_namelen  = znamelen;
5304 
5305         while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
5306                 const char *tag = nvpair_name(nvp);
5307                 size_t taglen = strnlen(tag, MAXNAMELEN);
5308                 if (taglen > cbp->cb_max_taglen)
5309                         cbp->cb_max_taglen  = taglen;
5310         }
5311 
5312         return (nvlist_add_nvlist(top_nvl, zname, nvl));
5313 }
5314 
5315 /*
5316  * zfs holds [-r] <snap> ...
5317  *
5318  *      -r      Recursively hold
5319  */
5320 static int
5321 zfs_do_holds(int argc, char **argv)
5322 {
5323         int errors = 0;
5324         int c;
5325         int i;
5326         boolean_t scripted = B_FALSE;
5327         boolean_t recursive = B_FALSE;
5328         const char *opts = "rH";
5329         nvlist_t *nvl;
5330 
5331         int types = ZFS_TYPE_SNAPSHOT;
5332         holds_cbdata_t cb = { 0 };
5333 
5334         int limit = 0;
5335         int ret = 0;
5336         int flags = 0;
5337 
5338         /* check options */
5339         while ((c = getopt(argc, argv, opts)) != -1) {
5340                 switch (c) {
5341                 case 'r':
5342                         recursive = B_TRUE;
5343                         break;
5344                 case 'H':
5345                         scripted = B_TRUE;
5346                         break;
5347                 case '?':
5348                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
5349                             optopt);
5350                         usage(B_FALSE);
5351                 }
5352         }
5353 
5354         if (recursive) {
5355                 types |= ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME;
5356                 flags |= ZFS_ITER_RECURSE;
5357         }
5358 
5359         argc -= optind;
5360         argv += optind;
5361 
5362         /* check number of arguments */
5363         if (argc < 1)
5364                 usage(B_FALSE);
5365 
5366         if (nvlist_alloc(&nvl, NV_UNIQUE_NAME, 0) != 0)
5367                 nomem();
5368 
5369         for (i = 0; i < argc; ++i) {
5370                 char *snapshot = argv[i];
5371                 const char *delim;
5372                 const char *snapname;
5373 
5374                 delim = strchr(snapshot, '@');
5375                 if (delim == NULL) {
5376                         (void) fprintf(stderr,
5377                             gettext("'%s' is not a snapshot\n"), snapshot);
5378                         ++errors;
5379                         continue;
5380                 }
5381                 snapname = delim + 1;
5382                 if (recursive)
5383                         snapshot[delim - snapshot] = '\0';
5384 
5385                 cb.cb_recursive = recursive;
5386                 cb.cb_snapname = snapname;
5387                 cb.cb_nvlp = &nvl;
5388 
5389                 /*
5390                  *  1. collect holds data, set format options
5391                  */
5392                 ret = zfs_for_each(argc, argv, flags, types, NULL, NULL, limit,
5393                     holds_callback, &cb);
5394                 if (ret != 0)
5395                         ++errors;
5396         }
5397 
5398         /*
5399          *  2. print holds data
5400          */
5401         print_holds(scripted, cb.cb_max_namelen, cb.cb_max_taglen, nvl);
5402 
5403         if (nvlist_empty(nvl))
5404                 (void) printf(gettext("no datasets available\n"));
5405 
5406         nvlist_free(nvl);
5407 
5408         return (0 != errors);
5409 }
5410 
5411 #define CHECK_SPINNER 30
5412 #define SPINNER_TIME 3          /* seconds */
5413 #define MOUNT_TIME 5            /* seconds */
5414 
5415 static int
5416 get_one_dataset(zfs_handle_t *zhp, void *data)
5417 {
5418         static char *spin[] = { "-", "\\", "|", "/" };
5419         static int spinval = 0;
5420         static int spincheck = 0;
5421         static time_t last_spin_time = (time_t)0;
5422         get_all_cb_t *cbp = data;
5423         zfs_type_t type = zfs_get_type(zhp);
5424 
5425         if (cbp->cb_verbose) {
5426                 if (--spincheck < 0) {
5427                         time_t now = time(NULL);
5428                         if (last_spin_time + SPINNER_TIME < now) {
5429                                 update_progress(spin[spinval++ % 4]);
5430                                 last_spin_time = now;
5431                         }
5432                         spincheck = CHECK_SPINNER;
5433                 }
5434         }
5435 
5436         /*
5437          * Interate over any nested datasets.
5438          */
5439         if (zfs_iter_filesystems(zhp, get_one_dataset, data) != 0) {
5440                 zfs_close(zhp);
5441                 return (1);
5442         }
5443 
5444         /*
5445          * Skip any datasets whose type does not match.
5446          */
5447         if ((type & ZFS_TYPE_FILESYSTEM) == 0) {
5448                 zfs_close(zhp);
5449                 return (0);
5450         }
5451         libzfs_add_handle(cbp, zhp);
5452         assert(cbp->cb_used <= cbp->cb_alloc);
5453 
5454         return (0);
5455 }
5456 
5457 static void
5458 get_all_datasets(zfs_handle_t ***dslist, size_t *count, boolean_t verbose)
5459 {
5460         get_all_cb_t cb = { 0 };
5461         cb.cb_verbose = verbose;
5462         cb.cb_getone = get_one_dataset;
5463 
5464         if (verbose)
5465                 set_progress_header(gettext("Reading ZFS config"));
5466         (void) zfs_iter_root(g_zfs, get_one_dataset, &cb);
5467 
5468         *dslist = cb.cb_handles;
5469         *count = cb.cb_used;
5470 
5471         if (verbose)
5472                 finish_progress(gettext("done."));
5473 }
5474 
5475 /*
5476  * Generic callback for sharing or mounting filesystems.  Because the code is so
5477  * similar, we have a common function with an extra parameter to determine which
5478  * mode we are using.
5479  */
5480 #define OP_SHARE        0x1
5481 #define OP_MOUNT        0x2
5482 
5483 /*
5484  * Share or mount a dataset.
5485  */
5486 static int
5487 share_mount_one(zfs_handle_t *zhp, int op, int flags, char *protocol,
5488     boolean_t explicit, const char *options)
5489 {
5490         char mountpoint[ZFS_MAXPROPLEN];
5491         char shareopts[ZFS_MAXPROPLEN];
5492         char smbshareopts[ZFS_MAXPROPLEN];
5493         const char *cmdname = op == OP_SHARE ? "share" : "mount";
5494         struct mnttab mnt;
5495         uint64_t zoned, canmount;
5496         boolean_t shared_nfs, shared_smb;
5497 
5498         assert(zfs_get_type(zhp) & ZFS_TYPE_FILESYSTEM);
5499 
5500         /*
5501          * Check to make sure we can mount/share this dataset.  If we
5502          * are in the global zone and the filesystem is exported to a
5503          * local zone, or if we are in a local zone and the
5504          * filesystem is not exported, then it is an error.
5505          */
5506         zoned = zfs_prop_get_int(zhp, ZFS_PROP_ZONED);
5507 
5508         if (zoned && getzoneid() == GLOBAL_ZONEID) {
5509                 if (!explicit)
5510                         return (0);
5511 
5512                 (void) fprintf(stderr, gettext("cannot %s '%s': "
5513                     "dataset is exported to a local zone\n"), cmdname,
5514                     zfs_get_name(zhp));
5515                 return (1);
5516 
5517         } else if (!zoned && getzoneid() != GLOBAL_ZONEID) {
5518                 if (!explicit)
5519                         return (0);
5520 
5521                 (void) fprintf(stderr, gettext("cannot %s '%s': "
5522                     "permission denied\n"), cmdname,
5523                     zfs_get_name(zhp));
5524                 return (1);
5525         }
5526 
5527         /*
5528          * Ignore any filesystems which don't apply to us. This
5529          * includes those with a legacy mountpoint, or those with
5530          * legacy share options.
5531          */
5532         verify(zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT, mountpoint,
5533             sizeof (mountpoint), NULL, NULL, 0, B_FALSE) == 0);
5534         verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS, shareopts,
5535             sizeof (shareopts), NULL, NULL, 0, B_FALSE) == 0);
5536         verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB, smbshareopts,
5537             sizeof (smbshareopts), NULL, NULL, 0, B_FALSE) == 0);
5538 
5539         if (op == OP_SHARE && strcmp(shareopts, "off") == 0 &&
5540             strcmp(smbshareopts, "off") == 0) {
5541                 if (!explicit)
5542                         return (0);
5543 
5544                 (void) fprintf(stderr, gettext("cannot share '%s': "
5545                     "legacy share\n"), zfs_get_name(zhp));
5546                 (void) fprintf(stderr, gettext("use share(1M) to "
5547                     "share this filesystem, or set "
5548                     "sharenfs property on\n"));
5549                 return (1);
5550         }
5551 
5552         /*
5553          * We cannot share or mount legacy filesystems. If the
5554          * shareopts is non-legacy but the mountpoint is legacy, we
5555          * treat it as a legacy share.
5556          */
5557         if (strcmp(mountpoint, "legacy") == 0) {
5558                 if (!explicit)
5559                         return (0);
5560 
5561                 (void) fprintf(stderr, gettext("cannot %s '%s': "
5562                     "legacy mountpoint\n"), cmdname, zfs_get_name(zhp));
5563                 (void) fprintf(stderr, gettext("use %s(1M) to "
5564                     "%s this filesystem\n"), cmdname, cmdname);
5565                 return (1);
5566         }
5567 
5568         if (strcmp(mountpoint, "none") == 0) {
5569                 if (!explicit)
5570                         return (0);
5571 
5572                 (void) fprintf(stderr, gettext("cannot %s '%s': no "
5573                     "mountpoint set\n"), cmdname, zfs_get_name(zhp));
5574                 return (1);
5575         }
5576 
5577         /*
5578          * canmount     explicit        outcome
5579          * on           no              pass through
5580          * on           yes             pass through
5581          * off          no              return 0
5582          * off          yes             display error, return 1
5583          * noauto       no              return 0
5584          * noauto       yes             pass through
5585          */
5586         canmount = zfs_prop_get_int(zhp, ZFS_PROP_CANMOUNT);
5587         if (canmount == ZFS_CANMOUNT_OFF) {
5588                 if (!explicit)
5589                         return (0);
5590 
5591                 (void) fprintf(stderr, gettext("cannot %s '%s': "
5592                     "'canmount' property is set to 'off'\n"), cmdname,
5593                     zfs_get_name(zhp));
5594                 return (1);
5595         } else if (canmount == ZFS_CANMOUNT_NOAUTO && !explicit) {
5596                 return (0);
5597         }
5598 
5599         /*
5600          * At this point, we have verified that the mountpoint and/or
5601          * shareopts are appropriate for auto management. If the
5602          * filesystem is already mounted or shared, return (failing
5603          * for explicit requests); otherwise mount or share the
5604          * filesystem.
5605          */
5606         switch (op) {
5607         case OP_SHARE:
5608 
5609                 shared_nfs = zfs_is_shared_nfs(zhp, NULL);
5610                 shared_smb = zfs_is_shared_smb(zhp, NULL);
5611 
5612                 if (shared_nfs && shared_smb ||
5613                     (shared_nfs && strcmp(shareopts, "on") == 0 &&
5614                     strcmp(smbshareopts, "off") == 0) ||
5615                     (shared_smb && strcmp(smbshareopts, "on") == 0 &&
5616                     strcmp(shareopts, "off") == 0)) {
5617                         if (!explicit)
5618                                 return (0);
5619 
5620                         (void) fprintf(stderr, gettext("cannot share "
5621                             "'%s': filesystem already shared\n"),
5622                             zfs_get_name(zhp));
5623                         return (1);
5624                 }
5625 
5626                 if (!zfs_is_mounted(zhp, NULL) &&
5627                     zfs_mount(zhp, NULL, 0) != 0)
5628                         return (1);
5629 
5630                 if (protocol == NULL) {
5631                         if (zfs_shareall(zhp) != 0)
5632                                 return (1);
5633                 } else if (strcmp(protocol, "nfs") == 0) {
5634                         if (zfs_share_nfs(zhp))
5635                                 return (1);
5636                 } else if (strcmp(protocol, "smb") == 0) {
5637                         if (zfs_share_smb(zhp))
5638                                 return (1);
5639                 } else {
5640                         (void) fprintf(stderr, gettext("cannot share "
5641                             "'%s': invalid share type '%s' "
5642                             "specified\n"),
5643                             zfs_get_name(zhp), protocol);
5644                         return (1);
5645                 }
5646 
5647                 break;
5648 
5649         case OP_MOUNT:
5650                 if (options == NULL)
5651                         mnt.mnt_mntopts = "";
5652                 else
5653                         mnt.mnt_mntopts = (char *)options;
5654 
5655                 if (!hasmntopt(&mnt, MNTOPT_REMOUNT) &&
5656                     zfs_is_mounted(zhp, NULL)) {
5657                         if (!explicit)
5658                                 return (0);
5659 
5660                         (void) fprintf(stderr, gettext("cannot mount "
5661                             "'%s': filesystem already mounted\n"),
5662                             zfs_get_name(zhp));
5663                         return (1);
5664                 }
5665 
5666                 if (zfs_mount(zhp, options, flags) != 0)
5667                         return (1);
5668                 break;
5669         }
5670 
5671         return (0);
5672 }
5673 
5674 /*
5675  * Reports progress in the form "(current/total)".  Not thread-safe.
5676  */
5677 static void
5678 report_mount_progress(int current, int total)
5679 {
5680         static time_t last_progress_time = 0;
5681         time_t now = time(NULL);
5682         char info[32];
5683 
5684         /* report 1..n instead of 0..n-1 */
5685         ++current;
5686 
5687         /* display header if we're here for the first time */
5688         if (current == 1) {
5689                 set_progress_header(gettext("Mounting ZFS filesystems"));
5690         } else if (current != total && last_progress_time + MOUNT_TIME >= now) {
5691                 /* too soon to report again */
5692                 return;
5693         }
5694 
5695         last_progress_time = now;
5696 
5697         (void) sprintf(info, "(%d/%d)", current, total);
5698 
5699         if (current == total)
5700                 finish_progress(info);
5701         else
5702                 update_progress(info);
5703 }
5704 
5705 static void
5706 append_options(char *mntopts, char *newopts)
5707 {
5708         int len = strlen(mntopts);
5709 
5710         /* original length plus new string to append plus 1 for the comma */
5711         if (len + 1 + strlen(newopts) >= MNT_LINE_MAX) {
5712                 (void) fprintf(stderr, gettext("the opts argument for "
5713                     "'%c' option is too long (more than %d chars)\n"),
5714                     "-o", MNT_LINE_MAX);
5715                 usage(B_FALSE);
5716         }
5717 
5718         if (*mntopts)
5719                 mntopts[len++] = ',';
5720 
5721         (void) strcpy(&mntopts[len], newopts);
5722 }
5723 
5724 static int
5725 share_mount(int op, int argc, char **argv)
5726 {
5727         int do_all = 0;
5728         boolean_t verbose = B_FALSE;
5729         int c, ret = 0;
5730         char *options = NULL;
5731         int flags = 0;
5732 
5733         /* check options */
5734         while ((c = getopt(argc, argv, op == OP_MOUNT ? ":avo:O" : "a"))
5735             != -1) {
5736                 switch (c) {
5737                 case 'a':
5738                         do_all = 1;
5739                         break;
5740                 case 'v':
5741                         verbose = B_TRUE;
5742                         break;
5743                 case 'o':
5744                         if (*optarg == '\0') {
5745                                 (void) fprintf(stderr, gettext("empty mount "
5746                                     "options (-o) specified\n"));
5747                                 usage(B_FALSE);
5748                         }
5749 
5750                         if (options == NULL)
5751                                 options = safe_malloc(MNT_LINE_MAX + 1);
5752 
5753                         /* option validation is done later */
5754                         append_options(options, optarg);
5755                         break;
5756 
5757                 case 'O':
5758                         flags |= MS_OVERLAY;
5759                         break;
5760                 case ':':
5761                         (void) fprintf(stderr, gettext("missing argument for "
5762                             "'%c' option\n"), optopt);
5763                         usage(B_FALSE);
5764                         break;
5765                 case '?':
5766                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
5767                             optopt);
5768                         usage(B_FALSE);
5769                 }
5770         }
5771 
5772         argc -= optind;
5773         argv += optind;
5774 
5775         /* check number of arguments */
5776         if (do_all) {
5777                 zfs_handle_t **dslist = NULL;
5778                 size_t i, count = 0;
5779                 char *protocol = NULL;
5780 
5781                 if (op == OP_SHARE && argc > 0) {
5782                         if (strcmp(argv[0], "nfs") != 0 &&
5783                             strcmp(argv[0], "smb") != 0) {
5784                                 (void) fprintf(stderr, gettext("share type "
5785                                     "must be 'nfs' or 'smb'\n"));
5786                                 usage(B_FALSE);
5787                         }
5788                         protocol = argv[0];
5789                         argc--;
5790                         argv++;
5791                 }
5792 
5793                 if (argc != 0) {
5794                         (void) fprintf(stderr, gettext("too many arguments\n"));
5795                         usage(B_FALSE);
5796                 }
5797 
5798                 start_progress_timer();
5799                 get_all_datasets(&dslist, &count, verbose);
5800 
5801                 if (count == 0)
5802                         return (0);
5803 
5804                 qsort(dslist, count, sizeof (void *), libzfs_dataset_cmp);
5805 
5806                 for (i = 0; i < count; i++) {
5807                         if (verbose)
5808                                 report_mount_progress(i, count);
5809 
5810                         if (share_mount_one(dslist[i], op, flags, protocol,
5811                             B_FALSE, options) != 0)
5812                                 ret = 1;
5813                         zfs_close(dslist[i]);
5814                 }
5815 
5816                 free(dslist);
5817         } else if (argc == 0) {
5818                 struct mnttab entry;
5819 
5820                 if ((op == OP_SHARE) || (options != NULL)) {
5821                         (void) fprintf(stderr, gettext("missing filesystem "
5822                             "argument (specify -a for all)\n"));
5823                         usage(B_FALSE);
5824                 }
5825 
5826                 /*
5827                  * When mount is given no arguments, go through /etc/mnttab and
5828                  * display any active ZFS mounts.  We hide any snapshots, since
5829                  * they are controlled automatically.
5830                  */
5831                 rewind(mnttab_file);
5832                 while (getmntent(mnttab_file, &entry) == 0) {
5833                         if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0 ||
5834                             strchr(entry.mnt_special, '@') != NULL)
5835                                 continue;
5836 
5837                         (void) printf("%-30s  %s\n", entry.mnt_special,
5838                             entry.mnt_mountp);
5839                 }
5840 
5841         } else {
5842                 zfs_handle_t *zhp;
5843 
5844                 if (argc > 1) {
5845                         (void) fprintf(stderr,
5846                             gettext("too many arguments\n"));
5847                         usage(B_FALSE);
5848                 }
5849 
5850                 if ((zhp = zfs_open(g_zfs, argv[0],
5851                     ZFS_TYPE_FILESYSTEM)) == NULL) {
5852                         ret = 1;
5853                 } else {
5854                         ret = share_mount_one(zhp, op, flags, NULL, B_TRUE,
5855                             options);
5856                         zfs_close(zhp);
5857                 }
5858         }
5859 
5860         return (ret);
5861 }
5862 
5863 /*
5864  * zfs mount -a [nfs]
5865  * zfs mount filesystem
5866  *
5867  * Mount all filesystems, or mount the given filesystem.
5868  */
5869 static int
5870 zfs_do_mount(int argc, char **argv)
5871 {
5872         return (share_mount(OP_MOUNT, argc, argv));
5873 }
5874 
5875 /*
5876  * zfs share -a [nfs | smb]
5877  * zfs share filesystem
5878  *
5879  * Share all filesystems, or share the given filesystem.
5880  */
5881 static int
5882 zfs_do_share(int argc, char **argv)
5883 {
5884         return (share_mount(OP_SHARE, argc, argv));
5885 }
5886 
5887 typedef struct unshare_unmount_node {
5888         zfs_handle_t    *un_zhp;
5889         char            *un_mountp;
5890         uu_avl_node_t   un_avlnode;
5891 } unshare_unmount_node_t;
5892 
5893 /* ARGSUSED */
5894 static int
5895 unshare_unmount_compare(const void *larg, const void *rarg, void *unused)
5896 {
5897         const unshare_unmount_node_t *l = larg;
5898         const unshare_unmount_node_t *r = rarg;
5899 
5900         return (strcmp(l->un_mountp, r->un_mountp));
5901 }
5902 
5903 /*
5904  * Convenience routine used by zfs_do_umount() and manual_unmount().  Given an
5905  * absolute path, find the entry /etc/mnttab, verify that its a ZFS filesystem,
5906  * and unmount it appropriately.
5907  */
5908 static int
5909 unshare_unmount_path(int op, char *path, int flags, boolean_t is_manual)
5910 {
5911         zfs_handle_t *zhp;
5912         int ret = 0;
5913         struct stat64 statbuf;
5914         struct extmnttab entry;
5915         const char *cmdname = (op == OP_SHARE) ? "unshare" : "unmount";
5916         ino_t path_inode;
5917 
5918         /*
5919          * Search for the path in /etc/mnttab.  Rather than looking for the
5920          * specific path, which can be fooled by non-standard paths (i.e. ".."
5921          * or "//"), we stat() the path and search for the corresponding
5922          * (major,minor) device pair.
5923          */
5924         if (stat64(path, &statbuf) != 0) {
5925                 (void) fprintf(stderr, gettext("cannot %s '%s': %s\n"),
5926                     cmdname, path, strerror(errno));
5927                 return (1);
5928         }
5929         path_inode = statbuf.st_ino;
5930 
5931         /*
5932          * Search for the given (major,minor) pair in the mount table.
5933          */
5934         rewind(mnttab_file);
5935         while ((ret = getextmntent(mnttab_file, &entry, 0)) == 0) {
5936                 if (entry.mnt_major == major(statbuf.st_dev) &&
5937                     entry.mnt_minor == minor(statbuf.st_dev))
5938                         break;
5939         }
5940         if (ret != 0) {
5941                 if (op == OP_SHARE) {
5942                         (void) fprintf(stderr, gettext("cannot %s '%s': not "
5943                             "currently mounted\n"), cmdname, path);
5944                         return (1);
5945                 }
5946                 (void) fprintf(stderr, gettext("warning: %s not in mnttab\n"),
5947                     path);
5948                 if ((ret = umount2(path, flags)) != 0)
5949                         (void) fprintf(stderr, gettext("%s: %s\n"), path,
5950                             strerror(errno));
5951                 return (ret != 0);
5952         }
5953 
5954         if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0) {
5955                 (void) fprintf(stderr, gettext("cannot %s '%s': not a ZFS "
5956                     "filesystem\n"), cmdname, path);
5957                 return (1);
5958         }
5959 
5960         if ((zhp = zfs_open(g_zfs, entry.mnt_special,
5961             ZFS_TYPE_FILESYSTEM)) == NULL)
5962                 return (1);
5963 
5964         ret = 1;
5965         if (stat64(entry.mnt_mountp, &statbuf) != 0) {
5966                 (void) fprintf(stderr, gettext("cannot %s '%s': %s\n"),
5967                     cmdname, path, strerror(errno));
5968                 goto out;
5969         } else if (statbuf.st_ino != path_inode) {
5970                 (void) fprintf(stderr, gettext("cannot "
5971                     "%s '%s': not a mountpoint\n"), cmdname, path);
5972                 goto out;
5973         }
5974 
5975         if (op == OP_SHARE) {
5976                 char nfs_mnt_prop[ZFS_MAXPROPLEN];
5977                 char smbshare_prop[ZFS_MAXPROPLEN];
5978 
5979                 verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS, nfs_mnt_prop,
5980                     sizeof (nfs_mnt_prop), NULL, NULL, 0, B_FALSE) == 0);
5981                 verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB, smbshare_prop,
5982                     sizeof (smbshare_prop), NULL, NULL, 0, B_FALSE) == 0);
5983 
5984                 if (strcmp(nfs_mnt_prop, "off") == 0 &&
5985                     strcmp(smbshare_prop, "off") == 0) {
5986                         (void) fprintf(stderr, gettext("cannot unshare "
5987                             "'%s': legacy share\n"), path);
5988                         (void) fprintf(stderr, gettext("use "
5989                             "unshare(1M) to unshare this filesystem\n"));
5990                 } else if (!zfs_is_shared(zhp)) {
5991                         (void) fprintf(stderr, gettext("cannot unshare '%s': "
5992                             "not currently shared\n"), path);
5993                 } else {
5994                         ret = zfs_unshareall_bypath(zhp, path);
5995                 }
5996         } else {
5997                 char mtpt_prop[ZFS_MAXPROPLEN];
5998 
5999                 verify(zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT, mtpt_prop,
6000                     sizeof (mtpt_prop), NULL, NULL, 0, B_FALSE) == 0);
6001 
6002                 if (is_manual) {
6003                         ret = zfs_unmount(zhp, NULL, flags);
6004                 } else if (strcmp(mtpt_prop, "legacy") == 0) {
6005                         (void) fprintf(stderr, gettext("cannot unmount "
6006                             "'%s': legacy mountpoint\n"),
6007                             zfs_get_name(zhp));
6008                         (void) fprintf(stderr, gettext("use umount(1M) "
6009                             "to unmount this filesystem\n"));
6010                 } else {
6011                         ret = zfs_unmountall(zhp, flags);
6012                 }
6013         }
6014 
6015 out:
6016         zfs_close(zhp);
6017 
6018         return (ret != 0);
6019 }
6020 
6021 /*
6022  * Generic callback for unsharing or unmounting a filesystem.
6023  */
6024 static int
6025 unshare_unmount(int op, int argc, char **argv)
6026 {
6027         int do_all = 0;
6028         int flags = 0;
6029         int ret = 0;
6030         int c;
6031         zfs_handle_t *zhp;
6032         char nfs_mnt_prop[ZFS_MAXPROPLEN];
6033         char sharesmb[ZFS_MAXPROPLEN];
6034 
6035         /* check options */
6036         while ((c = getopt(argc, argv, op == OP_SHARE ? "a" : "af")) != -1) {
6037                 switch (c) {
6038                 case 'a':
6039                         do_all = 1;
6040                         break;
6041                 case 'f':
6042                         flags = MS_FORCE;
6043                         break;
6044                 case '?':
6045                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
6046                             optopt);
6047                         usage(B_FALSE);
6048                 }
6049         }
6050 
6051         argc -= optind;
6052         argv += optind;
6053 
6054         if (do_all) {
6055                 /*
6056                  * We could make use of zfs_for_each() to walk all datasets in
6057                  * the system, but this would be very inefficient, especially
6058                  * since we would have to linearly search /etc/mnttab for each
6059                  * one.  Instead, do one pass through /etc/mnttab looking for
6060                  * zfs entries and call zfs_unmount() for each one.
6061                  *
6062                  * Things get a little tricky if the administrator has created
6063                  * mountpoints beneath other ZFS filesystems.  In this case, we
6064                  * have to unmount the deepest filesystems first.  To accomplish
6065                  * this, we place all the mountpoints in an AVL tree sorted by
6066                  * the special type (dataset name), and walk the result in
6067                  * reverse to make sure to get any snapshots first.
6068                  */
6069                 struct mnttab entry;
6070                 uu_avl_pool_t *pool;
6071                 uu_avl_t *tree;
6072                 unshare_unmount_node_t *node;
6073                 uu_avl_index_t idx;
6074                 uu_avl_walk_t *walk;
6075 
6076                 if (argc != 0) {
6077                         (void) fprintf(stderr, gettext("too many arguments\n"));
6078                         usage(B_FALSE);
6079                 }
6080 
6081                 if (((pool = uu_avl_pool_create("unmount_pool",
6082                     sizeof (unshare_unmount_node_t),
6083                     offsetof(unshare_unmount_node_t, un_avlnode),
6084                     unshare_unmount_compare, UU_DEFAULT)) == NULL) ||
6085                     ((tree = uu_avl_create(pool, NULL, UU_DEFAULT)) == NULL))
6086                         nomem();
6087 
6088                 rewind(mnttab_file);
6089                 while (getmntent(mnttab_file, &entry) == 0) {
6090 
6091                         /* ignore non-ZFS entries */
6092                         if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0)
6093                                 continue;
6094 
6095                         /* ignore snapshots */
6096                         if (strchr(entry.mnt_special, '@') != NULL)
6097                                 continue;
6098 
6099                         if ((zhp = zfs_open(g_zfs, entry.mnt_special,
6100                             ZFS_TYPE_FILESYSTEM)) == NULL) {
6101                                 ret = 1;
6102                                 continue;
6103                         }
6104 
6105                         switch (op) {
6106                         case OP_SHARE:
6107                                 verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS,
6108                                     nfs_mnt_prop,
6109                                     sizeof (nfs_mnt_prop),
6110                                     NULL, NULL, 0, B_FALSE) == 0);
6111                                 if (strcmp(nfs_mnt_prop, "off") != 0)
6112                                         break;
6113                                 verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB,
6114                                     nfs_mnt_prop,
6115                                     sizeof (nfs_mnt_prop),
6116                                     NULL, NULL, 0, B_FALSE) == 0);
6117                                 if (strcmp(nfs_mnt_prop, "off") == 0)
6118                                         continue;
6119                                 break;
6120                         case OP_MOUNT:
6121                                 /* Ignore legacy mounts */
6122                                 verify(zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT,
6123                                     nfs_mnt_prop,
6124                                     sizeof (nfs_mnt_prop),
6125                                     NULL, NULL, 0, B_FALSE) == 0);
6126                                 if (strcmp(nfs_mnt_prop, "legacy") == 0)
6127                                         continue;
6128                                 /* Ignore canmount=noauto mounts */
6129                                 if (zfs_prop_get_int(zhp, ZFS_PROP_CANMOUNT) ==
6130                                     ZFS_CANMOUNT_NOAUTO)
6131                                         continue;
6132                         default:
6133                                 break;
6134                         }
6135 
6136                         node = safe_malloc(sizeof (unshare_unmount_node_t));
6137                         node->un_zhp = zhp;
6138                         node->un_mountp = safe_strdup(entry.mnt_mountp);
6139 
6140                         uu_avl_node_init(node, &node->un_avlnode, pool);
6141 
6142                         if (uu_avl_find(tree, node, NULL, &idx) == NULL) {
6143                                 uu_avl_insert(tree, node, idx);
6144                         } else {
6145                                 zfs_close(node->un_zhp);
6146                                 free(node->un_mountp);
6147                                 free(node);
6148                         }
6149                 }
6150 
6151                 /*
6152                  * Walk the AVL tree in reverse, unmounting each filesystem and
6153                  * removing it from the AVL tree in the process.
6154                  */
6155                 if ((walk = uu_avl_walk_start(tree,
6156                     UU_WALK_REVERSE | UU_WALK_ROBUST)) == NULL)
6157                         nomem();
6158 
6159                 while ((node = uu_avl_walk_next(walk)) != NULL) {
6160                         uu_avl_remove(tree, node);
6161 
6162                         switch (op) {
6163                         case OP_SHARE:
6164                                 if (zfs_unshareall_bypath(node->un_zhp,
6165                                     node->un_mountp) != 0)
6166                                         ret = 1;
6167                                 break;
6168 
6169                         case OP_MOUNT:
6170                                 if (zfs_unmount(node->un_zhp,
6171                                     node->un_mountp, flags) != 0)
6172                                         ret = 1;
6173                                 break;
6174                         }
6175 
6176                         zfs_close(node->un_zhp);
6177                         free(node->un_mountp);
6178                         free(node);
6179                 }
6180 
6181                 uu_avl_walk_end(walk);
6182                 uu_avl_destroy(tree);
6183                 uu_avl_pool_destroy(pool);
6184 
6185         } else {
6186                 if (argc != 1) {
6187                         if (argc == 0)
6188                                 (void) fprintf(stderr,
6189                                     gettext("missing filesystem argument\n"));
6190                         else
6191                                 (void) fprintf(stderr,
6192                                     gettext("too many arguments\n"));
6193                         usage(B_FALSE);
6194                 }
6195 
6196                 /*
6197                  * We have an argument, but it may be a full path or a ZFS
6198                  * filesystem.  Pass full paths off to unmount_path() (shared by
6199                  * manual_unmount), otherwise open the filesystem and pass to
6200                  * zfs_unmount().
6201                  */
6202                 if (argv[0][0] == '/')
6203                         return (unshare_unmount_path(op, argv[0],
6204                             flags, B_FALSE));
6205 
6206                 if ((zhp = zfs_open(g_zfs, argv[0],
6207                     ZFS_TYPE_FILESYSTEM)) == NULL)
6208                         return (1);
6209 
6210                 verify(zfs_prop_get(zhp, op == OP_SHARE ?
6211                     ZFS_PROP_SHARENFS : ZFS_PROP_MOUNTPOINT,
6212                     nfs_mnt_prop, sizeof (nfs_mnt_prop), NULL,
6213                     NULL, 0, B_FALSE) == 0);
6214 
6215                 switch (op) {
6216                 case OP_SHARE:
6217                         verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS,
6218                             nfs_mnt_prop,
6219                             sizeof (nfs_mnt_prop),
6220                             NULL, NULL, 0, B_FALSE) == 0);
6221                         verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB,
6222                             sharesmb, sizeof (sharesmb), NULL, NULL,
6223                             0, B_FALSE) == 0);
6224 
6225                         if (strcmp(nfs_mnt_prop, "off") == 0 &&
6226                             strcmp(sharesmb, "off") == 0) {
6227                                 (void) fprintf(stderr, gettext("cannot "
6228                                     "unshare '%s': legacy share\n"),
6229                                     zfs_get_name(zhp));
6230                                 (void) fprintf(stderr, gettext("use "
6231                                     "unshare(1M) to unshare this "
6232                                     "filesystem\n"));
6233                                 ret = 1;
6234                         } else if (!zfs_is_shared(zhp)) {
6235                                 (void) fprintf(stderr, gettext("cannot "
6236                                     "unshare '%s': not currently "
6237                                     "shared\n"), zfs_get_name(zhp));
6238                                 ret = 1;
6239                         } else if (zfs_unshareall(zhp) != 0) {
6240                                 ret = 1;
6241                         }
6242                         break;
6243 
6244                 case OP_MOUNT:
6245                         if (strcmp(nfs_mnt_prop, "legacy") == 0) {
6246                                 (void) fprintf(stderr, gettext("cannot "
6247                                     "unmount '%s': legacy "
6248                                     "mountpoint\n"), zfs_get_name(zhp));
6249                                 (void) fprintf(stderr, gettext("use "
6250                                     "umount(1M) to unmount this "
6251                                     "filesystem\n"));
6252                                 ret = 1;
6253                         } else if (!zfs_is_mounted(zhp, NULL)) {
6254                                 (void) fprintf(stderr, gettext("cannot "
6255                                     "unmount '%s': not currently "
6256                                     "mounted\n"),
6257                                     zfs_get_name(zhp));
6258                                 ret = 1;
6259                         } else if (zfs_unmountall(zhp, flags) != 0) {
6260                                 ret = 1;
6261                         }
6262                         break;
6263                 }
6264 
6265                 zfs_close(zhp);
6266         }
6267 
6268         return (ret);
6269 }
6270 
6271 /*
6272  * zfs unmount -a
6273  * zfs unmount filesystem
6274  *
6275  * Unmount all filesystems, or a specific ZFS filesystem.
6276  */
6277 static int
6278 zfs_do_unmount(int argc, char **argv)
6279 {
6280         return (unshare_unmount(OP_MOUNT, argc, argv));
6281 }
6282 
6283 /*
6284  * zfs unshare -a
6285  * zfs unshare filesystem
6286  *
6287  * Unshare all filesystems, or a specific ZFS filesystem.
6288  */
6289 static int
6290 zfs_do_unshare(int argc, char **argv)
6291 {
6292         return (unshare_unmount(OP_SHARE, argc, argv));
6293 }
6294 
6295 /*
6296  * Called when invoked as /etc/fs/zfs/mount.  Do the mount if the mountpoint is
6297  * 'legacy'.  Otherwise, complain that use should be using 'zfs mount'.
6298  */
6299 static int
6300 manual_mount(int argc, char **argv)
6301 {
6302         zfs_handle_t *zhp;
6303         char mountpoint[ZFS_MAXPROPLEN];
6304         char mntopts[MNT_LINE_MAX] = { '\0' };
6305         int ret = 0;
6306         int c;
6307         int flags = 0;
6308         char *dataset, *path;
6309 
6310         /* check options */
6311         while ((c = getopt(argc, argv, ":mo:O")) != -1) {
6312                 switch (c) {
6313                 case 'o':
6314                         (void) strlcpy(mntopts, optarg, sizeof (mntopts));
6315                         break;
6316                 case 'O':
6317                         flags |= MS_OVERLAY;
6318                         break;
6319                 case 'm':
6320                         flags |= MS_NOMNTTAB;
6321                         break;
6322                 case ':':
6323                         (void) fprintf(stderr, gettext("missing argument for "
6324                             "'%c' option\n"), optopt);
6325                         usage(B_FALSE);
6326                         break;
6327                 case '?':
6328                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
6329                             optopt);
6330                         (void) fprintf(stderr, gettext("usage: mount [-o opts] "
6331                             "<path>\n"));
6332                         return (2);
6333                 }
6334         }
6335 
6336         argc -= optind;
6337         argv += optind;
6338 
6339         /* check that we only have two arguments */
6340         if (argc != 2) {
6341                 if (argc == 0)
6342                         (void) fprintf(stderr, gettext("missing dataset "
6343                             "argument\n"));
6344                 else if (argc == 1)
6345                         (void) fprintf(stderr,
6346                             gettext("missing mountpoint argument\n"));
6347                 else
6348                         (void) fprintf(stderr, gettext("too many arguments\n"));
6349                 (void) fprintf(stderr, "usage: mount <dataset> <mountpoint>\n");
6350                 return (2);
6351         }
6352 
6353         dataset = argv[0];
6354         path = argv[1];
6355 
6356         /* try to open the dataset */
6357         if ((zhp = zfs_open(g_zfs, dataset, ZFS_TYPE_FILESYSTEM)) == NULL)
6358                 return (1);
6359 
6360         (void) zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT, mountpoint,
6361             sizeof (mountpoint), NULL, NULL, 0, B_FALSE);
6362 
6363         /* check for legacy mountpoint and complain appropriately */
6364         ret = 0;
6365         if (strcmp(mountpoint, ZFS_MOUNTPOINT_LEGACY) == 0) {
6366                 if (mount(dataset, path, MS_OPTIONSTR | flags, MNTTYPE_ZFS,
6367                     NULL, 0, mntopts, sizeof (mntopts)) != 0) {
6368                         (void) fprintf(stderr, gettext("mount failed: %s\n"),
6369                             strerror(errno));
6370                         ret = 1;
6371                 }
6372         } else {
6373                 (void) fprintf(stderr, gettext("filesystem '%s' cannot be "
6374                     "mounted using 'mount -F zfs'\n"), dataset);
6375                 (void) fprintf(stderr, gettext("Use 'zfs set mountpoint=%s' "
6376                     "instead.\n"), path);
6377                 (void) fprintf(stderr, gettext("If you must use 'mount -F zfs' "
6378                     "or /etc/vfstab, use 'zfs set mountpoint=legacy'.\n"));
6379                 (void) fprintf(stderr, gettext("See zfs(1M) for more "
6380                     "information.\n"));
6381                 ret = 1;
6382         }
6383 
6384         return (ret);
6385 }
6386 
6387 /*
6388  * Called when invoked as /etc/fs/zfs/umount.  Unlike a manual mount, we allow
6389  * unmounts of non-legacy filesystems, as this is the dominant administrative
6390  * interface.
6391  */
6392 static int
6393 manual_unmount(int argc, char **argv)
6394 {
6395         int flags = 0;
6396         int c;
6397 
6398         /* check options */
6399         while ((c = getopt(argc, argv, "f")) != -1) {
6400                 switch (c) {
6401                 case 'f':
6402                         flags = MS_FORCE;
6403                         break;
6404                 case '?':
6405                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
6406                             optopt);
6407                         (void) fprintf(stderr, gettext("usage: unmount [-f] "
6408                             "<path>\n"));
6409                         return (2);
6410                 }
6411         }
6412 
6413         argc -= optind;
6414         argv += optind;
6415 
6416         /* check arguments */
6417         if (argc != 1) {
6418                 if (argc == 0)
6419                         (void) fprintf(stderr, gettext("missing path "
6420                             "argument\n"));
6421                 else
6422                         (void) fprintf(stderr, gettext("too many arguments\n"));
6423                 (void) fprintf(stderr, gettext("usage: unmount [-f] <path>\n"));
6424                 return (2);
6425         }
6426 
6427         return (unshare_unmount_path(OP_MOUNT, argv[0], flags, B_TRUE));
6428 }
6429 
6430 static int
6431 find_command_idx(char *command, int *idx)
6432 {
6433         int i;
6434 
6435         for (i = 0; i < NCOMMAND; i++) {
6436                 if (command_table[i].name == NULL)
6437                         continue;
6438 
6439                 if (strcmp(command, command_table[i].name) == 0) {
6440                         *idx = i;
6441                         return (0);
6442                 }
6443         }
6444         return (1);
6445 }
6446 
6447 static int
6448 zfs_do_diff(int argc, char **argv)
6449 {
6450         zfs_handle_t *zhp;
6451         int flags = 0;
6452         char *tosnap = NULL;
6453         char *fromsnap = NULL;
6454         char *atp, *copy;
6455         int err = 0;
6456         int c;
6457 
6458         while ((c = getopt(argc, argv, "FHt")) != -1) {
6459                 switch (c) {
6460                 case 'F':
6461                         flags |= ZFS_DIFF_CLASSIFY;
6462                         break;
6463                 case 'H':
6464                         flags |= ZFS_DIFF_PARSEABLE;
6465                         break;
6466                 case 't':
6467                         flags |= ZFS_DIFF_TIMESTAMP;
6468                         break;
6469                 default:
6470                         (void) fprintf(stderr,
6471                             gettext("invalid option '%c'\n"), optopt);
6472                         usage(B_FALSE);
6473                 }
6474         }
6475 
6476         argc -= optind;
6477         argv += optind;
6478 
6479         if (argc < 1) {
6480                 (void) fprintf(stderr,
6481                 gettext("must provide at least one snapshot name\n"));
6482                 usage(B_FALSE);
6483         }
6484 
6485         if (argc > 2) {
6486                 (void) fprintf(stderr, gettext("too many arguments\n"));
6487                 usage(B_FALSE);
6488         }
6489 
6490         fromsnap = argv[0];
6491         tosnap = (argc == 2) ? argv[1] : NULL;
6492 
6493         copy = NULL;
6494         if (*fromsnap != '@')
6495                 copy = strdup(fromsnap);
6496         else if (tosnap)
6497                 copy = strdup(tosnap);
6498         if (copy == NULL)
6499                 usage(B_FALSE);
6500 
6501         if (atp = strchr(copy, '@'))
6502                 *atp = '\0';
6503 
6504         if ((zhp = zfs_open(g_zfs, copy, ZFS_TYPE_FILESYSTEM)) == NULL)
6505                 return (1);
6506 
6507         free(copy);
6508 
6509         /*
6510          * Ignore SIGPIPE so that the library can give us
6511          * information on any failure
6512          */
6513         (void) sigignore(SIGPIPE);
6514 
6515         err = zfs_show_diffs(zhp, STDOUT_FILENO, fromsnap, tosnap, flags);
6516 
6517         zfs_close(zhp);
6518 
6519         return (err != 0);
6520 }
6521 
6522 int
6523 main(int argc, char **argv)
6524 {
6525         int ret = 0;
6526         int i;
6527         char *progname;
6528         char *cmdname;
6529 
6530         (void) setlocale(LC_ALL, "");
6531         (void) textdomain(TEXT_DOMAIN);
6532 
6533         opterr = 0;
6534 
6535         if ((g_zfs = libzfs_init()) == NULL) {
6536                 (void) fprintf(stderr, gettext("internal error: failed to "
6537                     "initialize ZFS library\n"));
6538                 return (1);
6539         }
6540 
6541         zfs_save_arguments(argc, argv, history_str, sizeof (history_str));
6542 
6543         libzfs_print_on_error(g_zfs, B_TRUE);
6544 
6545         if ((mnttab_file = fopen(MNTTAB, "r")) == NULL) {
6546                 (void) fprintf(stderr, gettext("internal error: unable to "
6547                     "open %s\n"), MNTTAB);
6548                 return (1);
6549         }
6550 
6551         /*
6552          * This command also doubles as the /etc/fs mount and unmount program.
6553          * Determine if we should take this behavior based on argv[0].
6554          */
6555         progname = basename(argv[0]);
6556         if (strcmp(progname, "mount") == 0) {
6557                 ret = manual_mount(argc, argv);
6558         } else if (strcmp(progname, "umount") == 0) {
6559                 ret = manual_unmount(argc, argv);
6560         } else {
6561                 /*
6562                  * Make sure the user has specified some command.
6563                  */
6564                 if (argc < 2) {
6565                         (void) fprintf(stderr, gettext("missing command\n"));
6566                         usage(B_FALSE);
6567                 }
6568 
6569                 cmdname = argv[1];
6570 
6571                 /*
6572                  * The 'umount' command is an alias for 'unmount'
6573                  */
6574                 if (strcmp(cmdname, "umount") == 0)
6575                         cmdname = "unmount";
6576 
6577                 /*
6578                  * The 'recv' command is an alias for 'receive'
6579                  */
6580                 if (strcmp(cmdname, "recv") == 0)
6581                         cmdname = "receive";
6582 
6583                 /*
6584                  * Special case '-?'
6585                  */
6586                 if (strcmp(cmdname, "-?") == 0)
6587                         usage(B_TRUE);
6588 
6589                 /*
6590                  * Run the appropriate command.
6591                  */
6592                 libzfs_mnttab_cache(g_zfs, B_TRUE);
6593                 if (find_command_idx(cmdname, &i) == 0) {
6594                         current_command = &command_table[i];
6595                         ret = command_table[i].func(argc - 1, argv + 1);
6596                 } else if (strchr(cmdname, '=') != NULL) {
6597                         verify(find_command_idx("set", &i) == 0);
6598                         current_command = &command_table[i];
6599                         ret = command_table[i].func(argc, argv);
6600                 } else {
6601                         (void) fprintf(stderr, gettext("unrecognized "
6602                             "command '%s'\n"), cmdname);
6603                         usage(B_FALSE);
6604                 }
6605                 libzfs_mnttab_cache(g_zfs, B_FALSE);
6606         }
6607 
6608         (void) fclose(mnttab_file);
6609 
6610         if (ret == 0 && log_history)
6611                 (void) zpool_log_history(g_zfs, history_str);
6612 
6613         libzfs_fini(g_zfs);
6614 
6615         /*
6616          * The 'ZFS_ABORT' environment variable causes us to dump core on exit
6617          * for the purposes of running ::findleaks.
6618          */
6619         if (getenv("ZFS_ABORT") != NULL) {
6620                 (void) printf("dumping core by request\n");
6621                 abort();
6622         }
6623 
6624         return (ret);
6625 }