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  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
  23  *
  24  * Portions Copyright 2010 Robert Milkowski
  25  *
  26  * Copyright 2017 Nexenta Systems, Inc.  All rights reserved.
  27  * Copyright (c) 2012, 2017 by Delphix. All rights reserved.
  28  * Copyright (c) 2013, Joyent, Inc. All rights reserved.
  29  * Copyright (c) 2014 Integros [integros.com]
  30  * Copyright (c) 2019, Joyent, Inc.
  31  */
  32 
  33 /*
  34  * ZFS volume emulation driver.
  35  *
  36  * Makes a DMU object look like a volume of arbitrary size, up to 2^64 bytes.
  37  * Volumes are accessed through the symbolic links named:
  38  *
  39  * /dev/zvol/dsk/<pool_name>/<dataset_name>
  40  * /dev/zvol/rdsk/<pool_name>/<dataset_name>
  41  *
  42  * These links are created by the /dev filesystem (sdev_zvolops.c).
  43  * Volumes are persistent through reboot.  No user command needs to be
  44  * run before opening and using a device.
  45  */
  46 
  47 #include <sys/types.h>
  48 #include <sys/param.h>
  49 #include <sys/errno.h>
  50 #include <sys/uio.h>
  51 #include <sys/buf.h>
  52 #include <sys/modctl.h>
  53 #include <sys/open.h>
  54 #include <sys/kmem.h>
  55 #include <sys/conf.h>
  56 #include <sys/cmn_err.h>
  57 #include <sys/stat.h>
  58 #include <sys/zap.h>
  59 #include <sys/spa.h>
  60 #include <sys/spa_impl.h>
  61 #include <sys/zio.h>
  62 #include <sys/dmu_traverse.h>
  63 #include <sys/dnode.h>
  64 #include <sys/dsl_dataset.h>
  65 #include <sys/dsl_prop.h>
  66 #include <sys/dkio.h>
  67 #include <sys/efi_partition.h>
  68 #include <sys/byteorder.h>
  69 #include <sys/pathname.h>
  70 #include <sys/ddi.h>
  71 #include <sys/sunddi.h>
  72 #include <sys/crc32.h>
  73 #include <sys/dirent.h>
  74 #include <sys/policy.h>
  75 #include <sys/fs/zfs.h>
  76 #include <sys/zfs_ioctl.h>
  77 #include <sys/mkdev.h>
  78 #include <sys/zil.h>
  79 #include <sys/refcount.h>
  80 #include <sys/zfs_znode.h>
  81 #include <sys/zfs_rlock.h>
  82 #include <sys/vdev_disk.h>
  83 #include <sys/vdev_impl.h>
  84 #include <sys/vdev_raidz.h>
  85 #include <sys/zvol.h>
  86 #include <sys/dumphdr.h>
  87 #include <sys/zil_impl.h>
  88 #include <sys/dbuf.h>
  89 #include <sys/dmu_tx.h>
  90 #include <sys/zfeature.h>
  91 #include <sys/zio_checksum.h>
  92 #include <sys/zil_impl.h>
  93 #include <sys/dkioc_free_util.h>
  94 #include <sys/zfs_rlock.h>
  95 
  96 #include "zfs_namecheck.h"
  97 
  98 void *zfsdev_state;
  99 static char *zvol_tag = "zvol_tag";
 100 
 101 #define ZVOL_DUMPSIZE           "dumpsize"
 102 
 103 /*
 104  * This lock protects the zfsdev_state structure from being modified
 105  * while it's being used, e.g. an open that comes in before a create
 106  * finishes.  It also protects temporary opens of the dataset so that,
 107  * e.g., an open doesn't get a spurious EBUSY.
 108  */
 109 kmutex_t zfsdev_state_lock;
 110 static uint32_t zvol_minors;
 111 
 112 typedef struct zvol_extent {
 113         list_node_t     ze_node;
 114         dva_t           ze_dva;         /* dva associated with this extent */
 115         uint64_t        ze_nblks;       /* number of blocks in extent */
 116 } zvol_extent_t;
 117 
 118 /*
 119  * The in-core state of each volume.
 120  */
 121 typedef struct zvol_state {
 122         char            zv_name[MAXPATHLEN]; /* pool/dd name */
 123         uint64_t        zv_volsize;     /* amount of space we advertise */
 124         uint64_t        zv_volblocksize; /* volume block size */
 125         minor_t         zv_minor;       /* minor number */
 126         uint8_t         zv_min_bs;      /* minimum addressable block shift */
 127         uint8_t         zv_flags;       /* readonly, dumpified, etc. */
 128         objset_t        *zv_objset;     /* objset handle */
 129         uint32_t        zv_open_count[OTYPCNT]; /* open counts */
 130         uint32_t        zv_total_opens; /* total open count */
 131         zilog_t         *zv_zilog;      /* ZIL handle */
 132         list_t          zv_extents;     /* List of extents for dump */
 133         rangelock_t     zv_rangelock;
 134         dnode_t         *zv_dn;         /* dnode hold */
 135 } zvol_state_t;
 136 
 137 /*
 138  * zvol specific flags
 139  */
 140 #define ZVOL_RDONLY     0x1
 141 #define ZVOL_DUMPIFIED  0x2
 142 #define ZVOL_EXCL       0x4
 143 #define ZVOL_WCE        0x8
 144 
 145 /*
 146  * zvol maximum transfer in one DMU tx.
 147  */
 148 int zvol_maxphys = DMU_MAX_ACCESS/2;
 149 
 150 /*
 151  * Toggle unmap functionality.
 152  */
 153 boolean_t zvol_unmap_enabled = B_TRUE;
 154 
 155 /*
 156  * If true, unmaps requested as synchronous are executed synchronously,
 157  * otherwise all unmaps are asynchronous.
 158  */
 159 boolean_t zvol_unmap_sync_enabled = B_FALSE;
 160 
 161 extern int zfs_set_prop_nvlist(const char *, zprop_source_t,
 162     nvlist_t *, nvlist_t *);
 163 static int zvol_remove_zv(zvol_state_t *);
 164 static int zvol_get_data(void *arg, lr_write_t *lr, char *buf,
 165     struct lwb *lwb, zio_t *zio);
 166 static int zvol_dumpify(zvol_state_t *zv);
 167 static int zvol_dump_fini(zvol_state_t *zv);
 168 static int zvol_dump_init(zvol_state_t *zv, boolean_t resize);
 169 
 170 static void
 171 zvol_size_changed(zvol_state_t *zv, uint64_t volsize)
 172 {
 173         dev_t dev = makedevice(ddi_driver_major(zfs_dip), zv->zv_minor);
 174 
 175         zv->zv_volsize = volsize;
 176         VERIFY(ddi_prop_update_int64(dev, zfs_dip,
 177             "Size", volsize) == DDI_SUCCESS);
 178         VERIFY(ddi_prop_update_int64(dev, zfs_dip,
 179             "Nblocks", lbtodb(volsize)) == DDI_SUCCESS);
 180 
 181         /* Notify specfs to invalidate the cached size */
 182         spec_size_invalidate(dev, VBLK);
 183         spec_size_invalidate(dev, VCHR);
 184 }
 185 
 186 int
 187 zvol_check_volsize(uint64_t volsize, uint64_t blocksize)
 188 {
 189         if (volsize == 0)
 190                 return (SET_ERROR(EINVAL));
 191 
 192         if (volsize % blocksize != 0)
 193                 return (SET_ERROR(EINVAL));
 194 
 195 #ifdef _ILP32
 196         if (volsize - 1 > SPEC_MAXOFFSET_T)
 197                 return (SET_ERROR(EOVERFLOW));
 198 #endif
 199         return (0);
 200 }
 201 
 202 int
 203 zvol_check_volblocksize(uint64_t volblocksize)
 204 {
 205         if (volblocksize < SPA_MINBLOCKSIZE ||
 206             volblocksize > SPA_OLD_MAXBLOCKSIZE ||
 207             !ISP2(volblocksize))
 208                 return (SET_ERROR(EDOM));
 209 
 210         return (0);
 211 }
 212 
 213 int
 214 zvol_get_stats(objset_t *os, nvlist_t *nv)
 215 {
 216         int error;
 217         dmu_object_info_t doi;
 218         uint64_t val;
 219 
 220         error = zap_lookup(os, ZVOL_ZAP_OBJ, "size", 8, 1, &val);
 221         if (error)
 222                 return (error);
 223 
 224         dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_VOLSIZE, val);
 225 
 226         error = dmu_object_info(os, ZVOL_OBJ, &doi);
 227 
 228         if (error == 0) {
 229                 dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_VOLBLOCKSIZE,
 230                     doi.doi_data_block_size);
 231         }
 232 
 233         return (error);
 234 }
 235 
 236 static zvol_state_t *
 237 zvol_minor_lookup(const char *name)
 238 {
 239         minor_t minor;
 240         zvol_state_t *zv;
 241 
 242         ASSERT(MUTEX_HELD(&zfsdev_state_lock));
 243 
 244         for (minor = 1; minor <= ZFSDEV_MAX_MINOR; minor++) {
 245                 zv = zfsdev_get_soft_state(minor, ZSST_ZVOL);
 246                 if (zv == NULL)
 247                         continue;
 248                 if (strcmp(zv->zv_name, name) == 0)
 249                         return (zv);
 250         }
 251 
 252         return (NULL);
 253 }
 254 
 255 /* extent mapping arg */
 256 struct maparg {
 257         zvol_state_t    *ma_zv;
 258         uint64_t        ma_blks;
 259 };
 260 
 261 /*ARGSUSED*/
 262 static int
 263 zvol_map_block(spa_t *spa, zilog_t *zilog, const blkptr_t *bp,
 264     const zbookmark_phys_t *zb, const dnode_phys_t *dnp, void *arg)
 265 {
 266         struct maparg *ma = arg;
 267         zvol_extent_t *ze;
 268         int bs = ma->ma_zv->zv_volblocksize;
 269 
 270         if (bp == NULL || BP_IS_HOLE(bp) ||
 271             zb->zb_object != ZVOL_OBJ || zb->zb_level != 0)
 272                 return (0);
 273 
 274         VERIFY(!BP_IS_EMBEDDED(bp));
 275 
 276         VERIFY3U(ma->ma_blks, ==, zb->zb_blkid);
 277         ma->ma_blks++;
 278 
 279         /* Abort immediately if we have encountered gang blocks */
 280         if (BP_IS_GANG(bp))
 281                 return (SET_ERROR(EFRAGS));
 282 
 283         /*
 284          * See if the block is at the end of the previous extent.
 285          */
 286         ze = list_tail(&ma->ma_zv->zv_extents);
 287         if (ze &&
 288             DVA_GET_VDEV(BP_IDENTITY(bp)) == DVA_GET_VDEV(&ze->ze_dva) &&
 289             DVA_GET_OFFSET(BP_IDENTITY(bp)) ==
 290             DVA_GET_OFFSET(&ze->ze_dva) + ze->ze_nblks * bs) {
 291                 ze->ze_nblks++;
 292                 return (0);
 293         }
 294 
 295         dprintf_bp(bp, "%s", "next blkptr:");
 296 
 297         /* start a new extent */
 298         ze = kmem_zalloc(sizeof (zvol_extent_t), KM_SLEEP);
 299         ze->ze_dva = bp->blk_dva[0];      /* structure assignment */
 300         ze->ze_nblks = 1;
 301         list_insert_tail(&ma->ma_zv->zv_extents, ze);
 302         return (0);
 303 }
 304 
 305 static void
 306 zvol_free_extents(zvol_state_t *zv)
 307 {
 308         zvol_extent_t *ze;
 309 
 310         while (ze = list_head(&zv->zv_extents)) {
 311                 list_remove(&zv->zv_extents, ze);
 312                 kmem_free(ze, sizeof (zvol_extent_t));
 313         }
 314 }
 315 
 316 static int
 317 zvol_get_lbas(zvol_state_t *zv)
 318 {
 319         objset_t *os = zv->zv_objset;
 320         struct maparg   ma;
 321         int             err;
 322 
 323         ma.ma_zv = zv;
 324         ma.ma_blks = 0;
 325         zvol_free_extents(zv);
 326 
 327         /* commit any in-flight changes before traversing the dataset */
 328         txg_wait_synced(dmu_objset_pool(os), 0);
 329         err = traverse_dataset(dmu_objset_ds(os), 0,
 330             TRAVERSE_PRE | TRAVERSE_PREFETCH_METADATA, zvol_map_block, &ma);
 331         if (err || ma.ma_blks != (zv->zv_volsize / zv->zv_volblocksize)) {
 332                 zvol_free_extents(zv);
 333                 return (err ? err : EIO);
 334         }
 335 
 336         return (0);
 337 }
 338 
 339 /* ARGSUSED */
 340 void
 341 zvol_create_cb(objset_t *os, void *arg, cred_t *cr, dmu_tx_t *tx)
 342 {
 343         zfs_creat_t *zct = arg;
 344         nvlist_t *nvprops = zct->zct_props;
 345         int error;
 346         uint64_t volblocksize, volsize;
 347 
 348         VERIFY(nvlist_lookup_uint64(nvprops,
 349             zfs_prop_to_name(ZFS_PROP_VOLSIZE), &volsize) == 0);
 350         if (nvlist_lookup_uint64(nvprops,
 351             zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE), &volblocksize) != 0)
 352                 volblocksize = zfs_prop_default_numeric(ZFS_PROP_VOLBLOCKSIZE);
 353 
 354         /*
 355          * These properties must be removed from the list so the generic
 356          * property setting step won't apply to them.
 357          */
 358         VERIFY(nvlist_remove_all(nvprops,
 359             zfs_prop_to_name(ZFS_PROP_VOLSIZE)) == 0);
 360         (void) nvlist_remove_all(nvprops,
 361             zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE));
 362 
 363         error = dmu_object_claim(os, ZVOL_OBJ, DMU_OT_ZVOL, volblocksize,
 364             DMU_OT_NONE, 0, tx);
 365         ASSERT(error == 0);
 366 
 367         error = zap_create_claim(os, ZVOL_ZAP_OBJ, DMU_OT_ZVOL_PROP,
 368             DMU_OT_NONE, 0, tx);
 369         ASSERT(error == 0);
 370 
 371         error = zap_update(os, ZVOL_ZAP_OBJ, "size", 8, 1, &volsize, tx);
 372         ASSERT(error == 0);
 373 }
 374 
 375 /*
 376  * Replay a TX_TRUNCATE ZIL transaction if asked.  TX_TRUNCATE is how we
 377  * implement DKIOCFREE/free-long-range.
 378  */
 379 static int
 380 zvol_replay_truncate(void *arg1, void *arg2, boolean_t byteswap)
 381 {
 382         zvol_state_t *zv = arg1;
 383         lr_truncate_t *lr = arg2;
 384         uint64_t offset, length;
 385 
 386         if (byteswap)
 387                 byteswap_uint64_array(lr, sizeof (*lr));
 388 
 389         offset = lr->lr_offset;
 390         length = lr->lr_length;
 391 
 392         return (dmu_free_long_range(zv->zv_objset, ZVOL_OBJ, offset, length));
 393 }
 394 
 395 /*
 396  * Replay a TX_WRITE ZIL transaction that didn't get committed
 397  * after a system failure
 398  */
 399 static int
 400 zvol_replay_write(void *arg1, void *arg2, boolean_t byteswap)
 401 {
 402         zvol_state_t *zv = arg1;
 403         lr_write_t *lr = arg2;
 404         objset_t *os = zv->zv_objset;
 405         char *data = (char *)(lr + 1);  /* data follows lr_write_t */
 406         uint64_t offset, length;
 407         dmu_tx_t *tx;
 408         int error;
 409 
 410         if (byteswap)
 411                 byteswap_uint64_array(lr, sizeof (*lr));
 412 
 413         offset = lr->lr_offset;
 414         length = lr->lr_length;
 415 
 416         /* If it's a dmu_sync() block, write the whole block */
 417         if (lr->lr_common.lrc_reclen == sizeof (lr_write_t)) {
 418                 uint64_t blocksize = BP_GET_LSIZE(&lr->lr_blkptr);
 419                 if (length < blocksize) {
 420                         offset -= offset % blocksize;
 421                         length = blocksize;
 422                 }
 423         }
 424 
 425         tx = dmu_tx_create(os);
 426         dmu_tx_hold_write(tx, ZVOL_OBJ, offset, length);
 427         error = dmu_tx_assign(tx, TXG_WAIT);
 428         if (error) {
 429                 dmu_tx_abort(tx);
 430         } else {
 431                 dmu_write(os, ZVOL_OBJ, offset, length, data, tx);
 432                 dmu_tx_commit(tx);
 433         }
 434 
 435         return (error);
 436 }
 437 
 438 /* ARGSUSED */
 439 static int
 440 zvol_replay_err(void *arg1, void *arg2, boolean_t byteswap)
 441 {
 442         return (SET_ERROR(ENOTSUP));
 443 }
 444 
 445 /*
 446  * Callback vectors for replaying records.
 447  * Only TX_WRITE and TX_TRUNCATE are needed for zvol.
 448  */
 449 zil_replay_func_t *zvol_replay_vector[TX_MAX_TYPE] = {
 450         zvol_replay_err,        /* 0 no such transaction type */
 451         zvol_replay_err,        /* TX_CREATE */
 452         zvol_replay_err,        /* TX_MKDIR */
 453         zvol_replay_err,        /* TX_MKXATTR */
 454         zvol_replay_err,        /* TX_SYMLINK */
 455         zvol_replay_err,        /* TX_REMOVE */
 456         zvol_replay_err,        /* TX_RMDIR */
 457         zvol_replay_err,        /* TX_LINK */
 458         zvol_replay_err,        /* TX_RENAME */
 459         zvol_replay_write,      /* TX_WRITE */
 460         zvol_replay_truncate,   /* TX_TRUNCATE */
 461         zvol_replay_err,        /* TX_SETATTR */
 462         zvol_replay_err,        /* TX_ACL */
 463         zvol_replay_err,        /* TX_CREATE_ACL */
 464         zvol_replay_err,        /* TX_CREATE_ATTR */
 465         zvol_replay_err,        /* TX_CREATE_ACL_ATTR */
 466         zvol_replay_err,        /* TX_MKDIR_ACL */
 467         zvol_replay_err,        /* TX_MKDIR_ATTR */
 468         zvol_replay_err,        /* TX_MKDIR_ACL_ATTR */
 469         zvol_replay_err,        /* TX_WRITE2 */
 470 };
 471 
 472 int
 473 zvol_name2minor(const char *name, minor_t *minor)
 474 {
 475         zvol_state_t *zv;
 476 
 477         mutex_enter(&zfsdev_state_lock);
 478         zv = zvol_minor_lookup(name);
 479         if (minor && zv)
 480                 *minor = zv->zv_minor;
 481         mutex_exit(&zfsdev_state_lock);
 482         return (zv ? 0 : -1);
 483 }
 484 
 485 /*
 486  * Create a minor node (plus a whole lot more) for the specified volume.
 487  */
 488 int
 489 zvol_create_minor(const char *name)
 490 {
 491         zfs_soft_state_t *zs;
 492         zvol_state_t *zv;
 493         objset_t *os;
 494         dmu_object_info_t doi;
 495         minor_t minor = 0;
 496         char chrbuf[30], blkbuf[30];
 497         int error;
 498 
 499         mutex_enter(&zfsdev_state_lock);
 500 
 501         if (zvol_minor_lookup(name) != NULL) {
 502                 mutex_exit(&zfsdev_state_lock);
 503                 return (SET_ERROR(EEXIST));
 504         }
 505 
 506         /* lie and say we're read-only */
 507         error = dmu_objset_own(name, DMU_OST_ZVOL, B_TRUE, FTAG, &os);
 508 
 509         if (error) {
 510                 mutex_exit(&zfsdev_state_lock);
 511                 return (error);
 512         }
 513 
 514         if ((minor = zfsdev_minor_alloc()) == 0) {
 515                 dmu_objset_disown(os, FTAG);
 516                 mutex_exit(&zfsdev_state_lock);
 517                 return (SET_ERROR(ENXIO));
 518         }
 519 
 520         if (ddi_soft_state_zalloc(zfsdev_state, minor) != DDI_SUCCESS) {
 521                 dmu_objset_disown(os, FTAG);
 522                 mutex_exit(&zfsdev_state_lock);
 523                 return (SET_ERROR(EAGAIN));
 524         }
 525         (void) ddi_prop_update_string(minor, zfs_dip, ZVOL_PROP_NAME,
 526             (char *)name);
 527 
 528         (void) snprintf(chrbuf, sizeof (chrbuf), "%u,raw", minor);
 529 
 530         if (ddi_create_minor_node(zfs_dip, chrbuf, S_IFCHR,
 531             minor, DDI_PSEUDO, 0) == DDI_FAILURE) {
 532                 ddi_soft_state_free(zfsdev_state, minor);
 533                 dmu_objset_disown(os, FTAG);
 534                 mutex_exit(&zfsdev_state_lock);
 535                 return (SET_ERROR(EAGAIN));
 536         }
 537 
 538         (void) snprintf(blkbuf, sizeof (blkbuf), "%u", minor);
 539 
 540         if (ddi_create_minor_node(zfs_dip, blkbuf, S_IFBLK,
 541             minor, DDI_PSEUDO, 0) == DDI_FAILURE) {
 542                 ddi_remove_minor_node(zfs_dip, chrbuf);
 543                 ddi_soft_state_free(zfsdev_state, minor);
 544                 dmu_objset_disown(os, FTAG);
 545                 mutex_exit(&zfsdev_state_lock);
 546                 return (SET_ERROR(EAGAIN));
 547         }
 548 
 549         zs = ddi_get_soft_state(zfsdev_state, minor);
 550         zs->zss_type = ZSST_ZVOL;
 551         zv = zs->zss_data = kmem_zalloc(sizeof (zvol_state_t), KM_SLEEP);
 552         (void) strlcpy(zv->zv_name, name, MAXPATHLEN);
 553         zv->zv_min_bs = DEV_BSHIFT;
 554         zv->zv_minor = minor;
 555         zv->zv_objset = os;
 556         if (dmu_objset_is_snapshot(os) || !spa_writeable(dmu_objset_spa(os)))
 557                 zv->zv_flags |= ZVOL_RDONLY;
 558         rangelock_init(&zv->zv_rangelock, NULL, NULL);
 559         list_create(&zv->zv_extents, sizeof (zvol_extent_t),
 560             offsetof(zvol_extent_t, ze_node));
 561         /* get and cache the blocksize */
 562         error = dmu_object_info(os, ZVOL_OBJ, &doi);
 563         ASSERT(error == 0);
 564         zv->zv_volblocksize = doi.doi_data_block_size;
 565 
 566         if (spa_writeable(dmu_objset_spa(os))) {
 567                 if (zil_replay_disable)
 568                         zil_destroy(dmu_objset_zil(os), B_FALSE);
 569                 else
 570                         zil_replay(os, zv, zvol_replay_vector);
 571         }
 572         dmu_objset_disown(os, FTAG);
 573         zv->zv_objset = NULL;
 574 
 575         zvol_minors++;
 576 
 577         mutex_exit(&zfsdev_state_lock);
 578 
 579         return (0);
 580 }
 581 
 582 /*
 583  * Remove minor node for the specified volume.
 584  */
 585 static int
 586 zvol_remove_zv(zvol_state_t *zv)
 587 {
 588         char nmbuf[20];
 589         minor_t minor = zv->zv_minor;
 590 
 591         ASSERT(MUTEX_HELD(&zfsdev_state_lock));
 592         if (zv->zv_total_opens != 0)
 593                 return (SET_ERROR(EBUSY));
 594 
 595         (void) snprintf(nmbuf, sizeof (nmbuf), "%u,raw", minor);
 596         ddi_remove_minor_node(zfs_dip, nmbuf);
 597 
 598         (void) snprintf(nmbuf, sizeof (nmbuf), "%u", minor);
 599         ddi_remove_minor_node(zfs_dip, nmbuf);
 600 
 601         rangelock_fini(&zv->zv_rangelock);
 602 
 603         kmem_free(zv, sizeof (zvol_state_t));
 604 
 605         ddi_soft_state_free(zfsdev_state, minor);
 606 
 607         zvol_minors--;
 608         return (0);
 609 }
 610 
 611 int
 612 zvol_remove_minor(const char *name)
 613 {
 614         zvol_state_t *zv;
 615         int rc;
 616 
 617         mutex_enter(&zfsdev_state_lock);
 618         if ((zv = zvol_minor_lookup(name)) == NULL) {
 619                 mutex_exit(&zfsdev_state_lock);
 620                 return (SET_ERROR(ENXIO));
 621         }
 622         rc = zvol_remove_zv(zv);
 623         mutex_exit(&zfsdev_state_lock);
 624         return (rc);
 625 }
 626 
 627 int
 628 zvol_first_open(zvol_state_t *zv)
 629 {
 630         objset_t *os;
 631         uint64_t volsize;
 632         int error;
 633         uint64_t readonly;
 634 
 635         /* lie and say we're read-only */
 636         error = dmu_objset_own(zv->zv_name, DMU_OST_ZVOL, B_TRUE,
 637             zvol_tag, &os);
 638         if (error)
 639                 return (error);
 640 
 641         zv->zv_objset = os;
 642         error = zap_lookup(os, ZVOL_ZAP_OBJ, "size", 8, 1, &volsize);
 643         if (error) {
 644                 ASSERT(error == 0);
 645                 dmu_objset_disown(os, zvol_tag);
 646                 return (error);
 647         }
 648 
 649         error = dnode_hold(os, ZVOL_OBJ, zvol_tag, &zv->zv_dn);
 650         if (error) {
 651                 dmu_objset_disown(os, zvol_tag);
 652                 return (error);
 653         }
 654 
 655         zvol_size_changed(zv, volsize);
 656         zv->zv_zilog = zil_open(os, zvol_get_data);
 657 
 658         VERIFY(dsl_prop_get_integer(zv->zv_name, "readonly", &readonly,
 659             NULL) == 0);
 660         if (readonly || dmu_objset_is_snapshot(os) ||
 661             !spa_writeable(dmu_objset_spa(os)))
 662                 zv->zv_flags |= ZVOL_RDONLY;
 663         else
 664                 zv->zv_flags &= ~ZVOL_RDONLY;
 665         return (error);
 666 }
 667 
 668 void
 669 zvol_last_close(zvol_state_t *zv)
 670 {
 671         zil_close(zv->zv_zilog);
 672         zv->zv_zilog = NULL;
 673 
 674         dnode_rele(zv->zv_dn, zvol_tag);
 675         zv->zv_dn = NULL;
 676 
 677         /*
 678          * Evict cached data
 679          */
 680         if (dsl_dataset_is_dirty(dmu_objset_ds(zv->zv_objset)) &&
 681             !(zv->zv_flags & ZVOL_RDONLY))
 682                 txg_wait_synced(dmu_objset_pool(zv->zv_objset), 0);
 683         dmu_objset_evict_dbufs(zv->zv_objset);
 684 
 685         dmu_objset_disown(zv->zv_objset, zvol_tag);
 686         zv->zv_objset = NULL;
 687 }
 688 
 689 int
 690 zvol_prealloc(zvol_state_t *zv)
 691 {
 692         objset_t *os = zv->zv_objset;
 693         dmu_tx_t *tx;
 694         uint64_t refd, avail, usedobjs, availobjs;
 695         uint64_t resid = zv->zv_volsize;
 696         uint64_t off = 0;
 697 
 698         /* Check the space usage before attempting to allocate the space */
 699         dmu_objset_space(os, &refd, &avail, &usedobjs, &availobjs);
 700         if (avail < zv->zv_volsize)
 701                 return (SET_ERROR(ENOSPC));
 702 
 703         /* Free old extents if they exist */
 704         zvol_free_extents(zv);
 705 
 706         while (resid != 0) {
 707                 int error;
 708                 uint64_t bytes = MIN(resid, SPA_OLD_MAXBLOCKSIZE);
 709 
 710                 tx = dmu_tx_create(os);
 711                 dmu_tx_hold_write(tx, ZVOL_OBJ, off, bytes);
 712                 error = dmu_tx_assign(tx, TXG_WAIT);
 713                 if (error) {
 714                         dmu_tx_abort(tx);
 715                         (void) dmu_free_long_range(os, ZVOL_OBJ, 0, off);
 716                         return (error);
 717                 }
 718                 dmu_prealloc(os, ZVOL_OBJ, off, bytes, tx);
 719                 dmu_tx_commit(tx);
 720                 off += bytes;
 721                 resid -= bytes;
 722         }
 723         txg_wait_synced(dmu_objset_pool(os), 0);
 724 
 725         return (0);
 726 }
 727 
 728 static int
 729 zvol_update_volsize(objset_t *os, uint64_t volsize)
 730 {
 731         dmu_tx_t *tx;
 732         int error;
 733 
 734         ASSERT(MUTEX_HELD(&zfsdev_state_lock));
 735 
 736         tx = dmu_tx_create(os);
 737         dmu_tx_hold_zap(tx, ZVOL_ZAP_OBJ, TRUE, NULL);
 738         dmu_tx_mark_netfree(tx);
 739         error = dmu_tx_assign(tx, TXG_WAIT);
 740         if (error) {
 741                 dmu_tx_abort(tx);
 742                 return (error);
 743         }
 744 
 745         error = zap_update(os, ZVOL_ZAP_OBJ, "size", 8, 1,
 746             &volsize, tx);
 747         dmu_tx_commit(tx);
 748 
 749         if (error == 0)
 750                 error = dmu_free_long_range(os,
 751                     ZVOL_OBJ, volsize, DMU_OBJECT_END);
 752         return (error);
 753 }
 754 
 755 void
 756 zvol_remove_minors(const char *name)
 757 {
 758         zvol_state_t *zv;
 759         char *namebuf;
 760         minor_t minor;
 761 
 762         namebuf = kmem_zalloc(strlen(name) + 2, KM_SLEEP);
 763         (void) strncpy(namebuf, name, strlen(name));
 764         (void) strcat(namebuf, "/");
 765         mutex_enter(&zfsdev_state_lock);
 766         for (minor = 1; minor <= ZFSDEV_MAX_MINOR; minor++) {
 767 
 768                 zv = zfsdev_get_soft_state(minor, ZSST_ZVOL);
 769                 if (zv == NULL)
 770                         continue;
 771                 if (strncmp(namebuf, zv->zv_name, strlen(namebuf)) == 0)
 772                         (void) zvol_remove_zv(zv);
 773         }
 774         kmem_free(namebuf, strlen(name) + 2);
 775 
 776         mutex_exit(&zfsdev_state_lock);
 777 }
 778 
 779 static int
 780 zvol_update_live_volsize(zvol_state_t *zv, uint64_t volsize)
 781 {
 782         uint64_t old_volsize = 0ULL;
 783         int error = 0;
 784 
 785         ASSERT(MUTEX_HELD(&zfsdev_state_lock));
 786 
 787         /*
 788          * Reinitialize the dump area to the new size. If we
 789          * failed to resize the dump area then restore it back to
 790          * its original size.  We must set the new volsize prior
 791          * to calling dumpvp_resize() to ensure that the devices'
 792          * size(9P) is not visible by the dump subsystem.
 793          */
 794         old_volsize = zv->zv_volsize;
 795         zvol_size_changed(zv, volsize);
 796 
 797         if (zv->zv_flags & ZVOL_DUMPIFIED) {
 798                 if ((error = zvol_dumpify(zv)) != 0 ||
 799                     (error = dumpvp_resize()) != 0) {
 800                         int dumpify_error;
 801 
 802                         (void) zvol_update_volsize(zv->zv_objset, old_volsize);
 803                         zvol_size_changed(zv, old_volsize);
 804                         dumpify_error = zvol_dumpify(zv);
 805                         error = dumpify_error ? dumpify_error : error;
 806                 }
 807         }
 808 
 809         /*
 810          * Generate a LUN expansion event.
 811          */
 812         if (error == 0) {
 813                 sysevent_id_t eid;
 814                 nvlist_t *attr;
 815                 char *physpath = kmem_zalloc(MAXPATHLEN, KM_SLEEP);
 816 
 817                 (void) snprintf(physpath, MAXPATHLEN, "%s%u", ZVOL_PSEUDO_DEV,
 818                     zv->zv_minor);
 819 
 820                 VERIFY(nvlist_alloc(&attr, NV_UNIQUE_NAME, KM_SLEEP) == 0);
 821                 VERIFY(nvlist_add_string(attr, DEV_PHYS_PATH, physpath) == 0);
 822 
 823                 (void) ddi_log_sysevent(zfs_dip, SUNW_VENDOR, EC_DEV_STATUS,
 824                     ESC_DEV_DLE, attr, &eid, DDI_SLEEP);
 825 
 826                 nvlist_free(attr);
 827                 kmem_free(physpath, MAXPATHLEN);
 828         }
 829         return (error);
 830 }
 831 
 832 int
 833 zvol_set_volsize(const char *name, uint64_t volsize)
 834 {
 835         zvol_state_t *zv = NULL;
 836         objset_t *os;
 837         int error;
 838         dmu_object_info_t doi;
 839         uint64_t readonly;
 840         boolean_t owned = B_FALSE;
 841 
 842         error = dsl_prop_get_integer(name,
 843             zfs_prop_to_name(ZFS_PROP_READONLY), &readonly, NULL);
 844         if (error != 0)
 845                 return (error);
 846         if (readonly)
 847                 return (SET_ERROR(EROFS));
 848 
 849         mutex_enter(&zfsdev_state_lock);
 850         zv = zvol_minor_lookup(name);
 851 
 852         if (zv == NULL || zv->zv_objset == NULL) {
 853                 if ((error = dmu_objset_own(name, DMU_OST_ZVOL, B_FALSE,
 854                     FTAG, &os)) != 0) {
 855                         mutex_exit(&zfsdev_state_lock);
 856                         return (error);
 857                 }
 858                 owned = B_TRUE;
 859                 if (zv != NULL)
 860                         zv->zv_objset = os;
 861         } else {
 862                 os = zv->zv_objset;
 863         }
 864 
 865         if ((error = dmu_object_info(os, ZVOL_OBJ, &doi)) != 0 ||
 866             (error = zvol_check_volsize(volsize, doi.doi_data_block_size)) != 0)
 867                 goto out;
 868 
 869         error = zvol_update_volsize(os, volsize);
 870 
 871         if (error == 0 && zv != NULL)
 872                 error = zvol_update_live_volsize(zv, volsize);
 873 out:
 874         if (owned) {
 875                 dmu_objset_disown(os, FTAG);
 876                 if (zv != NULL)
 877                         zv->zv_objset = NULL;
 878         }
 879         mutex_exit(&zfsdev_state_lock);
 880         return (error);
 881 }
 882 
 883 /*ARGSUSED*/
 884 int
 885 zvol_open(dev_t *devp, int flag, int otyp, cred_t *cr)
 886 {
 887         zvol_state_t *zv;
 888         int err = 0;
 889 
 890         mutex_enter(&zfsdev_state_lock);
 891 
 892         zv = zfsdev_get_soft_state(getminor(*devp), ZSST_ZVOL);
 893         if (zv == NULL) {
 894                 mutex_exit(&zfsdev_state_lock);
 895                 return (SET_ERROR(ENXIO));
 896         }
 897 
 898         if (zv->zv_total_opens == 0)
 899                 err = zvol_first_open(zv);
 900         if (err) {
 901                 mutex_exit(&zfsdev_state_lock);
 902                 return (err);
 903         }
 904         if ((flag & FWRITE) && (zv->zv_flags & ZVOL_RDONLY)) {
 905                 err = SET_ERROR(EROFS);
 906                 goto out;
 907         }
 908         if (zv->zv_flags & ZVOL_EXCL) {
 909                 err = SET_ERROR(EBUSY);
 910                 goto out;
 911         }
 912         if (flag & FEXCL) {
 913                 if (zv->zv_total_opens != 0) {
 914                         err = SET_ERROR(EBUSY);
 915                         goto out;
 916                 }
 917                 zv->zv_flags |= ZVOL_EXCL;
 918         }
 919 
 920         if (zv->zv_open_count[otyp] == 0 || otyp == OTYP_LYR) {
 921                 zv->zv_open_count[otyp]++;
 922                 zv->zv_total_opens++;
 923         }
 924         mutex_exit(&zfsdev_state_lock);
 925 
 926         return (err);
 927 out:
 928         if (zv->zv_total_opens == 0)
 929                 zvol_last_close(zv);
 930         mutex_exit(&zfsdev_state_lock);
 931         return (err);
 932 }
 933 
 934 /*ARGSUSED*/
 935 int
 936 zvol_close(dev_t dev, int flag, int otyp, cred_t *cr)
 937 {
 938         minor_t minor = getminor(dev);
 939         zvol_state_t *zv;
 940         int error = 0;
 941 
 942         mutex_enter(&zfsdev_state_lock);
 943 
 944         zv = zfsdev_get_soft_state(minor, ZSST_ZVOL);
 945         if (zv == NULL) {
 946                 mutex_exit(&zfsdev_state_lock);
 947                 return (SET_ERROR(ENXIO));
 948         }
 949 
 950         if (zv->zv_flags & ZVOL_EXCL) {
 951                 ASSERT(zv->zv_total_opens == 1);
 952                 zv->zv_flags &= ~ZVOL_EXCL;
 953         }
 954 
 955         /*
 956          * If the open count is zero, this is a spurious close.
 957          * That indicates a bug in the kernel / DDI framework.
 958          */
 959         ASSERT(zv->zv_open_count[otyp] != 0);
 960         ASSERT(zv->zv_total_opens != 0);
 961 
 962         /*
 963          * You may get multiple opens, but only one close.
 964          */
 965         zv->zv_open_count[otyp]--;
 966         zv->zv_total_opens--;
 967 
 968         if (zv->zv_total_opens == 0)
 969                 zvol_last_close(zv);
 970 
 971         mutex_exit(&zfsdev_state_lock);
 972         return (error);
 973 }
 974 
 975 /* ARGSUSED */
 976 static void
 977 zvol_get_done(zgd_t *zgd, int error)
 978 {
 979         if (zgd->zgd_db)
 980                 dmu_buf_rele(zgd->zgd_db, zgd);
 981 
 982         rangelock_exit(zgd->zgd_lr);
 983 
 984         kmem_free(zgd, sizeof (zgd_t));
 985 }
 986 
 987 /*
 988  * Get data to generate a TX_WRITE intent log record.
 989  */
 990 static int
 991 zvol_get_data(void *arg, lr_write_t *lr, char *buf, struct lwb *lwb, zio_t *zio)
 992 {
 993         zvol_state_t *zv = arg;
 994         uint64_t offset = lr->lr_offset;
 995         uint64_t size = lr->lr_length;       /* length of user data */
 996         dmu_buf_t *db;
 997         zgd_t *zgd;
 998         int error;
 999 
1000         ASSERT3P(lwb, !=, NULL);
1001         ASSERT3P(zio, !=, NULL);
1002         ASSERT3U(size, !=, 0);
1003 
1004         zgd = kmem_zalloc(sizeof (zgd_t), KM_SLEEP);
1005         zgd->zgd_lwb = lwb;
1006 
1007         /*
1008          * Write records come in two flavors: immediate and indirect.
1009          * For small writes it's cheaper to store the data with the
1010          * log record (immediate); for large writes it's cheaper to
1011          * sync the data and get a pointer to it (indirect) so that
1012          * we don't have to write the data twice.
1013          */
1014         if (buf != NULL) { /* immediate write */
1015                 zgd->zgd_lr = rangelock_enter(&zv->zv_rangelock, offset, size,
1016                     RL_READER);
1017                 error = dmu_read_by_dnode(zv->zv_dn, offset, size, buf,
1018                     DMU_READ_NO_PREFETCH);
1019         } else { /* indirect write */
1020                 /*
1021                  * Have to lock the whole block to ensure when it's written out
1022                  * and its checksum is being calculated that no one can change
1023                  * the data. Contrarily to zfs_get_data we need not re-check
1024                  * blocksize after we get the lock because it cannot be changed.
1025                  */
1026                 size = zv->zv_volblocksize;
1027                 offset = P2ALIGN(offset, size);
1028                 zgd->zgd_lr = rangelock_enter(&zv->zv_rangelock, offset, size,
1029                     RL_READER);
1030                 error = dmu_buf_hold_by_dnode(zv->zv_dn, offset, zgd, &db,
1031                     DMU_READ_NO_PREFETCH);
1032                 if (error == 0) {
1033                         blkptr_t *bp = &lr->lr_blkptr;
1034 
1035                         zgd->zgd_db = db;
1036                         zgd->zgd_bp = bp;
1037 
1038                         ASSERT(db->db_offset == offset);
1039                         ASSERT(db->db_size == size);
1040 
1041                         error = dmu_sync(zio, lr->lr_common.lrc_txg,
1042                             zvol_get_done, zgd);
1043 
1044                         if (error == 0)
1045                                 return (0);
1046                 }
1047         }
1048 
1049         zvol_get_done(zgd, error);
1050 
1051         return (error);
1052 }
1053 
1054 /*
1055  * zvol_log_write() handles synchronous writes using TX_WRITE ZIL transactions.
1056  *
1057  * We store data in the log buffers if it's small enough.
1058  * Otherwise we will later flush the data out via dmu_sync().
1059  */
1060 ssize_t zvol_immediate_write_sz = 32768;
1061 
1062 static void
1063 zvol_log_write(zvol_state_t *zv, dmu_tx_t *tx, offset_t off, ssize_t resid,
1064     boolean_t sync)
1065 {
1066         uint32_t blocksize = zv->zv_volblocksize;
1067         zilog_t *zilog = zv->zv_zilog;
1068         itx_wr_state_t write_state;
1069 
1070         if (zil_replaying(zilog, tx))
1071                 return;
1072 
1073         if (zilog->zl_logbias == ZFS_LOGBIAS_THROUGHPUT)
1074                 write_state = WR_INDIRECT;
1075         else if (!spa_has_slogs(zilog->zl_spa) &&
1076             resid >= blocksize && blocksize > zvol_immediate_write_sz)
1077                 write_state = WR_INDIRECT;
1078         else if (sync)
1079                 write_state = WR_COPIED;
1080         else
1081                 write_state = WR_NEED_COPY;
1082 
1083         while (resid) {
1084                 itx_t *itx;
1085                 lr_write_t *lr;
1086                 itx_wr_state_t wr_state = write_state;
1087                 ssize_t len = resid;
1088 
1089                 if (wr_state == WR_COPIED && resid > ZIL_MAX_COPIED_DATA)
1090                         wr_state = WR_NEED_COPY;
1091                 else if (wr_state == WR_INDIRECT)
1092                         len = MIN(blocksize - P2PHASE(off, blocksize), resid);
1093 
1094                 itx = zil_itx_create(TX_WRITE, sizeof (*lr) +
1095                     (wr_state == WR_COPIED ? len : 0));
1096                 lr = (lr_write_t *)&itx->itx_lr;
1097                 if (wr_state == WR_COPIED && dmu_read_by_dnode(zv->zv_dn,
1098                     off, len, lr + 1, DMU_READ_NO_PREFETCH) != 0) {
1099                         zil_itx_destroy(itx);
1100                         itx = zil_itx_create(TX_WRITE, sizeof (*lr));
1101                         lr = (lr_write_t *)&itx->itx_lr;
1102                         wr_state = WR_NEED_COPY;
1103                 }
1104 
1105                 itx->itx_wr_state = wr_state;
1106                 lr->lr_foid = ZVOL_OBJ;
1107                 lr->lr_offset = off;
1108                 lr->lr_length = len;
1109                 lr->lr_blkoff = 0;
1110                 BP_ZERO(&lr->lr_blkptr);
1111 
1112                 itx->itx_private = zv;
1113                 itx->itx_sync = sync;
1114 
1115                 zil_itx_assign(zilog, itx, tx);
1116 
1117                 off += len;
1118                 resid -= len;
1119         }
1120 }
1121 
1122 static int
1123 zvol_dumpio_vdev(vdev_t *vd, void *addr, uint64_t offset, uint64_t origoffset,
1124     uint64_t size, boolean_t doread, boolean_t isdump)
1125 {
1126         vdev_disk_t *dvd;
1127         int c;
1128         int numerrors = 0;
1129 
1130         if (vd->vdev_ops == &vdev_mirror_ops ||
1131             vd->vdev_ops == &vdev_replacing_ops ||
1132             vd->vdev_ops == &vdev_spare_ops) {
1133                 for (c = 0; c < vd->vdev_children; c++) {
1134                         int err = zvol_dumpio_vdev(vd->vdev_child[c],
1135                             addr, offset, origoffset, size, doread, isdump);
1136                         if (err != 0) {
1137                                 numerrors++;
1138                         } else if (doread) {
1139                                 break;
1140                         }
1141                 }
1142         }
1143 
1144         if (!vd->vdev_ops->vdev_op_leaf && vd->vdev_ops != &vdev_raidz_ops)
1145                 return (numerrors < vd->vdev_children ? 0 : EIO);
1146 
1147         if (doread && !vdev_readable(vd))
1148                 return (SET_ERROR(EIO));
1149         else if (!doread && !vdev_writeable(vd))
1150                 return (SET_ERROR(EIO));
1151 
1152         if (vd->vdev_ops == &vdev_raidz_ops) {
1153                 return (vdev_raidz_physio(vd,
1154                     addr, size, offset, origoffset, doread, isdump));
1155         }
1156 
1157         offset += VDEV_LABEL_START_SIZE;
1158 
1159         if (ddi_in_panic() || isdump) {
1160                 ASSERT(!doread);
1161                 if (doread)
1162                         return (SET_ERROR(EIO));
1163                 dvd = vd->vdev_tsd;
1164                 ASSERT3P(dvd, !=, NULL);
1165                 return (ldi_dump(dvd->vd_lh, addr, lbtodb(offset),
1166                     lbtodb(size)));
1167         } else {
1168                 dvd = vd->vdev_tsd;
1169                 ASSERT3P(dvd, !=, NULL);
1170                 return (vdev_disk_ldi_physio(dvd->vd_lh, addr, size,
1171                     offset, doread ? B_READ : B_WRITE));
1172         }
1173 }
1174 
1175 static int
1176 zvol_dumpio(zvol_state_t *zv, void *addr, uint64_t offset, uint64_t size,
1177     boolean_t doread, boolean_t isdump)
1178 {
1179         vdev_t *vd;
1180         int error;
1181         zvol_extent_t *ze;
1182         spa_t *spa = dmu_objset_spa(zv->zv_objset);
1183 
1184         /* Must be sector aligned, and not stradle a block boundary. */
1185         if (P2PHASE(offset, DEV_BSIZE) || P2PHASE(size, DEV_BSIZE) ||
1186             P2BOUNDARY(offset, size, zv->zv_volblocksize)) {
1187                 return (SET_ERROR(EINVAL));
1188         }
1189         ASSERT(size <= zv->zv_volblocksize);
1190 
1191         /* Locate the extent this belongs to */
1192         ze = list_head(&zv->zv_extents);
1193         while (offset >= ze->ze_nblks * zv->zv_volblocksize) {
1194                 offset -= ze->ze_nblks * zv->zv_volblocksize;
1195                 ze = list_next(&zv->zv_extents, ze);
1196         }
1197 
1198         if (ze == NULL)
1199                 return (SET_ERROR(EINVAL));
1200 
1201         if (!ddi_in_panic())
1202                 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
1203 
1204         vd = vdev_lookup_top(spa, DVA_GET_VDEV(&ze->ze_dva));
1205         offset += DVA_GET_OFFSET(&ze->ze_dva);
1206         error = zvol_dumpio_vdev(vd, addr, offset, DVA_GET_OFFSET(&ze->ze_dva),
1207             size, doread, isdump);
1208 
1209         if (!ddi_in_panic())
1210                 spa_config_exit(spa, SCL_STATE, FTAG);
1211 
1212         return (error);
1213 }
1214 
1215 int
1216 zvol_strategy(buf_t *bp)
1217 {
1218         zfs_soft_state_t *zs = NULL;
1219         zvol_state_t *zv;
1220         uint64_t off, volsize;
1221         size_t resid;
1222         char *addr;
1223         objset_t *os;
1224         int error = 0;
1225         boolean_t doread = bp->b_flags & B_READ;
1226         boolean_t is_dumpified;
1227         boolean_t sync;
1228 
1229         if (getminor(bp->b_edev) == 0) {
1230                 error = SET_ERROR(EINVAL);
1231         } else {
1232                 zs = ddi_get_soft_state(zfsdev_state, getminor(bp->b_edev));
1233                 if (zs == NULL)
1234                         error = SET_ERROR(ENXIO);
1235                 else if (zs->zss_type != ZSST_ZVOL)
1236                         error = SET_ERROR(EINVAL);
1237         }
1238 
1239         if (error) {
1240                 bioerror(bp, error);
1241                 biodone(bp);
1242                 return (0);
1243         }
1244 
1245         zv = zs->zss_data;
1246 
1247         if (!(bp->b_flags & B_READ) && (zv->zv_flags & ZVOL_RDONLY)) {
1248                 bioerror(bp, EROFS);
1249                 biodone(bp);
1250                 return (0);
1251         }
1252 
1253         off = ldbtob(bp->b_blkno);
1254         volsize = zv->zv_volsize;
1255 
1256         os = zv->zv_objset;
1257         ASSERT(os != NULL);
1258 
1259         bp_mapin(bp);
1260         addr = bp->b_un.b_addr;
1261         resid = bp->b_bcount;
1262 
1263         if (resid > 0 && (off < 0 || off >= volsize)) {
1264                 bioerror(bp, EIO);
1265                 biodone(bp);
1266                 return (0);
1267         }
1268 
1269         is_dumpified = zv->zv_flags & ZVOL_DUMPIFIED;
1270         sync = ((!(bp->b_flags & B_ASYNC) &&
1271             !(zv->zv_flags & ZVOL_WCE)) ||
1272             (zv->zv_objset->os_sync == ZFS_SYNC_ALWAYS)) &&
1273             !doread && !is_dumpified;
1274 
1275         /*
1276          * There must be no buffer changes when doing a dmu_sync() because
1277          * we can't change the data whilst calculating the checksum.
1278          */
1279         locked_range_t *lr = rangelock_enter(&zv->zv_rangelock, off, resid,
1280             doread ? RL_READER : RL_WRITER);
1281 
1282         while (resid != 0 && off < volsize) {
1283                 size_t size = MIN(resid, zvol_maxphys);
1284                 if (is_dumpified) {
1285                         size = MIN(size, P2END(off, zv->zv_volblocksize) - off);
1286                         error = zvol_dumpio(zv, addr, off, size,
1287                             doread, B_FALSE);
1288                 } else if (doread) {
1289                         error = dmu_read(os, ZVOL_OBJ, off, size, addr,
1290                             DMU_READ_PREFETCH);
1291                 } else {
1292                         dmu_tx_t *tx = dmu_tx_create(os);
1293                         dmu_tx_hold_write(tx, ZVOL_OBJ, off, size);
1294                         error = dmu_tx_assign(tx, TXG_WAIT);
1295                         if (error) {
1296                                 dmu_tx_abort(tx);
1297                         } else {
1298                                 dmu_write(os, ZVOL_OBJ, off, size, addr, tx);
1299                                 zvol_log_write(zv, tx, off, size, sync);
1300                                 dmu_tx_commit(tx);
1301                         }
1302                 }
1303                 if (error) {
1304                         /* convert checksum errors into IO errors */
1305                         if (error == ECKSUM)
1306                                 error = SET_ERROR(EIO);
1307                         break;
1308                 }
1309                 off += size;
1310                 addr += size;
1311                 resid -= size;
1312         }
1313         rangelock_exit(lr);
1314 
1315         if ((bp->b_resid = resid) == bp->b_bcount)
1316                 bioerror(bp, off > volsize ? EINVAL : error);
1317 
1318         if (sync)
1319                 zil_commit(zv->zv_zilog, ZVOL_OBJ);
1320         biodone(bp);
1321 
1322         return (0);
1323 }
1324 
1325 /*
1326  * Set the buffer count to the zvol maximum transfer.
1327  * Using our own routine instead of the default minphys()
1328  * means that for larger writes we write bigger buffers on X86
1329  * (128K instead of 56K) and flush the disk write cache less often
1330  * (every zvol_maxphys - currently 1MB) instead of minphys (currently
1331  * 56K on X86 and 128K on sparc).
1332  */
1333 void
1334 zvol_minphys(struct buf *bp)
1335 {
1336         if (bp->b_bcount > zvol_maxphys)
1337                 bp->b_bcount = zvol_maxphys;
1338 }
1339 
1340 int
1341 zvol_dump(dev_t dev, caddr_t addr, daddr_t blkno, int nblocks)
1342 {
1343         minor_t minor = getminor(dev);
1344         zvol_state_t *zv;
1345         int error = 0;
1346         uint64_t size;
1347         uint64_t boff;
1348         uint64_t resid;
1349 
1350         zv = zfsdev_get_soft_state(minor, ZSST_ZVOL);
1351         if (zv == NULL)
1352                 return (SET_ERROR(ENXIO));
1353 
1354         if ((zv->zv_flags & ZVOL_DUMPIFIED) == 0)
1355                 return (SET_ERROR(EINVAL));
1356 
1357         boff = ldbtob(blkno);
1358         resid = ldbtob(nblocks);
1359 
1360         VERIFY3U(boff + resid, <=, zv->zv_volsize);
1361 
1362         while (resid) {
1363                 size = MIN(resid, P2END(boff, zv->zv_volblocksize) - boff);
1364                 error = zvol_dumpio(zv, addr, boff, size, B_FALSE, B_TRUE);
1365                 if (error)
1366                         break;
1367                 boff += size;
1368                 addr += size;
1369                 resid -= size;
1370         }
1371 
1372         return (error);
1373 }
1374 
1375 /*ARGSUSED*/
1376 int
1377 zvol_read(dev_t dev, uio_t *uio, cred_t *cr)
1378 {
1379         minor_t minor = getminor(dev);
1380         zvol_state_t *zv;
1381         uint64_t volsize;
1382         int error = 0;
1383 
1384         zv = zfsdev_get_soft_state(minor, ZSST_ZVOL);
1385         if (zv == NULL)
1386                 return (SET_ERROR(ENXIO));
1387 
1388         volsize = zv->zv_volsize;
1389         if (uio->uio_resid > 0 &&
1390             (uio->uio_loffset < 0 || uio->uio_loffset >= volsize))
1391                 return (SET_ERROR(EIO));
1392 
1393         if (zv->zv_flags & ZVOL_DUMPIFIED) {
1394                 error = physio(zvol_strategy, NULL, dev, B_READ,
1395                     zvol_minphys, uio);
1396                 return (error);
1397         }
1398 
1399         locked_range_t *lr = rangelock_enter(&zv->zv_rangelock,
1400             uio->uio_loffset, uio->uio_resid, RL_READER);
1401         while (uio->uio_resid > 0 && uio->uio_loffset < volsize) {
1402                 uint64_t bytes = MIN(uio->uio_resid, DMU_MAX_ACCESS >> 1);
1403 
1404                 /* don't read past the end */
1405                 if (bytes > volsize - uio->uio_loffset)
1406                         bytes = volsize - uio->uio_loffset;
1407 
1408                 error =  dmu_read_uio(zv->zv_objset, ZVOL_OBJ, uio, bytes);
1409                 if (error) {
1410                         /* convert checksum errors into IO errors */
1411                         if (error == ECKSUM)
1412                                 error = SET_ERROR(EIO);
1413                         break;
1414                 }
1415         }
1416         rangelock_exit(lr);
1417 
1418         return (error);
1419 }
1420 
1421 /*ARGSUSED*/
1422 int
1423 zvol_write(dev_t dev, uio_t *uio, cred_t *cr)
1424 {
1425         minor_t minor = getminor(dev);
1426         zvol_state_t *zv;
1427         uint64_t volsize;
1428         int error = 0;
1429         boolean_t sync;
1430 
1431         zv = zfsdev_get_soft_state(minor, ZSST_ZVOL);
1432         if (zv == NULL)
1433                 return (SET_ERROR(ENXIO));
1434 
1435         volsize = zv->zv_volsize;
1436         if (uio->uio_resid > 0 &&
1437             (uio->uio_loffset < 0 || uio->uio_loffset >= volsize))
1438                 return (SET_ERROR(EIO));
1439 
1440         if (zv->zv_flags & ZVOL_DUMPIFIED) {
1441                 error = physio(zvol_strategy, NULL, dev, B_WRITE,
1442                     zvol_minphys, uio);
1443                 return (error);
1444         }
1445 
1446         sync = !(zv->zv_flags & ZVOL_WCE) ||
1447             (zv->zv_objset->os_sync == ZFS_SYNC_ALWAYS);
1448 
1449         locked_range_t *lr = rangelock_enter(&zv->zv_rangelock,
1450             uio->uio_loffset, uio->uio_resid, RL_WRITER);
1451         while (uio->uio_resid > 0 && uio->uio_loffset < volsize) {
1452                 uint64_t bytes = MIN(uio->uio_resid, DMU_MAX_ACCESS >> 1);
1453                 uint64_t off = uio->uio_loffset;
1454                 dmu_tx_t *tx = dmu_tx_create(zv->zv_objset);
1455 
1456                 if (bytes > volsize - off)   /* don't write past the end */
1457                         bytes = volsize - off;
1458 
1459                 dmu_tx_hold_write(tx, ZVOL_OBJ, off, bytes);
1460                 error = dmu_tx_assign(tx, TXG_WAIT);
1461                 if (error) {
1462                         dmu_tx_abort(tx);
1463                         break;
1464                 }
1465                 error = dmu_write_uio_dnode(zv->zv_dn, uio, bytes, tx);
1466                 if (error == 0)
1467                         zvol_log_write(zv, tx, off, bytes, sync);
1468                 dmu_tx_commit(tx);
1469 
1470                 if (error)
1471                         break;
1472         }
1473         rangelock_exit(lr);
1474 
1475         if (sync)
1476                 zil_commit(zv->zv_zilog, ZVOL_OBJ);
1477         return (error);
1478 }
1479 
1480 int
1481 zvol_getefi(void *arg, int flag, uint64_t vs, uint8_t bs)
1482 {
1483         struct uuid uuid = EFI_RESERVED;
1484         efi_gpe_t gpe = { 0 };
1485         uint32_t crc;
1486         dk_efi_t efi;
1487         int length;
1488         char *ptr;
1489 
1490         if (ddi_copyin(arg, &efi, sizeof (dk_efi_t), flag))
1491                 return (SET_ERROR(EFAULT));
1492         ptr = (char *)(uintptr_t)efi.dki_data_64;
1493         length = efi.dki_length;
1494         /*
1495          * Some clients may attempt to request a PMBR for the
1496          * zvol.  Currently this interface will return EINVAL to
1497          * such requests.  These requests could be supported by
1498          * adding a check for lba == 0 and consing up an appropriate
1499          * PMBR.
1500          */
1501         if (efi.dki_lba < 1 || efi.dki_lba > 2 || length <= 0)
1502                 return (SET_ERROR(EINVAL));
1503 
1504         gpe.efi_gpe_StartingLBA = LE_64(34ULL);
1505         gpe.efi_gpe_EndingLBA = LE_64((vs >> bs) - 1);
1506         UUID_LE_CONVERT(gpe.efi_gpe_PartitionTypeGUID, uuid);
1507 
1508         if (efi.dki_lba == 1) {
1509                 efi_gpt_t gpt = { 0 };
1510 
1511                 gpt.efi_gpt_Signature = LE_64(EFI_SIGNATURE);
1512                 gpt.efi_gpt_Revision = LE_32(EFI_VERSION_CURRENT);
1513                 gpt.efi_gpt_HeaderSize = LE_32(EFI_HEADER_SIZE);
1514                 gpt.efi_gpt_MyLBA = LE_64(1ULL);
1515                 gpt.efi_gpt_FirstUsableLBA = LE_64(34ULL);
1516                 gpt.efi_gpt_LastUsableLBA = LE_64((vs >> bs) - 1);
1517                 gpt.efi_gpt_PartitionEntryLBA = LE_64(2ULL);
1518                 gpt.efi_gpt_NumberOfPartitionEntries = LE_32(1);
1519                 gpt.efi_gpt_SizeOfPartitionEntry =
1520                     LE_32(sizeof (efi_gpe_t));
1521                 CRC32(crc, &gpe, sizeof (gpe), -1U, crc32_table);
1522                 gpt.efi_gpt_PartitionEntryArrayCRC32 = LE_32(~crc);
1523                 CRC32(crc, &gpt, EFI_HEADER_SIZE, -1U, crc32_table);
1524                 gpt.efi_gpt_HeaderCRC32 = LE_32(~crc);
1525                 if (ddi_copyout(&gpt, ptr, MIN(sizeof (gpt), length),
1526                     flag))
1527                         return (SET_ERROR(EFAULT));
1528                 ptr += sizeof (gpt);
1529                 length -= sizeof (gpt);
1530         }
1531         if (length > 0 && ddi_copyout(&gpe, ptr, MIN(sizeof (gpe),
1532             length), flag))
1533                 return (SET_ERROR(EFAULT));
1534         return (0);
1535 }
1536 
1537 /*
1538  * BEGIN entry points to allow external callers access to the volume.
1539  */
1540 /*
1541  * Return the volume parameters needed for access from an external caller.
1542  * These values are invariant as long as the volume is held open.
1543  */
1544 int
1545 zvol_get_volume_params(minor_t minor, uint64_t *blksize,
1546     uint64_t *max_xfer_len, void **minor_hdl, void **objset_hdl, void **zil_hdl,
1547     void **rl_hdl, void **dnode_hdl)
1548 {
1549         zvol_state_t *zv;
1550 
1551         zv = zfsdev_get_soft_state(minor, ZSST_ZVOL);
1552         if (zv == NULL)
1553                 return (SET_ERROR(ENXIO));
1554         if (zv->zv_flags & ZVOL_DUMPIFIED)
1555                 return (SET_ERROR(ENXIO));
1556 
1557         ASSERT(blksize && max_xfer_len && minor_hdl &&
1558             objset_hdl && zil_hdl && rl_hdl && dnode_hdl);
1559 
1560         *blksize = zv->zv_volblocksize;
1561         *max_xfer_len = (uint64_t)zvol_maxphys;
1562         *minor_hdl = zv;
1563         *objset_hdl = zv->zv_objset;
1564         *zil_hdl = zv->zv_zilog;
1565         *rl_hdl = &zv->zv_rangelock;
1566         *dnode_hdl = zv->zv_dn;
1567         return (0);
1568 }
1569 
1570 /*
1571  * Return the current volume size to an external caller.
1572  * The size can change while the volume is open.
1573  */
1574 uint64_t
1575 zvol_get_volume_size(void *minor_hdl)
1576 {
1577         zvol_state_t *zv = minor_hdl;
1578 
1579         return (zv->zv_volsize);
1580 }
1581 
1582 /*
1583  * Return the current WCE setting to an external caller.
1584  * The WCE setting can change while the volume is open.
1585  */
1586 int
1587 zvol_get_volume_wce(void *minor_hdl)
1588 {
1589         zvol_state_t *zv = minor_hdl;
1590 
1591         return ((zv->zv_flags & ZVOL_WCE) ? 1 : 0);
1592 }
1593 
1594 /*
1595  * Entry point for external callers to zvol_log_write
1596  */
1597 void
1598 zvol_log_write_minor(void *minor_hdl, dmu_tx_t *tx, offset_t off, ssize_t resid,
1599     boolean_t sync)
1600 {
1601         zvol_state_t *zv = minor_hdl;
1602 
1603         zvol_log_write(zv, tx, off, resid, sync);
1604 }
1605 /*
1606  * END entry points to allow external callers access to the volume.
1607  */
1608 
1609 /*
1610  * Log a DKIOCFREE/free-long-range to the ZIL with TX_TRUNCATE.
1611  */
1612 static void
1613 zvol_log_truncate(zvol_state_t *zv, dmu_tx_t *tx, uint64_t off, uint64_t len,
1614     boolean_t sync)
1615 {
1616         itx_t *itx;
1617         lr_truncate_t *lr;
1618         zilog_t *zilog = zv->zv_zilog;
1619 
1620         if (zil_replaying(zilog, tx))
1621                 return;
1622 
1623         itx = zil_itx_create(TX_TRUNCATE, sizeof (*lr));
1624         lr = (lr_truncate_t *)&itx->itx_lr;
1625         lr->lr_foid = ZVOL_OBJ;
1626         lr->lr_offset = off;
1627         lr->lr_length = len;
1628 
1629         itx->itx_sync = sync;
1630         zil_itx_assign(zilog, itx, tx);
1631 }
1632 
1633 /*
1634  * Dirtbag ioctls to support mkfs(1M) for UFS filesystems.  See dkio(7I).
1635  * Also a dirtbag dkio ioctl for unmap/free-block functionality.
1636  */
1637 /*ARGSUSED*/
1638 int
1639 zvol_ioctl(dev_t dev, int cmd, intptr_t arg, int flag, cred_t *cr, int *rvalp)
1640 {
1641         zvol_state_t *zv;
1642         struct dk_callback *dkc;
1643         int error = 0;
1644         locked_range_t *lr;
1645 
1646         mutex_enter(&zfsdev_state_lock);
1647 
1648         zv = zfsdev_get_soft_state(getminor(dev), ZSST_ZVOL);
1649 
1650         if (zv == NULL) {
1651                 mutex_exit(&zfsdev_state_lock);
1652                 return (SET_ERROR(ENXIO));
1653         }
1654         ASSERT(zv->zv_total_opens > 0);
1655 
1656         switch (cmd) {
1657 
1658         case DKIOCINFO:
1659         {
1660                 struct dk_cinfo dki;
1661 
1662                 bzero(&dki, sizeof (dki));
1663                 (void) strcpy(dki.dki_cname, "zvol");
1664                 (void) strcpy(dki.dki_dname, "zvol");
1665                 dki.dki_ctype = DKC_UNKNOWN;
1666                 dki.dki_unit = getminor(dev);
1667                 dki.dki_maxtransfer =
1668                     1 << (SPA_OLD_MAXBLOCKSHIFT - zv->zv_min_bs);
1669                 mutex_exit(&zfsdev_state_lock);
1670                 if (ddi_copyout(&dki, (void *)arg, sizeof (dki), flag))
1671                         error = SET_ERROR(EFAULT);
1672                 return (error);
1673         }
1674 
1675         case DKIOCGMEDIAINFO:
1676         {
1677                 struct dk_minfo dkm;
1678 
1679                 bzero(&dkm, sizeof (dkm));
1680                 dkm.dki_lbsize = 1U << zv->zv_min_bs;
1681                 dkm.dki_capacity = zv->zv_volsize >> zv->zv_min_bs;
1682                 dkm.dki_media_type = DK_UNKNOWN;
1683                 mutex_exit(&zfsdev_state_lock);
1684                 if (ddi_copyout(&dkm, (void *)arg, sizeof (dkm), flag))
1685                         error = SET_ERROR(EFAULT);
1686                 return (error);
1687         }
1688 
1689         case DKIOCGMEDIAINFOEXT:
1690         {
1691                 struct dk_minfo_ext dkmext;
1692 
1693                 bzero(&dkmext, sizeof (dkmext));
1694                 dkmext.dki_lbsize = 1U << zv->zv_min_bs;
1695                 dkmext.dki_pbsize = zv->zv_volblocksize;
1696                 dkmext.dki_capacity = zv->zv_volsize >> zv->zv_min_bs;
1697                 dkmext.dki_media_type = DK_UNKNOWN;
1698                 mutex_exit(&zfsdev_state_lock);
1699                 if (ddi_copyout(&dkmext, (void *)arg, sizeof (dkmext), flag))
1700                         error = SET_ERROR(EFAULT);
1701                 return (error);
1702         }
1703 
1704         case DKIOCGETEFI:
1705         {
1706                 uint64_t vs = zv->zv_volsize;
1707                 uint8_t bs = zv->zv_min_bs;
1708 
1709                 mutex_exit(&zfsdev_state_lock);
1710                 error = zvol_getefi((void *)arg, flag, vs, bs);
1711                 return (error);
1712         }
1713 
1714         case DKIOCFLUSHWRITECACHE:
1715                 dkc = (struct dk_callback *)arg;
1716                 mutex_exit(&zfsdev_state_lock);
1717                 zil_commit(zv->zv_zilog, ZVOL_OBJ);
1718                 if ((flag & FKIOCTL) && dkc != NULL && dkc->dkc_callback) {
1719                         (*dkc->dkc_callback)(dkc->dkc_cookie, error);
1720                         error = 0;
1721                 }
1722                 return (error);
1723 
1724         case DKIOCGETWCE:
1725         {
1726                 int wce = (zv->zv_flags & ZVOL_WCE) ? 1 : 0;
1727                 if (ddi_copyout(&wce, (void *)arg, sizeof (int),
1728                     flag))
1729                         error = SET_ERROR(EFAULT);
1730                 break;
1731         }
1732         case DKIOCSETWCE:
1733         {
1734                 int wce;
1735                 if (ddi_copyin((void *)arg, &wce, sizeof (int),
1736                     flag)) {
1737                         error = SET_ERROR(EFAULT);
1738                         break;
1739                 }
1740                 if (wce) {
1741                         zv->zv_flags |= ZVOL_WCE;
1742                         mutex_exit(&zfsdev_state_lock);
1743                 } else {
1744                         zv->zv_flags &= ~ZVOL_WCE;
1745                         mutex_exit(&zfsdev_state_lock);
1746                         zil_commit(zv->zv_zilog, ZVOL_OBJ);
1747                 }
1748                 return (0);
1749         }
1750 
1751         case DKIOCGGEOM:
1752         case DKIOCGVTOC:
1753                 /*
1754                  * commands using these (like prtvtoc) expect ENOTSUP
1755                  * since we're emulating an EFI label
1756                  */
1757                 error = SET_ERROR(ENOTSUP);
1758                 break;
1759 
1760         case DKIOCDUMPINIT:
1761                 lr = rangelock_enter(&zv->zv_rangelock, 0, zv->zv_volsize,
1762                     RL_WRITER);
1763                 error = zvol_dumpify(zv);
1764                 rangelock_exit(lr);
1765                 break;
1766 
1767         case DKIOCDUMPFINI:
1768                 if (!(zv->zv_flags & ZVOL_DUMPIFIED))
1769                         break;
1770                 lr = rangelock_enter(&zv->zv_rangelock, 0, zv->zv_volsize,
1771                     RL_WRITER);
1772                 error = zvol_dump_fini(zv);
1773                 rangelock_exit(lr);
1774                 break;
1775 
1776         case DKIOCFREE:
1777         {
1778                 dkioc_free_list_t *dfl;
1779                 dmu_tx_t *tx;
1780 
1781                 if (!zvol_unmap_enabled)
1782                         break;
1783 
1784                 if (!(flag & FKIOCTL)) {
1785                         error = dfl_copyin((void *)arg, &dfl, flag, KM_SLEEP);
1786                         if (error != 0)
1787                                 break;
1788                 } else {
1789                         dfl = (dkioc_free_list_t *)arg;
1790                         ASSERT3U(dfl->dfl_num_exts, <=, DFL_COPYIN_MAX_EXTS);
1791                         if (dfl->dfl_num_exts > DFL_COPYIN_MAX_EXTS) {
1792                                 error = SET_ERROR(EINVAL);
1793                                 break;
1794                         }
1795                 }
1796 
1797                 mutex_exit(&zfsdev_state_lock);
1798 
1799                 for (int i = 0; i < dfl->dfl_num_exts; i++) {
1800                         uint64_t start = dfl->dfl_exts[i].dfle_start,
1801                             length = dfl->dfl_exts[i].dfle_length,
1802                             end = start + length;
1803 
1804                         /*
1805                          * Apply Postel's Law to length-checking.  If they
1806                          * overshoot, just blank out until the end, if there's
1807                          * a need to blank out anything.
1808                          */
1809                         if (start >= zv->zv_volsize)
1810                                 continue;       /* No need to do anything... */
1811                         if (end > zv->zv_volsize) {
1812                                 end = DMU_OBJECT_END;
1813                                 length = end - start;
1814                         }
1815 
1816                         lr = rangelock_enter(&zv->zv_rangelock, start, length,
1817                             RL_WRITER);
1818                         tx = dmu_tx_create(zv->zv_objset);
1819                         error = dmu_tx_assign(tx, TXG_WAIT);
1820                         if (error != 0) {
1821                                 dmu_tx_abort(tx);
1822                         } else {
1823                                 zvol_log_truncate(zv, tx, start, length,
1824                                     B_TRUE);
1825                                 dmu_tx_commit(tx);
1826                                 error = dmu_free_long_range(zv->zv_objset,
1827                                     ZVOL_OBJ, start, length);
1828                         }
1829 
1830                         rangelock_exit(lr);
1831 
1832                         if (error != 0)
1833                                 break;
1834                 }
1835 
1836                 /*
1837                  * If the write-cache is disabled, 'sync' property
1838                  * is set to 'always', or if the caller is asking for
1839                  * a synchronous free, commit this operation to the zil.
1840                  * This will sync any previous uncommitted writes to the
1841                  * zvol object.
1842                  * Can be overridden by the zvol_unmap_sync_enabled tunable.
1843                  */
1844                 if ((error == 0) && zvol_unmap_sync_enabled &&
1845                     (!(zv->zv_flags & ZVOL_WCE) ||
1846                     (zv->zv_objset->os_sync == ZFS_SYNC_ALWAYS) ||
1847                     (dfl->dfl_flags & DF_WAIT_SYNC))) {
1848                         zil_commit(zv->zv_zilog, ZVOL_OBJ);
1849                 }
1850 
1851                 if (!(flag & FKIOCTL))
1852                         dfl_free(dfl);
1853 
1854                 return (error);
1855         }
1856 
1857         default:
1858                 error = SET_ERROR(ENOTTY);
1859                 break;
1860 
1861         }
1862         mutex_exit(&zfsdev_state_lock);
1863         return (error);
1864 }
1865 
1866 int
1867 zvol_busy(void)
1868 {
1869         return (zvol_minors != 0);
1870 }
1871 
1872 void
1873 zvol_init(void)
1874 {
1875         VERIFY(ddi_soft_state_init(&zfsdev_state, sizeof (zfs_soft_state_t),
1876             1) == 0);
1877         mutex_init(&zfsdev_state_lock, NULL, MUTEX_DEFAULT, NULL);
1878 }
1879 
1880 void
1881 zvol_fini(void)
1882 {
1883         mutex_destroy(&zfsdev_state_lock);
1884         ddi_soft_state_fini(&zfsdev_state);
1885 }
1886 
1887 /*ARGSUSED*/
1888 static int
1889 zfs_mvdev_dump_feature_check(void *arg, dmu_tx_t *tx)
1890 {
1891         spa_t *spa = dmu_tx_pool(tx)->dp_spa;
1892 
1893         if (spa_feature_is_active(spa, SPA_FEATURE_MULTI_VDEV_CRASH_DUMP))
1894                 return (1);
1895         return (0);
1896 }
1897 
1898 /*ARGSUSED*/
1899 static void
1900 zfs_mvdev_dump_activate_feature_sync(void *arg, dmu_tx_t *tx)
1901 {
1902         spa_t *spa = dmu_tx_pool(tx)->dp_spa;
1903 
1904         spa_feature_incr(spa, SPA_FEATURE_MULTI_VDEV_CRASH_DUMP, tx);
1905 }
1906 
1907 static int
1908 zvol_dump_init(zvol_state_t *zv, boolean_t resize)
1909 {
1910         dmu_tx_t *tx;
1911         int error;
1912         objset_t *os = zv->zv_objset;
1913         spa_t *spa = dmu_objset_spa(os);
1914         vdev_t *vd = spa->spa_root_vdev;
1915         nvlist_t *nv = NULL;
1916         uint64_t version = spa_version(spa);
1917         uint64_t checksum, compress, refresrv, vbs, dedup;
1918 
1919         ASSERT(MUTEX_HELD(&zfsdev_state_lock));
1920         ASSERT(vd->vdev_ops == &vdev_root_ops);
1921 
1922         error = dmu_free_long_range(zv->zv_objset, ZVOL_OBJ, 0,
1923             DMU_OBJECT_END);
1924         if (error != 0)
1925                 return (error);
1926         /* wait for dmu_free_long_range to actually free the blocks */
1927         txg_wait_synced(dmu_objset_pool(zv->zv_objset), 0);
1928 
1929         /*
1930          * If the pool on which the dump device is being initialized has more
1931          * than one child vdev, check that the MULTI_VDEV_CRASH_DUMP feature is
1932          * enabled.  If so, bump that feature's counter to indicate that the
1933          * feature is active. We also check the vdev type to handle the
1934          * following case:
1935          *   # zpool create test raidz disk1 disk2 disk3
1936          *   Now have spa_root_vdev->vdev_children == 1 (the raidz vdev),
1937          *   the raidz vdev itself has 3 children.
1938          */
1939         if (vd->vdev_children > 1 || vd->vdev_ops == &vdev_raidz_ops) {
1940                 if (!spa_feature_is_enabled(spa,
1941                     SPA_FEATURE_MULTI_VDEV_CRASH_DUMP))
1942                         return (SET_ERROR(ENOTSUP));
1943                 (void) dsl_sync_task(spa_name(spa),
1944                     zfs_mvdev_dump_feature_check,
1945                     zfs_mvdev_dump_activate_feature_sync, NULL,
1946                     2, ZFS_SPACE_CHECK_RESERVED);
1947         }
1948 
1949         if (!resize) {
1950                 error = dsl_prop_get_integer(zv->zv_name,
1951                     zfs_prop_to_name(ZFS_PROP_COMPRESSION), &compress, NULL);
1952                 if (error == 0) {
1953                         error = dsl_prop_get_integer(zv->zv_name,
1954                             zfs_prop_to_name(ZFS_PROP_CHECKSUM), &checksum,
1955                             NULL);
1956                 }
1957                 if (error == 0) {
1958                         error = dsl_prop_get_integer(zv->zv_name,
1959                             zfs_prop_to_name(ZFS_PROP_REFRESERVATION),
1960                             &refresrv, NULL);
1961                 }
1962                 if (error == 0) {
1963                         error = dsl_prop_get_integer(zv->zv_name,
1964                             zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE), &vbs,
1965                             NULL);
1966                 }
1967                 if (version >= SPA_VERSION_DEDUP && error == 0) {
1968                         error = dsl_prop_get_integer(zv->zv_name,
1969                             zfs_prop_to_name(ZFS_PROP_DEDUP), &dedup, NULL);
1970                 }
1971         }
1972         if (error != 0)
1973                 return (error);
1974 
1975         tx = dmu_tx_create(os);
1976         dmu_tx_hold_zap(tx, ZVOL_ZAP_OBJ, TRUE, NULL);
1977         dmu_tx_hold_bonus(tx, ZVOL_OBJ);
1978         error = dmu_tx_assign(tx, TXG_WAIT);
1979         if (error != 0) {
1980                 dmu_tx_abort(tx);
1981                 return (error);
1982         }
1983 
1984         /*
1985          * If we are resizing the dump device then we only need to
1986          * update the refreservation to match the newly updated
1987          * zvolsize. Otherwise, we save off the original state of the
1988          * zvol so that we can restore them if the zvol is ever undumpified.
1989          */
1990         if (resize) {
1991                 error = zap_update(os, ZVOL_ZAP_OBJ,
1992                     zfs_prop_to_name(ZFS_PROP_REFRESERVATION), 8, 1,
1993                     &zv->zv_volsize, tx);
1994         } else {
1995                 error = zap_update(os, ZVOL_ZAP_OBJ,
1996                     zfs_prop_to_name(ZFS_PROP_COMPRESSION), 8, 1,
1997                     &compress, tx);
1998                 if (error == 0) {
1999                         error = zap_update(os, ZVOL_ZAP_OBJ,
2000                             zfs_prop_to_name(ZFS_PROP_CHECKSUM), 8, 1,
2001                             &checksum, tx);
2002                 }
2003                 if (error == 0) {
2004                         error = zap_update(os, ZVOL_ZAP_OBJ,
2005                             zfs_prop_to_name(ZFS_PROP_REFRESERVATION), 8, 1,
2006                             &refresrv, tx);
2007                 }
2008                 if (error == 0) {
2009                         error = zap_update(os, ZVOL_ZAP_OBJ,
2010                             zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE), 8, 1,
2011                             &vbs, tx);
2012                 }
2013                 if (error == 0) {
2014                         error = dmu_object_set_blocksize(
2015                             os, ZVOL_OBJ, SPA_OLD_MAXBLOCKSIZE, 0, tx);
2016                 }
2017                 if (version >= SPA_VERSION_DEDUP && error == 0) {
2018                         error = zap_update(os, ZVOL_ZAP_OBJ,
2019                             zfs_prop_to_name(ZFS_PROP_DEDUP), 8, 1,
2020                             &dedup, tx);
2021                 }
2022                 if (error == 0)
2023                         zv->zv_volblocksize = SPA_OLD_MAXBLOCKSIZE;
2024         }
2025         dmu_tx_commit(tx);
2026 
2027         /*
2028          * We only need update the zvol's property if we are initializing
2029          * the dump area for the first time.
2030          */
2031         if (error == 0 && !resize) {
2032                 /*
2033                  * If MULTI_VDEV_CRASH_DUMP is active, use the NOPARITY checksum
2034                  * function.  Otherwise, use the old default -- OFF.
2035                  */
2036                 checksum = spa_feature_is_active(spa,
2037                     SPA_FEATURE_MULTI_VDEV_CRASH_DUMP) ? ZIO_CHECKSUM_NOPARITY :
2038                     ZIO_CHECKSUM_OFF;
2039 
2040                 VERIFY(nvlist_alloc(&nv, NV_UNIQUE_NAME, KM_SLEEP) == 0);
2041                 VERIFY(nvlist_add_uint64(nv,
2042                     zfs_prop_to_name(ZFS_PROP_REFRESERVATION), 0) == 0);
2043                 VERIFY(nvlist_add_uint64(nv,
2044                     zfs_prop_to_name(ZFS_PROP_COMPRESSION),
2045                     ZIO_COMPRESS_OFF) == 0);
2046                 VERIFY(nvlist_add_uint64(nv,
2047                     zfs_prop_to_name(ZFS_PROP_CHECKSUM),
2048                     checksum) == 0);
2049                 if (version >= SPA_VERSION_DEDUP) {
2050                         VERIFY(nvlist_add_uint64(nv,
2051                             zfs_prop_to_name(ZFS_PROP_DEDUP),
2052                             ZIO_CHECKSUM_OFF) == 0);
2053                 }
2054 
2055                 error = zfs_set_prop_nvlist(zv->zv_name, ZPROP_SRC_LOCAL,
2056                     nv, NULL);
2057                 nvlist_free(nv);
2058         }
2059 
2060         /* Allocate the space for the dump */
2061         if (error == 0)
2062                 error = zvol_prealloc(zv);
2063         return (error);
2064 }
2065 
2066 static int
2067 zvol_dumpify(zvol_state_t *zv)
2068 {
2069         int error = 0;
2070         uint64_t dumpsize = 0;
2071         dmu_tx_t *tx;
2072         objset_t *os = zv->zv_objset;
2073 
2074         if (zv->zv_flags & ZVOL_RDONLY)
2075                 return (SET_ERROR(EROFS));
2076 
2077         if (zap_lookup(zv->zv_objset, ZVOL_ZAP_OBJ, ZVOL_DUMPSIZE,
2078             8, 1, &dumpsize) != 0 || dumpsize != zv->zv_volsize) {
2079                 boolean_t resize = (dumpsize > 0);
2080 
2081                 if ((error = zvol_dump_init(zv, resize)) != 0) {
2082                         (void) zvol_dump_fini(zv);
2083                         return (error);
2084                 }
2085         }
2086 
2087         /*
2088          * Build up our lba mapping.
2089          */
2090         error = zvol_get_lbas(zv);
2091         if (error) {
2092                 (void) zvol_dump_fini(zv);
2093                 return (error);
2094         }
2095 
2096         tx = dmu_tx_create(os);
2097         dmu_tx_hold_zap(tx, ZVOL_ZAP_OBJ, TRUE, NULL);
2098         error = dmu_tx_assign(tx, TXG_WAIT);
2099         if (error) {
2100                 dmu_tx_abort(tx);
2101                 (void) zvol_dump_fini(zv);
2102                 return (error);
2103         }
2104 
2105         zv->zv_flags |= ZVOL_DUMPIFIED;
2106         error = zap_update(os, ZVOL_ZAP_OBJ, ZVOL_DUMPSIZE, 8, 1,
2107             &zv->zv_volsize, tx);
2108         dmu_tx_commit(tx);
2109 
2110         if (error) {
2111                 (void) zvol_dump_fini(zv);
2112                 return (error);
2113         }
2114 
2115         txg_wait_synced(dmu_objset_pool(os), 0);
2116         return (0);
2117 }
2118 
2119 static int
2120 zvol_dump_fini(zvol_state_t *zv)
2121 {
2122         dmu_tx_t *tx;
2123         objset_t *os = zv->zv_objset;
2124         nvlist_t *nv;
2125         int error = 0;
2126         uint64_t checksum, compress, refresrv, vbs, dedup;
2127         uint64_t version = spa_version(dmu_objset_spa(zv->zv_objset));
2128 
2129         /*
2130          * Attempt to restore the zvol back to its pre-dumpified state.
2131          * This is a best-effort attempt as it's possible that not all
2132          * of these properties were initialized during the dumpify process
2133          * (i.e. error during zvol_dump_init).
2134          */
2135 
2136         tx = dmu_tx_create(os);
2137         dmu_tx_hold_zap(tx, ZVOL_ZAP_OBJ, TRUE, NULL);
2138         error = dmu_tx_assign(tx, TXG_WAIT);
2139         if (error) {
2140                 dmu_tx_abort(tx);
2141                 return (error);
2142         }
2143         (void) zap_remove(os, ZVOL_ZAP_OBJ, ZVOL_DUMPSIZE, tx);
2144         dmu_tx_commit(tx);
2145 
2146         (void) zap_lookup(zv->zv_objset, ZVOL_ZAP_OBJ,
2147             zfs_prop_to_name(ZFS_PROP_CHECKSUM), 8, 1, &checksum);
2148         (void) zap_lookup(zv->zv_objset, ZVOL_ZAP_OBJ,
2149             zfs_prop_to_name(ZFS_PROP_COMPRESSION), 8, 1, &compress);
2150         (void) zap_lookup(zv->zv_objset, ZVOL_ZAP_OBJ,
2151             zfs_prop_to_name(ZFS_PROP_REFRESERVATION), 8, 1, &refresrv);
2152         (void) zap_lookup(zv->zv_objset, ZVOL_ZAP_OBJ,
2153             zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE), 8, 1, &vbs);
2154 
2155         VERIFY(nvlist_alloc(&nv, NV_UNIQUE_NAME, KM_SLEEP) == 0);
2156         (void) nvlist_add_uint64(nv,
2157             zfs_prop_to_name(ZFS_PROP_CHECKSUM), checksum);
2158         (void) nvlist_add_uint64(nv,
2159             zfs_prop_to_name(ZFS_PROP_COMPRESSION), compress);
2160         (void) nvlist_add_uint64(nv,
2161             zfs_prop_to_name(ZFS_PROP_REFRESERVATION), refresrv);
2162         if (version >= SPA_VERSION_DEDUP &&
2163             zap_lookup(zv->zv_objset, ZVOL_ZAP_OBJ,
2164             zfs_prop_to_name(ZFS_PROP_DEDUP), 8, 1, &dedup) == 0) {
2165                 (void) nvlist_add_uint64(nv,
2166                     zfs_prop_to_name(ZFS_PROP_DEDUP), dedup);
2167         }
2168         (void) zfs_set_prop_nvlist(zv->zv_name, ZPROP_SRC_LOCAL,
2169             nv, NULL);
2170         nvlist_free(nv);
2171 
2172         zvol_free_extents(zv);
2173         zv->zv_flags &= ~ZVOL_DUMPIFIED;
2174         (void) dmu_free_long_range(os, ZVOL_OBJ, 0, DMU_OBJECT_END);
2175         /* wait for dmu_free_long_range to actually free the blocks */
2176         txg_wait_synced(dmu_objset_pool(zv->zv_objset), 0);
2177         tx = dmu_tx_create(os);
2178         dmu_tx_hold_bonus(tx, ZVOL_OBJ);
2179         error = dmu_tx_assign(tx, TXG_WAIT);
2180         if (error) {
2181                 dmu_tx_abort(tx);
2182                 return (error);
2183         }
2184         if (dmu_object_set_blocksize(os, ZVOL_OBJ, vbs, 0, tx) == 0)
2185                 zv->zv_volblocksize = vbs;
2186         dmu_tx_commit(tx);
2187 
2188         return (0);
2189 }