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