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