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