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