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 (c) 2012 by Delphix. All rights reserved.
  25  * Copyright 2012 Milan Jurik. All rights reserved.
  26  * Copyright (c) 2012, Joyent, Inc. All rights reserved.
  27  * Copyright (c) 2013 Steven Hartland.  All rights reserved.
  28  * Copyright 2013 Nexenta Systems, Inc.  All rights reserved.
  29  */
  30 
  31 #include <assert.h>
  32 #include <ctype.h>
  33 #include <errno.h>
  34 #include <libgen.h>
  35 #include <libintl.h>
  36 #include <libuutil.h>
  37 #include <libnvpair.h>
  38 #include <locale.h>
  39 #include <stddef.h>
  40 #include <stdio.h>
  41 #include <stdlib.h>
  42 #include <strings.h>
  43 #include <unistd.h>
  44 #include <fcntl.h>
  45 #include <zone.h>
  46 #include <grp.h>
  47 #include <pwd.h>
  48 #include <signal.h>
  49 #include <sys/list.h>
  50 #include <sys/mkdev.h>
  51 #include <sys/mntent.h>
  52 #include <sys/mnttab.h>
  53 #include <sys/mount.h>
  54 #include <sys/stat.h>
  55 #include <sys/fs/zfs.h>
  56 #include <sys/types.h>
  57 #include <time.h>
  58 
  59 #include <libzfs.h>
  60 #include <libzfs_core.h>
  61 #include <zfs_prop.h>
  62 #include <zfs_deleg.h>
  63 #include <libuutil.h>
  64 #include <aclutils.h>
  65 #include <directory.h>
  66 
  67 #include "zfs_iter.h"
  68 #include "zfs_util.h"
  69 #include "zfs_comutil.h"
  70 
  71 libzfs_handle_t *g_zfs;
  72 
  73 static FILE *mnttab_file;
  74 static char history_str[HIS_MAX_RECORD_LEN];
  75 static boolean_t log_history = B_TRUE;
  76 
  77 static int zfs_do_clone(int argc, char **argv);
  78 static int zfs_do_create(int argc, char **argv);
  79 static int zfs_do_destroy(int argc, char **argv);
  80 static int zfs_do_get(int argc, char **argv);
  81 static int zfs_do_inherit(int argc, char **argv);
  82 static int zfs_do_list(int argc, char **argv);
  83 static int zfs_do_mount(int argc, char **argv);
  84 static int zfs_do_rename(int argc, char **argv);
  85 static int zfs_do_rollback(int argc, char **argv);
  86 static int zfs_do_set(int argc, char **argv);
  87 static int zfs_do_upgrade(int argc, char **argv);
  88 static int zfs_do_snapshot(int argc, char **argv);
  89 static int zfs_do_unmount(int argc, char **argv);
  90 static int zfs_do_share(int argc, char **argv);
  91 static int zfs_do_unshare(int argc, char **argv);
  92 static int zfs_do_send(int argc, char **argv);
  93 static int zfs_do_receive(int argc, char **argv);
  94 static int zfs_do_promote(int argc, char **argv);
  95 static int zfs_do_userspace(int argc, char **argv);
  96 static int zfs_do_allow(int argc, char **argv);
  97 static int zfs_do_unallow(int argc, char **argv);
  98 static int zfs_do_hold(int argc, char **argv);
  99 static int zfs_do_holds(int argc, char **argv);
 100 static int zfs_do_release(int argc, char **argv);
 101 static int zfs_do_diff(int argc, char **argv);
 102 
 103 /*
 104  * Enable a reasonable set of defaults for libumem debugging on DEBUG builds.
 105  */
 106 
 107 #ifdef DEBUG
 108 const char *
 109 _umem_debug_init(void)
 110 {
 111         return ("default,verbose"); /* $UMEM_DEBUG setting */
 112 }
 113 
 114 const char *
 115 _umem_logging_init(void)
 116 {
 117         return ("fail,contents"); /* $UMEM_LOGGING setting */
 118 }
 119 #endif
 120 
 121 typedef enum {
 122         HELP_CLONE,
 123         HELP_CREATE,
 124         HELP_DESTROY,
 125         HELP_GET,
 126         HELP_INHERIT,
 127         HELP_UPGRADE,
 128         HELP_LIST,
 129         HELP_MOUNT,
 130         HELP_PROMOTE,
 131         HELP_RECEIVE,
 132         HELP_RENAME,
 133         HELP_ROLLBACK,
 134         HELP_SEND,
 135         HELP_SET,
 136         HELP_SHARE,
 137         HELP_SNAPSHOT,
 138         HELP_UNMOUNT,
 139         HELP_UNSHARE,
 140         HELP_ALLOW,
 141         HELP_UNALLOW,
 142         HELP_USERSPACE,
 143         HELP_GROUPSPACE,
 144         HELP_HOLD,
 145         HELP_HOLDS,
 146         HELP_RELEASE,
 147         HELP_DIFF,
 148 } zfs_help_t;
 149 
 150 typedef struct zfs_command {
 151         const char      *name;
 152         int             (*func)(int argc, char **argv);
 153         zfs_help_t      usage;
 154 } zfs_command_t;
 155 
 156 /*
 157  * Master command table.  Each ZFS command has a name, associated function, and
 158  * usage message.  The usage messages need to be internationalized, so we have
 159  * to have a function to return the usage message based on a command index.
 160  *
 161  * These commands are organized according to how they are displayed in the usage
 162  * message.  An empty command (one with a NULL name) indicates an empty line in
 163  * the generic usage message.
 164  */
 165 static zfs_command_t command_table[] = {
 166         { "create",     zfs_do_create,          HELP_CREATE             },
 167         { "destroy",    zfs_do_destroy,         HELP_DESTROY            },
 168         { NULL },
 169         { "snapshot",   zfs_do_snapshot,        HELP_SNAPSHOT           },
 170         { "rollback",   zfs_do_rollback,        HELP_ROLLBACK           },
 171         { "clone",      zfs_do_clone,           HELP_CLONE              },
 172         { "promote",    zfs_do_promote,         HELP_PROMOTE            },
 173         { "rename",     zfs_do_rename,          HELP_RENAME             },
 174         { NULL },
 175         { "list",       zfs_do_list,            HELP_LIST               },
 176         { NULL },
 177         { "set",        zfs_do_set,             HELP_SET                },
 178         { "get",        zfs_do_get,             HELP_GET                },
 179         { "inherit",    zfs_do_inherit,         HELP_INHERIT            },
 180         { "upgrade",    zfs_do_upgrade,         HELP_UPGRADE            },
 181         { "userspace",  zfs_do_userspace,       HELP_USERSPACE          },
 182         { "groupspace", zfs_do_userspace,       HELP_GROUPSPACE         },
 183         { NULL },
 184         { "mount",      zfs_do_mount,           HELP_MOUNT              },
 185         { "unmount",    zfs_do_unmount,         HELP_UNMOUNT            },
 186         { "share",      zfs_do_share,           HELP_SHARE              },
 187         { "unshare",    zfs_do_unshare,         HELP_UNSHARE            },
 188         { NULL },
 189         { "send",       zfs_do_send,            HELP_SEND               },
 190         { "receive",    zfs_do_receive,         HELP_RECEIVE            },
 191         { NULL },
 192         { "allow",      zfs_do_allow,           HELP_ALLOW              },
 193         { NULL },
 194         { "unallow",    zfs_do_unallow,         HELP_UNALLOW            },
 195         { NULL },
 196         { "hold",       zfs_do_hold,            HELP_HOLD               },
 197         { "holds",      zfs_do_holds,           HELP_HOLDS              },
 198         { "release",    zfs_do_release,         HELP_RELEASE            },
 199         { "diff",       zfs_do_diff,            HELP_DIFF               },
 200 };
 201 
 202 #define NCOMMAND        (sizeof (command_table) / sizeof (command_table[0]))
 203 
 204 zfs_command_t *current_command;
 205 
 206 static const char *
 207 get_usage(zfs_help_t idx)
 208 {
 209         switch (idx) {
 210         case HELP_CLONE:
 211                 return (gettext("\tclone [-p] [-o property=value] ... "
 212                     "<snapshot> <filesystem|volume>\n"));
 213         case HELP_CREATE:
 214                 return (gettext("\tcreate [-p] [-o property=value] ... "
 215                     "<filesystem>\n"
 216                     "\tcreate [-ps] [-b blocksize] [-o property=value] ... "
 217                     "-V <size> <volume>\n"));
 218         case HELP_DESTROY:
 219                 return (gettext("\tdestroy [-fnpRrv] <filesystem|volume>\n"
 220                     "\tdestroy [-dnpRrv] "
 221                     "<filesystem|volume>@<snap>[%<snap>][,...]\n"));
 222         case HELP_GET:
 223                 return (gettext("\tget [-rHp] [-d max] "
 224                     "[-o \"all\" | field[,...]] [-t type[,...]] "
 225                     "[-s source[,...]]\n"
 226                     "\t    <\"all\" | property[,...]> "
 227                     "[filesystem|volume|snapshot] ...\n"));
 228         case HELP_INHERIT:
 229                 return (gettext("\tinherit [-rS] <property> "
 230                     "<filesystem|volume|snapshot> ...\n"));
 231         case HELP_UPGRADE:
 232                 return (gettext("\tupgrade [-v]\n"
 233                     "\tupgrade [-r] [-V version] <-a | filesystem ...>\n"));
 234         case HELP_LIST:
 235                 return (gettext("\tlist [-Hp] [-r|-d max] [-o property[,...]] "
 236                     "[-s property]...\n\t    [-S property]... [-t type[,...]] "
 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]... [-t type[,...]] "
 294                     "<filesystem|snapshot>\n"));
 295         case HELP_GROUPSPACE:
 296                 return (gettext("\tgroupspace [-Hinp] [-o field[,...]] "
 297                     "[-s field]...\n\t    [-S field]... [-t type[,...]] "
 298                     "<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 (parsable) 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", "posixuser", "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 [-Hp][-r|-d max] [-o property[,...]] [-s property] ... [-S property] ...
2785  *      [-t type[,...]] [filesystem|volume|snapshot] ...
2786  *
2787  *      -H      Scripted mode; elide headers and separate columns by tabs.
2788  *      -p      Display values in parsable (literal) format.
2789  *      -r      Recurse over all children.
2790  *      -d      Limit recursion by depth.
2791  *      -o      Control which fields to display.
2792  *      -s      Specify sort columns, descending order.
2793  *      -S      Specify sort columns, ascending order.
2794  *      -t      Control which object types to display.
2795  *
2796  * When given no arguments, list 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_literal;
2803         boolean_t       cb_scripted;
2804         zprop_list_t    *cb_proplist;
2805 } list_cbdata_t;
2806 
2807 /*
2808  * Given a list of columns to display, output appropriate headers for each one.
2809  */
2810 static void
2811 print_header(list_cbdata_t *cb)
2812 {
2813         zprop_list_t *pl = cb->cb_proplist;
2814         char headerbuf[ZFS_MAXPROPLEN];
2815         const char *header;
2816         int i;
2817         boolean_t first = B_TRUE;
2818         boolean_t right_justify;
2819 
2820         for (; pl != NULL; pl = pl->pl_next) {
2821                 if (!first) {
2822                         (void) printf("  ");
2823                 } else {
2824                         first = B_FALSE;
2825                 }
2826 
2827                 right_justify = B_FALSE;
2828                 if (pl->pl_prop != ZPROP_INVAL) {
2829                         header = zfs_prop_column_name(pl->pl_prop);
2830                         right_justify = zfs_prop_align_right(pl->pl_prop);
2831                 } else {
2832                         for (i = 0; pl->pl_user_prop[i] != '\0'; i++)
2833                                 headerbuf[i] = toupper(pl->pl_user_prop[i]);
2834                         headerbuf[i] = '\0';
2835                         header = headerbuf;
2836                 }
2837 
2838                 if (pl->pl_next == NULL && !right_justify)
2839                         (void) printf("%s", header);
2840                 else if (right_justify)
2841                         (void) printf("%*s", pl->pl_width, header);
2842                 else
2843                         (void) printf("%-*s", pl->pl_width, header);
2844         }
2845 
2846         (void) printf("\n");
2847 }
2848 
2849 /*
2850  * Given a dataset and a list of fields, print out all the properties according
2851  * to the described layout.
2852  */
2853 static void
2854 print_dataset(zfs_handle_t *zhp, list_cbdata_t *cb)
2855 {
2856         zprop_list_t *pl = cb->cb_proplist;
2857         boolean_t first = B_TRUE;
2858         char property[ZFS_MAXPROPLEN];
2859         nvlist_t *userprops = zfs_get_user_props(zhp);
2860         nvlist_t *propval;
2861         char *propstr;
2862         boolean_t right_justify;
2863 
2864         for (; pl != NULL; pl = pl->pl_next) {
2865                 if (!first) {
2866                         if (cb->cb_scripted)
2867                                 (void) printf("\t");
2868                         else
2869                                 (void) printf("  ");
2870                 } else {
2871                         first = B_FALSE;
2872                 }
2873 
2874                 if (pl->pl_prop != ZPROP_INVAL) {
2875                         if (zfs_prop_get(zhp, pl->pl_prop, property,
2876                             sizeof (property), NULL, NULL, 0,
2877                             cb->cb_literal) != 0)
2878                                 propstr = "-";
2879                         else
2880                                 propstr = property;
2881                         right_justify = zfs_prop_align_right(pl->pl_prop);
2882                 } else if (zfs_prop_userquota(pl->pl_user_prop)) {
2883                         if (zfs_prop_get_userquota(zhp, pl->pl_user_prop,
2884                             property, sizeof (property), cb->cb_literal) != 0)
2885                                 propstr = "-";
2886                         else
2887                                 propstr = property;
2888                         right_justify = B_TRUE;
2889                 } else if (zfs_prop_written(pl->pl_user_prop)) {
2890                         if (zfs_prop_get_written(zhp, pl->pl_user_prop,
2891                             property, sizeof (property), cb->cb_literal) != 0)
2892                                 propstr = "-";
2893                         else
2894                                 propstr = property;
2895                         right_justify = B_TRUE;
2896                 } else {
2897                         if (nvlist_lookup_nvlist(userprops,
2898                             pl->pl_user_prop, &propval) != 0)
2899                                 propstr = "-";
2900                         else
2901                                 verify(nvlist_lookup_string(propval,
2902                                     ZPROP_VALUE, &propstr) == 0);
2903                         right_justify = B_FALSE;
2904                 }
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 (cb->cb_scripted || (pl->pl_next == NULL && !right_justify))
2912                         (void) printf("%s", propstr);
2913                 else if (right_justify)
2914                         (void) printf("%*s", pl->pl_width, propstr);
2915                 else
2916                         (void) printf("%-*s", pl->pl_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);
2933                 cbp->cb_first = B_FALSE;
2934         }
2935 
2936         print_dataset(zhp, cbp);
2937 
2938         return (0);
2939 }
2940 
2941 static int
2942 zfs_do_list(int argc, char **argv)
2943 {
2944         int c;
2945         static char default_fields[] =
2946             "name,used,available,referenced,mountpoint";
2947         int types = ZFS_TYPE_DATASET;
2948         boolean_t types_specified = B_FALSE;
2949         char *fields = NULL;
2950         list_cbdata_t cb = { 0 };
2951         char *value;
2952         int limit = 0;
2953         int ret = 0;
2954         zfs_sort_column_t *sortcol = NULL;
2955         int flags = ZFS_ITER_PROP_LISTSNAPS | ZFS_ITER_ARGS_CAN_BE_PATHS;
2956 
2957         /* check options */
2958         while ((c = getopt(argc, argv, "HS:d:o:prs:t:")) != -1) {
2959                 switch (c) {
2960                 case 'o':
2961                         fields = optarg;
2962                         break;
2963                 case 'p':
2964                         cb.cb_literal = B_TRUE;
2965                         flags |= ZFS_ITER_LITERAL_PROPS;
2966                         break;
2967                 case 'd':
2968                         limit = parse_depth(optarg, &flags);
2969                         break;
2970                 case 'r':
2971                         flags |= ZFS_ITER_RECURSE;
2972                         break;
2973                 case 'H':
2974                         cb.cb_scripted = B_TRUE;
2975                         break;
2976                 case 's':
2977                         if (zfs_add_sort_column(&sortcol, optarg,
2978                             B_FALSE) != 0) {
2979                                 (void) fprintf(stderr,
2980                                     gettext("invalid property '%s'\n"), optarg);
2981                                 usage(B_FALSE);
2982                         }
2983                         break;
2984                 case 'S':
2985                         if (zfs_add_sort_column(&sortcol, optarg,
2986                             B_TRUE) != 0) {
2987                                 (void) fprintf(stderr,
2988                                     gettext("invalid property '%s'\n"), optarg);
2989                                 usage(B_FALSE);
2990                         }
2991                         break;
2992                 case 't':
2993                         types = 0;
2994                         types_specified = B_TRUE;
2995                         flags &= ~ZFS_ITER_PROP_LISTSNAPS;
2996                         while (*optarg != '\0') {
2997                                 static char *type_subopts[] = { "filesystem",
2998                                     "volume", "snapshot", "all", NULL };
2999 
3000                                 switch (getsubopt(&optarg, type_subopts,
3001                                     &value)) {
3002                                 case 0:
3003                                         types |= ZFS_TYPE_FILESYSTEM;
3004                                         break;
3005                                 case 1:
3006                                         types |= ZFS_TYPE_VOLUME;
3007                                         break;
3008                                 case 2:
3009                                         types |= ZFS_TYPE_SNAPSHOT;
3010                                         break;
3011                                 case 3:
3012                                         types = ZFS_TYPE_DATASET;
3013                                         break;
3014 
3015                                 default:
3016                                         (void) fprintf(stderr,
3017                                             gettext("invalid type '%s'\n"),
3018                                             value);
3019                                         usage(B_FALSE);
3020                                 }
3021                         }
3022                         break;
3023                 case ':':
3024                         (void) fprintf(stderr, gettext("missing argument for "
3025                             "'%c' option\n"), optopt);
3026                         usage(B_FALSE);
3027                         break;
3028                 case '?':
3029                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3030                             optopt);
3031                         usage(B_FALSE);
3032                 }
3033         }
3034 
3035         argc -= optind;
3036         argv += optind;
3037 
3038         if (fields == NULL)
3039                 fields = default_fields;
3040 
3041         /*
3042          * If "-o space" and no types were specified, don't display snapshots.
3043          */
3044         if (strcmp(fields, "space") == 0 && types_specified == B_FALSE)
3045                 types &= ~ZFS_TYPE_SNAPSHOT;
3046 
3047         /*
3048          * If the user specifies '-o all', the zprop_get_list() doesn't
3049          * normally include the name of the dataset.  For 'zfs list', we always
3050          * want this property to be first.
3051          */
3052         if (zprop_get_list(g_zfs, fields, &cb.cb_proplist, ZFS_TYPE_DATASET)
3053             != 0)
3054                 usage(B_FALSE);
3055 
3056         cb.cb_first = B_TRUE;
3057 
3058         ret = zfs_for_each(argc, argv, flags, types, sortcol, &cb.cb_proplist,
3059             limit, list_callback, &cb);
3060 
3061         zprop_free_list(cb.cb_proplist);
3062         zfs_free_sort_columns(sortcol);
3063 
3064         if (ret == 0 && cb.cb_first && !cb.cb_scripted)
3065                 (void) printf(gettext("no datasets available\n"));
3066 
3067         return (ret);
3068 }
3069 
3070 /*
3071  * zfs rename [-f] <fs | snap | vol> <fs | snap | vol>
3072  * zfs rename [-f] -p <fs | vol> <fs | vol>
3073  * zfs rename -r <snap> <snap>
3074  *
3075  * Renames the given dataset to another of the same type.
3076  *
3077  * The '-p' flag creates all the non-existing ancestors of the target first.
3078  */
3079 /* ARGSUSED */
3080 static int
3081 zfs_do_rename(int argc, char **argv)
3082 {
3083         zfs_handle_t *zhp;
3084         int c;
3085         int ret = 0;
3086         boolean_t recurse = B_FALSE;
3087         boolean_t parents = B_FALSE;
3088         boolean_t force_unmount = B_FALSE;
3089 
3090         /* check options */
3091         while ((c = getopt(argc, argv, "prf")) != -1) {
3092                 switch (c) {
3093                 case 'p':
3094                         parents = B_TRUE;
3095                         break;
3096                 case 'r':
3097                         recurse = B_TRUE;
3098                         break;
3099                 case 'f':
3100                         force_unmount = B_TRUE;
3101                         break;
3102                 case '?':
3103                 default:
3104                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3105                             optopt);
3106                         usage(B_FALSE);
3107                 }
3108         }
3109 
3110         argc -= optind;
3111         argv += optind;
3112 
3113         /* check number of arguments */
3114         if (argc < 1) {
3115                 (void) fprintf(stderr, gettext("missing source dataset "
3116                     "argument\n"));
3117                 usage(B_FALSE);
3118         }
3119         if (argc < 2) {
3120                 (void) fprintf(stderr, gettext("missing target dataset "
3121                     "argument\n"));
3122                 usage(B_FALSE);
3123         }
3124         if (argc > 2) {
3125                 (void) fprintf(stderr, gettext("too many arguments\n"));
3126                 usage(B_FALSE);
3127         }
3128 
3129         if (recurse && parents) {
3130                 (void) fprintf(stderr, gettext("-p and -r options are mutually "
3131                     "exclusive\n"));
3132                 usage(B_FALSE);
3133         }
3134 
3135         if (recurse && strchr(argv[0], '@') == 0) {
3136                 (void) fprintf(stderr, gettext("source dataset for recursive "
3137                     "rename must be a snapshot\n"));
3138                 usage(B_FALSE);
3139         }
3140 
3141         if ((zhp = zfs_open(g_zfs, argv[0], parents ? ZFS_TYPE_FILESYSTEM |
3142             ZFS_TYPE_VOLUME : ZFS_TYPE_DATASET)) == NULL)
3143                 return (1);
3144 
3145         /* If we were asked and the name looks good, try to create ancestors. */
3146         if (parents && zfs_name_valid(argv[1], zfs_get_type(zhp)) &&
3147             zfs_create_ancestors(g_zfs, argv[1]) != 0) {
3148                 zfs_close(zhp);
3149                 return (1);
3150         }
3151 
3152         ret = (zfs_rename(zhp, argv[1], recurse, force_unmount) != 0);
3153 
3154         zfs_close(zhp);
3155         return (ret);
3156 }
3157 
3158 /*
3159  * zfs promote <fs>
3160  *
3161  * Promotes the given clone fs to be the parent
3162  */
3163 /* ARGSUSED */
3164 static int
3165 zfs_do_promote(int argc, char **argv)
3166 {
3167         zfs_handle_t *zhp;
3168         int ret = 0;
3169 
3170         /* check options */
3171         if (argc > 1 && argv[1][0] == '-') {
3172                 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3173                     argv[1][1]);
3174                 usage(B_FALSE);
3175         }
3176 
3177         /* check number of arguments */
3178         if (argc < 2) {
3179                 (void) fprintf(stderr, gettext("missing clone filesystem"
3180                     " argument\n"));
3181                 usage(B_FALSE);
3182         }
3183         if (argc > 2) {
3184                 (void) fprintf(stderr, gettext("too many arguments\n"));
3185                 usage(B_FALSE);
3186         }
3187 
3188         zhp = zfs_open(g_zfs, argv[1], ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
3189         if (zhp == NULL)
3190                 return (1);
3191 
3192         ret = (zfs_promote(zhp) != 0);
3193 
3194 
3195         zfs_close(zhp);
3196         return (ret);
3197 }
3198 
3199 /*
3200  * zfs rollback [-rRf] <snapshot>
3201  *
3202  *      -r      Delete any intervening snapshots before doing rollback
3203  *      -R      Delete any snapshots and their clones
3204  *      -f      ignored for backwards compatability
3205  *
3206  * Given a filesystem, rollback to a specific snapshot, discarding any changes
3207  * since then and making it the active dataset.  If more recent snapshots exist,
3208  * the command will complain unless the '-r' flag is given.
3209  */
3210 typedef struct rollback_cbdata {
3211         uint64_t        cb_create;
3212         boolean_t       cb_first;
3213         int             cb_doclones;
3214         char            *cb_target;
3215         int             cb_error;
3216         boolean_t       cb_recurse;
3217         boolean_t       cb_dependent;
3218 } rollback_cbdata_t;
3219 
3220 /*
3221  * Report any snapshots more recent than the one specified.  Used when '-r' is
3222  * not specified.  We reuse this same callback for the snapshot dependents - if
3223  * 'cb_dependent' is set, then this is a dependent and we should report it
3224  * without checking the transaction group.
3225  */
3226 static int
3227 rollback_check(zfs_handle_t *zhp, void *data)
3228 {
3229         rollback_cbdata_t *cbp = data;
3230 
3231         if (cbp->cb_doclones) {
3232                 zfs_close(zhp);
3233                 return (0);
3234         }
3235 
3236         if (!cbp->cb_dependent) {
3237                 if (strcmp(zfs_get_name(zhp), cbp->cb_target) != 0 &&
3238                     zfs_get_type(zhp) == ZFS_TYPE_SNAPSHOT &&
3239                     zfs_prop_get_int(zhp, ZFS_PROP_CREATETXG) >
3240                     cbp->cb_create) {
3241 
3242                         if (cbp->cb_first && !cbp->cb_recurse) {
3243                                 (void) fprintf(stderr, gettext("cannot "
3244                                     "rollback to '%s': more recent snapshots "
3245                                     "exist\n"),
3246                                     cbp->cb_target);
3247                                 (void) fprintf(stderr, gettext("use '-r' to "
3248                                     "force deletion of the following "
3249                                     "snapshots:\n"));
3250                                 cbp->cb_first = 0;
3251                                 cbp->cb_error = 1;
3252                         }
3253 
3254                         if (cbp->cb_recurse) {
3255                                 cbp->cb_dependent = B_TRUE;
3256                                 if (zfs_iter_dependents(zhp, B_TRUE,
3257                                     rollback_check, cbp) != 0) {
3258                                         zfs_close(zhp);
3259                                         return (-1);
3260                                 }
3261                                 cbp->cb_dependent = B_FALSE;
3262                         } else {
3263                                 (void) fprintf(stderr, "%s\n",
3264                                     zfs_get_name(zhp));
3265                         }
3266                 }
3267         } else {
3268                 if (cbp->cb_first && cbp->cb_recurse) {
3269                         (void) fprintf(stderr, gettext("cannot rollback to "
3270                             "'%s': clones of previous snapshots exist\n"),
3271                             cbp->cb_target);
3272                         (void) fprintf(stderr, gettext("use '-R' to "
3273                             "force deletion of the following clones and "
3274                             "dependents:\n"));
3275                         cbp->cb_first = 0;
3276                         cbp->cb_error = 1;
3277                 }
3278 
3279                 (void) fprintf(stderr, "%s\n", zfs_get_name(zhp));
3280         }
3281 
3282         zfs_close(zhp);
3283         return (0);
3284 }
3285 
3286 static int
3287 zfs_do_rollback(int argc, char **argv)
3288 {
3289         int ret = 0;
3290         int c;
3291         boolean_t force = B_FALSE;
3292         rollback_cbdata_t cb = { 0 };
3293         zfs_handle_t *zhp, *snap;
3294         char parentname[ZFS_MAXNAMELEN];
3295         char *delim;
3296 
3297         /* check options */
3298         while ((c = getopt(argc, argv, "rRf")) != -1) {
3299                 switch (c) {
3300                 case 'r':
3301                         cb.cb_recurse = 1;
3302                         break;
3303                 case 'R':
3304                         cb.cb_recurse = 1;
3305                         cb.cb_doclones = 1;
3306                         break;
3307                 case 'f':
3308                         force = B_TRUE;
3309                         break;
3310                 case '?':
3311                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3312                             optopt);
3313                         usage(B_FALSE);
3314                 }
3315         }
3316 
3317         argc -= optind;
3318         argv += optind;
3319 
3320         /* check number of arguments */
3321         if (argc < 1) {
3322                 (void) fprintf(stderr, gettext("missing dataset argument\n"));
3323                 usage(B_FALSE);
3324         }
3325         if (argc > 1) {
3326                 (void) fprintf(stderr, gettext("too many arguments\n"));
3327                 usage(B_FALSE);
3328         }
3329 
3330         /* open the snapshot */
3331         if ((snap = zfs_open(g_zfs, argv[0], ZFS_TYPE_SNAPSHOT)) == NULL)
3332                 return (1);
3333 
3334         /* open the parent dataset */
3335         (void) strlcpy(parentname, argv[0], sizeof (parentname));
3336         verify((delim = strrchr(parentname, '@')) != NULL);
3337         *delim = '\0';
3338         if ((zhp = zfs_open(g_zfs, parentname, ZFS_TYPE_DATASET)) == NULL) {
3339                 zfs_close(snap);
3340                 return (1);
3341         }
3342 
3343         /*
3344          * Check for more recent snapshots and/or clones based on the presence
3345          * of '-r' and '-R'.
3346          */
3347         cb.cb_target = argv[0];
3348         cb.cb_create = zfs_prop_get_int(snap, ZFS_PROP_CREATETXG);
3349         cb.cb_first = B_TRUE;
3350         cb.cb_error = 0;
3351         if ((ret = zfs_iter_children(zhp, rollback_check, &cb)) != 0)
3352                 goto out;
3353 
3354         if ((ret = cb.cb_error) != 0)
3355                 goto out;
3356 
3357         /*
3358          * Rollback parent to the given snapshot.
3359          */
3360         ret = zfs_rollback(zhp, snap, force);
3361 
3362 out:
3363         zfs_close(snap);
3364         zfs_close(zhp);
3365 
3366         if (ret == 0)
3367                 return (0);
3368         else
3369                 return (1);
3370 }
3371 
3372 /*
3373  * zfs set property=value { fs | snap | vol } ...
3374  *
3375  * Sets the given property for all datasets specified on the command line.
3376  */
3377 typedef struct set_cbdata {
3378         char            *cb_propname;
3379         char            *cb_value;
3380 } set_cbdata_t;
3381 
3382 static int
3383 set_callback(zfs_handle_t *zhp, void *data)
3384 {
3385         set_cbdata_t *cbp = data;
3386 
3387         if (zfs_prop_set(zhp, cbp->cb_propname, cbp->cb_value) != 0) {
3388                 switch (libzfs_errno(g_zfs)) {
3389                 case EZFS_MOUNTFAILED:
3390                         (void) fprintf(stderr, gettext("property may be set "
3391                             "but unable to remount filesystem\n"));
3392                         break;
3393                 case EZFS_SHARENFSFAILED:
3394                         (void) fprintf(stderr, gettext("property may be set "
3395                             "but unable to reshare filesystem\n"));
3396                         break;
3397                 }
3398                 return (1);
3399         }
3400         return (0);
3401 }
3402 
3403 static int
3404 zfs_do_set(int argc, char **argv)
3405 {
3406         set_cbdata_t cb;
3407         int ret = 0;
3408 
3409         /* check for options */
3410         if (argc > 1 && argv[1][0] == '-') {
3411                 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3412                     argv[1][1]);
3413                 usage(B_FALSE);
3414         }
3415 
3416         /* check number of arguments */
3417         if (argc < 2) {
3418                 (void) fprintf(stderr, gettext("missing property=value "
3419                     "argument\n"));
3420                 usage(B_FALSE);
3421         }
3422         if (argc < 3) {
3423                 (void) fprintf(stderr, gettext("missing dataset name\n"));
3424                 usage(B_FALSE);
3425         }
3426 
3427         /* validate property=value argument */
3428         cb.cb_propname = argv[1];
3429         if (((cb.cb_value = strchr(cb.cb_propname, '=')) == NULL) ||
3430             (cb.cb_value[1] == '\0')) {
3431                 (void) fprintf(stderr, gettext("missing value in "
3432                     "property=value argument\n"));
3433                 usage(B_FALSE);
3434         }
3435 
3436         *cb.cb_value = '\0';
3437         cb.cb_value++;
3438 
3439         if (*cb.cb_propname == '\0') {
3440                 (void) fprintf(stderr,
3441                     gettext("missing property in property=value argument\n"));
3442                 usage(B_FALSE);
3443         }
3444 
3445         ret = zfs_for_each(argc - 2, argv + 2, NULL,
3446             ZFS_TYPE_DATASET, NULL, NULL, 0, set_callback, &cb);
3447 
3448         return (ret);
3449 }
3450 
3451 typedef struct snap_cbdata {
3452         nvlist_t *sd_nvl;
3453         boolean_t sd_recursive;
3454         const char *sd_snapname;
3455 } snap_cbdata_t;
3456 
3457 static int
3458 zfs_snapshot_cb(zfs_handle_t *zhp, void *arg)
3459 {
3460         snap_cbdata_t *sd = arg;
3461         char *name;
3462         int rv = 0;
3463         int error;
3464 
3465         if (sd->sd_recursive &&
3466             zfs_prop_get_int(zhp, ZFS_PROP_INCONSISTENT) != 0) {
3467                 zfs_close(zhp);
3468                 return (0);
3469         }
3470 
3471         error = asprintf(&name, "%s@%s", zfs_get_name(zhp), sd->sd_snapname);
3472         if (error == -1)
3473                 nomem();
3474         fnvlist_add_boolean(sd->sd_nvl, name);
3475         free(name);
3476 
3477         if (sd->sd_recursive)
3478                 rv = zfs_iter_filesystems(zhp, zfs_snapshot_cb, sd);
3479         zfs_close(zhp);
3480         return (rv);
3481 }
3482 
3483 /*
3484  * zfs snapshot [-r] [-o prop=value] ... <fs@snap>
3485  *
3486  * Creates a snapshot with the given name.  While functionally equivalent to
3487  * 'zfs create', it is a separate command to differentiate intent.
3488  */
3489 static int
3490 zfs_do_snapshot(int argc, char **argv)
3491 {
3492         int ret = 0;
3493         char c;
3494         nvlist_t *props;
3495         snap_cbdata_t sd = { 0 };
3496         boolean_t multiple_snaps = B_FALSE;
3497 
3498         if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0)
3499                 nomem();
3500         if (nvlist_alloc(&sd.sd_nvl, NV_UNIQUE_NAME, 0) != 0)
3501                 nomem();
3502 
3503         /* check options */
3504         while ((c = getopt(argc, argv, "ro:")) != -1) {
3505                 switch (c) {
3506                 case 'o':
3507                         if (parseprop(props))
3508                                 return (1);
3509                         break;
3510                 case 'r':
3511                         sd.sd_recursive = B_TRUE;
3512                         multiple_snaps = B_TRUE;
3513                         break;
3514                 case '?':
3515                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3516                             optopt);
3517                         goto usage;
3518                 }
3519         }
3520 
3521         argc -= optind;
3522         argv += optind;
3523 
3524         /* check number of arguments */
3525         if (argc < 1) {
3526                 (void) fprintf(stderr, gettext("missing snapshot argument\n"));
3527                 goto usage;
3528         }
3529 
3530         if (argc > 1)
3531                 multiple_snaps = B_TRUE;
3532         for (; argc > 0; argc--, argv++) {
3533                 char *atp;
3534                 zfs_handle_t *zhp;
3535 
3536                 atp = strchr(argv[0], '@');
3537                 if (atp == NULL)
3538                         goto usage;
3539                 *atp = '\0';
3540                 sd.sd_snapname = atp + 1;
3541                 zhp = zfs_open(g_zfs, argv[0],
3542                     ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
3543                 if (zhp == NULL)
3544                         goto usage;
3545                 if (zfs_snapshot_cb(zhp, &sd) != 0)
3546                         goto usage;
3547         }
3548 
3549         ret = zfs_snapshot_nvl(g_zfs, sd.sd_nvl, props);
3550         nvlist_free(sd.sd_nvl);
3551         nvlist_free(props);
3552         if (ret != 0 && multiple_snaps)
3553                 (void) fprintf(stderr, gettext("no snapshots were created\n"));
3554         return (ret != 0);
3555 
3556 usage:
3557         nvlist_free(sd.sd_nvl);
3558         nvlist_free(props);
3559         usage(B_FALSE);
3560         return (-1);
3561 }
3562 
3563 /*
3564  * Send a backup stream to stdout.
3565  */
3566 static int
3567 zfs_do_send(int argc, char **argv)
3568 {
3569         char *fromname = NULL;
3570         char *toname = NULL;
3571         char *cp;
3572         zfs_handle_t *zhp;
3573         sendflags_t flags = { 0 };
3574         int c, err;
3575         nvlist_t *dbgnv = NULL;
3576         boolean_t extraverbose = B_FALSE;
3577 
3578         /* check options */
3579         while ((c = getopt(argc, argv, ":i:I:RDpvnP")) != -1) {
3580                 switch (c) {
3581                 case 'i':
3582                         if (fromname)
3583                                 usage(B_FALSE);
3584                         fromname = optarg;
3585                         break;
3586                 case 'I':
3587                         if (fromname)
3588                                 usage(B_FALSE);
3589                         fromname = optarg;
3590                         flags.doall = B_TRUE;
3591                         break;
3592                 case 'R':
3593                         flags.replicate = B_TRUE;
3594                         break;
3595                 case 'p':
3596                         flags.props = B_TRUE;
3597                         break;
3598                 case 'P':
3599                         flags.parsable = B_TRUE;
3600                         flags.verbose = B_TRUE;
3601                         break;
3602                 case 'v':
3603                         if (flags.verbose)
3604                                 extraverbose = B_TRUE;
3605                         flags.verbose = B_TRUE;
3606                         flags.progress = B_TRUE;
3607                         break;
3608                 case 'D':
3609                         flags.dedup = B_TRUE;
3610                         break;
3611                 case 'n':
3612                         flags.dryrun = B_TRUE;
3613                         break;
3614                 case ':':
3615                         (void) fprintf(stderr, gettext("missing argument for "
3616                             "'%c' option\n"), optopt);
3617                         usage(B_FALSE);
3618                         break;
3619                 case '?':
3620                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3621                             optopt);
3622                         usage(B_FALSE);
3623                 }
3624         }
3625 
3626         argc -= optind;
3627         argv += optind;
3628 
3629         /* check number of arguments */
3630         if (argc < 1) {
3631                 (void) fprintf(stderr, gettext("missing snapshot argument\n"));
3632                 usage(B_FALSE);
3633         }
3634         if (argc > 1) {
3635                 (void) fprintf(stderr, gettext("too many arguments\n"));
3636                 usage(B_FALSE);
3637         }
3638 
3639         if (!flags.dryrun && isatty(STDOUT_FILENO)) {
3640                 (void) fprintf(stderr,
3641                     gettext("Error: Stream can not be written to a terminal.\n"
3642                     "You must redirect standard output.\n"));
3643                 return (1);
3644         }
3645 
3646         cp = strchr(argv[0], '@');
3647         if (cp == NULL) {
3648                 (void) fprintf(stderr,
3649                     gettext("argument must be a snapshot\n"));
3650                 usage(B_FALSE);
3651         }
3652         *cp = '\0';
3653         toname = cp + 1;
3654         zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
3655         if (zhp == NULL)
3656                 return (1);
3657 
3658         /*
3659          * If they specified the full path to the snapshot, chop off
3660          * everything except the short name of the snapshot, but special
3661          * case if they specify the origin.
3662          */
3663         if (fromname && (cp = strchr(fromname, '@')) != NULL) {
3664                 char origin[ZFS_MAXNAMELEN];
3665                 zprop_source_t src;
3666 
3667                 (void) zfs_prop_get(zhp, ZFS_PROP_ORIGIN,
3668                     origin, sizeof (origin), &src, NULL, 0, B_FALSE);
3669 
3670                 if (strcmp(origin, fromname) == 0) {
3671                         fromname = NULL;
3672                         flags.fromorigin = B_TRUE;
3673                 } else {
3674                         *cp = '\0';
3675                         if (cp != fromname && strcmp(argv[0], fromname)) {
3676                                 (void) fprintf(stderr,
3677                                     gettext("incremental source must be "
3678                                     "in same filesystem\n"));
3679                                 usage(B_FALSE);
3680                         }
3681                         fromname = cp + 1;
3682                         if (strchr(fromname, '@') || strchr(fromname, '/')) {
3683                                 (void) fprintf(stderr,
3684                                     gettext("invalid incremental source\n"));
3685                                 usage(B_FALSE);
3686                         }
3687                 }
3688         }
3689 
3690         if (flags.replicate && fromname == NULL)
3691                 flags.doall = B_TRUE;
3692 
3693         err = zfs_send(zhp, fromname, toname, &flags, STDOUT_FILENO, NULL, 0,
3694             extraverbose ? &dbgnv : NULL);
3695 
3696         if (extraverbose && dbgnv != NULL) {
3697                 /*
3698                  * dump_nvlist prints to stdout, but that's been
3699                  * redirected to a file.  Make it print to stderr
3700                  * instead.
3701                  */
3702                 (void) dup2(STDERR_FILENO, STDOUT_FILENO);
3703                 dump_nvlist(dbgnv, 0);
3704                 nvlist_free(dbgnv);
3705         }
3706         zfs_close(zhp);
3707 
3708         return (err != 0);
3709 }
3710 
3711 /*
3712  * zfs receive [-vnFu] [-d | -e] <fs@snap>
3713  *
3714  * Restore a backup stream from stdin.
3715  */
3716 static int
3717 zfs_do_receive(int argc, char **argv)
3718 {
3719         int c, err;
3720         recvflags_t flags = { 0 };
3721 
3722         /* check options */
3723         while ((c = getopt(argc, argv, ":denuvF")) != -1) {
3724                 switch (c) {
3725                 case 'd':
3726                         flags.isprefix = B_TRUE;
3727                         break;
3728                 case 'e':
3729                         flags.isprefix = B_TRUE;
3730                         flags.istail = B_TRUE;
3731                         break;
3732                 case 'n':
3733                         flags.dryrun = B_TRUE;
3734                         break;
3735                 case 'u':
3736                         flags.nomount = B_TRUE;
3737                         break;
3738                 case 'v':
3739                         flags.verbose = B_TRUE;
3740                         break;
3741                 case 'F':
3742                         flags.force = B_TRUE;
3743                         break;
3744                 case ':':
3745                         (void) fprintf(stderr, gettext("missing argument for "
3746                             "'%c' option\n"), optopt);
3747                         usage(B_FALSE);
3748                         break;
3749                 case '?':
3750                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3751                             optopt);
3752                         usage(B_FALSE);
3753                 }
3754         }
3755 
3756         argc -= optind;
3757         argv += optind;
3758 
3759         /* check number of arguments */
3760         if (argc < 1) {
3761                 (void) fprintf(stderr, gettext("missing snapshot argument\n"));
3762                 usage(B_FALSE);
3763         }
3764         if (argc > 1) {
3765                 (void) fprintf(stderr, gettext("too many arguments\n"));
3766                 usage(B_FALSE);
3767         }
3768 
3769         if (isatty(STDIN_FILENO)) {
3770                 (void) fprintf(stderr,
3771                     gettext("Error: Backup stream can not be read "
3772                     "from a terminal.\n"
3773                     "You must redirect standard input.\n"));
3774                 return (1);
3775         }
3776 
3777         err = zfs_receive(g_zfs, argv[0], &flags, STDIN_FILENO, NULL);
3778 
3779         return (err != 0);
3780 }
3781 
3782 /*
3783  * allow/unallow stuff
3784  */
3785 /* copied from zfs/sys/dsl_deleg.h */
3786 #define ZFS_DELEG_PERM_CREATE           "create"
3787 #define ZFS_DELEG_PERM_DESTROY          "destroy"
3788 #define ZFS_DELEG_PERM_SNAPSHOT         "snapshot"
3789 #define ZFS_DELEG_PERM_ROLLBACK         "rollback"
3790 #define ZFS_DELEG_PERM_CLONE            "clone"
3791 #define ZFS_DELEG_PERM_PROMOTE          "promote"
3792 #define ZFS_DELEG_PERM_RENAME           "rename"
3793 #define ZFS_DELEG_PERM_MOUNT            "mount"
3794 #define ZFS_DELEG_PERM_SHARE            "share"
3795 #define ZFS_DELEG_PERM_SEND             "send"
3796 #define ZFS_DELEG_PERM_RECEIVE          "receive"
3797 #define ZFS_DELEG_PERM_ALLOW            "allow"
3798 #define ZFS_DELEG_PERM_USERPROP         "userprop"
3799 #define ZFS_DELEG_PERM_VSCAN            "vscan" /* ??? */
3800 #define ZFS_DELEG_PERM_USERQUOTA        "userquota"
3801 #define ZFS_DELEG_PERM_GROUPQUOTA       "groupquota"
3802 #define ZFS_DELEG_PERM_USERUSED         "userused"
3803 #define ZFS_DELEG_PERM_GROUPUSED        "groupused"
3804 #define ZFS_DELEG_PERM_HOLD             "hold"
3805 #define ZFS_DELEG_PERM_RELEASE          "release"
3806 #define ZFS_DELEG_PERM_DIFF             "diff"
3807 
3808 #define ZFS_NUM_DELEG_NOTES ZFS_DELEG_NOTE_NONE
3809 
3810 static zfs_deleg_perm_tab_t zfs_deleg_perm_tbl[] = {
3811         { ZFS_DELEG_PERM_ALLOW, ZFS_DELEG_NOTE_ALLOW },
3812         { ZFS_DELEG_PERM_CLONE, ZFS_DELEG_NOTE_CLONE },
3813         { ZFS_DELEG_PERM_CREATE, ZFS_DELEG_NOTE_CREATE },
3814         { ZFS_DELEG_PERM_DESTROY, ZFS_DELEG_NOTE_DESTROY },
3815         { ZFS_DELEG_PERM_DIFF, ZFS_DELEG_NOTE_DIFF},
3816         { ZFS_DELEG_PERM_HOLD, ZFS_DELEG_NOTE_HOLD },
3817         { ZFS_DELEG_PERM_MOUNT, ZFS_DELEG_NOTE_MOUNT },
3818         { ZFS_DELEG_PERM_PROMOTE, ZFS_DELEG_NOTE_PROMOTE },
3819         { ZFS_DELEG_PERM_RECEIVE, ZFS_DELEG_NOTE_RECEIVE },
3820         { ZFS_DELEG_PERM_RELEASE, ZFS_DELEG_NOTE_RELEASE },
3821         { ZFS_DELEG_PERM_RENAME, ZFS_DELEG_NOTE_RENAME },
3822         { ZFS_DELEG_PERM_ROLLBACK, ZFS_DELEG_NOTE_ROLLBACK },
3823         { ZFS_DELEG_PERM_SEND, ZFS_DELEG_NOTE_SEND },
3824         { ZFS_DELEG_PERM_SHARE, ZFS_DELEG_NOTE_SHARE },
3825         { ZFS_DELEG_PERM_SNAPSHOT, ZFS_DELEG_NOTE_SNAPSHOT },
3826 
3827         { ZFS_DELEG_PERM_GROUPQUOTA, ZFS_DELEG_NOTE_GROUPQUOTA },
3828         { ZFS_DELEG_PERM_GROUPUSED, ZFS_DELEG_NOTE_GROUPUSED },
3829         { ZFS_DELEG_PERM_USERPROP, ZFS_DELEG_NOTE_USERPROP },
3830         { ZFS_DELEG_PERM_USERQUOTA, ZFS_DELEG_NOTE_USERQUOTA },
3831         { ZFS_DELEG_PERM_USERUSED, ZFS_DELEG_NOTE_USERUSED },
3832         { NULL, ZFS_DELEG_NOTE_NONE }
3833 };
3834 
3835 /* permission structure */
3836 typedef struct deleg_perm {
3837         zfs_deleg_who_type_t    dp_who_type;
3838         const char              *dp_name;
3839         boolean_t               dp_local;
3840         boolean_t               dp_descend;
3841 } deleg_perm_t;
3842 
3843 /* */
3844 typedef struct deleg_perm_node {
3845         deleg_perm_t            dpn_perm;
3846 
3847         uu_avl_node_t           dpn_avl_node;
3848 } deleg_perm_node_t;
3849 
3850 typedef struct fs_perm fs_perm_t;
3851 
3852 /* permissions set */
3853 typedef struct who_perm {
3854         zfs_deleg_who_type_t    who_type;
3855         const char              *who_name;              /* id */
3856         char                    who_ug_name[256];       /* user/group name */
3857         fs_perm_t               *who_fsperm;            /* uplink */
3858 
3859         uu_avl_t                *who_deleg_perm_avl;    /* permissions */
3860 } who_perm_t;
3861 
3862 /* */
3863 typedef struct who_perm_node {
3864         who_perm_t      who_perm;
3865         uu_avl_node_t   who_avl_node;
3866 } who_perm_node_t;
3867 
3868 typedef struct fs_perm_set fs_perm_set_t;
3869 /* fs permissions */
3870 struct fs_perm {
3871         const char              *fsp_name;
3872 
3873         uu_avl_t                *fsp_sc_avl;    /* sets,create */
3874         uu_avl_t                *fsp_uge_avl;   /* user,group,everyone */
3875 
3876         fs_perm_set_t           *fsp_set;       /* uplink */
3877 };
3878 
3879 /* */
3880 typedef struct fs_perm_node {
3881         fs_perm_t       fspn_fsperm;
3882         uu_avl_t        *fspn_avl;
3883 
3884         uu_list_node_t  fspn_list_node;
3885 } fs_perm_node_t;
3886 
3887 /* top level structure */
3888 struct fs_perm_set {
3889         uu_list_pool_t  *fsps_list_pool;
3890         uu_list_t       *fsps_list; /* list of fs_perms */
3891 
3892         uu_avl_pool_t   *fsps_named_set_avl_pool;
3893         uu_avl_pool_t   *fsps_who_perm_avl_pool;
3894         uu_avl_pool_t   *fsps_deleg_perm_avl_pool;
3895 };
3896 
3897 static inline const char *
3898 deleg_perm_type(zfs_deleg_note_t note)
3899 {
3900         /* subcommands */
3901         switch (note) {
3902                 /* SUBCOMMANDS */
3903                 /* OTHER */
3904         case ZFS_DELEG_NOTE_GROUPQUOTA:
3905         case ZFS_DELEG_NOTE_GROUPUSED:
3906         case ZFS_DELEG_NOTE_USERPROP:
3907         case ZFS_DELEG_NOTE_USERQUOTA:
3908         case ZFS_DELEG_NOTE_USERUSED:
3909                 /* other */
3910                 return (gettext("other"));
3911         default:
3912                 return (gettext("subcommand"));
3913         }
3914 }
3915 
3916 static int inline
3917 who_type2weight(zfs_deleg_who_type_t who_type)
3918 {
3919         int res;
3920         switch (who_type) {
3921                 case ZFS_DELEG_NAMED_SET_SETS:
3922                 case ZFS_DELEG_NAMED_SET:
3923                         res = 0;
3924                         break;
3925                 case ZFS_DELEG_CREATE_SETS:
3926                 case ZFS_DELEG_CREATE:
3927                         res = 1;
3928                         break;
3929                 case ZFS_DELEG_USER_SETS:
3930                 case ZFS_DELEG_USER:
3931                         res = 2;
3932                         break;
3933                 case ZFS_DELEG_GROUP_SETS:
3934                 case ZFS_DELEG_GROUP:
3935                         res = 3;
3936                         break;
3937                 case ZFS_DELEG_EVERYONE_SETS:
3938                 case ZFS_DELEG_EVERYONE:
3939                         res = 4;
3940                         break;
3941                 default:
3942                         res = -1;
3943         }
3944 
3945         return (res);
3946 }
3947 
3948 /* ARGSUSED */
3949 static int
3950 who_perm_compare(const void *larg, const void *rarg, void *unused)
3951 {
3952         const who_perm_node_t *l = larg;
3953         const who_perm_node_t *r = rarg;
3954         zfs_deleg_who_type_t ltype = l->who_perm.who_type;
3955         zfs_deleg_who_type_t rtype = r->who_perm.who_type;
3956         int lweight = who_type2weight(ltype);
3957         int rweight = who_type2weight(rtype);
3958         int res = lweight - rweight;
3959         if (res == 0)
3960                 res = strncmp(l->who_perm.who_name, r->who_perm.who_name,
3961                     ZFS_MAX_DELEG_NAME-1);
3962 
3963         if (res == 0)
3964                 return (0);
3965         if (res > 0)
3966                 return (1);
3967         else
3968                 return (-1);
3969 }
3970 
3971 /* ARGSUSED */
3972 static int
3973 deleg_perm_compare(const void *larg, const void *rarg, void *unused)
3974 {
3975         const deleg_perm_node_t *l = larg;
3976         const deleg_perm_node_t *r = rarg;
3977         int res =  strncmp(l->dpn_perm.dp_name, r->dpn_perm.dp_name,
3978             ZFS_MAX_DELEG_NAME-1);
3979 
3980         if (res == 0)
3981                 return (0);
3982 
3983         if (res > 0)
3984                 return (1);
3985         else
3986                 return (-1);
3987 }
3988 
3989 static inline void
3990 fs_perm_set_init(fs_perm_set_t *fspset)
3991 {
3992         bzero(fspset, sizeof (fs_perm_set_t));
3993 
3994         if ((fspset->fsps_list_pool = uu_list_pool_create("fsps_list_pool",
3995             sizeof (fs_perm_node_t), offsetof(fs_perm_node_t, fspn_list_node),
3996             NULL, UU_DEFAULT)) == NULL)
3997                 nomem();
3998         if ((fspset->fsps_list = uu_list_create(fspset->fsps_list_pool, NULL,
3999             UU_DEFAULT)) == NULL)
4000                 nomem();
4001 
4002         if ((fspset->fsps_named_set_avl_pool = uu_avl_pool_create(
4003             "named_set_avl_pool", sizeof (who_perm_node_t), offsetof(
4004             who_perm_node_t, who_avl_node), who_perm_compare,
4005             UU_DEFAULT)) == NULL)
4006                 nomem();
4007 
4008         if ((fspset->fsps_who_perm_avl_pool = uu_avl_pool_create(
4009             "who_perm_avl_pool", sizeof (who_perm_node_t), offsetof(
4010             who_perm_node_t, who_avl_node), who_perm_compare,
4011             UU_DEFAULT)) == NULL)
4012                 nomem();
4013 
4014         if ((fspset->fsps_deleg_perm_avl_pool = uu_avl_pool_create(
4015             "deleg_perm_avl_pool", sizeof (deleg_perm_node_t), offsetof(
4016             deleg_perm_node_t, dpn_avl_node), deleg_perm_compare, UU_DEFAULT))
4017             == NULL)
4018                 nomem();
4019 }
4020 
4021 static inline void fs_perm_fini(fs_perm_t *);
4022 static inline void who_perm_fini(who_perm_t *);
4023 
4024 static inline void
4025 fs_perm_set_fini(fs_perm_set_t *fspset)
4026 {
4027         fs_perm_node_t *node = uu_list_first(fspset->fsps_list);
4028 
4029         while (node != NULL) {
4030                 fs_perm_node_t *next_node =
4031                     uu_list_next(fspset->fsps_list, node);
4032                 fs_perm_t *fsperm = &node->fspn_fsperm;
4033                 fs_perm_fini(fsperm);
4034                 uu_list_remove(fspset->fsps_list, node);
4035                 free(node);
4036                 node = next_node;
4037         }
4038 
4039         uu_avl_pool_destroy(fspset->fsps_named_set_avl_pool);
4040         uu_avl_pool_destroy(fspset->fsps_who_perm_avl_pool);
4041         uu_avl_pool_destroy(fspset->fsps_deleg_perm_avl_pool);
4042 }
4043 
4044 static inline void
4045 deleg_perm_init(deleg_perm_t *deleg_perm, zfs_deleg_who_type_t type,
4046     const char *name)
4047 {
4048         deleg_perm->dp_who_type = type;
4049         deleg_perm->dp_name = name;
4050 }
4051 
4052 static inline void
4053 who_perm_init(who_perm_t *who_perm, fs_perm_t *fsperm,
4054     zfs_deleg_who_type_t type, const char *name)
4055 {
4056         uu_avl_pool_t   *pool;
4057         pool = fsperm->fsp_set->fsps_deleg_perm_avl_pool;
4058 
4059         bzero(who_perm, sizeof (who_perm_t));
4060 
4061         if ((who_perm->who_deleg_perm_avl = uu_avl_create(pool, NULL,
4062             UU_DEFAULT)) == NULL)
4063                 nomem();
4064 
4065         who_perm->who_type = type;
4066         who_perm->who_name = name;
4067         who_perm->who_fsperm = fsperm;
4068 }
4069 
4070 static inline void
4071 who_perm_fini(who_perm_t *who_perm)
4072 {
4073         deleg_perm_node_t *node = uu_avl_first(who_perm->who_deleg_perm_avl);
4074 
4075         while (node != NULL) {
4076                 deleg_perm_node_t *next_node =
4077                     uu_avl_next(who_perm->who_deleg_perm_avl, node);
4078 
4079                 uu_avl_remove(who_perm->who_deleg_perm_avl, node);
4080                 free(node);
4081                 node = next_node;
4082         }
4083 
4084         uu_avl_destroy(who_perm->who_deleg_perm_avl);
4085 }
4086 
4087 static inline void
4088 fs_perm_init(fs_perm_t *fsperm, fs_perm_set_t *fspset, const char *fsname)
4089 {
4090         uu_avl_pool_t   *nset_pool = fspset->fsps_named_set_avl_pool;
4091         uu_avl_pool_t   *who_pool = fspset->fsps_who_perm_avl_pool;
4092 
4093         bzero(fsperm, sizeof (fs_perm_t));
4094 
4095         if ((fsperm->fsp_sc_avl = uu_avl_create(nset_pool, NULL, UU_DEFAULT))
4096             == NULL)
4097                 nomem();
4098 
4099         if ((fsperm->fsp_uge_avl = uu_avl_create(who_pool, NULL, UU_DEFAULT))
4100             == NULL)
4101                 nomem();
4102 
4103         fsperm->fsp_set = fspset;
4104         fsperm->fsp_name = fsname;
4105 }
4106 
4107 static inline void
4108 fs_perm_fini(fs_perm_t *fsperm)
4109 {
4110         who_perm_node_t *node = uu_avl_first(fsperm->fsp_sc_avl);
4111         while (node != NULL) {
4112                 who_perm_node_t *next_node = uu_avl_next(fsperm->fsp_sc_avl,
4113                     node);
4114                 who_perm_t *who_perm = &node->who_perm;
4115                 who_perm_fini(who_perm);
4116                 uu_avl_remove(fsperm->fsp_sc_avl, node);
4117                 free(node);
4118                 node = next_node;
4119         }
4120 
4121         node = uu_avl_first(fsperm->fsp_uge_avl);
4122         while (node != NULL) {
4123                 who_perm_node_t *next_node = uu_avl_next(fsperm->fsp_uge_avl,
4124                     node);
4125                 who_perm_t *who_perm = &node->who_perm;
4126                 who_perm_fini(who_perm);
4127                 uu_avl_remove(fsperm->fsp_uge_avl, node);
4128                 free(node);
4129                 node = next_node;
4130         }
4131 
4132         uu_avl_destroy(fsperm->fsp_sc_avl);
4133         uu_avl_destroy(fsperm->fsp_uge_avl);
4134 }
4135 
4136 static void inline
4137 set_deleg_perm_node(uu_avl_t *avl, deleg_perm_node_t *node,
4138     zfs_deleg_who_type_t who_type, const char *name, char locality)
4139 {
4140         uu_avl_index_t idx = 0;
4141 
4142         deleg_perm_node_t *found_node = NULL;
4143         deleg_perm_t    *deleg_perm = &node->dpn_perm;
4144 
4145         deleg_perm_init(deleg_perm, who_type, name);
4146 
4147         if ((found_node = uu_avl_find(avl, node, NULL, &idx))
4148             == NULL)
4149                 uu_avl_insert(avl, node, idx);
4150         else {
4151                 node = found_node;
4152                 deleg_perm = &node->dpn_perm;
4153         }
4154 
4155 
4156         switch (locality) {
4157         case ZFS_DELEG_LOCAL:
4158                 deleg_perm->dp_local = B_TRUE;
4159                 break;
4160         case ZFS_DELEG_DESCENDENT:
4161                 deleg_perm->dp_descend = B_TRUE;
4162                 break;
4163         case ZFS_DELEG_NA:
4164                 break;
4165         default:
4166                 assert(B_FALSE); /* invalid locality */
4167         }
4168 }
4169 
4170 static inline int
4171 parse_who_perm(who_perm_t *who_perm, nvlist_t *nvl, char locality)
4172 {
4173         nvpair_t *nvp = NULL;
4174         fs_perm_set_t *fspset = who_perm->who_fsperm->fsp_set;
4175         uu_avl_t *avl = who_perm->who_deleg_perm_avl;
4176         zfs_deleg_who_type_t who_type = who_perm->who_type;
4177 
4178         while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
4179                 const char *name = nvpair_name(nvp);
4180                 data_type_t type = nvpair_type(nvp);
4181                 uu_avl_pool_t *avl_pool = fspset->fsps_deleg_perm_avl_pool;
4182                 deleg_perm_node_t *node =
4183                     safe_malloc(sizeof (deleg_perm_node_t));
4184 
4185                 assert(type == DATA_TYPE_BOOLEAN);
4186 
4187                 uu_avl_node_init(node, &node->dpn_avl_node, avl_pool);
4188                 set_deleg_perm_node(avl, node, who_type, name, locality);
4189         }
4190 
4191         return (0);
4192 }
4193 
4194 static inline int
4195 parse_fs_perm(fs_perm_t *fsperm, nvlist_t *nvl)
4196 {
4197         nvpair_t *nvp = NULL;
4198         fs_perm_set_t *fspset = fsperm->fsp_set;
4199 
4200         while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
4201                 nvlist_t *nvl2 = NULL;
4202                 const char *name = nvpair_name(nvp);
4203                 uu_avl_t *avl = NULL;
4204                 uu_avl_pool_t *avl_pool;
4205                 zfs_deleg_who_type_t perm_type = name[0];
4206                 char perm_locality = name[1];
4207                 const char *perm_name = name + 3;
4208                 boolean_t is_set = B_TRUE;
4209                 who_perm_t *who_perm = NULL;
4210 
4211                 assert('$' == name[2]);
4212 
4213                 if (nvpair_value_nvlist(nvp, &nvl2) != 0)
4214                         return (-1);
4215 
4216                 switch (perm_type) {
4217                 case ZFS_DELEG_CREATE:
4218                 case ZFS_DELEG_CREATE_SETS:
4219                 case ZFS_DELEG_NAMED_SET:
4220                 case ZFS_DELEG_NAMED_SET_SETS:
4221                         avl_pool = fspset->fsps_named_set_avl_pool;
4222                         avl = fsperm->fsp_sc_avl;
4223                         break;
4224                 case ZFS_DELEG_USER:
4225                 case ZFS_DELEG_USER_SETS:
4226                 case ZFS_DELEG_GROUP:
4227                 case ZFS_DELEG_GROUP_SETS:
4228                 case ZFS_DELEG_EVERYONE:
4229                 case ZFS_DELEG_EVERYONE_SETS:
4230                         avl_pool = fspset->fsps_who_perm_avl_pool;
4231                         avl = fsperm->fsp_uge_avl;
4232                         break;
4233                 }
4234 
4235                 if (is_set) {
4236                         who_perm_node_t *found_node = NULL;
4237                         who_perm_node_t *node = safe_malloc(
4238                             sizeof (who_perm_node_t));
4239                         who_perm = &node->who_perm;
4240                         uu_avl_index_t idx = 0;
4241 
4242                         uu_avl_node_init(node, &node->who_avl_node, avl_pool);
4243                         who_perm_init(who_perm, fsperm, perm_type, perm_name);
4244 
4245                         if ((found_node = uu_avl_find(avl, node, NULL, &idx))
4246                             == NULL) {
4247                                 if (avl == fsperm->fsp_uge_avl) {
4248                                         uid_t rid = 0;
4249                                         struct passwd *p = NULL;
4250                                         struct group *g = NULL;
4251                                         const char *nice_name = NULL;
4252 
4253                                         switch (perm_type) {
4254                                         case ZFS_DELEG_USER_SETS:
4255                                         case ZFS_DELEG_USER:
4256                                                 rid = atoi(perm_name);
4257                                                 p = getpwuid(rid);
4258                                                 if (p)
4259                                                         nice_name = p->pw_name;
4260                                                 break;
4261                                         case ZFS_DELEG_GROUP_SETS:
4262                                         case ZFS_DELEG_GROUP:
4263                                                 rid = atoi(perm_name);
4264                                                 g = getgrgid(rid);
4265                                                 if (g)
4266                                                         nice_name = g->gr_name;
4267                                                 break;
4268                                         }
4269 
4270                                         if (nice_name != NULL)
4271                                                 (void) strlcpy(
4272                                                     node->who_perm.who_ug_name,
4273                                                     nice_name, 256);
4274                                 }
4275 
4276                                 uu_avl_insert(avl, node, idx);
4277                         } else {
4278                                 node = found_node;
4279                                 who_perm = &node->who_perm;
4280                         }
4281                 }
4282 
4283                 (void) parse_who_perm(who_perm, nvl2, perm_locality);
4284         }
4285 
4286         return (0);
4287 }
4288 
4289 static inline int
4290 parse_fs_perm_set(fs_perm_set_t *fspset, nvlist_t *nvl)
4291 {
4292         nvpair_t *nvp = NULL;
4293         uu_avl_index_t idx = 0;
4294 
4295         while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
4296                 nvlist_t *nvl2 = NULL;
4297                 const char *fsname = nvpair_name(nvp);
4298                 data_type_t type = nvpair_type(nvp);
4299                 fs_perm_t *fsperm = NULL;
4300                 fs_perm_node_t *node = safe_malloc(sizeof (fs_perm_node_t));
4301                 if (node == NULL)
4302                         nomem();
4303 
4304                 fsperm = &node->fspn_fsperm;
4305 
4306                 assert(DATA_TYPE_NVLIST == type);
4307 
4308                 uu_list_node_init(node, &node->fspn_list_node,
4309                     fspset->fsps_list_pool);
4310 
4311                 idx = uu_list_numnodes(fspset->fsps_list);
4312                 fs_perm_init(fsperm, fspset, fsname);
4313 
4314                 if (nvpair_value_nvlist(nvp, &nvl2) != 0)
4315                         return (-1);
4316 
4317                 (void) parse_fs_perm(fsperm, nvl2);
4318 
4319                 uu_list_insert(fspset->fsps_list, node, idx);
4320         }
4321 
4322         return (0);
4323 }
4324 
4325 static inline const char *
4326 deleg_perm_comment(zfs_deleg_note_t note)
4327 {
4328         const char *str = "";
4329 
4330         /* subcommands */
4331         switch (note) {
4332                 /* SUBCOMMANDS */
4333         case ZFS_DELEG_NOTE_ALLOW:
4334                 str = gettext("Must also have the permission that is being"
4335                     "\n\t\t\t\tallowed");
4336                 break;
4337         case ZFS_DELEG_NOTE_CLONE:
4338                 str = gettext("Must also have the 'create' ability and 'mount'"
4339                     "\n\t\t\t\tability in the origin file system");
4340                 break;
4341         case ZFS_DELEG_NOTE_CREATE:
4342                 str = gettext("Must also have the 'mount' ability");
4343                 break;
4344         case ZFS_DELEG_NOTE_DESTROY:
4345                 str = gettext("Must also have the 'mount' ability");
4346                 break;
4347         case ZFS_DELEG_NOTE_DIFF:
4348                 str = gettext("Allows lookup of paths within a dataset;"
4349                     "\n\t\t\t\tgiven an object number. Ordinary users need this"
4350                     "\n\t\t\t\tin order to use zfs diff");
4351                 break;
4352         case ZFS_DELEG_NOTE_HOLD:
4353                 str = gettext("Allows adding a user hold to a snapshot");
4354                 break;
4355         case ZFS_DELEG_NOTE_MOUNT:
4356                 str = gettext("Allows mount/umount of ZFS datasets");
4357                 break;
4358         case ZFS_DELEG_NOTE_PROMOTE:
4359                 str = gettext("Must also have the 'mount'\n\t\t\t\tand"
4360                     " 'promote' ability in the origin file system");
4361                 break;
4362         case ZFS_DELEG_NOTE_RECEIVE:
4363                 str = gettext("Must also have the 'mount' and 'create'"
4364                     " ability");
4365                 break;
4366         case ZFS_DELEG_NOTE_RELEASE:
4367                 str = gettext("Allows releasing a user hold which\n\t\t\t\t"
4368                     "might destroy the snapshot");
4369                 break;
4370         case ZFS_DELEG_NOTE_RENAME:
4371                 str = gettext("Must also have the 'mount' and 'create'"
4372                     "\n\t\t\t\tability in the new parent");
4373                 break;
4374         case ZFS_DELEG_NOTE_ROLLBACK:
4375                 str = gettext("");
4376                 break;
4377         case ZFS_DELEG_NOTE_SEND:
4378                 str = gettext("");
4379                 break;
4380         case ZFS_DELEG_NOTE_SHARE:
4381                 str = gettext("Allows sharing file systems over NFS or SMB"
4382                     "\n\t\t\t\tprotocols");
4383                 break;
4384         case ZFS_DELEG_NOTE_SNAPSHOT:
4385                 str = gettext("");
4386                 break;
4387 /*
4388  *      case ZFS_DELEG_NOTE_VSCAN:
4389  *              str = gettext("");
4390  *              break;
4391  */
4392                 /* OTHER */
4393         case ZFS_DELEG_NOTE_GROUPQUOTA:
4394                 str = gettext("Allows accessing any groupquota@... property");
4395                 break;
4396         case ZFS_DELEG_NOTE_GROUPUSED:
4397                 str = gettext("Allows reading any groupused@... property");
4398                 break;
4399         case ZFS_DELEG_NOTE_USERPROP:
4400                 str = gettext("Allows changing any user property");
4401                 break;
4402         case ZFS_DELEG_NOTE_USERQUOTA:
4403                 str = gettext("Allows accessing any userquota@... property");
4404                 break;
4405         case ZFS_DELEG_NOTE_USERUSED:
4406                 str = gettext("Allows reading any userused@... property");
4407                 break;
4408                 /* other */
4409         default:
4410                 str = "";
4411         }
4412 
4413         return (str);
4414 }
4415 
4416 struct allow_opts {
4417         boolean_t local;
4418         boolean_t descend;
4419         boolean_t user;
4420         boolean_t group;
4421         boolean_t everyone;
4422         boolean_t create;
4423         boolean_t set;
4424         boolean_t recursive; /* unallow only */
4425         boolean_t prt_usage;
4426 
4427         boolean_t prt_perms;
4428         char *who;
4429         char *perms;
4430         const char *dataset;
4431 };
4432 
4433 static inline int
4434 prop_cmp(const void *a, const void *b)
4435 {
4436         const char *str1 = *(const char **)a;
4437         const char *str2 = *(const char **)b;
4438         return (strcmp(str1, str2));
4439 }
4440 
4441 static void
4442 allow_usage(boolean_t un, boolean_t requested, const char *msg)
4443 {
4444         const char *opt_desc[] = {
4445                 "-h", gettext("show this help message and exit"),
4446                 "-l", gettext("set permission locally"),
4447                 "-d", gettext("set permission for descents"),
4448                 "-u", gettext("set permission for user"),
4449                 "-g", gettext("set permission for group"),
4450                 "-e", gettext("set permission for everyone"),
4451                 "-c", gettext("set create time permission"),
4452                 "-s", gettext("define permission set"),
4453                 /* unallow only */
4454                 "-r", gettext("remove permissions recursively"),
4455         };
4456         size_t unallow_size = sizeof (opt_desc) / sizeof (char *);
4457         size_t allow_size = unallow_size - 2;
4458         const char *props[ZFS_NUM_PROPS];
4459         int i;
4460         size_t count = 0;
4461         FILE *fp = requested ? stdout : stderr;
4462         zprop_desc_t *pdtbl = zfs_prop_get_table();
4463         const char *fmt = gettext("%-16s %-14s\t%s\n");
4464 
4465         (void) fprintf(fp, gettext("Usage: %s\n"), get_usage(un ? HELP_UNALLOW :
4466             HELP_ALLOW));
4467         (void) fprintf(fp, gettext("Options:\n"));
4468         for (int i = 0; i < (un ? unallow_size : allow_size); i++) {
4469                 const char *opt = opt_desc[i++];
4470                 const char *optdsc = opt_desc[i];
4471                 (void) fprintf(fp, gettext("  %-10s  %s\n"), opt, optdsc);
4472         }
4473 
4474         (void) fprintf(fp, gettext("\nThe following permissions are "
4475             "supported:\n\n"));
4476         (void) fprintf(fp, fmt, gettext("NAME"), gettext("TYPE"),
4477             gettext("NOTES"));
4478         for (i = 0; i < ZFS_NUM_DELEG_NOTES; i++) {
4479                 const char *perm_name = zfs_deleg_perm_tbl[i].z_perm;
4480                 zfs_deleg_note_t perm_note = zfs_deleg_perm_tbl[i].z_note;
4481                 const char *perm_type = deleg_perm_type(perm_note);
4482                 const char *perm_comment = deleg_perm_comment(perm_note);
4483                 (void) fprintf(fp, fmt, perm_name, perm_type, perm_comment);
4484         }
4485 
4486         for (i = 0; i < ZFS_NUM_PROPS; i++) {
4487                 zprop_desc_t *pd = &pdtbl[i];
4488                 if (pd->pd_visible != B_TRUE)
4489                         continue;
4490 
4491                 if (pd->pd_attr == PROP_READONLY)
4492                         continue;
4493 
4494                 props[count++] = pd->pd_name;
4495         }
4496         props[count] = NULL;
4497 
4498         qsort(props, count, sizeof (char *), prop_cmp);
4499 
4500         for (i = 0; i < count; i++)
4501                 (void) fprintf(fp, fmt, props[i], gettext("property"), "");
4502 
4503         if (msg != NULL)
4504                 (void) fprintf(fp, gettext("\nzfs: error: %s"), msg);
4505 
4506         exit(requested ? 0 : 2);
4507 }
4508 
4509 static inline const char *
4510 munge_args(int argc, char **argv, boolean_t un, size_t expected_argc,
4511     char **permsp)
4512 {
4513         if (un && argc == expected_argc - 1)
4514                 *permsp = NULL;
4515         else if (argc == expected_argc)
4516                 *permsp = argv[argc - 2];
4517         else
4518                 allow_usage(un, B_FALSE,
4519                     gettext("wrong number of parameters\n"));
4520 
4521         return (argv[argc - 1]);
4522 }
4523 
4524 static void
4525 parse_allow_args(int argc, char **argv, boolean_t un, struct allow_opts *opts)
4526 {
4527         int uge_sum = opts->user + opts->group + opts->everyone;
4528         int csuge_sum = opts->create + opts->set + uge_sum;
4529         int ldcsuge_sum = csuge_sum + opts->local + opts->descend;
4530         int all_sum = un ? ldcsuge_sum + opts->recursive : ldcsuge_sum;
4531 
4532         if (uge_sum > 1)
4533                 allow_usage(un, B_FALSE,
4534                     gettext("-u, -g, and -e are mutually exclusive\n"));
4535 
4536         if (opts->prt_usage)
4537                 if (argc == 0 && all_sum == 0)
4538                         allow_usage(un, B_TRUE, NULL);
4539                 else
4540                         usage(B_FALSE);
4541 
4542         if (opts->set) {
4543                 if (csuge_sum > 1)
4544                         allow_usage(un, B_FALSE,
4545                             gettext("invalid options combined with -s\n"));
4546 
4547                 opts->dataset = munge_args(argc, argv, un, 3, &opts->perms);
4548                 if (argv[0][0] != '@')
4549                         allow_usage(un, B_FALSE,
4550                             gettext("invalid set name: missing '@' prefix\n"));
4551                 opts->who = argv[0];
4552         } else if (opts->create) {
4553                 if (ldcsuge_sum > 1)
4554                         allow_usage(un, B_FALSE,
4555                             gettext("invalid options combined with -c\n"));
4556                 opts->dataset = munge_args(argc, argv, un, 2, &opts->perms);
4557         } else if (opts->everyone) {
4558                 if (csuge_sum > 1)
4559                         allow_usage(un, B_FALSE,
4560                             gettext("invalid options combined with -e\n"));
4561                 opts->dataset = munge_args(argc, argv, un, 2, &opts->perms);
4562         } else if (uge_sum == 0 && argc > 0 && strcmp(argv[0], "everyone")
4563             == 0) {
4564                 opts->everyone = B_TRUE;
4565                 argc--;
4566                 argv++;
4567                 opts->dataset = munge_args(argc, argv, un, 2, &opts->perms);
4568         } else if (argc == 1 && !un) {
4569                 opts->prt_perms = B_TRUE;
4570                 opts->dataset = argv[argc-1];
4571         } else {
4572                 opts->dataset = munge_args(argc, argv, un, 3, &opts->perms);
4573                 opts->who = argv[0];
4574         }
4575 
4576         if (!opts->local && !opts->descend) {
4577                 opts->local = B_TRUE;
4578                 opts->descend = B_TRUE;
4579         }
4580 }
4581 
4582 static void
4583 store_allow_perm(zfs_deleg_who_type_t type, boolean_t local, boolean_t descend,
4584     const char *who, char *perms, nvlist_t *top_nvl)
4585 {
4586         int i;
4587         char ld[2] = { '\0', '\0' };
4588         char who_buf[ZFS_MAXNAMELEN+32];
4589         char base_type;
4590         char set_type;
4591         nvlist_t *base_nvl = NULL;
4592         nvlist_t *set_nvl = NULL;
4593         nvlist_t *nvl;
4594 
4595         if (nvlist_alloc(&base_nvl, NV_UNIQUE_NAME, 0) != 0)
4596                 nomem();
4597         if (nvlist_alloc(&set_nvl, NV_UNIQUE_NAME, 0) !=  0)
4598                 nomem();
4599 
4600         switch (type) {
4601         case ZFS_DELEG_NAMED_SET_SETS:
4602         case ZFS_DELEG_NAMED_SET:
4603                 set_type = ZFS_DELEG_NAMED_SET_SETS;
4604                 base_type = ZFS_DELEG_NAMED_SET;
4605                 ld[0] = ZFS_DELEG_NA;
4606                 break;
4607         case ZFS_DELEG_CREATE_SETS:
4608         case ZFS_DELEG_CREATE:
4609                 set_type = ZFS_DELEG_CREATE_SETS;
4610                 base_type = ZFS_DELEG_CREATE;
4611                 ld[0] = ZFS_DELEG_NA;
4612                 break;
4613         case ZFS_DELEG_USER_SETS:
4614         case ZFS_DELEG_USER:
4615                 set_type = ZFS_DELEG_USER_SETS;
4616                 base_type = ZFS_DELEG_USER;
4617                 if (local)
4618                         ld[0] = ZFS_DELEG_LOCAL;
4619                 if (descend)
4620                         ld[1] = ZFS_DELEG_DESCENDENT;
4621                 break;
4622         case ZFS_DELEG_GROUP_SETS:
4623         case ZFS_DELEG_GROUP:
4624                 set_type = ZFS_DELEG_GROUP_SETS;
4625                 base_type = ZFS_DELEG_GROUP;
4626                 if (local)
4627                         ld[0] = ZFS_DELEG_LOCAL;
4628                 if (descend)
4629                         ld[1] = ZFS_DELEG_DESCENDENT;
4630                 break;
4631         case ZFS_DELEG_EVERYONE_SETS:
4632         case ZFS_DELEG_EVERYONE:
4633                 set_type = ZFS_DELEG_EVERYONE_SETS;
4634                 base_type = ZFS_DELEG_EVERYONE;
4635                 if (local)
4636                         ld[0] = ZFS_DELEG_LOCAL;
4637                 if (descend)
4638                         ld[1] = ZFS_DELEG_DESCENDENT;
4639         }
4640 
4641         if (perms != NULL) {
4642                 char *curr = perms;
4643                 char *end = curr + strlen(perms);
4644 
4645                 while (curr < end) {
4646                         char *delim = strchr(curr, ',');
4647                         if (delim == NULL)
4648                                 delim = end;
4649                         else
4650                                 *delim = '\0';
4651 
4652                         if (curr[0] == '@')
4653                                 nvl = set_nvl;
4654                         else
4655                                 nvl = base_nvl;
4656 
4657                         (void) nvlist_add_boolean(nvl, curr);
4658                         if (delim != end)
4659                                 *delim = ',';
4660                         curr = delim + 1;
4661                 }
4662 
4663                 for (i = 0; i < 2; i++) {
4664                         char locality = ld[i];
4665                         if (locality == 0)
4666                                 continue;
4667 
4668                         if (!nvlist_empty(base_nvl)) {
4669                                 if (who != NULL)
4670                                         (void) snprintf(who_buf,
4671                                             sizeof (who_buf), "%c%c$%s",
4672                                             base_type, locality, who);
4673                                 else
4674                                         (void) snprintf(who_buf,
4675                                             sizeof (who_buf), "%c%c$",
4676                                             base_type, locality);
4677 
4678                                 (void) nvlist_add_nvlist(top_nvl, who_buf,
4679                                     base_nvl);
4680                         }
4681 
4682 
4683                         if (!nvlist_empty(set_nvl)) {
4684                                 if (who != NULL)
4685                                         (void) snprintf(who_buf,
4686                                             sizeof (who_buf), "%c%c$%s",
4687                                             set_type, locality, who);
4688                                 else
4689                                         (void) snprintf(who_buf,
4690                                             sizeof (who_buf), "%c%c$",
4691                                             set_type, locality);
4692 
4693                                 (void) nvlist_add_nvlist(top_nvl, who_buf,
4694                                     set_nvl);
4695                         }
4696                 }
4697         } else {
4698                 for (i = 0; i < 2; i++) {
4699                         char locality = ld[i];
4700                         if (locality == 0)
4701                                 continue;
4702 
4703                         if (who != NULL)
4704                                 (void) snprintf(who_buf, sizeof (who_buf),
4705                                     "%c%c$%s", base_type, locality, who);
4706                         else
4707                                 (void) snprintf(who_buf, sizeof (who_buf),
4708                                     "%c%c$", base_type, locality);
4709                         (void) nvlist_add_boolean(top_nvl, who_buf);
4710 
4711                         if (who != NULL)
4712                                 (void) snprintf(who_buf, sizeof (who_buf),
4713                                     "%c%c$%s", set_type, locality, who);
4714                         else
4715                                 (void) snprintf(who_buf, sizeof (who_buf),
4716                                     "%c%c$", set_type, locality);
4717                         (void) nvlist_add_boolean(top_nvl, who_buf);
4718                 }
4719         }
4720 }
4721 
4722 static int
4723 construct_fsacl_list(boolean_t un, struct allow_opts *opts, nvlist_t **nvlp)
4724 {
4725         if (nvlist_alloc(nvlp, NV_UNIQUE_NAME, 0) != 0)
4726                 nomem();
4727 
4728         if (opts->set) {
4729                 store_allow_perm(ZFS_DELEG_NAMED_SET, opts->local,
4730                     opts->descend, opts->who, opts->perms, *nvlp);
4731         } else if (opts->create) {
4732                 store_allow_perm(ZFS_DELEG_CREATE, opts->local,
4733                     opts->descend, NULL, opts->perms, *nvlp);
4734         } else if (opts->everyone) {
4735                 store_allow_perm(ZFS_DELEG_EVERYONE, opts->local,
4736                     opts->descend, NULL, opts->perms, *nvlp);
4737         } else {
4738                 char *curr = opts->who;
4739                 char *end = curr + strlen(curr);
4740 
4741                 while (curr < end) {
4742                         const char *who;
4743                         zfs_deleg_who_type_t who_type;
4744                         char *endch;
4745                         char *delim = strchr(curr, ',');
4746                         char errbuf[256];
4747                         char id[64];
4748                         struct passwd *p = NULL;
4749                         struct group *g = NULL;
4750 
4751                         uid_t rid;
4752                         if (delim == NULL)
4753                                 delim = end;
4754                         else
4755                                 *delim = '\0';
4756 
4757                         rid = (uid_t)strtol(curr, &endch, 0);
4758                         if (opts->user) {
4759                                 who_type = ZFS_DELEG_USER;
4760                                 if (*endch != '\0')
4761                                         p = getpwnam(curr);
4762                                 else
4763                                         p = getpwuid(rid);
4764 
4765                                 if (p != NULL)
4766                                         rid = p->pw_uid;
4767                                 else {
4768                                         (void) snprintf(errbuf, 256, gettext(
4769                                             "invalid user %s"), curr);
4770                                         allow_usage(un, B_TRUE, errbuf);
4771                                 }
4772                         } else if (opts->group) {
4773                                 who_type = ZFS_DELEG_GROUP;
4774                                 if (*endch != '\0')
4775                                         g = getgrnam(curr);
4776                                 else
4777                                         g = getgrgid(rid);
4778 
4779                                 if (g != NULL)
4780                                         rid = g->gr_gid;
4781                                 else {
4782                                         (void) snprintf(errbuf, 256, gettext(
4783                                             "invalid group %s"),  curr);
4784                                         allow_usage(un, B_TRUE, errbuf);
4785                                 }
4786                         } else {
4787                                 if (*endch != '\0') {
4788                                         p = getpwnam(curr);
4789                                 } else {
4790                                         p = getpwuid(rid);
4791                                 }
4792 
4793                                 if (p == NULL)
4794                                         if (*endch != '\0') {
4795                                                 g = getgrnam(curr);
4796                                         } else {
4797                                                 g = getgrgid(rid);
4798                                         }
4799 
4800                                 if (p != NULL) {
4801                                         who_type = ZFS_DELEG_USER;
4802                                         rid = p->pw_uid;
4803                                 } else if (g != NULL) {
4804                                         who_type = ZFS_DELEG_GROUP;
4805                                         rid = g->gr_gid;
4806                                 } else {
4807                                         (void) snprintf(errbuf, 256, gettext(
4808                                             "invalid user/group %s"), curr);
4809                                         allow_usage(un, B_TRUE, errbuf);
4810                                 }
4811                         }
4812 
4813                         (void) sprintf(id, "%u", rid);
4814                         who = id;
4815 
4816                         store_allow_perm(who_type, opts->local,
4817                             opts->descend, who, opts->perms, *nvlp);
4818                         curr = delim + 1;
4819                 }
4820         }
4821 
4822         return (0);
4823 }
4824 
4825 static void
4826 print_set_creat_perms(uu_avl_t *who_avl)
4827 {
4828         const char *sc_title[] = {
4829                 gettext("Permission sets:\n"),
4830                 gettext("Create time permissions:\n"),
4831                 NULL
4832         };
4833         const char **title_ptr = sc_title;
4834         who_perm_node_t *who_node = NULL;
4835         int prev_weight = -1;
4836 
4837         for (who_node = uu_avl_first(who_avl); who_node != NULL;
4838             who_node = uu_avl_next(who_avl, who_node)) {
4839                 uu_avl_t *avl = who_node->who_perm.who_deleg_perm_avl;
4840                 zfs_deleg_who_type_t who_type = who_node->who_perm.who_type;
4841                 const char *who_name = who_node->who_perm.who_name;
4842                 int weight = who_type2weight(who_type);
4843                 boolean_t first = B_TRUE;
4844                 deleg_perm_node_t *deleg_node;
4845 
4846                 if (prev_weight != weight) {
4847                         (void) printf(*title_ptr++);
4848                         prev_weight = weight;
4849                 }
4850 
4851                 if (who_name == NULL || strnlen(who_name, 1) == 0)
4852                         (void) printf("\t");
4853                 else
4854                         (void) printf("\t%s ", who_name);
4855 
4856                 for (deleg_node = uu_avl_first(avl); deleg_node != NULL;
4857                     deleg_node = uu_avl_next(avl, deleg_node)) {
4858                         if (first) {
4859                                 (void) printf("%s",
4860                                     deleg_node->dpn_perm.dp_name);
4861                                 first = B_FALSE;
4862                         } else
4863                                 (void) printf(",%s",
4864                                     deleg_node->dpn_perm.dp_name);
4865                 }
4866 
4867                 (void) printf("\n");
4868         }
4869 }
4870 
4871 static void inline
4872 print_uge_deleg_perms(uu_avl_t *who_avl, boolean_t local, boolean_t descend,
4873     const char *title)
4874 {
4875         who_perm_node_t *who_node = NULL;
4876         boolean_t prt_title = B_TRUE;
4877         uu_avl_walk_t *walk;
4878 
4879         if ((walk = uu_avl_walk_start(who_avl, UU_WALK_ROBUST)) == NULL)
4880                 nomem();
4881 
4882         while ((who_node = uu_avl_walk_next(walk)) != NULL) {
4883                 const char *who_name = who_node->who_perm.who_name;
4884                 const char *nice_who_name = who_node->who_perm.who_ug_name;
4885                 uu_avl_t *avl = who_node->who_perm.who_deleg_perm_avl;
4886                 zfs_deleg_who_type_t who_type = who_node->who_perm.who_type;
4887                 char delim = ' ';
4888                 deleg_perm_node_t *deleg_node;
4889                 boolean_t prt_who = B_TRUE;
4890 
4891                 for (deleg_node = uu_avl_first(avl);
4892                     deleg_node != NULL;
4893                     deleg_node = uu_avl_next(avl, deleg_node)) {
4894                         if (local != deleg_node->dpn_perm.dp_local ||
4895                             descend != deleg_node->dpn_perm.dp_descend)
4896                                 continue;
4897 
4898                         if (prt_who) {
4899                                 const char *who = NULL;
4900                                 if (prt_title) {
4901                                         prt_title = B_FALSE;
4902                                         (void) printf(title);
4903                                 }
4904 
4905                                 switch (who_type) {
4906                                 case ZFS_DELEG_USER_SETS:
4907                                 case ZFS_DELEG_USER:
4908                                         who = gettext("user");
4909                                         if (nice_who_name)
4910                                                 who_name  = nice_who_name;
4911                                         break;
4912                                 case ZFS_DELEG_GROUP_SETS:
4913                                 case ZFS_DELEG_GROUP:
4914                                         who = gettext("group");
4915                                         if (nice_who_name)
4916                                                 who_name  = nice_who_name;
4917                                         break;
4918                                 case ZFS_DELEG_EVERYONE_SETS:
4919                                 case ZFS_DELEG_EVERYONE:
4920                                         who = gettext("everyone");
4921                                         who_name = NULL;
4922                                 }
4923 
4924                                 prt_who = B_FALSE;
4925                                 if (who_name == NULL)
4926                                         (void) printf("\t%s", who);
4927                                 else
4928                                         (void) printf("\t%s %s", who, who_name);
4929                         }
4930 
4931                         (void) printf("%c%s", delim,
4932                             deleg_node->dpn_perm.dp_name);
4933                         delim = ',';
4934                 }
4935 
4936                 if (!prt_who)
4937                         (void) printf("\n");
4938         }
4939 
4940         uu_avl_walk_end(walk);
4941 }
4942 
4943 static void
4944 print_fs_perms(fs_perm_set_t *fspset)
4945 {
4946         fs_perm_node_t *node = NULL;
4947         char buf[ZFS_MAXNAMELEN+32];
4948         const char *dsname = buf;
4949 
4950         for (node = uu_list_first(fspset->fsps_list); node != NULL;
4951             node = uu_list_next(fspset->fsps_list, node)) {
4952                 uu_avl_t *sc_avl = node->fspn_fsperm.fsp_sc_avl;
4953                 uu_avl_t *uge_avl = node->fspn_fsperm.fsp_uge_avl;
4954                 int left = 0;
4955 
4956                 (void) snprintf(buf, ZFS_MAXNAMELEN+32,
4957                     gettext("---- Permissions on %s "),
4958                     node->fspn_fsperm.fsp_name);
4959                 (void) printf(dsname);
4960                 left = 70 - strlen(buf);
4961                 while (left-- > 0)
4962                         (void) printf("-");
4963                 (void) printf("\n");
4964 
4965                 print_set_creat_perms(sc_avl);
4966                 print_uge_deleg_perms(uge_avl, B_TRUE, B_FALSE,
4967                     gettext("Local permissions:\n"));
4968                 print_uge_deleg_perms(uge_avl, B_FALSE, B_TRUE,
4969                     gettext("Descendent permissions:\n"));
4970                 print_uge_deleg_perms(uge_avl, B_TRUE, B_TRUE,
4971                     gettext("Local+Descendent permissions:\n"));
4972         }
4973 }
4974 
4975 static fs_perm_set_t fs_perm_set = { NULL, NULL, NULL, NULL };
4976 
4977 struct deleg_perms {
4978         boolean_t un;
4979         nvlist_t *nvl;
4980 };
4981 
4982 static int
4983 set_deleg_perms(zfs_handle_t *zhp, void *data)
4984 {
4985         struct deleg_perms *perms = (struct deleg_perms *)data;
4986         zfs_type_t zfs_type = zfs_get_type(zhp);
4987 
4988         if (zfs_type != ZFS_TYPE_FILESYSTEM && zfs_type != ZFS_TYPE_VOLUME)
4989                 return (0);
4990 
4991         return (zfs_set_fsacl(zhp, perms->un, perms->nvl));
4992 }
4993 
4994 static int
4995 zfs_do_allow_unallow_impl(int argc, char **argv, boolean_t un)
4996 {
4997         zfs_handle_t *zhp;
4998         nvlist_t *perm_nvl = NULL;
4999         nvlist_t *update_perm_nvl = NULL;
5000         int error = 1;
5001         int c;
5002         struct allow_opts opts = { 0 };
5003 
5004         const char *optstr = un ? "ldugecsrh" : "ldugecsh";
5005 
5006         /* check opts */
5007         while ((c = getopt(argc, argv, optstr)) != -1) {
5008                 switch (c) {
5009                 case 'l':
5010                         opts.local = B_TRUE;
5011                         break;
5012                 case 'd':
5013                         opts.descend = B_TRUE;
5014                         break;
5015                 case 'u':
5016                         opts.user = B_TRUE;
5017                         break;
5018                 case 'g':
5019                         opts.group = B_TRUE;
5020                         break;
5021                 case 'e':
5022                         opts.everyone = B_TRUE;
5023                         break;
5024                 case 's':
5025                         opts.set = B_TRUE;
5026                         break;
5027                 case 'c':
5028                         opts.create = B_TRUE;
5029                         break;
5030                 case 'r':
5031                         opts.recursive = B_TRUE;
5032                         break;
5033                 case ':':
5034                         (void) fprintf(stderr, gettext("missing argument for "
5035                             "'%c' option\n"), optopt);
5036                         usage(B_FALSE);
5037                         break;
5038                 case 'h':
5039                         opts.prt_usage = B_TRUE;
5040                         break;
5041                 case '?':
5042                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
5043                             optopt);
5044                         usage(B_FALSE);
5045                 }
5046         }
5047 
5048         argc -= optind;
5049         argv += optind;
5050 
5051         /* check arguments */
5052         parse_allow_args(argc, argv, un, &opts);
5053 
5054         /* try to open the dataset */
5055         if ((zhp = zfs_open(g_zfs, opts.dataset, ZFS_TYPE_FILESYSTEM |
5056             ZFS_TYPE_VOLUME)) == NULL) {
5057                 (void) fprintf(stderr, "Failed to open dataset: %s\n",
5058                     opts.dataset);
5059                 return (-1);
5060         }
5061 
5062         if (zfs_get_fsacl(zhp, &perm_nvl) != 0)
5063                 goto cleanup2;
5064 
5065         fs_perm_set_init(&fs_perm_set);
5066         if (parse_fs_perm_set(&fs_perm_set, perm_nvl) != 0) {
5067                 (void) fprintf(stderr, "Failed to parse fsacl permissions\n");
5068                 goto cleanup1;
5069         }
5070 
5071         if (opts.prt_perms)
5072                 print_fs_perms(&fs_perm_set);
5073         else {
5074                 (void) construct_fsacl_list(un, &opts, &update_perm_nvl);
5075                 if (zfs_set_fsacl(zhp, un, update_perm_nvl) != 0)
5076                         goto cleanup0;
5077 
5078                 if (un && opts.recursive) {
5079                         struct deleg_perms data = { un, update_perm_nvl };
5080                         if (zfs_iter_filesystems(zhp, set_deleg_perms,
5081                             &data) != 0)
5082                                 goto cleanup0;
5083                 }
5084         }
5085 
5086         error = 0;
5087 
5088 cleanup0:
5089         nvlist_free(perm_nvl);
5090         if (update_perm_nvl != NULL)
5091                 nvlist_free(update_perm_nvl);
5092 cleanup1:
5093         fs_perm_set_fini(&fs_perm_set);
5094 cleanup2:
5095         zfs_close(zhp);
5096 
5097         return (error);
5098 }
5099 
5100 static int
5101 zfs_do_allow(int argc, char **argv)
5102 {
5103         return (zfs_do_allow_unallow_impl(argc, argv, B_FALSE));
5104 }
5105 
5106 static int
5107 zfs_do_unallow(int argc, char **argv)
5108 {
5109         return (zfs_do_allow_unallow_impl(argc, argv, B_TRUE));
5110 }
5111 
5112 static int
5113 zfs_do_hold_rele_impl(int argc, char **argv, boolean_t holding)
5114 {
5115         int errors = 0;
5116         int i;
5117         const char *tag;
5118         boolean_t recursive = B_FALSE;
5119         const char *opts = holding ? "rt" : "r";
5120         int c;
5121 
5122         /* check options */
5123         while ((c = getopt(argc, argv, opts)) != -1) {
5124                 switch (c) {
5125                 case 'r':
5126                         recursive = B_TRUE;
5127                         break;
5128                 case '?':
5129                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
5130                             optopt);
5131                         usage(B_FALSE);
5132                 }
5133         }
5134 
5135         argc -= optind;
5136         argv += optind;
5137 
5138         /* check number of arguments */
5139         if (argc < 2)
5140                 usage(B_FALSE);
5141 
5142         tag = argv[0];
5143         --argc;
5144         ++argv;
5145 
5146         if (holding && tag[0] == '.') {
5147                 /* tags starting with '.' are reserved for libzfs */
5148                 (void) fprintf(stderr, gettext("tag may not start with '.'\n"));
5149                 usage(B_FALSE);
5150         }
5151 
5152         for (i = 0; i < argc; ++i) {
5153                 zfs_handle_t *zhp;
5154                 char parent[ZFS_MAXNAMELEN];
5155                 const char *delim;
5156                 char *path = argv[i];
5157 
5158                 delim = strchr(path, '@');
5159                 if (delim == NULL) {
5160                         (void) fprintf(stderr,
5161                             gettext("'%s' is not a snapshot\n"), path);
5162                         ++errors;
5163                         continue;
5164                 }
5165                 (void) strncpy(parent, path, delim - path);
5166                 parent[delim - path] = '\0';
5167 
5168                 zhp = zfs_open(g_zfs, parent,
5169                     ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
5170                 if (zhp == NULL) {
5171                         ++errors;
5172                         continue;
5173                 }
5174                 if (holding) {
5175                         if (zfs_hold(zhp, delim+1, tag, recursive, -1) != 0)
5176                                 ++errors;
5177                 } else {
5178                         if (zfs_release(zhp, delim+1, tag, recursive) != 0)
5179                                 ++errors;
5180                 }
5181                 zfs_close(zhp);
5182         }
5183 
5184         return (errors != 0);
5185 }
5186 
5187 /*
5188  * zfs hold [-r] [-t] <tag> <snap> ...
5189  *
5190  *      -r      Recursively hold
5191  *
5192  * Apply a user-hold with the given tag to the list of snapshots.
5193  */
5194 static int
5195 zfs_do_hold(int argc, char **argv)
5196 {
5197         return (zfs_do_hold_rele_impl(argc, argv, B_TRUE));
5198 }
5199 
5200 /*
5201  * zfs release [-r] <tag> <snap> ...
5202  *
5203  *      -r      Recursively release
5204  *
5205  * Release a user-hold with the given tag from the list of snapshots.
5206  */
5207 static int
5208 zfs_do_release(int argc, char **argv)
5209 {
5210         return (zfs_do_hold_rele_impl(argc, argv, B_FALSE));
5211 }
5212 
5213 typedef struct holds_cbdata {
5214         boolean_t       cb_recursive;
5215         const char      *cb_snapname;
5216         nvlist_t        **cb_nvlp;
5217         size_t          cb_max_namelen;
5218         size_t          cb_max_taglen;
5219 } holds_cbdata_t;
5220 
5221 #define STRFTIME_FMT_STR "%a %b %e %k:%M %Y"
5222 #define DATETIME_BUF_LEN (32)
5223 /*
5224  *
5225  */
5226 static void
5227 print_holds(boolean_t scripted, size_t nwidth, size_t tagwidth, nvlist_t *nvl)
5228 {
5229         int i;
5230         nvpair_t *nvp = NULL;
5231         char *hdr_cols[] = { "NAME", "TAG", "TIMESTAMP" };
5232         const char *col;
5233 
5234         if (!scripted) {
5235                 for (i = 0; i < 3; i++) {
5236                         col = gettext(hdr_cols[i]);
5237                         if (i < 2)
5238                                 (void) printf("%-*s  ", i ? tagwidth : nwidth,
5239                                     col);
5240                         else
5241                                 (void) printf("%s\n", col);
5242                 }
5243         }
5244 
5245         while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
5246                 char *zname = nvpair_name(nvp);
5247                 nvlist_t *nvl2;
5248                 nvpair_t *nvp2 = NULL;
5249                 (void) nvpair_value_nvlist(nvp, &nvl2);
5250                 while ((nvp2 = nvlist_next_nvpair(nvl2, nvp2)) != NULL) {
5251                         char tsbuf[DATETIME_BUF_LEN];
5252                         char *tagname = nvpair_name(nvp2);
5253                         uint64_t val = 0;
5254                         time_t time;
5255                         struct tm t;
5256                         char sep = scripted ? '\t' : ' ';
5257                         size_t sepnum = scripted ? 1 : 2;
5258 
5259                         (void) nvpair_value_uint64(nvp2, &val);
5260                         time = (time_t)val;
5261                         (void) localtime_r(&time, &t);
5262                         (void) strftime(tsbuf, DATETIME_BUF_LEN,
5263                             gettext(STRFTIME_FMT_STR), &t);
5264 
5265                         (void) printf("%-*s%*c%-*s%*c%s\n", nwidth, zname,
5266                             sepnum, sep, tagwidth, tagname, sepnum, sep, tsbuf);
5267                 }
5268         }
5269 }
5270 
5271 /*
5272  * Generic callback function to list a dataset or snapshot.
5273  */
5274 static int
5275 holds_callback(zfs_handle_t *zhp, void *data)
5276 {
5277         holds_cbdata_t *cbp = data;
5278         nvlist_t *top_nvl = *cbp->cb_nvlp;
5279         nvlist_t *nvl = NULL;
5280         nvpair_t *nvp = NULL;
5281         const char *zname = zfs_get_name(zhp);
5282         size_t znamelen = strnlen(zname, ZFS_MAXNAMELEN);
5283 
5284         if (cbp->cb_recursive) {
5285                 const char *snapname;
5286                 char *delim  = strchr(zname, '@');
5287                 if (delim == NULL)
5288                         return (0);
5289 
5290                 snapname = delim + 1;
5291                 if (strcmp(cbp->cb_snapname, snapname))
5292                         return (0);
5293         }
5294 
5295         if (zfs_get_holds(zhp, &nvl) != 0)
5296                 return (-1);
5297 
5298         if (znamelen > cbp->cb_max_namelen)
5299                 cbp->cb_max_namelen  = znamelen;
5300 
5301         while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
5302                 const char *tag = nvpair_name(nvp);
5303                 size_t taglen = strnlen(tag, MAXNAMELEN);
5304                 if (taglen > cbp->cb_max_taglen)
5305                         cbp->cb_max_taglen  = taglen;
5306         }
5307 
5308         return (nvlist_add_nvlist(top_nvl, zname, nvl));
5309 }
5310 
5311 /*
5312  * zfs holds [-r] <snap> ...
5313  *
5314  *      -r      Recursively hold
5315  */
5316 static int
5317 zfs_do_holds(int argc, char **argv)
5318 {
5319         int errors = 0;
5320         int c;
5321         int i;
5322         boolean_t scripted = B_FALSE;
5323         boolean_t recursive = B_FALSE;
5324         const char *opts = "rH";
5325         nvlist_t *nvl;
5326 
5327         int types = ZFS_TYPE_SNAPSHOT;
5328         holds_cbdata_t cb = { 0 };
5329 
5330         int limit = 0;
5331         int ret = 0;
5332         int flags = 0;
5333 
5334         /* check options */
5335         while ((c = getopt(argc, argv, opts)) != -1) {
5336                 switch (c) {
5337                 case 'r':
5338                         recursive = B_TRUE;
5339                         break;
5340                 case 'H':
5341                         scripted = B_TRUE;
5342                         break;
5343                 case '?':
5344                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
5345                             optopt);
5346                         usage(B_FALSE);
5347                 }
5348         }
5349 
5350         if (recursive) {
5351                 types |= ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME;
5352                 flags |= ZFS_ITER_RECURSE;
5353         }
5354 
5355         argc -= optind;
5356         argv += optind;
5357 
5358         /* check number of arguments */
5359         if (argc < 1)
5360                 usage(B_FALSE);
5361 
5362         if (nvlist_alloc(&nvl, NV_UNIQUE_NAME, 0) != 0)
5363                 nomem();
5364 
5365         for (i = 0; i < argc; ++i) {
5366                 char *snapshot = argv[i];
5367                 const char *delim;
5368                 const char *snapname;
5369 
5370                 delim = strchr(snapshot, '@');
5371                 if (delim == NULL) {
5372                         (void) fprintf(stderr,
5373                             gettext("'%s' is not a snapshot\n"), snapshot);
5374                         ++errors;
5375                         continue;
5376                 }
5377                 snapname = delim + 1;
5378                 if (recursive)
5379                         snapshot[delim - snapshot] = '\0';
5380 
5381                 cb.cb_recursive = recursive;
5382                 cb.cb_snapname = snapname;
5383                 cb.cb_nvlp = &nvl;
5384 
5385                 /*
5386                  *  1. collect holds data, set format options
5387                  */
5388                 ret = zfs_for_each(argc, argv, flags, types, NULL, NULL, limit,
5389                     holds_callback, &cb);
5390                 if (ret != 0)
5391                         ++errors;
5392         }
5393 
5394         /*
5395          *  2. print holds data
5396          */
5397         print_holds(scripted, cb.cb_max_namelen, cb.cb_max_taglen, nvl);
5398 
5399         if (nvlist_empty(nvl))
5400                 (void) printf(gettext("no datasets available\n"));
5401 
5402         nvlist_free(nvl);
5403 
5404         return (0 != errors);
5405 }
5406 
5407 #define CHECK_SPINNER 30
5408 #define SPINNER_TIME 3          /* seconds */
5409 #define MOUNT_TIME 5            /* seconds */
5410 
5411 static int
5412 get_one_dataset(zfs_handle_t *zhp, void *data)
5413 {
5414         static char *spin[] = { "-", "\\", "|", "/" };
5415         static int spinval = 0;
5416         static int spincheck = 0;
5417         static time_t last_spin_time = (time_t)0;
5418         get_all_cb_t *cbp = data;
5419         zfs_type_t type = zfs_get_type(zhp);
5420 
5421         if (cbp->cb_verbose) {
5422                 if (--spincheck < 0) {
5423                         time_t now = time(NULL);
5424                         if (last_spin_time + SPINNER_TIME < now) {
5425                                 update_progress(spin[spinval++ % 4]);
5426                                 last_spin_time = now;
5427                         }
5428                         spincheck = CHECK_SPINNER;
5429                 }
5430         }
5431 
5432         /*
5433          * Interate over any nested datasets.
5434          */
5435         if (zfs_iter_filesystems(zhp, get_one_dataset, data) != 0) {
5436                 zfs_close(zhp);
5437                 return (1);
5438         }
5439 
5440         /*
5441          * Skip any datasets whose type does not match.
5442          */
5443         if ((type & ZFS_TYPE_FILESYSTEM) == 0) {
5444                 zfs_close(zhp);
5445                 return (0);
5446         }
5447         libzfs_add_handle(cbp, zhp);
5448         assert(cbp->cb_used <= cbp->cb_alloc);
5449 
5450         return (0);
5451 }
5452 
5453 static void
5454 get_all_datasets(zfs_handle_t ***dslist, size_t *count, boolean_t verbose)
5455 {
5456         get_all_cb_t cb = { 0 };
5457         cb.cb_verbose = verbose;
5458         cb.cb_getone = get_one_dataset;
5459 
5460         if (verbose)
5461                 set_progress_header(gettext("Reading ZFS config"));
5462         (void) zfs_iter_root(g_zfs, get_one_dataset, &cb);
5463 
5464         *dslist = cb.cb_handles;
5465         *count = cb.cb_used;
5466 
5467         if (verbose)
5468                 finish_progress(gettext("done."));
5469 }
5470 
5471 /*
5472  * Generic callback for sharing or mounting filesystems.  Because the code is so
5473  * similar, we have a common function with an extra parameter to determine which
5474  * mode we are using.
5475  */
5476 #define OP_SHARE        0x1
5477 #define OP_MOUNT        0x2
5478 
5479 /*
5480  * Share or mount a dataset.
5481  */
5482 static int
5483 share_mount_one(zfs_handle_t *zhp, int op, int flags, char *protocol,
5484     boolean_t explicit, const char *options)
5485 {
5486         char mountpoint[ZFS_MAXPROPLEN];
5487         char shareopts[ZFS_MAXPROPLEN];
5488         char smbshareopts[ZFS_MAXPROPLEN];
5489         const char *cmdname = op == OP_SHARE ? "share" : "mount";
5490         struct mnttab mnt;
5491         uint64_t zoned, canmount;
5492         boolean_t shared_nfs, shared_smb;
5493 
5494         assert(zfs_get_type(zhp) & ZFS_TYPE_FILESYSTEM);
5495 
5496         /*
5497          * Check to make sure we can mount/share this dataset.  If we
5498          * are in the global zone and the filesystem is exported to a
5499          * local zone, or if we are in a local zone and the
5500          * filesystem is not exported, then it is an error.
5501          */
5502         zoned = zfs_prop_get_int(zhp, ZFS_PROP_ZONED);
5503 
5504         if (zoned && getzoneid() == GLOBAL_ZONEID) {
5505                 if (!explicit)
5506                         return (0);
5507 
5508                 (void) fprintf(stderr, gettext("cannot %s '%s': "
5509                     "dataset is exported to a local zone\n"), cmdname,
5510                     zfs_get_name(zhp));
5511                 return (1);
5512 
5513         } else if (!zoned && getzoneid() != GLOBAL_ZONEID) {
5514                 if (!explicit)
5515                         return (0);
5516 
5517                 (void) fprintf(stderr, gettext("cannot %s '%s': "
5518                     "permission denied\n"), cmdname,
5519                     zfs_get_name(zhp));
5520                 return (1);
5521         }
5522 
5523         /*
5524          * Ignore any filesystems which don't apply to us. This
5525          * includes those with a legacy mountpoint, or those with
5526          * legacy share options.
5527          */
5528         verify(zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT, mountpoint,
5529             sizeof (mountpoint), NULL, NULL, 0, B_FALSE) == 0);
5530         verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS, shareopts,
5531             sizeof (shareopts), NULL, NULL, 0, B_FALSE) == 0);
5532         verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB, smbshareopts,
5533             sizeof (smbshareopts), NULL, NULL, 0, B_FALSE) == 0);
5534 
5535         if (op == OP_SHARE && strcmp(shareopts, "off") == 0 &&
5536             strcmp(smbshareopts, "off") == 0) {
5537                 if (!explicit)
5538                         return (0);
5539 
5540                 (void) fprintf(stderr, gettext("cannot share '%s': "
5541                     "legacy share\n"), zfs_get_name(zhp));
5542                 (void) fprintf(stderr, gettext("use share(1M) to "
5543                     "share this filesystem, or set "
5544                     "sharenfs property on\n"));
5545                 return (1);
5546         }
5547 
5548         /*
5549          * We cannot share or mount legacy filesystems. If the
5550          * shareopts is non-legacy but the mountpoint is legacy, we
5551          * treat it as a legacy share.
5552          */
5553         if (strcmp(mountpoint, "legacy") == 0) {
5554                 if (!explicit)
5555                         return (0);
5556 
5557                 (void) fprintf(stderr, gettext("cannot %s '%s': "
5558                     "legacy mountpoint\n"), cmdname, zfs_get_name(zhp));
5559                 (void) fprintf(stderr, gettext("use %s(1M) to "
5560                     "%s this filesystem\n"), cmdname, cmdname);
5561                 return (1);
5562         }
5563 
5564         if (strcmp(mountpoint, "none") == 0) {
5565                 if (!explicit)
5566                         return (0);
5567 
5568                 (void) fprintf(stderr, gettext("cannot %s '%s': no "
5569                     "mountpoint set\n"), cmdname, zfs_get_name(zhp));
5570                 return (1);
5571         }
5572 
5573         /*
5574          * canmount     explicit        outcome
5575          * on           no              pass through
5576          * on           yes             pass through
5577          * off          no              return 0
5578          * off          yes             display error, return 1
5579          * noauto       no              return 0
5580          * noauto       yes             pass through
5581          */
5582         canmount = zfs_prop_get_int(zhp, ZFS_PROP_CANMOUNT);
5583         if (canmount == ZFS_CANMOUNT_OFF) {
5584                 if (!explicit)
5585                         return (0);
5586 
5587                 (void) fprintf(stderr, gettext("cannot %s '%s': "
5588                     "'canmount' property is set to 'off'\n"), cmdname,
5589                     zfs_get_name(zhp));
5590                 return (1);
5591         } else if (canmount == ZFS_CANMOUNT_NOAUTO && !explicit) {
5592                 return (0);
5593         }
5594 
5595         /*
5596          * At this point, we have verified that the mountpoint and/or
5597          * shareopts are appropriate for auto management. If the
5598          * filesystem is already mounted or shared, return (failing
5599          * for explicit requests); otherwise mount or share the
5600          * filesystem.
5601          */
5602         switch (op) {
5603         case OP_SHARE:
5604 
5605                 shared_nfs = zfs_is_shared_nfs(zhp, NULL);
5606                 shared_smb = zfs_is_shared_smb(zhp, NULL);
5607 
5608                 if (shared_nfs && shared_smb ||
5609                     (shared_nfs && strcmp(shareopts, "on") == 0 &&
5610                     strcmp(smbshareopts, "off") == 0) ||
5611                     (shared_smb && strcmp(smbshareopts, "on") == 0 &&
5612                     strcmp(shareopts, "off") == 0)) {
5613                         if (!explicit)
5614                                 return (0);
5615 
5616                         (void) fprintf(stderr, gettext("cannot share "
5617                             "'%s': filesystem already shared\n"),
5618                             zfs_get_name(zhp));
5619                         return (1);
5620                 }
5621 
5622                 if (!zfs_is_mounted(zhp, NULL) &&
5623                     zfs_mount(zhp, NULL, 0) != 0)
5624                         return (1);
5625 
5626                 if (protocol == NULL) {
5627                         if (zfs_shareall(zhp) != 0)
5628                                 return (1);
5629                 } else if (strcmp(protocol, "nfs") == 0) {
5630                         if (zfs_share_nfs(zhp))
5631                                 return (1);
5632                 } else if (strcmp(protocol, "smb") == 0) {
5633                         if (zfs_share_smb(zhp))
5634                                 return (1);
5635                 } else {
5636                         (void) fprintf(stderr, gettext("cannot share "
5637                             "'%s': invalid share type '%s' "
5638                             "specified\n"),
5639                             zfs_get_name(zhp), protocol);
5640                         return (1);
5641                 }
5642 
5643                 break;
5644 
5645         case OP_MOUNT:
5646                 if (options == NULL)
5647                         mnt.mnt_mntopts = "";
5648                 else
5649                         mnt.mnt_mntopts = (char *)options;
5650 
5651                 if (!hasmntopt(&mnt, MNTOPT_REMOUNT) &&
5652                     zfs_is_mounted(zhp, NULL)) {
5653                         if (!explicit)
5654                                 return (0);
5655 
5656                         (void) fprintf(stderr, gettext("cannot mount "
5657                             "'%s': filesystem already mounted\n"),
5658                             zfs_get_name(zhp));
5659                         return (1);
5660                 }
5661 
5662                 if (zfs_mount(zhp, options, flags) != 0)
5663                         return (1);
5664                 break;
5665         }
5666 
5667         return (0);
5668 }
5669 
5670 /*
5671  * Reports progress in the form "(current/total)".  Not thread-safe.
5672  */
5673 static void
5674 report_mount_progress(int current, int total)
5675 {
5676         static time_t last_progress_time = 0;
5677         time_t now = time(NULL);
5678         char info[32];
5679 
5680         /* report 1..n instead of 0..n-1 */
5681         ++current;
5682 
5683         /* display header if we're here for the first time */
5684         if (current == 1) {
5685                 set_progress_header(gettext("Mounting ZFS filesystems"));
5686         } else if (current != total && last_progress_time + MOUNT_TIME >= now) {
5687                 /* too soon to report again */
5688                 return;
5689         }
5690 
5691         last_progress_time = now;
5692 
5693         (void) sprintf(info, "(%d/%d)", current, total);
5694 
5695         if (current == total)
5696                 finish_progress(info);
5697         else
5698                 update_progress(info);
5699 }
5700 
5701 static void
5702 append_options(char *mntopts, char *newopts)
5703 {
5704         int len = strlen(mntopts);
5705 
5706         /* original length plus new string to append plus 1 for the comma */
5707         if (len + 1 + strlen(newopts) >= MNT_LINE_MAX) {
5708                 (void) fprintf(stderr, gettext("the opts argument for "
5709                     "'%c' option is too long (more than %d chars)\n"),
5710                     "-o", MNT_LINE_MAX);
5711                 usage(B_FALSE);
5712         }
5713 
5714         if (*mntopts)
5715                 mntopts[len++] = ',';
5716 
5717         (void) strcpy(&mntopts[len], newopts);
5718 }
5719 
5720 static int
5721 share_mount(int op, int argc, char **argv)
5722 {
5723         int do_all = 0;
5724         boolean_t verbose = B_FALSE;
5725         int c, ret = 0;
5726         char *options = NULL;
5727         int flags = 0;
5728 
5729         /* check options */
5730         while ((c = getopt(argc, argv, op == OP_MOUNT ? ":avo:O" : "a"))
5731             != -1) {
5732                 switch (c) {
5733                 case 'a':
5734                         do_all = 1;
5735                         break;
5736                 case 'v':
5737                         verbose = B_TRUE;
5738                         break;
5739                 case 'o':
5740                         if (*optarg == '\0') {
5741                                 (void) fprintf(stderr, gettext("empty mount "
5742                                     "options (-o) specified\n"));
5743                                 usage(B_FALSE);
5744                         }
5745 
5746                         if (options == NULL)
5747                                 options = safe_malloc(MNT_LINE_MAX + 1);
5748 
5749                         /* option validation is done later */
5750                         append_options(options, optarg);
5751                         break;
5752 
5753                 case 'O':
5754                         flags |= MS_OVERLAY;
5755                         break;
5756                 case ':':
5757                         (void) fprintf(stderr, gettext("missing argument for "
5758                             "'%c' option\n"), optopt);
5759                         usage(B_FALSE);
5760                         break;
5761                 case '?':
5762                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
5763                             optopt);
5764                         usage(B_FALSE);
5765                 }
5766         }
5767 
5768         argc -= optind;
5769         argv += optind;
5770 
5771         /* check number of arguments */
5772         if (do_all) {
5773                 zfs_handle_t **dslist = NULL;
5774                 size_t i, count = 0;
5775                 char *protocol = NULL;
5776 
5777                 if (op == OP_SHARE && argc > 0) {
5778                         if (strcmp(argv[0], "nfs") != 0 &&
5779                             strcmp(argv[0], "smb") != 0) {
5780                                 (void) fprintf(stderr, gettext("share type "
5781                                     "must be 'nfs' or 'smb'\n"));
5782                                 usage(B_FALSE);
5783                         }
5784                         protocol = argv[0];
5785                         argc--;
5786                         argv++;
5787                 }
5788 
5789                 if (argc != 0) {
5790                         (void) fprintf(stderr, gettext("too many arguments\n"));
5791                         usage(B_FALSE);
5792                 }
5793 
5794                 start_progress_timer();
5795                 get_all_datasets(&dslist, &count, verbose);
5796 
5797                 if (count == 0)
5798                         return (0);
5799 
5800                 qsort(dslist, count, sizeof (void *), libzfs_dataset_cmp);
5801 
5802                 for (i = 0; i < count; i++) {
5803                         if (verbose)
5804                                 report_mount_progress(i, count);
5805 
5806                         if (share_mount_one(dslist[i], op, flags, protocol,
5807                             B_FALSE, options) != 0)
5808                                 ret = 1;
5809                         zfs_close(dslist[i]);
5810                 }
5811 
5812                 free(dslist);
5813         } else if (argc == 0) {
5814                 struct mnttab entry;
5815 
5816                 if ((op == OP_SHARE) || (options != NULL)) {
5817                         (void) fprintf(stderr, gettext("missing filesystem "
5818                             "argument (specify -a for all)\n"));
5819                         usage(B_FALSE);
5820                 }
5821 
5822                 /*
5823                  * When mount is given no arguments, go through /etc/mnttab and
5824                  * display any active ZFS mounts.  We hide any snapshots, since
5825                  * they are controlled automatically.
5826                  */
5827                 rewind(mnttab_file);
5828                 while (getmntent(mnttab_file, &entry) == 0) {
5829                         if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0 ||
5830                             strchr(entry.mnt_special, '@') != NULL)
5831                                 continue;
5832 
5833                         (void) printf("%-30s  %s\n", entry.mnt_special,
5834                             entry.mnt_mountp);
5835                 }
5836 
5837         } else {
5838                 zfs_handle_t *zhp;
5839 
5840                 if (argc > 1) {
5841                         (void) fprintf(stderr,
5842                             gettext("too many arguments\n"));
5843                         usage(B_FALSE);
5844                 }
5845 
5846                 if ((zhp = zfs_open(g_zfs, argv[0],
5847                     ZFS_TYPE_FILESYSTEM)) == NULL) {
5848                         ret = 1;
5849                 } else {
5850                         ret = share_mount_one(zhp, op, flags, NULL, B_TRUE,
5851                             options);
5852                         zfs_close(zhp);
5853                 }
5854         }
5855 
5856         return (ret);
5857 }
5858 
5859 /*
5860  * zfs mount -a [nfs]
5861  * zfs mount filesystem
5862  *
5863  * Mount all filesystems, or mount the given filesystem.
5864  */
5865 static int
5866 zfs_do_mount(int argc, char **argv)
5867 {
5868         return (share_mount(OP_MOUNT, argc, argv));
5869 }
5870 
5871 /*
5872  * zfs share -a [nfs | smb]
5873  * zfs share filesystem
5874  *
5875  * Share all filesystems, or share the given filesystem.
5876  */
5877 static int
5878 zfs_do_share(int argc, char **argv)
5879 {
5880         return (share_mount(OP_SHARE, argc, argv));
5881 }
5882 
5883 typedef struct unshare_unmount_node {
5884         zfs_handle_t    *un_zhp;
5885         char            *un_mountp;
5886         uu_avl_node_t   un_avlnode;
5887 } unshare_unmount_node_t;
5888 
5889 /* ARGSUSED */
5890 static int
5891 unshare_unmount_compare(const void *larg, const void *rarg, void *unused)
5892 {
5893         const unshare_unmount_node_t *l = larg;
5894         const unshare_unmount_node_t *r = rarg;
5895 
5896         return (strcmp(l->un_mountp, r->un_mountp));
5897 }
5898 
5899 /*
5900  * Convenience routine used by zfs_do_umount() and manual_unmount().  Given an
5901  * absolute path, find the entry /etc/mnttab, verify that its a ZFS filesystem,
5902  * and unmount it appropriately.
5903  */
5904 static int
5905 unshare_unmount_path(int op, char *path, int flags, boolean_t is_manual)
5906 {
5907         zfs_handle_t *zhp;
5908         int ret = 0;
5909         struct stat64 statbuf;
5910         struct extmnttab entry;
5911         const char *cmdname = (op == OP_SHARE) ? "unshare" : "unmount";
5912         ino_t path_inode;
5913 
5914         /*
5915          * Search for the path in /etc/mnttab.  Rather than looking for the
5916          * specific path, which can be fooled by non-standard paths (i.e. ".."
5917          * or "//"), we stat() the path and search for the corresponding
5918          * (major,minor) device pair.
5919          */
5920         if (stat64(path, &statbuf) != 0) {
5921                 (void) fprintf(stderr, gettext("cannot %s '%s': %s\n"),
5922                     cmdname, path, strerror(errno));
5923                 return (1);
5924         }
5925         path_inode = statbuf.st_ino;
5926 
5927         /*
5928          * Search for the given (major,minor) pair in the mount table.
5929          */
5930         rewind(mnttab_file);
5931         while ((ret = getextmntent(mnttab_file, &entry, 0)) == 0) {
5932                 if (entry.mnt_major == major(statbuf.st_dev) &&
5933                     entry.mnt_minor == minor(statbuf.st_dev))
5934                         break;
5935         }
5936         if (ret != 0) {
5937                 if (op == OP_SHARE) {
5938                         (void) fprintf(stderr, gettext("cannot %s '%s': not "
5939                             "currently mounted\n"), cmdname, path);
5940                         return (1);
5941                 }
5942                 (void) fprintf(stderr, gettext("warning: %s not in mnttab\n"),
5943                     path);
5944                 if ((ret = umount2(path, flags)) != 0)
5945                         (void) fprintf(stderr, gettext("%s: %s\n"), path,
5946                             strerror(errno));
5947                 return (ret != 0);
5948         }
5949 
5950         if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0) {
5951                 (void) fprintf(stderr, gettext("cannot %s '%s': not a ZFS "
5952                     "filesystem\n"), cmdname, path);
5953                 return (1);
5954         }
5955 
5956         if ((zhp = zfs_open(g_zfs, entry.mnt_special,
5957             ZFS_TYPE_FILESYSTEM)) == NULL)
5958                 return (1);
5959 
5960         ret = 1;
5961         if (stat64(entry.mnt_mountp, &statbuf) != 0) {
5962                 (void) fprintf(stderr, gettext("cannot %s '%s': %s\n"),
5963                     cmdname, path, strerror(errno));
5964                 goto out;
5965         } else if (statbuf.st_ino != path_inode) {
5966                 (void) fprintf(stderr, gettext("cannot "
5967                     "%s '%s': not a mountpoint\n"), cmdname, path);
5968                 goto out;
5969         }
5970 
5971         if (op == OP_SHARE) {
5972                 char nfs_mnt_prop[ZFS_MAXPROPLEN];
5973                 char smbshare_prop[ZFS_MAXPROPLEN];
5974 
5975                 verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS, nfs_mnt_prop,
5976                     sizeof (nfs_mnt_prop), NULL, NULL, 0, B_FALSE) == 0);
5977                 verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB, smbshare_prop,
5978                     sizeof (smbshare_prop), NULL, NULL, 0, B_FALSE) == 0);
5979 
5980                 if (strcmp(nfs_mnt_prop, "off") == 0 &&
5981                     strcmp(smbshare_prop, "off") == 0) {
5982                         (void) fprintf(stderr, gettext("cannot unshare "
5983                             "'%s': legacy share\n"), path);
5984                         (void) fprintf(stderr, gettext("use "
5985                             "unshare(1M) to unshare this filesystem\n"));
5986                 } else if (!zfs_is_shared(zhp)) {
5987                         (void) fprintf(stderr, gettext("cannot unshare '%s': "
5988                             "not currently shared\n"), path);
5989                 } else {
5990                         ret = zfs_unshareall_bypath(zhp, path);
5991                 }
5992         } else {
5993                 char mtpt_prop[ZFS_MAXPROPLEN];
5994 
5995                 verify(zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT, mtpt_prop,
5996                     sizeof (mtpt_prop), NULL, NULL, 0, B_FALSE) == 0);
5997 
5998                 if (is_manual) {
5999                         ret = zfs_unmount(zhp, NULL, flags);
6000                 } else if (strcmp(mtpt_prop, "legacy") == 0) {
6001                         (void) fprintf(stderr, gettext("cannot unmount "
6002                             "'%s': legacy mountpoint\n"),
6003                             zfs_get_name(zhp));
6004                         (void) fprintf(stderr, gettext("use umount(1M) "
6005                             "to unmount this filesystem\n"));
6006                 } else {
6007                         ret = zfs_unmountall(zhp, flags);
6008                 }
6009         }
6010 
6011 out:
6012         zfs_close(zhp);
6013 
6014         return (ret != 0);
6015 }
6016 
6017 /*
6018  * Generic callback for unsharing or unmounting a filesystem.
6019  */
6020 static int
6021 unshare_unmount(int op, int argc, char **argv)
6022 {
6023         int do_all = 0;
6024         int flags = 0;
6025         int ret = 0;
6026         int c;
6027         zfs_handle_t *zhp;
6028         char nfs_mnt_prop[ZFS_MAXPROPLEN];
6029         char sharesmb[ZFS_MAXPROPLEN];
6030 
6031         /* check options */
6032         while ((c = getopt(argc, argv, op == OP_SHARE ? "a" : "af")) != -1) {
6033                 switch (c) {
6034                 case 'a':
6035                         do_all = 1;
6036                         break;
6037                 case 'f':
6038                         flags = MS_FORCE;
6039                         break;
6040                 case '?':
6041                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
6042                             optopt);
6043                         usage(B_FALSE);
6044                 }
6045         }
6046 
6047         argc -= optind;
6048         argv += optind;
6049 
6050         if (do_all) {
6051                 /*
6052                  * We could make use of zfs_for_each() to walk all datasets in
6053                  * the system, but this would be very inefficient, especially
6054                  * since we would have to linearly search /etc/mnttab for each
6055                  * one.  Instead, do one pass through /etc/mnttab looking for
6056                  * zfs entries and call zfs_unmount() for each one.
6057                  *
6058                  * Things get a little tricky if the administrator has created
6059                  * mountpoints beneath other ZFS filesystems.  In this case, we
6060                  * have to unmount the deepest filesystems first.  To accomplish
6061                  * this, we place all the mountpoints in an AVL tree sorted by
6062                  * the special type (dataset name), and walk the result in
6063                  * reverse to make sure to get any snapshots first.
6064                  */
6065                 struct mnttab entry;
6066                 uu_avl_pool_t *pool;
6067                 uu_avl_t *tree;
6068                 unshare_unmount_node_t *node;
6069                 uu_avl_index_t idx;
6070                 uu_avl_walk_t *walk;
6071 
6072                 if (argc != 0) {
6073                         (void) fprintf(stderr, gettext("too many arguments\n"));
6074                         usage(B_FALSE);
6075                 }
6076 
6077                 if (((pool = uu_avl_pool_create("unmount_pool",
6078                     sizeof (unshare_unmount_node_t),
6079                     offsetof(unshare_unmount_node_t, un_avlnode),
6080                     unshare_unmount_compare, UU_DEFAULT)) == NULL) ||
6081                     ((tree = uu_avl_create(pool, NULL, UU_DEFAULT)) == NULL))
6082                         nomem();
6083 
6084                 rewind(mnttab_file);
6085                 while (getmntent(mnttab_file, &entry) == 0) {
6086 
6087                         /* ignore non-ZFS entries */
6088                         if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0)
6089                                 continue;
6090 
6091                         /* ignore snapshots */
6092                         if (strchr(entry.mnt_special, '@') != NULL)
6093                                 continue;
6094 
6095                         if ((zhp = zfs_open(g_zfs, entry.mnt_special,
6096                             ZFS_TYPE_FILESYSTEM)) == NULL) {
6097                                 ret = 1;
6098                                 continue;
6099                         }
6100 
6101                         switch (op) {
6102                         case OP_SHARE:
6103                                 verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS,
6104                                     nfs_mnt_prop,
6105                                     sizeof (nfs_mnt_prop),
6106                                     NULL, NULL, 0, B_FALSE) == 0);
6107                                 if (strcmp(nfs_mnt_prop, "off") != 0)
6108                                         break;
6109                                 verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB,
6110                                     nfs_mnt_prop,
6111                                     sizeof (nfs_mnt_prop),
6112                                     NULL, NULL, 0, B_FALSE) == 0);
6113                                 if (strcmp(nfs_mnt_prop, "off") == 0)
6114                                         continue;
6115                                 break;
6116                         case OP_MOUNT:
6117                                 /* Ignore legacy mounts */
6118                                 verify(zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT,
6119                                     nfs_mnt_prop,
6120                                     sizeof (nfs_mnt_prop),
6121                                     NULL, NULL, 0, B_FALSE) == 0);
6122                                 if (strcmp(nfs_mnt_prop, "legacy") == 0)
6123                                         continue;
6124                                 /* Ignore canmount=noauto mounts */
6125                                 if (zfs_prop_get_int(zhp, ZFS_PROP_CANMOUNT) ==
6126                                     ZFS_CANMOUNT_NOAUTO)
6127                                         continue;
6128                         default:
6129                                 break;
6130                         }
6131 
6132                         node = safe_malloc(sizeof (unshare_unmount_node_t));
6133                         node->un_zhp = zhp;
6134                         node->un_mountp = safe_strdup(entry.mnt_mountp);
6135 
6136                         uu_avl_node_init(node, &node->un_avlnode, pool);
6137 
6138                         if (uu_avl_find(tree, node, NULL, &idx) == NULL) {
6139                                 uu_avl_insert(tree, node, idx);
6140                         } else {
6141                                 zfs_close(node->un_zhp);
6142                                 free(node->un_mountp);
6143                                 free(node);
6144                         }
6145                 }
6146 
6147                 /*
6148                  * Walk the AVL tree in reverse, unmounting each filesystem and
6149                  * removing it from the AVL tree in the process.
6150                  */
6151                 if ((walk = uu_avl_walk_start(tree,
6152                     UU_WALK_REVERSE | UU_WALK_ROBUST)) == NULL)
6153                         nomem();
6154 
6155                 while ((node = uu_avl_walk_next(walk)) != NULL) {
6156                         uu_avl_remove(tree, node);
6157 
6158                         switch (op) {
6159                         case OP_SHARE:
6160                                 if (zfs_unshareall_bypath(node->un_zhp,
6161                                     node->un_mountp) != 0)
6162                                         ret = 1;
6163                                 break;
6164 
6165                         case OP_MOUNT:
6166                                 if (zfs_unmount(node->un_zhp,
6167                                     node->un_mountp, flags) != 0)
6168                                         ret = 1;
6169                                 break;
6170                         }
6171 
6172                         zfs_close(node->un_zhp);
6173                         free(node->un_mountp);
6174                         free(node);
6175                 }
6176 
6177                 uu_avl_walk_end(walk);
6178                 uu_avl_destroy(tree);
6179                 uu_avl_pool_destroy(pool);
6180 
6181         } else {
6182                 if (argc != 1) {
6183                         if (argc == 0)
6184                                 (void) fprintf(stderr,
6185                                     gettext("missing filesystem argument\n"));
6186                         else
6187                                 (void) fprintf(stderr,
6188                                     gettext("too many arguments\n"));
6189                         usage(B_FALSE);
6190                 }
6191 
6192                 /*
6193                  * We have an argument, but it may be a full path or a ZFS
6194                  * filesystem.  Pass full paths off to unmount_path() (shared by
6195                  * manual_unmount), otherwise open the filesystem and pass to
6196                  * zfs_unmount().
6197                  */
6198                 if (argv[0][0] == '/')
6199                         return (unshare_unmount_path(op, argv[0],
6200                             flags, B_FALSE));
6201 
6202                 if ((zhp = zfs_open(g_zfs, argv[0],
6203                     ZFS_TYPE_FILESYSTEM)) == NULL)
6204                         return (1);
6205 
6206                 verify(zfs_prop_get(zhp, op == OP_SHARE ?
6207                     ZFS_PROP_SHARENFS : ZFS_PROP_MOUNTPOINT,
6208                     nfs_mnt_prop, sizeof (nfs_mnt_prop), NULL,
6209                     NULL, 0, B_FALSE) == 0);
6210 
6211                 switch (op) {
6212                 case OP_SHARE:
6213                         verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS,
6214                             nfs_mnt_prop,
6215                             sizeof (nfs_mnt_prop),
6216                             NULL, NULL, 0, B_FALSE) == 0);
6217                         verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB,
6218                             sharesmb, sizeof (sharesmb), NULL, NULL,
6219                             0, B_FALSE) == 0);
6220 
6221                         if (strcmp(nfs_mnt_prop, "off") == 0 &&
6222                             strcmp(sharesmb, "off") == 0) {
6223                                 (void) fprintf(stderr, gettext("cannot "
6224                                     "unshare '%s': legacy share\n"),
6225                                     zfs_get_name(zhp));
6226                                 (void) fprintf(stderr, gettext("use "
6227                                     "unshare(1M) to unshare this "
6228                                     "filesystem\n"));
6229                                 ret = 1;
6230                         } else if (!zfs_is_shared(zhp)) {
6231                                 (void) fprintf(stderr, gettext("cannot "
6232                                     "unshare '%s': not currently "
6233                                     "shared\n"), zfs_get_name(zhp));
6234                                 ret = 1;
6235                         } else if (zfs_unshareall(zhp) != 0) {
6236                                 ret = 1;
6237                         }
6238                         break;
6239 
6240                 case OP_MOUNT:
6241                         if (strcmp(nfs_mnt_prop, "legacy") == 0) {
6242                                 (void) fprintf(stderr, gettext("cannot "
6243                                     "unmount '%s': legacy "
6244                                     "mountpoint\n"), zfs_get_name(zhp));
6245                                 (void) fprintf(stderr, gettext("use "
6246                                     "umount(1M) to unmount this "
6247                                     "filesystem\n"));
6248                                 ret = 1;
6249                         } else if (!zfs_is_mounted(zhp, NULL)) {
6250                                 (void) fprintf(stderr, gettext("cannot "
6251                                     "unmount '%s': not currently "
6252                                     "mounted\n"),
6253                                     zfs_get_name(zhp));
6254                                 ret = 1;
6255                         } else if (zfs_unmountall(zhp, flags) != 0) {
6256                                 ret = 1;
6257                         }
6258                         break;
6259                 }
6260 
6261                 zfs_close(zhp);
6262         }
6263 
6264         return (ret);
6265 }
6266 
6267 /*
6268  * zfs unmount -a
6269  * zfs unmount filesystem
6270  *
6271  * Unmount all filesystems, or a specific ZFS filesystem.
6272  */
6273 static int
6274 zfs_do_unmount(int argc, char **argv)
6275 {
6276         return (unshare_unmount(OP_MOUNT, argc, argv));
6277 }
6278 
6279 /*
6280  * zfs unshare -a
6281  * zfs unshare filesystem
6282  *
6283  * Unshare all filesystems, or a specific ZFS filesystem.
6284  */
6285 static int
6286 zfs_do_unshare(int argc, char **argv)
6287 {
6288         return (unshare_unmount(OP_SHARE, argc, argv));
6289 }
6290 
6291 /*
6292  * Called when invoked as /etc/fs/zfs/mount.  Do the mount if the mountpoint is
6293  * 'legacy'.  Otherwise, complain that use should be using 'zfs mount'.
6294  */
6295 static int
6296 manual_mount(int argc, char **argv)
6297 {
6298         zfs_handle_t *zhp;
6299         char mountpoint[ZFS_MAXPROPLEN];
6300         char mntopts[MNT_LINE_MAX] = { '\0' };
6301         int ret = 0;
6302         int c;
6303         int flags = 0;
6304         char *dataset, *path;
6305 
6306         /* check options */
6307         while ((c = getopt(argc, argv, ":mo:O")) != -1) {
6308                 switch (c) {
6309                 case 'o':
6310                         (void) strlcpy(mntopts, optarg, sizeof (mntopts));
6311                         break;
6312                 case 'O':
6313                         flags |= MS_OVERLAY;
6314                         break;
6315                 case 'm':
6316                         flags |= MS_NOMNTTAB;
6317                         break;
6318                 case ':':
6319                         (void) fprintf(stderr, gettext("missing argument for "
6320                             "'%c' option\n"), optopt);
6321                         usage(B_FALSE);
6322                         break;
6323                 case '?':
6324                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
6325                             optopt);
6326                         (void) fprintf(stderr, gettext("usage: mount [-o opts] "
6327                             "<path>\n"));
6328                         return (2);
6329                 }
6330         }
6331 
6332         argc -= optind;
6333         argv += optind;
6334 
6335         /* check that we only have two arguments */
6336         if (argc != 2) {
6337                 if (argc == 0)
6338                         (void) fprintf(stderr, gettext("missing dataset "
6339                             "argument\n"));
6340                 else if (argc == 1)
6341                         (void) fprintf(stderr,
6342                             gettext("missing mountpoint argument\n"));
6343                 else
6344                         (void) fprintf(stderr, gettext("too many arguments\n"));
6345                 (void) fprintf(stderr, "usage: mount <dataset> <mountpoint>\n");
6346                 return (2);
6347         }
6348 
6349         dataset = argv[0];
6350         path = argv[1];
6351 
6352         /* try to open the dataset */
6353         if ((zhp = zfs_open(g_zfs, dataset, ZFS_TYPE_FILESYSTEM)) == NULL)
6354                 return (1);
6355 
6356         (void) zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT, mountpoint,
6357             sizeof (mountpoint), NULL, NULL, 0, B_FALSE);
6358 
6359         /* check for legacy mountpoint and complain appropriately */
6360         ret = 0;
6361         if (strcmp(mountpoint, ZFS_MOUNTPOINT_LEGACY) == 0) {
6362                 if (mount(dataset, path, MS_OPTIONSTR | flags, MNTTYPE_ZFS,
6363                     NULL, 0, mntopts, sizeof (mntopts)) != 0) {
6364                         (void) fprintf(stderr, gettext("mount failed: %s\n"),
6365                             strerror(errno));
6366                         ret = 1;
6367                 }
6368         } else {
6369                 (void) fprintf(stderr, gettext("filesystem '%s' cannot be "
6370                     "mounted using 'mount -F zfs'\n"), dataset);
6371                 (void) fprintf(stderr, gettext("Use 'zfs set mountpoint=%s' "
6372                     "instead.\n"), path);
6373                 (void) fprintf(stderr, gettext("If you must use 'mount -F zfs' "
6374                     "or /etc/vfstab, use 'zfs set mountpoint=legacy'.\n"));
6375                 (void) fprintf(stderr, gettext("See zfs(1M) for more "
6376                     "information.\n"));
6377                 ret = 1;
6378         }
6379 
6380         return (ret);
6381 }
6382 
6383 /*
6384  * Called when invoked as /etc/fs/zfs/umount.  Unlike a manual mount, we allow
6385  * unmounts of non-legacy filesystems, as this is the dominant administrative
6386  * interface.
6387  */
6388 static int
6389 manual_unmount(int argc, char **argv)
6390 {
6391         int flags = 0;
6392         int c;
6393 
6394         /* check options */
6395         while ((c = getopt(argc, argv, "f")) != -1) {
6396                 switch (c) {
6397                 case 'f':
6398                         flags = MS_FORCE;
6399                         break;
6400                 case '?':
6401                         (void) fprintf(stderr, gettext("invalid option '%c'\n"),
6402                             optopt);
6403                         (void) fprintf(stderr, gettext("usage: unmount [-f] "
6404                             "<path>\n"));
6405                         return (2);
6406                 }
6407         }
6408 
6409         argc -= optind;
6410         argv += optind;
6411 
6412         /* check arguments */
6413         if (argc != 1) {
6414                 if (argc == 0)
6415                         (void) fprintf(stderr, gettext("missing path "
6416                             "argument\n"));
6417                 else
6418                         (void) fprintf(stderr, gettext("too many arguments\n"));
6419                 (void) fprintf(stderr, gettext("usage: unmount [-f] <path>\n"));
6420                 return (2);
6421         }
6422 
6423         return (unshare_unmount_path(OP_MOUNT, argv[0], flags, B_TRUE));
6424 }
6425 
6426 static int
6427 find_command_idx(char *command, int *idx)
6428 {
6429         int i;
6430 
6431         for (i = 0; i < NCOMMAND; i++) {
6432                 if (command_table[i].name == NULL)
6433                         continue;
6434 
6435                 if (strcmp(command, command_table[i].name) == 0) {
6436                         *idx = i;
6437                         return (0);
6438                 }
6439         }
6440         return (1);
6441 }
6442 
6443 static int
6444 zfs_do_diff(int argc, char **argv)
6445 {
6446         zfs_handle_t *zhp;
6447         int flags = 0;
6448         char *tosnap = NULL;
6449         char *fromsnap = NULL;
6450         char *atp, *copy;
6451         int err = 0;
6452         int c;
6453 
6454         while ((c = getopt(argc, argv, "FHt")) != -1) {
6455                 switch (c) {
6456                 case 'F':
6457                         flags |= ZFS_DIFF_CLASSIFY;
6458                         break;
6459                 case 'H':
6460                         flags |= ZFS_DIFF_PARSEABLE;
6461                         break;
6462                 case 't':
6463                         flags |= ZFS_DIFF_TIMESTAMP;
6464                         break;
6465                 default:
6466                         (void) fprintf(stderr,
6467                             gettext("invalid option '%c'\n"), optopt);
6468                         usage(B_FALSE);
6469                 }
6470         }
6471 
6472         argc -= optind;
6473         argv += optind;
6474 
6475         if (argc < 1) {
6476                 (void) fprintf(stderr,
6477                 gettext("must provide at least one snapshot name\n"));
6478                 usage(B_FALSE);
6479         }
6480 
6481         if (argc > 2) {
6482                 (void) fprintf(stderr, gettext("too many arguments\n"));
6483                 usage(B_FALSE);
6484         }
6485 
6486         fromsnap = argv[0];
6487         tosnap = (argc == 2) ? argv[1] : NULL;
6488 
6489         copy = NULL;
6490         if (*fromsnap != '@')
6491                 copy = strdup(fromsnap);
6492         else if (tosnap)
6493                 copy = strdup(tosnap);
6494         if (copy == NULL)
6495                 usage(B_FALSE);
6496 
6497         if (atp = strchr(copy, '@'))
6498                 *atp = '\0';
6499 
6500         if ((zhp = zfs_open(g_zfs, copy, ZFS_TYPE_FILESYSTEM)) == NULL)
6501                 return (1);
6502 
6503         free(copy);
6504 
6505         /*
6506          * Ignore SIGPIPE so that the library can give us
6507          * information on any failure
6508          */
6509         (void) sigignore(SIGPIPE);
6510 
6511         err = zfs_show_diffs(zhp, STDOUT_FILENO, fromsnap, tosnap, flags);
6512 
6513         zfs_close(zhp);
6514 
6515         return (err != 0);
6516 }
6517 
6518 int
6519 main(int argc, char **argv)
6520 {
6521         int ret = 0;
6522         int i;
6523         char *progname;
6524         char *cmdname;
6525 
6526         (void) setlocale(LC_ALL, "");
6527         (void) textdomain(TEXT_DOMAIN);
6528 
6529         opterr = 0;
6530 
6531         if ((g_zfs = libzfs_init()) == NULL) {
6532                 (void) fprintf(stderr, gettext("internal error: failed to "
6533                     "initialize ZFS library\n"));
6534                 return (1);
6535         }
6536 
6537         zfs_save_arguments(argc, argv, history_str, sizeof (history_str));
6538 
6539         libzfs_print_on_error(g_zfs, B_TRUE);
6540 
6541         if ((mnttab_file = fopen(MNTTAB, "r")) == NULL) {
6542                 (void) fprintf(stderr, gettext("internal error: unable to "
6543                     "open %s\n"), MNTTAB);
6544                 return (1);
6545         }
6546 
6547         /*
6548          * This command also doubles as the /etc/fs mount and unmount program.
6549          * Determine if we should take this behavior based on argv[0].
6550          */
6551         progname = basename(argv[0]);
6552         if (strcmp(progname, "mount") == 0) {
6553                 ret = manual_mount(argc, argv);
6554         } else if (strcmp(progname, "umount") == 0) {
6555                 ret = manual_unmount(argc, argv);
6556         } else {
6557                 /*
6558                  * Make sure the user has specified some command.
6559                  */
6560                 if (argc < 2) {
6561                         (void) fprintf(stderr, gettext("missing command\n"));
6562                         usage(B_FALSE);
6563                 }
6564 
6565                 cmdname = argv[1];
6566 
6567                 /*
6568                  * The 'umount' command is an alias for 'unmount'
6569                  */
6570                 if (strcmp(cmdname, "umount") == 0)
6571                         cmdname = "unmount";
6572 
6573                 /*
6574                  * The 'recv' command is an alias for 'receive'
6575                  */
6576                 if (strcmp(cmdname, "recv") == 0)
6577                         cmdname = "receive";
6578 
6579                 /*
6580                  * Special case '-?'
6581                  */
6582                 if (strcmp(cmdname, "-?") == 0)
6583                         usage(B_TRUE);
6584 
6585                 /*
6586                  * Run the appropriate command.
6587                  */
6588                 libzfs_mnttab_cache(g_zfs, B_TRUE);
6589                 if (find_command_idx(cmdname, &i) == 0) {
6590                         current_command = &command_table[i];
6591                         ret = command_table[i].func(argc - 1, argv + 1);
6592                 } else if (strchr(cmdname, '=') != NULL) {
6593                         verify(find_command_idx("set", &i) == 0);
6594                         current_command = &command_table[i];
6595                         ret = command_table[i].func(argc, argv);
6596                 } else {
6597                         (void) fprintf(stderr, gettext("unrecognized "
6598                             "command '%s'\n"), cmdname);
6599                         usage(B_FALSE);
6600                 }
6601                 libzfs_mnttab_cache(g_zfs, B_FALSE);
6602         }
6603 
6604         (void) fclose(mnttab_file);
6605 
6606         if (ret == 0 && log_history)
6607                 (void) zpool_log_history(g_zfs, history_str);
6608 
6609         libzfs_fini(g_zfs);
6610 
6611         /*
6612          * The 'ZFS_ABORT' environment variable causes us to dump core on exit
6613          * for the purposes of running ::findleaks.
6614          */
6615         if (getenv("ZFS_ABORT") != NULL) {
6616                 (void) printf("dumping core by request\n");
6617                 abort();
6618         }
6619 
6620         return (ret);
6621 }