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