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