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 2019 Joyent, Inc.
  25  * Copyright (c) 2011, 2016 by Delphix. All rights reserved.
  26  * Copyright (c) 2012 DEY Storage Systems, Inc.  All rights reserved.
  27  * Copyright (c) 2011-2012 Pawel Jakub Dawidek. All rights reserved.
  28  * Copyright (c) 2013 Martin Matuska. All rights reserved.
  29  * Copyright (c) 2013 Steven Hartland. All rights reserved.
  30  * Copyright (c) 2014 Integros [integros.com]
  31  * Copyright 2017 Nexenta Systems, Inc.
  32  * Copyright 2016 Igor Kozhukhov <ikozhukhov@gmail.com>
  33  * Copyright 2017-2018 RackTop Systems.
  34  */
  35 
  36 #include <ctype.h>
  37 #include <errno.h>
  38 #include <libintl.h>
  39 #include <math.h>
  40 #include <stdio.h>
  41 #include <stdlib.h>
  42 #include <strings.h>
  43 #include <unistd.h>
  44 #include <stddef.h>
  45 #include <zone.h>
  46 #include <fcntl.h>
  47 #include <sys/mntent.h>
  48 #include <sys/mount.h>
  49 #include <priv.h>
  50 #include <pwd.h>
  51 #include <grp.h>
  52 #include <stddef.h>
  53 #include <ucred.h>
  54 #include <idmap.h>
  55 #include <aclutils.h>
  56 #include <directory.h>
  57 #include <time.h>
  58 
  59 #include <sys/dnode.h>
  60 #include <sys/spa.h>
  61 #include <sys/zap.h>
  62 #include <sys/dsl_crypt.h>
  63 #include <libzfs.h>
  64 
  65 #include "zfs_namecheck.h"
  66 #include "zfs_prop.h"
  67 #include "libzfs_impl.h"
  68 #include "zfs_deleg.h"
  69 
  70 static int userquota_propname_decode(const char *propname, boolean_t zoned,
  71     zfs_userquota_prop_t *typep, char *domain, int domainlen, uint64_t *ridp);
  72 
  73 /*
  74  * Given a single type (not a mask of types), return the type in a human
  75  * readable form.
  76  */
  77 const char *
  78 zfs_type_to_name(zfs_type_t type)
  79 {
  80         switch (type) {
  81         case ZFS_TYPE_FILESYSTEM:
  82                 return (dgettext(TEXT_DOMAIN, "filesystem"));
  83         case ZFS_TYPE_SNAPSHOT:
  84                 return (dgettext(TEXT_DOMAIN, "snapshot"));
  85         case ZFS_TYPE_VOLUME:
  86                 return (dgettext(TEXT_DOMAIN, "volume"));
  87         case ZFS_TYPE_POOL:
  88                 return (dgettext(TEXT_DOMAIN, "pool"));
  89         case ZFS_TYPE_BOOKMARK:
  90                 return (dgettext(TEXT_DOMAIN, "bookmark"));
  91         default:
  92                 assert(!"unhandled zfs_type_t");
  93         }
  94 
  95         return (NULL);
  96 }
  97 
  98 /*
  99  * Validate a ZFS path.  This is used even before trying to open the dataset, to
 100  * provide a more meaningful error message.  We call zfs_error_aux() to
 101  * explain exactly why the name was not valid.
 102  */
 103 int
 104 zfs_validate_name(libzfs_handle_t *hdl, const char *path, int type,
 105     boolean_t modifying)
 106 {
 107         namecheck_err_t why;
 108         char what;
 109 
 110         if (entity_namecheck(path, &why, &what) != 0) {
 111                 if (hdl != NULL) {
 112                         switch (why) {
 113                         case NAME_ERR_TOOLONG:
 114                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
 115                                     "name is too long"));
 116                                 break;
 117 
 118                         case NAME_ERR_LEADING_SLASH:
 119                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
 120                                     "leading slash in name"));
 121                                 break;
 122 
 123                         case NAME_ERR_EMPTY_COMPONENT:
 124                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
 125                                     "empty component in name"));
 126                                 break;
 127 
 128                         case NAME_ERR_TRAILING_SLASH:
 129                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
 130                                     "trailing slash in name"));
 131                                 break;
 132 
 133                         case NAME_ERR_INVALCHAR:
 134                                 zfs_error_aux(hdl,
 135                                     dgettext(TEXT_DOMAIN, "invalid character "
 136                                     "'%c' in name"), what);
 137                                 break;
 138 
 139                         case NAME_ERR_MULTIPLE_DELIMITERS:
 140                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
 141                                     "multiple '@' and/or '#' delimiters in "
 142                                     "name"));
 143                                 break;
 144 
 145                         case NAME_ERR_NOLETTER:
 146                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
 147                                     "pool doesn't begin with a letter"));
 148                                 break;
 149 
 150                         case NAME_ERR_RESERVED:
 151                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
 152                                     "name is reserved"));
 153                                 break;
 154 
 155                         case NAME_ERR_DISKLIKE:
 156                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
 157                                     "reserved disk name"));
 158                                 break;
 159 
 160                         default:
 161                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
 162                                     "(%d) not defined"), why);
 163                                 break;
 164                         }
 165                 }
 166 
 167                 return (0);
 168         }
 169 
 170         if (!(type & ZFS_TYPE_SNAPSHOT) && strchr(path, '@') != NULL) {
 171                 if (hdl != NULL)
 172                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
 173                             "snapshot delimiter '@' is not expected here"));
 174                 return (0);
 175         }
 176 
 177         if (type == ZFS_TYPE_SNAPSHOT && strchr(path, '@') == NULL) {
 178                 if (hdl != NULL)
 179                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
 180                             "missing '@' delimiter in snapshot name"));
 181                 return (0);
 182         }
 183 
 184         if (!(type & ZFS_TYPE_BOOKMARK) && strchr(path, '#') != NULL) {
 185                 if (hdl != NULL)
 186                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
 187                             "bookmark delimiter '#' is not expected here"));
 188                 return (0);
 189         }
 190 
 191         if (type == ZFS_TYPE_BOOKMARK && strchr(path, '#') == NULL) {
 192                 if (hdl != NULL)
 193                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
 194                             "missing '#' delimiter in bookmark name"));
 195                 return (0);
 196         }
 197 
 198         if (modifying && strchr(path, '%') != NULL) {
 199                 if (hdl != NULL)
 200                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
 201                             "invalid character %c in name"), '%');
 202                 return (0);
 203         }
 204 
 205         return (-1);
 206 }
 207 
 208 int
 209 zfs_name_valid(const char *name, zfs_type_t type)
 210 {
 211         if (type == ZFS_TYPE_POOL)
 212                 return (zpool_name_valid(NULL, B_FALSE, name));
 213         return (zfs_validate_name(NULL, name, type, B_FALSE));
 214 }
 215 
 216 /*
 217  * This function takes the raw DSL properties, and filters out the user-defined
 218  * properties into a separate nvlist.
 219  */
 220 static nvlist_t *
 221 process_user_props(zfs_handle_t *zhp, nvlist_t *props)
 222 {
 223         libzfs_handle_t *hdl = zhp->zfs_hdl;
 224         nvpair_t *elem;
 225         nvlist_t *propval;
 226         nvlist_t *nvl;
 227 
 228         if (nvlist_alloc(&nvl, NV_UNIQUE_NAME, 0) != 0) {
 229                 (void) no_memory(hdl);
 230                 return (NULL);
 231         }
 232 
 233         elem = NULL;
 234         while ((elem = nvlist_next_nvpair(props, elem)) != NULL) {
 235                 if (!zfs_prop_user(nvpair_name(elem)))
 236                         continue;
 237 
 238                 verify(nvpair_value_nvlist(elem, &propval) == 0);
 239                 if (nvlist_add_nvlist(nvl, nvpair_name(elem), propval) != 0) {
 240                         nvlist_free(nvl);
 241                         (void) no_memory(hdl);
 242                         return (NULL);
 243                 }
 244         }
 245 
 246         return (nvl);
 247 }
 248 
 249 static zpool_handle_t *
 250 zpool_add_handle(zfs_handle_t *zhp, const char *pool_name)
 251 {
 252         libzfs_handle_t *hdl = zhp->zfs_hdl;
 253         zpool_handle_t *zph;
 254 
 255         if ((zph = zpool_open_canfail(hdl, pool_name)) != NULL) {
 256                 if (hdl->libzfs_pool_handles != NULL)
 257                         zph->zpool_next = hdl->libzfs_pool_handles;
 258                 hdl->libzfs_pool_handles = zph;
 259         }
 260         return (zph);
 261 }
 262 
 263 static zpool_handle_t *
 264 zpool_find_handle(zfs_handle_t *zhp, const char *pool_name, int len)
 265 {
 266         libzfs_handle_t *hdl = zhp->zfs_hdl;
 267         zpool_handle_t *zph = hdl->libzfs_pool_handles;
 268 
 269         while ((zph != NULL) &&
 270             (strncmp(pool_name, zpool_get_name(zph), len) != 0))
 271                 zph = zph->zpool_next;
 272         return (zph);
 273 }
 274 
 275 /*
 276  * Returns a handle to the pool that contains the provided dataset.
 277  * If a handle to that pool already exists then that handle is returned.
 278  * Otherwise, a new handle is created and added to the list of handles.
 279  */
 280 static zpool_handle_t *
 281 zpool_handle(zfs_handle_t *zhp)
 282 {
 283         char *pool_name;
 284         int len;
 285         zpool_handle_t *zph;
 286 
 287         len = strcspn(zhp->zfs_name, "/@#") + 1;
 288         pool_name = zfs_alloc(zhp->zfs_hdl, len);
 289         (void) strlcpy(pool_name, zhp->zfs_name, len);
 290 
 291         zph = zpool_find_handle(zhp, pool_name, len);
 292         if (zph == NULL)
 293                 zph = zpool_add_handle(zhp, pool_name);
 294 
 295         free(pool_name);
 296         return (zph);
 297 }
 298 
 299 void
 300 zpool_free_handles(libzfs_handle_t *hdl)
 301 {
 302         zpool_handle_t *next, *zph = hdl->libzfs_pool_handles;
 303 
 304         while (zph != NULL) {
 305                 next = zph->zpool_next;
 306                 zpool_close(zph);
 307                 zph = next;
 308         }
 309         hdl->libzfs_pool_handles = NULL;
 310 }
 311 
 312 /*
 313  * Utility function to gather stats (objset and zpl) for the given object.
 314  */
 315 static int
 316 get_stats_ioctl(zfs_handle_t *zhp, zfs_cmd_t *zc)
 317 {
 318         libzfs_handle_t *hdl = zhp->zfs_hdl;
 319 
 320         (void) strlcpy(zc->zc_name, zhp->zfs_name, sizeof (zc->zc_name));
 321 
 322         while (ioctl(hdl->libzfs_fd, ZFS_IOC_OBJSET_STATS, zc) != 0) {
 323                 if (errno == ENOMEM) {
 324                         if (zcmd_expand_dst_nvlist(hdl, zc) != 0) {
 325                                 return (-1);
 326                         }
 327                 } else {
 328                         return (-1);
 329                 }
 330         }
 331         return (0);
 332 }
 333 
 334 /*
 335  * Utility function to get the received properties of the given object.
 336  */
 337 static int
 338 get_recvd_props_ioctl(zfs_handle_t *zhp)
 339 {
 340         libzfs_handle_t *hdl = zhp->zfs_hdl;
 341         nvlist_t *recvdprops;
 342         zfs_cmd_t zc = { 0 };
 343         int err;
 344 
 345         if (zcmd_alloc_dst_nvlist(hdl, &zc, 0) != 0)
 346                 return (-1);
 347 
 348         (void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
 349 
 350         while (ioctl(hdl->libzfs_fd, ZFS_IOC_OBJSET_RECVD_PROPS, &zc) != 0) {
 351                 if (errno == ENOMEM) {
 352                         if (zcmd_expand_dst_nvlist(hdl, &zc) != 0) {
 353                                 return (-1);
 354                         }
 355                 } else {
 356                         zcmd_free_nvlists(&zc);
 357                         return (-1);
 358                 }
 359         }
 360 
 361         err = zcmd_read_dst_nvlist(zhp->zfs_hdl, &zc, &recvdprops);
 362         zcmd_free_nvlists(&zc);
 363         if (err != 0)
 364                 return (-1);
 365 
 366         nvlist_free(zhp->zfs_recvd_props);
 367         zhp->zfs_recvd_props = recvdprops;
 368 
 369         return (0);
 370 }
 371 
 372 static int
 373 put_stats_zhdl(zfs_handle_t *zhp, zfs_cmd_t *zc)
 374 {
 375         nvlist_t *allprops, *userprops;
 376 
 377         zhp->zfs_dmustats = zc->zc_objset_stats; /* structure assignment */
 378 
 379         if (zcmd_read_dst_nvlist(zhp->zfs_hdl, zc, &allprops) != 0) {
 380                 return (-1);
 381         }
 382 
 383         /*
 384          * XXX Why do we store the user props separately, in addition to
 385          * storing them in zfs_props?
 386          */
 387         if ((userprops = process_user_props(zhp, allprops)) == NULL) {
 388                 nvlist_free(allprops);
 389                 return (-1);
 390         }
 391 
 392         nvlist_free(zhp->zfs_props);
 393         nvlist_free(zhp->zfs_user_props);
 394 
 395         zhp->zfs_props = allprops;
 396         zhp->zfs_user_props = userprops;
 397 
 398         return (0);
 399 }
 400 
 401 static int
 402 get_stats(zfs_handle_t *zhp)
 403 {
 404         int rc = 0;
 405         zfs_cmd_t zc = { 0 };
 406 
 407         if (zcmd_alloc_dst_nvlist(zhp->zfs_hdl, &zc, 0) != 0)
 408                 return (-1);
 409         if (get_stats_ioctl(zhp, &zc) != 0)
 410                 rc = -1;
 411         else if (put_stats_zhdl(zhp, &zc) != 0)
 412                 rc = -1;
 413         zcmd_free_nvlists(&zc);
 414         return (rc);
 415 }
 416 
 417 /*
 418  * Refresh the properties currently stored in the handle.
 419  */
 420 void
 421 zfs_refresh_properties(zfs_handle_t *zhp)
 422 {
 423         (void) get_stats(zhp);
 424 }
 425 
 426 /*
 427  * Makes a handle from the given dataset name.  Used by zfs_open() and
 428  * zfs_iter_* to create child handles on the fly.
 429  */
 430 static int
 431 make_dataset_handle_common(zfs_handle_t *zhp, zfs_cmd_t *zc)
 432 {
 433         if (put_stats_zhdl(zhp, zc) != 0)
 434                 return (-1);
 435 
 436         /*
 437          * We've managed to open the dataset and gather statistics.  Determine
 438          * the high-level type.
 439          */
 440         if (zhp->zfs_dmustats.dds_type == DMU_OST_ZVOL)
 441                 zhp->zfs_head_type = ZFS_TYPE_VOLUME;
 442         else if (zhp->zfs_dmustats.dds_type == DMU_OST_ZFS)
 443                 zhp->zfs_head_type = ZFS_TYPE_FILESYSTEM;
 444         else if (zhp->zfs_dmustats.dds_type == DMU_OST_OTHER)
 445                 return (-1);
 446         else
 447                 abort();
 448 
 449         if (zhp->zfs_dmustats.dds_is_snapshot)
 450                 zhp->zfs_type = ZFS_TYPE_SNAPSHOT;
 451         else if (zhp->zfs_dmustats.dds_type == DMU_OST_ZVOL)
 452                 zhp->zfs_type = ZFS_TYPE_VOLUME;
 453         else if (zhp->zfs_dmustats.dds_type == DMU_OST_ZFS)
 454                 zhp->zfs_type = ZFS_TYPE_FILESYSTEM;
 455         else
 456                 abort();        /* we should never see any other types */
 457 
 458         if ((zhp->zpool_hdl = zpool_handle(zhp)) == NULL)
 459                 return (-1);
 460 
 461         return (0);
 462 }
 463 
 464 zfs_handle_t *
 465 make_dataset_handle(libzfs_handle_t *hdl, const char *path)
 466 {
 467         zfs_cmd_t zc = { 0 };
 468 
 469         zfs_handle_t *zhp = calloc(sizeof (zfs_handle_t), 1);
 470 
 471         if (zhp == NULL)
 472                 return (NULL);
 473 
 474         zhp->zfs_hdl = hdl;
 475         (void) strlcpy(zhp->zfs_name, path, sizeof (zhp->zfs_name));
 476         if (zcmd_alloc_dst_nvlist(hdl, &zc, 0) != 0) {
 477                 free(zhp);
 478                 return (NULL);
 479         }
 480         if (get_stats_ioctl(zhp, &zc) == -1) {
 481                 zcmd_free_nvlists(&zc);
 482                 free(zhp);
 483                 return (NULL);
 484         }
 485         if (make_dataset_handle_common(zhp, &zc) == -1) {
 486                 free(zhp);
 487                 zhp = NULL;
 488         }
 489         zcmd_free_nvlists(&zc);
 490         return (zhp);
 491 }
 492 
 493 zfs_handle_t *
 494 make_dataset_handle_zc(libzfs_handle_t *hdl, zfs_cmd_t *zc)
 495 {
 496         zfs_handle_t *zhp = calloc(sizeof (zfs_handle_t), 1);
 497 
 498         if (zhp == NULL)
 499                 return (NULL);
 500 
 501         zhp->zfs_hdl = hdl;
 502         (void) strlcpy(zhp->zfs_name, zc->zc_name, sizeof (zhp->zfs_name));
 503         if (make_dataset_handle_common(zhp, zc) == -1) {
 504                 free(zhp);
 505                 return (NULL);
 506         }
 507         return (zhp);
 508 }
 509 
 510 zfs_handle_t *
 511 make_dataset_simple_handle_zc(zfs_handle_t *pzhp, zfs_cmd_t *zc)
 512 {
 513         zfs_handle_t *zhp = calloc(sizeof (zfs_handle_t), 1);
 514 
 515         if (zhp == NULL)
 516                 return (NULL);
 517 
 518         zhp->zfs_hdl = pzhp->zfs_hdl;
 519         (void) strlcpy(zhp->zfs_name, zc->zc_name, sizeof (zhp->zfs_name));
 520         zhp->zfs_head_type = pzhp->zfs_type;
 521         zhp->zfs_type = ZFS_TYPE_SNAPSHOT;
 522         zhp->zpool_hdl = zpool_handle(zhp);
 523         return (zhp);
 524 }
 525 
 526 zfs_handle_t *
 527 zfs_handle_dup(zfs_handle_t *zhp_orig)
 528 {
 529         zfs_handle_t *zhp = calloc(sizeof (zfs_handle_t), 1);
 530 
 531         if (zhp == NULL)
 532                 return (NULL);
 533 
 534         zhp->zfs_hdl = zhp_orig->zfs_hdl;
 535         zhp->zpool_hdl = zhp_orig->zpool_hdl;
 536         (void) strlcpy(zhp->zfs_name, zhp_orig->zfs_name,
 537             sizeof (zhp->zfs_name));
 538         zhp->zfs_type = zhp_orig->zfs_type;
 539         zhp->zfs_head_type = zhp_orig->zfs_head_type;
 540         zhp->zfs_dmustats = zhp_orig->zfs_dmustats;
 541         if (zhp_orig->zfs_props != NULL) {
 542                 if (nvlist_dup(zhp_orig->zfs_props, &zhp->zfs_props, 0) != 0) {
 543                         (void) no_memory(zhp->zfs_hdl);
 544                         zfs_close(zhp);
 545                         return (NULL);
 546                 }
 547         }
 548         if (zhp_orig->zfs_user_props != NULL) {
 549                 if (nvlist_dup(zhp_orig->zfs_user_props,
 550                     &zhp->zfs_user_props, 0) != 0) {
 551                         (void) no_memory(zhp->zfs_hdl);
 552                         zfs_close(zhp);
 553                         return (NULL);
 554                 }
 555         }
 556         if (zhp_orig->zfs_recvd_props != NULL) {
 557                 if (nvlist_dup(zhp_orig->zfs_recvd_props,
 558                     &zhp->zfs_recvd_props, 0)) {
 559                         (void) no_memory(zhp->zfs_hdl);
 560                         zfs_close(zhp);
 561                         return (NULL);
 562                 }
 563         }
 564         zhp->zfs_mntcheck = zhp_orig->zfs_mntcheck;
 565         if (zhp_orig->zfs_mntopts != NULL) {
 566                 zhp->zfs_mntopts = zfs_strdup(zhp_orig->zfs_hdl,
 567                     zhp_orig->zfs_mntopts);
 568         }
 569         zhp->zfs_props_table = zhp_orig->zfs_props_table;
 570         return (zhp);
 571 }
 572 
 573 boolean_t
 574 zfs_bookmark_exists(const char *path)
 575 {
 576         nvlist_t *bmarks;
 577         nvlist_t *props;
 578         char fsname[ZFS_MAX_DATASET_NAME_LEN];
 579         char *bmark_name;
 580         char *pound;
 581         int err;
 582         boolean_t rv;
 583 
 584 
 585         (void) strlcpy(fsname, path, sizeof (fsname));
 586         pound = strchr(fsname, '#');
 587         if (pound == NULL)
 588                 return (B_FALSE);
 589 
 590         *pound = '\0';
 591         bmark_name = pound + 1;
 592         props = fnvlist_alloc();
 593         err = lzc_get_bookmarks(fsname, props, &bmarks);
 594         nvlist_free(props);
 595         if (err != 0) {
 596                 nvlist_free(bmarks);
 597                 return (B_FALSE);
 598         }
 599 
 600         rv = nvlist_exists(bmarks, bmark_name);
 601         nvlist_free(bmarks);
 602         return (rv);
 603 }
 604 
 605 zfs_handle_t *
 606 make_bookmark_handle(zfs_handle_t *parent, const char *path,
 607     nvlist_t *bmark_props)
 608 {
 609         zfs_handle_t *zhp = calloc(sizeof (zfs_handle_t), 1);
 610 
 611         if (zhp == NULL)
 612                 return (NULL);
 613 
 614         /* Fill in the name. */
 615         zhp->zfs_hdl = parent->zfs_hdl;
 616         (void) strlcpy(zhp->zfs_name, path, sizeof (zhp->zfs_name));
 617 
 618         /* Set the property lists. */
 619         if (nvlist_dup(bmark_props, &zhp->zfs_props, 0) != 0) {
 620                 free(zhp);
 621                 return (NULL);
 622         }
 623 
 624         /* Set the types. */
 625         zhp->zfs_head_type = parent->zfs_head_type;
 626         zhp->zfs_type = ZFS_TYPE_BOOKMARK;
 627 
 628         if ((zhp->zpool_hdl = zpool_handle(zhp)) == NULL) {
 629                 nvlist_free(zhp->zfs_props);
 630                 free(zhp);
 631                 return (NULL);
 632         }
 633 
 634         return (zhp);
 635 }
 636 
 637 struct zfs_open_bookmarks_cb_data {
 638         const char *path;
 639         zfs_handle_t *zhp;
 640 };
 641 
 642 static int
 643 zfs_open_bookmarks_cb(zfs_handle_t *zhp, void *data)
 644 {
 645         struct zfs_open_bookmarks_cb_data *dp = data;
 646 
 647         /*
 648          * Is it the one we are looking for?
 649          */
 650         if (strcmp(dp->path, zfs_get_name(zhp)) == 0) {
 651                 /*
 652                  * We found it.  Save it and let the caller know we are done.
 653                  */
 654                 dp->zhp = zhp;
 655                 return (EEXIST);
 656         }
 657 
 658         /*
 659          * Not found.  Close the handle and ask for another one.
 660          */
 661         zfs_close(zhp);
 662         return (0);
 663 }
 664 
 665 /*
 666  * Opens the given snapshot, bookmark, filesystem, or volume.   The 'types'
 667  * argument is a mask of acceptable types.  The function will print an
 668  * appropriate error message and return NULL if it can't be opened.
 669  */
 670 zfs_handle_t *
 671 zfs_open(libzfs_handle_t *hdl, const char *path, int types)
 672 {
 673         zfs_handle_t *zhp;
 674         char errbuf[1024];
 675         char *bookp;
 676 
 677         (void) snprintf(errbuf, sizeof (errbuf),
 678             dgettext(TEXT_DOMAIN, "cannot open '%s'"), path);
 679 
 680         /*
 681          * Validate the name before we even try to open it.
 682          */
 683         if (!zfs_validate_name(hdl, path, types, B_FALSE)) {
 684                 (void) zfs_error(hdl, EZFS_INVALIDNAME, errbuf);
 685                 return (NULL);
 686         }
 687 
 688         /*
 689          * Bookmarks needs to be handled separately.
 690          */
 691         bookp = strchr(path, '#');
 692         if (bookp == NULL) {
 693                 /*
 694                  * Try to get stats for the dataset, which will tell us if it
 695                  * exists.
 696                  */
 697                 errno = 0;
 698                 if ((zhp = make_dataset_handle(hdl, path)) == NULL) {
 699                         (void) zfs_standard_error(hdl, errno, errbuf);
 700                         return (NULL);
 701                 }
 702         } else {
 703                 char dsname[ZFS_MAX_DATASET_NAME_LEN];
 704                 zfs_handle_t *pzhp;
 705                 struct zfs_open_bookmarks_cb_data cb_data = {path, NULL};
 706 
 707                 /*
 708                  * We need to cut out '#' and everything after '#'
 709                  * to get the parent dataset name only.
 710                  */
 711                 assert(bookp - path < sizeof (dsname));
 712                 (void) strncpy(dsname, path, bookp - path);
 713                 dsname[bookp - path] = '\0';
 714 
 715                 /*
 716                  * Create handle for the parent dataset.
 717                  */
 718                 errno = 0;
 719                 if ((pzhp = make_dataset_handle(hdl, dsname)) == NULL) {
 720                         (void) zfs_standard_error(hdl, errno, errbuf);
 721                         return (NULL);
 722                 }
 723 
 724                 /*
 725                  * Iterate bookmarks to find the right one.
 726                  */
 727                 errno = 0;
 728                 if ((zfs_iter_bookmarks(pzhp, zfs_open_bookmarks_cb,
 729                     &cb_data) == 0) && (cb_data.zhp == NULL)) {
 730                         (void) zfs_error(hdl, EZFS_NOENT, errbuf);
 731                         zfs_close(pzhp);
 732                         return (NULL);
 733                 }
 734                 if (cb_data.zhp == NULL) {
 735                         (void) zfs_standard_error(hdl, errno, errbuf);
 736                         zfs_close(pzhp);
 737                         return (NULL);
 738                 }
 739                 zhp = cb_data.zhp;
 740 
 741                 /*
 742                  * Cleanup.
 743                  */
 744                 zfs_close(pzhp);
 745         }
 746 
 747         if (!(types & zhp->zfs_type)) {
 748                 (void) zfs_error(hdl, EZFS_BADTYPE, errbuf);
 749                 zfs_close(zhp);
 750                 return (NULL);
 751         }
 752 
 753         return (zhp);
 754 }
 755 
 756 /*
 757  * Release a ZFS handle.  Nothing to do but free the associated memory.
 758  */
 759 void
 760 zfs_close(zfs_handle_t *zhp)
 761 {
 762         if (zhp->zfs_mntopts)
 763                 free(zhp->zfs_mntopts);
 764         nvlist_free(zhp->zfs_props);
 765         nvlist_free(zhp->zfs_user_props);
 766         nvlist_free(zhp->zfs_recvd_props);
 767         free(zhp);
 768 }
 769 
 770 typedef struct mnttab_node {
 771         struct mnttab mtn_mt;
 772         avl_node_t mtn_node;
 773 } mnttab_node_t;
 774 
 775 static int
 776 libzfs_mnttab_cache_compare(const void *arg1, const void *arg2)
 777 {
 778         const mnttab_node_t *mtn1 = (const mnttab_node_t *)arg1;
 779         const mnttab_node_t *mtn2 = (const mnttab_node_t *)arg2;
 780         int rv;
 781 
 782         rv = strcmp(mtn1->mtn_mt.mnt_special, mtn2->mtn_mt.mnt_special);
 783 
 784         if (rv == 0)
 785                 return (0);
 786         return (rv > 0 ? 1 : -1);
 787 }
 788 
 789 void
 790 libzfs_mnttab_init(libzfs_handle_t *hdl)
 791 {
 792         (void) mutex_init(&hdl->libzfs_mnttab_cache_lock,
 793             LOCK_NORMAL | LOCK_ERRORCHECK, NULL);
 794         assert(avl_numnodes(&hdl->libzfs_mnttab_cache) == 0);
 795         avl_create(&hdl->libzfs_mnttab_cache, libzfs_mnttab_cache_compare,
 796             sizeof (mnttab_node_t), offsetof(mnttab_node_t, mtn_node));
 797 }
 798 
 799 void
 800 libzfs_mnttab_update(libzfs_handle_t *hdl)
 801 {
 802         struct mnttab entry;
 803 
 804         rewind(hdl->libzfs_mnttab);
 805         while (getmntent(hdl->libzfs_mnttab, &entry) == 0) {
 806                 mnttab_node_t *mtn;
 807 
 808                 if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0)
 809                         continue;
 810                 mtn = zfs_alloc(hdl, sizeof (mnttab_node_t));
 811                 mtn->mtn_mt.mnt_special = zfs_strdup(hdl, entry.mnt_special);
 812                 mtn->mtn_mt.mnt_mountp = zfs_strdup(hdl, entry.mnt_mountp);
 813                 mtn->mtn_mt.mnt_fstype = zfs_strdup(hdl, entry.mnt_fstype);
 814                 mtn->mtn_mt.mnt_mntopts = zfs_strdup(hdl, entry.mnt_mntopts);
 815                 avl_add(&hdl->libzfs_mnttab_cache, mtn);
 816         }
 817 }
 818 
 819 void
 820 libzfs_mnttab_fini(libzfs_handle_t *hdl)
 821 {
 822         void *cookie = NULL;
 823         mnttab_node_t *mtn;
 824 
 825         while ((mtn = avl_destroy_nodes(&hdl->libzfs_mnttab_cache, &cookie))
 826             != NULL) {
 827                 free(mtn->mtn_mt.mnt_special);
 828                 free(mtn->mtn_mt.mnt_mountp);
 829                 free(mtn->mtn_mt.mnt_fstype);
 830                 free(mtn->mtn_mt.mnt_mntopts);
 831                 free(mtn);
 832         }
 833         avl_destroy(&hdl->libzfs_mnttab_cache);
 834         (void) mutex_destroy(&hdl->libzfs_mnttab_cache_lock);
 835 }
 836 
 837 void
 838 libzfs_mnttab_cache(libzfs_handle_t *hdl, boolean_t enable)
 839 {
 840         hdl->libzfs_mnttab_enable = enable;
 841 }
 842 
 843 int
 844 libzfs_mnttab_find(libzfs_handle_t *hdl, const char *fsname,
 845     struct mnttab *entry)
 846 {
 847         mnttab_node_t find;
 848         mnttab_node_t *mtn;
 849         int ret = ENOENT;
 850 
 851         if (!hdl->libzfs_mnttab_enable) {
 852                 struct mnttab srch = { 0 };
 853 
 854                 if (avl_numnodes(&hdl->libzfs_mnttab_cache))
 855                         libzfs_mnttab_fini(hdl);
 856                 rewind(hdl->libzfs_mnttab);
 857                 srch.mnt_special = (char *)fsname;
 858                 srch.mnt_fstype = MNTTYPE_ZFS;
 859                 if (getmntany(hdl->libzfs_mnttab, entry, &srch) == 0)
 860                         return (0);
 861                 else
 862                         return (ENOENT);
 863         }
 864 
 865         mutex_enter(&hdl->libzfs_mnttab_cache_lock);
 866         if (avl_numnodes(&hdl->libzfs_mnttab_cache) == 0)
 867                 libzfs_mnttab_update(hdl);
 868 
 869         find.mtn_mt.mnt_special = (char *)fsname;
 870         mtn = avl_find(&hdl->libzfs_mnttab_cache, &find, NULL);
 871         if (mtn) {
 872                 *entry = mtn->mtn_mt;
 873                 ret = 0;
 874         }
 875         mutex_exit(&hdl->libzfs_mnttab_cache_lock);
 876         return (ret);
 877 }
 878 
 879 void
 880 libzfs_mnttab_add(libzfs_handle_t *hdl, const char *special,
 881     const char *mountp, const char *mntopts)
 882 {
 883         mnttab_node_t *mtn;
 884 
 885         mutex_enter(&hdl->libzfs_mnttab_cache_lock);
 886         if (avl_numnodes(&hdl->libzfs_mnttab_cache) != 0) {
 887                 mtn = zfs_alloc(hdl, sizeof (mnttab_node_t));
 888                 mtn->mtn_mt.mnt_special = zfs_strdup(hdl, special);
 889                 mtn->mtn_mt.mnt_mountp = zfs_strdup(hdl, mountp);
 890                 mtn->mtn_mt.mnt_fstype = zfs_strdup(hdl, MNTTYPE_ZFS);
 891                 mtn->mtn_mt.mnt_mntopts = zfs_strdup(hdl, mntopts);
 892                 avl_add(&hdl->libzfs_mnttab_cache, mtn);
 893         }
 894         mutex_exit(&hdl->libzfs_mnttab_cache_lock);
 895 }
 896 
 897 void
 898 libzfs_mnttab_remove(libzfs_handle_t *hdl, const char *fsname)
 899 {
 900         mnttab_node_t find;
 901         mnttab_node_t *ret;
 902 
 903         mutex_enter(&hdl->libzfs_mnttab_cache_lock);
 904         find.mtn_mt.mnt_special = (char *)fsname;
 905         if ((ret = avl_find(&hdl->libzfs_mnttab_cache, (void *)&find, NULL))
 906             != NULL) {
 907                 avl_remove(&hdl->libzfs_mnttab_cache, ret);
 908                 free(ret->mtn_mt.mnt_special);
 909                 free(ret->mtn_mt.mnt_mountp);
 910                 free(ret->mtn_mt.mnt_fstype);
 911                 free(ret->mtn_mt.mnt_mntopts);
 912                 free(ret);
 913         }
 914         mutex_exit(&hdl->libzfs_mnttab_cache_lock);
 915 }
 916 
 917 int
 918 zfs_spa_version(zfs_handle_t *zhp, int *spa_version)
 919 {
 920         zpool_handle_t *zpool_handle = zhp->zpool_hdl;
 921 
 922         if (zpool_handle == NULL)
 923                 return (-1);
 924 
 925         *spa_version = zpool_get_prop_int(zpool_handle,
 926             ZPOOL_PROP_VERSION, NULL);
 927         return (0);
 928 }
 929 
 930 /*
 931  * The choice of reservation property depends on the SPA version.
 932  */
 933 static int
 934 zfs_which_resv_prop(zfs_handle_t *zhp, zfs_prop_t *resv_prop)
 935 {
 936         int spa_version;
 937 
 938         if (zfs_spa_version(zhp, &spa_version) < 0)
 939                 return (-1);
 940 
 941         if (spa_version >= SPA_VERSION_REFRESERVATION)
 942                 *resv_prop = ZFS_PROP_REFRESERVATION;
 943         else
 944                 *resv_prop = ZFS_PROP_RESERVATION;
 945 
 946         return (0);
 947 }
 948 
 949 /*
 950  * Given an nvlist of properties to set, validates that they are correct, and
 951  * parses any numeric properties (index, boolean, etc) if they are specified as
 952  * strings.
 953  */
 954 nvlist_t *
 955 zfs_valid_proplist(libzfs_handle_t *hdl, zfs_type_t type, nvlist_t *nvl,
 956     uint64_t zoned, zfs_handle_t *zhp, zpool_handle_t *zpool_hdl,
 957     boolean_t key_params_ok, const char *errbuf)
 958 {
 959         nvpair_t *elem;
 960         uint64_t intval;
 961         char *strval;
 962         zfs_prop_t prop;
 963         nvlist_t *ret;
 964         int chosen_normal = -1;
 965         int chosen_utf = -1;
 966 
 967         if (nvlist_alloc(&ret, NV_UNIQUE_NAME, 0) != 0) {
 968                 (void) no_memory(hdl);
 969                 return (NULL);
 970         }
 971 
 972         /*
 973          * Make sure this property is valid and applies to this type.
 974          */
 975 
 976         elem = NULL;
 977         while ((elem = nvlist_next_nvpair(nvl, elem)) != NULL) {
 978                 const char *propname = nvpair_name(elem);
 979 
 980                 prop = zfs_name_to_prop(propname);
 981                 if (prop == ZPROP_INVAL && zfs_prop_user(propname)) {
 982                         /*
 983                          * This is a user property: make sure it's a
 984                          * string, and that it's less than ZAP_MAXNAMELEN.
 985                          */
 986                         if (nvpair_type(elem) != DATA_TYPE_STRING) {
 987                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
 988                                     "'%s' must be a string"), propname);
 989                                 (void) zfs_error(hdl, EZFS_BADPROP, errbuf);
 990                                 goto error;
 991                         }
 992 
 993                         if (strlen(nvpair_name(elem)) >= ZAP_MAXNAMELEN) {
 994                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
 995                                     "property name '%s' is too long"),
 996                                     propname);
 997                                 (void) zfs_error(hdl, EZFS_BADPROP, errbuf);
 998                                 goto error;
 999                         }
1000 
1001                         (void) nvpair_value_string(elem, &strval);
1002                         if (nvlist_add_string(ret, propname, strval) != 0) {
1003                                 (void) no_memory(hdl);
1004                                 goto error;
1005                         }
1006                         continue;
1007                 }
1008 
1009                 /*
1010                  * Currently, only user properties can be modified on
1011                  * snapshots.
1012                  */
1013                 if (type == ZFS_TYPE_SNAPSHOT) {
1014                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1015                             "this property can not be modified for snapshots"));
1016                         (void) zfs_error(hdl, EZFS_PROPTYPE, errbuf);
1017                         goto error;
1018                 }
1019 
1020                 if (prop == ZPROP_INVAL && zfs_prop_userquota(propname)) {
1021                         zfs_userquota_prop_t uqtype;
1022                         char newpropname[128];
1023                         char domain[128];
1024                         uint64_t rid;
1025                         uint64_t valary[3];
1026 
1027                         if (userquota_propname_decode(propname, zoned,
1028                             &uqtype, domain, sizeof (domain), &rid) != 0) {
1029                                 zfs_error_aux(hdl,
1030                                     dgettext(TEXT_DOMAIN,
1031                                     "'%s' has an invalid user/group name"),
1032                                     propname);
1033                                 (void) zfs_error(hdl, EZFS_BADPROP, errbuf);
1034                                 goto error;
1035                         }
1036 
1037                         if (uqtype != ZFS_PROP_USERQUOTA &&
1038                             uqtype != ZFS_PROP_GROUPQUOTA &&
1039                             uqtype != ZFS_PROP_USEROBJQUOTA &&
1040                             uqtype != ZFS_PROP_GROUPOBJQUOTA &&
1041                             uqtype != ZFS_PROP_PROJECTQUOTA &&
1042                             uqtype != ZFS_PROP_PROJECTOBJQUOTA) {
1043                                 zfs_error_aux(hdl,
1044                                     dgettext(TEXT_DOMAIN, "'%s' is readonly"),
1045                                     propname);
1046                                 (void) zfs_error(hdl, EZFS_PROPREADONLY,
1047                                     errbuf);
1048                                 goto error;
1049                         }
1050 
1051                         if (nvpair_type(elem) == DATA_TYPE_STRING) {
1052                                 (void) nvpair_value_string(elem, &strval);
1053                                 if (strcmp(strval, "none") == 0) {
1054                                         intval = 0;
1055                                 } else if (zfs_nicestrtonum(hdl,
1056                                     strval, &intval) != 0) {
1057                                         (void) zfs_error(hdl,
1058                                             EZFS_BADPROP, errbuf);
1059                                         goto error;
1060                                 }
1061                         } else if (nvpair_type(elem) ==
1062                             DATA_TYPE_UINT64) {
1063                                 (void) nvpair_value_uint64(elem, &intval);
1064                                 if (intval == 0) {
1065                                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1066                                             "use 'none' to disable "
1067                                             "{user|group|project}quota"));
1068                                         goto error;
1069                                 }
1070                         } else {
1071                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1072                                     "'%s' must be a number"), propname);
1073                                 (void) zfs_error(hdl, EZFS_BADPROP, errbuf);
1074                                 goto error;
1075                         }
1076 
1077                         /*
1078                          * Encode the prop name as
1079                          * userquota@<hex-rid>-domain, to make it easy
1080                          * for the kernel to decode.
1081                          */
1082                         (void) snprintf(newpropname, sizeof (newpropname),
1083                             "%s%llx-%s", zfs_userquota_prop_prefixes[uqtype],
1084                             (longlong_t)rid, domain);
1085                         valary[0] = uqtype;
1086                         valary[1] = rid;
1087                         valary[2] = intval;
1088                         if (nvlist_add_uint64_array(ret, newpropname,
1089                             valary, 3) != 0) {
1090                                 (void) no_memory(hdl);
1091                                 goto error;
1092                         }
1093                         continue;
1094                 } else if (prop == ZPROP_INVAL && zfs_prop_written(propname)) {
1095                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1096                             "'%s' is readonly"),
1097                             propname);
1098                         (void) zfs_error(hdl, EZFS_PROPREADONLY, errbuf);
1099                         goto error;
1100                 }
1101 
1102                 if (prop == ZPROP_INVAL) {
1103                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1104                             "invalid property '%s'"), propname);
1105                         (void) zfs_error(hdl, EZFS_BADPROP, errbuf);
1106                         goto error;
1107                 }
1108 
1109                 if (!zfs_prop_valid_for_type(prop, type)) {
1110                         zfs_error_aux(hdl,
1111                             dgettext(TEXT_DOMAIN, "'%s' does not "
1112                             "apply to datasets of this type"), propname);
1113                         (void) zfs_error(hdl, EZFS_PROPTYPE, errbuf);
1114                         goto error;
1115                 }
1116 
1117                 if (zfs_prop_readonly(prop) &&
1118                     !(zfs_prop_setonce(prop) && zhp == NULL) &&
1119                     !(zfs_prop_encryption_key_param(prop) && key_params_ok)) {
1120                         zfs_error_aux(hdl,
1121                             dgettext(TEXT_DOMAIN, "'%s' is readonly"),
1122                             propname);
1123                         (void) zfs_error(hdl, EZFS_PROPREADONLY, errbuf);
1124                         goto error;
1125                 }
1126 
1127                 if (zprop_parse_value(hdl, elem, prop, type, ret,
1128                     &strval, &intval, errbuf) != 0)
1129                         goto error;
1130 
1131                 /*
1132                  * Perform some additional checks for specific properties.
1133                  */
1134                 switch (prop) {
1135                 case ZFS_PROP_VERSION:
1136                 {
1137                         int version;
1138 
1139                         if (zhp == NULL)
1140                                 break;
1141                         version = zfs_prop_get_int(zhp, ZFS_PROP_VERSION);
1142                         if (intval < version) {
1143                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1144                                     "Can not downgrade; already at version %u"),
1145                                     version);
1146                                 (void) zfs_error(hdl, EZFS_BADPROP, errbuf);
1147                                 goto error;
1148                         }
1149                         break;
1150                 }
1151 
1152                 case ZFS_PROP_VOLBLOCKSIZE:
1153                 case ZFS_PROP_RECORDSIZE:
1154                 {
1155                         int maxbs = SPA_MAXBLOCKSIZE;
1156                         if (zpool_hdl != NULL) {
1157                                 maxbs = zpool_get_prop_int(zpool_hdl,
1158                                     ZPOOL_PROP_MAXBLOCKSIZE, NULL);
1159                         }
1160                         /*
1161                          * Volumes are limited to a volblocksize of 128KB,
1162                          * because they typically service workloads with
1163                          * small random writes, which incur a large performance
1164                          * penalty with large blocks.
1165                          */
1166                         if (prop == ZFS_PROP_VOLBLOCKSIZE)
1167                                 maxbs = SPA_OLD_MAXBLOCKSIZE;
1168                         /*
1169                          * The value must be a power of two between
1170                          * SPA_MINBLOCKSIZE and maxbs.
1171                          */
1172                         if (intval < SPA_MINBLOCKSIZE ||
1173                             intval > maxbs || !ISP2(intval)) {
1174                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1175                                     "'%s' must be power of 2 from 512B "
1176                                     "to %uKB"), propname, maxbs >> 10);
1177                                 (void) zfs_error(hdl, EZFS_BADPROP, errbuf);
1178                                 goto error;
1179                         }
1180                         break;
1181                 }
1182 
1183                 case ZFS_PROP_SPECIAL_SMALL_BLOCKS:
1184                         if (zpool_hdl != NULL) {
1185                                 char state[64] = "";
1186 
1187                                 /*
1188                                  * Issue a warning but do not fail so that
1189                                  * tests for setable properties succeed.
1190                                  */
1191                                 if (zpool_prop_get_feature(zpool_hdl,
1192                                     "feature@allocation_classes", state,
1193                                     sizeof (state)) != 0 ||
1194                                     strcmp(state, ZFS_FEATURE_ACTIVE) != 0) {
1195                                         (void) fprintf(stderr, gettext(
1196                                             "%s: property requires a special "
1197                                             "device in the pool\n"), propname);
1198                                 }
1199                         }
1200                         if (intval != 0 &&
1201                             (intval < SPA_MINBLOCKSIZE ||
1202                             intval > SPA_OLD_MAXBLOCKSIZE || !ISP2(intval))) {
1203                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1204                                     "invalid '%s=%d' property: must be zero or "
1205                                     "a power of 2 from 512B to 128K"), propname,
1206                                     intval);
1207                                 (void) zfs_error(hdl, EZFS_BADPROP, errbuf);
1208                                 goto error;
1209                         }
1210                         break;
1211 
1212                 case ZFS_PROP_MLSLABEL:
1213                 {
1214                         /*
1215                          * Verify the mlslabel string and convert to
1216                          * internal hex label string.
1217                          */
1218 
1219                         m_label_t *new_sl;
1220                         char *hex = NULL;       /* internal label string */
1221 
1222                         /* Default value is already OK. */
1223                         if (strcasecmp(strval, ZFS_MLSLABEL_DEFAULT) == 0)
1224                                 break;
1225 
1226                         /* Verify the label can be converted to binary form */
1227                         if (((new_sl = m_label_alloc(MAC_LABEL)) == NULL) ||
1228                             (str_to_label(strval, &new_sl, MAC_LABEL,
1229                             L_NO_CORRECTION, NULL) == -1)) {
1230                                 goto badlabel;
1231                         }
1232 
1233                         /* Now translate to hex internal label string */
1234                         if (label_to_str(new_sl, &hex, M_INTERNAL,
1235                             DEF_NAMES) != 0) {
1236                                 if (hex)
1237                                         free(hex);
1238                                 goto badlabel;
1239                         }
1240                         m_label_free(new_sl);
1241 
1242                         /* If string is already in internal form, we're done. */
1243                         if (strcmp(strval, hex) == 0) {
1244                                 free(hex);
1245                                 break;
1246                         }
1247 
1248                         /* Replace the label string with the internal form. */
1249                         (void) nvlist_remove(ret, zfs_prop_to_name(prop),
1250                             DATA_TYPE_STRING);
1251                         verify(nvlist_add_string(ret, zfs_prop_to_name(prop),
1252                             hex) == 0);
1253                         free(hex);
1254 
1255                         break;
1256 
1257 badlabel:
1258                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1259                             "invalid mlslabel '%s'"), strval);
1260                         (void) zfs_error(hdl, EZFS_BADPROP, errbuf);
1261                         m_label_free(new_sl);   /* OK if null */
1262                         goto error;
1263 
1264                 }
1265 
1266                 case ZFS_PROP_MOUNTPOINT:
1267                 {
1268                         namecheck_err_t why;
1269 
1270                         if (strcmp(strval, ZFS_MOUNTPOINT_NONE) == 0 ||
1271                             strcmp(strval, ZFS_MOUNTPOINT_LEGACY) == 0)
1272                                 break;
1273 
1274                         if (mountpoint_namecheck(strval, &why)) {
1275                                 switch (why) {
1276                                 case NAME_ERR_LEADING_SLASH:
1277                                         zfs_error_aux(hdl,
1278                                             dgettext(TEXT_DOMAIN,
1279                                             "'%s' must be an absolute path, "
1280                                             "'none', or 'legacy'"), propname);
1281                                         break;
1282                                 case NAME_ERR_TOOLONG:
1283                                         zfs_error_aux(hdl,
1284                                             dgettext(TEXT_DOMAIN,
1285                                             "component of '%s' is too long"),
1286                                             propname);
1287                                         break;
1288 
1289                                 default:
1290                                         zfs_error_aux(hdl,
1291                                             dgettext(TEXT_DOMAIN,
1292                                             "(%d) not defined"),
1293                                             why);
1294                                         break;
1295                                 }
1296                                 (void) zfs_error(hdl, EZFS_BADPROP, errbuf);
1297                                 goto error;
1298                         }
1299                 }
1300 
1301                         /*FALLTHRU*/
1302 
1303                 case ZFS_PROP_SHARESMB:
1304                 case ZFS_PROP_SHARENFS:
1305                         /*
1306                          * For the mountpoint and sharenfs or sharesmb
1307                          * properties, check if it can be set in a
1308                          * global/non-global zone based on
1309                          * the zoned property value:
1310                          *
1311                          *              global zone         non-global zone
1312                          * --------------------------------------------------
1313                          * zoned=on     mountpoint (no)     mountpoint (yes)
1314                          *              sharenfs (no)       sharenfs (no)
1315                          *              sharesmb (no)       sharesmb (no)
1316                          *
1317                          * zoned=off    mountpoint (yes)        N/A
1318                          *              sharenfs (yes)
1319                          *              sharesmb (yes)
1320                          */
1321                         if (zoned) {
1322                                 if (getzoneid() == GLOBAL_ZONEID) {
1323                                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1324                                             "'%s' cannot be set on "
1325                                             "dataset in a non-global zone"),
1326                                             propname);
1327                                         (void) zfs_error(hdl, EZFS_ZONED,
1328                                             errbuf);
1329                                         goto error;
1330                                 } else if (prop == ZFS_PROP_SHARENFS ||
1331                                     prop == ZFS_PROP_SHARESMB) {
1332                                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1333                                             "'%s' cannot be set in "
1334                                             "a non-global zone"), propname);
1335                                         (void) zfs_error(hdl, EZFS_ZONED,
1336                                             errbuf);
1337                                         goto error;
1338                                 }
1339                         } else if (getzoneid() != GLOBAL_ZONEID) {
1340                                 /*
1341                                  * If zoned property is 'off', this must be in
1342                                  * a global zone. If not, something is wrong.
1343                                  */
1344                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1345                                     "'%s' cannot be set while dataset "
1346                                     "'zoned' property is set"), propname);
1347                                 (void) zfs_error(hdl, EZFS_ZONED, errbuf);
1348                                 goto error;
1349                         }
1350 
1351                         /*
1352                          * At this point, it is legitimate to set the
1353                          * property. Now we want to make sure that the
1354                          * property value is valid if it is sharenfs.
1355                          */
1356                         if ((prop == ZFS_PROP_SHARENFS ||
1357                             prop == ZFS_PROP_SHARESMB) &&
1358                             strcmp(strval, "on") != 0 &&
1359                             strcmp(strval, "off") != 0) {
1360                                 zfs_share_proto_t proto;
1361 
1362                                 if (prop == ZFS_PROP_SHARESMB)
1363                                         proto = PROTO_SMB;
1364                                 else
1365                                         proto = PROTO_NFS;
1366 
1367                                 /*
1368                                  * Must be an valid sharing protocol
1369                                  * option string so init the libshare
1370                                  * in order to enable the parser and
1371                                  * then parse the options. We use the
1372                                  * control API since we don't care about
1373                                  * the current configuration and don't
1374                                  * want the overhead of loading it
1375                                  * until we actually do something.
1376                                  */
1377 
1378                                 if (zfs_init_libshare(hdl,
1379                                     SA_INIT_CONTROL_API) != SA_OK) {
1380                                         /*
1381                                          * An error occurred so we can't do
1382                                          * anything
1383                                          */
1384                                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1385                                             "'%s' cannot be set: problem "
1386                                             "in share initialization"),
1387                                             propname);
1388                                         (void) zfs_error(hdl, EZFS_BADPROP,
1389                                             errbuf);
1390                                         goto error;
1391                                 }
1392 
1393                                 if (zfs_parse_options(strval, proto) != SA_OK) {
1394                                         /*
1395                                          * There was an error in parsing so
1396                                          * deal with it by issuing an error
1397                                          * message and leaving after
1398                                          * uninitializing the the libshare
1399                                          * interface.
1400                                          */
1401                                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1402                                             "'%s' cannot be set to invalid "
1403                                             "options"), propname);
1404                                         (void) zfs_error(hdl, EZFS_BADPROP,
1405                                             errbuf);
1406                                         zfs_uninit_libshare(hdl);
1407                                         goto error;
1408                                 }
1409                                 zfs_uninit_libshare(hdl);
1410                         }
1411 
1412                         break;
1413 
1414                 case ZFS_PROP_KEYLOCATION:
1415                         if (!zfs_prop_valid_keylocation(strval, B_FALSE)) {
1416                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1417                                     "invalid keylocation"));
1418                                 (void) zfs_error(hdl, EZFS_BADPROP, errbuf);
1419                                 goto error;
1420                         }
1421 
1422                         if (zhp != NULL) {
1423                                 uint64_t crypt =
1424                                     zfs_prop_get_int(zhp, ZFS_PROP_ENCRYPTION);
1425 
1426                                 if (crypt == ZIO_CRYPT_OFF &&
1427                                     strcmp(strval, "none") != 0) {
1428                                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1429                                             "keylocation must be 'none' "
1430                                             "for unencrypted datasets"));
1431                                         (void) zfs_error(hdl, EZFS_BADPROP,
1432                                             errbuf);
1433                                         goto error;
1434                                 } else if (crypt != ZIO_CRYPT_OFF &&
1435                                     strcmp(strval, "none") == 0) {
1436                                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1437                                             "keylocation must not be 'none' "
1438                                             "for encrypted datasets"));
1439                                         (void) zfs_error(hdl, EZFS_BADPROP,
1440                                             errbuf);
1441                                         goto error;
1442                                 }
1443                         }
1444                         break;
1445 
1446                 case ZFS_PROP_PBKDF2_ITERS:
1447                         if (intval < MIN_PBKDF2_ITERATIONS) {
1448                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1449                                     "minimum pbkdf2 iterations is %u"),
1450                                     MIN_PBKDF2_ITERATIONS);
1451                                 (void) zfs_error(hdl, EZFS_BADPROP, errbuf);
1452                                 goto error;
1453                         }
1454                         break;
1455 
1456                 case ZFS_PROP_UTF8ONLY:
1457                         chosen_utf = (int)intval;
1458                         break;
1459 
1460                 case ZFS_PROP_NORMALIZE:
1461                         chosen_normal = (int)intval;
1462                         break;
1463 
1464                 default:
1465                         break;
1466                 }
1467 
1468                 /*
1469                  * For changes to existing volumes, we have some additional
1470                  * checks to enforce.
1471                  */
1472                 if (type == ZFS_TYPE_VOLUME && zhp != NULL) {
1473                         uint64_t volsize = zfs_prop_get_int(zhp,
1474                             ZFS_PROP_VOLSIZE);
1475                         uint64_t blocksize = zfs_prop_get_int(zhp,
1476                             ZFS_PROP_VOLBLOCKSIZE);
1477                         char buf[64];
1478 
1479                         switch (prop) {
1480                         case ZFS_PROP_RESERVATION:
1481                                 if (intval > volsize) {
1482                                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1483                                             "'%s' is greater than current "
1484                                             "volume size"), propname);
1485                                         (void) zfs_error(hdl, EZFS_BADPROP,
1486                                             errbuf);
1487                                         goto error;
1488                                 }
1489                                 break;
1490 
1491                         case ZFS_PROP_REFRESERVATION:
1492                                 if (intval > volsize && intval != UINT64_MAX) {
1493                                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1494                                             "'%s' is greater than current "
1495                                             "volume size"), propname);
1496                                         (void) zfs_error(hdl, EZFS_BADPROP,
1497                                             errbuf);
1498                                         goto error;
1499                                 }
1500                                 break;
1501 
1502                         case ZFS_PROP_VOLSIZE:
1503                                 if (intval % blocksize != 0) {
1504                                         zfs_nicenum(blocksize, buf,
1505                                             sizeof (buf));
1506                                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1507                                             "'%s' must be a multiple of "
1508                                             "volume block size (%s)"),
1509                                             propname, buf);
1510                                         (void) zfs_error(hdl, EZFS_BADPROP,
1511                                             errbuf);
1512                                         goto error;
1513                                 }
1514 
1515                                 if (intval == 0) {
1516                                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1517                                             "'%s' cannot be zero"),
1518                                             propname);
1519                                         (void) zfs_error(hdl, EZFS_BADPROP,
1520                                             errbuf);
1521                                         goto error;
1522                                 }
1523                                 break;
1524 
1525                         default:
1526                                 break;
1527                         }
1528                 }
1529 
1530                 /* check encryption properties */
1531                 if (zhp != NULL) {
1532                         int64_t crypt = zfs_prop_get_int(zhp,
1533                             ZFS_PROP_ENCRYPTION);
1534 
1535                         switch (prop) {
1536                         case ZFS_PROP_COPIES:
1537                                 if (crypt != ZIO_CRYPT_OFF && intval > 2) {
1538                                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1539                                             "encrypted datasets cannot have "
1540                                             "3 copies"));
1541                                         (void) zfs_error(hdl, EZFS_BADPROP,
1542                                             errbuf);
1543                                         goto error;
1544                                 }
1545                                 break;
1546                         default:
1547                                 break;
1548                         }
1549                 }
1550         }
1551 
1552         /*
1553          * If normalization was chosen, but no UTF8 choice was made,
1554          * enforce rejection of non-UTF8 names.
1555          *
1556          * If normalization was chosen, but rejecting non-UTF8 names
1557          * was explicitly not chosen, it is an error.
1558          */
1559         if (chosen_normal > 0 && chosen_utf < 0) {
1560                 if (nvlist_add_uint64(ret,
1561                     zfs_prop_to_name(ZFS_PROP_UTF8ONLY), 1) != 0) {
1562                         (void) no_memory(hdl);
1563                         goto error;
1564                 }
1565         } else if (chosen_normal > 0 && chosen_utf == 0) {
1566                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1567                     "'%s' must be set 'on' if normalization chosen"),
1568                     zfs_prop_to_name(ZFS_PROP_UTF8ONLY));
1569                 (void) zfs_error(hdl, EZFS_BADPROP, errbuf);
1570                 goto error;
1571         }
1572         return (ret);
1573 
1574 error:
1575         nvlist_free(ret);
1576         return (NULL);
1577 }
1578 
1579 int
1580 zfs_add_synthetic_resv(zfs_handle_t *zhp, nvlist_t *nvl)
1581 {
1582         uint64_t old_volsize;
1583         uint64_t new_volsize;
1584         uint64_t old_reservation;
1585         uint64_t new_reservation;
1586         zfs_prop_t resv_prop;
1587         nvlist_t *props;
1588         zpool_handle_t *zph = zpool_handle(zhp);
1589 
1590         /*
1591          * If this is an existing volume, and someone is setting the volsize,
1592          * make sure that it matches the reservation, or add it if necessary.
1593          */
1594         old_volsize = zfs_prop_get_int(zhp, ZFS_PROP_VOLSIZE);
1595         if (zfs_which_resv_prop(zhp, &resv_prop) < 0)
1596                 return (-1);
1597         old_reservation = zfs_prop_get_int(zhp, resv_prop);
1598 
1599         props = fnvlist_alloc();
1600         fnvlist_add_uint64(props, zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE),
1601             zfs_prop_get_int(zhp, ZFS_PROP_VOLBLOCKSIZE));
1602 
1603         if ((zvol_volsize_to_reservation(zph, old_volsize, props) !=
1604             old_reservation) || nvlist_exists(nvl,
1605             zfs_prop_to_name(resv_prop))) {
1606                 fnvlist_free(props);
1607                 return (0);
1608         }
1609         if (nvlist_lookup_uint64(nvl, zfs_prop_to_name(ZFS_PROP_VOLSIZE),
1610             &new_volsize) != 0) {
1611                 fnvlist_free(props);
1612                 return (-1);
1613         }
1614         new_reservation = zvol_volsize_to_reservation(zph, new_volsize, props);
1615         fnvlist_free(props);
1616 
1617         if (nvlist_add_uint64(nvl, zfs_prop_to_name(resv_prop),
1618             new_reservation) != 0) {
1619                 (void) no_memory(zhp->zfs_hdl);
1620                 return (-1);
1621         }
1622         return (1);
1623 }
1624 
1625 /*
1626  * Helper for 'zfs {set|clone} refreservation=auto'.  Must be called after
1627  * zfs_valid_proplist(), as it is what sets the UINT64_MAX sentinal value.
1628  * Return codes must match zfs_add_synthetic_resv().
1629  */
1630 static int
1631 zfs_fix_auto_resv(zfs_handle_t *zhp, nvlist_t *nvl)
1632 {
1633         uint64_t volsize;
1634         uint64_t resvsize;
1635         zfs_prop_t prop;
1636         nvlist_t *props;
1637 
1638         if (!ZFS_IS_VOLUME(zhp)) {
1639                 return (0);
1640         }
1641 
1642         if (zfs_which_resv_prop(zhp, &prop) != 0) {
1643                 return (-1);
1644         }
1645 
1646         if (prop != ZFS_PROP_REFRESERVATION) {
1647                 return (0);
1648         }
1649 
1650         if (nvlist_lookup_uint64(nvl, zfs_prop_to_name(prop), &resvsize) != 0) {
1651                 /* No value being set, so it can't be "auto" */
1652                 return (0);
1653         }
1654         if (resvsize != UINT64_MAX) {
1655                 /* Being set to a value other than "auto" */
1656                 return (0);
1657         }
1658 
1659         props = fnvlist_alloc();
1660 
1661         fnvlist_add_uint64(props, zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE),
1662             zfs_prop_get_int(zhp, ZFS_PROP_VOLBLOCKSIZE));
1663 
1664         if (nvlist_lookup_uint64(nvl, zfs_prop_to_name(ZFS_PROP_VOLSIZE),
1665             &volsize) != 0) {
1666                 volsize = zfs_prop_get_int(zhp, ZFS_PROP_VOLSIZE);
1667         }
1668 
1669         resvsize = zvol_volsize_to_reservation(zpool_handle(zhp), volsize,
1670             props);
1671         fnvlist_free(props);
1672 
1673         (void) nvlist_remove_all(nvl, zfs_prop_to_name(prop));
1674         if (nvlist_add_uint64(nvl, zfs_prop_to_name(prop), resvsize) != 0) {
1675                 (void) no_memory(zhp->zfs_hdl);
1676                 return (-1);
1677         }
1678         return (1);
1679 }
1680 
1681 void
1682 zfs_setprop_error(libzfs_handle_t *hdl, zfs_prop_t prop, int err,
1683     char *errbuf)
1684 {
1685         switch (err) {
1686 
1687         case ENOSPC:
1688                 /*
1689                  * For quotas and reservations, ENOSPC indicates
1690                  * something different; setting a quota or reservation
1691                  * doesn't use any disk space.
1692                  */
1693                 switch (prop) {
1694                 case ZFS_PROP_QUOTA:
1695                 case ZFS_PROP_REFQUOTA:
1696                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1697                             "size is less than current used or "
1698                             "reserved space"));
1699                         (void) zfs_error(hdl, EZFS_PROPSPACE, errbuf);
1700                         break;
1701 
1702                 case ZFS_PROP_RESERVATION:
1703                 case ZFS_PROP_REFRESERVATION:
1704                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1705                             "size is greater than available space"));
1706                         (void) zfs_error(hdl, EZFS_PROPSPACE, errbuf);
1707                         break;
1708 
1709                 default:
1710                         (void) zfs_standard_error(hdl, err, errbuf);
1711                         break;
1712                 }
1713                 break;
1714 
1715         case EBUSY:
1716                 (void) zfs_standard_error(hdl, EBUSY, errbuf);
1717                 break;
1718 
1719         case EROFS:
1720                 (void) zfs_error(hdl, EZFS_DSREADONLY, errbuf);
1721                 break;
1722 
1723         case E2BIG:
1724                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1725                     "property value too long"));
1726                 (void) zfs_error(hdl, EZFS_BADPROP, errbuf);
1727                 break;
1728 
1729         case ENOTSUP:
1730                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1731                     "pool and or dataset must be upgraded to set this "
1732                     "property or value"));
1733                 (void) zfs_error(hdl, EZFS_BADVERSION, errbuf);
1734                 break;
1735 
1736         case ERANGE:
1737                 if (prop == ZFS_PROP_COMPRESSION ||
1738                     prop == ZFS_PROP_RECORDSIZE) {
1739                         (void) zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1740                             "property setting is not allowed on "
1741                             "bootable datasets"));
1742                         (void) zfs_error(hdl, EZFS_NOTSUP, errbuf);
1743                 } else if (prop == ZFS_PROP_CHECKSUM ||
1744                     prop == ZFS_PROP_DEDUP) {
1745                         (void) zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1746                             "property setting is not allowed on "
1747                             "root pools"));
1748                         (void) zfs_error(hdl, EZFS_NOTSUP, errbuf);
1749                 } else {
1750                         (void) zfs_standard_error(hdl, err, errbuf);
1751                 }
1752                 break;
1753 
1754         case EINVAL:
1755                 if (prop == ZPROP_INVAL) {
1756                         (void) zfs_error(hdl, EZFS_BADPROP, errbuf);
1757                 } else {
1758                         (void) zfs_standard_error(hdl, err, errbuf);
1759                 }
1760                 break;
1761 
1762         case EACCES:
1763                 if (prop == ZFS_PROP_KEYLOCATION) {
1764                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1765                             "keylocation may only be set on encryption roots"));
1766                         (void) zfs_error(hdl, EZFS_BADPROP, errbuf);
1767                 } else {
1768                         (void) zfs_standard_error(hdl, err, errbuf);
1769                 }
1770                 break;
1771 
1772         case EOVERFLOW:
1773                 /*
1774                  * This platform can't address a volume this big.
1775                  */
1776 #ifdef _ILP32
1777                 if (prop == ZFS_PROP_VOLSIZE) {
1778                         (void) zfs_error(hdl, EZFS_VOLTOOBIG, errbuf);
1779                         break;
1780                 }
1781 #endif
1782                 /* FALLTHROUGH */
1783         default:
1784                 (void) zfs_standard_error(hdl, err, errbuf);
1785         }
1786 }
1787 
1788 /*
1789  * Given a property name and value, set the property for the given dataset.
1790  */
1791 int
1792 zfs_prop_set(zfs_handle_t *zhp, const char *propname, const char *propval)
1793 {
1794         int ret = -1;
1795         char errbuf[1024];
1796         libzfs_handle_t *hdl = zhp->zfs_hdl;
1797         nvlist_t *nvl = NULL;
1798 
1799         (void) snprintf(errbuf, sizeof (errbuf),
1800             dgettext(TEXT_DOMAIN, "cannot set property for '%s'"),
1801             zhp->zfs_name);
1802 
1803         if (nvlist_alloc(&nvl, NV_UNIQUE_NAME, 0) != 0 ||
1804             nvlist_add_string(nvl, propname, propval) != 0) {
1805                 (void) no_memory(hdl);
1806                 goto error;
1807         }
1808 
1809         ret = zfs_prop_set_list(zhp, nvl);
1810 
1811 error:
1812         nvlist_free(nvl);
1813         return (ret);
1814 }
1815 
1816 
1817 
1818 /*
1819  * Given an nvlist of property names and values, set the properties for the
1820  * given dataset.
1821  */
1822 int
1823 zfs_prop_set_list(zfs_handle_t *zhp, nvlist_t *props)
1824 {
1825         zfs_cmd_t zc = { 0 };
1826         int ret = -1;
1827         prop_changelist_t **cls = NULL;
1828         int cl_idx;
1829         char errbuf[1024];
1830         libzfs_handle_t *hdl = zhp->zfs_hdl;
1831         nvlist_t *nvl;
1832         int nvl_len;
1833         int added_resv = 0;
1834 
1835         (void) snprintf(errbuf, sizeof (errbuf),
1836             dgettext(TEXT_DOMAIN, "cannot set property for '%s'"),
1837             zhp->zfs_name);
1838 
1839         if ((nvl = zfs_valid_proplist(hdl, zhp->zfs_type, props,
1840             zfs_prop_get_int(zhp, ZFS_PROP_ZONED), zhp, zhp->zpool_hdl,
1841             B_FALSE, errbuf)) == NULL)
1842                 goto error;
1843 
1844         /*
1845          * We have to check for any extra properties which need to be added
1846          * before computing the length of the nvlist.
1847          */
1848         for (nvpair_t *elem = nvlist_next_nvpair(nvl, NULL);
1849             elem != NULL;
1850             elem = nvlist_next_nvpair(nvl, elem)) {
1851                 if (zfs_name_to_prop(nvpair_name(elem)) == ZFS_PROP_VOLSIZE &&
1852                     (added_resv = zfs_add_synthetic_resv(zhp, nvl)) == -1) {
1853                         goto error;
1854                 }
1855         }
1856 
1857         if (added_resv != 1 &&
1858             (added_resv = zfs_fix_auto_resv(zhp, nvl)) == -1) {
1859                 goto error;
1860         }
1861 
1862         /*
1863          * Check how many properties we're setting and allocate an array to
1864          * store changelist pointers for postfix().
1865          */
1866         nvl_len = 0;
1867         for (nvpair_t *elem = nvlist_next_nvpair(nvl, NULL);
1868             elem != NULL;
1869             elem = nvlist_next_nvpair(nvl, elem))
1870                 nvl_len++;
1871         if ((cls = calloc(nvl_len, sizeof (prop_changelist_t *))) == NULL)
1872                 goto error;
1873 
1874         cl_idx = 0;
1875         for (nvpair_t *elem = nvlist_next_nvpair(nvl, NULL);
1876             elem != NULL;
1877             elem = nvlist_next_nvpair(nvl, elem)) {
1878 
1879                 zfs_prop_t prop = zfs_name_to_prop(nvpair_name(elem));
1880 
1881                 assert(cl_idx < nvl_len);
1882                 /*
1883                  * We don't want to unmount & remount the dataset when changing
1884                  * its canmount property to 'on' or 'noauto'.  We only use
1885                  * the changelist logic to unmount when setting canmount=off.
1886                  */
1887                 if (prop != ZFS_PROP_CANMOUNT ||
1888                     (fnvpair_value_uint64(elem) == ZFS_CANMOUNT_OFF &&
1889                     zfs_is_mounted(zhp, NULL))) {
1890                         cls[cl_idx] = changelist_gather(zhp, prop, 0, 0);
1891                         if (cls[cl_idx] == NULL)
1892                                 goto error;
1893                 }
1894 
1895                 if (prop == ZFS_PROP_MOUNTPOINT &&
1896                     changelist_haszonedchild(cls[cl_idx])) {
1897                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1898                             "child dataset with inherited mountpoint is used "
1899                             "in a non-global zone"));
1900                         ret = zfs_error(hdl, EZFS_ZONED, errbuf);
1901                         goto error;
1902                 }
1903 
1904                 if (cls[cl_idx] != NULL &&
1905                     (ret = changelist_prefix(cls[cl_idx])) != 0)
1906                         goto error;
1907 
1908                 cl_idx++;
1909         }
1910         assert(cl_idx == nvl_len);
1911 
1912         /*
1913          * Execute the corresponding ioctl() to set this list of properties.
1914          */
1915         (void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
1916 
1917         if ((ret = zcmd_write_src_nvlist(hdl, &zc, nvl)) != 0 ||
1918             (ret = zcmd_alloc_dst_nvlist(hdl, &zc, 0)) != 0)
1919                 goto error;
1920 
1921         ret = zfs_ioctl(hdl, ZFS_IOC_SET_PROP, &zc);
1922 
1923         if (ret != 0) {
1924                 if (zc.zc_nvlist_dst_filled == B_FALSE) {
1925                         (void) zfs_standard_error(hdl, errno, errbuf);
1926                         goto error;
1927                 }
1928 
1929                 /* Get the list of unset properties back and report them. */
1930                 nvlist_t *errorprops = NULL;
1931                 if (zcmd_read_dst_nvlist(hdl, &zc, &errorprops) != 0)
1932                         goto error;
1933                 for (nvpair_t *elem = nvlist_next_nvpair(errorprops, NULL);
1934                     elem != NULL;
1935                     elem = nvlist_next_nvpair(errorprops, elem)) {
1936                         zfs_prop_t prop = zfs_name_to_prop(nvpair_name(elem));
1937                         zfs_setprop_error(hdl, prop, errno, errbuf);
1938                 }
1939                 nvlist_free(errorprops);
1940 
1941                 if (added_resv && errno == ENOSPC) {
1942                         /* clean up the volsize property we tried to set */
1943                         uint64_t old_volsize = zfs_prop_get_int(zhp,
1944                             ZFS_PROP_VOLSIZE);
1945                         nvlist_free(nvl);
1946                         nvl = NULL;
1947                         zcmd_free_nvlists(&zc);
1948 
1949                         if (nvlist_alloc(&nvl, NV_UNIQUE_NAME, 0) != 0)
1950                                 goto error;
1951                         if (nvlist_add_uint64(nvl,
1952                             zfs_prop_to_name(ZFS_PROP_VOLSIZE),
1953                             old_volsize) != 0)
1954                                 goto error;
1955                         if (zcmd_write_src_nvlist(hdl, &zc, nvl) != 0)
1956                                 goto error;
1957                         (void) zfs_ioctl(hdl, ZFS_IOC_SET_PROP, &zc);
1958                 }
1959         } else {
1960                 for (cl_idx = 0; cl_idx < nvl_len; cl_idx++) {
1961                         if (cls[cl_idx] != NULL) {
1962                                 int clp_err = changelist_postfix(cls[cl_idx]);
1963                                 if (clp_err != 0)
1964                                         ret = clp_err;
1965                         }
1966                 }
1967 
1968                 /*
1969                  * Refresh the statistics so the new property value
1970                  * is reflected.
1971                  */
1972                 if (ret == 0)
1973                         (void) get_stats(zhp);
1974         }
1975 
1976 error:
1977         nvlist_free(nvl);
1978         zcmd_free_nvlists(&zc);
1979         if (cls != NULL) {
1980                 for (cl_idx = 0; cl_idx < nvl_len; cl_idx++) {
1981                         if (cls[cl_idx] != NULL)
1982                                 changelist_free(cls[cl_idx]);
1983                 }
1984                 free(cls);
1985         }
1986         return (ret);
1987 }
1988 
1989 /*
1990  * Given a property, inherit the value from the parent dataset, or if received
1991  * is TRUE, revert to the received value, if any.
1992  */
1993 int
1994 zfs_prop_inherit(zfs_handle_t *zhp, const char *propname, boolean_t received)
1995 {
1996         zfs_cmd_t zc = { 0 };
1997         int ret;
1998         prop_changelist_t *cl;
1999         libzfs_handle_t *hdl = zhp->zfs_hdl;
2000         char errbuf[1024];
2001         zfs_prop_t prop;
2002 
2003         (void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
2004             "cannot inherit %s for '%s'"), propname, zhp->zfs_name);
2005 
2006         zc.zc_cookie = received;
2007         if ((prop = zfs_name_to_prop(propname)) == ZPROP_INVAL) {
2008                 /*
2009                  * For user properties, the amount of work we have to do is very
2010                  * small, so just do it here.
2011                  */
2012                 if (!zfs_prop_user(propname)) {
2013                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2014                             "invalid property"));
2015                         return (zfs_error(hdl, EZFS_BADPROP, errbuf));
2016                 }
2017 
2018                 (void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
2019                 (void) strlcpy(zc.zc_value, propname, sizeof (zc.zc_value));
2020 
2021                 if (zfs_ioctl(zhp->zfs_hdl, ZFS_IOC_INHERIT_PROP, &zc) != 0)
2022                         return (zfs_standard_error(hdl, errno, errbuf));
2023 
2024                 return (0);
2025         }
2026 
2027         /*
2028          * Verify that this property is inheritable.
2029          */
2030         if (zfs_prop_readonly(prop))
2031                 return (zfs_error(hdl, EZFS_PROPREADONLY, errbuf));
2032 
2033         if (!zfs_prop_inheritable(prop) && !received)
2034                 return (zfs_error(hdl, EZFS_PROPNONINHERIT, errbuf));
2035 
2036         /*
2037          * Check to see if the value applies to this type
2038          */
2039         if (!zfs_prop_valid_for_type(prop, zhp->zfs_type))
2040                 return (zfs_error(hdl, EZFS_PROPTYPE, errbuf));
2041 
2042         /*
2043          * Normalize the name, to get rid of shorthand abbreviations.
2044          */
2045         propname = zfs_prop_to_name(prop);
2046         (void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
2047         (void) strlcpy(zc.zc_value, propname, sizeof (zc.zc_value));
2048 
2049         if (prop == ZFS_PROP_MOUNTPOINT && getzoneid() == GLOBAL_ZONEID &&
2050             zfs_prop_get_int(zhp, ZFS_PROP_ZONED)) {
2051                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2052                     "dataset is used in a non-global zone"));
2053                 return (zfs_error(hdl, EZFS_ZONED, errbuf));
2054         }
2055 
2056         /*
2057          * Determine datasets which will be affected by this change, if any.
2058          */
2059         if ((cl = changelist_gather(zhp, prop, 0, 0)) == NULL)
2060                 return (-1);
2061 
2062         if (prop == ZFS_PROP_MOUNTPOINT && changelist_haszonedchild(cl)) {
2063                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2064                     "child dataset with inherited mountpoint is used "
2065                     "in a non-global zone"));
2066                 ret = zfs_error(hdl, EZFS_ZONED, errbuf);
2067                 goto error;
2068         }
2069 
2070         if ((ret = changelist_prefix(cl)) != 0)
2071                 goto error;
2072 
2073         if ((ret = zfs_ioctl(zhp->zfs_hdl, ZFS_IOC_INHERIT_PROP, &zc)) != 0) {
2074                 return (zfs_standard_error(hdl, errno, errbuf));
2075         } else {
2076 
2077                 if ((ret = changelist_postfix(cl)) != 0)
2078                         goto error;
2079 
2080                 /*
2081                  * Refresh the statistics so the new property is reflected.
2082                  */
2083                 (void) get_stats(zhp);
2084         }
2085 
2086 error:
2087         changelist_free(cl);
2088         return (ret);
2089 }
2090 
2091 /*
2092  * True DSL properties are stored in an nvlist.  The following two functions
2093  * extract them appropriately.
2094  */
2095 static uint64_t
2096 getprop_uint64(zfs_handle_t *zhp, zfs_prop_t prop, char **source)
2097 {
2098         nvlist_t *nv;
2099         uint64_t value;
2100 
2101         *source = NULL;
2102         if (nvlist_lookup_nvlist(zhp->zfs_props,
2103             zfs_prop_to_name(prop), &nv) == 0) {
2104                 verify(nvlist_lookup_uint64(nv, ZPROP_VALUE, &value) == 0);
2105                 (void) nvlist_lookup_string(nv, ZPROP_SOURCE, source);
2106         } else {
2107                 verify(!zhp->zfs_props_table ||
2108                     zhp->zfs_props_table[prop] == B_TRUE);
2109                 value = zfs_prop_default_numeric(prop);
2110                 *source = "";
2111         }
2112 
2113         return (value);
2114 }
2115 
2116 static const char *
2117 getprop_string(zfs_handle_t *zhp, zfs_prop_t prop, char **source)
2118 {
2119         nvlist_t *nv;
2120         const char *value;
2121 
2122         *source = NULL;
2123         if (nvlist_lookup_nvlist(zhp->zfs_props,
2124             zfs_prop_to_name(prop), &nv) == 0) {
2125                 value = fnvlist_lookup_string(nv, ZPROP_VALUE);
2126                 (void) nvlist_lookup_string(nv, ZPROP_SOURCE, source);
2127         } else {
2128                 verify(!zhp->zfs_props_table ||
2129                     zhp->zfs_props_table[prop] == B_TRUE);
2130                 value = zfs_prop_default_string(prop);
2131                 *source = "";
2132         }
2133 
2134         return (value);
2135 }
2136 
2137 static boolean_t
2138 zfs_is_recvd_props_mode(zfs_handle_t *zhp)
2139 {
2140         return (zhp->zfs_props == zhp->zfs_recvd_props);
2141 }
2142 
2143 static void
2144 zfs_set_recvd_props_mode(zfs_handle_t *zhp, uint64_t *cookie)
2145 {
2146         *cookie = (uint64_t)(uintptr_t)zhp->zfs_props;
2147         zhp->zfs_props = zhp->zfs_recvd_props;
2148 }
2149 
2150 static void
2151 zfs_unset_recvd_props_mode(zfs_handle_t *zhp, uint64_t *cookie)
2152 {
2153         zhp->zfs_props = (nvlist_t *)(uintptr_t)*cookie;
2154         *cookie = 0;
2155 }
2156 
2157 /*
2158  * Internal function for getting a numeric property.  Both zfs_prop_get() and
2159  * zfs_prop_get_int() are built using this interface.
2160  *
2161  * Certain properties can be overridden using 'mount -o'.  In this case, scan
2162  * the contents of the /etc/mnttab entry, searching for the appropriate options.
2163  * If they differ from the on-disk values, report the current values and mark
2164  * the source "temporary".
2165  */
2166 static int
2167 get_numeric_property(zfs_handle_t *zhp, zfs_prop_t prop, zprop_source_t *src,
2168     char **source, uint64_t *val)
2169 {
2170         zfs_cmd_t zc = { 0 };
2171         nvlist_t *zplprops = NULL;
2172         struct mnttab mnt;
2173         char *mntopt_on = NULL;
2174         char *mntopt_off = NULL;
2175         boolean_t received = zfs_is_recvd_props_mode(zhp);
2176 
2177         *source = NULL;
2178 
2179         switch (prop) {
2180         case ZFS_PROP_ATIME:
2181                 mntopt_on = MNTOPT_ATIME;
2182                 mntopt_off = MNTOPT_NOATIME;
2183                 break;
2184 
2185         case ZFS_PROP_DEVICES:
2186                 mntopt_on = MNTOPT_DEVICES;
2187                 mntopt_off = MNTOPT_NODEVICES;
2188                 break;
2189 
2190         case ZFS_PROP_EXEC:
2191                 mntopt_on = MNTOPT_EXEC;
2192                 mntopt_off = MNTOPT_NOEXEC;
2193                 break;
2194 
2195         case ZFS_PROP_READONLY:
2196                 mntopt_on = MNTOPT_RO;
2197                 mntopt_off = MNTOPT_RW;
2198                 break;
2199 
2200         case ZFS_PROP_SETUID:
2201                 mntopt_on = MNTOPT_SETUID;
2202                 mntopt_off = MNTOPT_NOSETUID;
2203                 break;
2204 
2205         case ZFS_PROP_XATTR:
2206                 mntopt_on = MNTOPT_XATTR;
2207                 mntopt_off = MNTOPT_NOXATTR;
2208                 break;
2209 
2210         case ZFS_PROP_NBMAND:
2211                 mntopt_on = MNTOPT_NBMAND;
2212                 mntopt_off = MNTOPT_NONBMAND;
2213                 break;
2214 
2215         default:
2216                 break;
2217         }
2218 
2219         /*
2220          * Because looking up the mount options is potentially expensive
2221          * (iterating over all of /etc/mnttab), we defer its calculation until
2222          * we're looking up a property which requires its presence.
2223          */
2224         if (!zhp->zfs_mntcheck &&
2225             (mntopt_on != NULL || prop == ZFS_PROP_MOUNTED)) {
2226                 libzfs_handle_t *hdl = zhp->zfs_hdl;
2227                 struct mnttab entry;
2228 
2229                 if (libzfs_mnttab_find(hdl, zhp->zfs_name, &entry) == 0) {
2230                         zhp->zfs_mntopts = zfs_strdup(hdl,
2231                             entry.mnt_mntopts);
2232                         if (zhp->zfs_mntopts == NULL)
2233                                 return (-1);
2234                 }
2235 
2236                 zhp->zfs_mntcheck = B_TRUE;
2237         }
2238 
2239         if (zhp->zfs_mntopts == NULL)
2240                 mnt.mnt_mntopts = "";
2241         else
2242                 mnt.mnt_mntopts = zhp->zfs_mntopts;
2243 
2244         switch (prop) {
2245         case ZFS_PROP_ATIME:
2246         case ZFS_PROP_DEVICES:
2247         case ZFS_PROP_EXEC:
2248         case ZFS_PROP_READONLY:
2249         case ZFS_PROP_SETUID:
2250         case ZFS_PROP_XATTR:
2251         case ZFS_PROP_NBMAND:
2252                 *val = getprop_uint64(zhp, prop, source);
2253 
2254                 if (received)
2255                         break;
2256 
2257                 if (hasmntopt(&mnt, mntopt_on) && !*val) {
2258                         *val = B_TRUE;
2259                         if (src)
2260                                 *src = ZPROP_SRC_TEMPORARY;
2261                 } else if (hasmntopt(&mnt, mntopt_off) && *val) {
2262                         *val = B_FALSE;
2263                         if (src)
2264                                 *src = ZPROP_SRC_TEMPORARY;
2265                 }
2266                 break;
2267 
2268         case ZFS_PROP_CANMOUNT:
2269         case ZFS_PROP_VOLSIZE:
2270         case ZFS_PROP_QUOTA:
2271         case ZFS_PROP_REFQUOTA:
2272         case ZFS_PROP_RESERVATION:
2273         case ZFS_PROP_REFRESERVATION:
2274         case ZFS_PROP_FILESYSTEM_LIMIT:
2275         case ZFS_PROP_SNAPSHOT_LIMIT:
2276         case ZFS_PROP_FILESYSTEM_COUNT:
2277         case ZFS_PROP_SNAPSHOT_COUNT:
2278                 *val = getprop_uint64(zhp, prop, source);
2279 
2280                 if (*source == NULL) {
2281                         /* not default, must be local */
2282                         *source = zhp->zfs_name;
2283                 }
2284                 break;
2285 
2286         case ZFS_PROP_MOUNTED:
2287                 *val = (zhp->zfs_mntopts != NULL);
2288                 break;
2289 
2290         case ZFS_PROP_NUMCLONES:
2291                 *val = zhp->zfs_dmustats.dds_num_clones;
2292                 break;
2293 
2294         case ZFS_PROP_VERSION:
2295         case ZFS_PROP_NORMALIZE:
2296         case ZFS_PROP_UTF8ONLY:
2297         case ZFS_PROP_CASE:
2298                 if (!zfs_prop_valid_for_type(prop, zhp->zfs_head_type) ||
2299                     zcmd_alloc_dst_nvlist(zhp->zfs_hdl, &zc, 0) != 0)
2300                         return (-1);
2301                 (void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
2302                 if (zfs_ioctl(zhp->zfs_hdl, ZFS_IOC_OBJSET_ZPLPROPS, &zc)) {
2303                         zcmd_free_nvlists(&zc);
2304                         return (-1);
2305                 }
2306                 if (zcmd_read_dst_nvlist(zhp->zfs_hdl, &zc, &zplprops) != 0 ||
2307                     nvlist_lookup_uint64(zplprops, zfs_prop_to_name(prop),
2308                     val) != 0) {
2309                         zcmd_free_nvlists(&zc);
2310                         return (-1);
2311                 }
2312                 nvlist_free(zplprops);
2313                 zcmd_free_nvlists(&zc);
2314                 break;
2315 
2316         case ZFS_PROP_INCONSISTENT:
2317                 *val = zhp->zfs_dmustats.dds_inconsistent;
2318                 break;
2319 
2320         default:
2321                 switch (zfs_prop_get_type(prop)) {
2322                 case PROP_TYPE_NUMBER:
2323                 case PROP_TYPE_INDEX:
2324                         *val = getprop_uint64(zhp, prop, source);
2325                         /*
2326                          * If we tried to use a default value for a
2327                          * readonly property, it means that it was not
2328                          * present.  Note this only applies to "truly"
2329                          * readonly properties, not set-once properties
2330                          * like volblocksize.
2331                          */
2332                         if (zfs_prop_readonly(prop) &&
2333                             !zfs_prop_setonce(prop) &&
2334                             *source != NULL && (*source)[0] == '\0') {
2335                                 *source = NULL;
2336                                 return (-1);
2337                         }
2338                         break;
2339 
2340                 case PROP_TYPE_STRING:
2341                 default:
2342                         zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
2343                             "cannot get non-numeric property"));
2344                         return (zfs_error(zhp->zfs_hdl, EZFS_BADPROP,
2345                             dgettext(TEXT_DOMAIN, "internal error")));
2346                 }
2347         }
2348 
2349         return (0);
2350 }
2351 
2352 /*
2353  * Calculate the source type, given the raw source string.
2354  */
2355 static void
2356 get_source(zfs_handle_t *zhp, zprop_source_t *srctype, char *source,
2357     char *statbuf, size_t statlen)
2358 {
2359         if (statbuf == NULL || *srctype == ZPROP_SRC_TEMPORARY)
2360                 return;
2361 
2362         if (source == NULL) {
2363                 *srctype = ZPROP_SRC_NONE;
2364         } else if (source[0] == '\0') {
2365                 *srctype = ZPROP_SRC_DEFAULT;
2366         } else if (strstr(source, ZPROP_SOURCE_VAL_RECVD) != NULL) {
2367                 *srctype = ZPROP_SRC_RECEIVED;
2368         } else {
2369                 if (strcmp(source, zhp->zfs_name) == 0) {
2370                         *srctype = ZPROP_SRC_LOCAL;
2371                 } else {
2372                         (void) strlcpy(statbuf, source, statlen);
2373                         *srctype = ZPROP_SRC_INHERITED;
2374                 }
2375         }
2376 
2377 }
2378 
2379 int
2380 zfs_prop_get_recvd(zfs_handle_t *zhp, const char *propname, char *propbuf,
2381     size_t proplen, boolean_t literal)
2382 {
2383         zfs_prop_t prop;
2384         int err = 0;
2385 
2386         if (zhp->zfs_recvd_props == NULL)
2387                 if (get_recvd_props_ioctl(zhp) != 0)
2388                         return (-1);
2389 
2390         prop = zfs_name_to_prop(propname);
2391 
2392         if (prop != ZPROP_INVAL) {
2393                 uint64_t cookie;
2394                 if (!nvlist_exists(zhp->zfs_recvd_props, propname))
2395                         return (-1);
2396                 zfs_set_recvd_props_mode(zhp, &cookie);
2397                 err = zfs_prop_get(zhp, prop, propbuf, proplen,
2398                     NULL, NULL, 0, literal);
2399                 zfs_unset_recvd_props_mode(zhp, &cookie);
2400         } else {
2401                 nvlist_t *propval;
2402                 char *recvdval;
2403                 if (nvlist_lookup_nvlist(zhp->zfs_recvd_props,
2404                     propname, &propval) != 0)
2405                         return (-1);
2406                 verify(nvlist_lookup_string(propval, ZPROP_VALUE,
2407                     &recvdval) == 0);
2408                 (void) strlcpy(propbuf, recvdval, proplen);
2409         }
2410 
2411         return (err == 0 ? 0 : -1);
2412 }
2413 
2414 static int
2415 get_clones_string(zfs_handle_t *zhp, char *propbuf, size_t proplen)
2416 {
2417         nvlist_t *value;
2418         nvpair_t *pair;
2419 
2420         value = zfs_get_clones_nvl(zhp);
2421         if (value == NULL)
2422                 return (-1);
2423 
2424         propbuf[0] = '\0';
2425         for (pair = nvlist_next_nvpair(value, NULL); pair != NULL;
2426             pair = nvlist_next_nvpair(value, pair)) {
2427                 if (propbuf[0] != '\0')
2428                         (void) strlcat(propbuf, ",", proplen);
2429                 (void) strlcat(propbuf, nvpair_name(pair), proplen);
2430         }
2431 
2432         return (0);
2433 }
2434 
2435 struct get_clones_arg {
2436         uint64_t numclones;
2437         nvlist_t *value;
2438         const char *origin;
2439         char buf[ZFS_MAX_DATASET_NAME_LEN];
2440 };
2441 
2442 int
2443 get_clones_cb(zfs_handle_t *zhp, void *arg)
2444 {
2445         struct get_clones_arg *gca = arg;
2446 
2447         if (gca->numclones == 0) {
2448                 zfs_close(zhp);
2449                 return (0);
2450         }
2451 
2452         if (zfs_prop_get(zhp, ZFS_PROP_ORIGIN, gca->buf, sizeof (gca->buf),
2453             NULL, NULL, 0, B_TRUE) != 0)
2454                 goto out;
2455         if (strcmp(gca->buf, gca->origin) == 0) {
2456                 fnvlist_add_boolean(gca->value, zfs_get_name(zhp));
2457                 gca->numclones--;
2458         }
2459 
2460 out:
2461         (void) zfs_iter_children(zhp, get_clones_cb, gca);
2462         zfs_close(zhp);
2463         return (0);
2464 }
2465 
2466 nvlist_t *
2467 zfs_get_clones_nvl(zfs_handle_t *zhp)
2468 {
2469         nvlist_t *nv, *value;
2470 
2471         if (nvlist_lookup_nvlist(zhp->zfs_props,
2472             zfs_prop_to_name(ZFS_PROP_CLONES), &nv) != 0) {
2473                 struct get_clones_arg gca;
2474 
2475                 /*
2476                  * if this is a snapshot, then the kernel wasn't able
2477                  * to get the clones.  Do it by slowly iterating.
2478                  */
2479                 if (zhp->zfs_type != ZFS_TYPE_SNAPSHOT)
2480                         return (NULL);
2481                 if (nvlist_alloc(&nv, NV_UNIQUE_NAME, 0) != 0)
2482                         return (NULL);
2483                 if (nvlist_alloc(&value, NV_UNIQUE_NAME, 0) != 0) {
2484                         nvlist_free(nv);
2485                         return (NULL);
2486                 }
2487 
2488                 gca.numclones = zfs_prop_get_int(zhp, ZFS_PROP_NUMCLONES);
2489                 gca.value = value;
2490                 gca.origin = zhp->zfs_name;
2491 
2492                 if (gca.numclones != 0) {
2493                         zfs_handle_t *root;
2494                         char pool[ZFS_MAX_DATASET_NAME_LEN];
2495                         char *cp = pool;
2496 
2497                         /* get the pool name */
2498                         (void) strlcpy(pool, zhp->zfs_name, sizeof (pool));
2499                         (void) strsep(&cp, "/@");
2500                         root = zfs_open(zhp->zfs_hdl, pool,
2501                             ZFS_TYPE_FILESYSTEM);
2502 
2503                         (void) get_clones_cb(root, &gca);
2504                 }
2505 
2506                 if (gca.numclones != 0 ||
2507                     nvlist_add_nvlist(nv, ZPROP_VALUE, value) != 0 ||
2508                     nvlist_add_nvlist(zhp->zfs_props,
2509                     zfs_prop_to_name(ZFS_PROP_CLONES), nv) != 0) {
2510                         nvlist_free(nv);
2511                         nvlist_free(value);
2512                         return (NULL);
2513                 }
2514                 nvlist_free(nv);
2515                 nvlist_free(value);
2516                 verify(0 == nvlist_lookup_nvlist(zhp->zfs_props,
2517                     zfs_prop_to_name(ZFS_PROP_CLONES), &nv));
2518         }
2519 
2520         verify(nvlist_lookup_nvlist(nv, ZPROP_VALUE, &value) == 0);
2521 
2522         return (value);
2523 }
2524 
2525 /*
2526  * Accepts a property and value and checks that the value
2527  * matches the one found by the channel program. If they are
2528  * not equal, print both of them.
2529  */
2530 void
2531 zcp_check(zfs_handle_t *zhp, zfs_prop_t prop, uint64_t intval,
2532     const char *strval)
2533 {
2534         if (!zhp->zfs_hdl->libzfs_prop_debug)
2535                 return;
2536         int error;
2537         char *poolname = zhp->zpool_hdl->zpool_name;
2538         const char *program =
2539             "args = ...\n"
2540             "ds = args['dataset']\n"
2541             "prop = args['property']\n"
2542             "value, setpoint = zfs.get_prop(ds, prop)\n"
2543             "return {value=value, setpoint=setpoint}\n";
2544         nvlist_t *outnvl;
2545         nvlist_t *retnvl;
2546         nvlist_t *argnvl = fnvlist_alloc();
2547 
2548         fnvlist_add_string(argnvl, "dataset", zhp->zfs_name);
2549         fnvlist_add_string(argnvl, "property", zfs_prop_to_name(prop));
2550 
2551         error = lzc_channel_program_nosync(poolname, program,
2552             10 * 1000 * 1000, 10 * 1024 * 1024, argnvl, &outnvl);
2553 
2554         if (error == 0) {
2555                 retnvl = fnvlist_lookup_nvlist(outnvl, "return");
2556                 if (zfs_prop_get_type(prop) == PROP_TYPE_NUMBER) {
2557                         int64_t ans;
2558                         error = nvlist_lookup_int64(retnvl, "value", &ans);
2559                         if (error != 0) {
2560                                 (void) fprintf(stderr, "zcp check error: %u\n",
2561                                     error);
2562                                 return;
2563                         }
2564                         if (ans != intval) {
2565                                 (void) fprintf(stderr,
2566                                     "%s: zfs found %lld, but zcp found %lld\n",
2567                                     zfs_prop_to_name(prop),
2568                                     (longlong_t)intval, (longlong_t)ans);
2569                         }
2570                 } else {
2571                         char *str_ans;
2572                         error = nvlist_lookup_string(retnvl, "value", &str_ans);
2573                         if (error != 0) {
2574                                 (void) fprintf(stderr, "zcp check error: %u\n",
2575                                     error);
2576                                 return;
2577                         }
2578                         if (strcmp(strval, str_ans) != 0) {
2579                                 (void) fprintf(stderr,
2580                                     "%s: zfs found %s, but zcp found %s\n",
2581                                     zfs_prop_to_name(prop),
2582                                     strval, str_ans);
2583                         }
2584                 }
2585         } else {
2586                 (void) fprintf(stderr,
2587                     "zcp check failed, channel program error: %u\n", error);
2588         }
2589         nvlist_free(argnvl);
2590         nvlist_free(outnvl);
2591 }
2592 
2593 /*
2594  * Retrieve a property from the given object.  If 'literal' is specified, then
2595  * numbers are left as exact values.  Otherwise, numbers are converted to a
2596  * human-readable form.
2597  *
2598  * Returns 0 on success, or -1 on error.
2599  */
2600 int
2601 zfs_prop_get(zfs_handle_t *zhp, zfs_prop_t prop, char *propbuf, size_t proplen,
2602     zprop_source_t *src, char *statbuf, size_t statlen, boolean_t literal)
2603 {
2604         char *source = NULL;
2605         uint64_t val;
2606         const char *str;
2607         const char *strval;
2608         boolean_t received = zfs_is_recvd_props_mode(zhp);
2609 
2610         /*
2611          * Check to see if this property applies to our object
2612          */
2613         if (!zfs_prop_valid_for_type(prop, zhp->zfs_type))
2614                 return (-1);
2615 
2616         if (received && zfs_prop_readonly(prop))
2617                 return (-1);
2618 
2619         if (src)
2620                 *src = ZPROP_SRC_NONE;
2621 
2622         switch (prop) {
2623         case ZFS_PROP_CREATION:
2624                 /*
2625                  * 'creation' is a time_t stored in the statistics.  We convert
2626                  * this into a string unless 'literal' is specified.
2627                  */
2628                 {
2629                         val = getprop_uint64(zhp, prop, &source);
2630                         time_t time = (time_t)val;
2631                         struct tm t;
2632 
2633                         if (literal ||
2634                             localtime_r(&time, &t) == NULL ||
2635                             strftime(propbuf, proplen, "%a %b %e %k:%M %Y",
2636                             &t) == 0)
2637                                 (void) snprintf(propbuf, proplen, "%llu", val);
2638                 }
2639                 zcp_check(zhp, prop, val, NULL);
2640                 break;
2641 
2642         case ZFS_PROP_MOUNTPOINT:
2643                 /*
2644                  * Getting the precise mountpoint can be tricky.
2645                  *
2646                  *  - for 'none' or 'legacy', return those values.
2647                  *  - for inherited mountpoints, we want to take everything
2648                  *    after our ancestor and append it to the inherited value.
2649                  *
2650                  * If the pool has an alternate root, we want to prepend that
2651                  * root to any values we return.
2652                  */
2653 
2654                 str = getprop_string(zhp, prop, &source);
2655 
2656                 if (str[0] == '/') {
2657                         char buf[MAXPATHLEN];
2658                         char *root = buf;
2659                         const char *relpath;
2660 
2661                         /*
2662                          * If we inherit the mountpoint, even from a dataset
2663                          * with a received value, the source will be the path of
2664                          * the dataset we inherit from. If source is
2665                          * ZPROP_SOURCE_VAL_RECVD, the received value is not
2666                          * inherited.
2667                          */
2668                         if (strcmp(source, ZPROP_SOURCE_VAL_RECVD) == 0) {
2669                                 relpath = "";
2670                         } else {
2671                                 relpath = zhp->zfs_name + strlen(source);
2672                                 if (relpath[0] == '/')
2673                                         relpath++;
2674                         }
2675 
2676                         if ((zpool_get_prop(zhp->zpool_hdl,
2677                             ZPOOL_PROP_ALTROOT, buf, MAXPATHLEN, NULL,
2678                             B_FALSE)) || (strcmp(root, "-") == 0))
2679                                 root[0] = '\0';
2680                         /*
2681                          * Special case an alternate root of '/'. This will
2682                          * avoid having multiple leading slashes in the
2683                          * mountpoint path.
2684                          */
2685                         if (strcmp(root, "/") == 0)
2686                                 root++;
2687 
2688                         /*
2689                          * If the mountpoint is '/' then skip over this
2690                          * if we are obtaining either an alternate root or
2691                          * an inherited mountpoint.
2692                          */
2693                         if (str[1] == '\0' && (root[0] != '\0' ||
2694                             relpath[0] != '\0'))
2695                                 str++;
2696 
2697                         if (relpath[0] == '\0')
2698                                 (void) snprintf(propbuf, proplen, "%s%s",
2699                                     root, str);
2700                         else
2701                                 (void) snprintf(propbuf, proplen, "%s%s%s%s",
2702                                     root, str, relpath[0] == '@' ? "" : "/",
2703                                     relpath);
2704                 } else {
2705                         /* 'legacy' or 'none' */
2706                         (void) strlcpy(propbuf, str, proplen);
2707                 }
2708                 zcp_check(zhp, prop, 0, propbuf);
2709                 break;
2710 
2711         case ZFS_PROP_ORIGIN:
2712                 str = getprop_string(zhp, prop, &source);
2713                 if (str == NULL)
2714                         return (-1);
2715                 (void) strlcpy(propbuf, str, proplen);
2716                 zcp_check(zhp, prop, 0, str);
2717                 break;
2718 
2719         case ZFS_PROP_CLONES:
2720                 if (get_clones_string(zhp, propbuf, proplen) != 0)
2721                         return (-1);
2722                 break;
2723 
2724         case ZFS_PROP_QUOTA:
2725         case ZFS_PROP_REFQUOTA:
2726         case ZFS_PROP_RESERVATION:
2727         case ZFS_PROP_REFRESERVATION:
2728 
2729                 if (get_numeric_property(zhp, prop, src, &source, &val) != 0)
2730                         return (-1);
2731                 /*
2732                  * If quota or reservation is 0, we translate this into 'none'
2733                  * (unless literal is set), and indicate that it's the default
2734                  * value.  Otherwise, we print the number nicely and indicate
2735                  * that its set locally.
2736                  */
2737                 if (val == 0) {
2738                         if (literal)
2739                                 (void) strlcpy(propbuf, "0", proplen);
2740                         else
2741                                 (void) strlcpy(propbuf, "none", proplen);
2742                 } else {
2743                         if (literal)
2744                                 (void) snprintf(propbuf, proplen, "%llu",
2745                                     (u_longlong_t)val);
2746                         else
2747                                 zfs_nicenum(val, propbuf, proplen);
2748                 }
2749                 zcp_check(zhp, prop, val, NULL);
2750                 break;
2751 
2752         case ZFS_PROP_FILESYSTEM_LIMIT:
2753         case ZFS_PROP_SNAPSHOT_LIMIT:
2754         case ZFS_PROP_FILESYSTEM_COUNT:
2755         case ZFS_PROP_SNAPSHOT_COUNT:
2756 
2757                 if (get_numeric_property(zhp, prop, src, &source, &val) != 0)
2758                         return (-1);
2759 
2760                 /*
2761                  * If limit is UINT64_MAX, we translate this into 'none' (unless
2762                  * literal is set), and indicate that it's the default value.
2763                  * Otherwise, we print the number nicely and indicate that it's
2764                  * set locally.
2765                  */
2766                 if (literal) {
2767                         (void) snprintf(propbuf, proplen, "%llu",
2768                             (u_longlong_t)val);
2769                 } else if (val == UINT64_MAX) {
2770                         (void) strlcpy(propbuf, "none", proplen);
2771                 } else {
2772                         zfs_nicenum(val, propbuf, proplen);
2773                 }
2774 
2775                 zcp_check(zhp, prop, val, NULL);
2776                 break;
2777 
2778         case ZFS_PROP_REFRATIO:
2779         case ZFS_PROP_COMPRESSRATIO:
2780                 if (get_numeric_property(zhp, prop, src, &source, &val) != 0)
2781                         return (-1);
2782                 (void) snprintf(propbuf, proplen, "%llu.%02llux",
2783                     (u_longlong_t)(val / 100),
2784                     (u_longlong_t)(val % 100));
2785                 zcp_check(zhp, prop, val, NULL);
2786                 break;
2787 
2788         case ZFS_PROP_TYPE:
2789                 switch (zhp->zfs_type) {
2790                 case ZFS_TYPE_FILESYSTEM:
2791                         str = "filesystem";
2792                         break;
2793                 case ZFS_TYPE_VOLUME:
2794                         str = "volume";
2795                         break;
2796                 case ZFS_TYPE_SNAPSHOT:
2797                         str = "snapshot";
2798                         break;
2799                 case ZFS_TYPE_BOOKMARK:
2800                         str = "bookmark";
2801                         break;
2802                 default:
2803                         abort();
2804                 }
2805                 (void) snprintf(propbuf, proplen, "%s", str);
2806                 zcp_check(zhp, prop, 0, propbuf);
2807                 break;
2808 
2809         case ZFS_PROP_MOUNTED:
2810                 /*
2811                  * The 'mounted' property is a pseudo-property that described
2812                  * whether the filesystem is currently mounted.  Even though
2813                  * it's a boolean value, the typical values of "on" and "off"
2814                  * don't make sense, so we translate to "yes" and "no".
2815                  */
2816                 if (get_numeric_property(zhp, ZFS_PROP_MOUNTED,
2817                     src, &source, &val) != 0)
2818                         return (-1);
2819                 if (val)
2820                         (void) strlcpy(propbuf, "yes", proplen);
2821                 else
2822                         (void) strlcpy(propbuf, "no", proplen);
2823                 break;
2824 
2825         case ZFS_PROP_NAME:
2826                 /*
2827                  * The 'name' property is a pseudo-property derived from the
2828                  * dataset name.  It is presented as a real property to simplify
2829                  * consumers.
2830                  */
2831                 (void) strlcpy(propbuf, zhp->zfs_name, proplen);
2832                 zcp_check(zhp, prop, 0, propbuf);
2833                 break;
2834 
2835         case ZFS_PROP_MLSLABEL:
2836                 {
2837                         m_label_t *new_sl = NULL;
2838                         char *ascii = NULL;     /* human readable label */
2839 
2840                         (void) strlcpy(propbuf,
2841                             getprop_string(zhp, prop, &source), proplen);
2842 
2843                         if (literal || (strcasecmp(propbuf,
2844                             ZFS_MLSLABEL_DEFAULT) == 0))
2845                                 break;
2846 
2847                         /*
2848                          * Try to translate the internal hex string to
2849                          * human-readable output.  If there are any
2850                          * problems just use the hex string.
2851                          */
2852 
2853                         if (str_to_label(propbuf, &new_sl, MAC_LABEL,
2854                             L_NO_CORRECTION, NULL) == -1) {
2855                                 m_label_free(new_sl);
2856                                 break;
2857                         }
2858 
2859                         if (label_to_str(new_sl, &ascii, M_LABEL,
2860                             DEF_NAMES) != 0) {
2861                                 if (ascii)
2862                                         free(ascii);
2863                                 m_label_free(new_sl);
2864                                 break;
2865                         }
2866                         m_label_free(new_sl);
2867 
2868                         (void) strlcpy(propbuf, ascii, proplen);
2869                         free(ascii);
2870                 }
2871                 break;
2872 
2873         case ZFS_PROP_GUID:
2874         case ZFS_PROP_CREATETXG:
2875                 /*
2876                  * GUIDs are stored as numbers, but they are identifiers.
2877                  * We don't want them to be pretty printed, because pretty
2878                  * printing mangles the ID into a truncated and useless value.
2879                  */
2880                 if (get_numeric_property(zhp, prop, src, &source, &val) != 0)
2881                         return (-1);
2882                 (void) snprintf(propbuf, proplen, "%llu", (u_longlong_t)val);
2883                 zcp_check(zhp, prop, val, NULL);
2884                 break;
2885 
2886         default:
2887                 switch (zfs_prop_get_type(prop)) {
2888                 case PROP_TYPE_NUMBER:
2889                         if (get_numeric_property(zhp, prop, src,
2890                             &source, &val) != 0) {
2891                                 return (-1);
2892                         }
2893 
2894                         if (literal) {
2895                                 (void) snprintf(propbuf, proplen, "%llu",
2896                                     (u_longlong_t)val);
2897                         } else {
2898                                 zfs_nicenum(val, propbuf, proplen);
2899                         }
2900                         zcp_check(zhp, prop, val, NULL);
2901                         break;
2902 
2903                 case PROP_TYPE_STRING:
2904                         str = getprop_string(zhp, prop, &source);
2905                         if (str == NULL)
2906                                 return (-1);
2907 
2908                         (void) strlcpy(propbuf, str, proplen);
2909                         zcp_check(zhp, prop, 0, str);
2910                         break;
2911 
2912                 case PROP_TYPE_INDEX:
2913                         if (get_numeric_property(zhp, prop, src,
2914                             &source, &val) != 0)
2915                                 return (-1);
2916                         if (zfs_prop_index_to_string(prop, val, &strval) != 0)
2917                                 return (-1);
2918 
2919                         (void) strlcpy(propbuf, strval, proplen);
2920                         zcp_check(zhp, prop, 0, strval);
2921                         break;
2922 
2923                 default:
2924                         abort();
2925                 }
2926         }
2927 
2928         get_source(zhp, src, source, statbuf, statlen);
2929 
2930         return (0);
2931 }
2932 
2933 /*
2934  * Utility function to get the given numeric property.  Does no validation that
2935  * the given property is the appropriate type; should only be used with
2936  * hard-coded property types.
2937  */
2938 uint64_t
2939 zfs_prop_get_int(zfs_handle_t *zhp, zfs_prop_t prop)
2940 {
2941         char *source;
2942         uint64_t val;
2943 
2944         (void) get_numeric_property(zhp, prop, NULL, &source, &val);
2945 
2946         return (val);
2947 }
2948 
2949 int
2950 zfs_prop_set_int(zfs_handle_t *zhp, zfs_prop_t prop, uint64_t val)
2951 {
2952         char buf[64];
2953 
2954         (void) snprintf(buf, sizeof (buf), "%llu", (longlong_t)val);
2955         return (zfs_prop_set(zhp, zfs_prop_to_name(prop), buf));
2956 }
2957 
2958 /*
2959  * Similar to zfs_prop_get(), but returns the value as an integer.
2960  */
2961 int
2962 zfs_prop_get_numeric(zfs_handle_t *zhp, zfs_prop_t prop, uint64_t *value,
2963     zprop_source_t *src, char *statbuf, size_t statlen)
2964 {
2965         char *source;
2966 
2967         /*
2968          * Check to see if this property applies to our object
2969          */
2970         if (!zfs_prop_valid_for_type(prop, zhp->zfs_type)) {
2971                 return (zfs_error_fmt(zhp->zfs_hdl, EZFS_PROPTYPE,
2972                     dgettext(TEXT_DOMAIN, "cannot get property '%s'"),
2973                     zfs_prop_to_name(prop)));
2974         }
2975 
2976         if (src)
2977                 *src = ZPROP_SRC_NONE;
2978 
2979         if (get_numeric_property(zhp, prop, src, &source, value) != 0)
2980                 return (-1);
2981 
2982         get_source(zhp, src, source, statbuf, statlen);
2983 
2984         return (0);
2985 }
2986 
2987 static int
2988 idmap_id_to_numeric_domain_rid(uid_t id, boolean_t isuser,
2989     char **domainp, idmap_rid_t *ridp)
2990 {
2991         idmap_get_handle_t *get_hdl = NULL;
2992         idmap_stat status;
2993         int err = EINVAL;
2994 
2995         if (idmap_get_create(&get_hdl) != IDMAP_SUCCESS)
2996                 goto out;
2997 
2998         if (isuser) {
2999                 err = idmap_get_sidbyuid(get_hdl, id,
3000                     IDMAP_REQ_FLG_USE_CACHE, domainp, ridp, &status);
3001         } else {
3002                 err = idmap_get_sidbygid(get_hdl, id,
3003                     IDMAP_REQ_FLG_USE_CACHE, domainp, ridp, &status);
3004         }
3005         if (err == IDMAP_SUCCESS &&
3006             idmap_get_mappings(get_hdl) == IDMAP_SUCCESS &&
3007             status == IDMAP_SUCCESS)
3008                 err = 0;
3009         else
3010                 err = EINVAL;
3011 out:
3012         if (get_hdl)
3013                 idmap_get_destroy(get_hdl);
3014         return (err);
3015 }
3016 
3017 /*
3018  * convert the propname into parameters needed by kernel
3019  * Eg: userquota@ahrens -> ZFS_PROP_USERQUOTA, "", 126829
3020  * Eg: userused@matt@domain -> ZFS_PROP_USERUSED, "S-1-123-456", 789
3021  * Eg: groupquota@staff -> ZFS_PROP_GROUPQUOTA, "", 1234
3022  * Eg: groupused@staff -> ZFS_PROP_GROUPUSED, "", 1234
3023  * Eg: projectquota@123 -> ZFS_PROP_PROJECTQUOTA, "", 123
3024  * Eg: projectused@789 -> ZFS_PROP_PROJECTUSED, "", 789
3025  */
3026 static int
3027 userquota_propname_decode(const char *propname, boolean_t zoned,
3028     zfs_userquota_prop_t *typep, char *domain, int domainlen, uint64_t *ridp)
3029 {
3030         zfs_userquota_prop_t type;
3031         char *cp;
3032         boolean_t isuser;
3033         boolean_t isgroup;
3034         boolean_t isproject;
3035         struct passwd *pw;
3036         struct group *gr;
3037 
3038         domain[0] = '\0';
3039 
3040         /* Figure out the property type ({user|group|project}{quota|space}) */
3041         for (type = 0; type < ZFS_NUM_USERQUOTA_PROPS; type++) {
3042                 if (strncmp(propname, zfs_userquota_prop_prefixes[type],
3043                     strlen(zfs_userquota_prop_prefixes[type])) == 0)
3044                         break;
3045         }
3046         if (type == ZFS_NUM_USERQUOTA_PROPS)
3047                 return (EINVAL);
3048         *typep = type;
3049 
3050         isuser = (type == ZFS_PROP_USERQUOTA || type == ZFS_PROP_USERUSED ||
3051             type == ZFS_PROP_USEROBJQUOTA ||
3052             type == ZFS_PROP_USEROBJUSED);
3053         isgroup = (type == ZFS_PROP_GROUPQUOTA || type == ZFS_PROP_GROUPUSED ||
3054             type == ZFS_PROP_GROUPOBJQUOTA ||
3055             type == ZFS_PROP_GROUPOBJUSED);
3056         isproject = (type == ZFS_PROP_PROJECTQUOTA ||
3057             type == ZFS_PROP_PROJECTUSED || type == ZFS_PROP_PROJECTOBJQUOTA ||
3058             type == ZFS_PROP_PROJECTOBJUSED);
3059 
3060         cp = strchr(propname, '@') + 1;
3061 
3062         if (isuser && (pw = getpwnam(cp)) != NULL) {
3063                 if (zoned && getzoneid() == GLOBAL_ZONEID)
3064                         return (ENOENT);
3065                 *ridp = pw->pw_uid;
3066         } else if (isgroup && (gr = getgrnam(cp)) != NULL) {
3067                 if (zoned && getzoneid() == GLOBAL_ZONEID)
3068                         return (ENOENT);
3069                 *ridp = gr->gr_gid;
3070         } else if (!isproject && strchr(cp, '@')) {
3071                 /*
3072                  * It's a SID name (eg "user@domain") that needs to be
3073                  * turned into S-1-domainID-RID.
3074                  */
3075                 directory_error_t e;
3076                 char *numericsid = NULL;
3077                 char *end;
3078 
3079                 if (zoned && getzoneid() == GLOBAL_ZONEID)
3080                         return (ENOENT);
3081                 if (isuser) {
3082                         e = directory_sid_from_user_name(NULL,
3083                             cp, &numericsid);
3084                 } else {
3085                         e = directory_sid_from_group_name(NULL,
3086                             cp, &numericsid);
3087                 }
3088                 if (e != NULL) {
3089                         directory_error_free(e);
3090                         return (ENOENT);
3091                 }
3092                 if (numericsid == NULL)
3093                         return (ENOENT);
3094                 cp = numericsid;
3095                 (void) strlcpy(domain, cp, domainlen);
3096                 cp = strrchr(domain, '-');
3097                 *cp = '\0';
3098                 cp++;
3099 
3100                 errno = 0;
3101                 *ridp = strtoull(cp, &end, 10);
3102                 free(numericsid);
3103 
3104                 if (errno != 0 || *end != '\0')
3105                         return (EINVAL);
3106         } else {
3107                 /* It's a user/group/project ID (eg "12345"). */
3108                 char *end;
3109                 uid_t id = strtoul(cp, &end, 10);
3110                 if (*end != '\0')
3111                         return (EINVAL);
3112                 if (id > MAXUID && !isproject) {
3113                         /* It's an ephemeral ID. */
3114                         idmap_rid_t rid;
3115                         char *mapdomain;
3116 
3117                         if (idmap_id_to_numeric_domain_rid(id, isuser,
3118                             &mapdomain, &rid) != 0)
3119                                 return (ENOENT);
3120                         (void) strlcpy(domain, mapdomain, domainlen);
3121                         *ridp = rid;
3122                 } else {
3123                         *ridp = id;
3124                 }
3125         }
3126 
3127         return (0);
3128 }
3129 
3130 static int
3131 zfs_prop_get_userquota_common(zfs_handle_t *zhp, const char *propname,
3132     uint64_t *propvalue, zfs_userquota_prop_t *typep)
3133 {
3134         int err;
3135         zfs_cmd_t zc = { 0 };
3136 
3137         (void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
3138 
3139         err = userquota_propname_decode(propname,
3140             zfs_prop_get_int(zhp, ZFS_PROP_ZONED),
3141             typep, zc.zc_value, sizeof (zc.zc_value), &zc.zc_guid);
3142         zc.zc_objset_type = *typep;
3143         if (err)
3144                 return (err);
3145 
3146         err = ioctl(zhp->zfs_hdl->libzfs_fd, ZFS_IOC_USERSPACE_ONE, &zc);
3147         if (err)
3148                 return (err);
3149 
3150         *propvalue = zc.zc_cookie;
3151         return (0);
3152 }
3153 
3154 int
3155 zfs_prop_get_userquota_int(zfs_handle_t *zhp, const char *propname,
3156     uint64_t *propvalue)
3157 {
3158         zfs_userquota_prop_t type;
3159 
3160         return (zfs_prop_get_userquota_common(zhp, propname, propvalue,
3161             &type));
3162 }
3163 
3164 int
3165 zfs_prop_get_userquota(zfs_handle_t *zhp, const char *propname,
3166     char *propbuf, int proplen, boolean_t literal)
3167 {
3168         int err;
3169         uint64_t propvalue;
3170         zfs_userquota_prop_t type;
3171 
3172         err = zfs_prop_get_userquota_common(zhp, propname, &propvalue,
3173             &type);
3174 
3175         if (err)
3176                 return (err);
3177 
3178         if (literal) {
3179                 (void) snprintf(propbuf, proplen, "%llu", propvalue);
3180         } else if (propvalue == 0 &&
3181             (type == ZFS_PROP_USERQUOTA || type == ZFS_PROP_GROUPQUOTA ||
3182             type == ZFS_PROP_USEROBJQUOTA || type == ZFS_PROP_GROUPOBJQUOTA ||
3183             type == ZFS_PROP_PROJECTQUOTA || ZFS_PROP_PROJECTOBJQUOTA)) {
3184                 (void) strlcpy(propbuf, "none", proplen);
3185         } else if (type == ZFS_PROP_USERQUOTA || type == ZFS_PROP_GROUPQUOTA ||
3186             type == ZFS_PROP_USERUSED || type == ZFS_PROP_GROUPUSED ||
3187             type == ZFS_PROP_PROJECTUSED || type == ZFS_PROP_PROJECTQUOTA) {
3188                 zfs_nicenum(propvalue, propbuf, proplen);
3189         } else {
3190                 zfs_nicenum(propvalue, propbuf, proplen);
3191         }
3192         return (0);
3193 }
3194 
3195 int
3196 zfs_prop_get_written_int(zfs_handle_t *zhp, const char *propname,
3197     uint64_t *propvalue)
3198 {
3199         int err;
3200         zfs_cmd_t zc = { 0 };
3201         const char *snapname;
3202 
3203         (void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
3204 
3205         snapname = strchr(propname, '@') + 1;
3206         if (strchr(snapname, '@')) {
3207                 (void) strlcpy(zc.zc_value, snapname, sizeof (zc.zc_value));
3208         } else {
3209                 /* snapname is the short name, append it to zhp's fsname */
3210                 char *cp;
3211 
3212                 (void) strlcpy(zc.zc_value, zhp->zfs_name,
3213                     sizeof (zc.zc_value));
3214                 cp = strchr(zc.zc_value, '@');
3215                 if (cp != NULL)
3216                         *cp = '\0';
3217                 (void) strlcat(zc.zc_value, "@", sizeof (zc.zc_value));
3218                 (void) strlcat(zc.zc_value, snapname, sizeof (zc.zc_value));
3219         }
3220 
3221         err = ioctl(zhp->zfs_hdl->libzfs_fd, ZFS_IOC_SPACE_WRITTEN, &zc);
3222         if (err)
3223                 return (err);
3224 
3225         *propvalue = zc.zc_cookie;
3226         return (0);
3227 }
3228 
3229 int
3230 zfs_prop_get_written(zfs_handle_t *zhp, const char *propname,
3231     char *propbuf, int proplen, boolean_t literal)
3232 {
3233         int err;
3234         uint64_t propvalue;
3235 
3236         err = zfs_prop_get_written_int(zhp, propname, &propvalue);
3237 
3238         if (err)
3239                 return (err);
3240 
3241         if (literal) {
3242                 (void) snprintf(propbuf, proplen, "%llu", propvalue);
3243         } else {
3244                 zfs_nicenum(propvalue, propbuf, proplen);
3245         }
3246         return (0);
3247 }
3248 
3249 /*
3250  * Returns the name of the given zfs handle.
3251  */
3252 const char *
3253 zfs_get_name(const zfs_handle_t *zhp)
3254 {
3255         return (zhp->zfs_name);
3256 }
3257 
3258 /*
3259  * Returns the name of the parent pool for the given zfs handle.
3260  */
3261 const char *
3262 zfs_get_pool_name(const zfs_handle_t *zhp)
3263 {
3264         return (zhp->zpool_hdl->zpool_name);
3265 }
3266 
3267 /*
3268  * Returns the type of the given zfs handle.
3269  */
3270 zfs_type_t
3271 zfs_get_type(const zfs_handle_t *zhp)
3272 {
3273         return (zhp->zfs_type);
3274 }
3275 
3276 /*
3277  * Is one dataset name a child dataset of another?
3278  *
3279  * Needs to handle these cases:
3280  * Dataset 1    "a/foo"         "a/foo"         "a/foo"         "a/foo"
3281  * Dataset 2    "a/fo"          "a/foobar"      "a/bar/baz"     "a/foo/bar"
3282  * Descendant?  No.             No.             No.             Yes.
3283  */
3284 static boolean_t
3285 is_descendant(const char *ds1, const char *ds2)
3286 {
3287         size_t d1len = strlen(ds1);
3288 
3289         /* ds2 can't be a descendant if it's smaller */
3290         if (strlen(ds2) < d1len)
3291                 return (B_FALSE);
3292 
3293         /* otherwise, compare strings and verify that there's a '/' char */
3294         return (ds2[d1len] == '/' && (strncmp(ds1, ds2, d1len) == 0));
3295 }
3296 
3297 /*
3298  * Given a complete name, return just the portion that refers to the parent.
3299  * Will return -1 if there is no parent (path is just the name of the
3300  * pool).
3301  */
3302 static int
3303 parent_name(const char *path, char *buf, size_t buflen)
3304 {
3305         char *slashp;
3306 
3307         (void) strlcpy(buf, path, buflen);
3308 
3309         if ((slashp = strrchr(buf, '/')) == NULL)
3310                 return (-1);
3311         *slashp = '\0';
3312 
3313         return (0);
3314 }
3315 
3316 int
3317 zfs_parent_name(zfs_handle_t *zhp, char *buf, size_t buflen)
3318 {
3319         return (parent_name(zfs_get_name(zhp), buf, buflen));
3320 }
3321 
3322 /*
3323  * If accept_ancestor is false, then check to make sure that the given path has
3324  * a parent, and that it exists.  If accept_ancestor is true, then find the
3325  * closest existing ancestor for the given path.  In prefixlen return the
3326  * length of already existing prefix of the given path.  We also fetch the
3327  * 'zoned' property, which is used to validate property settings when creating
3328  * new datasets.
3329  */
3330 static int
3331 check_parents(libzfs_handle_t *hdl, const char *path, uint64_t *zoned,
3332     boolean_t accept_ancestor, int *prefixlen)
3333 {
3334         zfs_cmd_t zc = { 0 };
3335         char parent[ZFS_MAX_DATASET_NAME_LEN];
3336         char *slash;
3337         zfs_handle_t *zhp;
3338         char errbuf[1024];
3339         uint64_t is_zoned;
3340 
3341         (void) snprintf(errbuf, sizeof (errbuf),
3342             dgettext(TEXT_DOMAIN, "cannot create '%s'"), path);
3343 
3344         /* get parent, and check to see if this is just a pool */
3345         if (parent_name(path, parent, sizeof (parent)) != 0) {
3346                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3347                     "missing dataset name"));
3348                 return (zfs_error(hdl, EZFS_INVALIDNAME, errbuf));
3349         }
3350 
3351         /* check to see if the pool exists */
3352         if ((slash = strchr(parent, '/')) == NULL)
3353                 slash = parent + strlen(parent);
3354         (void) strncpy(zc.zc_name, parent, slash - parent);
3355         zc.zc_name[slash - parent] = '\0';
3356         if (ioctl(hdl->libzfs_fd, ZFS_IOC_OBJSET_STATS, &zc) != 0 &&
3357             errno == ENOENT) {
3358                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3359                     "no such pool '%s'"), zc.zc_name);
3360                 return (zfs_error(hdl, EZFS_NOENT, errbuf));
3361         }
3362 
3363         /* check to see if the parent dataset exists */
3364         while ((zhp = make_dataset_handle(hdl, parent)) == NULL) {
3365                 if (errno == ENOENT && accept_ancestor) {
3366                         /*
3367                          * Go deeper to find an ancestor, give up on top level.
3368                          */
3369                         if (parent_name(parent, parent, sizeof (parent)) != 0) {
3370                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3371                                     "no such pool '%s'"), zc.zc_name);
3372                                 return (zfs_error(hdl, EZFS_NOENT, errbuf));
3373                         }
3374                 } else if (errno == ENOENT) {
3375                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3376                             "parent does not exist"));
3377                         return (zfs_error(hdl, EZFS_NOENT, errbuf));
3378                 } else
3379                         return (zfs_standard_error(hdl, errno, errbuf));
3380         }
3381 
3382         is_zoned = zfs_prop_get_int(zhp, ZFS_PROP_ZONED);
3383         if (zoned != NULL)
3384                 *zoned = is_zoned;
3385 
3386         /* we are in a non-global zone, but parent is in the global zone */
3387         if (getzoneid() != GLOBAL_ZONEID && !is_zoned) {
3388                 (void) zfs_standard_error(hdl, EPERM, errbuf);
3389                 zfs_close(zhp);
3390                 return (-1);
3391         }
3392 
3393         /* make sure parent is a filesystem */
3394         if (zfs_get_type(zhp) != ZFS_TYPE_FILESYSTEM) {
3395                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3396                     "parent is not a filesystem"));
3397                 (void) zfs_error(hdl, EZFS_BADTYPE, errbuf);
3398                 zfs_close(zhp);
3399                 return (-1);
3400         }
3401 
3402         zfs_close(zhp);
3403         if (prefixlen != NULL)
3404                 *prefixlen = strlen(parent);
3405         return (0);
3406 }
3407 
3408 /*
3409  * Finds whether the dataset of the given type(s) exists.
3410  */
3411 boolean_t
3412 zfs_dataset_exists(libzfs_handle_t *hdl, const char *path, zfs_type_t types)
3413 {
3414         zfs_handle_t *zhp;
3415 
3416         if (!zfs_validate_name(hdl, path, types, B_FALSE))
3417                 return (B_FALSE);
3418 
3419         /*
3420          * Try to get stats for the dataset, which will tell us if it exists.
3421          */
3422         if ((zhp = make_dataset_handle(hdl, path)) != NULL) {
3423                 int ds_type = zhp->zfs_type;
3424 
3425                 zfs_close(zhp);
3426                 if (types & ds_type)
3427                         return (B_TRUE);
3428         }
3429         return (B_FALSE);
3430 }
3431 
3432 /*
3433  * Given a path to 'target', create all the ancestors between
3434  * the prefixlen portion of the path, and the target itself.
3435  * Fail if the initial prefixlen-ancestor does not already exist.
3436  */
3437 int
3438 create_parents(libzfs_handle_t *hdl, char *target, int prefixlen)
3439 {
3440         zfs_handle_t *h;
3441         char *cp;
3442         const char *opname;
3443 
3444         /* make sure prefix exists */
3445         cp = target + prefixlen;
3446         if (*cp != '/') {
3447                 assert(strchr(cp, '/') == NULL);
3448                 h = zfs_open(hdl, target, ZFS_TYPE_FILESYSTEM);
3449         } else {
3450                 *cp = '\0';
3451                 h = zfs_open(hdl, target, ZFS_TYPE_FILESYSTEM);
3452                 *cp = '/';
3453         }
3454         if (h == NULL)
3455                 return (-1);
3456         zfs_close(h);
3457 
3458         /*
3459          * Attempt to create, mount, and share any ancestor filesystems,
3460          * up to the prefixlen-long one.
3461          */
3462         for (cp = target + prefixlen + 1;
3463             (cp = strchr(cp, '/')) != NULL; *cp = '/', cp++) {
3464 
3465                 *cp = '\0';
3466 
3467                 h = make_dataset_handle(hdl, target);
3468                 if (h) {
3469                         /* it already exists, nothing to do here */
3470                         zfs_close(h);
3471                         continue;
3472                 }
3473 
3474                 if (zfs_create(hdl, target, ZFS_TYPE_FILESYSTEM,
3475                     NULL) != 0) {
3476                         opname = dgettext(TEXT_DOMAIN, "create");
3477                         goto ancestorerr;
3478                 }
3479 
3480                 h = zfs_open(hdl, target, ZFS_TYPE_FILESYSTEM);
3481                 if (h == NULL) {
3482                         opname = dgettext(TEXT_DOMAIN, "open");
3483                         goto ancestorerr;
3484                 }
3485 
3486                 if (zfs_mount(h, NULL, 0) != 0) {
3487                         opname = dgettext(TEXT_DOMAIN, "mount");
3488                         goto ancestorerr;
3489                 }
3490 
3491                 if (zfs_share(h) != 0) {
3492                         opname = dgettext(TEXT_DOMAIN, "share");
3493                         goto ancestorerr;
3494                 }
3495 
3496                 zfs_close(h);
3497         }
3498 
3499         return (0);
3500 
3501 ancestorerr:
3502         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3503             "failed to %s ancestor '%s'"), opname, target);
3504         return (-1);
3505 }
3506 
3507 /*
3508  * Creates non-existing ancestors of the given path.
3509  */
3510 int
3511 zfs_create_ancestors(libzfs_handle_t *hdl, const char *path)
3512 {
3513         int prefix;
3514         char *path_copy;
3515         char errbuf[1024];
3516         int rc = 0;
3517 
3518         (void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
3519             "cannot create '%s'"), path);
3520 
3521         /*
3522          * Check that we are not passing the nesting limit
3523          * before we start creating any ancestors.
3524          */
3525         if (dataset_nestcheck(path) != 0) {
3526                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3527                     "maximum name nesting depth exceeded"));
3528                 return (zfs_error(hdl, EZFS_INVALIDNAME, errbuf));
3529         }
3530 
3531         if (check_parents(hdl, path, NULL, B_TRUE, &prefix) != 0)
3532                 return (-1);
3533 
3534         if ((path_copy = strdup(path)) != NULL) {
3535                 rc = create_parents(hdl, path_copy, prefix);
3536                 free(path_copy);
3537         }
3538         if (path_copy == NULL || rc != 0)
3539                 return (-1);
3540 
3541         return (0);
3542 }
3543 
3544 /*
3545  * Create a new filesystem or volume.
3546  */
3547 int
3548 zfs_create(libzfs_handle_t *hdl, const char *path, zfs_type_t type,
3549     nvlist_t *props)
3550 {
3551         int ret;
3552         uint64_t size = 0;
3553         uint64_t blocksize = zfs_prop_default_numeric(ZFS_PROP_VOLBLOCKSIZE);
3554         uint8_t *wkeydata = NULL;
3555         uint_t wkeylen = 0;
3556         char errbuf[1024];
3557         char parent[MAXNAMELEN];
3558         uint64_t zoned;
3559         enum lzc_dataset_type ost;
3560         zpool_handle_t *zpool_handle;
3561 
3562         (void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
3563             "cannot create '%s'"), path);
3564 
3565         /* validate the path, taking care to note the extended error message */
3566         if (!zfs_validate_name(hdl, path, type, B_TRUE))
3567                 return (zfs_error(hdl, EZFS_INVALIDNAME, errbuf));
3568 
3569         if (dataset_nestcheck(path) != 0) {
3570                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3571                     "maximum name nesting depth exceeded"));
3572                 return (zfs_error(hdl, EZFS_INVALIDNAME, errbuf));
3573         }
3574 
3575         /* validate parents exist */
3576         if (check_parents(hdl, path, &zoned, B_FALSE, NULL) != 0)
3577                 return (-1);
3578 
3579         /*
3580          * The failure modes when creating a dataset of a different type over
3581          * one that already exists is a little strange.  In particular, if you
3582          * try to create a dataset on top of an existing dataset, the ioctl()
3583          * will return ENOENT, not EEXIST.  To prevent this from happening, we
3584          * first try to see if the dataset exists.
3585          */
3586         if (zfs_dataset_exists(hdl, path, ZFS_TYPE_DATASET)) {
3587                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3588                     "dataset already exists"));
3589                 return (zfs_error(hdl, EZFS_EXISTS, errbuf));
3590         }
3591 
3592         if (type == ZFS_TYPE_VOLUME)
3593                 ost = LZC_DATSET_TYPE_ZVOL;
3594         else
3595                 ost = LZC_DATSET_TYPE_ZFS;
3596 
3597         /* open zpool handle for prop validation */
3598         char pool_path[ZFS_MAX_DATASET_NAME_LEN];
3599         (void) strlcpy(pool_path, path, sizeof (pool_path));
3600 
3601         /* truncate pool_path at first slash */
3602         char *p = strchr(pool_path, '/');
3603         if (p != NULL)
3604                 *p = '\0';
3605 
3606         if ((zpool_handle = zpool_open(hdl, pool_path)) == NULL)
3607                 return (-1);
3608 
3609         if (props && (props = zfs_valid_proplist(hdl, type, props,
3610             zoned, NULL, zpool_handle, B_TRUE, errbuf)) == 0) {
3611                 zpool_close(zpool_handle);
3612                 return (-1);
3613         }
3614         zpool_close(zpool_handle);
3615 
3616         if (type == ZFS_TYPE_VOLUME) {
3617                 /*
3618                  * If we are creating a volume, the size and block size must
3619                  * satisfy a few restraints.  First, the blocksize must be a
3620                  * valid block size between SPA_{MIN,MAX}BLOCKSIZE.  Second, the
3621                  * volsize must be a multiple of the block size, and cannot be
3622                  * zero.
3623                  */
3624                 if (props == NULL || nvlist_lookup_uint64(props,
3625                     zfs_prop_to_name(ZFS_PROP_VOLSIZE), &size) != 0) {
3626                         nvlist_free(props);
3627                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3628                             "missing volume size"));
3629                         return (zfs_error(hdl, EZFS_BADPROP, errbuf));
3630                 }
3631 
3632                 if ((ret = nvlist_lookup_uint64(props,
3633                     zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE),
3634                     &blocksize)) != 0) {
3635                         if (ret == ENOENT) {
3636                                 blocksize = zfs_prop_default_numeric(
3637                                     ZFS_PROP_VOLBLOCKSIZE);
3638                         } else {
3639                                 nvlist_free(props);
3640                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3641                                     "missing volume block size"));
3642                                 return (zfs_error(hdl, EZFS_BADPROP, errbuf));
3643                         }
3644                 }
3645 
3646                 if (size == 0) {
3647                         nvlist_free(props);
3648                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3649                             "volume size cannot be zero"));
3650                         return (zfs_error(hdl, EZFS_BADPROP, errbuf));
3651                 }
3652 
3653                 if (size % blocksize != 0) {
3654                         nvlist_free(props);
3655                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3656                             "volume size must be a multiple of volume block "
3657                             "size"));
3658                         return (zfs_error(hdl, EZFS_BADPROP, errbuf));
3659                 }
3660         }
3661 
3662         (void) parent_name(path, parent, sizeof (parent));
3663         if (zfs_crypto_create(hdl, parent, props, NULL, B_TRUE,
3664             &wkeydata, &wkeylen) != 0) {
3665                 nvlist_free(props);
3666                 return (zfs_error(hdl, EZFS_CRYPTOFAILED, errbuf));
3667         }
3668 
3669         /* create the dataset */
3670         ret = lzc_create(path, ost, props, wkeydata, wkeylen);
3671         nvlist_free(props);
3672         if (wkeydata != NULL)
3673                 free(wkeydata);
3674 
3675         /* check for failure */
3676         if (ret != 0) {
3677                 switch (errno) {
3678                 case ENOENT:
3679                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3680                             "no such parent '%s'"), parent);
3681                         return (zfs_error(hdl, EZFS_NOENT, errbuf));
3682 
3683                 case EINVAL:
3684                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3685                             "parent '%s' is not a filesystem"), parent);
3686                         return (zfs_error(hdl, EZFS_BADTYPE, errbuf));
3687 
3688                 case ENOTSUP:
3689                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3690                             "pool must be upgraded to set this "
3691                             "property or value"));
3692                         return (zfs_error(hdl, EZFS_BADVERSION, errbuf));
3693                 case ERANGE:
3694                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3695                             "invalid property value(s) specified"));
3696                         return (zfs_error(hdl, EZFS_BADPROP, errbuf));
3697                 case EACCES:
3698                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3699                             "encryption root's key is not loaded "
3700                             "or provided"));
3701                         return (zfs_error(hdl, EZFS_CRYPTOFAILED, errbuf));
3702 
3703 #ifdef _ILP32
3704                 case EOVERFLOW:
3705                         /*
3706                          * This platform can't address a volume this big.
3707                          */
3708                         if (type == ZFS_TYPE_VOLUME)
3709                                 return (zfs_error(hdl, EZFS_VOLTOOBIG,
3710                                     errbuf));
3711 #endif
3712                         /* FALLTHROUGH */
3713                 default:
3714                         return (zfs_standard_error(hdl, errno, errbuf));
3715                 }
3716         }
3717 
3718         return (0);
3719 }
3720 
3721 /*
3722  * Destroys the given dataset.  The caller must make sure that the filesystem
3723  * isn't mounted, and that there are no active dependents. If the file system
3724  * does not exist this function does nothing.
3725  */
3726 int
3727 zfs_destroy(zfs_handle_t *zhp, boolean_t defer)
3728 {
3729         int error;
3730 
3731         if (zhp->zfs_type != ZFS_TYPE_SNAPSHOT && defer)
3732                 return (EINVAL);
3733 
3734         if (zhp->zfs_type == ZFS_TYPE_BOOKMARK) {
3735                 nvlist_t *nv = fnvlist_alloc();
3736                 fnvlist_add_boolean(nv, zhp->zfs_name);
3737                 error = lzc_destroy_bookmarks(nv, NULL);
3738                 fnvlist_free(nv);
3739                 if (error != 0) {
3740                         return (zfs_standard_error_fmt(zhp->zfs_hdl, error,
3741                             dgettext(TEXT_DOMAIN, "cannot destroy '%s'"),
3742                             zhp->zfs_name));
3743                 }
3744                 return (0);
3745         }
3746 
3747         if (zhp->zfs_type == ZFS_TYPE_SNAPSHOT) {
3748                 nvlist_t *nv = fnvlist_alloc();
3749                 fnvlist_add_boolean(nv, zhp->zfs_name);
3750                 error = lzc_destroy_snaps(nv, defer, NULL);
3751                 fnvlist_free(nv);
3752         } else {
3753                 error = lzc_destroy(zhp->zfs_name);
3754         }
3755 
3756         if (error != 0 && error != ENOENT) {
3757                 return (zfs_standard_error_fmt(zhp->zfs_hdl, errno,
3758                     dgettext(TEXT_DOMAIN, "cannot destroy '%s'"),
3759                     zhp->zfs_name));
3760         }
3761 
3762         remove_mountpoint(zhp);
3763 
3764         return (0);
3765 }
3766 
3767 struct destroydata {
3768         nvlist_t *nvl;
3769         const char *snapname;
3770 };
3771 
3772 static int
3773 zfs_check_snap_cb(zfs_handle_t *zhp, void *arg)
3774 {
3775         struct destroydata *dd = arg;
3776         char name[ZFS_MAX_DATASET_NAME_LEN];
3777         int rv = 0;
3778 
3779         (void) snprintf(name, sizeof (name),
3780             "%s@%s", zhp->zfs_name, dd->snapname);
3781 
3782         if (lzc_exists(name))
3783                 verify(nvlist_add_boolean(dd->nvl, name) == 0);
3784 
3785         rv = zfs_iter_filesystems(zhp, zfs_check_snap_cb, dd);
3786         zfs_close(zhp);
3787         return (rv);
3788 }
3789 
3790 /*
3791  * Destroys all snapshots with the given name in zhp & descendants.
3792  */
3793 int
3794 zfs_destroy_snaps(zfs_handle_t *zhp, char *snapname, boolean_t defer)
3795 {
3796         int ret;
3797         struct destroydata dd = { 0 };
3798 
3799         dd.snapname = snapname;
3800         verify(nvlist_alloc(&dd.nvl, NV_UNIQUE_NAME, 0) == 0);
3801         (void) zfs_check_snap_cb(zfs_handle_dup(zhp), &dd);
3802 
3803         if (nvlist_empty(dd.nvl)) {
3804                 ret = zfs_standard_error_fmt(zhp->zfs_hdl, ENOENT,
3805                     dgettext(TEXT_DOMAIN, "cannot destroy '%s@%s'"),
3806                     zhp->zfs_name, snapname);
3807         } else {
3808                 ret = zfs_destroy_snaps_nvl(zhp->zfs_hdl, dd.nvl, defer);
3809         }
3810         nvlist_free(dd.nvl);
3811         return (ret);
3812 }
3813 
3814 /*
3815  * Destroys all the snapshots named in the nvlist.
3816  */
3817 int
3818 zfs_destroy_snaps_nvl(libzfs_handle_t *hdl, nvlist_t *snaps, boolean_t defer)
3819 {
3820         int ret;
3821         nvlist_t *errlist = NULL;
3822 
3823         ret = lzc_destroy_snaps(snaps, defer, &errlist);
3824 
3825         if (ret == 0) {
3826                 nvlist_free(errlist);
3827                 return (0);
3828         }
3829 
3830         if (nvlist_empty(errlist)) {
3831                 char errbuf[1024];
3832                 (void) snprintf(errbuf, sizeof (errbuf),
3833                     dgettext(TEXT_DOMAIN, "cannot destroy snapshots"));
3834 
3835                 ret = zfs_standard_error(hdl, ret, errbuf);
3836         }
3837         for (nvpair_t *pair = nvlist_next_nvpair(errlist, NULL);
3838             pair != NULL; pair = nvlist_next_nvpair(errlist, pair)) {
3839                 char errbuf[1024];
3840                 (void) snprintf(errbuf, sizeof (errbuf),
3841                     dgettext(TEXT_DOMAIN, "cannot destroy snapshot %s"),
3842                     nvpair_name(pair));
3843 
3844                 switch (fnvpair_value_int32(pair)) {
3845                 case EEXIST:
3846                         zfs_error_aux(hdl,
3847                             dgettext(TEXT_DOMAIN, "snapshot is cloned"));
3848                         ret = zfs_error(hdl, EZFS_EXISTS, errbuf);
3849                         break;
3850                 default:
3851                         ret = zfs_standard_error(hdl, errno, errbuf);
3852                         break;
3853                 }
3854         }
3855 
3856         nvlist_free(errlist);
3857         return (ret);
3858 }
3859 
3860 /*
3861  * Clones the given dataset.  The target must be of the same type as the source.
3862  */
3863 int
3864 zfs_clone(zfs_handle_t *zhp, const char *target, nvlist_t *props)
3865 {
3866         char parent[ZFS_MAX_DATASET_NAME_LEN];
3867         int ret;
3868         char errbuf[1024];
3869         libzfs_handle_t *hdl = zhp->zfs_hdl;
3870         uint64_t zoned;
3871 
3872         assert(zhp->zfs_type == ZFS_TYPE_SNAPSHOT);
3873 
3874         (void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
3875             "cannot create '%s'"), target);
3876 
3877         /* validate the target/clone name */
3878         if (!zfs_validate_name(hdl, target, ZFS_TYPE_FILESYSTEM, B_TRUE))
3879                 return (zfs_error(hdl, EZFS_INVALIDNAME, errbuf));
3880 
3881         /* validate parents exist */
3882         if (check_parents(hdl, target, &zoned, B_FALSE, NULL) != 0)
3883                 return (-1);
3884 
3885         (void) parent_name(target, parent, sizeof (parent));
3886 
3887         /* do the clone */
3888 
3889         if (props) {
3890                 zfs_type_t type;
3891 
3892                 if (ZFS_IS_VOLUME(zhp)) {
3893                         type = ZFS_TYPE_VOLUME;
3894                 } else {
3895                         type = ZFS_TYPE_FILESYSTEM;
3896                 }
3897                 if ((props = zfs_valid_proplist(hdl, type, props, zoned,
3898                     zhp, zhp->zpool_hdl, B_TRUE, errbuf)) == NULL)
3899                         return (-1);
3900                 if (zfs_fix_auto_resv(zhp, props) == -1) {
3901                         nvlist_free(props);
3902                         return (-1);
3903                 }
3904         }
3905 
3906         if (zfs_crypto_clone_check(hdl, zhp, parent, props) != 0) {
3907                 nvlist_free(props);
3908                 return (zfs_error(hdl, EZFS_CRYPTOFAILED, errbuf));
3909         }
3910 
3911         ret = lzc_clone(target, zhp->zfs_name, props);
3912         nvlist_free(props);
3913 
3914         if (ret != 0) {
3915                 switch (errno) {
3916 
3917                 case ENOENT:
3918                         /*
3919                          * The parent doesn't exist.  We should have caught this
3920                          * above, but there may a race condition that has since
3921                          * destroyed the parent.
3922                          *
3923                          * At this point, we don't know whether it's the source
3924                          * that doesn't exist anymore, or whether the target
3925                          * dataset doesn't exist.
3926                          */
3927                         zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
3928                             "no such parent '%s'"), parent);
3929                         return (zfs_error(zhp->zfs_hdl, EZFS_NOENT, errbuf));
3930 
3931                 case EXDEV:
3932                         zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
3933                             "source and target pools differ"));
3934                         return (zfs_error(zhp->zfs_hdl, EZFS_CROSSTARGET,
3935                             errbuf));
3936 
3937                 default:
3938                         return (zfs_standard_error(zhp->zfs_hdl, errno,
3939                             errbuf));
3940                 }
3941         }
3942 
3943         return (ret);
3944 }
3945 
3946 /*
3947  * Promotes the given clone fs to be the clone parent.
3948  */
3949 int
3950 zfs_promote(zfs_handle_t *zhp)
3951 {
3952         libzfs_handle_t *hdl = zhp->zfs_hdl;
3953         char snapname[ZFS_MAX_DATASET_NAME_LEN];
3954         int ret;
3955         char errbuf[1024];
3956 
3957         (void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
3958             "cannot promote '%s'"), zhp->zfs_name);
3959 
3960         if (zhp->zfs_type == ZFS_TYPE_SNAPSHOT) {
3961                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3962                     "snapshots can not be promoted"));
3963                 return (zfs_error(hdl, EZFS_BADTYPE, errbuf));
3964         }
3965 
3966         if (zhp->zfs_dmustats.dds_origin[0] == '\0') {
3967                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3968                     "not a cloned filesystem"));
3969                 return (zfs_error(hdl, EZFS_BADTYPE, errbuf));
3970         }
3971 
3972         if (!zfs_validate_name(hdl, zhp->zfs_name, zhp->zfs_type, B_TRUE))
3973                 return (zfs_error(hdl, EZFS_INVALIDNAME, errbuf));
3974 
3975         ret = lzc_promote(zhp->zfs_name, snapname, sizeof (snapname));
3976 
3977         if (ret != 0) {
3978                 switch (ret) {
3979                 case EEXIST:
3980                         /* There is a conflicting snapshot name. */
3981                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3982                             "conflicting snapshot '%s' from parent '%s'"),
3983                             snapname, zhp->zfs_dmustats.dds_origin);
3984                         return (zfs_error(hdl, EZFS_EXISTS, errbuf));
3985 
3986                 default:
3987                         return (zfs_standard_error(hdl, ret, errbuf));
3988                 }
3989         }
3990         return (ret);
3991 }
3992 
3993 typedef struct snapdata {
3994         nvlist_t *sd_nvl;
3995         const char *sd_snapname;
3996 } snapdata_t;
3997 
3998 static int
3999 zfs_snapshot_cb(zfs_handle_t *zhp, void *arg)
4000 {
4001         snapdata_t *sd = arg;
4002         char name[ZFS_MAX_DATASET_NAME_LEN];
4003         int rv = 0;
4004 
4005         if (zfs_prop_get_int(zhp, ZFS_PROP_INCONSISTENT) == 0) {
4006                 (void) snprintf(name, sizeof (name),
4007                     "%s@%s", zfs_get_name(zhp), sd->sd_snapname);
4008 
4009                 fnvlist_add_boolean(sd->sd_nvl, name);
4010 
4011                 rv = zfs_iter_filesystems(zhp, zfs_snapshot_cb, sd);
4012         }
4013         zfs_close(zhp);
4014 
4015         return (rv);
4016 }
4017 
4018 int
4019 zfs_remap_indirects(libzfs_handle_t *hdl, const char *fs)
4020 {
4021         int err;
4022         char errbuf[1024];
4023 
4024         (void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
4025             "cannot remap dataset '%s'"), fs);
4026 
4027         err = lzc_remap(fs);
4028 
4029         if (err != 0) {
4030                 switch (err) {
4031                 case ENOTSUP:
4032                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4033                             "pool must be upgraded"));
4034                         (void) zfs_error(hdl, EZFS_BADVERSION, errbuf);
4035                         break;
4036                 case EINVAL:
4037                         (void) zfs_error(hdl, EZFS_BADTYPE, errbuf);
4038                         break;
4039                 default:
4040                         (void) zfs_standard_error(hdl, err, errbuf);
4041                         break;
4042                 }
4043         }
4044 
4045         return (err);
4046 }
4047 
4048 /*
4049  * Creates snapshots.  The keys in the snaps nvlist are the snapshots to be
4050  * created.
4051  */
4052 int
4053 zfs_snapshot_nvl(libzfs_handle_t *hdl, nvlist_t *snaps, nvlist_t *props)
4054 {
4055         int ret;
4056         char errbuf[1024];
4057         nvpair_t *elem;
4058         nvlist_t *errors;
4059 
4060         (void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
4061             "cannot create snapshots "));
4062 
4063         elem = NULL;
4064         while ((elem = nvlist_next_nvpair(snaps, elem)) != NULL) {
4065                 const char *snapname = nvpair_name(elem);
4066 
4067                 /* validate the target name */
4068                 if (!zfs_validate_name(hdl, snapname, ZFS_TYPE_SNAPSHOT,
4069                     B_TRUE)) {
4070                         (void) snprintf(errbuf, sizeof (errbuf),
4071                             dgettext(TEXT_DOMAIN,
4072                             "cannot create snapshot '%s'"), snapname);
4073                         return (zfs_error(hdl, EZFS_INVALIDNAME, errbuf));
4074                 }
4075         }
4076 
4077         /*
4078          * get pool handle for prop validation. assumes all snaps are in the
4079          * same pool, as does lzc_snapshot (below).
4080          */
4081         char pool[ZFS_MAX_DATASET_NAME_LEN];
4082         elem = nvlist_next_nvpair(snaps, NULL);
4083         (void) strlcpy(pool, nvpair_name(elem), sizeof (pool));
4084         pool[strcspn(pool, "/@")] = '\0';
4085         zpool_handle_t *zpool_hdl = zpool_open(hdl, pool);
4086 
4087         if (props != NULL &&
4088             (props = zfs_valid_proplist(hdl, ZFS_TYPE_SNAPSHOT,
4089             props, B_FALSE, NULL, zpool_hdl, B_FALSE, errbuf)) == NULL) {
4090                 zpool_close(zpool_hdl);
4091                 return (-1);
4092         }
4093         zpool_close(zpool_hdl);
4094 
4095         ret = lzc_snapshot(snaps, props, &errors);
4096 
4097         if (ret != 0) {
4098                 boolean_t printed = B_FALSE;
4099                 for (elem = nvlist_next_nvpair(errors, NULL);
4100                     elem != NULL;
4101                     elem = nvlist_next_nvpair(errors, elem)) {
4102                         (void) snprintf(errbuf, sizeof (errbuf),
4103                             dgettext(TEXT_DOMAIN,
4104                             "cannot create snapshot '%s'"), nvpair_name(elem));
4105                         (void) zfs_standard_error(hdl,
4106                             fnvpair_value_int32(elem), errbuf);
4107                         printed = B_TRUE;
4108                 }
4109                 if (!printed) {
4110                         switch (ret) {
4111                         case EXDEV:
4112                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4113                                     "multiple snapshots of same "
4114                                     "fs not allowed"));
4115                                 (void) zfs_error(hdl, EZFS_EXISTS, errbuf);
4116 
4117                                 break;
4118                         default:
4119                                 (void) zfs_standard_error(hdl, ret, errbuf);
4120                         }
4121                 }
4122         }
4123 
4124         nvlist_free(props);
4125         nvlist_free(errors);
4126         return (ret);
4127 }
4128 
4129 int
4130 zfs_snapshot(libzfs_handle_t *hdl, const char *path, boolean_t recursive,
4131     nvlist_t *props)
4132 {
4133         int ret;
4134         snapdata_t sd = { 0 };
4135         char fsname[ZFS_MAX_DATASET_NAME_LEN];
4136         char *cp;
4137         zfs_handle_t *zhp;
4138         char errbuf[1024];
4139 
4140         (void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
4141             "cannot snapshot %s"), path);
4142 
4143         if (!zfs_validate_name(hdl, path, ZFS_TYPE_SNAPSHOT, B_TRUE))
4144                 return (zfs_error(hdl, EZFS_INVALIDNAME, errbuf));
4145 
4146         (void) strlcpy(fsname, path, sizeof (fsname));
4147         cp = strchr(fsname, '@');
4148         *cp = '\0';
4149         sd.sd_snapname = cp + 1;
4150 
4151         if ((zhp = zfs_open(hdl, fsname, ZFS_TYPE_FILESYSTEM |
4152             ZFS_TYPE_VOLUME)) == NULL) {
4153                 return (-1);
4154         }
4155 
4156         verify(nvlist_alloc(&sd.sd_nvl, NV_UNIQUE_NAME, 0) == 0);
4157         if (recursive) {
4158                 (void) zfs_snapshot_cb(zfs_handle_dup(zhp), &sd);
4159         } else {
4160                 fnvlist_add_boolean(sd.sd_nvl, path);
4161         }
4162 
4163         ret = zfs_snapshot_nvl(hdl, sd.sd_nvl, props);
4164         nvlist_free(sd.sd_nvl);
4165         zfs_close(zhp);
4166         return (ret);
4167 }
4168 
4169 /*
4170  * Destroy any more recent snapshots.  We invoke this callback on any dependents
4171  * of the snapshot first.  If the 'cb_dependent' member is non-zero, then this
4172  * is a dependent and we should just destroy it without checking the transaction
4173  * group.
4174  */
4175 typedef struct rollback_data {
4176         const char      *cb_target;             /* the snapshot */
4177         uint64_t        cb_create;              /* creation time reference */
4178         boolean_t       cb_error;
4179         boolean_t       cb_force;
4180 } rollback_data_t;
4181 
4182 static int
4183 rollback_destroy_dependent(zfs_handle_t *zhp, void *data)
4184 {
4185         rollback_data_t *cbp = data;
4186         prop_changelist_t *clp;
4187 
4188         /* We must destroy this clone; first unmount it */
4189         clp = changelist_gather(zhp, ZFS_PROP_NAME, 0,
4190             cbp->cb_force ? MS_FORCE: 0);
4191         if (clp == NULL || changelist_prefix(clp) != 0) {
4192                 cbp->cb_error = B_TRUE;
4193                 zfs_close(zhp);
4194                 return (0);
4195         }
4196         if (zfs_destroy(zhp, B_FALSE) != 0)
4197                 cbp->cb_error = B_TRUE;
4198         else
4199                 changelist_remove(clp, zhp->zfs_name);
4200         (void) changelist_postfix(clp);
4201         changelist_free(clp);
4202 
4203         zfs_close(zhp);
4204         return (0);
4205 }
4206 
4207 static int
4208 rollback_destroy(zfs_handle_t *zhp, void *data)
4209 {
4210         rollback_data_t *cbp = data;
4211 
4212         if (zfs_prop_get_int(zhp, ZFS_PROP_CREATETXG) > cbp->cb_create) {
4213                 cbp->cb_error |= zfs_iter_dependents(zhp, B_FALSE,
4214                     rollback_destroy_dependent, cbp);
4215 
4216                 cbp->cb_error |= zfs_destroy(zhp, B_FALSE);
4217         }
4218 
4219         zfs_close(zhp);
4220         return (0);
4221 }
4222 
4223 /*
4224  * Given a dataset, rollback to a specific snapshot, discarding any
4225  * data changes since then and making it the active dataset.
4226  *
4227  * Any snapshots and bookmarks more recent than the target are
4228  * destroyed, along with their dependents (i.e. clones).
4229  */
4230 int
4231 zfs_rollback(zfs_handle_t *zhp, zfs_handle_t *snap, boolean_t force)
4232 {
4233         rollback_data_t cb = { 0 };
4234         int err;
4235         boolean_t restore_resv = 0;
4236         uint64_t old_volsize = 0, new_volsize;
4237         zfs_prop_t resv_prop;
4238 
4239         assert(zhp->zfs_type == ZFS_TYPE_FILESYSTEM ||
4240             zhp->zfs_type == ZFS_TYPE_VOLUME);
4241 
4242         /*
4243          * Destroy all recent snapshots and their dependents.
4244          */
4245         cb.cb_force = force;
4246         cb.cb_target = snap->zfs_name;
4247         cb.cb_create = zfs_prop_get_int(snap, ZFS_PROP_CREATETXG);
4248         (void) zfs_iter_snapshots(zhp, B_FALSE, rollback_destroy, &cb);
4249         (void) zfs_iter_bookmarks(zhp, rollback_destroy, &cb);
4250 
4251         if (cb.cb_error)
4252                 return (-1);
4253 
4254         /*
4255          * Now that we have verified that the snapshot is the latest,
4256          * rollback to the given snapshot.
4257          */
4258 
4259         if (zhp->zfs_type == ZFS_TYPE_VOLUME) {
4260                 if (zfs_which_resv_prop(zhp, &resv_prop) < 0)
4261                         return (-1);
4262                 old_volsize = zfs_prop_get_int(zhp, ZFS_PROP_VOLSIZE);
4263                 restore_resv =
4264                     (old_volsize == zfs_prop_get_int(zhp, resv_prop));
4265         }
4266 
4267         /*
4268          * Pass both the filesystem and the wanted snapshot names,
4269          * we would get an error back if the snapshot is destroyed or
4270          * a new snapshot is created before this request is processed.
4271          */
4272         err = lzc_rollback_to(zhp->zfs_name, snap->zfs_name);
4273         if (err != 0) {
4274                 char errbuf[1024];
4275 
4276                 (void) snprintf(errbuf, sizeof (errbuf),
4277                     dgettext(TEXT_DOMAIN, "cannot rollback '%s'"),
4278                     zhp->zfs_name);
4279                 switch (err) {
4280                 case EEXIST:
4281                         zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
4282                             "there is a snapshot or bookmark more recent "
4283                             "than '%s'"), snap->zfs_name);
4284                         (void) zfs_error(zhp->zfs_hdl, EZFS_EXISTS, errbuf);
4285                         break;
4286                 case ESRCH:
4287                         zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
4288                             "'%s' is not found among snapshots of '%s'"),
4289                             snap->zfs_name, zhp->zfs_name);
4290                         (void) zfs_error(zhp->zfs_hdl, EZFS_NOENT, errbuf);
4291                         break;
4292                 case EINVAL:
4293                         (void) zfs_error(zhp->zfs_hdl, EZFS_BADTYPE, errbuf);
4294                         break;
4295                 default:
4296                         (void) zfs_standard_error(zhp->zfs_hdl, err, errbuf);
4297                 }
4298                 return (err);
4299         }
4300 
4301         /*
4302          * For volumes, if the pre-rollback volsize matched the pre-
4303          * rollback reservation and the volsize has changed then set
4304          * the reservation property to the post-rollback volsize.
4305          * Make a new handle since the rollback closed the dataset.
4306          */
4307         if ((zhp->zfs_type == ZFS_TYPE_VOLUME) &&
4308             (zhp = make_dataset_handle(zhp->zfs_hdl, zhp->zfs_name))) {
4309                 if (restore_resv) {
4310                         new_volsize = zfs_prop_get_int(zhp, ZFS_PROP_VOLSIZE);
4311                         if (old_volsize != new_volsize)
4312                                 err = zfs_prop_set_int(zhp, resv_prop,
4313                                     new_volsize);
4314                 }
4315                 zfs_close(zhp);
4316         }
4317         return (err);
4318 }
4319 
4320 /*
4321  * Renames the given dataset.
4322  */
4323 int
4324 zfs_rename(zfs_handle_t *zhp, const char *target, boolean_t recursive,
4325     boolean_t force_unmount)
4326 {
4327         int ret = 0;
4328         zfs_cmd_t zc = { 0 };
4329         char *delim;
4330         prop_changelist_t *cl = NULL;
4331         zfs_handle_t *zhrp = NULL;
4332         char *parentname = NULL;
4333         char parent[ZFS_MAX_DATASET_NAME_LEN];
4334         libzfs_handle_t *hdl = zhp->zfs_hdl;
4335         char errbuf[1024];
4336 
4337         /* if we have the same exact name, just return success */
4338         if (strcmp(zhp->zfs_name, target) == 0)
4339                 return (0);
4340 
4341         (void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
4342             "cannot rename to '%s'"), target);
4343 
4344         /* make sure source name is valid */
4345         if (!zfs_validate_name(hdl, zhp->zfs_name, zhp->zfs_type, B_TRUE))
4346                 return (zfs_error(hdl, EZFS_INVALIDNAME, errbuf));
4347 
4348         /*
4349          * Make sure the target name is valid
4350          */
4351         if (zhp->zfs_type == ZFS_TYPE_SNAPSHOT) {
4352                 if ((strchr(target, '@') == NULL) ||
4353                     *target == '@') {
4354                         /*
4355                          * Snapshot target name is abbreviated,
4356                          * reconstruct full dataset name
4357                          */
4358                         (void) strlcpy(parent, zhp->zfs_name,
4359                             sizeof (parent));
4360                         delim = strchr(parent, '@');
4361                         if (strchr(target, '@') == NULL)
4362                                 *(++delim) = '\0';
4363                         else
4364                                 *delim = '\0';
4365                         (void) strlcat(parent, target, sizeof (parent));
4366                         target = parent;
4367                 } else {
4368                         /*
4369                          * Make sure we're renaming within the same dataset.
4370                          */
4371                         delim = strchr(target, '@');
4372                         if (strncmp(zhp->zfs_name, target, delim - target)
4373                             != 0 || zhp->zfs_name[delim - target] != '@') {
4374                                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4375                                     "snapshots must be part of same "
4376                                     "dataset"));
4377                                 return (zfs_error(hdl, EZFS_CROSSTARGET,
4378                                     errbuf));
4379                         }
4380                 }
4381 
4382                 if (!zfs_validate_name(hdl, target, zhp->zfs_type, B_TRUE))
4383                         return (zfs_error(hdl, EZFS_INVALIDNAME, errbuf));
4384         } else {
4385                 if (recursive) {
4386                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4387                             "recursive rename must be a snapshot"));
4388                         return (zfs_error(hdl, EZFS_BADTYPE, errbuf));
4389                 }
4390 
4391                 if (!zfs_validate_name(hdl, target, zhp->zfs_type, B_TRUE))
4392                         return (zfs_error(hdl, EZFS_INVALIDNAME, errbuf));
4393 
4394                 /* validate parents */
4395                 if (check_parents(hdl, target, NULL, B_FALSE, NULL) != 0)
4396                         return (-1);
4397 
4398                 /* make sure we're in the same pool */
4399                 verify((delim = strchr(target, '/')) != NULL);
4400                 if (strncmp(zhp->zfs_name, target, delim - target) != 0 ||
4401                     zhp->zfs_name[delim - target] != '/') {
4402                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4403                             "datasets must be within same pool"));
4404                         return (zfs_error(hdl, EZFS_CROSSTARGET, errbuf));
4405                 }
4406 
4407                 /* new name cannot be a child of the current dataset name */
4408                 if (is_descendant(zhp->zfs_name, target)) {
4409                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4410                             "New dataset name cannot be a descendant of "
4411                             "current dataset name"));
4412                         return (zfs_error(hdl, EZFS_INVALIDNAME, errbuf));
4413                 }
4414         }
4415 
4416         (void) snprintf(errbuf, sizeof (errbuf),
4417             dgettext(TEXT_DOMAIN, "cannot rename '%s'"), zhp->zfs_name);
4418 
4419         if (getzoneid() == GLOBAL_ZONEID &&
4420             zfs_prop_get_int(zhp, ZFS_PROP_ZONED)) {
4421                 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4422                     "dataset is used in a non-global zone"));
4423                 return (zfs_error(hdl, EZFS_ZONED, errbuf));
4424         }
4425 
4426         if (recursive) {
4427                 parentname = zfs_strdup(zhp->zfs_hdl, zhp->zfs_name);
4428                 if (parentname == NULL) {
4429                         ret = -1;
4430                         goto error;
4431                 }
4432                 delim = strchr(parentname, '@');
4433                 *delim = '\0';
4434                 zhrp = zfs_open(zhp->zfs_hdl, parentname, ZFS_TYPE_DATASET);
4435                 if (zhrp == NULL) {
4436                         ret = -1;
4437                         goto error;
4438                 }
4439         } else if (zhp->zfs_type != ZFS_TYPE_SNAPSHOT) {
4440                 if ((cl = changelist_gather(zhp, ZFS_PROP_NAME, 0,
4441                     force_unmount ? MS_FORCE : 0)) == NULL)
4442                         return (-1);
4443 
4444                 if (changelist_haszonedchild(cl)) {
4445                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4446                             "child dataset with inherited mountpoint is used "
4447                             "in a non-global zone"));
4448                         (void) zfs_error(hdl, EZFS_ZONED, errbuf);
4449                         ret = -1;
4450                         goto error;
4451                 }
4452 
4453                 if ((ret = changelist_prefix(cl)) != 0)
4454                         goto error;
4455         }
4456 
4457         if (ZFS_IS_VOLUME(zhp))
4458                 zc.zc_objset_type = DMU_OST_ZVOL;
4459         else
4460                 zc.zc_objset_type = DMU_OST_ZFS;
4461 
4462         (void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
4463         (void) strlcpy(zc.zc_value, target, sizeof (zc.zc_value));
4464 
4465         zc.zc_cookie = recursive;
4466 
4467         if ((ret = zfs_ioctl(zhp->zfs_hdl, ZFS_IOC_RENAME, &zc)) != 0) {
4468                 /*
4469                  * if it was recursive, the one that actually failed will
4470                  * be in zc.zc_name
4471                  */
4472                 (void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
4473                     "cannot rename '%s'"), zc.zc_name);
4474 
4475                 if (recursive && errno == EEXIST) {
4476                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4477                             "a child dataset already has a snapshot "
4478                             "with the new name"));
4479                         (void) zfs_error(hdl, EZFS_EXISTS, errbuf);
4480                 } else if (errno == EACCES) {
4481                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4482                             "cannot move encrypted child outside of "
4483                             "its encryption root"));
4484                         (void) zfs_error(hdl, EZFS_CRYPTOFAILED, errbuf);
4485                 } else {
4486                         (void) zfs_standard_error(zhp->zfs_hdl, errno, errbuf);
4487                 }
4488 
4489                 /*
4490                  * On failure, we still want to remount any filesystems that
4491                  * were previously mounted, so we don't alter the system state.
4492                  */
4493                 if (cl != NULL)
4494                         (void) changelist_postfix(cl);
4495         } else {
4496                 if (cl != NULL) {
4497                         changelist_rename(cl, zfs_get_name(zhp), target);
4498                         ret = changelist_postfix(cl);
4499                 }
4500         }
4501 
4502 error:
4503         if (parentname != NULL) {
4504                 free(parentname);
4505         }
4506         if (zhrp != NULL) {
4507                 zfs_close(zhrp);
4508         }
4509         if (cl != NULL) {
4510                 changelist_free(cl);
4511         }
4512         return (ret);
4513 }
4514 
4515 nvlist_t *
4516 zfs_get_user_props(zfs_handle_t *zhp)
4517 {
4518         return (zhp->zfs_user_props);
4519 }
4520 
4521 nvlist_t *
4522 zfs_get_recvd_props(zfs_handle_t *zhp)
4523 {
4524         if (zhp->zfs_recvd_props == NULL)
4525                 if (get_recvd_props_ioctl(zhp) != 0)
4526                         return (NULL);
4527         return (zhp->zfs_recvd_props);
4528 }
4529 
4530 /*
4531  * This function is used by 'zfs list' to determine the exact set of columns to
4532  * display, and their maximum widths.  This does two main things:
4533  *
4534  *      - If this is a list of all properties, then expand the list to include
4535  *        all native properties, and set a flag so that for each dataset we look
4536  *        for new unique user properties and add them to the list.
4537  *
4538  *      - For non fixed-width properties, keep track of the maximum width seen
4539  *        so that we can size the column appropriately. If the user has
4540  *        requested received property values, we also need to compute the width
4541  *        of the RECEIVED column.
4542  */
4543 int
4544 zfs_expand_proplist(zfs_handle_t *zhp, zprop_list_t **plp, boolean_t received,
4545     boolean_t literal)
4546 {
4547         libzfs_handle_t *hdl = zhp->zfs_hdl;
4548         zprop_list_t *entry;
4549         zprop_list_t **last, **start;
4550         nvlist_t *userprops, *propval;
4551         nvpair_t *elem;
4552         char *strval;
4553         char buf[ZFS_MAXPROPLEN];
4554 
4555         if (zprop_expand_list(hdl, plp, ZFS_TYPE_DATASET) != 0)
4556                 return (-1);
4557 
4558         userprops = zfs_get_user_props(zhp);
4559 
4560         entry = *plp;
4561         if (entry->pl_all && nvlist_next_nvpair(userprops, NULL) != NULL) {
4562                 /*
4563                  * Go through and add any user properties as necessary.  We
4564                  * start by incrementing our list pointer to the first
4565                  * non-native property.
4566                  */
4567                 start = plp;
4568                 while (*start != NULL) {
4569                         if ((*start)->pl_prop == ZPROP_INVAL)
4570                                 break;
4571                         start = &(*start)->pl_next;
4572                 }
4573 
4574                 elem = NULL;
4575                 while ((elem = nvlist_next_nvpair(userprops, elem)) != NULL) {
4576                         /*
4577                          * See if we've already found this property in our list.
4578                          */
4579                         for (last = start; *last != NULL;
4580                             last = &(*last)->pl_next) {
4581                                 if (strcmp((*last)->pl_user_prop,
4582                                     nvpair_name(elem)) == 0)
4583                                         break;
4584                         }
4585 
4586                         if (*last == NULL) {
4587                                 if ((entry = zfs_alloc(hdl,
4588                                     sizeof (zprop_list_t))) == NULL ||
4589                                     ((entry->pl_user_prop = zfs_strdup(hdl,
4590                                     nvpair_name(elem)))) == NULL) {
4591                                         free(entry);
4592                                         return (-1);
4593                                 }
4594 
4595                                 entry->pl_prop = ZPROP_INVAL;
4596                                 entry->pl_width = strlen(nvpair_name(elem));
4597                                 entry->pl_all = B_TRUE;
4598                                 *last = entry;
4599                         }
4600                 }
4601         }
4602 
4603         /*
4604          * Now go through and check the width of any non-fixed columns
4605          */
4606         for (entry = *plp; entry != NULL; entry = entry->pl_next) {
4607                 if (entry->pl_fixed && !literal)
4608                         continue;
4609 
4610                 if (entry->pl_prop != ZPROP_INVAL) {
4611                         if (zfs_prop_get(zhp, entry->pl_prop,
4612                             buf, sizeof (buf), NULL, NULL, 0, literal) == 0) {
4613                                 if (strlen(buf) > entry->pl_width)
4614                                         entry->pl_width = strlen(buf);
4615                         }
4616                         if (received && zfs_prop_get_recvd(zhp,
4617                             zfs_prop_to_name(entry->pl_prop),
4618                             buf, sizeof (buf), literal) == 0)
4619                                 if (strlen(buf) > entry->pl_recvd_width)
4620                                         entry->pl_recvd_width = strlen(buf);
4621                 } else {
4622                         if (nvlist_lookup_nvlist(userprops, entry->pl_user_prop,
4623                             &propval) == 0) {
4624                                 verify(nvlist_lookup_string(propval,
4625                                     ZPROP_VALUE, &strval) == 0);
4626                                 if (strlen(strval) > entry->pl_width)
4627                                         entry->pl_width = strlen(strval);
4628                         }
4629                         if (received && zfs_prop_get_recvd(zhp,
4630                             entry->pl_user_prop,
4631                             buf, sizeof (buf), literal) == 0)
4632                                 if (strlen(buf) > entry->pl_recvd_width)
4633                                         entry->pl_recvd_width = strlen(buf);
4634                 }
4635         }
4636 
4637         return (0);
4638 }
4639 
4640 int
4641 zfs_deleg_share_nfs(libzfs_handle_t *hdl, char *dataset, char *path,
4642     char *resource, void *export, void *sharetab,
4643     int sharemax, zfs_share_op_t operation)
4644 {
4645         zfs_cmd_t zc = { 0 };
4646         int error;
4647 
4648         (void) strlcpy(zc.zc_name, dataset, sizeof (zc.zc_name));
4649         (void) strlcpy(zc.zc_value, path, sizeof (zc.zc_value));
4650         if (resource)
4651                 (void) strlcpy(zc.zc_string, resource, sizeof (zc.zc_string));
4652         zc.zc_share.z_sharedata = (uint64_t)(uintptr_t)sharetab;
4653         zc.zc_share.z_exportdata = (uint64_t)(uintptr_t)export;
4654         zc.zc_share.z_sharetype = operation;
4655         zc.zc_share.z_sharemax = sharemax;
4656         error = ioctl(hdl->libzfs_fd, ZFS_IOC_SHARE, &zc);
4657         return (error);
4658 }
4659 
4660 void
4661 zfs_prune_proplist(zfs_handle_t *zhp, uint8_t *props)
4662 {
4663         nvpair_t *curr;
4664 
4665         /*
4666          * Keep a reference to the props-table against which we prune the
4667          * properties.
4668          */
4669         zhp->zfs_props_table = props;
4670 
4671         curr = nvlist_next_nvpair(zhp->zfs_props, NULL);
4672 
4673         while (curr) {
4674                 zfs_prop_t zfs_prop = zfs_name_to_prop(nvpair_name(curr));
4675                 nvpair_t *next = nvlist_next_nvpair(zhp->zfs_props, curr);
4676 
4677                 /*
4678                  * User properties will result in ZPROP_INVAL, and since we
4679                  * only know how to prune standard ZFS properties, we always
4680                  * leave these in the list.  This can also happen if we
4681                  * encounter an unknown DSL property (when running older
4682                  * software, for example).
4683                  */
4684                 if (zfs_prop != ZPROP_INVAL && props[zfs_prop] == B_FALSE)
4685                         (void) nvlist_remove(zhp->zfs_props,
4686                             nvpair_name(curr), nvpair_type(curr));
4687                 curr = next;
4688         }
4689 }
4690 
4691 static int
4692 zfs_smb_acl_mgmt(libzfs_handle_t *hdl, char *dataset, char *path,
4693     zfs_smb_acl_op_t cmd, char *resource1, char *resource2)
4694 {
4695         zfs_cmd_t zc = { 0 };
4696         nvlist_t *nvlist = NULL;
4697         int error;
4698 
4699         (void) strlcpy(zc.zc_name, dataset, sizeof (zc.zc_name));
4700         (void) strlcpy(zc.zc_value, path, sizeof (zc.zc_value));
4701         zc.zc_cookie = (uint64_t)cmd;
4702 
4703         if (cmd == ZFS_SMB_ACL_RENAME) {
4704                 if (nvlist_alloc(&nvlist, NV_UNIQUE_NAME, 0) != 0) {
4705                         (void) no_memory(hdl);
4706                         return (0);
4707                 }
4708         }
4709 
4710         switch (cmd) {
4711         case ZFS_SMB_ACL_ADD:
4712         case ZFS_SMB_ACL_REMOVE:
4713                 (void) strlcpy(zc.zc_string, resource1, sizeof (zc.zc_string));
4714                 break;
4715         case ZFS_SMB_ACL_RENAME:
4716                 if (nvlist_add_string(nvlist, ZFS_SMB_ACL_SRC,
4717                     resource1) != 0) {
4718                                 (void) no_memory(hdl);
4719                                 return (-1);
4720                 }
4721                 if (nvlist_add_string(nvlist, ZFS_SMB_ACL_TARGET,
4722                     resource2) != 0) {
4723                                 (void) no_memory(hdl);
4724                                 return (-1);
4725                 }
4726                 if (zcmd_write_src_nvlist(hdl, &zc, nvlist) != 0) {
4727                         nvlist_free(nvlist);
4728                         return (-1);
4729                 }
4730                 break;
4731         case ZFS_SMB_ACL_PURGE:
4732                 break;
4733         default:
4734                 return (-1);
4735         }
4736         error = ioctl(hdl->libzfs_fd, ZFS_IOC_SMB_ACL, &zc);
4737         nvlist_free(nvlist);
4738         return (error);
4739 }
4740 
4741 int
4742 zfs_smb_acl_add(libzfs_handle_t *hdl, char *dataset,
4743     char *path, char *resource)
4744 {
4745         return (zfs_smb_acl_mgmt(hdl, dataset, path, ZFS_SMB_ACL_ADD,
4746             resource, NULL));
4747 }
4748 
4749 int
4750 zfs_smb_acl_remove(libzfs_handle_t *hdl, char *dataset,
4751     char *path, char *resource)
4752 {
4753         return (zfs_smb_acl_mgmt(hdl, dataset, path, ZFS_SMB_ACL_REMOVE,
4754             resource, NULL));
4755 }
4756 
4757 int
4758 zfs_smb_acl_purge(libzfs_handle_t *hdl, char *dataset, char *path)
4759 {
4760         return (zfs_smb_acl_mgmt(hdl, dataset, path, ZFS_SMB_ACL_PURGE,
4761             NULL, NULL));
4762 }
4763 
4764 int
4765 zfs_smb_acl_rename(libzfs_handle_t *hdl, char *dataset, char *path,
4766     char *oldname, char *newname)
4767 {
4768         return (zfs_smb_acl_mgmt(hdl, dataset, path, ZFS_SMB_ACL_RENAME,
4769             oldname, newname));
4770 }
4771 
4772 int
4773 zfs_userspace(zfs_handle_t *zhp, zfs_userquota_prop_t type,
4774     zfs_userspace_cb_t func, void *arg)
4775 {
4776         zfs_cmd_t zc = { 0 };
4777         zfs_useracct_t buf[100];
4778         libzfs_handle_t *hdl = zhp->zfs_hdl;
4779         int ret;
4780 
4781         (void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
4782 
4783         zc.zc_objset_type = type;
4784         zc.zc_nvlist_dst = (uintptr_t)buf;
4785 
4786         for (;;) {
4787                 zfs_useracct_t *zua = buf;
4788 
4789                 zc.zc_nvlist_dst_size = sizeof (buf);
4790                 if (zfs_ioctl(hdl, ZFS_IOC_USERSPACE_MANY, &zc) != 0) {
4791                         char errbuf[1024];
4792 
4793                         if ((errno == ENOTSUP &&
4794                             (type == ZFS_PROP_USEROBJUSED ||
4795                             type == ZFS_PROP_GROUPOBJUSED ||
4796                             type == ZFS_PROP_USEROBJQUOTA ||
4797                             type == ZFS_PROP_GROUPOBJQUOTA ||
4798                             type == ZFS_PROP_PROJECTOBJUSED ||
4799                             type == ZFS_PROP_PROJECTOBJQUOTA ||
4800                             type == ZFS_PROP_PROJECTUSED ||
4801                             type == ZFS_PROP_PROJECTQUOTA)))
4802                                 break;
4803 
4804                         (void) snprintf(errbuf, sizeof (errbuf),
4805                             dgettext(TEXT_DOMAIN,
4806                             "cannot get used/quota for %s"), zc.zc_name);
4807                         return (zfs_standard_error_fmt(hdl, errno, errbuf));
4808                 }
4809                 if (zc.zc_nvlist_dst_size == 0)
4810                         break;
4811 
4812                 while (zc.zc_nvlist_dst_size > 0) {
4813                         if ((ret = func(arg, zua->zu_domain, zua->zu_rid,
4814                             zua->zu_space)) != 0)
4815                                 return (ret);
4816                         zua++;
4817                         zc.zc_nvlist_dst_size -= sizeof (zfs_useracct_t);
4818                 }
4819         }
4820 
4821         return (0);
4822 }
4823 
4824 struct holdarg {
4825         nvlist_t *nvl;
4826         const char *snapname;
4827         const char *tag;
4828         boolean_t recursive;
4829         int error;
4830 };
4831 
4832 static int
4833 zfs_hold_one(zfs_handle_t *zhp, void *arg)
4834 {
4835         struct holdarg *ha = arg;
4836         char name[ZFS_MAX_DATASET_NAME_LEN];
4837         int rv = 0;
4838 
4839         (void) snprintf(name, sizeof (name),
4840             "%s@%s", zhp->zfs_name, ha->snapname);
4841 
4842         if (lzc_exists(name))
4843                 fnvlist_add_string(ha->nvl, name, ha->tag);
4844 
4845         if (ha->recursive)
4846                 rv = zfs_iter_filesystems(zhp, zfs_hold_one, ha);
4847         zfs_close(zhp);
4848         return (rv);
4849 }
4850 
4851 int
4852 zfs_hold(zfs_handle_t *zhp, const char *snapname, const char *tag,
4853     boolean_t recursive, int cleanup_fd)
4854 {
4855         int ret;
4856         struct holdarg ha;
4857 
4858         ha.nvl = fnvlist_alloc();
4859         ha.snapname = snapname;
4860         ha.tag = tag;
4861         ha.recursive = recursive;
4862         (void) zfs_hold_one(zfs_handle_dup(zhp), &ha);
4863 
4864         if (nvlist_empty(ha.nvl)) {
4865                 char errbuf[1024];
4866 
4867                 fnvlist_free(ha.nvl);
4868                 ret = ENOENT;
4869                 (void) snprintf(errbuf, sizeof (errbuf),
4870                     dgettext(TEXT_DOMAIN,
4871                     "cannot hold snapshot '%s@%s'"),
4872                     zhp->zfs_name, snapname);
4873                 (void) zfs_standard_error(zhp->zfs_hdl, ret, errbuf);
4874                 return (ret);
4875         }
4876 
4877         ret = zfs_hold_nvl(zhp, cleanup_fd, ha.nvl);
4878         fnvlist_free(ha.nvl);
4879 
4880         return (ret);
4881 }
4882 
4883 int
4884 zfs_hold_nvl(zfs_handle_t *zhp, int cleanup_fd, nvlist_t *holds)
4885 {
4886         int ret;
4887         nvlist_t *errors;
4888         libzfs_handle_t *hdl = zhp->zfs_hdl;
4889         char errbuf[1024];
4890         nvpair_t *elem;
4891 
4892         errors = NULL;
4893         ret = lzc_hold(holds, cleanup_fd, &errors);
4894 
4895         if (ret == 0) {
4896                 /* There may be errors even in the success case. */
4897                 fnvlist_free(errors);
4898                 return (0);
4899         }
4900 
4901         if (nvlist_empty(errors)) {
4902                 /* no hold-specific errors */
4903                 (void) snprintf(errbuf, sizeof (errbuf),
4904                     dgettext(TEXT_DOMAIN, "cannot hold"));
4905                 switch (ret) {
4906                 case ENOTSUP:
4907                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4908                             "pool must be upgraded"));
4909                         (void) zfs_error(hdl, EZFS_BADVERSION, errbuf);
4910                         break;
4911                 case EINVAL:
4912                         (void) zfs_error(hdl, EZFS_BADTYPE, errbuf);
4913                         break;
4914                 default:
4915                         (void) zfs_standard_error(hdl, ret, errbuf);
4916                 }
4917         }
4918 
4919         for (elem = nvlist_next_nvpair(errors, NULL);
4920             elem != NULL;
4921             elem = nvlist_next_nvpair(errors, elem)) {
4922                 (void) snprintf(errbuf, sizeof (errbuf),
4923                     dgettext(TEXT_DOMAIN,
4924                     "cannot hold snapshot '%s'"), nvpair_name(elem));
4925                 switch (fnvpair_value_int32(elem)) {
4926                 case E2BIG:
4927                         /*
4928                          * Temporary tags wind up having the ds object id
4929                          * prepended. So even if we passed the length check
4930                          * above, it's still possible for the tag to wind
4931                          * up being slightly too long.
4932                          */
4933                         (void) zfs_error(hdl, EZFS_TAGTOOLONG, errbuf);
4934                         break;
4935                 case EINVAL:
4936                         (void) zfs_error(hdl, EZFS_BADTYPE, errbuf);
4937                         break;
4938                 case EEXIST:
4939                         (void) zfs_error(hdl, EZFS_REFTAG_HOLD, errbuf);
4940                         break;
4941                 default:
4942                         (void) zfs_standard_error(hdl,
4943                             fnvpair_value_int32(elem), errbuf);
4944                 }
4945         }
4946 
4947         fnvlist_free(errors);
4948         return (ret);
4949 }
4950 
4951 static int
4952 zfs_release_one(zfs_handle_t *zhp, void *arg)
4953 {
4954         struct holdarg *ha = arg;
4955         char name[ZFS_MAX_DATASET_NAME_LEN];
4956         int rv = 0;
4957         nvlist_t *existing_holds;
4958 
4959         (void) snprintf(name, sizeof (name),
4960             "%s@%s", zhp->zfs_name, ha->snapname);
4961 
4962         if (lzc_get_holds(name, &existing_holds) != 0) {
4963                 ha->error = ENOENT;
4964         } else if (!nvlist_exists(existing_holds, ha->tag)) {
4965                 ha->error = ESRCH;
4966         } else {
4967                 nvlist_t *torelease = fnvlist_alloc();
4968                 fnvlist_add_boolean(torelease, ha->tag);
4969                 fnvlist_add_nvlist(ha->nvl, name, torelease);
4970                 fnvlist_free(torelease);
4971         }
4972 
4973         if (ha->recursive)
4974                 rv = zfs_iter_filesystems(zhp, zfs_release_one, ha);
4975         zfs_close(zhp);
4976         return (rv);
4977 }
4978 
4979 int
4980 zfs_release(zfs_handle_t *zhp, const char *snapname, const char *tag,
4981     boolean_t recursive)
4982 {
4983         int ret;
4984         struct holdarg ha;
4985         nvlist_t *errors = NULL;
4986         nvpair_t *elem;
4987         libzfs_handle_t *hdl = zhp->zfs_hdl;
4988         char errbuf[1024];
4989 
4990         ha.nvl = fnvlist_alloc();
4991         ha.snapname = snapname;
4992         ha.tag = tag;
4993         ha.recursive = recursive;
4994         ha.error = 0;
4995         (void) zfs_release_one(zfs_handle_dup(zhp), &ha);
4996 
4997         if (nvlist_empty(ha.nvl)) {
4998                 fnvlist_free(ha.nvl);
4999                 ret = ha.error;
5000                 (void) snprintf(errbuf, sizeof (errbuf),
5001                     dgettext(TEXT_DOMAIN,
5002                     "cannot release hold from snapshot '%s@%s'"),
5003                     zhp->zfs_name, snapname);
5004                 if (ret == ESRCH) {
5005                         (void) zfs_error(hdl, EZFS_REFTAG_RELE, errbuf);
5006                 } else {
5007                         (void) zfs_standard_error(hdl, ret, errbuf);
5008                 }
5009                 return (ret);
5010         }
5011 
5012         ret = lzc_release(ha.nvl, &errors);
5013         fnvlist_free(ha.nvl);
5014 
5015         if (ret == 0) {
5016                 /* There may be errors even in the success case. */
5017                 fnvlist_free(errors);
5018                 return (0);
5019         }
5020 
5021         if (nvlist_empty(errors)) {
5022                 /* no hold-specific errors */
5023                 (void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
5024                     "cannot release"));
5025                 switch (errno) {
5026                 case ENOTSUP:
5027                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
5028                             "pool must be upgraded"));
5029                         (void) zfs_error(hdl, EZFS_BADVERSION, errbuf);
5030                         break;
5031                 default:
5032                         (void) zfs_standard_error_fmt(hdl, errno, errbuf);
5033                 }
5034         }
5035 
5036         for (elem = nvlist_next_nvpair(errors, NULL);
5037             elem != NULL;
5038             elem = nvlist_next_nvpair(errors, elem)) {
5039                 (void) snprintf(errbuf, sizeof (errbuf),
5040                     dgettext(TEXT_DOMAIN,
5041                     "cannot release hold from snapshot '%s'"),
5042                     nvpair_name(elem));
5043                 switch (fnvpair_value_int32(elem)) {
5044                 case ESRCH:
5045                         (void) zfs_error(hdl, EZFS_REFTAG_RELE, errbuf);
5046                         break;
5047                 case EINVAL:
5048                         (void) zfs_error(hdl, EZFS_BADTYPE, errbuf);
5049                         break;
5050                 default:
5051                         (void) zfs_standard_error_fmt(hdl,
5052                             fnvpair_value_int32(elem), errbuf);
5053                 }
5054         }
5055 
5056         fnvlist_free(errors);
5057         return (ret);
5058 }
5059 
5060 int
5061 zfs_get_fsacl(zfs_handle_t *zhp, nvlist_t **nvl)
5062 {
5063         zfs_cmd_t zc = { 0 };
5064         libzfs_handle_t *hdl = zhp->zfs_hdl;
5065         int nvsz = 2048;
5066         void *nvbuf;
5067         int err = 0;
5068         char errbuf[1024];
5069 
5070         assert(zhp->zfs_type == ZFS_TYPE_VOLUME ||
5071             zhp->zfs_type == ZFS_TYPE_FILESYSTEM);
5072 
5073 tryagain:
5074 
5075         nvbuf = malloc(nvsz);
5076         if (nvbuf == NULL) {
5077                 err = (zfs_error(hdl, EZFS_NOMEM, strerror(errno)));
5078                 goto out;
5079         }
5080 
5081         zc.zc_nvlist_dst_size = nvsz;
5082         zc.zc_nvlist_dst = (uintptr_t)nvbuf;
5083 
5084         (void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
5085 
5086         if (ioctl(hdl->libzfs_fd, ZFS_IOC_GET_FSACL, &zc) != 0) {
5087                 (void) snprintf(errbuf, sizeof (errbuf),
5088                     dgettext(TEXT_DOMAIN, "cannot get permissions on '%s'"),
5089                     zc.zc_name);
5090                 switch (errno) {
5091                 case ENOMEM:
5092                         free(nvbuf);
5093                         nvsz = zc.zc_nvlist_dst_size;
5094                         goto tryagain;
5095 
5096                 case ENOTSUP:
5097                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
5098                             "pool must be upgraded"));
5099                         err = zfs_error(hdl, EZFS_BADVERSION, errbuf);
5100                         break;
5101                 case EINVAL:
5102                         err = zfs_error(hdl, EZFS_BADTYPE, errbuf);
5103                         break;
5104                 case ENOENT:
5105                         err = zfs_error(hdl, EZFS_NOENT, errbuf);
5106                         break;
5107                 default:
5108                         err = zfs_standard_error_fmt(hdl, errno, errbuf);
5109                         break;
5110                 }
5111         } else {
5112                 /* success */
5113                 int rc = nvlist_unpack(nvbuf, zc.zc_nvlist_dst_size, nvl, 0);
5114                 if (rc) {
5115                         (void) snprintf(errbuf, sizeof (errbuf), dgettext(
5116                             TEXT_DOMAIN, "cannot get permissions on '%s'"),
5117                             zc.zc_name);
5118                         err = zfs_standard_error_fmt(hdl, rc, errbuf);
5119                 }
5120         }
5121 
5122         free(nvbuf);
5123 out:
5124         return (err);
5125 }
5126 
5127 int
5128 zfs_set_fsacl(zfs_handle_t *zhp, boolean_t un, nvlist_t *nvl)
5129 {
5130         zfs_cmd_t zc = { 0 };
5131         libzfs_handle_t *hdl = zhp->zfs_hdl;
5132         char *nvbuf;
5133         char errbuf[1024];
5134         size_t nvsz;
5135         int err;
5136 
5137         assert(zhp->zfs_type == ZFS_TYPE_VOLUME ||
5138             zhp->zfs_type == ZFS_TYPE_FILESYSTEM);
5139 
5140         err = nvlist_size(nvl, &nvsz, NV_ENCODE_NATIVE);
5141         assert(err == 0);
5142 
5143         nvbuf = malloc(nvsz);
5144 
5145         err = nvlist_pack(nvl, &nvbuf, &nvsz, NV_ENCODE_NATIVE, 0);
5146         assert(err == 0);
5147 
5148         zc.zc_nvlist_src_size = nvsz;
5149         zc.zc_nvlist_src = (uintptr_t)nvbuf;
5150         zc.zc_perm_action = un;
5151 
5152         (void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
5153 
5154         if (zfs_ioctl(hdl, ZFS_IOC_SET_FSACL, &zc) != 0) {
5155                 (void) snprintf(errbuf, sizeof (errbuf),
5156                     dgettext(TEXT_DOMAIN, "cannot set permissions on '%s'"),
5157                     zc.zc_name);
5158                 switch (errno) {
5159                 case ENOTSUP:
5160                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
5161                             "pool must be upgraded"));
5162                         err = zfs_error(hdl, EZFS_BADVERSION, errbuf);
5163                         break;
5164                 case EINVAL:
5165                         err = zfs_error(hdl, EZFS_BADTYPE, errbuf);
5166                         break;
5167                 case ENOENT:
5168                         err = zfs_error(hdl, EZFS_NOENT, errbuf);
5169                         break;
5170                 default:
5171                         err = zfs_standard_error_fmt(hdl, errno, errbuf);
5172                         break;
5173                 }
5174         }
5175 
5176         free(nvbuf);
5177 
5178         return (err);
5179 }
5180 
5181 int
5182 zfs_get_holds(zfs_handle_t *zhp, nvlist_t **nvl)
5183 {
5184         int err;
5185         char errbuf[1024];
5186 
5187         err = lzc_get_holds(zhp->zfs_name, nvl);
5188 
5189         if (err != 0) {
5190                 libzfs_handle_t *hdl = zhp->zfs_hdl;
5191 
5192                 (void) snprintf(errbuf, sizeof (errbuf),
5193                     dgettext(TEXT_DOMAIN, "cannot get holds for '%s'"),
5194                     zhp->zfs_name);
5195                 switch (err) {
5196                 case ENOTSUP:
5197                         zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
5198                             "pool must be upgraded"));
5199                         err = zfs_error(hdl, EZFS_BADVERSION, errbuf);
5200                         break;
5201                 case EINVAL:
5202                         err = zfs_error(hdl, EZFS_BADTYPE, errbuf);
5203                         break;
5204                 case ENOENT:
5205                         err = zfs_error(hdl, EZFS_NOENT, errbuf);
5206                         break;
5207                 default:
5208                         err = zfs_standard_error_fmt(hdl, errno, errbuf);
5209                         break;
5210                 }
5211         }
5212 
5213         return (err);
5214 }
5215 
5216 /*
5217  * The theory of raidz space accounting
5218  *
5219  * The "referenced" property of RAIDZ vdevs is scaled such that a 128KB block
5220  * will "reference" 128KB, even though it allocates more than that, to store the
5221  * parity information (and perhaps skip sectors). This concept of the
5222  * "referenced" (and other DMU space accounting) being lower than the allocated
5223  * space by a constant factor is called "raidz deflation."
5224  *
5225  * As mentioned above, the constant factor for raidz deflation assumes a 128KB
5226  * block size. However, zvols typically have a much smaller block size (default
5227  * 8KB). These smaller blocks may require proportionally much more parity
5228  * information (and perhaps skip sectors). In this case, the change to the
5229  * "referenced" property may be much more than the logical block size.
5230  *
5231  * Suppose a raidz vdev has 5 disks with ashift=12.  A 128k block may be written
5232  * as follows.
5233  *
5234  * +-------+-------+-------+-------+-------+
5235  * | disk1 | disk2 | disk3 | disk4 | disk5 |
5236  * +-------+-------+-------+-------+-------+
5237  * |  P0   |  D0   |  D8   |  D16  |  D24  |
5238  * |  P1   |  D1   |  D9   |  D17  |  D25  |
5239  * |  P2   |  D2   |  D10  |  D18  |  D26  |
5240  * |  P3   |  D3   |  D11  |  D19  |  D27  |
5241  * |  P4   |  D4   |  D12  |  D20  |  D28  |
5242  * |  P5   |  D5   |  D13  |  D21  |  D29  |
5243  * |  P6   |  D6   |  D14  |  D22  |  D30  |
5244  * |  P7   |  D7   |  D15  |  D23  |  D31  |
5245  * +-------+-------+-------+-------+-------+
5246  *
5247  * Above, notice that 160k was allocated: 8 x 4k parity sectors + 32 x 4k data
5248  * sectors.  The dataset's referenced will increase by 128k and the pool's
5249  * allocated and free properties will be adjusted by 160k.
5250  *
5251  * A 4k block written to the same raidz vdev will require two 4k sectors.  The
5252  * blank cells represent unallocated space.
5253  *
5254  * +-------+-------+-------+-------+-------+
5255  * | disk1 | disk2 | disk3 | disk4 | disk5 |
5256  * +-------+-------+-------+-------+-------+
5257  * |  P0   |  D0   |       |       |       |
5258  * +-------+-------+-------+-------+-------+
5259  *
5260  * Above, notice that the 4k block required one sector for parity and another
5261  * for data.  vdev_raidz_asize() will return 8k and as such the pool's allocated
5262  * and free properties will be adjusted by 8k.  The dataset will not be charged
5263  * 8k.  Rather, it will be charged a value that is scaled according to the
5264  * overhead of the 128k block on the same vdev.  This 8k allocation will be
5265  * charged 8k * 128k / 160k.  128k is from SPA_OLD_MAXBLOCKSIZE and 160k is as
5266  * calculated in the 128k block example above.
5267  *
5268  * Every raidz allocation is sized to be a multiple of nparity+1 sectors.  That
5269  * is, every raidz1 allocation will be a multiple of 2 sectors, raidz2
5270  * allocations are a multiple of 3 sectors, and raidz3 allocations are a
5271  * multiple of of 4 sectors.  When a block does not fill the required number of
5272  * sectors, skip blocks (sectors) are used.
5273  *
5274  * An 8k block being written to a raidz vdev may be written as follows:
5275  *
5276  * +-------+-------+-------+-------+-------+
5277  * | disk1 | disk2 | disk3 | disk4 | disk5 |
5278  * +-------+-------+-------+-------+-------+
5279  * |  P0   |  D0   |  D1   |  S0   |       |
5280  * +-------+-------+-------+-------+-------+
5281  *
5282  * In order to maintain the nparity+1 allocation size, a skip block (S0) was
5283  * added.  For this 8k block, the pool's allocated and free properties are
5284  * adjusted by 16k and the dataset's referenced is increased by 16k * 128k /
5285  * 160k.  Again, 128k is from SPA_OLD_MAXBLOCKSIZE and 160k is as calculated in
5286  * the 128k block example above.
5287  *
5288  * Compression may lead to a variety of block sizes being written for the same
5289  * volume or file.  There is no clear way to reserve just the amount of space
5290  * that will be required, so the worst case (no compression) is assumed.
5291  * Note that metadata blocks will typically be compressed, so the reservation
5292  * size returned by zvol_volsize_to_reservation() will generally be slightly
5293  * larger than the maximum that the volume can reference.
5294  */
5295 
5296 /*
5297  * Derived from function of same name in uts/common/fs/zfs/vdev_raidz.c.
5298  * Returns the amount of space (in bytes) that will be allocated for the
5299  * specified block size. Note that the "referenced" space accounted will be less
5300  * than this, but not necessarily equal to "blksize", due to RAIDZ deflation.
5301  */
5302 static uint64_t
5303 vdev_raidz_asize(uint64_t ndisks, uint64_t nparity, uint64_t ashift,
5304     uint64_t blksize)
5305 {
5306         uint64_t asize, ndata;
5307 
5308         ASSERT3U(ndisks, >, nparity);
5309         ndata = ndisks - nparity;
5310         asize = ((blksize - 1) >> ashift) + 1;
5311         asize += nparity * ((asize + ndata - 1) / ndata);
5312         asize = roundup(asize, nparity + 1) << ashift;
5313 
5314         return (asize);
5315 }
5316 
5317 /*
5318  * Determine how much space will be allocated if it lands on the most space-
5319  * inefficient top-level vdev.  Returns the size in bytes required to store one
5320  * copy of the volume data.  See theory comment above.
5321  */
5322 static uint64_t
5323 volsize_from_vdevs(zpool_handle_t *zhp, uint64_t nblocks, uint64_t blksize)
5324 {
5325         nvlist_t *config, *tree, **vdevs;
5326         uint_t nvdevs, v;
5327         uint64_t ret = 0;
5328 
5329         config = zpool_get_config(zhp, NULL);
5330         if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, &tree) != 0 ||
5331             nvlist_lookup_nvlist_array(tree, ZPOOL_CONFIG_CHILDREN,
5332             &vdevs, &nvdevs) != 0) {
5333                 return (nblocks * blksize);
5334         }
5335 
5336         for (v = 0; v < nvdevs; v++) {
5337                 char *type;
5338                 uint64_t nparity, ashift, asize, tsize;
5339                 nvlist_t **disks;
5340                 uint_t ndisks;
5341                 uint64_t volsize;
5342 
5343                 if (nvlist_lookup_string(vdevs[v], ZPOOL_CONFIG_TYPE,
5344                     &type) != 0 || strcmp(type, VDEV_TYPE_RAIDZ) != 0 ||
5345                     nvlist_lookup_uint64(vdevs[v], ZPOOL_CONFIG_NPARITY,
5346                     &nparity) != 0 ||
5347                     nvlist_lookup_uint64(vdevs[v], ZPOOL_CONFIG_ASHIFT,
5348                     &ashift) != 0 ||
5349                     nvlist_lookup_nvlist_array(vdevs[v], ZPOOL_CONFIG_CHILDREN,
5350                     &disks, &ndisks) != 0) {
5351                         continue;
5352                 }
5353 
5354                 /* allocation size for the "typical" 128k block */
5355                 tsize = vdev_raidz_asize(ndisks, nparity, ashift,
5356                     SPA_OLD_MAXBLOCKSIZE);
5357                 /* allocation size for the blksize block */
5358                 asize = vdev_raidz_asize(ndisks, nparity, ashift, blksize);
5359 
5360                 /*
5361                  * Scale this size down as a ratio of 128k / tsize.  See theory
5362                  * statement above.
5363                  */
5364                 volsize = nblocks * asize * SPA_OLD_MAXBLOCKSIZE / tsize;
5365                 if (volsize > ret) {
5366                         ret = volsize;
5367                 }
5368         }
5369 
5370         if (ret == 0) {
5371                 ret = nblocks * blksize;
5372         }
5373 
5374         return (ret);
5375 }
5376 
5377 /*
5378  * Convert the zvol's volume size to an appropriate reservation.  See theory
5379  * comment above.
5380  *
5381  * Note: If this routine is updated, it is necessary to update the ZFS test
5382  * suite's shell version in reservation.shlib.
5383  */
5384 uint64_t
5385 zvol_volsize_to_reservation(zpool_handle_t *zph, uint64_t volsize,
5386     nvlist_t *props)
5387 {
5388         uint64_t numdb;
5389         uint64_t nblocks, volblocksize;
5390         int ncopies;
5391         char *strval;
5392 
5393         if (nvlist_lookup_string(props,
5394             zfs_prop_to_name(ZFS_PROP_COPIES), &strval) == 0)
5395                 ncopies = atoi(strval);
5396         else
5397                 ncopies = 1;
5398         if (nvlist_lookup_uint64(props,
5399             zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE),
5400             &volblocksize) != 0)
5401                 volblocksize = ZVOL_DEFAULT_BLOCKSIZE;
5402 
5403         nblocks = volsize / volblocksize;
5404         /*
5405          * Metadata defaults to using 128k blocks, not volblocksize blocks.  For
5406          * this reason, only the data blocks are scaled based on vdev config.
5407          */
5408         volsize = volsize_from_vdevs(zph, nblocks, volblocksize);
5409 
5410         /* start with metadnode L0-L6 */
5411         numdb = 7;
5412         /* calculate number of indirects */
5413         while (nblocks > 1) {
5414                 nblocks += DNODES_PER_LEVEL - 1;
5415                 nblocks /= DNODES_PER_LEVEL;
5416                 numdb += nblocks;
5417         }
5418         numdb *= MIN(SPA_DVAS_PER_BP, ncopies + 1);
5419         volsize *= ncopies;
5420         /*
5421          * this is exactly DN_MAX_INDBLKSHIFT when metadata isn't
5422          * compressed, but in practice they compress down to about
5423          * 1100 bytes
5424          */
5425         numdb *= 1ULL << DN_MAX_INDBLKSHIFT;
5426         volsize += numdb;
5427         return (volsize);
5428 }