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