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