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