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