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