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