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