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