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