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