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