1 /*
   2  * CDDL HEADER START
   3  *
   4  * The contents of this file are subject to the terms of the
   5  * Common Development and Distribution License (the "License").
   6  * You may not use this file except in compliance with the License.
   7  *
   8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
   9  * or http://www.opensolaris.org/os/licensing.
  10  * See the License for the specific language governing permissions
  11  * and limitations under the License.
  12  *
  13  * When distributing Covered Code, include this CDDL HEADER in each
  14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
  15  * If applicable, add the following below this CDDL HEADER, with the
  16  * fields enclosed by brackets "[]" replaced with your own identifying
  17  * information: Portions Copyright [yyyy] [name of copyright owner]
  18  *
  19  * CDDL HEADER END
  20  */
  21 
  22 /*
  23  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
  24  * Copyright (c) 2011-2012 Pawel Jakub Dawidek. All rights reserved.
  25  * Portions Copyright 2011 Martin Matuska
  26  * Copyright 2015, OmniTI Computer Consulting, Inc. All rights reserved.
  27  * Copyright 2015 Nexenta Systems, Inc.  All rights reserved.
  28  * Copyright (c) 2014, 2016 Joyent, Inc. All rights reserved.
  29  * Copyright (c) 2011, 2017 by Delphix. All rights reserved.
  30  * Copyright (c) 2013 by Saso Kiselkov. All rights reserved.
  31  * Copyright (c) 2013 Steven Hartland. All rights reserved.
  32  * Copyright (c) 2014 Integros [integros.com]
  33  * Copyright 2016 Toomas Soome <tsoome@me.com>
  34  * Copyright 2017 RackTop Systems.
  35  * Copyright (c) 2017 Datto Inc.
  36  */
  37 
  38 /*
  39  * ZFS ioctls.
  40  *
  41  * This file handles the ioctls to /dev/zfs, used for configuring ZFS storage
  42  * pools and filesystems, e.g. with /sbin/zfs and /sbin/zpool.
  43  *
  44  * There are two ways that we handle ioctls: the legacy way where almost
  45  * all of the logic is in the ioctl callback, and the new way where most
  46  * of the marshalling is handled in the common entry point, zfsdev_ioctl().
  47  *
  48  * Non-legacy ioctls should be registered by calling
  49  * zfs_ioctl_register() from zfs_ioctl_init().  The ioctl is invoked
  50  * from userland by lzc_ioctl().
  51  *
  52  * The registration arguments are as follows:
  53  *
  54  * const char *name
  55  *   The name of the ioctl.  This is used for history logging.  If the
  56  *   ioctl returns successfully (the callback returns 0), and allow_log
  57  *   is true, then a history log entry will be recorded with the input &
  58  *   output nvlists.  The log entry can be printed with "zpool history -i".
  59  *
  60  * zfs_ioc_t ioc
  61  *   The ioctl request number, which userland will pass to ioctl(2).
  62  *   The ioctl numbers can change from release to release, because
  63  *   the caller (libzfs) must be matched to the kernel.
  64  *
  65  * zfs_secpolicy_func_t *secpolicy
  66  *   This function will be called before the zfs_ioc_func_t, to
  67  *   determine if this operation is permitted.  It should return EPERM
  68  *   on failure, and 0 on success.  Checks include determining if the
  69  *   dataset is visible in this zone, and if the user has either all
  70  *   zfs privileges in the zone (SYS_MOUNT), or has been granted permission
  71  *   to do this operation on this dataset with "zfs allow".
  72  *
  73  * zfs_ioc_namecheck_t namecheck
  74  *   This specifies what to expect in the zfs_cmd_t:zc_name -- a pool
  75  *   name, a dataset name, or nothing.  If the name is not well-formed,
  76  *   the ioctl will fail and the callback will not be called.
  77  *   Therefore, the callback can assume that the name is well-formed
  78  *   (e.g. is null-terminated, doesn't have more than one '@' character,
  79  *   doesn't have invalid characters).
  80  *
  81  * zfs_ioc_poolcheck_t pool_check
  82  *   This specifies requirements on the pool state.  If the pool does
  83  *   not meet them (is suspended or is readonly), the ioctl will fail
  84  *   and the callback will not be called.  If any checks are specified
  85  *   (i.e. it is not POOL_CHECK_NONE), namecheck must not be NO_NAME.
  86  *   Multiple checks can be or-ed together (e.g. POOL_CHECK_SUSPENDED |
  87  *   POOL_CHECK_READONLY).
  88  *
  89  * boolean_t smush_outnvlist
  90  *   If smush_outnvlist is true, then the output is presumed to be a
  91  *   list of errors, and it will be "smushed" down to fit into the
  92  *   caller's buffer, by removing some entries and replacing them with a
  93  *   single "N_MORE_ERRORS" entry indicating how many were removed.  See
  94  *   nvlist_smush() for details.  If smush_outnvlist is false, and the
  95  *   outnvlist does not fit into the userland-provided buffer, then the
  96  *   ioctl will fail with ENOMEM.
  97  *
  98  * zfs_ioc_func_t *func
  99  *   The callback function that will perform the operation.
 100  *
 101  *   The callback should return 0 on success, or an error number on
 102  *   failure.  If the function fails, the userland ioctl will return -1,
 103  *   and errno will be set to the callback's return value.  The callback
 104  *   will be called with the following arguments:
 105  *
 106  *   const char *name
 107  *     The name of the pool or dataset to operate on, from
 108  *     zfs_cmd_t:zc_name.  The 'namecheck' argument specifies the
 109  *     expected type (pool, dataset, or none).
 110  *
 111  *   nvlist_t *innvl
 112  *     The input nvlist, deserialized from zfs_cmd_t:zc_nvlist_src.  Or
 113  *     NULL if no input nvlist was provided.  Changes to this nvlist are
 114  *     ignored.  If the input nvlist could not be deserialized, the
 115  *     ioctl will fail and the callback will not be called.
 116  *
 117  *   nvlist_t *outnvl
 118  *     The output nvlist, initially empty.  The callback can fill it in,
 119  *     and it will be returned to userland by serializing it into
 120  *     zfs_cmd_t:zc_nvlist_dst.  If it is non-empty, and serialization
 121  *     fails (e.g. because the caller didn't supply a large enough
 122  *     buffer), then the overall ioctl will fail.  See the
 123  *     'smush_nvlist' argument above for additional behaviors.
 124  *
 125  *     There are two typical uses of the output nvlist:
 126  *       - To return state, e.g. property values.  In this case,
 127  *         smush_outnvlist should be false.  If the buffer was not large
 128  *         enough, the caller will reallocate a larger buffer and try
 129  *         the ioctl again.
 130  *
 131  *       - To return multiple errors from an ioctl which makes on-disk
 132  *         changes.  In this case, smush_outnvlist should be true.
 133  *         Ioctls which make on-disk modifications should generally not
 134  *         use the outnvl if they succeed, because the caller can not
 135  *         distinguish between the operation failing, and
 136  *         deserialization failing.
 137  */
 138 
 139 #include <sys/types.h>
 140 #include <sys/param.h>
 141 #include <sys/errno.h>
 142 #include <sys/uio.h>
 143 #include <sys/buf.h>
 144 #include <sys/modctl.h>
 145 #include <sys/open.h>
 146 #include <sys/file.h>
 147 #include <sys/kmem.h>
 148 #include <sys/conf.h>
 149 #include <sys/cmn_err.h>
 150 #include <sys/stat.h>
 151 #include <sys/zfs_ioctl.h>
 152 #include <sys/zfs_vfsops.h>
 153 #include <sys/zfs_znode.h>
 154 #include <sys/zap.h>
 155 #include <sys/spa.h>
 156 #include <sys/spa_impl.h>
 157 #include <sys/vdev.h>
 158 #include <sys/priv_impl.h>
 159 #include <sys/dmu.h>
 160 #include <sys/dsl_dir.h>
 161 #include <sys/dsl_dataset.h>
 162 #include <sys/dsl_prop.h>
 163 #include <sys/dsl_deleg.h>
 164 #include <sys/dmu_objset.h>
 165 #include <sys/dmu_impl.h>
 166 #include <sys/dmu_tx.h>
 167 #include <sys/ddi.h>
 168 #include <sys/sunddi.h>
 169 #include <sys/sunldi.h>
 170 #include <sys/policy.h>
 171 #include <sys/zone.h>
 172 #include <sys/nvpair.h>
 173 #include <sys/pathname.h>
 174 #include <sys/mount.h>
 175 #include <sys/sdt.h>
 176 #include <sys/fs/zfs.h>
 177 #include <sys/zfs_ctldir.h>
 178 #include <sys/zfs_dir.h>
 179 #include <sys/zfs_onexit.h>
 180 #include <sys/zvol.h>
 181 #include <sys/dsl_scan.h>
 182 #include <sharefs/share.h>
 183 #include <sys/dmu_objset.h>
 184 #include <sys/dmu_send.h>
 185 #include <sys/dsl_destroy.h>
 186 #include <sys/dsl_bookmark.h>
 187 #include <sys/dsl_userhold.h>
 188 #include <sys/zfeature.h>
 189 #include <sys/zcp.h>
 190 #include <sys/zio_checksum.h>
 191 #include <sys/vdev_removal.h>
 192 
 193 #include "zfs_namecheck.h"
 194 #include "zfs_prop.h"
 195 #include "zfs_deleg.h"
 196 #include "zfs_comutil.h"
 197 
 198 #include "lua.h"
 199 #include "lauxlib.h"
 200 
 201 extern struct modlfs zfs_modlfs;
 202 
 203 extern void zfs_init(void);
 204 extern void zfs_fini(void);
 205 
 206 ldi_ident_t zfs_li = NULL;
 207 dev_info_t *zfs_dip;
 208 
 209 uint_t zfs_fsyncer_key;
 210 extern uint_t rrw_tsd_key;
 211 static uint_t zfs_allow_log_key;
 212 
 213 typedef int zfs_ioc_legacy_func_t(zfs_cmd_t *);
 214 typedef int zfs_ioc_func_t(const char *, nvlist_t *, nvlist_t *);
 215 typedef int zfs_secpolicy_func_t(zfs_cmd_t *, nvlist_t *, cred_t *);
 216 
 217 typedef enum {
 218         NO_NAME,
 219         POOL_NAME,
 220         DATASET_NAME
 221 } zfs_ioc_namecheck_t;
 222 
 223 typedef enum {
 224         POOL_CHECK_NONE         = 1 << 0,
 225         POOL_CHECK_SUSPENDED    = 1 << 1,
 226         POOL_CHECK_READONLY     = 1 << 2,
 227 } zfs_ioc_poolcheck_t;
 228 
 229 typedef struct zfs_ioc_vec {
 230         zfs_ioc_legacy_func_t   *zvec_legacy_func;
 231         zfs_ioc_func_t          *zvec_func;
 232         zfs_secpolicy_func_t    *zvec_secpolicy;
 233         zfs_ioc_namecheck_t     zvec_namecheck;
 234         boolean_t               zvec_allow_log;
 235         zfs_ioc_poolcheck_t     zvec_pool_check;
 236         boolean_t               zvec_smush_outnvlist;
 237         const char              *zvec_name;
 238 } zfs_ioc_vec_t;
 239 
 240 /* This array is indexed by zfs_userquota_prop_t */
 241 static const char *userquota_perms[] = {
 242         ZFS_DELEG_PERM_USERUSED,
 243         ZFS_DELEG_PERM_USERQUOTA,
 244         ZFS_DELEG_PERM_GROUPUSED,
 245         ZFS_DELEG_PERM_GROUPQUOTA,
 246 };
 247 
 248 static int zfs_ioc_userspace_upgrade(zfs_cmd_t *zc);
 249 static int zfs_check_settable(const char *name, nvpair_t *property,
 250     cred_t *cr);
 251 static int zfs_check_clearable(char *dataset, nvlist_t *props,
 252     nvlist_t **errors);
 253 static int zfs_fill_zplprops_root(uint64_t, nvlist_t *, nvlist_t *,
 254     boolean_t *);
 255 int zfs_set_prop_nvlist(const char *, zprop_source_t, nvlist_t *, nvlist_t *);
 256 static int get_nvlist(uint64_t nvl, uint64_t size, int iflag, nvlist_t **nvp);
 257 
 258 static int zfs_prop_activate_feature(spa_t *spa, spa_feature_t feature);
 259 
 260 /* _NOTE(PRINTFLIKE(4)) - this is printf-like, but lint is too whiney */
 261 void
 262 __dprintf(const char *file, const char *func, int line, const char *fmt, ...)
 263 {
 264         const char *newfile;
 265         char buf[512];
 266         va_list adx;
 267 
 268         /*
 269          * Get rid of annoying "../common/" prefix to filename.
 270          */
 271         newfile = strrchr(file, '/');
 272         if (newfile != NULL) {
 273                 newfile = newfile + 1; /* Get rid of leading / */
 274         } else {
 275                 newfile = file;
 276         }
 277 
 278         va_start(adx, fmt);
 279         (void) vsnprintf(buf, sizeof (buf), fmt, adx);
 280         va_end(adx);
 281 
 282         /*
 283          * To get this data, use the zfs-dprintf probe as so:
 284          * dtrace -q -n 'zfs-dprintf \
 285          *      /stringof(arg0) == "dbuf.c"/ \
 286          *      {printf("%s: %s", stringof(arg1), stringof(arg3))}'
 287          * arg0 = file name
 288          * arg1 = function name
 289          * arg2 = line number
 290          * arg3 = message
 291          */
 292         DTRACE_PROBE4(zfs__dprintf,
 293             char *, newfile, char *, func, int, line, char *, buf);
 294 }
 295 
 296 static void
 297 history_str_free(char *buf)
 298 {
 299         kmem_free(buf, HIS_MAX_RECORD_LEN);
 300 }
 301 
 302 static char *
 303 history_str_get(zfs_cmd_t *zc)
 304 {
 305         char *buf;
 306 
 307         if (zc->zc_history == NULL)
 308                 return (NULL);
 309 
 310         buf = kmem_alloc(HIS_MAX_RECORD_LEN, KM_SLEEP);
 311         if (copyinstr((void *)(uintptr_t)zc->zc_history,
 312             buf, HIS_MAX_RECORD_LEN, NULL) != 0) {
 313                 history_str_free(buf);
 314                 return (NULL);
 315         }
 316 
 317         buf[HIS_MAX_RECORD_LEN -1] = '\0';
 318 
 319         return (buf);
 320 }
 321 
 322 /*
 323  * Check to see if the named dataset is currently defined as bootable
 324  */
 325 static boolean_t
 326 zfs_is_bootfs(const char *name)
 327 {
 328         objset_t *os;
 329 
 330         if (dmu_objset_hold(name, FTAG, &os) == 0) {
 331                 boolean_t ret;
 332                 ret = (dmu_objset_id(os) == spa_bootfs(dmu_objset_spa(os)));
 333                 dmu_objset_rele(os, FTAG);
 334                 return (ret);
 335         }
 336         return (B_FALSE);
 337 }
 338 
 339 /*
 340  * Return non-zero if the spa version is less than requested version.
 341  */
 342 static int
 343 zfs_earlier_version(const char *name, int version)
 344 {
 345         spa_t *spa;
 346 
 347         if (spa_open(name, &spa, FTAG) == 0) {
 348                 if (spa_version(spa) < version) {
 349                         spa_close(spa, FTAG);
 350                         return (1);
 351                 }
 352                 spa_close(spa, FTAG);
 353         }
 354         return (0);
 355 }
 356 
 357 /*
 358  * Return TRUE if the ZPL version is less than requested version.
 359  */
 360 static boolean_t
 361 zpl_earlier_version(const char *name, int version)
 362 {
 363         objset_t *os;
 364         boolean_t rc = B_TRUE;
 365 
 366         if (dmu_objset_hold(name, FTAG, &os) == 0) {
 367                 uint64_t zplversion;
 368 
 369                 if (dmu_objset_type(os) != DMU_OST_ZFS) {
 370                         dmu_objset_rele(os, FTAG);
 371                         return (B_TRUE);
 372                 }
 373                 /* XXX reading from non-owned objset */
 374                 if (zfs_get_zplprop(os, ZFS_PROP_VERSION, &zplversion) == 0)
 375                         rc = zplversion < version;
 376                 dmu_objset_rele(os, FTAG);
 377         }
 378         return (rc);
 379 }
 380 
 381 static void
 382 zfs_log_history(zfs_cmd_t *zc)
 383 {
 384         spa_t *spa;
 385         char *buf;
 386 
 387         if ((buf = history_str_get(zc)) == NULL)
 388                 return;
 389 
 390         if (spa_open(zc->zc_name, &spa, FTAG) == 0) {
 391                 if (spa_version(spa) >= SPA_VERSION_ZPOOL_HISTORY)
 392                         (void) spa_history_log(spa, buf);
 393                 spa_close(spa, FTAG);
 394         }
 395         history_str_free(buf);
 396 }
 397 
 398 /*
 399  * Policy for top-level read operations (list pools).  Requires no privileges,
 400  * and can be used in the local zone, as there is no associated dataset.
 401  */
 402 /* ARGSUSED */
 403 static int
 404 zfs_secpolicy_none(zfs_cmd_t *zc, nvlist_t *innvl, cred_t *cr)
 405 {
 406         return (0);
 407 }
 408 
 409 /*
 410  * Policy for dataset read operations (list children, get statistics).  Requires
 411  * no privileges, but must be visible in the local zone.
 412  */
 413 /* ARGSUSED */
 414 static int
 415 zfs_secpolicy_read(zfs_cmd_t *zc, nvlist_t *innvl, cred_t *cr)
 416 {
 417         if (INGLOBALZONE(curproc) ||
 418             zone_dataset_visible(zc->zc_name, NULL))
 419                 return (0);
 420 
 421         return (SET_ERROR(ENOENT));
 422 }
 423 
 424 static int
 425 zfs_dozonecheck_impl(const char *dataset, uint64_t zoned, cred_t *cr)
 426 {
 427         int writable = 1;
 428 
 429         /*
 430          * The dataset must be visible by this zone -- check this first
 431          * so they don't see EPERM on something they shouldn't know about.
 432          */
 433         if (!INGLOBALZONE(curproc) &&
 434             !zone_dataset_visible(dataset, &writable))
 435                 return (SET_ERROR(ENOENT));
 436 
 437         if (INGLOBALZONE(curproc)) {
 438                 /*
 439                  * If the fs is zoned, only root can access it from the
 440                  * global zone.
 441                  */
 442                 if (secpolicy_zfs(cr) && zoned)
 443                         return (SET_ERROR(EPERM));
 444         } else {
 445                 /*
 446                  * If we are in a local zone, the 'zoned' property must be set.
 447                  */
 448                 if (!zoned)
 449                         return (SET_ERROR(EPERM));
 450 
 451                 /* must be writable by this zone */
 452                 if (!writable)
 453                         return (SET_ERROR(EPERM));
 454         }
 455         return (0);
 456 }
 457 
 458 static int
 459 zfs_dozonecheck(const char *dataset, cred_t *cr)
 460 {
 461         uint64_t zoned;
 462 
 463         if (dsl_prop_get_integer(dataset, "zoned", &zoned, NULL))
 464                 return (SET_ERROR(ENOENT));
 465 
 466         return (zfs_dozonecheck_impl(dataset, zoned, cr));
 467 }
 468 
 469 static int
 470 zfs_dozonecheck_ds(const char *dataset, dsl_dataset_t *ds, cred_t *cr)
 471 {
 472         uint64_t zoned;
 473 
 474         if (dsl_prop_get_int_ds(ds, "zoned", &zoned))
 475                 return (SET_ERROR(ENOENT));
 476 
 477         return (zfs_dozonecheck_impl(dataset, zoned, cr));
 478 }
 479 
 480 static int
 481 zfs_secpolicy_write_perms_ds(const char *name, dsl_dataset_t *ds,
 482     const char *perm, cred_t *cr)
 483 {
 484         int error;
 485 
 486         error = zfs_dozonecheck_ds(name, ds, cr);
 487         if (error == 0) {
 488                 error = secpolicy_zfs(cr);
 489                 if (error != 0)
 490                         error = dsl_deleg_access_impl(ds, perm, cr);
 491         }
 492         return (error);
 493 }
 494 
 495 static int
 496 zfs_secpolicy_write_perms(const char *name, const char *perm, cred_t *cr)
 497 {
 498         int error;
 499         dsl_dataset_t *ds;
 500         dsl_pool_t *dp;
 501 
 502         /*
 503          * First do a quick check for root in the global zone, which
 504          * is allowed to do all write_perms.  This ensures that zfs_ioc_*
 505          * will get to handle nonexistent datasets.
 506          */
 507         if (INGLOBALZONE(curproc) && secpolicy_zfs(cr) == 0)
 508                 return (0);
 509 
 510         error = dsl_pool_hold(name, FTAG, &dp);
 511         if (error != 0)
 512                 return (error);
 513 
 514         error = dsl_dataset_hold(dp, name, FTAG, &ds);
 515         if (error != 0) {
 516                 dsl_pool_rele(dp, FTAG);
 517                 return (error);
 518         }
 519 
 520         error = zfs_secpolicy_write_perms_ds(name, ds, perm, cr);
 521 
 522         dsl_dataset_rele(ds, FTAG);
 523         dsl_pool_rele(dp, FTAG);
 524         return (error);
 525 }
 526 
 527 /*
 528  * Policy for setting the security label property.
 529  *
 530  * Returns 0 for success, non-zero for access and other errors.
 531  */
 532 static int
 533 zfs_set_slabel_policy(const char *name, char *strval, cred_t *cr)
 534 {
 535         char            ds_hexsl[MAXNAMELEN];
 536         bslabel_t       ds_sl, new_sl;
 537         boolean_t       new_default = FALSE;
 538         uint64_t        zoned;
 539         int             needed_priv = -1;
 540         int             error;
 541 
 542         /* First get the existing dataset label. */
 543         error = dsl_prop_get(name, zfs_prop_to_name(ZFS_PROP_MLSLABEL),
 544             1, sizeof (ds_hexsl), &ds_hexsl, NULL);
 545         if (error != 0)
 546                 return (SET_ERROR(EPERM));
 547 
 548         if (strcasecmp(strval, ZFS_MLSLABEL_DEFAULT) == 0)
 549                 new_default = TRUE;
 550 
 551         /* The label must be translatable */
 552         if (!new_default && (hexstr_to_label(strval, &new_sl) != 0))
 553                 return (SET_ERROR(EINVAL));
 554 
 555         /*
 556          * In a non-global zone, disallow attempts to set a label that
 557          * doesn't match that of the zone; otherwise no other checks
 558          * are needed.
 559          */
 560         if (!INGLOBALZONE(curproc)) {
 561                 if (new_default || !blequal(&new_sl, CR_SL(CRED())))
 562                         return (SET_ERROR(EPERM));
 563                 return (0);
 564         }
 565 
 566         /*
 567          * For global-zone datasets (i.e., those whose zoned property is
 568          * "off", verify that the specified new label is valid for the
 569          * global zone.
 570          */
 571         if (dsl_prop_get_integer(name,
 572             zfs_prop_to_name(ZFS_PROP_ZONED), &zoned, NULL))
 573                 return (SET_ERROR(EPERM));
 574         if (!zoned) {
 575                 if (zfs_check_global_label(name, strval) != 0)
 576                         return (SET_ERROR(EPERM));
 577         }
 578 
 579         /*
 580          * If the existing dataset label is nondefault, check if the
 581          * dataset is mounted (label cannot be changed while mounted).
 582          * Get the zfsvfs; if there isn't one, then the dataset isn't
 583          * mounted (or isn't a dataset, doesn't exist, ...).
 584          */
 585         if (strcasecmp(ds_hexsl, ZFS_MLSLABEL_DEFAULT) != 0) {
 586                 objset_t *os;
 587                 static char *setsl_tag = "setsl_tag";
 588 
 589                 /*
 590                  * Try to own the dataset; abort if there is any error,
 591                  * (e.g., already mounted, in use, or other error).
 592                  */
 593                 error = dmu_objset_own(name, DMU_OST_ZFS, B_TRUE,
 594                     setsl_tag, &os);
 595                 if (error != 0)
 596                         return (SET_ERROR(EPERM));
 597 
 598                 dmu_objset_disown(os, setsl_tag);
 599 
 600                 if (new_default) {
 601                         needed_priv = PRIV_FILE_DOWNGRADE_SL;
 602                         goto out_check;
 603                 }
 604 
 605                 if (hexstr_to_label(strval, &new_sl) != 0)
 606                         return (SET_ERROR(EPERM));
 607 
 608                 if (blstrictdom(&ds_sl, &new_sl))
 609                         needed_priv = PRIV_FILE_DOWNGRADE_SL;
 610                 else if (blstrictdom(&new_sl, &ds_sl))
 611                         needed_priv = PRIV_FILE_UPGRADE_SL;
 612         } else {
 613                 /* dataset currently has a default label */
 614                 if (!new_default)
 615                         needed_priv = PRIV_FILE_UPGRADE_SL;
 616         }
 617 
 618 out_check:
 619         if (needed_priv != -1)
 620                 return (PRIV_POLICY(cr, needed_priv, B_FALSE, EPERM, NULL));
 621         return (0);
 622 }
 623 
 624 static int
 625 zfs_secpolicy_setprop(const char *dsname, zfs_prop_t prop, nvpair_t *propval,
 626     cred_t *cr)
 627 {
 628         char *strval;
 629 
 630         /*
 631          * Check permissions for special properties.
 632          */
 633         switch (prop) {
 634         case ZFS_PROP_ZONED:
 635                 /*
 636                  * Disallow setting of 'zoned' from within a local zone.
 637                  */
 638                 if (!INGLOBALZONE(curproc))
 639                         return (SET_ERROR(EPERM));
 640                 break;
 641 
 642         case ZFS_PROP_QUOTA:
 643         case ZFS_PROP_FILESYSTEM_LIMIT:
 644         case ZFS_PROP_SNAPSHOT_LIMIT:
 645                 if (!INGLOBALZONE(curproc)) {
 646                         uint64_t zoned;
 647                         char setpoint[ZFS_MAX_DATASET_NAME_LEN];
 648                         /*
 649                          * Unprivileged users are allowed to modify the
 650                          * limit on things *under* (ie. contained by)
 651                          * the thing they own.
 652                          */
 653                         if (dsl_prop_get_integer(dsname, "zoned", &zoned,
 654                             setpoint))
 655                                 return (SET_ERROR(EPERM));
 656                         if (!zoned || strlen(dsname) <= strlen(setpoint))
 657                                 return (SET_ERROR(EPERM));
 658                 }
 659                 break;
 660 
 661         case ZFS_PROP_MLSLABEL:
 662                 if (!is_system_labeled())
 663                         return (SET_ERROR(EPERM));
 664 
 665                 if (nvpair_value_string(propval, &strval) == 0) {
 666                         int err;
 667 
 668                         err = zfs_set_slabel_policy(dsname, strval, CRED());
 669                         if (err != 0)
 670                                 return (err);
 671                 }
 672                 break;
 673         }
 674 
 675         return (zfs_secpolicy_write_perms(dsname, zfs_prop_to_name(prop), cr));
 676 }
 677 
 678 /* ARGSUSED */
 679 static int
 680 zfs_secpolicy_set_fsacl(zfs_cmd_t *zc, nvlist_t *innvl, cred_t *cr)
 681 {
 682         int error;
 683 
 684         error = zfs_dozonecheck(zc->zc_name, cr);
 685         if (error != 0)
 686                 return (error);
 687 
 688         /*
 689          * permission to set permissions will be evaluated later in
 690          * dsl_deleg_can_allow()
 691          */
 692         return (0);
 693 }
 694 
 695 /* ARGSUSED */
 696 static int
 697 zfs_secpolicy_rollback(zfs_cmd_t *zc, nvlist_t *innvl, cred_t *cr)
 698 {
 699         return (zfs_secpolicy_write_perms(zc->zc_name,
 700             ZFS_DELEG_PERM_ROLLBACK, cr));
 701 }
 702 
 703 /* ARGSUSED */
 704 static int
 705 zfs_secpolicy_send(zfs_cmd_t *zc, nvlist_t *innvl, cred_t *cr)
 706 {
 707         dsl_pool_t *dp;
 708         dsl_dataset_t *ds;
 709         char *cp;
 710         int error;
 711 
 712         /*
 713          * Generate the current snapshot name from the given objsetid, then
 714          * use that name for the secpolicy/zone checks.
 715          */
 716         cp = strchr(zc->zc_name, '@');
 717         if (cp == NULL)
 718                 return (SET_ERROR(EINVAL));
 719         error = dsl_pool_hold(zc->zc_name, FTAG, &dp);
 720         if (error != 0)
 721                 return (error);
 722 
 723         error = dsl_dataset_hold_obj(dp, zc->zc_sendobj, FTAG, &ds);
 724         if (error != 0) {
 725                 dsl_pool_rele(dp, FTAG);
 726                 return (error);
 727         }
 728 
 729         dsl_dataset_name(ds, zc->zc_name);
 730 
 731         error = zfs_secpolicy_write_perms_ds(zc->zc_name, ds,
 732             ZFS_DELEG_PERM_SEND, cr);
 733         dsl_dataset_rele(ds, FTAG);
 734         dsl_pool_rele(dp, FTAG);
 735 
 736         return (error);
 737 }
 738 
 739 /* ARGSUSED */
 740 static int
 741 zfs_secpolicy_send_new(zfs_cmd_t *zc, nvlist_t *innvl, cred_t *cr)
 742 {
 743         return (zfs_secpolicy_write_perms(zc->zc_name,
 744             ZFS_DELEG_PERM_SEND, cr));
 745 }
 746 
 747 /* ARGSUSED */
 748 static int
 749 zfs_secpolicy_deleg_share(zfs_cmd_t *zc, nvlist_t *innvl, cred_t *cr)
 750 {
 751         vnode_t *vp;
 752         int error;
 753 
 754         if ((error = lookupname(zc->zc_value, UIO_SYSSPACE,
 755             NO_FOLLOW, NULL, &vp)) != 0)
 756                 return (error);
 757 
 758         /* Now make sure mntpnt and dataset are ZFS */
 759 
 760         if (vp->v_vfsp->vfs_fstype != zfsfstype ||
 761             (strcmp((char *)refstr_value(vp->v_vfsp->vfs_resource),
 762             zc->zc_name) != 0)) {
 763                 VN_RELE(vp);
 764                 return (SET_ERROR(EPERM));
 765         }
 766 
 767         VN_RELE(vp);
 768         return (dsl_deleg_access(zc->zc_name,
 769             ZFS_DELEG_PERM_SHARE, cr));
 770 }
 771 
 772 int
 773 zfs_secpolicy_share(zfs_cmd_t *zc, nvlist_t *innvl, cred_t *cr)
 774 {
 775         if (!INGLOBALZONE(curproc))
 776                 return (SET_ERROR(EPERM));
 777 
 778         if (secpolicy_nfs(cr) == 0) {
 779                 return (0);
 780         } else {
 781                 return (zfs_secpolicy_deleg_share(zc, innvl, cr));
 782         }
 783 }
 784 
 785 int
 786 zfs_secpolicy_smb_acl(zfs_cmd_t *zc, nvlist_t *innvl, cred_t *cr)
 787 {
 788         if (!INGLOBALZONE(curproc))
 789                 return (SET_ERROR(EPERM));
 790 
 791         if (secpolicy_smb(cr) == 0) {
 792                 return (0);
 793         } else {
 794                 return (zfs_secpolicy_deleg_share(zc, innvl, cr));
 795         }
 796 }
 797 
 798 static int
 799 zfs_get_parent(const char *datasetname, char *parent, int parentsize)
 800 {
 801         char *cp;
 802 
 803         /*
 804          * Remove the @bla or /bla from the end of the name to get the parent.
 805          */
 806         (void) strncpy(parent, datasetname, parentsize);
 807         cp = strrchr(parent, '@');
 808         if (cp != NULL) {
 809                 cp[0] = '\0';
 810         } else {
 811                 cp = strrchr(parent, '/');
 812                 if (cp == NULL)
 813                         return (SET_ERROR(ENOENT));
 814                 cp[0] = '\0';
 815         }
 816 
 817         return (0);
 818 }
 819 
 820 int
 821 zfs_secpolicy_destroy_perms(const char *name, cred_t *cr)
 822 {
 823         int error;
 824 
 825         if ((error = zfs_secpolicy_write_perms(name,
 826             ZFS_DELEG_PERM_MOUNT, cr)) != 0)
 827                 return (error);
 828 
 829         return (zfs_secpolicy_write_perms(name, ZFS_DELEG_PERM_DESTROY, cr));
 830 }
 831 
 832 /* ARGSUSED */
 833 static int
 834 zfs_secpolicy_destroy(zfs_cmd_t *zc, nvlist_t *innvl, cred_t *cr)
 835 {
 836         return (zfs_secpolicy_destroy_perms(zc->zc_name, cr));
 837 }
 838 
 839 /*
 840  * Destroying snapshots with delegated permissions requires
 841  * descendant mount and destroy permissions.
 842  */
 843 /* ARGSUSED */
 844 static int
 845 zfs_secpolicy_destroy_snaps(zfs_cmd_t *zc, nvlist_t *innvl, cred_t *cr)
 846 {
 847         nvlist_t *snaps;
 848         nvpair_t *pair, *nextpair;
 849         int error = 0;
 850 
 851         if (nvlist_lookup_nvlist(innvl, "snaps", &snaps) != 0)
 852                 return (SET_ERROR(EINVAL));
 853         for (pair = nvlist_next_nvpair(snaps, NULL); pair != NULL;
 854             pair = nextpair) {
 855                 nextpair = nvlist_next_nvpair(snaps, pair);
 856                 error = zfs_secpolicy_destroy_perms(nvpair_name(pair), cr);
 857                 if (error == ENOENT) {
 858                         /*
 859                          * Ignore any snapshots that don't exist (we consider
 860                          * them "already destroyed").  Remove the name from the
 861                          * nvl here in case the snapshot is created between
 862                          * now and when we try to destroy it (in which case
 863                          * we don't want to destroy it since we haven't
 864                          * checked for permission).
 865                          */
 866                         fnvlist_remove_nvpair(snaps, pair);
 867                         error = 0;
 868                 }
 869                 if (error != 0)
 870                         break;
 871         }
 872 
 873         return (error);
 874 }
 875 
 876 int
 877 zfs_secpolicy_rename_perms(const char *from, const char *to, cred_t *cr)
 878 {
 879         char    parentname[ZFS_MAX_DATASET_NAME_LEN];
 880         int     error;
 881 
 882         if ((error = zfs_secpolicy_write_perms(from,
 883             ZFS_DELEG_PERM_RENAME, cr)) != 0)
 884                 return (error);
 885 
 886         if ((error = zfs_secpolicy_write_perms(from,
 887             ZFS_DELEG_PERM_MOUNT, cr)) != 0)
 888                 return (error);
 889 
 890         if ((error = zfs_get_parent(to, parentname,
 891             sizeof (parentname))) != 0)
 892                 return (error);
 893 
 894         if ((error = zfs_secpolicy_write_perms(parentname,
 895             ZFS_DELEG_PERM_CREATE, cr)) != 0)
 896                 return (error);
 897 
 898         if ((error = zfs_secpolicy_write_perms(parentname,
 899             ZFS_DELEG_PERM_MOUNT, cr)) != 0)
 900                 return (error);
 901 
 902         return (error);
 903 }
 904 
 905 /* ARGSUSED */
 906 static int
 907 zfs_secpolicy_rename(zfs_cmd_t *zc, nvlist_t *innvl, cred_t *cr)
 908 {
 909         return (zfs_secpolicy_rename_perms(zc->zc_name, zc->zc_value, cr));
 910 }
 911 
 912 /* ARGSUSED */
 913 static int
 914 zfs_secpolicy_promote(zfs_cmd_t *zc, nvlist_t *innvl, cred_t *cr)
 915 {
 916         dsl_pool_t *dp;
 917         dsl_dataset_t *clone;
 918         int error;
 919 
 920         error = zfs_secpolicy_write_perms(zc->zc_name,
 921             ZFS_DELEG_PERM_PROMOTE, cr);
 922         if (error != 0)
 923                 return (error);
 924 
 925         error = dsl_pool_hold(zc->zc_name, FTAG, &dp);
 926         if (error != 0)
 927                 return (error);
 928 
 929         error = dsl_dataset_hold(dp, zc->zc_name, FTAG, &clone);
 930 
 931         if (error == 0) {
 932                 char parentname[ZFS_MAX_DATASET_NAME_LEN];
 933                 dsl_dataset_t *origin = NULL;
 934                 dsl_dir_t *dd;
 935                 dd = clone->ds_dir;
 936 
 937                 error = dsl_dataset_hold_obj(dd->dd_pool,
 938                     dsl_dir_phys(dd)->dd_origin_obj, FTAG, &origin);
 939                 if (error != 0) {
 940                         dsl_dataset_rele(clone, FTAG);
 941                         dsl_pool_rele(dp, FTAG);
 942                         return (error);
 943                 }
 944 
 945                 error = zfs_secpolicy_write_perms_ds(zc->zc_name, clone,
 946                     ZFS_DELEG_PERM_MOUNT, cr);
 947 
 948                 dsl_dataset_name(origin, parentname);
 949                 if (error == 0) {
 950                         error = zfs_secpolicy_write_perms_ds(parentname, origin,
 951                             ZFS_DELEG_PERM_PROMOTE, cr);
 952                 }
 953                 dsl_dataset_rele(clone, FTAG);
 954                 dsl_dataset_rele(origin, FTAG);
 955         }
 956         dsl_pool_rele(dp, FTAG);
 957         return (error);
 958 }
 959 
 960 /* ARGSUSED */
 961 static int
 962 zfs_secpolicy_recv(zfs_cmd_t *zc, nvlist_t *innvl, cred_t *cr)
 963 {
 964         int error;
 965 
 966         if ((error = zfs_secpolicy_write_perms(zc->zc_name,
 967             ZFS_DELEG_PERM_RECEIVE, cr)) != 0)
 968                 return (error);
 969 
 970         if ((error = zfs_secpolicy_write_perms(zc->zc_name,
 971             ZFS_DELEG_PERM_MOUNT, cr)) != 0)
 972                 return (error);
 973 
 974         return (zfs_secpolicy_write_perms(zc->zc_name,
 975             ZFS_DELEG_PERM_CREATE, cr));
 976 }
 977 
 978 int
 979 zfs_secpolicy_snapshot_perms(const char *name, cred_t *cr)
 980 {
 981         return (zfs_secpolicy_write_perms(name,
 982             ZFS_DELEG_PERM_SNAPSHOT, cr));
 983 }
 984 
 985 /*
 986  * Check for permission to create each snapshot in the nvlist.
 987  */
 988 /* ARGSUSED */
 989 static int
 990 zfs_secpolicy_snapshot(zfs_cmd_t *zc, nvlist_t *innvl, cred_t *cr)
 991 {
 992         nvlist_t *snaps;
 993         int error = 0;
 994         nvpair_t *pair;
 995 
 996         if (nvlist_lookup_nvlist(innvl, "snaps", &snaps) != 0)
 997                 return (SET_ERROR(EINVAL));
 998         for (pair = nvlist_next_nvpair(snaps, NULL); pair != NULL;
 999             pair = nvlist_next_nvpair(snaps, pair)) {
1000                 char *name = nvpair_name(pair);
1001                 char *atp = strchr(name, '@');
1002 
1003                 if (atp == NULL) {
1004                         error = SET_ERROR(EINVAL);
1005                         break;
1006                 }
1007                 *atp = '\0';
1008                 error = zfs_secpolicy_snapshot_perms(name, cr);
1009                 *atp = '@';
1010                 if (error != 0)
1011                         break;
1012         }
1013         return (error);
1014 }
1015 
1016 /*
1017  * Check for permission to create each snapshot in the nvlist.
1018  */
1019 /* ARGSUSED */
1020 static int
1021 zfs_secpolicy_bookmark(zfs_cmd_t *zc, nvlist_t *innvl, cred_t *cr)
1022 {
1023         int error = 0;
1024 
1025         for (nvpair_t *pair = nvlist_next_nvpair(innvl, NULL);
1026             pair != NULL; pair = nvlist_next_nvpair(innvl, pair)) {
1027                 char *name = nvpair_name(pair);
1028                 char *hashp = strchr(name, '#');
1029 
1030                 if (hashp == NULL) {
1031                         error = SET_ERROR(EINVAL);
1032                         break;
1033                 }
1034                 *hashp = '\0';
1035                 error = zfs_secpolicy_write_perms(name,
1036                     ZFS_DELEG_PERM_BOOKMARK, cr);
1037                 *hashp = '#';
1038                 if (error != 0)
1039                         break;
1040         }
1041         return (error);
1042 }
1043 
1044 /* ARGSUSED */
1045 static int
1046 zfs_secpolicy_remap(zfs_cmd_t *zc, nvlist_t *innvl, cred_t *cr)
1047 {
1048         return (zfs_secpolicy_write_perms(zc->zc_name,
1049             ZFS_DELEG_PERM_REMAP, cr));
1050 }
1051 
1052 /* ARGSUSED */
1053 static int
1054 zfs_secpolicy_destroy_bookmarks(zfs_cmd_t *zc, nvlist_t *innvl, cred_t *cr)
1055 {
1056         nvpair_t *pair, *nextpair;
1057         int error = 0;
1058 
1059         for (pair = nvlist_next_nvpair(innvl, NULL); pair != NULL;
1060             pair = nextpair) {
1061                 char *name = nvpair_name(pair);
1062                 char *hashp = strchr(name, '#');
1063                 nextpair = nvlist_next_nvpair(innvl, pair);
1064 
1065                 if (hashp == NULL) {
1066                         error = SET_ERROR(EINVAL);
1067                         break;
1068                 }
1069 
1070                 *hashp = '\0';
1071                 error = zfs_secpolicy_write_perms(name,
1072                     ZFS_DELEG_PERM_DESTROY, cr);
1073                 *hashp = '#';
1074                 if (error == ENOENT) {
1075                         /*
1076                          * Ignore any filesystems that don't exist (we consider
1077                          * their bookmarks "already destroyed").  Remove
1078                          * the name from the nvl here in case the filesystem
1079                          * is created between now and when we try to destroy
1080                          * the bookmark (in which case we don't want to
1081                          * destroy it since we haven't checked for permission).
1082                          */
1083                         fnvlist_remove_nvpair(innvl, pair);
1084                         error = 0;
1085                 }
1086                 if (error != 0)
1087                         break;
1088         }
1089 
1090         return (error);
1091 }
1092 
1093 /* ARGSUSED */
1094 static int
1095 zfs_secpolicy_log_history(zfs_cmd_t *zc, nvlist_t *innvl, cred_t *cr)
1096 {
1097         /*
1098          * Even root must have a proper TSD so that we know what pool
1099          * to log to.
1100          */
1101         if (tsd_get(zfs_allow_log_key) == NULL)
1102                 return (SET_ERROR(EPERM));
1103         return (0);
1104 }
1105 
1106 static int
1107 zfs_secpolicy_create_clone(zfs_cmd_t *zc, nvlist_t *innvl, cred_t *cr)
1108 {
1109         char    parentname[ZFS_MAX_DATASET_NAME_LEN];
1110         int     error;
1111         char    *origin;
1112 
1113         if ((error = zfs_get_parent(zc->zc_name, parentname,
1114             sizeof (parentname))) != 0)
1115                 return (error);
1116 
1117         if (nvlist_lookup_string(innvl, "origin", &origin) == 0 &&
1118             (error = zfs_secpolicy_write_perms(origin,
1119             ZFS_DELEG_PERM_CLONE, cr)) != 0)
1120                 return (error);
1121 
1122         if ((error = zfs_secpolicy_write_perms(parentname,
1123             ZFS_DELEG_PERM_CREATE, cr)) != 0)
1124                 return (error);
1125 
1126         return (zfs_secpolicy_write_perms(parentname,
1127             ZFS_DELEG_PERM_MOUNT, cr));
1128 }
1129 
1130 /*
1131  * Policy for pool operations - create/destroy pools, add vdevs, etc.  Requires
1132  * SYS_CONFIG privilege, which is not available in a local zone.
1133  */
1134 /* ARGSUSED */
1135 static int
1136 zfs_secpolicy_config(zfs_cmd_t *zc, nvlist_t *innvl, cred_t *cr)
1137 {
1138         if (secpolicy_sys_config(cr, B_FALSE) != 0)
1139                 return (SET_ERROR(EPERM));
1140 
1141         return (0);
1142 }
1143 
1144 /*
1145  * Policy for object to name lookups.
1146  */
1147 /* ARGSUSED */
1148 static int
1149 zfs_secpolicy_diff(zfs_cmd_t *zc, nvlist_t *innvl, cred_t *cr)
1150 {
1151         int error;
1152 
1153         if ((error = secpolicy_sys_config(cr, B_FALSE)) == 0)
1154                 return (0);
1155 
1156         error = zfs_secpolicy_write_perms(zc->zc_name, ZFS_DELEG_PERM_DIFF, cr);
1157         return (error);
1158 }
1159 
1160 /*
1161  * Policy for fault injection.  Requires all privileges.
1162  */
1163 /* ARGSUSED */
1164 static int
1165 zfs_secpolicy_inject(zfs_cmd_t *zc, nvlist_t *innvl, cred_t *cr)
1166 {
1167         return (secpolicy_zinject(cr));
1168 }
1169 
1170 /* ARGSUSED */
1171 static int
1172 zfs_secpolicy_inherit_prop(zfs_cmd_t *zc, nvlist_t *innvl, cred_t *cr)
1173 {
1174         zfs_prop_t prop = zfs_name_to_prop(zc->zc_value);
1175 
1176         if (prop == ZPROP_INVAL) {
1177                 if (!zfs_prop_user(zc->zc_value))
1178                         return (SET_ERROR(EINVAL));
1179                 return (zfs_secpolicy_write_perms(zc->zc_name,
1180                     ZFS_DELEG_PERM_USERPROP, cr));
1181         } else {
1182                 return (zfs_secpolicy_setprop(zc->zc_name, prop,
1183                     NULL, cr));
1184         }
1185 }
1186 
1187 static int
1188 zfs_secpolicy_userspace_one(zfs_cmd_t *zc, nvlist_t *innvl, cred_t *cr)
1189 {
1190         int err = zfs_secpolicy_read(zc, innvl, cr);
1191         if (err)
1192                 return (err);
1193 
1194         if (zc->zc_objset_type >= ZFS_NUM_USERQUOTA_PROPS)
1195                 return (SET_ERROR(EINVAL));
1196 
1197         if (zc->zc_value[0] == 0) {
1198                 /*
1199                  * They are asking about a posix uid/gid.  If it's
1200                  * themself, allow it.
1201                  */
1202                 if (zc->zc_objset_type == ZFS_PROP_USERUSED ||
1203                     zc->zc_objset_type == ZFS_PROP_USERQUOTA) {
1204                         if (zc->zc_guid == crgetuid(cr))
1205                                 return (0);
1206                 } else {
1207                         if (groupmember(zc->zc_guid, cr))
1208                                 return (0);
1209                 }
1210         }
1211 
1212         return (zfs_secpolicy_write_perms(zc->zc_name,
1213             userquota_perms[zc->zc_objset_type], cr));
1214 }
1215 
1216 static int
1217 zfs_secpolicy_userspace_many(zfs_cmd_t *zc, nvlist_t *innvl, cred_t *cr)
1218 {
1219         int err = zfs_secpolicy_read(zc, innvl, cr);
1220         if (err)
1221                 return (err);
1222 
1223         if (zc->zc_objset_type >= ZFS_NUM_USERQUOTA_PROPS)
1224                 return (SET_ERROR(EINVAL));
1225 
1226         return (zfs_secpolicy_write_perms(zc->zc_name,
1227             userquota_perms[zc->zc_objset_type], cr));
1228 }
1229 
1230 /* ARGSUSED */
1231 static int
1232 zfs_secpolicy_userspace_upgrade(zfs_cmd_t *zc, nvlist_t *innvl, cred_t *cr)
1233 {
1234         return (zfs_secpolicy_setprop(zc->zc_name, ZFS_PROP_VERSION,
1235             NULL, cr));
1236 }
1237 
1238 /* ARGSUSED */
1239 static int
1240 zfs_secpolicy_hold(zfs_cmd_t *zc, nvlist_t *innvl, cred_t *cr)
1241 {
1242         nvpair_t *pair;
1243         nvlist_t *holds;
1244         int error;
1245 
1246         error = nvlist_lookup_nvlist(innvl, "holds", &holds);
1247         if (error != 0)
1248                 return (SET_ERROR(EINVAL));
1249 
1250         for (pair = nvlist_next_nvpair(holds, NULL); pair != NULL;
1251             pair = nvlist_next_nvpair(holds, pair)) {
1252                 char fsname[ZFS_MAX_DATASET_NAME_LEN];
1253                 error = dmu_fsname(nvpair_name(pair), fsname);
1254                 if (error != 0)
1255                         return (error);
1256                 error = zfs_secpolicy_write_perms(fsname,
1257                     ZFS_DELEG_PERM_HOLD, cr);
1258                 if (error != 0)
1259                         return (error);
1260         }
1261         return (0);
1262 }
1263 
1264 /* ARGSUSED */
1265 static int
1266 zfs_secpolicy_release(zfs_cmd_t *zc, nvlist_t *innvl, cred_t *cr)
1267 {
1268         nvpair_t *pair;
1269         int error;
1270 
1271         for (pair = nvlist_next_nvpair(innvl, NULL); pair != NULL;
1272             pair = nvlist_next_nvpair(innvl, pair)) {
1273                 char fsname[ZFS_MAX_DATASET_NAME_LEN];
1274                 error = dmu_fsname(nvpair_name(pair), fsname);
1275                 if (error != 0)
1276                         return (error);
1277                 error = zfs_secpolicy_write_perms(fsname,
1278                     ZFS_DELEG_PERM_RELEASE, cr);
1279                 if (error != 0)
1280                         return (error);
1281         }
1282         return (0);
1283 }
1284 
1285 /*
1286  * Policy for allowing temporary snapshots to be taken or released
1287  */
1288 static int
1289 zfs_secpolicy_tmp_snapshot(zfs_cmd_t *zc, nvlist_t *innvl, cred_t *cr)
1290 {
1291         /*
1292          * A temporary snapshot is the same as a snapshot,
1293          * hold, destroy and release all rolled into one.
1294          * Delegated diff alone is sufficient that we allow this.
1295          */
1296         int error;
1297 
1298         if ((error = zfs_secpolicy_write_perms(zc->zc_name,
1299             ZFS_DELEG_PERM_DIFF, cr)) == 0)
1300                 return (0);
1301 
1302         error = zfs_secpolicy_snapshot_perms(zc->zc_name, cr);
1303         if (error == 0)
1304                 error = zfs_secpolicy_hold(zc, innvl, cr);
1305         if (error == 0)
1306                 error = zfs_secpolicy_release(zc, innvl, cr);
1307         if (error == 0)
1308                 error = zfs_secpolicy_destroy(zc, innvl, cr);
1309         return (error);
1310 }
1311 
1312 /*
1313  * Returns the nvlist as specified by the user in the zfs_cmd_t.
1314  */
1315 static int
1316 get_nvlist(uint64_t nvl, uint64_t size, int iflag, nvlist_t **nvp)
1317 {
1318         char *packed;
1319         int error;
1320         nvlist_t *list = NULL;
1321 
1322         /*
1323          * Read in and unpack the user-supplied nvlist.
1324          */
1325         if (size == 0)
1326                 return (SET_ERROR(EINVAL));
1327 
1328         packed = kmem_alloc(size, KM_SLEEP);
1329 
1330         if ((error = ddi_copyin((void *)(uintptr_t)nvl, packed, size,
1331             iflag)) != 0) {
1332                 kmem_free(packed, size);
1333                 return (SET_ERROR(EFAULT));
1334         }
1335 
1336         if ((error = nvlist_unpack(packed, size, &list, 0)) != 0) {
1337                 kmem_free(packed, size);
1338                 return (error);
1339         }
1340 
1341         kmem_free(packed, size);
1342 
1343         *nvp = list;
1344         return (0);
1345 }
1346 
1347 /*
1348  * Reduce the size of this nvlist until it can be serialized in 'max' bytes.
1349  * Entries will be removed from the end of the nvlist, and one int32 entry
1350  * named "N_MORE_ERRORS" will be added indicating how many entries were
1351  * removed.
1352  */
1353 static int
1354 nvlist_smush(nvlist_t *errors, size_t max)
1355 {
1356         size_t size;
1357 
1358         size = fnvlist_size(errors);
1359 
1360         if (size > max) {
1361                 nvpair_t *more_errors;
1362                 int n = 0;
1363 
1364                 if (max < 1024)
1365                         return (SET_ERROR(ENOMEM));
1366 
1367                 fnvlist_add_int32(errors, ZPROP_N_MORE_ERRORS, 0);
1368                 more_errors = nvlist_prev_nvpair(errors, NULL);
1369 
1370                 do {
1371                         nvpair_t *pair = nvlist_prev_nvpair(errors,
1372                             more_errors);
1373                         fnvlist_remove_nvpair(errors, pair);
1374                         n++;
1375                         size = fnvlist_size(errors);
1376                 } while (size > max);
1377 
1378                 fnvlist_remove_nvpair(errors, more_errors);
1379                 fnvlist_add_int32(errors, ZPROP_N_MORE_ERRORS, n);
1380                 ASSERT3U(fnvlist_size(errors), <=, max);
1381         }
1382 
1383         return (0);
1384 }
1385 
1386 static int
1387 put_nvlist(zfs_cmd_t *zc, nvlist_t *nvl)
1388 {
1389         char *packed = NULL;
1390         int error = 0;
1391         size_t size;
1392 
1393         size = fnvlist_size(nvl);
1394 
1395         if (size > zc->zc_nvlist_dst_size) {
1396                 error = SET_ERROR(ENOMEM);
1397         } else {
1398                 packed = fnvlist_pack(nvl, &size);
1399                 if (ddi_copyout(packed, (void *)(uintptr_t)zc->zc_nvlist_dst,
1400                     size, zc->zc_iflags) != 0)
1401                         error = SET_ERROR(EFAULT);
1402                 fnvlist_pack_free(packed, size);
1403         }
1404 
1405         zc->zc_nvlist_dst_size = size;
1406         zc->zc_nvlist_dst_filled = B_TRUE;
1407         return (error);
1408 }
1409 
1410 int
1411 getzfsvfs_impl(objset_t *os, zfsvfs_t **zfvp)
1412 {
1413         int error = 0;
1414         if (dmu_objset_type(os) != DMU_OST_ZFS) {
1415                 return (SET_ERROR(EINVAL));
1416         }
1417 
1418         mutex_enter(&os->os_user_ptr_lock);
1419         *zfvp = dmu_objset_get_user(os);
1420         if (*zfvp) {
1421                 VFS_HOLD((*zfvp)->z_vfs);
1422         } else {
1423                 error = SET_ERROR(ESRCH);
1424         }
1425         mutex_exit(&os->os_user_ptr_lock);
1426         return (error);
1427 }
1428 
1429 int
1430 getzfsvfs(const char *dsname, zfsvfs_t **zfvp)
1431 {
1432         objset_t *os;
1433         int error;
1434 
1435         error = dmu_objset_hold(dsname, FTAG, &os);
1436         if (error != 0)
1437                 return (error);
1438 
1439         error = getzfsvfs_impl(os, zfvp);
1440         dmu_objset_rele(os, FTAG);
1441         return (error);
1442 }
1443 
1444 /*
1445  * Find a zfsvfs_t for a mounted filesystem, or create our own, in which
1446  * case its z_vfs will be NULL, and it will be opened as the owner.
1447  * If 'writer' is set, the z_teardown_lock will be held for RW_WRITER,
1448  * which prevents all vnode ops from running.
1449  */
1450 static int
1451 zfsvfs_hold(const char *name, void *tag, zfsvfs_t **zfvp, boolean_t writer)
1452 {
1453         int error = 0;
1454 
1455         if (getzfsvfs(name, zfvp) != 0)
1456                 error = zfsvfs_create(name, zfvp);
1457         if (error == 0) {
1458                 rrm_enter(&(*zfvp)->z_teardown_lock, (writer) ? RW_WRITER :
1459                     RW_READER, tag);
1460                 if ((*zfvp)->z_unmounted) {
1461                         /*
1462                          * XXX we could probably try again, since the unmounting
1463                          * thread should be just about to disassociate the
1464                          * objset from the zfsvfs.
1465                          */
1466                         rrm_exit(&(*zfvp)->z_teardown_lock, tag);
1467                         return (SET_ERROR(EBUSY));
1468                 }
1469         }
1470         return (error);
1471 }
1472 
1473 static void
1474 zfsvfs_rele(zfsvfs_t *zfsvfs, void *tag)
1475 {
1476         rrm_exit(&zfsvfs->z_teardown_lock, tag);
1477 
1478         if (zfsvfs->z_vfs) {
1479                 VFS_RELE(zfsvfs->z_vfs);
1480         } else {
1481                 dmu_objset_disown(zfsvfs->z_os, zfsvfs);
1482                 zfsvfs_free(zfsvfs);
1483         }
1484 }
1485 
1486 static int
1487 zfs_ioc_pool_create(zfs_cmd_t *zc)
1488 {
1489         int error;
1490         nvlist_t *config, *props = NULL;
1491         nvlist_t *rootprops = NULL;
1492         nvlist_t *zplprops = NULL;
1493 
1494         if (error = get_nvlist(zc->zc_nvlist_conf, zc->zc_nvlist_conf_size,
1495             zc->zc_iflags, &config))
1496                 return (error);
1497 
1498         if (zc->zc_nvlist_src_size != 0 && (error =
1499             get_nvlist(zc->zc_nvlist_src, zc->zc_nvlist_src_size,
1500             zc->zc_iflags, &props))) {
1501                 nvlist_free(config);
1502                 return (error);
1503         }
1504 
1505         if (props) {
1506                 nvlist_t *nvl = NULL;
1507                 uint64_t version = SPA_VERSION;
1508 
1509                 (void) nvlist_lookup_uint64(props,
1510                     zpool_prop_to_name(ZPOOL_PROP_VERSION), &version);
1511                 if (!SPA_VERSION_IS_SUPPORTED(version)) {
1512                         error = SET_ERROR(EINVAL);
1513                         goto pool_props_bad;
1514                 }
1515                 (void) nvlist_lookup_nvlist(props, ZPOOL_ROOTFS_PROPS, &nvl);
1516                 if (nvl) {
1517                         error = nvlist_dup(nvl, &rootprops, KM_SLEEP);
1518                         if (error != 0) {
1519                                 nvlist_free(config);
1520                                 nvlist_free(props);
1521                                 return (error);
1522                         }
1523                         (void) nvlist_remove_all(props, ZPOOL_ROOTFS_PROPS);
1524                 }
1525                 VERIFY(nvlist_alloc(&zplprops, NV_UNIQUE_NAME, KM_SLEEP) == 0);
1526                 error = zfs_fill_zplprops_root(version, rootprops,
1527                     zplprops, NULL);
1528                 if (error != 0)
1529                         goto pool_props_bad;
1530         }
1531 
1532         error = spa_create(zc->zc_name, config, props, zplprops);
1533 
1534         /*
1535          * Set the remaining root properties
1536          */
1537         if (!error && (error = zfs_set_prop_nvlist(zc->zc_name,
1538             ZPROP_SRC_LOCAL, rootprops, NULL)) != 0)
1539                 (void) spa_destroy(zc->zc_name);
1540 
1541 pool_props_bad:
1542         nvlist_free(rootprops);
1543         nvlist_free(zplprops);
1544         nvlist_free(config);
1545         nvlist_free(props);
1546 
1547         return (error);
1548 }
1549 
1550 static int
1551 zfs_ioc_pool_destroy(zfs_cmd_t *zc)
1552 {
1553         int error;
1554         zfs_log_history(zc);
1555         error = spa_destroy(zc->zc_name);
1556         if (error == 0)
1557                 zvol_remove_minors(zc->zc_name);
1558         return (error);
1559 }
1560 
1561 static int
1562 zfs_ioc_pool_import(zfs_cmd_t *zc)
1563 {
1564         nvlist_t *config, *props = NULL;
1565         uint64_t guid;
1566         int error;
1567 
1568         if ((error = get_nvlist(zc->zc_nvlist_conf, zc->zc_nvlist_conf_size,
1569             zc->zc_iflags, &config)) != 0)
1570                 return (error);
1571 
1572         if (zc->zc_nvlist_src_size != 0 && (error =
1573             get_nvlist(zc->zc_nvlist_src, zc->zc_nvlist_src_size,
1574             zc->zc_iflags, &props))) {
1575                 nvlist_free(config);
1576                 return (error);
1577         }
1578 
1579         if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID, &guid) != 0 ||
1580             guid != zc->zc_guid)
1581                 error = SET_ERROR(EINVAL);
1582         else
1583                 error = spa_import(zc->zc_name, config, props, zc->zc_cookie);
1584 
1585         if (zc->zc_nvlist_dst != 0) {
1586                 int err;
1587 
1588                 if ((err = put_nvlist(zc, config)) != 0)
1589                         error = err;
1590         }
1591 
1592         nvlist_free(config);
1593 
1594         nvlist_free(props);
1595 
1596         return (error);
1597 }
1598 
1599 static int
1600 zfs_ioc_pool_export(zfs_cmd_t *zc)
1601 {
1602         int error;
1603         boolean_t force = (boolean_t)zc->zc_cookie;
1604         boolean_t hardforce = (boolean_t)zc->zc_guid;
1605 
1606         zfs_log_history(zc);
1607         error = spa_export(zc->zc_name, NULL, force, hardforce);
1608         if (error == 0)
1609                 zvol_remove_minors(zc->zc_name);
1610         return (error);
1611 }
1612 
1613 static int
1614 zfs_ioc_pool_configs(zfs_cmd_t *zc)
1615 {
1616         nvlist_t *configs;
1617         int error;
1618 
1619         if ((configs = spa_all_configs(&zc->zc_cookie)) == NULL)
1620                 return (SET_ERROR(EEXIST));
1621 
1622         error = put_nvlist(zc, configs);
1623 
1624         nvlist_free(configs);
1625 
1626         return (error);
1627 }
1628 
1629 /*
1630  * inputs:
1631  * zc_name              name of the pool
1632  *
1633  * outputs:
1634  * zc_cookie            real errno
1635  * zc_nvlist_dst        config nvlist
1636  * zc_nvlist_dst_size   size of config nvlist
1637  */
1638 static int
1639 zfs_ioc_pool_stats(zfs_cmd_t *zc)
1640 {
1641         nvlist_t *config;
1642         int error;
1643         int ret = 0;
1644 
1645         error = spa_get_stats(zc->zc_name, &config, zc->zc_value,
1646             sizeof (zc->zc_value));
1647 
1648         if (config != NULL) {
1649                 ret = put_nvlist(zc, config);
1650                 nvlist_free(config);
1651 
1652                 /*
1653                  * The config may be present even if 'error' is non-zero.
1654                  * In this case we return success, and preserve the real errno
1655                  * in 'zc_cookie'.
1656                  */
1657                 zc->zc_cookie = error;
1658         } else {
1659                 ret = error;
1660         }
1661 
1662         return (ret);
1663 }
1664 
1665 /*
1666  * Try to import the given pool, returning pool stats as appropriate so that
1667  * user land knows which devices are available and overall pool health.
1668  */
1669 static int
1670 zfs_ioc_pool_tryimport(zfs_cmd_t *zc)
1671 {
1672         nvlist_t *tryconfig, *config;
1673         int error;
1674 
1675         if ((error = get_nvlist(zc->zc_nvlist_conf, zc->zc_nvlist_conf_size,
1676             zc->zc_iflags, &tryconfig)) != 0)
1677                 return (error);
1678 
1679         config = spa_tryimport(tryconfig);
1680 
1681         nvlist_free(tryconfig);
1682 
1683         if (config == NULL)
1684                 return (SET_ERROR(EINVAL));
1685 
1686         error = put_nvlist(zc, config);
1687         nvlist_free(config);
1688 
1689         return (error);
1690 }
1691 
1692 /*
1693  * inputs:
1694  * zc_name              name of the pool
1695  * zc_cookie            scan func (pool_scan_func_t)
1696  * zc_flags             scrub pause/resume flag (pool_scrub_cmd_t)
1697  */
1698 static int
1699 zfs_ioc_pool_scan(zfs_cmd_t *zc)
1700 {
1701         spa_t *spa;
1702         int error;
1703 
1704         if ((error = spa_open(zc->zc_name, &spa, FTAG)) != 0)
1705                 return (error);
1706 
1707         if (zc->zc_flags >= POOL_SCRUB_FLAGS_END)
1708                 return (SET_ERROR(EINVAL));
1709 
1710         if (zc->zc_flags == POOL_SCRUB_PAUSE)
1711                 error = spa_scrub_pause_resume(spa, POOL_SCRUB_PAUSE);
1712         else if (zc->zc_cookie == POOL_SCAN_NONE)
1713                 error = spa_scan_stop(spa);
1714         else
1715                 error = spa_scan(spa, zc->zc_cookie);
1716 
1717         spa_close(spa, FTAG);
1718 
1719         return (error);
1720 }
1721 
1722 static int
1723 zfs_ioc_pool_freeze(zfs_cmd_t *zc)
1724 {
1725         spa_t *spa;
1726         int error;
1727 
1728         error = spa_open(zc->zc_name, &spa, FTAG);
1729         if (error == 0) {
1730                 spa_freeze(spa);
1731                 spa_close(spa, FTAG);
1732         }
1733         return (error);
1734 }
1735 
1736 static int
1737 zfs_ioc_pool_upgrade(zfs_cmd_t *zc)
1738 {
1739         spa_t *spa;
1740         int error;
1741 
1742         if ((error = spa_open(zc->zc_name, &spa, FTAG)) != 0)
1743                 return (error);
1744 
1745         if (zc->zc_cookie < spa_version(spa) ||
1746             !SPA_VERSION_IS_SUPPORTED(zc->zc_cookie)) {
1747                 spa_close(spa, FTAG);
1748                 return (SET_ERROR(EINVAL));
1749         }
1750 
1751         spa_upgrade(spa, zc->zc_cookie);
1752         spa_close(spa, FTAG);
1753 
1754         return (error);
1755 }
1756 
1757 static int
1758 zfs_ioc_pool_get_history(zfs_cmd_t *zc)
1759 {
1760         spa_t *spa;
1761         char *hist_buf;
1762         uint64_t size;
1763         int error;
1764 
1765         if ((size = zc->zc_history_len) == 0)
1766                 return (SET_ERROR(EINVAL));
1767 
1768         if ((error = spa_open(zc->zc_name, &spa, FTAG)) != 0)
1769                 return (error);
1770 
1771         if (spa_version(spa) < SPA_VERSION_ZPOOL_HISTORY) {
1772                 spa_close(spa, FTAG);
1773                 return (SET_ERROR(ENOTSUP));
1774         }
1775 
1776         hist_buf = kmem_alloc(size, KM_SLEEP);
1777         if ((error = spa_history_get(spa, &zc->zc_history_offset,
1778             &zc->zc_history_len, hist_buf)) == 0) {
1779                 error = ddi_copyout(hist_buf,
1780                     (void *)(uintptr_t)zc->zc_history,
1781                     zc->zc_history_len, zc->zc_iflags);
1782         }
1783 
1784         spa_close(spa, FTAG);
1785         kmem_free(hist_buf, size);
1786         return (error);
1787 }
1788 
1789 static int
1790 zfs_ioc_pool_reguid(zfs_cmd_t *zc)
1791 {
1792         spa_t *spa;
1793         int error;
1794 
1795         error = spa_open(zc->zc_name, &spa, FTAG);
1796         if (error == 0) {
1797                 error = spa_change_guid(spa);
1798                 spa_close(spa, FTAG);
1799         }
1800         return (error);
1801 }
1802 
1803 static int
1804 zfs_ioc_dsobj_to_dsname(zfs_cmd_t *zc)
1805 {
1806         return (dsl_dsobj_to_dsname(zc->zc_name, zc->zc_obj, zc->zc_value));
1807 }
1808 
1809 /*
1810  * inputs:
1811  * zc_name              name of filesystem
1812  * zc_obj               object to find
1813  *
1814  * outputs:
1815  * zc_value             name of object
1816  */
1817 static int
1818 zfs_ioc_obj_to_path(zfs_cmd_t *zc)
1819 {
1820         objset_t *os;
1821         int error;
1822 
1823         /* XXX reading from objset not owned */
1824         if ((error = dmu_objset_hold(zc->zc_name, FTAG, &os)) != 0)
1825                 return (error);
1826         if (dmu_objset_type(os) != DMU_OST_ZFS) {
1827                 dmu_objset_rele(os, FTAG);
1828                 return (SET_ERROR(EINVAL));
1829         }
1830         error = zfs_obj_to_path(os, zc->zc_obj, zc->zc_value,
1831             sizeof (zc->zc_value));
1832         dmu_objset_rele(os, FTAG);
1833 
1834         return (error);
1835 }
1836 
1837 /*
1838  * inputs:
1839  * zc_name              name of filesystem
1840  * zc_obj               object to find
1841  *
1842  * outputs:
1843  * zc_stat              stats on object
1844  * zc_value             path to object
1845  */
1846 static int
1847 zfs_ioc_obj_to_stats(zfs_cmd_t *zc)
1848 {
1849         objset_t *os;
1850         int error;
1851 
1852         /* XXX reading from objset not owned */
1853         if ((error = dmu_objset_hold(zc->zc_name, FTAG, &os)) != 0)
1854                 return (error);
1855         if (dmu_objset_type(os) != DMU_OST_ZFS) {
1856                 dmu_objset_rele(os, FTAG);
1857                 return (SET_ERROR(EINVAL));
1858         }
1859         error = zfs_obj_to_stats(os, zc->zc_obj, &zc->zc_stat, zc->zc_value,
1860             sizeof (zc->zc_value));
1861         dmu_objset_rele(os, FTAG);
1862 
1863         return (error);
1864 }
1865 
1866 static int
1867 zfs_ioc_vdev_add(zfs_cmd_t *zc)
1868 {
1869         spa_t *spa;
1870         int error;
1871         nvlist_t *config, **l2cache, **spares;
1872         uint_t nl2cache = 0, nspares = 0;
1873 
1874         error = spa_open(zc->zc_name, &spa, FTAG);
1875         if (error != 0)
1876                 return (error);
1877 
1878         error = get_nvlist(zc->zc_nvlist_conf, zc->zc_nvlist_conf_size,
1879             zc->zc_iflags, &config);
1880         (void) nvlist_lookup_nvlist_array(config, ZPOOL_CONFIG_L2CACHE,
1881             &l2cache, &nl2cache);
1882 
1883         (void) nvlist_lookup_nvlist_array(config, ZPOOL_CONFIG_SPARES,
1884             &spares, &nspares);
1885 
1886         /*
1887          * A root pool with concatenated devices is not supported.
1888          * Thus, can not add a device to a root pool.
1889          *
1890          * Intent log device can not be added to a rootpool because
1891          * during mountroot, zil is replayed, a seperated log device
1892          * can not be accessed during the mountroot time.
1893          *
1894          * l2cache and spare devices are ok to be added to a rootpool.
1895          */
1896         if (spa_bootfs(spa) != 0 && nl2cache == 0 && nspares == 0) {
1897                 nvlist_free(config);
1898                 spa_close(spa, FTAG);
1899                 return (SET_ERROR(EDOM));
1900         }
1901 
1902         if (error == 0) {
1903                 error = spa_vdev_add(spa, config);
1904                 nvlist_free(config);
1905         }
1906         spa_close(spa, FTAG);
1907         return (error);
1908 }
1909 
1910 /*
1911  * inputs:
1912  * zc_name              name of the pool
1913  * zc_guid              guid of vdev to remove
1914  * zc_cookie            cancel removal
1915  */
1916 static int
1917 zfs_ioc_vdev_remove(zfs_cmd_t *zc)
1918 {
1919         spa_t *spa;
1920         int error;
1921 
1922         error = spa_open(zc->zc_name, &spa, FTAG);
1923         if (error != 0)
1924                 return (error);
1925         if (zc->zc_cookie != 0) {
1926                 error = spa_vdev_remove_cancel(spa);
1927         } else {
1928                 error = spa_vdev_remove(spa, zc->zc_guid, B_FALSE);
1929         }
1930         spa_close(spa, FTAG);
1931         return (error);
1932 }
1933 
1934 static int
1935 zfs_ioc_vdev_set_state(zfs_cmd_t *zc)
1936 {
1937         spa_t *spa;
1938         int error;
1939         vdev_state_t newstate = VDEV_STATE_UNKNOWN;
1940 
1941         if ((error = spa_open(zc->zc_name, &spa, FTAG)) != 0)
1942                 return (error);
1943         switch (zc->zc_cookie) {
1944         case VDEV_STATE_ONLINE:
1945                 error = vdev_online(spa, zc->zc_guid, zc->zc_obj, &newstate);
1946                 break;
1947 
1948         case VDEV_STATE_OFFLINE:
1949                 error = vdev_offline(spa, zc->zc_guid, zc->zc_obj);
1950                 break;
1951 
1952         case VDEV_STATE_FAULTED:
1953                 if (zc->zc_obj != VDEV_AUX_ERR_EXCEEDED &&
1954                     zc->zc_obj != VDEV_AUX_EXTERNAL)
1955                         zc->zc_obj = VDEV_AUX_ERR_EXCEEDED;
1956 
1957                 error = vdev_fault(spa, zc->zc_guid, zc->zc_obj);
1958                 break;
1959 
1960         case VDEV_STATE_DEGRADED:
1961                 if (zc->zc_obj != VDEV_AUX_ERR_EXCEEDED &&
1962                     zc->zc_obj != VDEV_AUX_EXTERNAL)
1963                         zc->zc_obj = VDEV_AUX_ERR_EXCEEDED;
1964 
1965                 error = vdev_degrade(spa, zc->zc_guid, zc->zc_obj);
1966                 break;
1967 
1968         default:
1969                 error = SET_ERROR(EINVAL);
1970         }
1971         zc->zc_cookie = newstate;
1972         spa_close(spa, FTAG);
1973         return (error);
1974 }
1975 
1976 static int
1977 zfs_ioc_vdev_attach(zfs_cmd_t *zc)
1978 {
1979         spa_t *spa;
1980         int replacing = zc->zc_cookie;
1981         nvlist_t *config;
1982         int error;
1983 
1984         if ((error = spa_open(zc->zc_name, &spa, FTAG)) != 0)
1985                 return (error);
1986 
1987         if ((error = get_nvlist(zc->zc_nvlist_conf, zc->zc_nvlist_conf_size,
1988             zc->zc_iflags, &config)) == 0) {
1989                 error = spa_vdev_attach(spa, zc->zc_guid, config, replacing);
1990                 nvlist_free(config);
1991         }
1992 
1993         spa_close(spa, FTAG);
1994         return (error);
1995 }
1996 
1997 static int
1998 zfs_ioc_vdev_detach(zfs_cmd_t *zc)
1999 {
2000         spa_t *spa;
2001         int error;
2002 
2003         if ((error = spa_open(zc->zc_name, &spa, FTAG)) != 0)
2004                 return (error);
2005 
2006         error = spa_vdev_detach(spa, zc->zc_guid, 0, B_FALSE);
2007 
2008         spa_close(spa, FTAG);
2009         return (error);
2010 }
2011 
2012 static int
2013 zfs_ioc_vdev_split(zfs_cmd_t *zc)
2014 {
2015         spa_t *spa;
2016         nvlist_t *config, *props = NULL;
2017         int error;
2018         boolean_t exp = !!(zc->zc_cookie & ZPOOL_EXPORT_AFTER_SPLIT);
2019 
2020         if ((error = spa_open(zc->zc_name, &spa, FTAG)) != 0)
2021                 return (error);
2022 
2023         if (error = get_nvlist(zc->zc_nvlist_conf, zc->zc_nvlist_conf_size,
2024             zc->zc_iflags, &config)) {
2025                 spa_close(spa, FTAG);
2026                 return (error);
2027         }
2028 
2029         if (zc->zc_nvlist_src_size != 0 && (error =
2030             get_nvlist(zc->zc_nvlist_src, zc->zc_nvlist_src_size,
2031             zc->zc_iflags, &props))) {
2032                 spa_close(spa, FTAG);
2033                 nvlist_free(config);
2034                 return (error);
2035         }
2036 
2037         error = spa_vdev_split_mirror(spa, zc->zc_string, config, props, exp);
2038 
2039         spa_close(spa, FTAG);
2040 
2041         nvlist_free(config);
2042         nvlist_free(props);
2043 
2044         return (error);
2045 }
2046 
2047 static int
2048 zfs_ioc_vdev_setpath(zfs_cmd_t *zc)
2049 {
2050         spa_t *spa;
2051         char *path = zc->zc_value;
2052         uint64_t guid = zc->zc_guid;
2053         int error;
2054 
2055         error = spa_open(zc->zc_name, &spa, FTAG);
2056         if (error != 0)
2057                 return (error);
2058 
2059         error = spa_vdev_setpath(spa, guid, path);
2060         spa_close(spa, FTAG);
2061         return (error);
2062 }
2063 
2064 static int
2065 zfs_ioc_vdev_setfru(zfs_cmd_t *zc)
2066 {
2067         spa_t *spa;
2068         char *fru = zc->zc_value;
2069         uint64_t guid = zc->zc_guid;
2070         int error;
2071 
2072         error = spa_open(zc->zc_name, &spa, FTAG);
2073         if (error != 0)
2074                 return (error);
2075 
2076         error = spa_vdev_setfru(spa, guid, fru);
2077         spa_close(spa, FTAG);
2078         return (error);
2079 }
2080 
2081 static int
2082 zfs_ioc_objset_stats_impl(zfs_cmd_t *zc, objset_t *os)
2083 {
2084         int error = 0;
2085         nvlist_t *nv;
2086 
2087         dmu_objset_fast_stat(os, &zc->zc_objset_stats);
2088 
2089         if (zc->zc_nvlist_dst != 0 &&
2090             (error = dsl_prop_get_all(os, &nv)) == 0) {
2091                 dmu_objset_stats(os, nv);
2092                 /*
2093                  * NB: zvol_get_stats() will read the objset contents,
2094                  * which we aren't supposed to do with a
2095                  * DS_MODE_USER hold, because it could be
2096                  * inconsistent.  So this is a bit of a workaround...
2097                  * XXX reading with out owning
2098                  */
2099                 if (!zc->zc_objset_stats.dds_inconsistent &&
2100                     dmu_objset_type(os) == DMU_OST_ZVOL) {
2101                         error = zvol_get_stats(os, nv);
2102                         if (error == EIO)
2103                                 return (error);
2104                         VERIFY0(error);
2105                 }
2106                 error = put_nvlist(zc, nv);
2107                 nvlist_free(nv);
2108         }
2109 
2110         return (error);
2111 }
2112 
2113 /*
2114  * inputs:
2115  * zc_name              name of filesystem
2116  * zc_nvlist_dst_size   size of buffer for property nvlist
2117  *
2118  * outputs:
2119  * zc_objset_stats      stats
2120  * zc_nvlist_dst        property nvlist
2121  * zc_nvlist_dst_size   size of property nvlist
2122  */
2123 static int
2124 zfs_ioc_objset_stats(zfs_cmd_t *zc)
2125 {
2126         objset_t *os;
2127         int error;
2128 
2129         error = dmu_objset_hold(zc->zc_name, FTAG, &os);
2130         if (error == 0) {
2131                 error = zfs_ioc_objset_stats_impl(zc, os);
2132                 dmu_objset_rele(os, FTAG);
2133         }
2134 
2135         return (error);
2136 }
2137 
2138 /*
2139  * inputs:
2140  * zc_name              name of filesystem
2141  * zc_nvlist_dst_size   size of buffer for property nvlist
2142  *
2143  * outputs:
2144  * zc_nvlist_dst        received property nvlist
2145  * zc_nvlist_dst_size   size of received property nvlist
2146  *
2147  * Gets received properties (distinct from local properties on or after
2148  * SPA_VERSION_RECVD_PROPS) for callers who want to differentiate received from
2149  * local property values.
2150  */
2151 static int
2152 zfs_ioc_objset_recvd_props(zfs_cmd_t *zc)
2153 {
2154         int error = 0;
2155         nvlist_t *nv;
2156 
2157         /*
2158          * Without this check, we would return local property values if the
2159          * caller has not already received properties on or after
2160          * SPA_VERSION_RECVD_PROPS.
2161          */
2162         if (!dsl_prop_get_hasrecvd(zc->zc_name))
2163                 return (SET_ERROR(ENOTSUP));
2164 
2165         if (zc->zc_nvlist_dst != 0 &&
2166             (error = dsl_prop_get_received(zc->zc_name, &nv)) == 0) {
2167                 error = put_nvlist(zc, nv);
2168                 nvlist_free(nv);
2169         }
2170 
2171         return (error);
2172 }
2173 
2174 static int
2175 nvl_add_zplprop(objset_t *os, nvlist_t *props, zfs_prop_t prop)
2176 {
2177         uint64_t value;
2178         int error;
2179 
2180         /*
2181          * zfs_get_zplprop() will either find a value or give us
2182          * the default value (if there is one).
2183          */
2184         if ((error = zfs_get_zplprop(os, prop, &value)) != 0)
2185                 return (error);
2186         VERIFY(nvlist_add_uint64(props, zfs_prop_to_name(prop), value) == 0);
2187         return (0);
2188 }
2189 
2190 /*
2191  * inputs:
2192  * zc_name              name of filesystem
2193  * zc_nvlist_dst_size   size of buffer for zpl property nvlist
2194  *
2195  * outputs:
2196  * zc_nvlist_dst        zpl property nvlist
2197  * zc_nvlist_dst_size   size of zpl property nvlist
2198  */
2199 static int
2200 zfs_ioc_objset_zplprops(zfs_cmd_t *zc)
2201 {
2202         objset_t *os;
2203         int err;
2204 
2205         /* XXX reading without owning */
2206         if (err = dmu_objset_hold(zc->zc_name, FTAG, &os))
2207                 return (err);
2208 
2209         dmu_objset_fast_stat(os, &zc->zc_objset_stats);
2210 
2211         /*
2212          * NB: nvl_add_zplprop() will read the objset contents,
2213          * which we aren't supposed to do with a DS_MODE_USER
2214          * hold, because it could be inconsistent.
2215          */
2216         if (zc->zc_nvlist_dst != NULL &&
2217             !zc->zc_objset_stats.dds_inconsistent &&
2218             dmu_objset_type(os) == DMU_OST_ZFS) {
2219                 nvlist_t *nv;
2220 
2221                 VERIFY(nvlist_alloc(&nv, NV_UNIQUE_NAME, KM_SLEEP) == 0);
2222                 if ((err = nvl_add_zplprop(os, nv, ZFS_PROP_VERSION)) == 0 &&
2223                     (err = nvl_add_zplprop(os, nv, ZFS_PROP_NORMALIZE)) == 0 &&
2224                     (err = nvl_add_zplprop(os, nv, ZFS_PROP_UTF8ONLY)) == 0 &&
2225                     (err = nvl_add_zplprop(os, nv, ZFS_PROP_CASE)) == 0)
2226                         err = put_nvlist(zc, nv);
2227                 nvlist_free(nv);
2228         } else {
2229                 err = SET_ERROR(ENOENT);
2230         }
2231         dmu_objset_rele(os, FTAG);
2232         return (err);
2233 }
2234 
2235 static boolean_t
2236 dataset_name_hidden(const char *name)
2237 {
2238         /*
2239          * Skip over datasets that are not visible in this zone,
2240          * internal datasets (which have a $ in their name), and
2241          * temporary datasets (which have a % in their name).
2242          */
2243         if (strchr(name, '$') != NULL)
2244                 return (B_TRUE);
2245         if (strchr(name, '%') != NULL)
2246                 return (B_TRUE);
2247         if (!INGLOBALZONE(curproc) && !zone_dataset_visible(name, NULL))
2248                 return (B_TRUE);
2249         return (B_FALSE);
2250 }
2251 
2252 /*
2253  * inputs:
2254  * zc_name              name of filesystem
2255  * zc_cookie            zap cursor
2256  * zc_nvlist_dst_size   size of buffer for property nvlist
2257  *
2258  * outputs:
2259  * zc_name              name of next filesystem
2260  * zc_cookie            zap cursor
2261  * zc_objset_stats      stats
2262  * zc_nvlist_dst        property nvlist
2263  * zc_nvlist_dst_size   size of property nvlist
2264  */
2265 static int
2266 zfs_ioc_dataset_list_next(zfs_cmd_t *zc)
2267 {
2268         objset_t *os;
2269         int error;
2270         char *p;
2271         size_t orig_len = strlen(zc->zc_name);
2272 
2273 top:
2274         if (error = dmu_objset_hold(zc->zc_name, FTAG, &os)) {
2275                 if (error == ENOENT)
2276                         error = SET_ERROR(ESRCH);
2277                 return (error);
2278         }
2279 
2280         p = strrchr(zc->zc_name, '/');
2281         if (p == NULL || p[1] != '\0')
2282                 (void) strlcat(zc->zc_name, "/", sizeof (zc->zc_name));
2283         p = zc->zc_name + strlen(zc->zc_name);
2284 
2285         do {
2286                 error = dmu_dir_list_next(os,
2287                     sizeof (zc->zc_name) - (p - zc->zc_name), p,
2288                     NULL, &zc->zc_cookie);
2289                 if (error == ENOENT)
2290                         error = SET_ERROR(ESRCH);
2291         } while (error == 0 && dataset_name_hidden(zc->zc_name));
2292         dmu_objset_rele(os, FTAG);
2293 
2294         /*
2295          * If it's an internal dataset (ie. with a '$' in its name),
2296          * don't try to get stats for it, otherwise we'll return ENOENT.
2297          */
2298         if (error == 0 && strchr(zc->zc_name, '$') == NULL) {
2299                 error = zfs_ioc_objset_stats(zc); /* fill in the stats */
2300                 if (error == ENOENT) {
2301                         /* We lost a race with destroy, get the next one. */
2302                         zc->zc_name[orig_len] = '\0';
2303                         goto top;
2304                 }
2305         }
2306         return (error);
2307 }
2308 
2309 /*
2310  * inputs:
2311  * zc_name              name of filesystem
2312  * zc_cookie            zap cursor
2313  * zc_nvlist_dst_size   size of buffer for property nvlist
2314  * zc_simple            when set, only name is requested
2315  *
2316  * outputs:
2317  * zc_name              name of next snapshot
2318  * zc_objset_stats      stats
2319  * zc_nvlist_dst        property nvlist
2320  * zc_nvlist_dst_size   size of property nvlist
2321  */
2322 static int
2323 zfs_ioc_snapshot_list_next(zfs_cmd_t *zc)
2324 {
2325         objset_t *os;
2326         int error;
2327 
2328         error = dmu_objset_hold(zc->zc_name, FTAG, &os);
2329         if (error != 0) {
2330                 return (error == ENOENT ? ESRCH : error);
2331         }
2332 
2333         /*
2334          * A dataset name of maximum length cannot have any snapshots,
2335          * so exit immediately.
2336          */
2337         if (strlcat(zc->zc_name, "@", sizeof (zc->zc_name)) >=
2338             ZFS_MAX_DATASET_NAME_LEN) {
2339                 dmu_objset_rele(os, FTAG);
2340                 return (SET_ERROR(ESRCH));
2341         }
2342 
2343         error = dmu_snapshot_list_next(os,
2344             sizeof (zc->zc_name) - strlen(zc->zc_name),
2345             zc->zc_name + strlen(zc->zc_name), &zc->zc_obj, &zc->zc_cookie,
2346             NULL);
2347 
2348         if (error == 0 && !zc->zc_simple) {
2349                 dsl_dataset_t *ds;
2350                 dsl_pool_t *dp = os->os_dsl_dataset->ds_dir->dd_pool;
2351 
2352                 error = dsl_dataset_hold_obj(dp, zc->zc_obj, FTAG, &ds);
2353                 if (error == 0) {
2354                         objset_t *ossnap;
2355 
2356                         error = dmu_objset_from_ds(ds, &ossnap);
2357                         if (error == 0)
2358                                 error = zfs_ioc_objset_stats_impl(zc, ossnap);
2359                         dsl_dataset_rele(ds, FTAG);
2360                 }
2361         } else if (error == ENOENT) {
2362                 error = SET_ERROR(ESRCH);
2363         }
2364 
2365         dmu_objset_rele(os, FTAG);
2366         /* if we failed, undo the @ that we tacked on to zc_name */
2367         if (error != 0)
2368                 *strchr(zc->zc_name, '@') = '\0';
2369         return (error);
2370 }
2371 
2372 static int
2373 zfs_prop_set_userquota(const char *dsname, nvpair_t *pair)
2374 {
2375         const char *propname = nvpair_name(pair);
2376         uint64_t *valary;
2377         unsigned int vallen;
2378         const char *domain;
2379         char *dash;
2380         zfs_userquota_prop_t type;
2381         uint64_t rid;
2382         uint64_t quota;
2383         zfsvfs_t *zfsvfs;
2384         int err;
2385 
2386         if (nvpair_type(pair) == DATA_TYPE_NVLIST) {
2387                 nvlist_t *attrs;
2388                 VERIFY(nvpair_value_nvlist(pair, &attrs) == 0);
2389                 if (nvlist_lookup_nvpair(attrs, ZPROP_VALUE,
2390                     &pair) != 0)
2391                         return (SET_ERROR(EINVAL));
2392         }
2393 
2394         /*
2395          * A correctly constructed propname is encoded as
2396          * userquota@<rid>-<domain>.
2397          */
2398         if ((dash = strchr(propname, '-')) == NULL ||
2399             nvpair_value_uint64_array(pair, &valary, &vallen) != 0 ||
2400             vallen != 3)
2401                 return (SET_ERROR(EINVAL));
2402 
2403         domain = dash + 1;
2404         type = valary[0];
2405         rid = valary[1];
2406         quota = valary[2];
2407 
2408         err = zfsvfs_hold(dsname, FTAG, &zfsvfs, B_FALSE);
2409         if (err == 0) {
2410                 err = zfs_set_userquota(zfsvfs, type, domain, rid, quota);
2411                 zfsvfs_rele(zfsvfs, FTAG);
2412         }
2413 
2414         return (err);
2415 }
2416 
2417 /*
2418  * If the named property is one that has a special function to set its value,
2419  * return 0 on success and a positive error code on failure; otherwise if it is
2420  * not one of the special properties handled by this function, return -1.
2421  *
2422  * XXX: It would be better for callers of the property interface if we handled
2423  * these special cases in dsl_prop.c (in the dsl layer).
2424  */
2425 static int
2426 zfs_prop_set_special(const char *dsname, zprop_source_t source,
2427     nvpair_t *pair)
2428 {
2429         const char *propname = nvpair_name(pair);
2430         zfs_prop_t prop = zfs_name_to_prop(propname);
2431         uint64_t intval;
2432         int err = -1;
2433 
2434         if (prop == ZPROP_INVAL) {
2435                 if (zfs_prop_userquota(propname))
2436                         return (zfs_prop_set_userquota(dsname, pair));
2437                 return (-1);
2438         }
2439 
2440         if (nvpair_type(pair) == DATA_TYPE_NVLIST) {
2441                 nvlist_t *attrs;
2442                 VERIFY(nvpair_value_nvlist(pair, &attrs) == 0);
2443                 VERIFY(nvlist_lookup_nvpair(attrs, ZPROP_VALUE,
2444                     &pair) == 0);
2445         }
2446 
2447         if (zfs_prop_get_type(prop) == PROP_TYPE_STRING)
2448                 return (-1);
2449 
2450         VERIFY(0 == nvpair_value_uint64(pair, &intval));
2451 
2452         switch (prop) {
2453         case ZFS_PROP_QUOTA:
2454                 err = dsl_dir_set_quota(dsname, source, intval);
2455                 break;
2456         case ZFS_PROP_REFQUOTA:
2457                 err = dsl_dataset_set_refquota(dsname, source, intval);
2458                 break;
2459         case ZFS_PROP_FILESYSTEM_LIMIT:
2460         case ZFS_PROP_SNAPSHOT_LIMIT:
2461                 if (intval == UINT64_MAX) {
2462                         /* clearing the limit, just do it */
2463                         err = 0;
2464                 } else {
2465                         err = dsl_dir_activate_fs_ss_limit(dsname);
2466                 }
2467                 /*
2468                  * Set err to -1 to force the zfs_set_prop_nvlist code down the
2469                  * default path to set the value in the nvlist.
2470                  */
2471                 if (err == 0)
2472                         err = -1;
2473                 break;
2474         case ZFS_PROP_RESERVATION:
2475                 err = dsl_dir_set_reservation(dsname, source, intval);
2476                 break;
2477         case ZFS_PROP_REFRESERVATION:
2478                 err = dsl_dataset_set_refreservation(dsname, source, intval);
2479                 break;
2480         case ZFS_PROP_VOLSIZE:
2481                 err = zvol_set_volsize(dsname, intval);
2482                 break;
2483         case ZFS_PROP_VERSION:
2484         {
2485                 zfsvfs_t *zfsvfs;
2486 
2487                 if ((err = zfsvfs_hold(dsname, FTAG, &zfsvfs, B_TRUE)) != 0)
2488                         break;
2489 
2490                 err = zfs_set_version(zfsvfs, intval);
2491                 zfsvfs_rele(zfsvfs, FTAG);
2492 
2493                 if (err == 0 && intval >= ZPL_VERSION_USERSPACE) {
2494                         zfs_cmd_t *zc;
2495 
2496                         zc = kmem_zalloc(sizeof (zfs_cmd_t), KM_SLEEP);
2497                         (void) strcpy(zc->zc_name, dsname);
2498                         (void) zfs_ioc_userspace_upgrade(zc);
2499                         kmem_free(zc, sizeof (zfs_cmd_t));
2500                 }
2501                 break;
2502         }
2503         default:
2504                 err = -1;
2505         }
2506 
2507         return (err);
2508 }
2509 
2510 /*
2511  * This function is best effort. If it fails to set any of the given properties,
2512  * it continues to set as many as it can and returns the last error
2513  * encountered. If the caller provides a non-NULL errlist, it will be filled in
2514  * with the list of names of all the properties that failed along with the
2515  * corresponding error numbers.
2516  *
2517  * If every property is set successfully, zero is returned and errlist is not
2518  * modified.
2519  */
2520 int
2521 zfs_set_prop_nvlist(const char *dsname, zprop_source_t source, nvlist_t *nvl,
2522     nvlist_t *errlist)
2523 {
2524         nvpair_t *pair;
2525         nvpair_t *propval;
2526         int rv = 0;
2527         uint64_t intval;
2528         char *strval;
2529         nvlist_t *genericnvl = fnvlist_alloc();
2530         nvlist_t *retrynvl = fnvlist_alloc();
2531 
2532 retry:
2533         pair = NULL;
2534         while ((pair = nvlist_next_nvpair(nvl, pair)) != NULL) {
2535                 const char *propname = nvpair_name(pair);
2536                 zfs_prop_t prop = zfs_name_to_prop(propname);
2537                 int err = 0;
2538 
2539                 /* decode the property value */
2540                 propval = pair;
2541                 if (nvpair_type(pair) == DATA_TYPE_NVLIST) {
2542                         nvlist_t *attrs;
2543                         attrs = fnvpair_value_nvlist(pair);
2544                         if (nvlist_lookup_nvpair(attrs, ZPROP_VALUE,
2545                             &propval) != 0)
2546                                 err = SET_ERROR(EINVAL);
2547                 }
2548 
2549                 /* Validate value type */
2550                 if (err == 0 && prop == ZPROP_INVAL) {
2551                         if (zfs_prop_user(propname)) {
2552                                 if (nvpair_type(propval) != DATA_TYPE_STRING)
2553                                         err = SET_ERROR(EINVAL);
2554                         } else if (zfs_prop_userquota(propname)) {
2555                                 if (nvpair_type(propval) !=
2556                                     DATA_TYPE_UINT64_ARRAY)
2557                                         err = SET_ERROR(EINVAL);
2558                         } else {
2559                                 err = SET_ERROR(EINVAL);
2560                         }
2561                 } else if (err == 0) {
2562                         if (nvpair_type(propval) == DATA_TYPE_STRING) {
2563                                 if (zfs_prop_get_type(prop) != PROP_TYPE_STRING)
2564                                         err = SET_ERROR(EINVAL);
2565                         } else if (nvpair_type(propval) == DATA_TYPE_UINT64) {
2566                                 const char *unused;
2567 
2568                                 intval = fnvpair_value_uint64(propval);
2569 
2570                                 switch (zfs_prop_get_type(prop)) {
2571                                 case PROP_TYPE_NUMBER:
2572                                         break;
2573                                 case PROP_TYPE_STRING:
2574                                         err = SET_ERROR(EINVAL);
2575                                         break;
2576                                 case PROP_TYPE_INDEX:
2577                                         if (zfs_prop_index_to_string(prop,
2578                                             intval, &unused) != 0)
2579                                                 err = SET_ERROR(EINVAL);
2580                                         break;
2581                                 default:
2582                                         cmn_err(CE_PANIC,
2583                                             "unknown property type");
2584                                 }
2585                         } else {
2586                                 err = SET_ERROR(EINVAL);
2587                         }
2588                 }
2589 
2590                 /* Validate permissions */
2591                 if (err == 0)
2592                         err = zfs_check_settable(dsname, pair, CRED());
2593 
2594                 if (err == 0) {
2595                         err = zfs_prop_set_special(dsname, source, pair);
2596                         if (err == -1) {
2597                                 /*
2598                                  * For better performance we build up a list of
2599                                  * properties to set in a single transaction.
2600                                  */
2601                                 err = nvlist_add_nvpair(genericnvl, pair);
2602                         } else if (err != 0 && nvl != retrynvl) {
2603                                 /*
2604                                  * This may be a spurious error caused by
2605                                  * receiving quota and reservation out of order.
2606                                  * Try again in a second pass.
2607                                  */
2608                                 err = nvlist_add_nvpair(retrynvl, pair);
2609                         }
2610                 }
2611 
2612                 if (err != 0) {
2613                         if (errlist != NULL)
2614                                 fnvlist_add_int32(errlist, propname, err);
2615                         rv = err;
2616                 }
2617         }
2618 
2619         if (nvl != retrynvl && !nvlist_empty(retrynvl)) {
2620                 nvl = retrynvl;
2621                 goto retry;
2622         }
2623 
2624         if (!nvlist_empty(genericnvl) &&
2625             dsl_props_set(dsname, source, genericnvl) != 0) {
2626                 /*
2627                  * If this fails, we still want to set as many properties as we
2628                  * can, so try setting them individually.
2629                  */
2630                 pair = NULL;
2631                 while ((pair = nvlist_next_nvpair(genericnvl, pair)) != NULL) {
2632                         const char *propname = nvpair_name(pair);
2633                         int err = 0;
2634 
2635                         propval = pair;
2636                         if (nvpair_type(pair) == DATA_TYPE_NVLIST) {
2637                                 nvlist_t *attrs;
2638                                 attrs = fnvpair_value_nvlist(pair);
2639                                 propval = fnvlist_lookup_nvpair(attrs,
2640                                     ZPROP_VALUE);
2641                         }
2642 
2643                         if (nvpair_type(propval) == DATA_TYPE_STRING) {
2644                                 strval = fnvpair_value_string(propval);
2645                                 err = dsl_prop_set_string(dsname, propname,
2646                                     source, strval);
2647                         } else {
2648                                 intval = fnvpair_value_uint64(propval);
2649                                 err = dsl_prop_set_int(dsname, propname, source,
2650                                     intval);
2651                         }
2652 
2653                         if (err != 0) {
2654                                 if (errlist != NULL) {
2655                                         fnvlist_add_int32(errlist, propname,
2656                                             err);
2657                                 }
2658                                 rv = err;
2659                         }
2660                 }
2661         }
2662         nvlist_free(genericnvl);
2663         nvlist_free(retrynvl);
2664 
2665         return (rv);
2666 }
2667 
2668 /*
2669  * Check that all the properties are valid user properties.
2670  */
2671 static int
2672 zfs_check_userprops(const char *fsname, nvlist_t *nvl)
2673 {
2674         nvpair_t *pair = NULL;
2675         int error = 0;
2676 
2677         while ((pair = nvlist_next_nvpair(nvl, pair)) != NULL) {
2678                 const char *propname = nvpair_name(pair);
2679 
2680                 if (!zfs_prop_user(propname) ||
2681                     nvpair_type(pair) != DATA_TYPE_STRING)
2682                         return (SET_ERROR(EINVAL));
2683 
2684                 if (error = zfs_secpolicy_write_perms(fsname,
2685                     ZFS_DELEG_PERM_USERPROP, CRED()))
2686                         return (error);
2687 
2688                 if (strlen(propname) >= ZAP_MAXNAMELEN)
2689                         return (SET_ERROR(ENAMETOOLONG));
2690 
2691                 if (strlen(fnvpair_value_string(pair)) >= ZAP_MAXVALUELEN)
2692                         return (E2BIG);
2693         }
2694         return (0);
2695 }
2696 
2697 static void
2698 props_skip(nvlist_t *props, nvlist_t *skipped, nvlist_t **newprops)
2699 {
2700         nvpair_t *pair;
2701 
2702         VERIFY(nvlist_alloc(newprops, NV_UNIQUE_NAME, KM_SLEEP) == 0);
2703 
2704         pair = NULL;
2705         while ((pair = nvlist_next_nvpair(props, pair)) != NULL) {
2706                 if (nvlist_exists(skipped, nvpair_name(pair)))
2707                         continue;
2708 
2709                 VERIFY(nvlist_add_nvpair(*newprops, pair) == 0);
2710         }
2711 }
2712 
2713 static int
2714 clear_received_props(const char *dsname, nvlist_t *props,
2715     nvlist_t *skipped)
2716 {
2717         int err = 0;
2718         nvlist_t *cleared_props = NULL;
2719         props_skip(props, skipped, &cleared_props);
2720         if (!nvlist_empty(cleared_props)) {
2721                 /*
2722                  * Acts on local properties until the dataset has received
2723                  * properties at least once on or after SPA_VERSION_RECVD_PROPS.
2724                  */
2725                 zprop_source_t flags = (ZPROP_SRC_NONE |
2726                     (dsl_prop_get_hasrecvd(dsname) ? ZPROP_SRC_RECEIVED : 0));
2727                 err = zfs_set_prop_nvlist(dsname, flags, cleared_props, NULL);
2728         }
2729         nvlist_free(cleared_props);
2730         return (err);
2731 }
2732 
2733 /*
2734  * inputs:
2735  * zc_name              name of filesystem
2736  * zc_value             name of property to set
2737  * zc_nvlist_src{_size} nvlist of properties to apply
2738  * zc_cookie            received properties flag
2739  *
2740  * outputs:
2741  * zc_nvlist_dst{_size} error for each unapplied received property
2742  */
2743 static int
2744 zfs_ioc_set_prop(zfs_cmd_t *zc)
2745 {
2746         nvlist_t *nvl;
2747         boolean_t received = zc->zc_cookie;
2748         zprop_source_t source = (received ? ZPROP_SRC_RECEIVED :
2749             ZPROP_SRC_LOCAL);
2750         nvlist_t *errors;
2751         int error;
2752 
2753         if ((error = get_nvlist(zc->zc_nvlist_src, zc->zc_nvlist_src_size,
2754             zc->zc_iflags, &nvl)) != 0)
2755                 return (error);
2756 
2757         if (received) {
2758                 nvlist_t *origprops;
2759 
2760                 if (dsl_prop_get_received(zc->zc_name, &origprops) == 0) {
2761                         (void) clear_received_props(zc->zc_name,
2762                             origprops, nvl);
2763                         nvlist_free(origprops);
2764                 }
2765 
2766                 error = dsl_prop_set_hasrecvd(zc->zc_name);
2767         }
2768 
2769         errors = fnvlist_alloc();
2770         if (error == 0)
2771                 error = zfs_set_prop_nvlist(zc->zc_name, source, nvl, errors);
2772 
2773         if (zc->zc_nvlist_dst != NULL && errors != NULL) {
2774                 (void) put_nvlist(zc, errors);
2775         }
2776 
2777         nvlist_free(errors);
2778         nvlist_free(nvl);
2779         return (error);
2780 }
2781 
2782 /*
2783  * inputs:
2784  * zc_name              name of filesystem
2785  * zc_value             name of property to inherit
2786  * zc_cookie            revert to received value if TRUE
2787  *
2788  * outputs:             none
2789  */
2790 static int
2791 zfs_ioc_inherit_prop(zfs_cmd_t *zc)
2792 {
2793         const char *propname = zc->zc_value;
2794         zfs_prop_t prop = zfs_name_to_prop(propname);
2795         boolean_t received = zc->zc_cookie;
2796         zprop_source_t source = (received
2797             ? ZPROP_SRC_NONE            /* revert to received value, if any */
2798             : ZPROP_SRC_INHERITED);     /* explicitly inherit */
2799 
2800         if (received) {
2801                 nvlist_t *dummy;
2802                 nvpair_t *pair;
2803                 zprop_type_t type;
2804                 int err;
2805 
2806                 /*
2807                  * zfs_prop_set_special() expects properties in the form of an
2808                  * nvpair with type info.
2809                  */
2810                 if (prop == ZPROP_INVAL) {
2811                         if (!zfs_prop_user(propname))
2812                                 return (SET_ERROR(EINVAL));
2813 
2814                         type = PROP_TYPE_STRING;
2815                 } else if (prop == ZFS_PROP_VOLSIZE ||
2816                     prop == ZFS_PROP_VERSION) {
2817                         return (SET_ERROR(EINVAL));
2818                 } else {
2819                         type = zfs_prop_get_type(prop);
2820                 }
2821 
2822                 VERIFY(nvlist_alloc(&dummy, NV_UNIQUE_NAME, KM_SLEEP) == 0);
2823 
2824                 switch (type) {
2825                 case PROP_TYPE_STRING:
2826                         VERIFY(0 == nvlist_add_string(dummy, propname, ""));
2827                         break;
2828                 case PROP_TYPE_NUMBER:
2829                 case PROP_TYPE_INDEX:
2830                         VERIFY(0 == nvlist_add_uint64(dummy, propname, 0));
2831                         break;
2832                 default:
2833                         nvlist_free(dummy);
2834                         return (SET_ERROR(EINVAL));
2835                 }
2836 
2837                 pair = nvlist_next_nvpair(dummy, NULL);
2838                 err = zfs_prop_set_special(zc->zc_name, source, pair);
2839                 nvlist_free(dummy);
2840                 if (err != -1)
2841                         return (err); /* special property already handled */
2842         } else {
2843                 /*
2844                  * Only check this in the non-received case. We want to allow
2845                  * 'inherit -S' to revert non-inheritable properties like quota
2846                  * and reservation to the received or default values even though
2847                  * they are not considered inheritable.
2848                  */
2849                 if (prop != ZPROP_INVAL && !zfs_prop_inheritable(prop))
2850                         return (SET_ERROR(EINVAL));
2851         }
2852 
2853         /* property name has been validated by zfs_secpolicy_inherit_prop() */
2854         return (dsl_prop_inherit(zc->zc_name, zc->zc_value, source));
2855 }
2856 
2857 static int
2858 zfs_ioc_pool_set_props(zfs_cmd_t *zc)
2859 {
2860         nvlist_t *props;
2861         spa_t *spa;
2862         int error;
2863         nvpair_t *pair;
2864 
2865         if (error = get_nvlist(zc->zc_nvlist_src, zc->zc_nvlist_src_size,
2866             zc->zc_iflags, &props))
2867                 return (error);
2868 
2869         /*
2870          * If the only property is the configfile, then just do a spa_lookup()
2871          * to handle the faulted case.
2872          */
2873         pair = nvlist_next_nvpair(props, NULL);
2874         if (pair != NULL && strcmp(nvpair_name(pair),
2875             zpool_prop_to_name(ZPOOL_PROP_CACHEFILE)) == 0 &&
2876             nvlist_next_nvpair(props, pair) == NULL) {
2877                 mutex_enter(&spa_namespace_lock);
2878                 if ((spa = spa_lookup(zc->zc_name)) != NULL) {
2879                         spa_configfile_set(spa, props, B_FALSE);
2880                         spa_write_cachefile(spa, B_FALSE, B_TRUE);
2881                 }
2882                 mutex_exit(&spa_namespace_lock);
2883                 if (spa != NULL) {
2884                         nvlist_free(props);
2885                         return (0);
2886                 }
2887         }
2888 
2889         if ((error = spa_open(zc->zc_name, &spa, FTAG)) != 0) {
2890                 nvlist_free(props);
2891                 return (error);
2892         }
2893 
2894         error = spa_prop_set(spa, props);
2895 
2896         nvlist_free(props);
2897         spa_close(spa, FTAG);
2898 
2899         return (error);
2900 }
2901 
2902 static int
2903 zfs_ioc_pool_get_props(zfs_cmd_t *zc)
2904 {
2905         spa_t *spa;
2906         int error;
2907         nvlist_t *nvp = NULL;
2908 
2909         if ((error = spa_open(zc->zc_name, &spa, FTAG)) != 0) {
2910                 /*
2911                  * If the pool is faulted, there may be properties we can still
2912                  * get (such as altroot and cachefile), so attempt to get them
2913                  * anyway.
2914                  */
2915                 mutex_enter(&spa_namespace_lock);
2916                 if ((spa = spa_lookup(zc->zc_name)) != NULL)
2917                         error = spa_prop_get(spa, &nvp);
2918                 mutex_exit(&spa_namespace_lock);
2919         } else {
2920                 error = spa_prop_get(spa, &nvp);
2921                 spa_close(spa, FTAG);
2922         }
2923 
2924         if (error == 0 && zc->zc_nvlist_dst != NULL)
2925                 error = put_nvlist(zc, nvp);
2926         else
2927                 error = SET_ERROR(EFAULT);
2928 
2929         nvlist_free(nvp);
2930         return (error);
2931 }
2932 
2933 /*
2934  * inputs:
2935  * zc_name              name of filesystem
2936  * zc_nvlist_src{_size} nvlist of delegated permissions
2937  * zc_perm_action       allow/unallow flag
2938  *
2939  * outputs:             none
2940  */
2941 static int
2942 zfs_ioc_set_fsacl(zfs_cmd_t *zc)
2943 {
2944         int error;
2945         nvlist_t *fsaclnv = NULL;
2946 
2947         if ((error = get_nvlist(zc->zc_nvlist_src, zc->zc_nvlist_src_size,
2948             zc->zc_iflags, &fsaclnv)) != 0)
2949                 return (error);
2950 
2951         /*
2952          * Verify nvlist is constructed correctly
2953          */
2954         if ((error = zfs_deleg_verify_nvlist(fsaclnv)) != 0) {
2955                 nvlist_free(fsaclnv);
2956                 return (SET_ERROR(EINVAL));
2957         }
2958 
2959         /*
2960          * If we don't have PRIV_SYS_MOUNT, then validate
2961          * that user is allowed to hand out each permission in
2962          * the nvlist(s)
2963          */
2964 
2965         error = secpolicy_zfs(CRED());
2966         if (error != 0) {
2967                 if (zc->zc_perm_action == B_FALSE) {
2968                         error = dsl_deleg_can_allow(zc->zc_name,
2969                             fsaclnv, CRED());
2970                 } else {
2971                         error = dsl_deleg_can_unallow(zc->zc_name,
2972                             fsaclnv, CRED());
2973                 }
2974         }
2975 
2976         if (error == 0)
2977                 error = dsl_deleg_set(zc->zc_name, fsaclnv, zc->zc_perm_action);
2978 
2979         nvlist_free(fsaclnv);
2980         return (error);
2981 }
2982 
2983 /*
2984  * inputs:
2985  * zc_name              name of filesystem
2986  *
2987  * outputs:
2988  * zc_nvlist_src{_size} nvlist of delegated permissions
2989  */
2990 static int
2991 zfs_ioc_get_fsacl(zfs_cmd_t *zc)
2992 {
2993         nvlist_t *nvp;
2994         int error;
2995 
2996         if ((error = dsl_deleg_get(zc->zc_name, &nvp)) == 0) {
2997                 error = put_nvlist(zc, nvp);
2998                 nvlist_free(nvp);
2999         }
3000 
3001         return (error);
3002 }
3003 
3004 /* ARGSUSED */
3005 static void
3006 zfs_create_cb(objset_t *os, void *arg, cred_t *cr, dmu_tx_t *tx)
3007 {
3008         zfs_creat_t *zct = arg;
3009 
3010         zfs_create_fs(os, cr, zct->zct_zplprops, tx);
3011 }
3012 
3013 #define ZFS_PROP_UNDEFINED      ((uint64_t)-1)
3014 
3015 /*
3016  * inputs:
3017  * os                   parent objset pointer (NULL if root fs)
3018  * fuids_ok             fuids allowed in this version of the spa?
3019  * sa_ok                SAs allowed in this version of the spa?
3020  * createprops          list of properties requested by creator
3021  *
3022  * outputs:
3023  * zplprops     values for the zplprops we attach to the master node object
3024  * is_ci        true if requested file system will be purely case-insensitive
3025  *
3026  * Determine the settings for utf8only, normalization and
3027  * casesensitivity.  Specific values may have been requested by the
3028  * creator and/or we can inherit values from the parent dataset.  If
3029  * the file system is of too early a vintage, a creator can not
3030  * request settings for these properties, even if the requested
3031  * setting is the default value.  We don't actually want to create dsl
3032  * properties for these, so remove them from the source nvlist after
3033  * processing.
3034  */
3035 static int
3036 zfs_fill_zplprops_impl(objset_t *os, uint64_t zplver,
3037     boolean_t fuids_ok, boolean_t sa_ok, nvlist_t *createprops,
3038     nvlist_t *zplprops, boolean_t *is_ci)
3039 {
3040         uint64_t sense = ZFS_PROP_UNDEFINED;
3041         uint64_t norm = ZFS_PROP_UNDEFINED;
3042         uint64_t u8 = ZFS_PROP_UNDEFINED;
3043 
3044         ASSERT(zplprops != NULL);
3045 
3046         if (os != NULL && os->os_phys->os_type != DMU_OST_ZFS)
3047                 return (SET_ERROR(EINVAL));
3048 
3049         /*
3050          * Pull out creator prop choices, if any.
3051          */
3052         if (createprops) {
3053                 (void) nvlist_lookup_uint64(createprops,
3054                     zfs_prop_to_name(ZFS_PROP_VERSION), &zplver);
3055                 (void) nvlist_lookup_uint64(createprops,
3056                     zfs_prop_to_name(ZFS_PROP_NORMALIZE), &norm);
3057                 (void) nvlist_remove_all(createprops,
3058                     zfs_prop_to_name(ZFS_PROP_NORMALIZE));
3059                 (void) nvlist_lookup_uint64(createprops,
3060                     zfs_prop_to_name(ZFS_PROP_UTF8ONLY), &u8);
3061                 (void) nvlist_remove_all(createprops,
3062                     zfs_prop_to_name(ZFS_PROP_UTF8ONLY));
3063                 (void) nvlist_lookup_uint64(createprops,
3064                     zfs_prop_to_name(ZFS_PROP_CASE), &sense);
3065                 (void) nvlist_remove_all(createprops,
3066                     zfs_prop_to_name(ZFS_PROP_CASE));
3067         }
3068 
3069         /*
3070          * If the zpl version requested is whacky or the file system
3071          * or pool is version is too "young" to support normalization
3072          * and the creator tried to set a value for one of the props,
3073          * error out.
3074          */
3075         if ((zplver < ZPL_VERSION_INITIAL || zplver > ZPL_VERSION) ||
3076             (zplver >= ZPL_VERSION_FUID && !fuids_ok) ||
3077             (zplver >= ZPL_VERSION_SA && !sa_ok) ||
3078             (zplver < ZPL_VERSION_NORMALIZATION &&
3079             (norm != ZFS_PROP_UNDEFINED || u8 != ZFS_PROP_UNDEFINED ||
3080             sense != ZFS_PROP_UNDEFINED)))
3081                 return (SET_ERROR(ENOTSUP));
3082 
3083         /*
3084          * Put the version in the zplprops
3085          */
3086         VERIFY(nvlist_add_uint64(zplprops,
3087             zfs_prop_to_name(ZFS_PROP_VERSION), zplver) == 0);
3088 
3089         if (norm == ZFS_PROP_UNDEFINED)
3090                 VERIFY(zfs_get_zplprop(os, ZFS_PROP_NORMALIZE, &norm) == 0);
3091         VERIFY(nvlist_add_uint64(zplprops,
3092             zfs_prop_to_name(ZFS_PROP_NORMALIZE), norm) == 0);
3093 
3094         /*
3095          * If we're normalizing, names must always be valid UTF-8 strings.
3096          */
3097         if (norm)
3098                 u8 = 1;
3099         if (u8 == ZFS_PROP_UNDEFINED)
3100                 VERIFY(zfs_get_zplprop(os, ZFS_PROP_UTF8ONLY, &u8) == 0);
3101         VERIFY(nvlist_add_uint64(zplprops,
3102             zfs_prop_to_name(ZFS_PROP_UTF8ONLY), u8) == 0);
3103 
3104         if (sense == ZFS_PROP_UNDEFINED)
3105                 VERIFY(zfs_get_zplprop(os, ZFS_PROP_CASE, &sense) == 0);
3106         VERIFY(nvlist_add_uint64(zplprops,
3107             zfs_prop_to_name(ZFS_PROP_CASE), sense) == 0);
3108 
3109         if (is_ci)
3110                 *is_ci = (sense == ZFS_CASE_INSENSITIVE);
3111 
3112         return (0);
3113 }
3114 
3115 static int
3116 zfs_fill_zplprops(const char *dataset, nvlist_t *createprops,
3117     nvlist_t *zplprops, boolean_t *is_ci)
3118 {
3119         boolean_t fuids_ok, sa_ok;
3120         uint64_t zplver = ZPL_VERSION;
3121         objset_t *os = NULL;
3122         char parentname[ZFS_MAX_DATASET_NAME_LEN];
3123         char *cp;
3124         spa_t *spa;
3125         uint64_t spa_vers;
3126         int error;
3127 
3128         (void) strlcpy(parentname, dataset, sizeof (parentname));
3129         cp = strrchr(parentname, '/');
3130         ASSERT(cp != NULL);
3131         cp[0] = '\0';
3132 
3133         if ((error = spa_open(dataset, &spa, FTAG)) != 0)
3134                 return (error);
3135 
3136         spa_vers = spa_version(spa);
3137         spa_close(spa, FTAG);
3138 
3139         zplver = zfs_zpl_version_map(spa_vers);
3140         fuids_ok = (zplver >= ZPL_VERSION_FUID);
3141         sa_ok = (zplver >= ZPL_VERSION_SA);
3142 
3143         /*
3144          * Open parent object set so we can inherit zplprop values.
3145          */
3146         if ((error = dmu_objset_hold(parentname, FTAG, &os)) != 0)
3147                 return (error);
3148 
3149         error = zfs_fill_zplprops_impl(os, zplver, fuids_ok, sa_ok, createprops,
3150             zplprops, is_ci);
3151         dmu_objset_rele(os, FTAG);
3152         return (error);
3153 }
3154 
3155 static int
3156 zfs_fill_zplprops_root(uint64_t spa_vers, nvlist_t *createprops,
3157     nvlist_t *zplprops, boolean_t *is_ci)
3158 {
3159         boolean_t fuids_ok;
3160         boolean_t sa_ok;
3161         uint64_t zplver = ZPL_VERSION;
3162         int error;
3163 
3164         zplver = zfs_zpl_version_map(spa_vers);
3165         fuids_ok = (zplver >= ZPL_VERSION_FUID);
3166         sa_ok = (zplver >= ZPL_VERSION_SA);
3167 
3168         error = zfs_fill_zplprops_impl(NULL, zplver, fuids_ok, sa_ok,
3169             createprops, zplprops, is_ci);
3170         return (error);
3171 }
3172 
3173 /*
3174  * innvl: {
3175  *     "type" -> dmu_objset_type_t (int32)
3176  *     (optional) "props" -> { prop -> value }
3177  * }
3178  *
3179  * outnvl: propname -> error code (int32)
3180  */
3181 static int
3182 zfs_ioc_create(const char *fsname, nvlist_t *innvl, nvlist_t *outnvl)
3183 {
3184         int error = 0;
3185         zfs_creat_t zct = { 0 };
3186         nvlist_t *nvprops = NULL;
3187         void (*cbfunc)(objset_t *os, void *arg, cred_t *cr, dmu_tx_t *tx);
3188         int32_t type32;
3189         dmu_objset_type_t type;
3190         boolean_t is_insensitive = B_FALSE;
3191 
3192         if (nvlist_lookup_int32(innvl, "type", &type32) != 0)
3193                 return (SET_ERROR(EINVAL));
3194         type = type32;
3195         (void) nvlist_lookup_nvlist(innvl, "props", &nvprops);
3196 
3197         switch (type) {
3198         case DMU_OST_ZFS:
3199                 cbfunc = zfs_create_cb;
3200                 break;
3201 
3202         case DMU_OST_ZVOL:
3203                 cbfunc = zvol_create_cb;
3204                 break;
3205 
3206         default:
3207                 cbfunc = NULL;
3208                 break;
3209         }
3210         if (strchr(fsname, '@') ||
3211             strchr(fsname, '%'))
3212                 return (SET_ERROR(EINVAL));
3213 
3214         zct.zct_props = nvprops;
3215 
3216         if (cbfunc == NULL)
3217                 return (SET_ERROR(EINVAL));
3218 
3219         if (type == DMU_OST_ZVOL) {
3220                 uint64_t volsize, volblocksize;
3221 
3222                 if (nvprops == NULL)
3223                         return (SET_ERROR(EINVAL));
3224                 if (nvlist_lookup_uint64(nvprops,
3225                     zfs_prop_to_name(ZFS_PROP_VOLSIZE), &volsize) != 0)
3226                         return (SET_ERROR(EINVAL));
3227 
3228                 if ((error = nvlist_lookup_uint64(nvprops,
3229                     zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE),
3230                     &volblocksize)) != 0 && error != ENOENT)
3231                         return (SET_ERROR(EINVAL));
3232 
3233                 if (error != 0)
3234                         volblocksize = zfs_prop_default_numeric(
3235                             ZFS_PROP_VOLBLOCKSIZE);
3236 
3237                 if ((error = zvol_check_volblocksize(
3238                     volblocksize)) != 0 ||
3239                     (error = zvol_check_volsize(volsize,
3240                     volblocksize)) != 0)
3241                         return (error);
3242         } else if (type == DMU_OST_ZFS) {
3243                 int error;
3244 
3245                 /*
3246                  * We have to have normalization and
3247                  * case-folding flags correct when we do the
3248                  * file system creation, so go figure them out
3249                  * now.
3250                  */
3251                 VERIFY(nvlist_alloc(&zct.zct_zplprops,
3252                     NV_UNIQUE_NAME, KM_SLEEP) == 0);
3253                 error = zfs_fill_zplprops(fsname, nvprops,
3254                     zct.zct_zplprops, &is_insensitive);
3255                 if (error != 0) {
3256                         nvlist_free(zct.zct_zplprops);
3257                         return (error);
3258                 }
3259         }
3260 
3261         error = dmu_objset_create(fsname, type,
3262             is_insensitive ? DS_FLAG_CI_DATASET : 0, cbfunc, &zct);
3263         nvlist_free(zct.zct_zplprops);
3264 
3265         /*
3266          * It would be nice to do this atomically.
3267          */
3268         if (error == 0) {
3269                 error = zfs_set_prop_nvlist(fsname, ZPROP_SRC_LOCAL,
3270                     nvprops, outnvl);
3271                 if (error != 0)
3272                         (void) dsl_destroy_head(fsname);
3273         }
3274         return (error);
3275 }
3276 
3277 /*
3278  * innvl: {
3279  *     "origin" -> name of origin snapshot
3280  *     (optional) "props" -> { prop -> value }
3281  * }
3282  *
3283  * outnvl: propname -> error code (int32)
3284  */
3285 static int
3286 zfs_ioc_clone(const char *fsname, nvlist_t *innvl, nvlist_t *outnvl)
3287 {
3288         int error = 0;
3289         nvlist_t *nvprops = NULL;
3290         char *origin_name;
3291 
3292         if (nvlist_lookup_string(innvl, "origin", &origin_name) != 0)
3293                 return (SET_ERROR(EINVAL));
3294         (void) nvlist_lookup_nvlist(innvl, "props", &nvprops);
3295 
3296         if (strchr(fsname, '@') ||
3297             strchr(fsname, '%'))
3298                 return (SET_ERROR(EINVAL));
3299 
3300         if (dataset_namecheck(origin_name, NULL, NULL) != 0)
3301                 return (SET_ERROR(EINVAL));
3302         error = dmu_objset_clone(fsname, origin_name);
3303         if (error != 0)
3304                 return (error);
3305 
3306         /*
3307          * It would be nice to do this atomically.
3308          */
3309         if (error == 0) {
3310                 error = zfs_set_prop_nvlist(fsname, ZPROP_SRC_LOCAL,
3311                     nvprops, outnvl);
3312                 if (error != 0)
3313                         (void) dsl_destroy_head(fsname);
3314         }
3315         return (error);
3316 }
3317 
3318 /* ARGSUSED */
3319 static int
3320 zfs_ioc_remap(const char *fsname, nvlist_t *innvl, nvlist_t *outnvl)
3321 {
3322         if (strchr(fsname, '@') ||
3323             strchr(fsname, '%'))
3324                 return (SET_ERROR(EINVAL));
3325 
3326         return (dmu_objset_remap_indirects(fsname));
3327 }
3328 
3329 /*
3330  * innvl: {
3331  *     "snaps" -> { snapshot1, snapshot2 }
3332  *     (optional) "props" -> { prop -> value (string) }
3333  * }
3334  *
3335  * outnvl: snapshot -> error code (int32)
3336  */
3337 static int
3338 zfs_ioc_snapshot(const char *poolname, nvlist_t *innvl, nvlist_t *outnvl)
3339 {
3340         nvlist_t *snaps;
3341         nvlist_t *props = NULL;
3342         int error, poollen;
3343         nvpair_t *pair;
3344 
3345         (void) nvlist_lookup_nvlist(innvl, "props", &props);
3346         if ((error = zfs_check_userprops(poolname, props)) != 0)
3347                 return (error);
3348 
3349         if (!nvlist_empty(props) &&
3350             zfs_earlier_version(poolname, SPA_VERSION_SNAP_PROPS))
3351                 return (SET_ERROR(ENOTSUP));
3352 
3353         if (nvlist_lookup_nvlist(innvl, "snaps", &snaps) != 0)
3354                 return (SET_ERROR(EINVAL));
3355         poollen = strlen(poolname);
3356         for (pair = nvlist_next_nvpair(snaps, NULL); pair != NULL;
3357             pair = nvlist_next_nvpair(snaps, pair)) {
3358                 const char *name = nvpair_name(pair);
3359                 const char *cp = strchr(name, '@');
3360 
3361                 /*
3362                  * The snap name must contain an @, and the part after it must
3363                  * contain only valid characters.
3364                  */
3365                 if (cp == NULL ||
3366                     zfs_component_namecheck(cp + 1, NULL, NULL) != 0)
3367                         return (SET_ERROR(EINVAL));
3368 
3369                 /*
3370                  * The snap must be in the specified pool.
3371                  */
3372                 if (strncmp(name, poolname, poollen) != 0 ||
3373                     (name[poollen] != '/' && name[poollen] != '@'))
3374                         return (SET_ERROR(EXDEV));
3375 
3376                 /* This must be the only snap of this fs. */
3377                 for (nvpair_t *pair2 = nvlist_next_nvpair(snaps, pair);
3378                     pair2 != NULL; pair2 = nvlist_next_nvpair(snaps, pair2)) {
3379                         if (strncmp(name, nvpair_name(pair2), cp - name + 1)
3380                             == 0) {
3381                                 return (SET_ERROR(EXDEV));
3382                         }
3383                 }
3384         }
3385 
3386         error = dsl_dataset_snapshot(snaps, props, outnvl);
3387         return (error);
3388 }
3389 
3390 /*
3391  * innvl: "message" -> string
3392  */
3393 /* ARGSUSED */
3394 static int
3395 zfs_ioc_log_history(const char *unused, nvlist_t *innvl, nvlist_t *outnvl)
3396 {
3397         char *message;
3398         spa_t *spa;
3399         int error;
3400         char *poolname;
3401 
3402         /*
3403          * The poolname in the ioctl is not set, we get it from the TSD,
3404          * which was set at the end of the last successful ioctl that allows
3405          * logging.  The secpolicy func already checked that it is set.
3406          * Only one log ioctl is allowed after each successful ioctl, so
3407          * we clear the TSD here.
3408          */
3409         poolname = tsd_get(zfs_allow_log_key);
3410         (void) tsd_set(zfs_allow_log_key, NULL);
3411         error = spa_open(poolname, &spa, FTAG);
3412         strfree(poolname);
3413         if (error != 0)
3414                 return (error);
3415 
3416         if (nvlist_lookup_string(innvl, "message", &message) != 0)  {
3417                 spa_close(spa, FTAG);
3418                 return (SET_ERROR(EINVAL));
3419         }
3420 
3421         if (spa_version(spa) < SPA_VERSION_ZPOOL_HISTORY) {
3422                 spa_close(spa, FTAG);
3423                 return (SET_ERROR(ENOTSUP));
3424         }
3425 
3426         error = spa_history_log(spa, message);
3427         spa_close(spa, FTAG);
3428         return (error);
3429 }
3430 
3431 /*
3432  * The dp_config_rwlock must not be held when calling this, because the
3433  * unmount may need to write out data.
3434  *
3435  * This function is best-effort.  Callers must deal gracefully if it
3436  * remains mounted (or is remounted after this call).
3437  *
3438  * Returns 0 if the argument is not a snapshot, or it is not currently a
3439  * filesystem, or we were able to unmount it.  Returns error code otherwise.
3440  */
3441 void
3442 zfs_unmount_snap(const char *snapname)
3443 {
3444         vfs_t *vfsp = NULL;
3445         zfsvfs_t *zfsvfs = NULL;
3446 
3447         if (strchr(snapname, '@') == NULL)
3448                 return;
3449 
3450         int err = getzfsvfs(snapname, &zfsvfs);
3451         if (err != 0) {
3452                 ASSERT3P(zfsvfs, ==, NULL);
3453                 return;
3454         }
3455         vfsp = zfsvfs->z_vfs;
3456 
3457         ASSERT(!dsl_pool_config_held(dmu_objset_pool(zfsvfs->z_os)));
3458 
3459         err = vn_vfswlock(vfsp->vfs_vnodecovered);
3460         VFS_RELE(vfsp);
3461         if (err != 0)
3462                 return;
3463 
3464         /*
3465          * Always force the unmount for snapshots.
3466          */
3467         (void) dounmount(vfsp, MS_FORCE, kcred);
3468 }
3469 
3470 /* ARGSUSED */
3471 static int
3472 zfs_unmount_snap_cb(const char *snapname, void *arg)
3473 {
3474         zfs_unmount_snap(snapname);
3475         return (0);
3476 }
3477 
3478 /*
3479  * When a clone is destroyed, its origin may also need to be destroyed,
3480  * in which case it must be unmounted.  This routine will do that unmount
3481  * if necessary.
3482  */
3483 void
3484 zfs_destroy_unmount_origin(const char *fsname)
3485 {
3486         int error;
3487         objset_t *os;
3488         dsl_dataset_t *ds;
3489 
3490         error = dmu_objset_hold(fsname, FTAG, &os);
3491         if (error != 0)
3492                 return;
3493         ds = dmu_objset_ds(os);
3494         if (dsl_dir_is_clone(ds->ds_dir) && DS_IS_DEFER_DESTROY(ds->ds_prev)) {
3495                 char originname[ZFS_MAX_DATASET_NAME_LEN];
3496                 dsl_dataset_name(ds->ds_prev, originname);
3497                 dmu_objset_rele(os, FTAG);
3498                 zfs_unmount_snap(originname);
3499         } else {
3500                 dmu_objset_rele(os, FTAG);
3501         }
3502 }
3503 
3504 /*
3505  * innvl: {
3506  *     "snaps" -> { snapshot1, snapshot2 }
3507  *     (optional boolean) "defer"
3508  * }
3509  *
3510  * outnvl: snapshot -> error code (int32)
3511  *
3512  */
3513 /* ARGSUSED */
3514 static int
3515 zfs_ioc_destroy_snaps(const char *poolname, nvlist_t *innvl, nvlist_t *outnvl)
3516 {
3517         nvlist_t *snaps;
3518         nvpair_t *pair;
3519         boolean_t defer;
3520 
3521         if (nvlist_lookup_nvlist(innvl, "snaps", &snaps) != 0)
3522                 return (SET_ERROR(EINVAL));
3523         defer = nvlist_exists(innvl, "defer");
3524 
3525         for (pair = nvlist_next_nvpair(snaps, NULL); pair != NULL;
3526             pair = nvlist_next_nvpair(snaps, pair)) {
3527                 zfs_unmount_snap(nvpair_name(pair));
3528         }
3529 
3530         return (dsl_destroy_snapshots_nvl(snaps, defer, outnvl));
3531 }
3532 
3533 /*
3534  * Create bookmarks.  Bookmark names are of the form <fs>#<bmark>.
3535  * All bookmarks must be in the same pool.
3536  *
3537  * innvl: {
3538  *     bookmark1 -> snapshot1, bookmark2 -> snapshot2
3539  * }
3540  *
3541  * outnvl: bookmark -> error code (int32)
3542  *
3543  */
3544 /* ARGSUSED */
3545 static int
3546 zfs_ioc_bookmark(const char *poolname, nvlist_t *innvl, nvlist_t *outnvl)
3547 {
3548         for (nvpair_t *pair = nvlist_next_nvpair(innvl, NULL);
3549             pair != NULL; pair = nvlist_next_nvpair(innvl, pair)) {
3550                 char *snap_name;
3551 
3552                 /*
3553                  * Verify the snapshot argument.
3554                  */
3555                 if (nvpair_value_string(pair, &snap_name) != 0)
3556                         return (SET_ERROR(EINVAL));
3557 
3558 
3559                 /* Verify that the keys (bookmarks) are unique */
3560                 for (nvpair_t *pair2 = nvlist_next_nvpair(innvl, pair);
3561                     pair2 != NULL; pair2 = nvlist_next_nvpair(innvl, pair2)) {
3562                         if (strcmp(nvpair_name(pair), nvpair_name(pair2)) == 0)
3563                                 return (SET_ERROR(EINVAL));
3564                 }
3565         }
3566 
3567         return (dsl_bookmark_create(innvl, outnvl));
3568 }
3569 
3570 /*
3571  * innvl: {
3572  *     property 1, property 2, ...
3573  * }
3574  *
3575  * outnvl: {
3576  *     bookmark name 1 -> { property 1, property 2, ... },
3577  *     bookmark name 2 -> { property 1, property 2, ... }
3578  * }
3579  *
3580  */
3581 static int
3582 zfs_ioc_get_bookmarks(const char *fsname, nvlist_t *innvl, nvlist_t *outnvl)
3583 {
3584         return (dsl_get_bookmarks(fsname, innvl, outnvl));
3585 }
3586 
3587 /*
3588  * innvl: {
3589  *     bookmark name 1, bookmark name 2
3590  * }
3591  *
3592  * outnvl: bookmark -> error code (int32)
3593  *
3594  */
3595 static int
3596 zfs_ioc_destroy_bookmarks(const char *poolname, nvlist_t *innvl,
3597     nvlist_t *outnvl)
3598 {
3599         int error, poollen;
3600 
3601         poollen = strlen(poolname);
3602         for (nvpair_t *pair = nvlist_next_nvpair(innvl, NULL);
3603             pair != NULL; pair = nvlist_next_nvpair(innvl, pair)) {
3604                 const char *name = nvpair_name(pair);
3605                 const char *cp = strchr(name, '#');
3606 
3607                 /*
3608                  * The bookmark name must contain an #, and the part after it
3609                  * must contain only valid characters.
3610                  */
3611                 if (cp == NULL ||
3612                     zfs_component_namecheck(cp + 1, NULL, NULL) != 0)
3613                         return (SET_ERROR(EINVAL));
3614 
3615                 /*
3616                  * The bookmark must be in the specified pool.
3617                  */
3618                 if (strncmp(name, poolname, poollen) != 0 ||
3619                     (name[poollen] != '/' && name[poollen] != '#'))
3620                         return (SET_ERROR(EXDEV));
3621         }
3622 
3623         error = dsl_bookmark_destroy(innvl, outnvl);
3624         return (error);
3625 }
3626 
3627 static int
3628 zfs_ioc_channel_program(const char *poolname, nvlist_t *innvl,
3629     nvlist_t *outnvl)
3630 {
3631         char *program;
3632         uint64_t instrlimit, memlimit;
3633         boolean_t sync_flag;
3634         nvpair_t *nvarg = NULL;
3635 
3636         if (0 != nvlist_lookup_string(innvl, ZCP_ARG_PROGRAM, &program)) {
3637                 return (EINVAL);
3638         }
3639         if (0 != nvlist_lookup_boolean_value(innvl, ZCP_ARG_SYNC, &sync_flag)) {
3640                 sync_flag = B_TRUE;
3641         }
3642         if (0 != nvlist_lookup_uint64(innvl, ZCP_ARG_INSTRLIMIT, &instrlimit)) {
3643                 instrlimit = ZCP_DEFAULT_INSTRLIMIT;
3644         }
3645         if (0 != nvlist_lookup_uint64(innvl, ZCP_ARG_MEMLIMIT, &memlimit)) {
3646                 memlimit = ZCP_DEFAULT_MEMLIMIT;
3647         }
3648         if (0 != nvlist_lookup_nvpair(innvl, ZCP_ARG_ARGLIST, &nvarg)) {
3649                 return (EINVAL);
3650         }
3651 
3652         if (instrlimit == 0 || instrlimit > zfs_lua_max_instrlimit)
3653                 return (EINVAL);
3654         if (memlimit == 0 || memlimit > zfs_lua_max_memlimit)
3655                 return (EINVAL);
3656 
3657         return (zcp_eval(poolname, program, sync_flag, instrlimit, memlimit,
3658             nvarg, outnvl));
3659 }
3660 
3661 /*
3662  * inputs:
3663  * zc_name              name of dataset to destroy
3664  * zc_objset_type       type of objset
3665  * zc_defer_destroy     mark for deferred destroy
3666  *
3667  * outputs:             none
3668  */
3669 static int
3670 zfs_ioc_destroy(zfs_cmd_t *zc)
3671 {
3672         int err;
3673 
3674         if (zc->zc_objset_type == DMU_OST_ZFS)
3675                 zfs_unmount_snap(zc->zc_name);
3676 
3677         if (strchr(zc->zc_name, '@'))
3678                 err = dsl_destroy_snapshot(zc->zc_name, zc->zc_defer_destroy);
3679         else
3680                 err = dsl_destroy_head(zc->zc_name);
3681         if (zc->zc_objset_type == DMU_OST_ZVOL && err == 0)
3682                 (void) zvol_remove_minor(zc->zc_name);
3683         return (err);
3684 }
3685 
3686 /*
3687  * fsname is name of dataset to rollback (to most recent snapshot)
3688  *
3689  * innvl may contain name of expected target snapshot
3690  *
3691  * outnvl: "target" -> name of most recent snapshot
3692  * }
3693  */
3694 /* ARGSUSED */
3695 static int
3696 zfs_ioc_rollback(const char *fsname, nvlist_t *innvl, nvlist_t *outnvl)
3697 {
3698         zfsvfs_t *zfsvfs;
3699         char *target = NULL;
3700         int error;
3701 
3702         (void) nvlist_lookup_string(innvl, "target", &target);
3703         if (target != NULL) {
3704                 const char *cp = strchr(target, '@');
3705 
3706                 /*
3707                  * The snap name must contain an @, and the part after it must
3708                  * contain only valid characters.
3709                  */
3710                 if (cp == NULL ||
3711                     zfs_component_namecheck(cp + 1, NULL, NULL) != 0)
3712                         return (SET_ERROR(EINVAL));
3713         }
3714 
3715         if (getzfsvfs(fsname, &zfsvfs) == 0) {
3716                 dsl_dataset_t *ds;
3717 
3718                 ds = dmu_objset_ds(zfsvfs->z_os);
3719                 error = zfs_suspend_fs(zfsvfs);
3720                 if (error == 0) {
3721                         int resume_err;
3722 
3723                         error = dsl_dataset_rollback(fsname, target, zfsvfs,
3724                             outnvl);
3725                         resume_err = zfs_resume_fs(zfsvfs, ds);
3726                         error = error ? error : resume_err;
3727                 }
3728                 VFS_RELE(zfsvfs->z_vfs);
3729         } else {
3730                 error = dsl_dataset_rollback(fsname, target, NULL, outnvl);
3731         }
3732         return (error);
3733 }
3734 
3735 static int
3736 recursive_unmount(const char *fsname, void *arg)
3737 {
3738         const char *snapname = arg;
3739         char fullname[ZFS_MAX_DATASET_NAME_LEN];
3740 
3741         (void) snprintf(fullname, sizeof (fullname), "%s@%s", fsname, snapname);
3742         zfs_unmount_snap(fullname);
3743 
3744         return (0);
3745 }
3746 
3747 /*
3748  * inputs:
3749  * zc_name      old name of dataset
3750  * zc_value     new name of dataset
3751  * zc_cookie    recursive flag (only valid for snapshots)
3752  *
3753  * outputs:     none
3754  */
3755 static int
3756 zfs_ioc_rename(zfs_cmd_t *zc)
3757 {
3758         boolean_t recursive = zc->zc_cookie & 1;
3759         char *at;
3760 
3761         /* "zfs rename" from and to ...%recv datasets should both fail */
3762         zc->zc_name[sizeof (zc->zc_name) - 1] = '\0';
3763         zc->zc_value[sizeof (zc->zc_value) - 1] = '\0';
3764         if (dataset_namecheck(zc->zc_name, NULL, NULL) != 0 ||
3765             dataset_namecheck(zc->zc_value, NULL, NULL) != 0 ||
3766             strchr(zc->zc_name, '%') || strchr(zc->zc_value, '%'))
3767                 return (SET_ERROR(EINVAL));
3768 
3769         at = strchr(zc->zc_name, '@');
3770         if (at != NULL) {
3771                 /* snaps must be in same fs */
3772                 int error;
3773 
3774                 if (strncmp(zc->zc_name, zc->zc_value, at - zc->zc_name + 1))
3775                         return (SET_ERROR(EXDEV));
3776                 *at = '\0';
3777                 if (zc->zc_objset_type == DMU_OST_ZFS) {
3778                         error = dmu_objset_find(zc->zc_name,
3779                             recursive_unmount, at + 1,
3780                             recursive ? DS_FIND_CHILDREN : 0);
3781                         if (error != 0) {
3782                                 *at = '@';
3783                                 return (error);
3784                         }
3785                 }
3786                 error = dsl_dataset_rename_snapshot(zc->zc_name,
3787                     at + 1, strchr(zc->zc_value, '@') + 1, recursive);
3788                 *at = '@';
3789 
3790                 return (error);
3791         } else {
3792                 if (zc->zc_objset_type == DMU_OST_ZVOL)
3793                         (void) zvol_remove_minor(zc->zc_name);
3794                 return (dsl_dir_rename(zc->zc_name, zc->zc_value));
3795         }
3796 }
3797 
3798 static int
3799 zfs_check_settable(const char *dsname, nvpair_t *pair, cred_t *cr)
3800 {
3801         const char *propname = nvpair_name(pair);
3802         boolean_t issnap = (strchr(dsname, '@') != NULL);
3803         zfs_prop_t prop = zfs_name_to_prop(propname);
3804         uint64_t intval;
3805         int err;
3806 
3807         if (prop == ZPROP_INVAL) {
3808                 if (zfs_prop_user(propname)) {
3809                         if (err = zfs_secpolicy_write_perms(dsname,
3810                             ZFS_DELEG_PERM_USERPROP, cr))
3811                                 return (err);
3812                         return (0);
3813                 }
3814 
3815                 if (!issnap && zfs_prop_userquota(propname)) {
3816                         const char *perm = NULL;
3817                         const char *uq_prefix =
3818                             zfs_userquota_prop_prefixes[ZFS_PROP_USERQUOTA];
3819                         const char *gq_prefix =
3820                             zfs_userquota_prop_prefixes[ZFS_PROP_GROUPQUOTA];
3821 
3822                         if (strncmp(propname, uq_prefix,
3823                             strlen(uq_prefix)) == 0) {
3824                                 perm = ZFS_DELEG_PERM_USERQUOTA;
3825                         } else if (strncmp(propname, gq_prefix,
3826                             strlen(gq_prefix)) == 0) {
3827                                 perm = ZFS_DELEG_PERM_GROUPQUOTA;
3828                         } else {
3829                                 /* USERUSED and GROUPUSED are read-only */
3830                                 return (SET_ERROR(EINVAL));
3831                         }
3832 
3833                         if (err = zfs_secpolicy_write_perms(dsname, perm, cr))
3834                                 return (err);
3835                         return (0);
3836                 }
3837 
3838                 return (SET_ERROR(EINVAL));
3839         }
3840 
3841         if (issnap)
3842                 return (SET_ERROR(EINVAL));
3843 
3844         if (nvpair_type(pair) == DATA_TYPE_NVLIST) {
3845                 /*
3846                  * dsl_prop_get_all_impl() returns properties in this
3847                  * format.
3848                  */
3849                 nvlist_t *attrs;
3850                 VERIFY(nvpair_value_nvlist(pair, &attrs) == 0);
3851                 VERIFY(nvlist_lookup_nvpair(attrs, ZPROP_VALUE,
3852                     &pair) == 0);
3853         }
3854 
3855         /*
3856          * Check that this value is valid for this pool version
3857          */
3858         switch (prop) {
3859         case ZFS_PROP_COMPRESSION:
3860                 /*
3861                  * If the user specified gzip compression, make sure
3862                  * the SPA supports it. We ignore any errors here since
3863                  * we'll catch them later.
3864                  */
3865                 if (nvpair_value_uint64(pair, &intval) == 0) {
3866                         if (intval >= ZIO_COMPRESS_GZIP_1 &&
3867                             intval <= ZIO_COMPRESS_GZIP_9 &&
3868                             zfs_earlier_version(dsname,
3869                             SPA_VERSION_GZIP_COMPRESSION)) {
3870                                 return (SET_ERROR(ENOTSUP));
3871                         }
3872 
3873                         if (intval == ZIO_COMPRESS_ZLE &&
3874                             zfs_earlier_version(dsname,
3875                             SPA_VERSION_ZLE_COMPRESSION))
3876                                 return (SET_ERROR(ENOTSUP));
3877 
3878                         if (intval == ZIO_COMPRESS_LZ4) {
3879                                 spa_t *spa;
3880 
3881                                 if ((err = spa_open(dsname, &spa, FTAG)) != 0)
3882                                         return (err);
3883 
3884                                 if (!spa_feature_is_enabled(spa,
3885                                     SPA_FEATURE_LZ4_COMPRESS)) {
3886                                         spa_close(spa, FTAG);
3887                                         return (SET_ERROR(ENOTSUP));
3888                                 }
3889                                 spa_close(spa, FTAG);
3890                         }
3891 
3892                         /*
3893                          * If this is a bootable dataset then
3894                          * verify that the compression algorithm
3895                          * is supported for booting. We must return
3896                          * something other than ENOTSUP since it
3897                          * implies a downrev pool version.
3898                          */
3899                         if (zfs_is_bootfs(dsname) &&
3900                             !BOOTFS_COMPRESS_VALID(intval)) {
3901                                 return (SET_ERROR(ERANGE));
3902                         }
3903                 }
3904                 break;
3905 
3906         case ZFS_PROP_COPIES:
3907                 if (zfs_earlier_version(dsname, SPA_VERSION_DITTO_BLOCKS))
3908                         return (SET_ERROR(ENOTSUP));
3909                 break;
3910 
3911         case ZFS_PROP_RECORDSIZE:
3912                 /* Record sizes above 128k need the feature to be enabled */
3913                 if (nvpair_value_uint64(pair, &intval) == 0 &&
3914                     intval > SPA_OLD_MAXBLOCKSIZE) {
3915                         spa_t *spa;
3916 
3917                         /*
3918                          * We don't allow setting the property above 1MB,
3919                          * unless the tunable has been changed.
3920                          */
3921                         if (intval > zfs_max_recordsize ||
3922                             intval > SPA_MAXBLOCKSIZE)
3923                                 return (SET_ERROR(ERANGE));
3924 
3925                         if ((err = spa_open(dsname, &spa, FTAG)) != 0)
3926                                 return (err);
3927 
3928                         if (!spa_feature_is_enabled(spa,
3929                             SPA_FEATURE_LARGE_BLOCKS)) {
3930                                 spa_close(spa, FTAG);
3931                                 return (SET_ERROR(ENOTSUP));
3932                         }
3933                         spa_close(spa, FTAG);
3934                 }
3935                 break;
3936 
3937         case ZFS_PROP_SHARESMB:
3938                 if (zpl_earlier_version(dsname, ZPL_VERSION_FUID))
3939                         return (SET_ERROR(ENOTSUP));
3940                 break;
3941 
3942         case ZFS_PROP_ACLINHERIT:
3943                 if (nvpair_type(pair) == DATA_TYPE_UINT64 &&
3944                     nvpair_value_uint64(pair, &intval) == 0) {
3945                         if (intval == ZFS_ACL_PASSTHROUGH_X &&
3946                             zfs_earlier_version(dsname,
3947                             SPA_VERSION_PASSTHROUGH_X))
3948                                 return (SET_ERROR(ENOTSUP));
3949                 }
3950                 break;
3951 
3952         case ZFS_PROP_CHECKSUM:
3953         case ZFS_PROP_DEDUP:
3954         {
3955                 spa_feature_t feature;
3956                 spa_t *spa;
3957 
3958                 /* dedup feature version checks */
3959                 if (prop == ZFS_PROP_DEDUP &&
3960                     zfs_earlier_version(dsname, SPA_VERSION_DEDUP))
3961                         return (SET_ERROR(ENOTSUP));
3962 
3963                 if (nvpair_value_uint64(pair, &intval) != 0)
3964                         return (SET_ERROR(EINVAL));
3965 
3966                 /* check prop value is enabled in features */
3967                 feature = zio_checksum_to_feature(intval & ZIO_CHECKSUM_MASK);
3968                 if (feature == SPA_FEATURE_NONE)
3969                         break;
3970 
3971                 if ((err = spa_open(dsname, &spa, FTAG)) != 0)
3972                         return (err);
3973                 /*
3974                  * Salted checksums are not supported on root pools.
3975                  */
3976                 if (spa_bootfs(spa) != 0 &&
3977                     intval < ZIO_CHECKSUM_FUNCTIONS &&
3978                     (zio_checksum_table[intval].ci_flags &
3979                     ZCHECKSUM_FLAG_SALTED)) {
3980                         spa_close(spa, FTAG);
3981                         return (SET_ERROR(ERANGE));
3982                 }
3983                 if (!spa_feature_is_enabled(spa, feature)) {
3984                         spa_close(spa, FTAG);
3985                         return (SET_ERROR(ENOTSUP));
3986                 }
3987                 spa_close(spa, FTAG);
3988                 break;
3989         }
3990         }
3991 
3992         return (zfs_secpolicy_setprop(dsname, prop, pair, CRED()));
3993 }
3994 
3995 /*
3996  * Checks for a race condition to make sure we don't increment a feature flag
3997  * multiple times.
3998  */
3999 static int
4000 zfs_prop_activate_feature_check(void *arg, dmu_tx_t *tx)
4001 {
4002         spa_t *spa = dmu_tx_pool(tx)->dp_spa;
4003         spa_feature_t *featurep = arg;
4004 
4005         if (!spa_feature_is_active(spa, *featurep))
4006                 return (0);
4007         else
4008                 return (SET_ERROR(EBUSY));
4009 }
4010 
4011 /*
4012  * The callback invoked on feature activation in the sync task caused by
4013  * zfs_prop_activate_feature.
4014  */
4015 static void
4016 zfs_prop_activate_feature_sync(void *arg, dmu_tx_t *tx)
4017 {
4018         spa_t *spa = dmu_tx_pool(tx)->dp_spa;
4019         spa_feature_t *featurep = arg;
4020 
4021         spa_feature_incr(spa, *featurep, tx);
4022 }
4023 
4024 /*
4025  * Activates a feature on a pool in response to a property setting. This
4026  * creates a new sync task which modifies the pool to reflect the feature
4027  * as being active.
4028  */
4029 static int
4030 zfs_prop_activate_feature(spa_t *spa, spa_feature_t feature)
4031 {
4032         int err;
4033 
4034         /* EBUSY here indicates that the feature is already active */
4035         err = dsl_sync_task(spa_name(spa),
4036             zfs_prop_activate_feature_check, zfs_prop_activate_feature_sync,
4037             &feature, 2, ZFS_SPACE_CHECK_RESERVED);
4038 
4039         if (err != 0 && err != EBUSY)
4040                 return (err);
4041         else
4042                 return (0);
4043 }
4044 
4045 /*
4046  * Removes properties from the given props list that fail permission checks
4047  * needed to clear them and to restore them in case of a receive error. For each
4048  * property, make sure we have both set and inherit permissions.
4049  *
4050  * Returns the first error encountered if any permission checks fail. If the
4051  * caller provides a non-NULL errlist, it also gives the complete list of names
4052  * of all the properties that failed a permission check along with the
4053  * corresponding error numbers. The caller is responsible for freeing the
4054  * returned errlist.
4055  *
4056  * If every property checks out successfully, zero is returned and the list
4057  * pointed at by errlist is NULL.
4058  */
4059 static int
4060 zfs_check_clearable(char *dataset, nvlist_t *props, nvlist_t **errlist)
4061 {
4062         zfs_cmd_t *zc;
4063         nvpair_t *pair, *next_pair;
4064         nvlist_t *errors;
4065         int err, rv = 0;
4066 
4067         if (props == NULL)
4068                 return (0);
4069 
4070         VERIFY(nvlist_alloc(&errors, NV_UNIQUE_NAME, KM_SLEEP) == 0);
4071 
4072         zc = kmem_alloc(sizeof (zfs_cmd_t), KM_SLEEP);
4073         (void) strcpy(zc->zc_name, dataset);
4074         pair = nvlist_next_nvpair(props, NULL);
4075         while (pair != NULL) {
4076                 next_pair = nvlist_next_nvpair(props, pair);
4077 
4078                 (void) strcpy(zc->zc_value, nvpair_name(pair));
4079                 if ((err = zfs_check_settable(dataset, pair, CRED())) != 0 ||
4080                     (err = zfs_secpolicy_inherit_prop(zc, NULL, CRED())) != 0) {
4081                         VERIFY(nvlist_remove_nvpair(props, pair) == 0);
4082                         VERIFY(nvlist_add_int32(errors,
4083                             zc->zc_value, err) == 0);
4084                 }
4085                 pair = next_pair;
4086         }
4087         kmem_free(zc, sizeof (zfs_cmd_t));
4088 
4089         if ((pair = nvlist_next_nvpair(errors, NULL)) == NULL) {
4090                 nvlist_free(errors);
4091                 errors = NULL;
4092         } else {
4093                 VERIFY(nvpair_value_int32(pair, &rv) == 0);
4094         }
4095 
4096         if (errlist == NULL)
4097                 nvlist_free(errors);
4098         else
4099                 *errlist = errors;
4100 
4101         return (rv);
4102 }
4103 
4104 static boolean_t
4105 propval_equals(nvpair_t *p1, nvpair_t *p2)
4106 {
4107         if (nvpair_type(p1) == DATA_TYPE_NVLIST) {
4108                 /* dsl_prop_get_all_impl() format */
4109                 nvlist_t *attrs;
4110                 VERIFY(nvpair_value_nvlist(p1, &attrs) == 0);
4111                 VERIFY(nvlist_lookup_nvpair(attrs, ZPROP_VALUE,
4112                     &p1) == 0);
4113         }
4114 
4115         if (nvpair_type(p2) == DATA_TYPE_NVLIST) {
4116                 nvlist_t *attrs;
4117                 VERIFY(nvpair_value_nvlist(p2, &attrs) == 0);
4118                 VERIFY(nvlist_lookup_nvpair(attrs, ZPROP_VALUE,
4119                     &p2) == 0);
4120         }
4121 
4122         if (nvpair_type(p1) != nvpair_type(p2))
4123                 return (B_FALSE);
4124 
4125         if (nvpair_type(p1) == DATA_TYPE_STRING) {
4126                 char *valstr1, *valstr2;
4127 
4128                 VERIFY(nvpair_value_string(p1, (char **)&valstr1) == 0);
4129                 VERIFY(nvpair_value_string(p2, (char **)&valstr2) == 0);
4130                 return (strcmp(valstr1, valstr2) == 0);
4131         } else {
4132                 uint64_t intval1, intval2;
4133 
4134                 VERIFY(nvpair_value_uint64(p1, &intval1) == 0);
4135                 VERIFY(nvpair_value_uint64(p2, &intval2) == 0);
4136                 return (intval1 == intval2);
4137         }
4138 }
4139 
4140 /*
4141  * Remove properties from props if they are not going to change (as determined
4142  * by comparison with origprops). Remove them from origprops as well, since we
4143  * do not need to clear or restore properties that won't change.
4144  */
4145 static void
4146 props_reduce(nvlist_t *props, nvlist_t *origprops)
4147 {
4148         nvpair_t *pair, *next_pair;
4149 
4150         if (origprops == NULL)
4151                 return; /* all props need to be received */
4152 
4153         pair = nvlist_next_nvpair(props, NULL);
4154         while (pair != NULL) {
4155                 const char *propname = nvpair_name(pair);
4156                 nvpair_t *match;
4157 
4158                 next_pair = nvlist_next_nvpair(props, pair);
4159 
4160                 if ((nvlist_lookup_nvpair(origprops, propname,
4161                     &match) != 0) || !propval_equals(pair, match))
4162                         goto next; /* need to set received value */
4163 
4164                 /* don't clear the existing received value */
4165                 (void) nvlist_remove_nvpair(origprops, match);
4166                 /* don't bother receiving the property */
4167                 (void) nvlist_remove_nvpair(props, pair);
4168 next:
4169                 pair = next_pair;
4170         }
4171 }
4172 
4173 /*
4174  * Extract properties that cannot be set PRIOR to the receipt of a dataset.
4175  * For example, refquota cannot be set until after the receipt of a dataset,
4176  * because in replication streams, an older/earlier snapshot may exceed the
4177  * refquota.  We want to receive the older/earlier snapshot, but setting
4178  * refquota pre-receipt will set the dsl's ACTUAL quota, which will prevent
4179  * the older/earlier snapshot from being received (with EDQUOT).
4180  *
4181  * The ZFS test "zfs_receive_011_pos" demonstrates such a scenario.
4182  *
4183  * libzfs will need to be judicious handling errors encountered by props
4184  * extracted by this function.
4185  */
4186 static nvlist_t *
4187 extract_delay_props(nvlist_t *props)
4188 {
4189         nvlist_t *delayprops;
4190         nvpair_t *nvp, *tmp;
4191         static const zfs_prop_t delayable[] = { ZFS_PROP_REFQUOTA, 0 };
4192         int i;
4193 
4194         VERIFY(nvlist_alloc(&delayprops, NV_UNIQUE_NAME, KM_SLEEP) == 0);
4195 
4196         for (nvp = nvlist_next_nvpair(props, NULL); nvp != NULL;
4197             nvp = nvlist_next_nvpair(props, nvp)) {
4198                 /*
4199                  * strcmp() is safe because zfs_prop_to_name() always returns
4200                  * a bounded string.
4201                  */
4202                 for (i = 0; delayable[i] != 0; i++) {
4203                         if (strcmp(zfs_prop_to_name(delayable[i]),
4204                             nvpair_name(nvp)) == 0) {
4205                                 break;
4206                         }
4207                 }
4208                 if (delayable[i] != 0) {
4209                         tmp = nvlist_prev_nvpair(props, nvp);
4210                         VERIFY(nvlist_add_nvpair(delayprops, nvp) == 0);
4211                         VERIFY(nvlist_remove_nvpair(props, nvp) == 0);
4212                         nvp = tmp;
4213                 }
4214         }
4215 
4216         if (nvlist_empty(delayprops)) {
4217                 nvlist_free(delayprops);
4218                 delayprops = NULL;
4219         }
4220         return (delayprops);
4221 }
4222 
4223 #ifdef  DEBUG
4224 static boolean_t zfs_ioc_recv_inject_err;
4225 #endif
4226 
4227 /*
4228  * inputs:
4229  * zc_name              name of containing filesystem
4230  * zc_nvlist_src{_size} nvlist of properties to apply
4231  * zc_value             name of snapshot to create
4232  * zc_string            name of clone origin (if DRR_FLAG_CLONE)
4233  * zc_cookie            file descriptor to recv from
4234  * zc_begin_record      the BEGIN record of the stream (not byteswapped)
4235  * zc_guid              force flag
4236  * zc_cleanup_fd        cleanup-on-exit file descriptor
4237  * zc_action_handle     handle for this guid/ds mapping (or zero on first call)
4238  * zc_resumable         if data is incomplete assume sender will resume
4239  *
4240  * outputs:
4241  * zc_cookie            number of bytes read
4242  * zc_nvlist_dst{_size} error for each unapplied received property
4243  * zc_obj               zprop_errflags_t
4244  * zc_action_handle     handle for this guid/ds mapping
4245  */
4246 static int
4247 zfs_ioc_recv(zfs_cmd_t *zc)
4248 {
4249         file_t *fp;
4250         dmu_recv_cookie_t drc;
4251         boolean_t force = (boolean_t)zc->zc_guid;
4252         int fd;
4253         int error = 0;
4254         int props_error = 0;
4255         nvlist_t *errors;
4256         offset_t off;
4257         nvlist_t *props = NULL; /* sent properties */
4258         nvlist_t *origprops = NULL; /* existing properties */
4259         nvlist_t *delayprops = NULL; /* sent properties applied post-receive */
4260         char *origin = NULL;
4261         char *tosnap;
4262         char tofs[ZFS_MAX_DATASET_NAME_LEN];
4263         boolean_t first_recvd_props = B_FALSE;
4264 
4265         if (dataset_namecheck(zc->zc_value, NULL, NULL) != 0 ||
4266             strchr(zc->zc_value, '@') == NULL ||
4267             strchr(zc->zc_value, '%'))
4268                 return (SET_ERROR(EINVAL));
4269 
4270         (void) strcpy(tofs, zc->zc_value);
4271         tosnap = strchr(tofs, '@');
4272         *tosnap++ = '\0';
4273 
4274         if (zc->zc_nvlist_src != NULL &&
4275             (error = get_nvlist(zc->zc_nvlist_src, zc->zc_nvlist_src_size,
4276             zc->zc_iflags, &props)) != 0)
4277                 return (error);
4278 
4279         fd = zc->zc_cookie;
4280         fp = getf(fd);
4281         if (fp == NULL) {
4282                 nvlist_free(props);
4283                 return (SET_ERROR(EBADF));
4284         }
4285 
4286         errors = fnvlist_alloc();
4287 
4288         if (zc->zc_string[0])
4289                 origin = zc->zc_string;
4290 
4291         error = dmu_recv_begin(tofs, tosnap,
4292             &zc->zc_begin_record, force, zc->zc_resumable, origin, &drc);
4293         if (error != 0)
4294                 goto out;
4295 
4296         /*
4297          * Set properties before we receive the stream so that they are applied
4298          * to the new data. Note that we must call dmu_recv_stream() if
4299          * dmu_recv_begin() succeeds.
4300          */
4301         if (props != NULL && !drc.drc_newfs) {
4302                 if (spa_version(dsl_dataset_get_spa(drc.drc_ds)) >=
4303                     SPA_VERSION_RECVD_PROPS &&
4304                     !dsl_prop_get_hasrecvd(tofs))
4305                         first_recvd_props = B_TRUE;
4306 
4307                 /*
4308                  * If new received properties are supplied, they are to
4309                  * completely replace the existing received properties, so stash
4310                  * away the existing ones.
4311                  */
4312                 if (dsl_prop_get_received(tofs, &origprops) == 0) {
4313                         nvlist_t *errlist = NULL;
4314                         /*
4315                          * Don't bother writing a property if its value won't
4316                          * change (and avoid the unnecessary security checks).
4317                          *
4318                          * The first receive after SPA_VERSION_RECVD_PROPS is a
4319                          * special case where we blow away all local properties
4320                          * regardless.
4321                          */
4322                         if (!first_recvd_props)
4323                                 props_reduce(props, origprops);
4324                         if (zfs_check_clearable(tofs, origprops, &errlist) != 0)
4325                                 (void) nvlist_merge(errors, errlist, 0);
4326                         nvlist_free(errlist);
4327 
4328                         if (clear_received_props(tofs, origprops,
4329                             first_recvd_props ? NULL : props) != 0)
4330                                 zc->zc_obj |= ZPROP_ERR_NOCLEAR;
4331                 } else {
4332                         zc->zc_obj |= ZPROP_ERR_NOCLEAR;
4333                 }
4334         }
4335 
4336         if (props != NULL) {
4337                 props_error = dsl_prop_set_hasrecvd(tofs);
4338 
4339                 if (props_error == 0) {
4340                         delayprops = extract_delay_props(props);
4341                         (void) zfs_set_prop_nvlist(tofs, ZPROP_SRC_RECEIVED,
4342                             props, errors);
4343                 }
4344         }
4345 
4346         off = fp->f_offset;
4347         error = dmu_recv_stream(&drc, fp->f_vnode, &off, zc->zc_cleanup_fd,
4348             &zc->zc_action_handle);
4349 
4350         if (error == 0) {
4351                 zfsvfs_t *zfsvfs = NULL;
4352 
4353                 if (getzfsvfs(tofs, &zfsvfs) == 0) {
4354                         /* online recv */
4355                         dsl_dataset_t *ds;
4356                         int end_err;
4357 
4358                         ds = dmu_objset_ds(zfsvfs->z_os);
4359                         error = zfs_suspend_fs(zfsvfs);
4360                         /*
4361                          * If the suspend fails, then the recv_end will
4362                          * likely also fail, and clean up after itself.
4363                          */
4364                         end_err = dmu_recv_end(&drc, zfsvfs);
4365                         if (error == 0)
4366                                 error = zfs_resume_fs(zfsvfs, ds);
4367                         error = error ? error : end_err;
4368                         VFS_RELE(zfsvfs->z_vfs);
4369                 } else {
4370                         error = dmu_recv_end(&drc, NULL);
4371                 }
4372 
4373                 /* Set delayed properties now, after we're done receiving. */
4374                 if (delayprops != NULL && error == 0) {
4375                         (void) zfs_set_prop_nvlist(tofs, ZPROP_SRC_RECEIVED,
4376                             delayprops, errors);
4377                 }
4378         }
4379 
4380         if (delayprops != NULL) {
4381                 /*
4382                  * Merge delayed props back in with initial props, in case
4383                  * we're DEBUG and zfs_ioc_recv_inject_err is set (which means
4384                  * we have to make sure clear_received_props() includes
4385                  * the delayed properties).
4386                  *
4387                  * Since zfs_ioc_recv_inject_err is only in DEBUG kernels,
4388                  * using ASSERT() will be just like a VERIFY.
4389                  */
4390                 ASSERT(nvlist_merge(props, delayprops, 0) == 0);
4391                 nvlist_free(delayprops);
4392         }
4393 
4394         /*
4395          * Now that all props, initial and delayed, are set, report the prop
4396          * errors to the caller.
4397          */
4398         if (zc->zc_nvlist_dst_size != 0 &&
4399             (nvlist_smush(errors, zc->zc_nvlist_dst_size) != 0 ||
4400             put_nvlist(zc, errors) != 0)) {
4401                 /*
4402                  * Caller made zc->zc_nvlist_dst less than the minimum expected
4403                  * size or supplied an invalid address.
4404                  */
4405                 props_error = SET_ERROR(EINVAL);
4406         }
4407 
4408         zc->zc_cookie = off - fp->f_offset;
4409         if (VOP_SEEK(fp->f_vnode, fp->f_offset, &off, NULL) == 0)
4410                 fp->f_offset = off;
4411 
4412 #ifdef  DEBUG
4413         if (zfs_ioc_recv_inject_err) {
4414                 zfs_ioc_recv_inject_err = B_FALSE;
4415                 error = 1;
4416         }
4417 #endif
4418         /*
4419          * On error, restore the original props.
4420          */
4421         if (error != 0 && props != NULL && !drc.drc_newfs) {
4422                 if (clear_received_props(tofs, props, NULL) != 0) {
4423                         /*
4424                          * We failed to clear the received properties.
4425                          * Since we may have left a $recvd value on the
4426                          * system, we can't clear the $hasrecvd flag.
4427                          */
4428                         zc->zc_obj |= ZPROP_ERR_NORESTORE;
4429                 } else if (first_recvd_props) {
4430                         dsl_prop_unset_hasrecvd(tofs);
4431                 }
4432 
4433                 if (origprops == NULL && !drc.drc_newfs) {
4434                         /* We failed to stash the original properties. */
4435                         zc->zc_obj |= ZPROP_ERR_NORESTORE;
4436                 }
4437 
4438                 /*
4439                  * dsl_props_set() will not convert RECEIVED to LOCAL on or
4440                  * after SPA_VERSION_RECVD_PROPS, so we need to specify LOCAL
4441                  * explictly if we're restoring local properties cleared in the
4442                  * first new-style receive.
4443                  */
4444                 if (origprops != NULL &&
4445                     zfs_set_prop_nvlist(tofs, (first_recvd_props ?
4446                     ZPROP_SRC_LOCAL : ZPROP_SRC_RECEIVED),
4447                     origprops, NULL) != 0) {
4448                         /*
4449                          * We stashed the original properties but failed to
4450                          * restore them.
4451                          */
4452                         zc->zc_obj |= ZPROP_ERR_NORESTORE;
4453                 }
4454         }
4455 out:
4456         nvlist_free(props);
4457         nvlist_free(origprops);
4458         nvlist_free(errors);
4459         releasef(fd);
4460 
4461         if (error == 0)
4462                 error = props_error;
4463 
4464         return (error);
4465 }
4466 
4467 /*
4468  * inputs:
4469  * zc_name      name of snapshot to send
4470  * zc_cookie    file descriptor to send stream to
4471  * zc_obj       fromorigin flag (mutually exclusive with zc_fromobj)
4472  * zc_sendobj   objsetid of snapshot to send
4473  * zc_fromobj   objsetid of incremental fromsnap (may be zero)
4474  * zc_guid      if set, estimate size of stream only.  zc_cookie is ignored.
4475  *              output size in zc_objset_type.
4476  * zc_flags     lzc_send_flags
4477  *
4478  * outputs:
4479  * zc_objset_type       estimated size, if zc_guid is set
4480  */
4481 static int
4482 zfs_ioc_send(zfs_cmd_t *zc)
4483 {
4484         int error;
4485         offset_t off;
4486         boolean_t estimate = (zc->zc_guid != 0);
4487         boolean_t embedok = (zc->zc_flags & 0x1);
4488         boolean_t large_block_ok = (zc->zc_flags & 0x2);
4489         boolean_t compressok = (zc->zc_flags & 0x4);
4490 
4491         if (zc->zc_obj != 0) {
4492                 dsl_pool_t *dp;
4493                 dsl_dataset_t *tosnap;
4494 
4495                 error = dsl_pool_hold(zc->zc_name, FTAG, &dp);
4496                 if (error != 0)
4497                         return (error);
4498 
4499                 error = dsl_dataset_hold_obj(dp, zc->zc_sendobj, FTAG, &tosnap);
4500                 if (error != 0) {
4501                         dsl_pool_rele(dp, FTAG);
4502                         return (error);
4503                 }
4504 
4505                 if (dsl_dir_is_clone(tosnap->ds_dir))
4506                         zc->zc_fromobj =
4507                             dsl_dir_phys(tosnap->ds_dir)->dd_origin_obj;
4508                 dsl_dataset_rele(tosnap, FTAG);
4509                 dsl_pool_rele(dp, FTAG);
4510         }
4511 
4512         if (estimate) {
4513                 dsl_pool_t *dp;
4514                 dsl_dataset_t *tosnap;
4515                 dsl_dataset_t *fromsnap = NULL;
4516 
4517                 error = dsl_pool_hold(zc->zc_name, FTAG, &dp);
4518                 if (error != 0)
4519                         return (error);
4520 
4521                 error = dsl_dataset_hold_obj(dp, zc->zc_sendobj, FTAG, &tosnap);
4522                 if (error != 0) {
4523                         dsl_pool_rele(dp, FTAG);
4524                         return (error);
4525                 }
4526 
4527                 if (zc->zc_fromobj != 0) {
4528                         error = dsl_dataset_hold_obj(dp, zc->zc_fromobj,
4529                             FTAG, &fromsnap);
4530                         if (error != 0) {
4531                                 dsl_dataset_rele(tosnap, FTAG);
4532                                 dsl_pool_rele(dp, FTAG);
4533                                 return (error);
4534                         }
4535                 }
4536 
4537                 error = dmu_send_estimate(tosnap, fromsnap, compressok,
4538                     &zc->zc_objset_type);
4539 
4540                 if (fromsnap != NULL)
4541                         dsl_dataset_rele(fromsnap, FTAG);
4542                 dsl_dataset_rele(tosnap, FTAG);
4543                 dsl_pool_rele(dp, FTAG);
4544         } else {
4545                 file_t *fp = getf(zc->zc_cookie);
4546                 if (fp == NULL)
4547                         return (SET_ERROR(EBADF));
4548 
4549                 off = fp->f_offset;
4550                 error = dmu_send_obj(zc->zc_name, zc->zc_sendobj,
4551                     zc->zc_fromobj, embedok, large_block_ok, compressok,
4552                     zc->zc_cookie, fp->f_vnode, &off);
4553 
4554                 if (VOP_SEEK(fp->f_vnode, fp->f_offset, &off, NULL) == 0)
4555                         fp->f_offset = off;
4556                 releasef(zc->zc_cookie);
4557         }
4558         return (error);
4559 }
4560 
4561 /*
4562  * inputs:
4563  * zc_name      name of snapshot on which to report progress
4564  * zc_cookie    file descriptor of send stream
4565  *
4566  * outputs:
4567  * zc_cookie    number of bytes written in send stream thus far
4568  */
4569 static int
4570 zfs_ioc_send_progress(zfs_cmd_t *zc)
4571 {
4572         dsl_pool_t *dp;
4573         dsl_dataset_t *ds;
4574         dmu_sendarg_t *dsp = NULL;
4575         int error;
4576 
4577         error = dsl_pool_hold(zc->zc_name, FTAG, &dp);
4578         if (error != 0)
4579                 return (error);
4580 
4581         error = dsl_dataset_hold(dp, zc->zc_name, FTAG, &ds);
4582         if (error != 0) {
4583                 dsl_pool_rele(dp, FTAG);
4584                 return (error);
4585         }
4586 
4587         mutex_enter(&ds->ds_sendstream_lock);
4588 
4589         /*
4590          * Iterate over all the send streams currently active on this dataset.
4591          * If there's one which matches the specified file descriptor _and_ the
4592          * stream was started by the current process, return the progress of
4593          * that stream.
4594          */
4595         for (dsp = list_head(&ds->ds_sendstreams); dsp != NULL;
4596             dsp = list_next(&ds->ds_sendstreams, dsp)) {
4597                 if (dsp->dsa_outfd == zc->zc_cookie &&
4598                     dsp->dsa_proc == curproc)
4599                         break;
4600         }
4601 
4602         if (dsp != NULL)
4603                 zc->zc_cookie = *(dsp->dsa_off);
4604         else
4605                 error = SET_ERROR(ENOENT);
4606 
4607         mutex_exit(&ds->ds_sendstream_lock);
4608         dsl_dataset_rele(ds, FTAG);
4609         dsl_pool_rele(dp, FTAG);
4610         return (error);
4611 }
4612 
4613 static int
4614 zfs_ioc_inject_fault(zfs_cmd_t *zc)
4615 {
4616         int id, error;
4617 
4618         error = zio_inject_fault(zc->zc_name, (int)zc->zc_guid, &id,
4619             &zc->zc_inject_record);
4620 
4621         if (error == 0)
4622                 zc->zc_guid = (uint64_t)id;
4623 
4624         return (error);
4625 }
4626 
4627 static int
4628 zfs_ioc_clear_fault(zfs_cmd_t *zc)
4629 {
4630         return (zio_clear_fault((int)zc->zc_guid));
4631 }
4632 
4633 static int
4634 zfs_ioc_inject_list_next(zfs_cmd_t *zc)
4635 {
4636         int id = (int)zc->zc_guid;
4637         int error;
4638 
4639         error = zio_inject_list_next(&id, zc->zc_name, sizeof (zc->zc_name),
4640             &zc->zc_inject_record);
4641 
4642         zc->zc_guid = id;
4643 
4644         return (error);
4645 }
4646 
4647 static int
4648 zfs_ioc_error_log(zfs_cmd_t *zc)
4649 {
4650         spa_t *spa;
4651         int error;
4652         size_t count = (size_t)zc->zc_nvlist_dst_size;
4653 
4654         if ((error = spa_open(zc->zc_name, &spa, FTAG)) != 0)
4655                 return (error);
4656 
4657         error = spa_get_errlog(spa, (void *)(uintptr_t)zc->zc_nvlist_dst,
4658             &count);
4659         if (error == 0)
4660                 zc->zc_nvlist_dst_size = count;
4661         else
4662                 zc->zc_nvlist_dst_size = spa_get_errlog_size(spa);
4663 
4664         spa_close(spa, FTAG);
4665 
4666         return (error);
4667 }
4668 
4669 static int
4670 zfs_ioc_clear(zfs_cmd_t *zc)
4671 {
4672         spa_t *spa;
4673         vdev_t *vd;
4674         int error;
4675 
4676         /*
4677          * On zpool clear we also fix up missing slogs
4678          */
4679         mutex_enter(&spa_namespace_lock);
4680         spa = spa_lookup(zc->zc_name);
4681         if (spa == NULL) {
4682                 mutex_exit(&spa_namespace_lock);
4683                 return (SET_ERROR(EIO));
4684         }
4685         if (spa_get_log_state(spa) == SPA_LOG_MISSING) {
4686                 /* we need to let spa_open/spa_load clear the chains */
4687                 spa_set_log_state(spa, SPA_LOG_CLEAR);
4688         }
4689         spa->spa_last_open_failed = 0;
4690         mutex_exit(&spa_namespace_lock);
4691 
4692         if (zc->zc_cookie & ZPOOL_NO_REWIND) {
4693                 error = spa_open(zc->zc_name, &spa, FTAG);
4694         } else {
4695                 nvlist_t *policy;
4696                 nvlist_t *config = NULL;
4697 
4698                 if (zc->zc_nvlist_src == NULL)
4699                         return (SET_ERROR(EINVAL));
4700 
4701                 if ((error = get_nvlist(zc->zc_nvlist_src,
4702                     zc->zc_nvlist_src_size, zc->zc_iflags, &policy)) == 0) {
4703                         error = spa_open_rewind(zc->zc_name, &spa, FTAG,
4704                             policy, &config);
4705                         if (config != NULL) {
4706                                 int err;
4707 
4708                                 if ((err = put_nvlist(zc, config)) != 0)
4709                                         error = err;
4710                                 nvlist_free(config);
4711                         }
4712                         nvlist_free(policy);
4713                 }
4714         }
4715 
4716         if (error != 0)
4717                 return (error);
4718 
4719         spa_vdev_state_enter(spa, SCL_NONE);
4720 
4721         if (zc->zc_guid == 0) {
4722                 vd = NULL;
4723         } else {
4724                 vd = spa_lookup_by_guid(spa, zc->zc_guid, B_TRUE);
4725                 if (vd == NULL) {
4726                         (void) spa_vdev_state_exit(spa, NULL, ENODEV);
4727                         spa_close(spa, FTAG);
4728                         return (SET_ERROR(ENODEV));
4729                 }
4730         }
4731 
4732         vdev_clear(spa, vd);
4733 
4734         (void) spa_vdev_state_exit(spa, NULL, 0);
4735 
4736         /*
4737          * Resume any suspended I/Os.
4738          */
4739         if (zio_resume(spa) != 0)
4740                 error = SET_ERROR(EIO);
4741 
4742         spa_close(spa, FTAG);
4743 
4744         return (error);
4745 }
4746 
4747 static int
4748 zfs_ioc_pool_reopen(zfs_cmd_t *zc)
4749 {
4750         spa_t *spa;
4751         int error;
4752 
4753         error = spa_open(zc->zc_name, &spa, FTAG);
4754         if (error != 0)
4755                 return (error);
4756 
4757         spa_vdev_state_enter(spa, SCL_NONE);
4758 
4759         /*
4760          * If a resilver is already in progress then set the
4761          * spa_scrub_reopen flag to B_TRUE so that we don't restart
4762          * the scan as a side effect of the reopen. Otherwise, let
4763          * vdev_open() decided if a resilver is required.
4764          */
4765         spa->spa_scrub_reopen = dsl_scan_resilvering(spa->spa_dsl_pool);
4766         vdev_reopen(spa->spa_root_vdev);
4767         spa->spa_scrub_reopen = B_FALSE;
4768 
4769         (void) spa_vdev_state_exit(spa, NULL, 0);
4770         spa_close(spa, FTAG);
4771         return (0);
4772 }
4773 /*
4774  * inputs:
4775  * zc_name      name of filesystem
4776  *
4777  * outputs:
4778  * zc_string    name of conflicting snapshot, if there is one
4779  */
4780 static int
4781 zfs_ioc_promote(zfs_cmd_t *zc)
4782 {
4783         dsl_pool_t *dp;
4784         dsl_dataset_t *ds, *ods;
4785         char origin[ZFS_MAX_DATASET_NAME_LEN];
4786         char *cp;
4787         int error;
4788 
4789         zc->zc_name[sizeof (zc->zc_name) - 1] = '\0';
4790         if (dataset_namecheck(zc->zc_name, NULL, NULL) != 0 ||
4791             strchr(zc->zc_name, '%'))
4792                 return (SET_ERROR(EINVAL));
4793 
4794         error = dsl_pool_hold(zc->zc_name, FTAG, &dp);
4795         if (error != 0)
4796                 return (error);
4797 
4798         error = dsl_dataset_hold(dp, zc->zc_name, FTAG, &ds);
4799         if (error != 0) {
4800                 dsl_pool_rele(dp, FTAG);
4801                 return (error);
4802         }
4803 
4804         if (!dsl_dir_is_clone(ds->ds_dir)) {
4805                 dsl_dataset_rele(ds, FTAG);
4806                 dsl_pool_rele(dp, FTAG);
4807                 return (SET_ERROR(EINVAL));
4808         }
4809 
4810         error = dsl_dataset_hold_obj(dp,
4811             dsl_dir_phys(ds->ds_dir)->dd_origin_obj, FTAG, &ods);
4812         if (error != 0) {
4813                 dsl_dataset_rele(ds, FTAG);
4814                 dsl_pool_rele(dp, FTAG);
4815                 return (error);
4816         }
4817 
4818         dsl_dataset_name(ods, origin);
4819         dsl_dataset_rele(ods, FTAG);
4820         dsl_dataset_rele(ds, FTAG);
4821         dsl_pool_rele(dp, FTAG);
4822 
4823         /*
4824          * We don't need to unmount *all* the origin fs's snapshots, but
4825          * it's easier.
4826          */
4827         cp = strchr(origin, '@');
4828         if (cp)
4829                 *cp = '\0';
4830         (void) dmu_objset_find(origin,
4831             zfs_unmount_snap_cb, NULL, DS_FIND_SNAPSHOTS);
4832         return (dsl_dataset_promote(zc->zc_name, zc->zc_string));
4833 }
4834 
4835 /*
4836  * Retrieve a single {user|group}{used|quota}@... property.
4837  *
4838  * inputs:
4839  * zc_name      name of filesystem
4840  * zc_objset_type zfs_userquota_prop_t
4841  * zc_value     domain name (eg. "S-1-234-567-89")
4842  * zc_guid      RID/UID/GID
4843  *
4844  * outputs:
4845  * zc_cookie    property value
4846  */
4847 static int
4848 zfs_ioc_userspace_one(zfs_cmd_t *zc)
4849 {
4850         zfsvfs_t *zfsvfs;
4851         int error;
4852 
4853         if (zc->zc_objset_type >= ZFS_NUM_USERQUOTA_PROPS)
4854                 return (SET_ERROR(EINVAL));
4855 
4856         error = zfsvfs_hold(zc->zc_name, FTAG, &zfsvfs, B_FALSE);
4857         if (error != 0)
4858                 return (error);
4859 
4860         error = zfs_userspace_one(zfsvfs,
4861             zc->zc_objset_type, zc->zc_value, zc->zc_guid, &zc->zc_cookie);
4862         zfsvfs_rele(zfsvfs, FTAG);
4863 
4864         return (error);
4865 }
4866 
4867 /*
4868  * inputs:
4869  * zc_name              name of filesystem
4870  * zc_cookie            zap cursor
4871  * zc_objset_type       zfs_userquota_prop_t
4872  * zc_nvlist_dst[_size] buffer to fill (not really an nvlist)
4873  *
4874  * outputs:
4875  * zc_nvlist_dst[_size] data buffer (array of zfs_useracct_t)
4876  * zc_cookie    zap cursor
4877  */
4878 static int
4879 zfs_ioc_userspace_many(zfs_cmd_t *zc)
4880 {
4881         zfsvfs_t *zfsvfs;
4882         int bufsize = zc->zc_nvlist_dst_size;
4883 
4884         if (bufsize <= 0)
4885                 return (SET_ERROR(ENOMEM));
4886 
4887         int error = zfsvfs_hold(zc->zc_name, FTAG, &zfsvfs, B_FALSE);
4888         if (error != 0)
4889                 return (error);
4890 
4891         void *buf = kmem_alloc(bufsize, KM_SLEEP);
4892 
4893         error = zfs_userspace_many(zfsvfs, zc->zc_objset_type, &zc->zc_cookie,
4894             buf, &zc->zc_nvlist_dst_size);
4895 
4896         if (error == 0) {
4897                 error = xcopyout(buf,
4898                     (void *)(uintptr_t)zc->zc_nvlist_dst,
4899                     zc->zc_nvlist_dst_size);
4900         }
4901         kmem_free(buf, bufsize);
4902         zfsvfs_rele(zfsvfs, FTAG);
4903 
4904         return (error);
4905 }
4906 
4907 /*
4908  * inputs:
4909  * zc_name              name of filesystem
4910  *
4911  * outputs:
4912  * none
4913  */
4914 static int
4915 zfs_ioc_userspace_upgrade(zfs_cmd_t *zc)
4916 {
4917         objset_t *os;
4918         int error = 0;
4919         zfsvfs_t *zfsvfs;
4920 
4921         if (getzfsvfs(zc->zc_name, &zfsvfs) == 0) {
4922                 if (!dmu_objset_userused_enabled(zfsvfs->z_os)) {
4923                         /*
4924                          * If userused is not enabled, it may be because the
4925                          * objset needs to be closed & reopened (to grow the
4926                          * objset_phys_t).  Suspend/resume the fs will do that.
4927                          */
4928                         dsl_dataset_t *ds;
4929 
4930                         ds = dmu_objset_ds(zfsvfs->z_os);
4931                         error = zfs_suspend_fs(zfsvfs);
4932                         if (error == 0) {
4933                                 dmu_objset_refresh_ownership(zfsvfs->z_os,
4934                                     zfsvfs);
4935                                 error = zfs_resume_fs(zfsvfs, ds);
4936                         }
4937                 }
4938                 if (error == 0)
4939                         error = dmu_objset_userspace_upgrade(zfsvfs->z_os);
4940                 VFS_RELE(zfsvfs->z_vfs);
4941         } else {
4942                 /* XXX kind of reading contents without owning */
4943                 error = dmu_objset_hold(zc->zc_name, FTAG, &os);
4944                 if (error != 0)
4945                         return (error);
4946 
4947                 error = dmu_objset_userspace_upgrade(os);
4948                 dmu_objset_rele(os, FTAG);
4949         }
4950 
4951         return (error);
4952 }
4953 
4954 /*
4955  * We don't want to have a hard dependency
4956  * against some special symbols in sharefs
4957  * nfs, and smbsrv.  Determine them if needed when
4958  * the first file system is shared.
4959  * Neither sharefs, nfs or smbsrv are unloadable modules.
4960  */
4961 int (*znfsexport_fs)(void *arg);
4962 int (*zshare_fs)(enum sharefs_sys_op, share_t *, uint32_t);
4963 int (*zsmbexport_fs)(void *arg, boolean_t add_share);
4964 
4965 int zfs_nfsshare_inited;
4966 int zfs_smbshare_inited;
4967 
4968 ddi_modhandle_t nfs_mod;
4969 ddi_modhandle_t sharefs_mod;
4970 ddi_modhandle_t smbsrv_mod;
4971 kmutex_t zfs_share_lock;
4972 
4973 static int
4974 zfs_init_sharefs()
4975 {
4976         int error;
4977 
4978         ASSERT(MUTEX_HELD(&zfs_share_lock));
4979         /* Both NFS and SMB shares also require sharetab support. */
4980         if (sharefs_mod == NULL && ((sharefs_mod =
4981             ddi_modopen("fs/sharefs",
4982             KRTLD_MODE_FIRST, &error)) == NULL)) {
4983                 return (SET_ERROR(ENOSYS));
4984         }
4985         if (zshare_fs == NULL && ((zshare_fs =
4986             (int (*)(enum sharefs_sys_op, share_t *, uint32_t))
4987             ddi_modsym(sharefs_mod, "sharefs_impl", &error)) == NULL)) {
4988                 return (SET_ERROR(ENOSYS));
4989         }
4990         return (0);
4991 }
4992 
4993 static int
4994 zfs_ioc_share(zfs_cmd_t *zc)
4995 {
4996         int error;
4997         int opcode;
4998 
4999         switch (zc->zc_share.z_sharetype) {
5000         case ZFS_SHARE_NFS:
5001         case ZFS_UNSHARE_NFS:
5002                 if (zfs_nfsshare_inited == 0) {
5003                         mutex_enter(&zfs_share_lock);
5004                         if (nfs_mod == NULL && ((nfs_mod = ddi_modopen("fs/nfs",
5005                             KRTLD_MODE_FIRST, &error)) == NULL)) {
5006                                 mutex_exit(&zfs_share_lock);
5007                                 return (SET_ERROR(ENOSYS));
5008                         }
5009                         if (znfsexport_fs == NULL &&
5010                             ((znfsexport_fs = (int (*)(void *))
5011                             ddi_modsym(nfs_mod,
5012                             "nfs_export", &error)) == NULL)) {
5013                                 mutex_exit(&zfs_share_lock);
5014                                 return (SET_ERROR(ENOSYS));
5015                         }
5016                         error = zfs_init_sharefs();
5017                         if (error != 0) {
5018                                 mutex_exit(&zfs_share_lock);
5019                                 return (SET_ERROR(ENOSYS));
5020                         }
5021                         zfs_nfsshare_inited = 1;
5022                         mutex_exit(&zfs_share_lock);
5023                 }
5024                 break;
5025         case ZFS_SHARE_SMB:
5026         case ZFS_UNSHARE_SMB:
5027                 if (zfs_smbshare_inited == 0) {
5028                         mutex_enter(&zfs_share_lock);
5029                         if (smbsrv_mod == NULL && ((smbsrv_mod =
5030                             ddi_modopen("drv/smbsrv",
5031                             KRTLD_MODE_FIRST, &error)) == NULL)) {
5032                                 mutex_exit(&zfs_share_lock);
5033                                 return (SET_ERROR(ENOSYS));
5034                         }
5035                         if (zsmbexport_fs == NULL && ((zsmbexport_fs =
5036                             (int (*)(void *, boolean_t))ddi_modsym(smbsrv_mod,
5037                             "smb_server_share", &error)) == NULL)) {
5038                                 mutex_exit(&zfs_share_lock);
5039                                 return (SET_ERROR(ENOSYS));
5040                         }
5041                         error = zfs_init_sharefs();
5042                         if (error != 0) {
5043                                 mutex_exit(&zfs_share_lock);
5044                                 return (SET_ERROR(ENOSYS));
5045                         }
5046                         zfs_smbshare_inited = 1;
5047                         mutex_exit(&zfs_share_lock);
5048                 }
5049                 break;
5050         default:
5051                 return (SET_ERROR(EINVAL));
5052         }
5053 
5054         switch (zc->zc_share.z_sharetype) {
5055         case ZFS_SHARE_NFS:
5056         case ZFS_UNSHARE_NFS:
5057                 if (error =
5058                     znfsexport_fs((void *)
5059                     (uintptr_t)zc->zc_share.z_exportdata))
5060                         return (error);
5061                 break;
5062         case ZFS_SHARE_SMB:
5063         case ZFS_UNSHARE_SMB:
5064                 if (error = zsmbexport_fs((void *)
5065                     (uintptr_t)zc->zc_share.z_exportdata,
5066                     zc->zc_share.z_sharetype == ZFS_SHARE_SMB ?
5067                     B_TRUE: B_FALSE)) {
5068                         return (error);
5069                 }
5070                 break;
5071         }
5072 
5073         opcode = (zc->zc_share.z_sharetype == ZFS_SHARE_NFS ||
5074             zc->zc_share.z_sharetype == ZFS_SHARE_SMB) ?
5075             SHAREFS_ADD : SHAREFS_REMOVE;
5076 
5077         /*
5078          * Add or remove share from sharetab
5079          */
5080         error = zshare_fs(opcode,
5081             (void *)(uintptr_t)zc->zc_share.z_sharedata,
5082             zc->zc_share.z_sharemax);
5083 
5084         return (error);
5085 
5086 }
5087 
5088 ace_t full_access[] = {
5089         {(uid_t)-1, ACE_ALL_PERMS, ACE_EVERYONE, 0}
5090 };
5091 
5092 /*
5093  * inputs:
5094  * zc_name              name of containing filesystem
5095  * zc_obj               object # beyond which we want next in-use object #
5096  *
5097  * outputs:
5098  * zc_obj               next in-use object #
5099  */
5100 static int
5101 zfs_ioc_next_obj(zfs_cmd_t *zc)
5102 {
5103         objset_t *os = NULL;
5104         int error;
5105 
5106         error = dmu_objset_hold(zc->zc_name, FTAG, &os);
5107         if (error != 0)
5108                 return (error);
5109 
5110         error = dmu_object_next(os, &zc->zc_obj, B_FALSE,
5111             dsl_dataset_phys(os->os_dsl_dataset)->ds_prev_snap_txg);
5112 
5113         dmu_objset_rele(os, FTAG);
5114         return (error);
5115 }
5116 
5117 /*
5118  * inputs:
5119  * zc_name              name of filesystem
5120  * zc_value             prefix name for snapshot
5121  * zc_cleanup_fd        cleanup-on-exit file descriptor for calling process
5122  *
5123  * outputs:
5124  * zc_value             short name of new snapshot
5125  */
5126 static int
5127 zfs_ioc_tmp_snapshot(zfs_cmd_t *zc)
5128 {
5129         char *snap_name;
5130         char *hold_name;
5131         int error;
5132         minor_t minor;
5133 
5134         error = zfs_onexit_fd_hold(zc->zc_cleanup_fd, &minor);
5135         if (error != 0)
5136                 return (error);
5137 
5138         snap_name = kmem_asprintf("%s-%016llx", zc->zc_value,
5139             (u_longlong_t)ddi_get_lbolt64());
5140         hold_name = kmem_asprintf("%%%s", zc->zc_value);
5141 
5142         error = dsl_dataset_snapshot_tmp(zc->zc_name, snap_name, minor,
5143             hold_name);
5144         if (error == 0)
5145                 (void) strcpy(zc->zc_value, snap_name);
5146         strfree(snap_name);
5147         strfree(hold_name);
5148         zfs_onexit_fd_rele(zc->zc_cleanup_fd);
5149         return (error);
5150 }
5151 
5152 /*
5153  * inputs:
5154  * zc_name              name of "to" snapshot
5155  * zc_value             name of "from" snapshot
5156  * zc_cookie            file descriptor to write diff data on
5157  *
5158  * outputs:
5159  * dmu_diff_record_t's to the file descriptor
5160  */
5161 static int
5162 zfs_ioc_diff(zfs_cmd_t *zc)
5163 {
5164         file_t *fp;
5165         offset_t off;
5166         int error;
5167 
5168         fp = getf(zc->zc_cookie);
5169         if (fp == NULL)
5170                 return (SET_ERROR(EBADF));
5171 
5172         off = fp->f_offset;
5173 
5174         error = dmu_diff(zc->zc_name, zc->zc_value, fp->f_vnode, &off);
5175 
5176         if (VOP_SEEK(fp->f_vnode, fp->f_offset, &off, NULL) == 0)
5177                 fp->f_offset = off;
5178         releasef(zc->zc_cookie);
5179 
5180         return (error);
5181 }
5182 
5183 /*
5184  * Remove all ACL files in shares dir
5185  */
5186 static int
5187 zfs_smb_acl_purge(znode_t *dzp)
5188 {
5189         zap_cursor_t    zc;
5190         zap_attribute_t zap;
5191         zfsvfs_t *zfsvfs = dzp->z_zfsvfs;
5192         int error;
5193 
5194         for (zap_cursor_init(&zc, zfsvfs->z_os, dzp->z_id);
5195             (error = zap_cursor_retrieve(&zc, &zap)) == 0;
5196             zap_cursor_advance(&zc)) {
5197                 if ((error = VOP_REMOVE(ZTOV(dzp), zap.za_name, kcred,
5198                     NULL, 0)) != 0)
5199                         break;
5200         }
5201         zap_cursor_fini(&zc);
5202         return (error);
5203 }
5204 
5205 static int
5206 zfs_ioc_smb_acl(zfs_cmd_t *zc)
5207 {
5208         vnode_t *vp;
5209         znode_t *dzp;
5210         vnode_t *resourcevp = NULL;
5211         znode_t *sharedir;
5212         zfsvfs_t *zfsvfs;
5213         nvlist_t *nvlist;
5214         char *src, *target;
5215         vattr_t vattr;
5216         vsecattr_t vsec;
5217         int error = 0;
5218 
5219         if ((error = lookupname(zc->zc_value, UIO_SYSSPACE,
5220             NO_FOLLOW, NULL, &vp)) != 0)
5221                 return (error);
5222 
5223         /* Now make sure mntpnt and dataset are ZFS */
5224 
5225         if (vp->v_vfsp->vfs_fstype != zfsfstype ||
5226             (strcmp((char *)refstr_value(vp->v_vfsp->vfs_resource),
5227             zc->zc_name) != 0)) {
5228                 VN_RELE(vp);
5229                 return (SET_ERROR(EINVAL));
5230         }
5231 
5232         dzp = VTOZ(vp);
5233         zfsvfs = dzp->z_zfsvfs;
5234         ZFS_ENTER(zfsvfs);
5235 
5236         /*
5237          * Create share dir if its missing.
5238          */
5239         mutex_enter(&zfsvfs->z_lock);
5240         if (zfsvfs->z_shares_dir == 0) {
5241                 dmu_tx_t *tx;
5242 
5243                 tx = dmu_tx_create(zfsvfs->z_os);
5244                 dmu_tx_hold_zap(tx, MASTER_NODE_OBJ, TRUE,
5245                     ZFS_SHARES_DIR);
5246                 dmu_tx_hold_zap(tx, DMU_NEW_OBJECT, FALSE, NULL);
5247                 error = dmu_tx_assign(tx, TXG_WAIT);
5248                 if (error != 0) {
5249                         dmu_tx_abort(tx);
5250                 } else {
5251                         error = zfs_create_share_dir(zfsvfs, tx);
5252                         dmu_tx_commit(tx);
5253                 }
5254                 if (error != 0) {
5255                         mutex_exit(&zfsvfs->z_lock);
5256                         VN_RELE(vp);
5257                         ZFS_EXIT(zfsvfs);
5258                         return (error);
5259                 }
5260         }
5261         mutex_exit(&zfsvfs->z_lock);
5262 
5263         ASSERT(zfsvfs->z_shares_dir);
5264         if ((error = zfs_zget(zfsvfs, zfsvfs->z_shares_dir, &sharedir)) != 0) {
5265                 VN_RELE(vp);
5266                 ZFS_EXIT(zfsvfs);
5267                 return (error);
5268         }
5269 
5270         switch (zc->zc_cookie) {
5271         case ZFS_SMB_ACL_ADD:
5272                 vattr.va_mask = AT_MODE|AT_UID|AT_GID|AT_TYPE;
5273                 vattr.va_type = VREG;
5274                 vattr.va_mode = S_IFREG|0777;
5275                 vattr.va_uid = 0;
5276                 vattr.va_gid = 0;
5277 
5278                 vsec.vsa_mask = VSA_ACE;
5279                 vsec.vsa_aclentp = &full_access;
5280                 vsec.vsa_aclentsz = sizeof (full_access);
5281                 vsec.vsa_aclcnt = 1;
5282 
5283                 error = VOP_CREATE(ZTOV(sharedir), zc->zc_string,
5284                     &vattr, EXCL, 0, &resourcevp, kcred, 0, NULL, &vsec);
5285                 if (resourcevp)
5286                         VN_RELE(resourcevp);
5287                 break;
5288 
5289         case ZFS_SMB_ACL_REMOVE:
5290                 error = VOP_REMOVE(ZTOV(sharedir), zc->zc_string, kcred,
5291                     NULL, 0);
5292                 break;
5293 
5294         case ZFS_SMB_ACL_RENAME:
5295                 if ((error = get_nvlist(zc->zc_nvlist_src,
5296                     zc->zc_nvlist_src_size, zc->zc_iflags, &nvlist)) != 0) {
5297                         VN_RELE(vp);
5298                         VN_RELE(ZTOV(sharedir));
5299                         ZFS_EXIT(zfsvfs);
5300                         return (error);
5301                 }
5302                 if (nvlist_lookup_string(nvlist, ZFS_SMB_ACL_SRC, &src) ||
5303                     nvlist_lookup_string(nvlist, ZFS_SMB_ACL_TARGET,
5304                     &target)) {
5305                         VN_RELE(vp);
5306                         VN_RELE(ZTOV(sharedir));
5307                         ZFS_EXIT(zfsvfs);
5308                         nvlist_free(nvlist);
5309                         return (error);
5310                 }
5311                 error = VOP_RENAME(ZTOV(sharedir), src, ZTOV(sharedir), target,
5312                     kcred, NULL, 0);
5313                 nvlist_free(nvlist);
5314                 break;
5315 
5316         case ZFS_SMB_ACL_PURGE:
5317                 error = zfs_smb_acl_purge(sharedir);
5318                 break;
5319 
5320         default:
5321                 error = SET_ERROR(EINVAL);
5322                 break;
5323         }
5324 
5325         VN_RELE(vp);
5326         VN_RELE(ZTOV(sharedir));
5327 
5328         ZFS_EXIT(zfsvfs);
5329 
5330         return (error);
5331 }
5332 
5333 /*
5334  * innvl: {
5335  *     "holds" -> { snapname -> holdname (string), ... }
5336  *     (optional) "cleanup_fd" -> fd (int32)
5337  * }
5338  *
5339  * outnvl: {
5340  *     snapname -> error value (int32)
5341  *     ...
5342  * }
5343  */
5344 /* ARGSUSED */
5345 static int
5346 zfs_ioc_hold(const char *pool, nvlist_t *args, nvlist_t *errlist)
5347 {
5348         nvpair_t *pair;
5349         nvlist_t *holds;
5350         int cleanup_fd = -1;
5351         int error;
5352         minor_t minor = 0;
5353 
5354         error = nvlist_lookup_nvlist(args, "holds", &holds);
5355         if (error != 0)
5356                 return (SET_ERROR(EINVAL));
5357 
5358         /* make sure the user didn't pass us any invalid (empty) tags */
5359         for (pair = nvlist_next_nvpair(holds, NULL); pair != NULL;
5360             pair = nvlist_next_nvpair(holds, pair)) {
5361                 char *htag;
5362 
5363                 error = nvpair_value_string(pair, &htag);
5364                 if (error != 0)
5365                         return (SET_ERROR(error));
5366 
5367                 if (strlen(htag) == 0)
5368                         return (SET_ERROR(EINVAL));
5369         }
5370 
5371         if (nvlist_lookup_int32(args, "cleanup_fd", &cleanup_fd) == 0) {
5372                 error = zfs_onexit_fd_hold(cleanup_fd, &minor);
5373                 if (error != 0)
5374                         return (error);
5375         }
5376 
5377         error = dsl_dataset_user_hold(holds, minor, errlist);
5378         if (minor != 0)
5379                 zfs_onexit_fd_rele(cleanup_fd);
5380         return (error);
5381 }
5382 
5383 /*
5384  * innvl is not used.
5385  *
5386  * outnvl: {
5387  *    holdname -> time added (uint64 seconds since epoch)
5388  *    ...
5389  * }
5390  */
5391 /* ARGSUSED */
5392 static int
5393 zfs_ioc_get_holds(const char *snapname, nvlist_t *args, nvlist_t *outnvl)
5394 {
5395         return (dsl_dataset_get_holds(snapname, outnvl));
5396 }
5397 
5398 /*
5399  * innvl: {
5400  *     snapname -> { holdname, ... }
5401  *     ...
5402  * }
5403  *
5404  * outnvl: {
5405  *     snapname -> error value (int32)
5406  *     ...
5407  * }
5408  */
5409 /* ARGSUSED */
5410 static int
5411 zfs_ioc_release(const char *pool, nvlist_t *holds, nvlist_t *errlist)
5412 {
5413         return (dsl_dataset_user_release(holds, errlist));
5414 }
5415 
5416 /*
5417  * inputs:
5418  * zc_name              name of new filesystem or snapshot
5419  * zc_value             full name of old snapshot
5420  *
5421  * outputs:
5422  * zc_cookie            space in bytes
5423  * zc_objset_type       compressed space in bytes
5424  * zc_perm_action       uncompressed space in bytes
5425  */
5426 static int
5427 zfs_ioc_space_written(zfs_cmd_t *zc)
5428 {
5429         int error;
5430         dsl_pool_t *dp;
5431         dsl_dataset_t *new, *old;
5432 
5433         error = dsl_pool_hold(zc->zc_name, FTAG, &dp);
5434         if (error != 0)
5435                 return (error);
5436         error = dsl_dataset_hold(dp, zc->zc_name, FTAG, &new);
5437         if (error != 0) {
5438                 dsl_pool_rele(dp, FTAG);
5439                 return (error);
5440         }
5441         error = dsl_dataset_hold(dp, zc->zc_value, FTAG, &old);
5442         if (error != 0) {
5443                 dsl_dataset_rele(new, FTAG);
5444                 dsl_pool_rele(dp, FTAG);
5445                 return (error);
5446         }
5447 
5448         error = dsl_dataset_space_written(old, new, &zc->zc_cookie,
5449             &zc->zc_objset_type, &zc->zc_perm_action);
5450         dsl_dataset_rele(old, FTAG);
5451         dsl_dataset_rele(new, FTAG);
5452         dsl_pool_rele(dp, FTAG);
5453         return (error);
5454 }
5455 
5456 /*
5457  * innvl: {
5458  *     "firstsnap" -> snapshot name
5459  * }
5460  *
5461  * outnvl: {
5462  *     "used" -> space in bytes
5463  *     "compressed" -> compressed space in bytes
5464  *     "uncompressed" -> uncompressed space in bytes
5465  * }
5466  */
5467 static int
5468 zfs_ioc_space_snaps(const char *lastsnap, nvlist_t *innvl, nvlist_t *outnvl)
5469 {
5470         int error;
5471         dsl_pool_t *dp;
5472         dsl_dataset_t *new, *old;
5473         char *firstsnap;
5474         uint64_t used, comp, uncomp;
5475 
5476         if (nvlist_lookup_string(innvl, "firstsnap", &firstsnap) != 0)
5477                 return (SET_ERROR(EINVAL));
5478 
5479         error = dsl_pool_hold(lastsnap, FTAG, &dp);
5480         if (error != 0)
5481                 return (error);
5482 
5483         error = dsl_dataset_hold(dp, lastsnap, FTAG, &new);
5484         if (error == 0 && !new->ds_is_snapshot) {
5485                 dsl_dataset_rele(new, FTAG);
5486                 error = SET_ERROR(EINVAL);
5487         }
5488         if (error != 0) {
5489                 dsl_pool_rele(dp, FTAG);
5490                 return (error);
5491         }
5492         error = dsl_dataset_hold(dp, firstsnap, FTAG, &old);
5493         if (error == 0 && !old->ds_is_snapshot) {
5494                 dsl_dataset_rele(old, FTAG);
5495                 error = SET_ERROR(EINVAL);
5496         }
5497         if (error != 0) {
5498                 dsl_dataset_rele(new, FTAG);
5499                 dsl_pool_rele(dp, FTAG);
5500                 return (error);
5501         }
5502 
5503         error = dsl_dataset_space_wouldfree(old, new, &used, &comp, &uncomp);
5504         dsl_dataset_rele(old, FTAG);
5505         dsl_dataset_rele(new, FTAG);
5506         dsl_pool_rele(dp, FTAG);
5507         fnvlist_add_uint64(outnvl, "used", used);
5508         fnvlist_add_uint64(outnvl, "compressed", comp);
5509         fnvlist_add_uint64(outnvl, "uncompressed", uncomp);
5510         return (error);
5511 }
5512 
5513 /*
5514  * innvl: {
5515  *     "fd" -> file descriptor to write stream to (int32)
5516  *     (optional) "fromsnap" -> full snap name to send an incremental from
5517  *     (optional) "largeblockok" -> (value ignored)
5518  *         indicates that blocks > 128KB are permitted
5519  *     (optional) "embedok" -> (value ignored)
5520  *         presence indicates DRR_WRITE_EMBEDDED records are permitted
5521  *     (optional) "compressok" -> (value ignored)
5522  *         presence indicates compressed DRR_WRITE records are permitted
5523  *     (optional) "resume_object" and "resume_offset" -> (uint64)
5524  *         if present, resume send stream from specified object and offset.
5525  * }
5526  *
5527  * outnvl is unused
5528  */
5529 /* ARGSUSED */
5530 static int
5531 zfs_ioc_send_new(const char *snapname, nvlist_t *innvl, nvlist_t *outnvl)
5532 {
5533         int error;
5534         offset_t off;
5535         char *fromname = NULL;
5536         int fd;
5537         boolean_t largeblockok;
5538         boolean_t embedok;
5539         boolean_t compressok;
5540         uint64_t resumeobj = 0;
5541         uint64_t resumeoff = 0;
5542 
5543         error = nvlist_lookup_int32(innvl, "fd", &fd);
5544         if (error != 0)
5545                 return (SET_ERROR(EINVAL));
5546 
5547         (void) nvlist_lookup_string(innvl, "fromsnap", &fromname);
5548 
5549         largeblockok = nvlist_exists(innvl, "largeblockok");
5550         embedok = nvlist_exists(innvl, "embedok");
5551         compressok = nvlist_exists(innvl, "compressok");
5552 
5553         (void) nvlist_lookup_uint64(innvl, "resume_object", &resumeobj);
5554         (void) nvlist_lookup_uint64(innvl, "resume_offset", &resumeoff);
5555 
5556         file_t *fp = getf(fd);
5557         if (fp == NULL)
5558                 return (SET_ERROR(EBADF));
5559 
5560         off = fp->f_offset;
5561         error = dmu_send(snapname, fromname, embedok, largeblockok, compressok,
5562             fd, resumeobj, resumeoff, fp->f_vnode, &off);
5563 
5564         if (VOP_SEEK(fp->f_vnode, fp->f_offset, &off, NULL) == 0)
5565                 fp->f_offset = off;
5566         releasef(fd);
5567         return (error);
5568 }
5569 
5570 /*
5571  * Determine approximately how large a zfs send stream will be -- the number
5572  * of bytes that will be written to the fd supplied to zfs_ioc_send_new().
5573  *
5574  * innvl: {
5575  *     (optional) "from" -> full snap or bookmark name to send an incremental
5576  *                          from
5577  *     (optional) "largeblockok" -> (value ignored)
5578  *         indicates that blocks > 128KB are permitted
5579  *     (optional) "embedok" -> (value ignored)
5580  *         presence indicates DRR_WRITE_EMBEDDED records are permitted
5581  *     (optional) "compressok" -> (value ignored)
5582  *         presence indicates compressed DRR_WRITE records are permitted
5583  * }
5584  *
5585  * outnvl: {
5586  *     "space" -> bytes of space (uint64)
5587  * }
5588  */
5589 static int
5590 zfs_ioc_send_space(const char *snapname, nvlist_t *innvl, nvlist_t *outnvl)
5591 {
5592         dsl_pool_t *dp;
5593         dsl_dataset_t *tosnap;
5594         int error;
5595         char *fromname;
5596         boolean_t compressok;
5597         uint64_t space;
5598 
5599         error = dsl_pool_hold(snapname, FTAG, &dp);
5600         if (error != 0)
5601                 return (error);
5602 
5603         error = dsl_dataset_hold(dp, snapname, FTAG, &tosnap);
5604         if (error != 0) {
5605                 dsl_pool_rele(dp, FTAG);
5606                 return (error);
5607         }
5608 
5609         compressok = nvlist_exists(innvl, "compressok");
5610 
5611         error = nvlist_lookup_string(innvl, "from", &fromname);
5612         if (error == 0) {
5613                 if (strchr(fromname, '@') != NULL) {
5614                         /*
5615                          * If from is a snapshot, hold it and use the more
5616                          * efficient dmu_send_estimate to estimate send space
5617                          * size using deadlists.
5618                          */
5619                         dsl_dataset_t *fromsnap;
5620                         error = dsl_dataset_hold(dp, fromname, FTAG, &fromsnap);
5621                         if (error != 0)
5622                                 goto out;
5623                         error = dmu_send_estimate(tosnap, fromsnap, compressok,
5624                             &space);
5625                         dsl_dataset_rele(fromsnap, FTAG);
5626                 } else if (strchr(fromname, '#') != NULL) {
5627                         /*
5628                          * If from is a bookmark, fetch the creation TXG of the
5629                          * snapshot it was created from and use that to find
5630                          * blocks that were born after it.
5631                          */
5632                         zfs_bookmark_phys_t frombm;
5633 
5634                         error = dsl_bookmark_lookup(dp, fromname, tosnap,
5635                             &frombm);
5636                         if (error != 0)
5637                                 goto out;
5638                         error = dmu_send_estimate_from_txg(tosnap,
5639                             frombm.zbm_creation_txg, compressok, &space);
5640                 } else {
5641                         /*
5642                          * from is not properly formatted as a snapshot or
5643                          * bookmark
5644                          */
5645                         error = SET_ERROR(EINVAL);
5646                         goto out;
5647                 }
5648         } else {
5649                 /*
5650                  * If estimating the size of a full send, use dmu_send_estimate.
5651                  */
5652                 error = dmu_send_estimate(tosnap, NULL, compressok, &space);
5653         }
5654 
5655         fnvlist_add_uint64(outnvl, "space", space);
5656 
5657 out:
5658         dsl_dataset_rele(tosnap, FTAG);
5659         dsl_pool_rele(dp, FTAG);
5660         return (error);
5661 }
5662 
5663 static zfs_ioc_vec_t zfs_ioc_vec[ZFS_IOC_LAST - ZFS_IOC_FIRST];
5664 
5665 static void
5666 zfs_ioctl_register_legacy(zfs_ioc_t ioc, zfs_ioc_legacy_func_t *func,
5667     zfs_secpolicy_func_t *secpolicy, zfs_ioc_namecheck_t namecheck,
5668     boolean_t log_history, zfs_ioc_poolcheck_t pool_check)
5669 {
5670         zfs_ioc_vec_t *vec = &zfs_ioc_vec[ioc - ZFS_IOC_FIRST];
5671 
5672         ASSERT3U(ioc, >=, ZFS_IOC_FIRST);
5673         ASSERT3U(ioc, <, ZFS_IOC_LAST);
5674         ASSERT3P(vec->zvec_legacy_func, ==, NULL);
5675         ASSERT3P(vec->zvec_func, ==, NULL);
5676 
5677         vec->zvec_legacy_func = func;
5678         vec->zvec_secpolicy = secpolicy;
5679         vec->zvec_namecheck = namecheck;
5680         vec->zvec_allow_log = log_history;
5681         vec->zvec_pool_check = pool_check;
5682 }
5683 
5684 /*
5685  * See the block comment at the beginning of this file for details on
5686  * each argument to this function.
5687  */
5688 static void
5689 zfs_ioctl_register(const char *name, zfs_ioc_t ioc, zfs_ioc_func_t *func,
5690     zfs_secpolicy_func_t *secpolicy, zfs_ioc_namecheck_t namecheck,
5691     zfs_ioc_poolcheck_t pool_check, boolean_t smush_outnvlist,
5692     boolean_t allow_log)
5693 {
5694         zfs_ioc_vec_t *vec = &zfs_ioc_vec[ioc - ZFS_IOC_FIRST];
5695 
5696         ASSERT3U(ioc, >=, ZFS_IOC_FIRST);
5697         ASSERT3U(ioc, <, ZFS_IOC_LAST);
5698         ASSERT3P(vec->zvec_legacy_func, ==, NULL);
5699         ASSERT3P(vec->zvec_func, ==, NULL);
5700 
5701         /* if we are logging, the name must be valid */
5702         ASSERT(!allow_log || namecheck != NO_NAME);
5703 
5704         vec->zvec_name = name;
5705         vec->zvec_func = func;
5706         vec->zvec_secpolicy = secpolicy;
5707         vec->zvec_namecheck = namecheck;
5708         vec->zvec_pool_check = pool_check;
5709         vec->zvec_smush_outnvlist = smush_outnvlist;
5710         vec->zvec_allow_log = allow_log;
5711 }
5712 
5713 static void
5714 zfs_ioctl_register_pool(zfs_ioc_t ioc, zfs_ioc_legacy_func_t *func,
5715     zfs_secpolicy_func_t *secpolicy, boolean_t log_history,
5716     zfs_ioc_poolcheck_t pool_check)
5717 {
5718         zfs_ioctl_register_legacy(ioc, func, secpolicy,
5719             POOL_NAME, log_history, pool_check);
5720 }
5721 
5722 static void
5723 zfs_ioctl_register_dataset_nolog(zfs_ioc_t ioc, zfs_ioc_legacy_func_t *func,
5724     zfs_secpolicy_func_t *secpolicy, zfs_ioc_poolcheck_t pool_check)
5725 {
5726         zfs_ioctl_register_legacy(ioc, func, secpolicy,
5727             DATASET_NAME, B_FALSE, pool_check);
5728 }
5729 
5730 static void
5731 zfs_ioctl_register_pool_modify(zfs_ioc_t ioc, zfs_ioc_legacy_func_t *func)
5732 {
5733         zfs_ioctl_register_legacy(ioc, func, zfs_secpolicy_config,
5734             POOL_NAME, B_TRUE, POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY);
5735 }
5736 
5737 static void
5738 zfs_ioctl_register_pool_meta(zfs_ioc_t ioc, zfs_ioc_legacy_func_t *func,
5739     zfs_secpolicy_func_t *secpolicy)
5740 {
5741         zfs_ioctl_register_legacy(ioc, func, secpolicy,
5742             NO_NAME, B_FALSE, POOL_CHECK_NONE);
5743 }
5744 
5745 static void
5746 zfs_ioctl_register_dataset_read_secpolicy(zfs_ioc_t ioc,
5747     zfs_ioc_legacy_func_t *func, zfs_secpolicy_func_t *secpolicy)
5748 {
5749         zfs_ioctl_register_legacy(ioc, func, secpolicy,
5750             DATASET_NAME, B_FALSE, POOL_CHECK_SUSPENDED);
5751 }
5752 
5753 static void
5754 zfs_ioctl_register_dataset_read(zfs_ioc_t ioc, zfs_ioc_legacy_func_t *func)
5755 {
5756         zfs_ioctl_register_dataset_read_secpolicy(ioc, func,
5757             zfs_secpolicy_read);
5758 }
5759 
5760 static void
5761 zfs_ioctl_register_dataset_modify(zfs_ioc_t ioc, zfs_ioc_legacy_func_t *func,
5762     zfs_secpolicy_func_t *secpolicy)
5763 {
5764         zfs_ioctl_register_legacy(ioc, func, secpolicy,
5765             DATASET_NAME, B_TRUE, POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY);
5766 }
5767 
5768 static void
5769 zfs_ioctl_init(void)
5770 {
5771         zfs_ioctl_register("snapshot", ZFS_IOC_SNAPSHOT,
5772             zfs_ioc_snapshot, zfs_secpolicy_snapshot, POOL_NAME,
5773             POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY, B_TRUE, B_TRUE);
5774 
5775         zfs_ioctl_register("log_history", ZFS_IOC_LOG_HISTORY,
5776             zfs_ioc_log_history, zfs_secpolicy_log_history, NO_NAME,
5777             POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY, B_FALSE, B_FALSE);
5778 
5779         zfs_ioctl_register("space_snaps", ZFS_IOC_SPACE_SNAPS,
5780             zfs_ioc_space_snaps, zfs_secpolicy_read, DATASET_NAME,
5781             POOL_CHECK_SUSPENDED, B_FALSE, B_FALSE);
5782 
5783         zfs_ioctl_register("send", ZFS_IOC_SEND_NEW,
5784             zfs_ioc_send_new, zfs_secpolicy_send_new, DATASET_NAME,
5785             POOL_CHECK_SUSPENDED, B_FALSE, B_FALSE);
5786 
5787         zfs_ioctl_register("send_space", ZFS_IOC_SEND_SPACE,
5788             zfs_ioc_send_space, zfs_secpolicy_read, DATASET_NAME,
5789             POOL_CHECK_SUSPENDED, B_FALSE, B_FALSE);
5790 
5791         zfs_ioctl_register("create", ZFS_IOC_CREATE,
5792             zfs_ioc_create, zfs_secpolicy_create_clone, DATASET_NAME,
5793             POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY, B_TRUE, B_TRUE);
5794 
5795         zfs_ioctl_register("clone", ZFS_IOC_CLONE,
5796             zfs_ioc_clone, zfs_secpolicy_create_clone, DATASET_NAME,
5797             POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY, B_TRUE, B_TRUE);
5798 
5799         zfs_ioctl_register("remap", ZFS_IOC_REMAP,
5800             zfs_ioc_remap, zfs_secpolicy_remap, DATASET_NAME,
5801             POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY, B_FALSE, B_TRUE);
5802 
5803         zfs_ioctl_register("destroy_snaps", ZFS_IOC_DESTROY_SNAPS,
5804             zfs_ioc_destroy_snaps, zfs_secpolicy_destroy_snaps, POOL_NAME,
5805             POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY, B_TRUE, B_TRUE);
5806 
5807         zfs_ioctl_register("hold", ZFS_IOC_HOLD,
5808             zfs_ioc_hold, zfs_secpolicy_hold, POOL_NAME,
5809             POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY, B_TRUE, B_TRUE);
5810         zfs_ioctl_register("release", ZFS_IOC_RELEASE,
5811             zfs_ioc_release, zfs_secpolicy_release, POOL_NAME,
5812             POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY, B_TRUE, B_TRUE);
5813 
5814         zfs_ioctl_register("get_holds", ZFS_IOC_GET_HOLDS,
5815             zfs_ioc_get_holds, zfs_secpolicy_read, DATASET_NAME,
5816             POOL_CHECK_SUSPENDED, B_FALSE, B_FALSE);
5817 
5818         zfs_ioctl_register("rollback", ZFS_IOC_ROLLBACK,
5819             zfs_ioc_rollback, zfs_secpolicy_rollback, DATASET_NAME,
5820             POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY, B_FALSE, B_TRUE);
5821 
5822         zfs_ioctl_register("bookmark", ZFS_IOC_BOOKMARK,
5823             zfs_ioc_bookmark, zfs_secpolicy_bookmark, POOL_NAME,
5824             POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY, B_TRUE, B_TRUE);
5825 
5826         zfs_ioctl_register("get_bookmarks", ZFS_IOC_GET_BOOKMARKS,
5827             zfs_ioc_get_bookmarks, zfs_secpolicy_read, DATASET_NAME,
5828             POOL_CHECK_SUSPENDED, B_FALSE, B_FALSE);
5829 
5830         zfs_ioctl_register("destroy_bookmarks", ZFS_IOC_DESTROY_BOOKMARKS,
5831             zfs_ioc_destroy_bookmarks, zfs_secpolicy_destroy_bookmarks,
5832             POOL_NAME,
5833             POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY, B_TRUE, B_TRUE);
5834 
5835         zfs_ioctl_register("channel_program", ZFS_IOC_CHANNEL_PROGRAM,
5836             zfs_ioc_channel_program, zfs_secpolicy_config,
5837             POOL_NAME, POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY, B_TRUE,
5838             B_TRUE);
5839 
5840         /* IOCTLS that use the legacy function signature */
5841 
5842         zfs_ioctl_register_legacy(ZFS_IOC_POOL_FREEZE, zfs_ioc_pool_freeze,
5843             zfs_secpolicy_config, NO_NAME, B_FALSE, POOL_CHECK_READONLY);
5844 
5845         zfs_ioctl_register_pool(ZFS_IOC_POOL_CREATE, zfs_ioc_pool_create,
5846             zfs_secpolicy_config, B_TRUE, POOL_CHECK_NONE);
5847         zfs_ioctl_register_pool_modify(ZFS_IOC_POOL_SCAN,
5848             zfs_ioc_pool_scan);
5849         zfs_ioctl_register_pool_modify(ZFS_IOC_POOL_UPGRADE,
5850             zfs_ioc_pool_upgrade);
5851         zfs_ioctl_register_pool_modify(ZFS_IOC_VDEV_ADD,
5852             zfs_ioc_vdev_add);
5853         zfs_ioctl_register_pool_modify(ZFS_IOC_VDEV_REMOVE,
5854             zfs_ioc_vdev_remove);
5855         zfs_ioctl_register_pool_modify(ZFS_IOC_VDEV_SET_STATE,
5856             zfs_ioc_vdev_set_state);
5857         zfs_ioctl_register_pool_modify(ZFS_IOC_VDEV_ATTACH,
5858             zfs_ioc_vdev_attach);
5859         zfs_ioctl_register_pool_modify(ZFS_IOC_VDEV_DETACH,
5860             zfs_ioc_vdev_detach);
5861         zfs_ioctl_register_pool_modify(ZFS_IOC_VDEV_SETPATH,
5862             zfs_ioc_vdev_setpath);
5863         zfs_ioctl_register_pool_modify(ZFS_IOC_VDEV_SETFRU,
5864             zfs_ioc_vdev_setfru);
5865         zfs_ioctl_register_pool_modify(ZFS_IOC_POOL_SET_PROPS,
5866             zfs_ioc_pool_set_props);
5867         zfs_ioctl_register_pool_modify(ZFS_IOC_VDEV_SPLIT,
5868             zfs_ioc_vdev_split);
5869         zfs_ioctl_register_pool_modify(ZFS_IOC_POOL_REGUID,
5870             zfs_ioc_pool_reguid);
5871 
5872         zfs_ioctl_register_pool_meta(ZFS_IOC_POOL_CONFIGS,
5873             zfs_ioc_pool_configs, zfs_secpolicy_none);
5874         zfs_ioctl_register_pool_meta(ZFS_IOC_POOL_TRYIMPORT,
5875             zfs_ioc_pool_tryimport, zfs_secpolicy_config);
5876         zfs_ioctl_register_pool_meta(ZFS_IOC_INJECT_FAULT,
5877             zfs_ioc_inject_fault, zfs_secpolicy_inject);
5878         zfs_ioctl_register_pool_meta(ZFS_IOC_CLEAR_FAULT,
5879             zfs_ioc_clear_fault, zfs_secpolicy_inject);
5880         zfs_ioctl_register_pool_meta(ZFS_IOC_INJECT_LIST_NEXT,
5881             zfs_ioc_inject_list_next, zfs_secpolicy_inject);
5882 
5883         /*
5884          * pool destroy, and export don't log the history as part of
5885          * zfsdev_ioctl, but rather zfs_ioc_pool_export
5886          * does the logging of those commands.
5887          */
5888         zfs_ioctl_register_pool(ZFS_IOC_POOL_DESTROY, zfs_ioc_pool_destroy,
5889             zfs_secpolicy_config, B_FALSE, POOL_CHECK_NONE);
5890         zfs_ioctl_register_pool(ZFS_IOC_POOL_EXPORT, zfs_ioc_pool_export,
5891             zfs_secpolicy_config, B_FALSE, POOL_CHECK_NONE);
5892 
5893         zfs_ioctl_register_pool(ZFS_IOC_POOL_STATS, zfs_ioc_pool_stats,
5894             zfs_secpolicy_read, B_FALSE, POOL_CHECK_NONE);
5895         zfs_ioctl_register_pool(ZFS_IOC_POOL_GET_PROPS, zfs_ioc_pool_get_props,
5896             zfs_secpolicy_read, B_FALSE, POOL_CHECK_NONE);
5897 
5898         zfs_ioctl_register_pool(ZFS_IOC_ERROR_LOG, zfs_ioc_error_log,
5899             zfs_secpolicy_inject, B_FALSE, POOL_CHECK_SUSPENDED);
5900         zfs_ioctl_register_pool(ZFS_IOC_DSOBJ_TO_DSNAME,
5901             zfs_ioc_dsobj_to_dsname,
5902             zfs_secpolicy_diff, B_FALSE, POOL_CHECK_SUSPENDED);
5903         zfs_ioctl_register_pool(ZFS_IOC_POOL_GET_HISTORY,
5904             zfs_ioc_pool_get_history,
5905             zfs_secpolicy_config, B_FALSE, POOL_CHECK_SUSPENDED);
5906 
5907         zfs_ioctl_register_pool(ZFS_IOC_POOL_IMPORT, zfs_ioc_pool_import,
5908             zfs_secpolicy_config, B_TRUE, POOL_CHECK_NONE);
5909 
5910         zfs_ioctl_register_pool(ZFS_IOC_CLEAR, zfs_ioc_clear,
5911             zfs_secpolicy_config, B_TRUE, POOL_CHECK_READONLY);
5912         zfs_ioctl_register_pool(ZFS_IOC_POOL_REOPEN, zfs_ioc_pool_reopen,
5913             zfs_secpolicy_config, B_TRUE, POOL_CHECK_SUSPENDED);
5914 
5915         zfs_ioctl_register_dataset_read(ZFS_IOC_SPACE_WRITTEN,
5916             zfs_ioc_space_written);
5917         zfs_ioctl_register_dataset_read(ZFS_IOC_OBJSET_RECVD_PROPS,
5918             zfs_ioc_objset_recvd_props);
5919         zfs_ioctl_register_dataset_read(ZFS_IOC_NEXT_OBJ,
5920             zfs_ioc_next_obj);
5921         zfs_ioctl_register_dataset_read(ZFS_IOC_GET_FSACL,
5922             zfs_ioc_get_fsacl);
5923         zfs_ioctl_register_dataset_read(ZFS_IOC_OBJSET_STATS,
5924             zfs_ioc_objset_stats);
5925         zfs_ioctl_register_dataset_read(ZFS_IOC_OBJSET_ZPLPROPS,
5926             zfs_ioc_objset_zplprops);
5927         zfs_ioctl_register_dataset_read(ZFS_IOC_DATASET_LIST_NEXT,
5928             zfs_ioc_dataset_list_next);
5929         zfs_ioctl_register_dataset_read(ZFS_IOC_SNAPSHOT_LIST_NEXT,
5930             zfs_ioc_snapshot_list_next);
5931         zfs_ioctl_register_dataset_read(ZFS_IOC_SEND_PROGRESS,
5932             zfs_ioc_send_progress);
5933 
5934         zfs_ioctl_register_dataset_read_secpolicy(ZFS_IOC_DIFF,
5935             zfs_ioc_diff, zfs_secpolicy_diff);
5936         zfs_ioctl_register_dataset_read_secpolicy(ZFS_IOC_OBJ_TO_STATS,
5937             zfs_ioc_obj_to_stats, zfs_secpolicy_diff);
5938         zfs_ioctl_register_dataset_read_secpolicy(ZFS_IOC_OBJ_TO_PATH,
5939             zfs_ioc_obj_to_path, zfs_secpolicy_diff);
5940         zfs_ioctl_register_dataset_read_secpolicy(ZFS_IOC_USERSPACE_ONE,
5941             zfs_ioc_userspace_one, zfs_secpolicy_userspace_one);
5942         zfs_ioctl_register_dataset_read_secpolicy(ZFS_IOC_USERSPACE_MANY,
5943             zfs_ioc_userspace_many, zfs_secpolicy_userspace_many);
5944         zfs_ioctl_register_dataset_read_secpolicy(ZFS_IOC_SEND,
5945             zfs_ioc_send, zfs_secpolicy_send);
5946 
5947         zfs_ioctl_register_dataset_modify(ZFS_IOC_SET_PROP, zfs_ioc_set_prop,
5948             zfs_secpolicy_none);
5949         zfs_ioctl_register_dataset_modify(ZFS_IOC_DESTROY, zfs_ioc_destroy,
5950             zfs_secpolicy_destroy);
5951         zfs_ioctl_register_dataset_modify(ZFS_IOC_RENAME, zfs_ioc_rename,
5952             zfs_secpolicy_rename);
5953         zfs_ioctl_register_dataset_modify(ZFS_IOC_RECV, zfs_ioc_recv,
5954             zfs_secpolicy_recv);
5955         zfs_ioctl_register_dataset_modify(ZFS_IOC_PROMOTE, zfs_ioc_promote,
5956             zfs_secpolicy_promote);
5957         zfs_ioctl_register_dataset_modify(ZFS_IOC_INHERIT_PROP,
5958             zfs_ioc_inherit_prop, zfs_secpolicy_inherit_prop);
5959         zfs_ioctl_register_dataset_modify(ZFS_IOC_SET_FSACL, zfs_ioc_set_fsacl,
5960             zfs_secpolicy_set_fsacl);
5961 
5962         zfs_ioctl_register_dataset_nolog(ZFS_IOC_SHARE, zfs_ioc_share,
5963             zfs_secpolicy_share, POOL_CHECK_NONE);
5964         zfs_ioctl_register_dataset_nolog(ZFS_IOC_SMB_ACL, zfs_ioc_smb_acl,
5965             zfs_secpolicy_smb_acl, POOL_CHECK_NONE);
5966         zfs_ioctl_register_dataset_nolog(ZFS_IOC_USERSPACE_UPGRADE,
5967             zfs_ioc_userspace_upgrade, zfs_secpolicy_userspace_upgrade,
5968             POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY);
5969         zfs_ioctl_register_dataset_nolog(ZFS_IOC_TMP_SNAPSHOT,
5970             zfs_ioc_tmp_snapshot, zfs_secpolicy_tmp_snapshot,
5971             POOL_CHECK_SUSPENDED | POOL_CHECK_READONLY);
5972 }
5973 
5974 int
5975 pool_status_check(const char *name, zfs_ioc_namecheck_t type,
5976     zfs_ioc_poolcheck_t check)
5977 {
5978         spa_t *spa;
5979         int error;
5980 
5981         ASSERT(type == POOL_NAME || type == DATASET_NAME);
5982 
5983         if (check & POOL_CHECK_NONE)
5984                 return (0);
5985 
5986         error = spa_open(name, &spa, FTAG);
5987         if (error == 0) {
5988                 if ((check & POOL_CHECK_SUSPENDED) && spa_suspended(spa))
5989                         error = SET_ERROR(EAGAIN);
5990                 else if ((check & POOL_CHECK_READONLY) && !spa_writeable(spa))
5991                         error = SET_ERROR(EROFS);
5992                 spa_close(spa, FTAG);
5993         }
5994         return (error);
5995 }
5996 
5997 /*
5998  * Find a free minor number.
5999  */
6000 minor_t
6001 zfsdev_minor_alloc(void)
6002 {
6003         static minor_t last_minor;
6004         minor_t m;
6005 
6006         ASSERT(MUTEX_HELD(&zfsdev_state_lock));
6007 
6008         for (m = last_minor + 1; m != last_minor; m++) {
6009                 if (m > ZFSDEV_MAX_MINOR)
6010                         m = 1;
6011                 if (ddi_get_soft_state(zfsdev_state, m) == NULL) {
6012                         last_minor = m;
6013                         return (m);
6014                 }
6015         }
6016 
6017         return (0);
6018 }
6019 
6020 static int
6021 zfs_ctldev_init(dev_t *devp)
6022 {
6023         minor_t minor;
6024         zfs_soft_state_t *zs;
6025 
6026         ASSERT(MUTEX_HELD(&zfsdev_state_lock));
6027         ASSERT(getminor(*devp) == 0);
6028 
6029         minor = zfsdev_minor_alloc();
6030         if (minor == 0)
6031                 return (SET_ERROR(ENXIO));
6032 
6033         if (ddi_soft_state_zalloc(zfsdev_state, minor) != DDI_SUCCESS)
6034                 return (SET_ERROR(EAGAIN));
6035 
6036         *devp = makedevice(getemajor(*devp), minor);
6037 
6038         zs = ddi_get_soft_state(zfsdev_state, minor);
6039         zs->zss_type = ZSST_CTLDEV;
6040         zfs_onexit_init((zfs_onexit_t **)&zs->zss_data);
6041 
6042         return (0);
6043 }
6044 
6045 static void
6046 zfs_ctldev_destroy(zfs_onexit_t *zo, minor_t minor)
6047 {
6048         ASSERT(MUTEX_HELD(&zfsdev_state_lock));
6049 
6050         zfs_onexit_destroy(zo);
6051         ddi_soft_state_free(zfsdev_state, minor);
6052 }
6053 
6054 void *
6055 zfsdev_get_soft_state(minor_t minor, enum zfs_soft_state_type which)
6056 {
6057         zfs_soft_state_t *zp;
6058 
6059         zp = ddi_get_soft_state(zfsdev_state, minor);
6060         if (zp == NULL || zp->zss_type != which)
6061                 return (NULL);
6062 
6063         return (zp->zss_data);
6064 }
6065 
6066 static int
6067 zfsdev_open(dev_t *devp, int flag, int otyp, cred_t *cr)
6068 {
6069         int error = 0;
6070 
6071         if (getminor(*devp) != 0)
6072                 return (zvol_open(devp, flag, otyp, cr));
6073 
6074         /* This is the control device. Allocate a new minor if requested. */
6075         if (flag & FEXCL) {
6076                 mutex_enter(&zfsdev_state_lock);
6077                 error = zfs_ctldev_init(devp);
6078                 mutex_exit(&zfsdev_state_lock);
6079         }
6080 
6081         return (error);
6082 }
6083 
6084 static int
6085 zfsdev_close(dev_t dev, int flag, int otyp, cred_t *cr)
6086 {
6087         zfs_onexit_t *zo;
6088         minor_t minor = getminor(dev);
6089 
6090         if (minor == 0)
6091                 return (0);
6092 
6093         mutex_enter(&zfsdev_state_lock);
6094         zo = zfsdev_get_soft_state(minor, ZSST_CTLDEV);
6095         if (zo == NULL) {
6096                 mutex_exit(&zfsdev_state_lock);
6097                 return (zvol_close(dev, flag, otyp, cr));
6098         }
6099         zfs_ctldev_destroy(zo, minor);
6100         mutex_exit(&zfsdev_state_lock);
6101 
6102         return (0);
6103 }
6104 
6105 static int
6106 zfsdev_ioctl(dev_t dev, int cmd, intptr_t arg, int flag, cred_t *cr, int *rvalp)
6107 {
6108         zfs_cmd_t *zc;
6109         uint_t vecnum;
6110         int error, rc, len;
6111         minor_t minor = getminor(dev);
6112         const zfs_ioc_vec_t *vec;
6113         char *saved_poolname = NULL;
6114         nvlist_t *innvl = NULL;
6115 
6116         if (minor != 0 &&
6117             zfsdev_get_soft_state(minor, ZSST_CTLDEV) == NULL)
6118                 return (zvol_ioctl(dev, cmd, arg, flag, cr, rvalp));
6119 
6120         vecnum = cmd - ZFS_IOC_FIRST;
6121         ASSERT3U(getmajor(dev), ==, ddi_driver_major(zfs_dip));
6122 
6123         if (vecnum >= sizeof (zfs_ioc_vec) / sizeof (zfs_ioc_vec[0]))
6124                 return (SET_ERROR(EINVAL));
6125         vec = &zfs_ioc_vec[vecnum];
6126 
6127         zc = kmem_zalloc(sizeof (zfs_cmd_t), KM_SLEEP);
6128 
6129         error = ddi_copyin((void *)arg, zc, sizeof (zfs_cmd_t), flag);
6130         if (error != 0) {
6131                 error = SET_ERROR(EFAULT);
6132                 goto out;
6133         }
6134 
6135         zc->zc_iflags = flag & FKIOCTL;
6136         if (zc->zc_nvlist_src_size != 0) {
6137                 error = get_nvlist(zc->zc_nvlist_src, zc->zc_nvlist_src_size,
6138                     zc->zc_iflags, &innvl);
6139                 if (error != 0)
6140                         goto out;
6141         }
6142 
6143         /*
6144          * Ensure that all pool/dataset names are valid before we pass down to
6145          * the lower layers.
6146          */
6147         zc->zc_name[sizeof (zc->zc_name) - 1] = '\0';
6148         switch (vec->zvec_namecheck) {
6149         case POOL_NAME:
6150                 if (pool_namecheck(zc->zc_name, NULL, NULL) != 0)
6151                         error = SET_ERROR(EINVAL);
6152                 else
6153                         error = pool_status_check(zc->zc_name,
6154                             vec->zvec_namecheck, vec->zvec_pool_check);
6155                 break;
6156 
6157         case DATASET_NAME:
6158                 if (dataset_namecheck(zc->zc_name, NULL, NULL) != 0)
6159                         error = SET_ERROR(EINVAL);
6160                 else
6161                         error = pool_status_check(zc->zc_name,
6162                             vec->zvec_namecheck, vec->zvec_pool_check);
6163                 break;
6164 
6165         case NO_NAME:
6166                 break;
6167         }
6168 
6169 
6170         if (error == 0)
6171                 error = vec->zvec_secpolicy(zc, innvl, cr);
6172 
6173         if (error != 0)
6174                 goto out;
6175 
6176         /* legacy ioctls can modify zc_name */
6177         len = strcspn(zc->zc_name, "/@#") + 1;
6178         saved_poolname = kmem_alloc(len, KM_SLEEP);
6179         (void) strlcpy(saved_poolname, zc->zc_name, len);
6180 
6181         if (vec->zvec_func != NULL) {
6182                 nvlist_t *outnvl;
6183                 int puterror = 0;
6184                 spa_t *spa;
6185                 nvlist_t *lognv = NULL;
6186 
6187                 ASSERT(vec->zvec_legacy_func == NULL);
6188 
6189                 /*
6190                  * Add the innvl to the lognv before calling the func,
6191                  * in case the func changes the innvl.
6192                  */
6193                 if (vec->zvec_allow_log) {
6194                         lognv = fnvlist_alloc();
6195                         fnvlist_add_string(lognv, ZPOOL_HIST_IOCTL,
6196                             vec->zvec_name);
6197                         if (!nvlist_empty(innvl)) {
6198                                 fnvlist_add_nvlist(lognv, ZPOOL_HIST_INPUT_NVL,
6199                                     innvl);
6200                         }
6201                 }
6202 
6203                 outnvl = fnvlist_alloc();
6204                 error = vec->zvec_func(zc->zc_name, innvl, outnvl);
6205 
6206                 /*
6207                  * Some commands can partially execute, modfiy state, and still
6208                  * return an error.  In these cases, attempt to record what
6209                  * was modified.
6210                  */
6211                 if ((error == 0 ||
6212                     (cmd == ZFS_IOC_CHANNEL_PROGRAM && error != EINVAL)) &&
6213                     vec->zvec_allow_log &&
6214                     spa_open(zc->zc_name, &spa, FTAG) == 0) {
6215                         if (!nvlist_empty(outnvl)) {
6216                                 fnvlist_add_nvlist(lognv, ZPOOL_HIST_OUTPUT_NVL,
6217                                     outnvl);
6218                         }
6219                         if (error != 0) {
6220                                 fnvlist_add_int64(lognv, ZPOOL_HIST_ERRNO,
6221                                     error);
6222                         }
6223                         (void) spa_history_log_nvl(spa, lognv);
6224                         spa_close(spa, FTAG);
6225                 }
6226                 fnvlist_free(lognv);
6227 
6228                 if (!nvlist_empty(outnvl) || zc->zc_nvlist_dst_size != 0) {
6229                         int smusherror = 0;
6230                         if (vec->zvec_smush_outnvlist) {
6231                                 smusherror = nvlist_smush(outnvl,
6232                                     zc->zc_nvlist_dst_size);
6233                         }
6234                         if (smusherror == 0)
6235                                 puterror = put_nvlist(zc, outnvl);
6236                 }
6237 
6238                 if (puterror != 0)
6239                         error = puterror;
6240 
6241                 nvlist_free(outnvl);
6242         } else {
6243                 error = vec->zvec_legacy_func(zc);
6244         }
6245 
6246 out:
6247         nvlist_free(innvl);
6248         rc = ddi_copyout(zc, (void *)arg, sizeof (zfs_cmd_t), flag);
6249         if (error == 0 && rc != 0)
6250                 error = SET_ERROR(EFAULT);
6251         if (error == 0 && vec->zvec_allow_log) {
6252                 char *s = tsd_get(zfs_allow_log_key);
6253                 if (s != NULL)
6254                         strfree(s);
6255                 (void) tsd_set(zfs_allow_log_key, saved_poolname);
6256         } else {
6257                 if (saved_poolname != NULL)
6258                         strfree(saved_poolname);
6259         }
6260 
6261         kmem_free(zc, sizeof (zfs_cmd_t));
6262         return (error);
6263 }
6264 
6265 static int
6266 zfs_attach(dev_info_t *dip, ddi_attach_cmd_t cmd)
6267 {
6268         if (cmd != DDI_ATTACH)
6269                 return (DDI_FAILURE);
6270 
6271         if (ddi_create_minor_node(dip, "zfs", S_IFCHR, 0,
6272             DDI_PSEUDO, 0) == DDI_FAILURE)
6273                 return (DDI_FAILURE);
6274 
6275         zfs_dip = dip;
6276 
6277         ddi_report_dev(dip);
6278 
6279         return (DDI_SUCCESS);
6280 }
6281 
6282 static int
6283 zfs_detach(dev_info_t *dip, ddi_detach_cmd_t cmd)
6284 {
6285         if (spa_busy() || zfs_busy() || zvol_busy())
6286                 return (DDI_FAILURE);
6287 
6288         if (cmd != DDI_DETACH)
6289                 return (DDI_FAILURE);
6290 
6291         zfs_dip = NULL;
6292 
6293         ddi_prop_remove_all(dip);
6294         ddi_remove_minor_node(dip, NULL);
6295 
6296         return (DDI_SUCCESS);
6297 }
6298 
6299 /*ARGSUSED*/
6300 static int
6301 zfs_info(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg, void **result)
6302 {
6303         switch (infocmd) {
6304         case DDI_INFO_DEVT2DEVINFO:
6305                 *result = zfs_dip;
6306                 return (DDI_SUCCESS);
6307 
6308         case DDI_INFO_DEVT2INSTANCE:
6309                 *result = (void *)0;
6310                 return (DDI_SUCCESS);
6311         }
6312 
6313         return (DDI_FAILURE);
6314 }
6315 
6316 /*
6317  * OK, so this is a little weird.
6318  *
6319  * /dev/zfs is the control node, i.e. minor 0.
6320  * /dev/zvol/[r]dsk/pool/dataset are the zvols, minor > 0.
6321  *
6322  * /dev/zfs has basically nothing to do except serve up ioctls,
6323  * so most of the standard driver entry points are in zvol.c.
6324  */
6325 static struct cb_ops zfs_cb_ops = {
6326         zfsdev_open,    /* open */
6327         zfsdev_close,   /* close */
6328         zvol_strategy,  /* strategy */
6329         nodev,          /* print */
6330         zvol_dump,      /* dump */
6331         zvol_read,      /* read */
6332         zvol_write,     /* write */
6333         zfsdev_ioctl,   /* ioctl */
6334         nodev,          /* devmap */
6335         nodev,          /* mmap */
6336         nodev,          /* segmap */
6337         nochpoll,       /* poll */
6338         ddi_prop_op,    /* prop_op */
6339         NULL,           /* streamtab */
6340         D_NEW | D_MP | D_64BIT,         /* Driver compatibility flag */
6341         CB_REV,         /* version */
6342         nodev,          /* async read */
6343         nodev,          /* async write */
6344 };
6345 
6346 static struct dev_ops zfs_dev_ops = {
6347         DEVO_REV,       /* version */
6348         0,              /* refcnt */
6349         zfs_info,       /* info */
6350         nulldev,        /* identify */
6351         nulldev,        /* probe */
6352         zfs_attach,     /* attach */
6353         zfs_detach,     /* detach */
6354         nodev,          /* reset */
6355         &zfs_cb_ops,        /* driver operations */
6356         NULL,           /* no bus operations */
6357         NULL,           /* power */
6358         ddi_quiesce_not_needed, /* quiesce */
6359 };
6360 
6361 static struct modldrv zfs_modldrv = {
6362         &mod_driverops,
6363         "ZFS storage pool",
6364         &zfs_dev_ops
6365 };
6366 
6367 static struct modlinkage modlinkage = {
6368         MODREV_1,
6369         (void *)&zfs_modlfs,
6370         (void *)&zfs_modldrv,
6371         NULL
6372 };
6373 
6374 static void
6375 zfs_allow_log_destroy(void *arg)
6376 {
6377         char *poolname = arg;
6378         strfree(poolname);
6379 }
6380 
6381 int
6382 _init(void)
6383 {
6384         int error;
6385 
6386         spa_init(FREAD | FWRITE);
6387         zfs_init();
6388         zvol_init();
6389         zfs_ioctl_init();
6390 
6391         if ((error = mod_install(&modlinkage)) != 0) {
6392                 zvol_fini();
6393                 zfs_fini();
6394                 spa_fini();
6395                 return (error);
6396         }
6397 
6398         tsd_create(&zfs_fsyncer_key, NULL);
6399         tsd_create(&rrw_tsd_key, rrw_tsd_destroy);
6400         tsd_create(&zfs_allow_log_key, zfs_allow_log_destroy);
6401 
6402         error = ldi_ident_from_mod(&modlinkage, &zfs_li);
6403         ASSERT(error == 0);
6404         mutex_init(&zfs_share_lock, NULL, MUTEX_DEFAULT, NULL);
6405 
6406         return (0);
6407 }
6408 
6409 int
6410 _fini(void)
6411 {
6412         int error;
6413 
6414         if (spa_busy() || zfs_busy() || zvol_busy() || zio_injection_enabled)
6415                 return (SET_ERROR(EBUSY));
6416 
6417         if ((error = mod_remove(&modlinkage)) != 0)
6418                 return (error);
6419 
6420         zvol_fini();
6421         zfs_fini();
6422         spa_fini();
6423         if (zfs_nfsshare_inited)
6424                 (void) ddi_modclose(nfs_mod);
6425         if (zfs_smbshare_inited)
6426                 (void) ddi_modclose(smbsrv_mod);
6427         if (zfs_nfsshare_inited || zfs_smbshare_inited)
6428                 (void) ddi_modclose(sharefs_mod);
6429 
6430         tsd_destroy(&zfs_fsyncer_key);
6431         ldi_ident_release(zfs_li);
6432         zfs_li = NULL;
6433         mutex_destroy(&zfs_share_lock);
6434 
6435         return (error);
6436 }
6437 
6438 int
6439 _info(struct modinfo *modinfop)
6440 {
6441         return (mod_info(&modlinkage, modinfop));
6442 }