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