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