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