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