xref: /NextBSD/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zvol.c (revision 84d351007654069f9643c8e4b4802a7f5f08ee42)
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 (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
23  *
24  * Copyright (c) 2006-2010 Pawel Jakub Dawidek <pjd@FreeBSD.org>
25  * All rights reserved.
26  *
27  * Portions Copyright 2010 Robert Milkowski
28  *
29  * Copyright 2011 Nexenta Systems, Inc.  All rights reserved.
30  * Copyright (c) 2012, 2014 by Delphix. All rights reserved.
31  * Copyright (c) 2013, Joyent, Inc. All rights reserved.
32  */
33 
34 /* Portions Copyright 2011 Martin Matuska <mm@FreeBSD.org> */
35 
36 /*
37  * ZFS volume emulation driver.
38  *
39  * Makes a DMU object look like a volume of arbitrary size, up to 2^64 bytes.
40  * Volumes are accessed through the symbolic links named:
41  *
42  * /dev/zvol/dsk/<pool_name>/<dataset_name>
43  * /dev/zvol/rdsk/<pool_name>/<dataset_name>
44  *
45  * These links are created by the /dev filesystem (sdev_zvolops.c).
46  * Volumes are persistent through reboot.  No user command needs to be
47  * run before opening and using a device.
48  *
49  * FreeBSD notes.
50  * On FreeBSD ZVOLs are simply GEOM providers like any other storage device
51  * in the system.
52  */
53 
54 #include <sys/types.h>
55 #include <sys/param.h>
56 #include <sys/kernel.h>
57 #include <sys/errno.h>
58 #include <sys/uio.h>
59 #include <sys/bio.h>
60 #include <sys/buf.h>
61 #include <sys/kmem.h>
62 #include <sys/conf.h>
63 #include <sys/cmn_err.h>
64 #include <sys/stat.h>
65 #include <sys/zap.h>
66 #include <sys/spa.h>
67 #include <sys/spa_impl.h>
68 #include <sys/zio.h>
69 #include <sys/disk.h>
70 #include <sys/dmu_traverse.h>
71 #include <sys/dnode.h>
72 #include <sys/dsl_dataset.h>
73 #include <sys/dsl_prop.h>
74 #include <sys/dkio.h>
75 #include <sys/byteorder.h>
76 #include <sys/sunddi.h>
77 #include <sys/dirent.h>
78 #include <sys/policy.h>
79 #include <sys/queue.h>
80 #include <sys/fs/zfs.h>
81 #include <sys/zfs_ioctl.h>
82 #include <sys/zil.h>
83 #include <sys/refcount.h>
84 #include <sys/zfs_znode.h>
85 #include <sys/zfs_rlock.h>
86 #include <sys/vdev_impl.h>
87 #include <sys/vdev_raidz.h>
88 #include <sys/zvol.h>
89 #include <sys/zil_impl.h>
90 #include <sys/dbuf.h>
91 #include <sys/dmu_tx.h>
92 #include <sys/zfeature.h>
93 #include <sys/zio_checksum.h>
94 #include <sys/filio.h>
95 
96 #include <geom/geom.h>
97 
98 #include "zfs_namecheck.h"
99 
100 #ifndef illumos
101 struct g_class zfs_zvol_class = {
102 	.name = "ZFS::ZVOL",
103 	.version = G_VERSION,
104 };
105 
106 DECLARE_GEOM_CLASS(zfs_zvol_class, zfs_zvol);
107 
108 #endif
109 void *zfsdev_state;
110 static char *zvol_tag = "zvol_tag";
111 
112 #define	ZVOL_DUMPSIZE		"dumpsize"
113 
114 /*
115  * This lock protects the zfsdev_state structure from being modified
116  * while it's being used, e.g. an open that comes in before a create
117  * finishes.  It also protects temporary opens of the dataset so that,
118  * e.g., an open doesn't get a spurious EBUSY.
119  */
120 #ifdef illumos
121 kmutex_t zfsdev_state_lock;
122 #else
123 /*
124  * In FreeBSD we've replaced the upstream zfsdev_state_lock with the
125  * spa_namespace_lock in the ZVOL code.
126  */
127 #define zfsdev_state_lock spa_namespace_lock
128 #endif
129 static uint32_t zvol_minors;
130 
131 #ifndef illumos
132 SYSCTL_DECL(_vfs_zfs);
133 SYSCTL_NODE(_vfs_zfs, OID_AUTO, vol, CTLFLAG_RW, 0, "ZFS VOLUME");
134 static int	volmode = ZFS_VOLMODE_GEOM;
135 SYSCTL_INT(_vfs_zfs_vol, OID_AUTO, mode, CTLFLAG_RWTUN, &volmode, 0,
136     "Expose as GEOM providers (1), device files (2) or neither");
137 
138 #endif
139 typedef struct zvol_extent {
140 	list_node_t	ze_node;
141 	dva_t		ze_dva;		/* dva associated with this extent */
142 	uint64_t	ze_nblks;	/* number of blocks in extent */
143 } zvol_extent_t;
144 
145 /*
146  * The in-core state of each volume.
147  */
148 typedef struct zvol_state {
149 #ifndef illumos
150 	LIST_ENTRY(zvol_state)	zv_links;
151 #endif
152 	char		zv_name[MAXPATHLEN]; /* pool/dd name */
153 	uint64_t	zv_volsize;	/* amount of space we advertise */
154 	uint64_t	zv_volblocksize; /* volume block size */
155 #ifdef illumos
156 	minor_t		zv_minor;	/* minor number */
157 #else
158 	struct cdev	*zv_dev;	/* non-GEOM device */
159 	struct g_provider *zv_provider;	/* GEOM provider */
160 #endif
161 	uint8_t		zv_min_bs;	/* minimum addressable block shift */
162 	uint8_t		zv_flags;	/* readonly, dumpified, etc. */
163 	objset_t	*zv_objset;	/* objset handle */
164 #ifdef illumos
165 	uint32_t	zv_open_count[OTYPCNT];	/* open counts */
166 #endif
167 	uint32_t	zv_total_opens;	/* total open count */
168 	zilog_t		*zv_zilog;	/* ZIL handle */
169 	list_t		zv_extents;	/* List of extents for dump */
170 	znode_t		zv_znode;	/* for range locking */
171 	dmu_buf_t	*zv_dbuf;	/* bonus handle */
172 #ifndef illumos
173 	int		zv_state;
174 	int		zv_volmode;	/* Provide GEOM or cdev */
175 	struct bio_queue_head zv_queue;
176 	struct mtx	zv_queue_mtx;	/* zv_queue mutex */
177 #endif
178 } zvol_state_t;
179 
180 #ifndef illumos
181 static LIST_HEAD(, zvol_state) all_zvols;
182 #endif
183 /*
184  * zvol specific flags
185  */
186 #define	ZVOL_RDONLY	0x1
187 #define	ZVOL_DUMPIFIED	0x2
188 #define	ZVOL_EXCL	0x4
189 #define	ZVOL_WCE	0x8
190 
191 /*
192  * zvol maximum transfer in one DMU tx.
193  */
194 int zvol_maxphys = DMU_MAX_ACCESS/2;
195 
196 /*
197  * Toggle unmap functionality.
198  */
199 boolean_t zvol_unmap_enabled = B_TRUE;
200 #ifndef illumos
201 SYSCTL_INT(_vfs_zfs_vol, OID_AUTO, unmap_enabled, CTLFLAG_RWTUN,
202     &zvol_unmap_enabled, 0,
203     "Enable UNMAP functionality");
204 
205 static d_open_t		zvol_d_open;
206 static d_close_t	zvol_d_close;
207 static d_read_t		zvol_read;
208 static d_write_t	zvol_write;
209 static d_ioctl_t	zvol_d_ioctl;
210 static d_strategy_t	zvol_strategy;
211 
212 static struct cdevsw zvol_cdevsw = {
213 	.d_version =	D_VERSION,
214 	.d_open =	zvol_d_open,
215 	.d_close =	zvol_d_close,
216 	.d_read =	zvol_read,
217 	.d_write =	zvol_write,
218 	.d_ioctl =	zvol_d_ioctl,
219 	.d_strategy =	zvol_strategy,
220 	.d_name =	"zvol",
221 	.d_flags =	D_DISK | D_TRACKCLOSE,
222 };
223 
224 static void zvol_geom_run(zvol_state_t *zv);
225 static void zvol_geom_destroy(zvol_state_t *zv);
226 static int zvol_geom_access(struct g_provider *pp, int acr, int acw, int ace);
227 static void zvol_geom_start(struct bio *bp);
228 static void zvol_geom_worker(void *arg);
229 static void zvol_log_truncate(zvol_state_t *zv, dmu_tx_t *tx, uint64_t off,
230     uint64_t len, boolean_t sync);
231 #endif	/* !illumos */
232 
233 extern int zfs_set_prop_nvlist(const char *, zprop_source_t,
234     nvlist_t *, nvlist_t *);
235 static int zvol_remove_zv(zvol_state_t *);
236 static int zvol_get_data(void *arg, lr_write_t *lr, char *buf, zio_t *zio);
237 static int zvol_dumpify(zvol_state_t *zv);
238 static int zvol_dump_fini(zvol_state_t *zv);
239 static int zvol_dump_init(zvol_state_t *zv, boolean_t resize);
240 
241 static void
zvol_size_changed(zvol_state_t * zv,uint64_t volsize)242 zvol_size_changed(zvol_state_t *zv, uint64_t volsize)
243 {
244 #ifdef illumos
245 	dev_t dev = makedevice(ddi_driver_major(zfs_dip), zv->zv_minor);
246 
247 	zv->zv_volsize = volsize;
248 	VERIFY(ddi_prop_update_int64(dev, zfs_dip,
249 	    "Size", volsize) == DDI_SUCCESS);
250 	VERIFY(ddi_prop_update_int64(dev, zfs_dip,
251 	    "Nblocks", lbtodb(volsize)) == DDI_SUCCESS);
252 
253 	/* Notify specfs to invalidate the cached size */
254 	spec_size_invalidate(dev, VBLK);
255 	spec_size_invalidate(dev, VCHR);
256 #else	/* !illumos */
257 	zv->zv_volsize = volsize;
258 	if (zv->zv_volmode == ZFS_VOLMODE_GEOM) {
259 		struct g_provider *pp;
260 
261 		pp = zv->zv_provider;
262 		if (pp == NULL)
263 			return;
264 		g_topology_lock();
265 		g_resize_provider(pp, zv->zv_volsize);
266 		g_topology_unlock();
267 	}
268 #endif	/* illumos */
269 }
270 
271 int
zvol_check_volsize(uint64_t volsize,uint64_t blocksize)272 zvol_check_volsize(uint64_t volsize, uint64_t blocksize)
273 {
274 	if (volsize == 0)
275 		return (SET_ERROR(EINVAL));
276 
277 	if (volsize % blocksize != 0)
278 		return (SET_ERROR(EINVAL));
279 
280 #ifdef _ILP32
281 	if (volsize - 1 > SPEC_MAXOFFSET_T)
282 		return (SET_ERROR(EOVERFLOW));
283 #endif
284 	return (0);
285 }
286 
287 int
zvol_check_volblocksize(uint64_t volblocksize)288 zvol_check_volblocksize(uint64_t volblocksize)
289 {
290 	if (volblocksize < SPA_MINBLOCKSIZE ||
291 	    volblocksize > SPA_OLD_MAXBLOCKSIZE ||
292 	    !ISP2(volblocksize))
293 		return (SET_ERROR(EDOM));
294 
295 	return (0);
296 }
297 
298 int
zvol_get_stats(objset_t * os,nvlist_t * nv)299 zvol_get_stats(objset_t *os, nvlist_t *nv)
300 {
301 	int error;
302 	dmu_object_info_t doi;
303 	uint64_t val;
304 
305 	error = zap_lookup(os, ZVOL_ZAP_OBJ, "size", 8, 1, &val);
306 	if (error)
307 		return (error);
308 
309 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_VOLSIZE, val);
310 
311 	error = dmu_object_info(os, ZVOL_OBJ, &doi);
312 
313 	if (error == 0) {
314 		dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_VOLBLOCKSIZE,
315 		    doi.doi_data_block_size);
316 	}
317 
318 	return (error);
319 }
320 
321 static zvol_state_t *
zvol_minor_lookup(const char * name)322 zvol_minor_lookup(const char *name)
323 {
324 #ifdef illumos
325 	minor_t minor;
326 #endif
327 	zvol_state_t *zv;
328 
329 	ASSERT(MUTEX_HELD(&zfsdev_state_lock));
330 
331 #ifdef illumos
332 	for (minor = 1; minor <= ZFSDEV_MAX_MINOR; minor++) {
333 		zv = zfsdev_get_soft_state(minor, ZSST_ZVOL);
334 		if (zv == NULL)
335 			continue;
336 #else
337 	LIST_FOREACH(zv, &all_zvols, zv_links) {
338 #endif
339 		if (strcmp(zv->zv_name, name) == 0)
340 			return (zv);
341 	}
342 
343 	return (NULL);
344 }
345 
346 /* extent mapping arg */
347 struct maparg {
348 	zvol_state_t	*ma_zv;
349 	uint64_t	ma_blks;
350 };
351 
352 /*ARGSUSED*/
353 static int
354 zvol_map_block(spa_t *spa, zilog_t *zilog, const blkptr_t *bp,
355     const zbookmark_phys_t *zb, const dnode_phys_t *dnp, void *arg)
356 {
357 	struct maparg *ma = arg;
358 	zvol_extent_t *ze;
359 	int bs = ma->ma_zv->zv_volblocksize;
360 
361 	if (bp == NULL || BP_IS_HOLE(bp) ||
362 	    zb->zb_object != ZVOL_OBJ || zb->zb_level != 0)
363 		return (0);
364 
365 	VERIFY(!BP_IS_EMBEDDED(bp));
366 
367 	VERIFY3U(ma->ma_blks, ==, zb->zb_blkid);
368 	ma->ma_blks++;
369 
370 	/* Abort immediately if we have encountered gang blocks */
371 	if (BP_IS_GANG(bp))
372 		return (SET_ERROR(EFRAGS));
373 
374 	/*
375 	 * See if the block is at the end of the previous extent.
376 	 */
377 	ze = list_tail(&ma->ma_zv->zv_extents);
378 	if (ze &&
379 	    DVA_GET_VDEV(BP_IDENTITY(bp)) == DVA_GET_VDEV(&ze->ze_dva) &&
380 	    DVA_GET_OFFSET(BP_IDENTITY(bp)) ==
381 	    DVA_GET_OFFSET(&ze->ze_dva) + ze->ze_nblks * bs) {
382 		ze->ze_nblks++;
383 		return (0);
384 	}
385 
386 	dprintf_bp(bp, "%s", "next blkptr:");
387 
388 	/* start a new extent */
389 	ze = kmem_zalloc(sizeof (zvol_extent_t), KM_SLEEP);
390 	ze->ze_dva = bp->blk_dva[0];	/* structure assignment */
391 	ze->ze_nblks = 1;
392 	list_insert_tail(&ma->ma_zv->zv_extents, ze);
393 	return (0);
394 }
395 
396 static void
397 zvol_free_extents(zvol_state_t *zv)
398 {
399 	zvol_extent_t *ze;
400 
401 	while (ze = list_head(&zv->zv_extents)) {
402 		list_remove(&zv->zv_extents, ze);
403 		kmem_free(ze, sizeof (zvol_extent_t));
404 	}
405 }
406 
407 static int
408 zvol_get_lbas(zvol_state_t *zv)
409 {
410 	objset_t *os = zv->zv_objset;
411 	struct maparg	ma;
412 	int		err;
413 
414 	ma.ma_zv = zv;
415 	ma.ma_blks = 0;
416 	zvol_free_extents(zv);
417 
418 	/* commit any in-flight changes before traversing the dataset */
419 	txg_wait_synced(dmu_objset_pool(os), 0);
420 	err = traverse_dataset(dmu_objset_ds(os), 0,
421 	    TRAVERSE_PRE | TRAVERSE_PREFETCH_METADATA, zvol_map_block, &ma);
422 	if (err || ma.ma_blks != (zv->zv_volsize / zv->zv_volblocksize)) {
423 		zvol_free_extents(zv);
424 		return (err ? err : EIO);
425 	}
426 
427 	return (0);
428 }
429 
430 /* ARGSUSED */
431 void
432 zvol_create_cb(objset_t *os, void *arg, cred_t *cr, dmu_tx_t *tx)
433 {
434 	zfs_creat_t *zct = arg;
435 	nvlist_t *nvprops = zct->zct_props;
436 	int error;
437 	uint64_t volblocksize, volsize;
438 
439 	VERIFY(nvlist_lookup_uint64(nvprops,
440 	    zfs_prop_to_name(ZFS_PROP_VOLSIZE), &volsize) == 0);
441 	if (nvlist_lookup_uint64(nvprops,
442 	    zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE), &volblocksize) != 0)
443 		volblocksize = zfs_prop_default_numeric(ZFS_PROP_VOLBLOCKSIZE);
444 
445 	/*
446 	 * These properties must be removed from the list so the generic
447 	 * property setting step won't apply to them.
448 	 */
449 	VERIFY(nvlist_remove_all(nvprops,
450 	    zfs_prop_to_name(ZFS_PROP_VOLSIZE)) == 0);
451 	(void) nvlist_remove_all(nvprops,
452 	    zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE));
453 
454 	error = dmu_object_claim(os, ZVOL_OBJ, DMU_OT_ZVOL, volblocksize,
455 	    DMU_OT_NONE, 0, tx);
456 	ASSERT(error == 0);
457 
458 	error = zap_create_claim(os, ZVOL_ZAP_OBJ, DMU_OT_ZVOL_PROP,
459 	    DMU_OT_NONE, 0, tx);
460 	ASSERT(error == 0);
461 
462 	error = zap_update(os, ZVOL_ZAP_OBJ, "size", 8, 1, &volsize, tx);
463 	ASSERT(error == 0);
464 }
465 
466 /*
467  * Replay a TX_TRUNCATE ZIL transaction if asked.  TX_TRUNCATE is how we
468  * implement DKIOCFREE/free-long-range.
469  */
470 static int
471 zvol_replay_truncate(zvol_state_t *zv, lr_truncate_t *lr, boolean_t byteswap)
472 {
473 	uint64_t offset, length;
474 
475 	if (byteswap)
476 		byteswap_uint64_array(lr, sizeof (*lr));
477 
478 	offset = lr->lr_offset;
479 	length = lr->lr_length;
480 
481 	return (dmu_free_long_range(zv->zv_objset, ZVOL_OBJ, offset, length));
482 }
483 
484 /*
485  * Replay a TX_WRITE ZIL transaction that didn't get committed
486  * after a system failure
487  */
488 static int
489 zvol_replay_write(zvol_state_t *zv, lr_write_t *lr, boolean_t byteswap)
490 {
491 	objset_t *os = zv->zv_objset;
492 	char *data = (char *)(lr + 1);	/* data follows lr_write_t */
493 	uint64_t offset, length;
494 	dmu_tx_t *tx;
495 	int error;
496 
497 	if (byteswap)
498 		byteswap_uint64_array(lr, sizeof (*lr));
499 
500 	offset = lr->lr_offset;
501 	length = lr->lr_length;
502 
503 	/* If it's a dmu_sync() block, write the whole block */
504 	if (lr->lr_common.lrc_reclen == sizeof (lr_write_t)) {
505 		uint64_t blocksize = BP_GET_LSIZE(&lr->lr_blkptr);
506 		if (length < blocksize) {
507 			offset -= offset % blocksize;
508 			length = blocksize;
509 		}
510 	}
511 
512 	tx = dmu_tx_create(os);
513 	dmu_tx_hold_write(tx, ZVOL_OBJ, offset, length);
514 	error = dmu_tx_assign(tx, TXG_WAIT);
515 	if (error) {
516 		dmu_tx_abort(tx);
517 	} else {
518 		dmu_write(os, ZVOL_OBJ, offset, length, data, tx);
519 		dmu_tx_commit(tx);
520 	}
521 
522 	return (error);
523 }
524 
525 /* ARGSUSED */
526 static int
527 zvol_replay_err(zvol_state_t *zv, lr_t *lr, boolean_t byteswap)
528 {
529 	return (SET_ERROR(ENOTSUP));
530 }
531 
532 /*
533  * Callback vectors for replaying records.
534  * Only TX_WRITE and TX_TRUNCATE are needed for zvol.
535  */
536 zil_replay_func_t *zvol_replay_vector[TX_MAX_TYPE] = {
537 	zvol_replay_err,	/* 0 no such transaction type */
538 	zvol_replay_err,	/* TX_CREATE */
539 	zvol_replay_err,	/* TX_MKDIR */
540 	zvol_replay_err,	/* TX_MKXATTR */
541 	zvol_replay_err,	/* TX_SYMLINK */
542 	zvol_replay_err,	/* TX_REMOVE */
543 	zvol_replay_err,	/* TX_RMDIR */
544 	zvol_replay_err,	/* TX_LINK */
545 	zvol_replay_err,	/* TX_RENAME */
546 	zvol_replay_write,	/* TX_WRITE */
547 	zvol_replay_truncate,	/* TX_TRUNCATE */
548 	zvol_replay_err,	/* TX_SETATTR */
549 	zvol_replay_err,	/* TX_ACL */
550 	zvol_replay_err,	/* TX_CREATE_ACL */
551 	zvol_replay_err,	/* TX_CREATE_ATTR */
552 	zvol_replay_err,	/* TX_CREATE_ACL_ATTR */
553 	zvol_replay_err,	/* TX_MKDIR_ACL */
554 	zvol_replay_err,	/* TX_MKDIR_ATTR */
555 	zvol_replay_err,	/* TX_MKDIR_ACL_ATTR */
556 	zvol_replay_err,	/* TX_WRITE2 */
557 };
558 
559 #ifdef illumos
560 int
561 zvol_name2minor(const char *name, minor_t *minor)
562 {
563 	zvol_state_t *zv;
564 
565 	mutex_enter(&zfsdev_state_lock);
566 	zv = zvol_minor_lookup(name);
567 	if (minor && zv)
568 		*minor = zv->zv_minor;
569 	mutex_exit(&zfsdev_state_lock);
570 	return (zv ? 0 : -1);
571 }
572 #endif	/* illumos */
573 
574 /*
575  * Create a minor node (plus a whole lot more) for the specified volume.
576  */
577 int
578 zvol_create_minor(const char *name)
579 {
580 	zfs_soft_state_t *zs;
581 	zvol_state_t *zv;
582 	objset_t *os;
583 	dmu_object_info_t doi;
584 #ifdef illumos
585 	minor_t minor = 0;
586 	char chrbuf[30], blkbuf[30];
587 #else
588 	struct cdev *dev;
589 	struct g_provider *pp;
590 	struct g_geom *gp;
591 	uint64_t volsize, mode;
592 #endif
593 	int error;
594 
595 #ifndef illumos
596 	ZFS_LOG(1, "Creating ZVOL %s...", name);
597 #endif
598 
599 	mutex_enter(&zfsdev_state_lock);
600 
601 	if (zvol_minor_lookup(name) != NULL) {
602 		mutex_exit(&zfsdev_state_lock);
603 		return (SET_ERROR(EEXIST));
604 	}
605 
606 	/* lie and say we're read-only */
607 	error = dmu_objset_own(name, DMU_OST_ZVOL, B_TRUE, FTAG, &os);
608 
609 	if (error) {
610 		mutex_exit(&zfsdev_state_lock);
611 		return (error);
612 	}
613 
614 #ifdef illumos
615 	if ((minor = zfsdev_minor_alloc()) == 0) {
616 		dmu_objset_disown(os, FTAG);
617 		mutex_exit(&zfsdev_state_lock);
618 		return (SET_ERROR(ENXIO));
619 	}
620 
621 	if (ddi_soft_state_zalloc(zfsdev_state, minor) != DDI_SUCCESS) {
622 		dmu_objset_disown(os, FTAG);
623 		mutex_exit(&zfsdev_state_lock);
624 		return (SET_ERROR(EAGAIN));
625 	}
626 	(void) ddi_prop_update_string(minor, zfs_dip, ZVOL_PROP_NAME,
627 	    (char *)name);
628 
629 	(void) snprintf(chrbuf, sizeof (chrbuf), "%u,raw", minor);
630 
631 	if (ddi_create_minor_node(zfs_dip, chrbuf, S_IFCHR,
632 	    minor, DDI_PSEUDO, 0) == DDI_FAILURE) {
633 		ddi_soft_state_free(zfsdev_state, minor);
634 		dmu_objset_disown(os, FTAG);
635 		mutex_exit(&zfsdev_state_lock);
636 		return (SET_ERROR(EAGAIN));
637 	}
638 
639 	(void) snprintf(blkbuf, sizeof (blkbuf), "%u", minor);
640 
641 	if (ddi_create_minor_node(zfs_dip, blkbuf, S_IFBLK,
642 	    minor, DDI_PSEUDO, 0) == DDI_FAILURE) {
643 		ddi_remove_minor_node(zfs_dip, chrbuf);
644 		ddi_soft_state_free(zfsdev_state, minor);
645 		dmu_objset_disown(os, FTAG);
646 		mutex_exit(&zfsdev_state_lock);
647 		return (SET_ERROR(EAGAIN));
648 	}
649 
650 	zs = ddi_get_soft_state(zfsdev_state, minor);
651 	zs->zss_type = ZSST_ZVOL;
652 	zv = zs->zss_data = kmem_zalloc(sizeof (zvol_state_t), KM_SLEEP);
653 #else	/* !illumos */
654 
655 	zv = kmem_zalloc(sizeof(*zv), KM_SLEEP);
656 	zv->zv_state = 0;
657 	error = zap_lookup(os, ZVOL_ZAP_OBJ, "size", 8, 1, &volsize);
658 	if (error) {
659 		kmem_free(zv, sizeof(*zv));
660 		dmu_objset_disown(os, zvol_tag);
661 		mutex_exit(&zfsdev_state_lock);
662 		return (error);
663 	}
664 	error = dsl_prop_get_integer(name,
665 	    zfs_prop_to_name(ZFS_PROP_VOLMODE), &mode, NULL);
666 	if (error != 0 || mode == ZFS_VOLMODE_DEFAULT)
667 		mode = volmode;
668 
669 	DROP_GIANT();
670 	zv->zv_volsize = volsize;
671 	zv->zv_volmode = mode;
672 	if (zv->zv_volmode == ZFS_VOLMODE_GEOM) {
673 		g_topology_lock();
674 		gp = g_new_geomf(&zfs_zvol_class, "zfs::zvol::%s", name);
675 		gp->start = zvol_geom_start;
676 		gp->access = zvol_geom_access;
677 		pp = g_new_providerf(gp, "%s/%s", ZVOL_DRIVER, name);
678 		pp->flags |= G_PF_DIRECT_RECEIVE | G_PF_DIRECT_SEND;
679 		pp->sectorsize = DEV_BSIZE;
680 		pp->mediasize = zv->zv_volsize;
681 		pp->private = zv;
682 
683 		zv->zv_provider = pp;
684 		bioq_init(&zv->zv_queue);
685 		mtx_init(&zv->zv_queue_mtx, "zvol", NULL, MTX_DEF);
686 	} else if (zv->zv_volmode == ZFS_VOLMODE_DEV) {
687 		if (make_dev_p(MAKEDEV_CHECKNAME | MAKEDEV_WAITOK,
688 		    &dev, &zvol_cdevsw, NULL, UID_ROOT, GID_OPERATOR,
689 		    0640, "%s/%s", ZVOL_DRIVER, name) != 0) {
690 			kmem_free(zv, sizeof(*zv));
691 			dmu_objset_disown(os, FTAG);
692 			mutex_exit(&zfsdev_state_lock);
693 			return (SET_ERROR(ENXIO));
694 		}
695 		zv->zv_dev = dev;
696 		dev->si_iosize_max = MAXPHYS;
697 		dev->si_drv2 = zv;
698 	}
699 	LIST_INSERT_HEAD(&all_zvols, zv, zv_links);
700 #endif	/* illumos */
701 
702 	(void) strlcpy(zv->zv_name, name, MAXPATHLEN);
703 	zv->zv_min_bs = DEV_BSHIFT;
704 #ifdef illumos
705 	zv->zv_minor = minor;
706 #endif
707 	zv->zv_objset = os;
708 	if (dmu_objset_is_snapshot(os) || !spa_writeable(dmu_objset_spa(os)))
709 		zv->zv_flags |= ZVOL_RDONLY;
710 	mutex_init(&zv->zv_znode.z_range_lock, NULL, MUTEX_DEFAULT, NULL);
711 	avl_create(&zv->zv_znode.z_range_avl, zfs_range_compare,
712 	    sizeof (rl_t), offsetof(rl_t, r_node));
713 	list_create(&zv->zv_extents, sizeof (zvol_extent_t),
714 	    offsetof(zvol_extent_t, ze_node));
715 	/* get and cache the blocksize */
716 	error = dmu_object_info(os, ZVOL_OBJ, &doi);
717 	ASSERT(error == 0);
718 	zv->zv_volblocksize = doi.doi_data_block_size;
719 
720 	if (spa_writeable(dmu_objset_spa(os))) {
721 		if (zil_replay_disable)
722 			zil_destroy(dmu_objset_zil(os), B_FALSE);
723 		else
724 			zil_replay(os, zv, zvol_replay_vector);
725 	}
726 	dmu_objset_disown(os, FTAG);
727 	zv->zv_objset = NULL;
728 
729 	zvol_minors++;
730 
731 	mutex_exit(&zfsdev_state_lock);
732 #ifndef illumos
733 	if (zv->zv_volmode == ZFS_VOLMODE_GEOM) {
734 		zvol_geom_run(zv);
735 		g_topology_unlock();
736 	}
737 	PICKUP_GIANT();
738 
739 	ZFS_LOG(1, "ZVOL %s created.", name);
740 #endif
741 
742 	return (0);
743 }
744 
745 /*
746  * Remove minor node for the specified volume.
747  */
748 static int
749 zvol_remove_zv(zvol_state_t *zv)
750 {
751 #ifdef illumos
752 	char nmbuf[20];
753 	minor_t minor = zv->zv_minor;
754 #endif
755 
756 	ASSERT(MUTEX_HELD(&zfsdev_state_lock));
757 	if (zv->zv_total_opens != 0)
758 		return (SET_ERROR(EBUSY));
759 
760 #ifdef illumos
761 	(void) snprintf(nmbuf, sizeof (nmbuf), "%u,raw", minor);
762 	ddi_remove_minor_node(zfs_dip, nmbuf);
763 
764 	(void) snprintf(nmbuf, sizeof (nmbuf), "%u", minor);
765 	ddi_remove_minor_node(zfs_dip, nmbuf);
766 #else
767 	ZFS_LOG(1, "ZVOL %s destroyed.", zv->zv_name);
768 
769 	LIST_REMOVE(zv, zv_links);
770 	if (zv->zv_volmode == ZFS_VOLMODE_GEOM) {
771 		g_topology_lock();
772 		zvol_geom_destroy(zv);
773 		g_topology_unlock();
774 	} else if (zv->zv_volmode == ZFS_VOLMODE_DEV)
775 		destroy_dev(zv->zv_dev);
776 #endif
777 
778 	avl_destroy(&zv->zv_znode.z_range_avl);
779 	mutex_destroy(&zv->zv_znode.z_range_lock);
780 
781 	kmem_free(zv, sizeof (zvol_state_t));
782 #ifdef illumos
783 	ddi_soft_state_free(zfsdev_state, minor);
784 #endif
785 	zvol_minors--;
786 	return (0);
787 }
788 
789 int
790 zvol_remove_minor(const char *name)
791 {
792 	zvol_state_t *zv;
793 	int rc;
794 
795 	mutex_enter(&zfsdev_state_lock);
796 	if ((zv = zvol_minor_lookup(name)) == NULL) {
797 		mutex_exit(&zfsdev_state_lock);
798 		return (SET_ERROR(ENXIO));
799 	}
800 	rc = zvol_remove_zv(zv);
801 	mutex_exit(&zfsdev_state_lock);
802 	return (rc);
803 }
804 
805 int
806 zvol_first_open(zvol_state_t *zv)
807 {
808 	objset_t *os;
809 	uint64_t volsize;
810 	int error;
811 	uint64_t readonly;
812 
813 	/* lie and say we're read-only */
814 	error = dmu_objset_own(zv->zv_name, DMU_OST_ZVOL, B_TRUE,
815 	    zvol_tag, &os);
816 	if (error)
817 		return (error);
818 
819 	zv->zv_objset = os;
820 	error = zap_lookup(os, ZVOL_ZAP_OBJ, "size", 8, 1, &volsize);
821 	if (error) {
822 		ASSERT(error == 0);
823 		dmu_objset_disown(os, zvol_tag);
824 		return (error);
825 	}
826 
827 	error = dmu_bonus_hold(os, ZVOL_OBJ, zvol_tag, &zv->zv_dbuf);
828 	if (error) {
829 		dmu_objset_disown(os, zvol_tag);
830 		return (error);
831 	}
832 
833 	zvol_size_changed(zv, volsize);
834 	zv->zv_zilog = zil_open(os, zvol_get_data);
835 
836 	VERIFY(dsl_prop_get_integer(zv->zv_name, "readonly", &readonly,
837 	    NULL) == 0);
838 	if (readonly || dmu_objset_is_snapshot(os) ||
839 	    !spa_writeable(dmu_objset_spa(os)))
840 		zv->zv_flags |= ZVOL_RDONLY;
841 	else
842 		zv->zv_flags &= ~ZVOL_RDONLY;
843 	return (error);
844 }
845 
846 void
847 zvol_last_close(zvol_state_t *zv)
848 {
849 	zil_close(zv->zv_zilog);
850 	zv->zv_zilog = NULL;
851 
852 	dmu_buf_rele(zv->zv_dbuf, zvol_tag);
853 	zv->zv_dbuf = NULL;
854 
855 	/*
856 	 * Evict cached data
857 	 */
858 	if (dsl_dataset_is_dirty(dmu_objset_ds(zv->zv_objset)) &&
859 	    !(zv->zv_flags & ZVOL_RDONLY))
860 		txg_wait_synced(dmu_objset_pool(zv->zv_objset), 0);
861 	dmu_objset_evict_dbufs(zv->zv_objset);
862 
863 	dmu_objset_disown(zv->zv_objset, zvol_tag);
864 	zv->zv_objset = NULL;
865 }
866 
867 #ifdef illumos
868 int
869 zvol_prealloc(zvol_state_t *zv)
870 {
871 	objset_t *os = zv->zv_objset;
872 	dmu_tx_t *tx;
873 	uint64_t refd, avail, usedobjs, availobjs;
874 	uint64_t resid = zv->zv_volsize;
875 	uint64_t off = 0;
876 
877 	/* Check the space usage before attempting to allocate the space */
878 	dmu_objset_space(os, &refd, &avail, &usedobjs, &availobjs);
879 	if (avail < zv->zv_volsize)
880 		return (SET_ERROR(ENOSPC));
881 
882 	/* Free old extents if they exist */
883 	zvol_free_extents(zv);
884 
885 	while (resid != 0) {
886 		int error;
887 		uint64_t bytes = MIN(resid, SPA_OLD_MAXBLOCKSIZE);
888 
889 		tx = dmu_tx_create(os);
890 		dmu_tx_hold_write(tx, ZVOL_OBJ, off, bytes);
891 		error = dmu_tx_assign(tx, TXG_WAIT);
892 		if (error) {
893 			dmu_tx_abort(tx);
894 			(void) dmu_free_long_range(os, ZVOL_OBJ, 0, off);
895 			return (error);
896 		}
897 		dmu_prealloc(os, ZVOL_OBJ, off, bytes, tx);
898 		dmu_tx_commit(tx);
899 		off += bytes;
900 		resid -= bytes;
901 	}
902 	txg_wait_synced(dmu_objset_pool(os), 0);
903 
904 	return (0);
905 }
906 #endif	/* illumos */
907 
908 static int
909 zvol_update_volsize(objset_t *os, uint64_t volsize)
910 {
911 	dmu_tx_t *tx;
912 	int error;
913 
914 	ASSERT(MUTEX_HELD(&zfsdev_state_lock));
915 
916 	tx = dmu_tx_create(os);
917 	dmu_tx_hold_zap(tx, ZVOL_ZAP_OBJ, TRUE, NULL);
918 	dmu_tx_mark_netfree(tx);
919 	error = dmu_tx_assign(tx, TXG_WAIT);
920 	if (error) {
921 		dmu_tx_abort(tx);
922 		return (error);
923 	}
924 
925 	error = zap_update(os, ZVOL_ZAP_OBJ, "size", 8, 1,
926 	    &volsize, tx);
927 	dmu_tx_commit(tx);
928 
929 	if (error == 0)
930 		error = dmu_free_long_range(os,
931 		    ZVOL_OBJ, volsize, DMU_OBJECT_END);
932 	return (error);
933 }
934 
935 void
936 zvol_remove_minors(const char *name)
937 {
938 #ifdef illumos
939 	zvol_state_t *zv;
940 	char *namebuf;
941 	minor_t minor;
942 
943 	namebuf = kmem_zalloc(strlen(name) + 2, KM_SLEEP);
944 	(void) strncpy(namebuf, name, strlen(name));
945 	(void) strcat(namebuf, "/");
946 	mutex_enter(&zfsdev_state_lock);
947 	for (minor = 1; minor <= ZFSDEV_MAX_MINOR; minor++) {
948 
949 		zv = zfsdev_get_soft_state(minor, ZSST_ZVOL);
950 		if (zv == NULL)
951 			continue;
952 		if (strncmp(namebuf, zv->zv_name, strlen(namebuf)) == 0)
953 			(void) zvol_remove_zv(zv);
954 	}
955 	kmem_free(namebuf, strlen(name) + 2);
956 
957 	mutex_exit(&zfsdev_state_lock);
958 #else	/* !illumos */
959 	zvol_state_t *zv, *tzv;
960 	size_t namelen;
961 
962 	namelen = strlen(name);
963 
964 	DROP_GIANT();
965 	mutex_enter(&zfsdev_state_lock);
966 
967 	LIST_FOREACH_SAFE(zv, &all_zvols, zv_links, tzv) {
968 		if (strcmp(zv->zv_name, name) == 0 ||
969 		    (strncmp(zv->zv_name, name, namelen) == 0 &&
970 		    strlen(zv->zv_name) > namelen && (zv->zv_name[namelen] == '/' ||
971 		    zv->zv_name[namelen] == '@'))) {
972 			(void) zvol_remove_zv(zv);
973 		}
974 	}
975 
976 	mutex_exit(&zfsdev_state_lock);
977 	PICKUP_GIANT();
978 #endif	/* illumos */
979 }
980 
981 static int
982 zvol_update_live_volsize(zvol_state_t *zv, uint64_t volsize)
983 {
984 	uint64_t old_volsize = 0ULL;
985 	int error = 0;
986 
987 	ASSERT(MUTEX_HELD(&zfsdev_state_lock));
988 
989 	/*
990 	 * Reinitialize the dump area to the new size. If we
991 	 * failed to resize the dump area then restore it back to
992 	 * its original size.  We must set the new volsize prior
993 	 * to calling dumpvp_resize() to ensure that the devices'
994 	 * size(9P) is not visible by the dump subsystem.
995 	 */
996 	old_volsize = zv->zv_volsize;
997 	zvol_size_changed(zv, volsize);
998 
999 #ifdef ZVOL_DUMP
1000 	if (zv->zv_flags & ZVOL_DUMPIFIED) {
1001 		if ((error = zvol_dumpify(zv)) != 0 ||
1002 		    (error = dumpvp_resize()) != 0) {
1003 			int dumpify_error;
1004 
1005 			(void) zvol_update_volsize(zv->zv_objset, old_volsize);
1006 			zvol_size_changed(zv, old_volsize);
1007 			dumpify_error = zvol_dumpify(zv);
1008 			error = dumpify_error ? dumpify_error : error;
1009 		}
1010 	}
1011 #endif	/* ZVOL_DUMP */
1012 
1013 #ifdef illumos
1014 	/*
1015 	 * Generate a LUN expansion event.
1016 	 */
1017 	if (error == 0) {
1018 		sysevent_id_t eid;
1019 		nvlist_t *attr;
1020 		char *physpath = kmem_zalloc(MAXPATHLEN, KM_SLEEP);
1021 
1022 		(void) snprintf(physpath, MAXPATHLEN, "%s%u", ZVOL_PSEUDO_DEV,
1023 		    zv->zv_minor);
1024 
1025 		VERIFY(nvlist_alloc(&attr, NV_UNIQUE_NAME, KM_SLEEP) == 0);
1026 		VERIFY(nvlist_add_string(attr, DEV_PHYS_PATH, physpath) == 0);
1027 
1028 		(void) ddi_log_sysevent(zfs_dip, SUNW_VENDOR, EC_DEV_STATUS,
1029 		    ESC_DEV_DLE, attr, &eid, DDI_SLEEP);
1030 
1031 		nvlist_free(attr);
1032 		kmem_free(physpath, MAXPATHLEN);
1033 	}
1034 #endif	/* illumos */
1035 	return (error);
1036 }
1037 
1038 int
1039 zvol_set_volsize(const char *name, uint64_t volsize)
1040 {
1041 	zvol_state_t *zv = NULL;
1042 	objset_t *os;
1043 	int error;
1044 	dmu_object_info_t doi;
1045 	uint64_t readonly;
1046 	boolean_t owned = B_FALSE;
1047 
1048 	error = dsl_prop_get_integer(name,
1049 	    zfs_prop_to_name(ZFS_PROP_READONLY), &readonly, NULL);
1050 	if (error != 0)
1051 		return (error);
1052 	if (readonly)
1053 		return (SET_ERROR(EROFS));
1054 
1055 	mutex_enter(&zfsdev_state_lock);
1056 	zv = zvol_minor_lookup(name);
1057 
1058 	if (zv == NULL || zv->zv_objset == NULL) {
1059 		if ((error = dmu_objset_own(name, DMU_OST_ZVOL, B_FALSE,
1060 		    FTAG, &os)) != 0) {
1061 			mutex_exit(&zfsdev_state_lock);
1062 			return (error);
1063 		}
1064 		owned = B_TRUE;
1065 		if (zv != NULL)
1066 			zv->zv_objset = os;
1067 	} else {
1068 		os = zv->zv_objset;
1069 	}
1070 
1071 	if ((error = dmu_object_info(os, ZVOL_OBJ, &doi)) != 0 ||
1072 	    (error = zvol_check_volsize(volsize, doi.doi_data_block_size)) != 0)
1073 		goto out;
1074 
1075 	error = zvol_update_volsize(os, volsize);
1076 
1077 	if (error == 0 && zv != NULL)
1078 		error = zvol_update_live_volsize(zv, volsize);
1079 out:
1080 	if (owned) {
1081 		dmu_objset_disown(os, FTAG);
1082 		if (zv != NULL)
1083 			zv->zv_objset = NULL;
1084 	}
1085 	mutex_exit(&zfsdev_state_lock);
1086 	return (error);
1087 }
1088 
1089 /*ARGSUSED*/
1090 #ifdef illumos
1091 int
1092 zvol_open(dev_t *devp, int flag, int otyp, cred_t *cr)
1093 #else
1094 static int
1095 zvol_open(struct g_provider *pp, int flag, int count)
1096 #endif
1097 {
1098 	zvol_state_t *zv;
1099 	int err = 0;
1100 #ifdef illumos
1101 
1102 	mutex_enter(&zfsdev_state_lock);
1103 
1104 	zv = zfsdev_get_soft_state(getminor(*devp), ZSST_ZVOL);
1105 	if (zv == NULL) {
1106 		mutex_exit(&zfsdev_state_lock);
1107 		return (SET_ERROR(ENXIO));
1108 	}
1109 
1110 	if (zv->zv_total_opens == 0)
1111 		err = zvol_first_open(zv);
1112 	if (err) {
1113 		mutex_exit(&zfsdev_state_lock);
1114 		return (err);
1115 	}
1116 #else	/* !illumos */
1117 	boolean_t locked = B_FALSE;
1118 
1119 	/*
1120 	 * Protect against recursively entering spa_namespace_lock
1121 	 * when spa_open() is used for a pool on a (local) ZVOL(s).
1122 	 * This is needed since we replaced upstream zfsdev_state_lock
1123 	 * with spa_namespace_lock in the ZVOL code.
1124 	 * We are using the same trick as spa_open().
1125 	 * Note that calls in zvol_first_open which need to resolve
1126 	 * pool name to a spa object will enter spa_open()
1127 	 * recursively, but that function already has all the
1128 	 * necessary protection.
1129 	 */
1130 	if (!MUTEX_HELD(&zfsdev_state_lock)) {
1131 		mutex_enter(&zfsdev_state_lock);
1132 		locked = B_TRUE;
1133 	}
1134 
1135 	zv = pp->private;
1136 	if (zv == NULL) {
1137 		if (locked)
1138 			mutex_exit(&zfsdev_state_lock);
1139 		return (SET_ERROR(ENXIO));
1140 	}
1141 
1142 	if (zv->zv_total_opens == 0) {
1143 		err = zvol_first_open(zv);
1144 		if (err) {
1145 			if (locked)
1146 				mutex_exit(&zfsdev_state_lock);
1147 			return (err);
1148 		}
1149 		pp->mediasize = zv->zv_volsize;
1150 		pp->stripeoffset = 0;
1151 		pp->stripesize = zv->zv_volblocksize;
1152 	}
1153 #endif	/* illumos */
1154 	if ((flag & FWRITE) && (zv->zv_flags & ZVOL_RDONLY)) {
1155 		err = SET_ERROR(EROFS);
1156 		goto out;
1157 	}
1158 	if (zv->zv_flags & ZVOL_EXCL) {
1159 		err = SET_ERROR(EBUSY);
1160 		goto out;
1161 	}
1162 #ifdef FEXCL
1163 	if (flag & FEXCL) {
1164 		if (zv->zv_total_opens != 0) {
1165 			err = SET_ERROR(EBUSY);
1166 			goto out;
1167 		}
1168 		zv->zv_flags |= ZVOL_EXCL;
1169 	}
1170 #endif
1171 
1172 #ifdef illumos
1173 	if (zv->zv_open_count[otyp] == 0 || otyp == OTYP_LYR) {
1174 		zv->zv_open_count[otyp]++;
1175 		zv->zv_total_opens++;
1176 	}
1177 	mutex_exit(&zfsdev_state_lock);
1178 #else
1179 	zv->zv_total_opens += count;
1180 	if (locked)
1181 		mutex_exit(&zfsdev_state_lock);
1182 #endif
1183 
1184 	return (err);
1185 out:
1186 	if (zv->zv_total_opens == 0)
1187 		zvol_last_close(zv);
1188 #ifdef illumos
1189 	mutex_exit(&zfsdev_state_lock);
1190 #else
1191 	if (locked)
1192 		mutex_exit(&zfsdev_state_lock);
1193 #endif
1194 	return (err);
1195 }
1196 
1197 /*ARGSUSED*/
1198 #ifdef illumos
1199 int
1200 zvol_close(dev_t dev, int flag, int otyp, cred_t *cr)
1201 {
1202 	minor_t minor = getminor(dev);
1203 	zvol_state_t *zv;
1204 	int error = 0;
1205 
1206 	mutex_enter(&zfsdev_state_lock);
1207 
1208 	zv = zfsdev_get_soft_state(minor, ZSST_ZVOL);
1209 	if (zv == NULL) {
1210 		mutex_exit(&zfsdev_state_lock);
1211 #else	/* !illumos */
1212 static int
1213 zvol_close(struct g_provider *pp, int flag, int count)
1214 {
1215 	zvol_state_t *zv;
1216 	int error = 0;
1217 	boolean_t locked = B_FALSE;
1218 
1219 	/* See comment in zvol_open(). */
1220 	if (!MUTEX_HELD(&zfsdev_state_lock)) {
1221 		mutex_enter(&zfsdev_state_lock);
1222 		locked = B_TRUE;
1223 	}
1224 
1225 	zv = pp->private;
1226 	if (zv == NULL) {
1227 		if (locked)
1228 			mutex_exit(&zfsdev_state_lock);
1229 #endif	/* illumos */
1230 		return (SET_ERROR(ENXIO));
1231 	}
1232 
1233 	if (zv->zv_flags & ZVOL_EXCL) {
1234 		ASSERT(zv->zv_total_opens == 1);
1235 		zv->zv_flags &= ~ZVOL_EXCL;
1236 	}
1237 
1238 	/*
1239 	 * If the open count is zero, this is a spurious close.
1240 	 * That indicates a bug in the kernel / DDI framework.
1241 	 */
1242 #ifdef illumos
1243 	ASSERT(zv->zv_open_count[otyp] != 0);
1244 #endif
1245 	ASSERT(zv->zv_total_opens != 0);
1246 
1247 	/*
1248 	 * You may get multiple opens, but only one close.
1249 	 */
1250 #ifdef illumos
1251 	zv->zv_open_count[otyp]--;
1252 	zv->zv_total_opens--;
1253 #else
1254 	zv->zv_total_opens -= count;
1255 #endif
1256 
1257 	if (zv->zv_total_opens == 0)
1258 		zvol_last_close(zv);
1259 
1260 #ifdef illumos
1261 	mutex_exit(&zfsdev_state_lock);
1262 #else
1263 	if (locked)
1264 		mutex_exit(&zfsdev_state_lock);
1265 #endif
1266 	return (error);
1267 }
1268 
1269 static void
1270 zvol_get_done(zgd_t *zgd, int error)
1271 {
1272 	if (zgd->zgd_db)
1273 		dmu_buf_rele(zgd->zgd_db, zgd);
1274 
1275 	zfs_range_unlock(zgd->zgd_rl);
1276 
1277 	if (error == 0 && zgd->zgd_bp)
1278 		zil_add_block(zgd->zgd_zilog, zgd->zgd_bp);
1279 
1280 	kmem_free(zgd, sizeof (zgd_t));
1281 }
1282 
1283 /*
1284  * Get data to generate a TX_WRITE intent log record.
1285  */
1286 static int
1287 zvol_get_data(void *arg, lr_write_t *lr, char *buf, zio_t *zio)
1288 {
1289 	zvol_state_t *zv = arg;
1290 	objset_t *os = zv->zv_objset;
1291 	uint64_t object = ZVOL_OBJ;
1292 	uint64_t offset = lr->lr_offset;
1293 	uint64_t size = lr->lr_length;	/* length of user data */
1294 	blkptr_t *bp = &lr->lr_blkptr;
1295 	dmu_buf_t *db;
1296 	zgd_t *zgd;
1297 	int error;
1298 
1299 	ASSERT(zio != NULL);
1300 	ASSERT(size != 0);
1301 
1302 	zgd = kmem_zalloc(sizeof (zgd_t), KM_SLEEP);
1303 	zgd->zgd_zilog = zv->zv_zilog;
1304 	zgd->zgd_rl = zfs_range_lock(&zv->zv_znode, offset, size, RL_READER);
1305 
1306 	/*
1307 	 * Write records come in two flavors: immediate and indirect.
1308 	 * For small writes it's cheaper to store the data with the
1309 	 * log record (immediate); for large writes it's cheaper to
1310 	 * sync the data and get a pointer to it (indirect) so that
1311 	 * we don't have to write the data twice.
1312 	 */
1313 	if (buf != NULL) {	/* immediate write */
1314 		error = dmu_read(os, object, offset, size, buf,
1315 		    DMU_READ_NO_PREFETCH);
1316 	} else {
1317 		size = zv->zv_volblocksize;
1318 		offset = P2ALIGN(offset, size);
1319 		error = dmu_buf_hold(os, object, offset, zgd, &db,
1320 		    DMU_READ_NO_PREFETCH);
1321 		if (error == 0) {
1322 			blkptr_t *obp = dmu_buf_get_blkptr(db);
1323 			if (obp) {
1324 				ASSERT(BP_IS_HOLE(bp));
1325 				*bp = *obp;
1326 			}
1327 
1328 			zgd->zgd_db = db;
1329 			zgd->zgd_bp = bp;
1330 
1331 			ASSERT(db->db_offset == offset);
1332 			ASSERT(db->db_size == size);
1333 
1334 			error = dmu_sync(zio, lr->lr_common.lrc_txg,
1335 			    zvol_get_done, zgd);
1336 
1337 			if (error == 0)
1338 				return (0);
1339 		}
1340 	}
1341 
1342 	zvol_get_done(zgd, error);
1343 
1344 	return (error);
1345 }
1346 
1347 /*
1348  * zvol_log_write() handles synchronous writes using TX_WRITE ZIL transactions.
1349  *
1350  * We store data in the log buffers if it's small enough.
1351  * Otherwise we will later flush the data out via dmu_sync().
1352  */
1353 ssize_t zvol_immediate_write_sz = 32768;
1354 
1355 static void
1356 zvol_log_write(zvol_state_t *zv, dmu_tx_t *tx, offset_t off, ssize_t resid,
1357     boolean_t sync)
1358 {
1359 	uint32_t blocksize = zv->zv_volblocksize;
1360 	zilog_t *zilog = zv->zv_zilog;
1361 	boolean_t slogging;
1362 	ssize_t immediate_write_sz;
1363 
1364 	if (zil_replaying(zilog, tx))
1365 		return;
1366 
1367 	immediate_write_sz = (zilog->zl_logbias == ZFS_LOGBIAS_THROUGHPUT)
1368 	    ? 0 : zvol_immediate_write_sz;
1369 
1370 	slogging = spa_has_slogs(zilog->zl_spa) &&
1371 	    (zilog->zl_logbias == ZFS_LOGBIAS_LATENCY);
1372 
1373 	while (resid) {
1374 		itx_t *itx;
1375 		lr_write_t *lr;
1376 		ssize_t len;
1377 		itx_wr_state_t write_state;
1378 
1379 		/*
1380 		 * Unlike zfs_log_write() we can be called with
1381 		 * upto DMU_MAX_ACCESS/2 (5MB) writes.
1382 		 */
1383 		if (blocksize > immediate_write_sz && !slogging &&
1384 		    resid >= blocksize && off % blocksize == 0) {
1385 			write_state = WR_INDIRECT; /* uses dmu_sync */
1386 			len = blocksize;
1387 		} else if (sync) {
1388 			write_state = WR_COPIED;
1389 			len = MIN(ZIL_MAX_LOG_DATA, resid);
1390 		} else {
1391 			write_state = WR_NEED_COPY;
1392 			len = MIN(ZIL_MAX_LOG_DATA, resid);
1393 		}
1394 
1395 		itx = zil_itx_create(TX_WRITE, sizeof (*lr) +
1396 		    (write_state == WR_COPIED ? len : 0));
1397 		lr = (lr_write_t *)&itx->itx_lr;
1398 		if (write_state == WR_COPIED && dmu_read(zv->zv_objset,
1399 		    ZVOL_OBJ, off, len, lr + 1, DMU_READ_NO_PREFETCH) != 0) {
1400 			zil_itx_destroy(itx);
1401 			itx = zil_itx_create(TX_WRITE, sizeof (*lr));
1402 			lr = (lr_write_t *)&itx->itx_lr;
1403 			write_state = WR_NEED_COPY;
1404 		}
1405 
1406 		itx->itx_wr_state = write_state;
1407 		if (write_state == WR_NEED_COPY)
1408 			itx->itx_sod += len;
1409 		lr->lr_foid = ZVOL_OBJ;
1410 		lr->lr_offset = off;
1411 		lr->lr_length = len;
1412 		lr->lr_blkoff = 0;
1413 		BP_ZERO(&lr->lr_blkptr);
1414 
1415 		itx->itx_private = zv;
1416 		itx->itx_sync = sync;
1417 
1418 		zil_itx_assign(zilog, itx, tx);
1419 
1420 		off += len;
1421 		resid -= len;
1422 	}
1423 }
1424 
1425 #ifdef illumos
1426 static int
1427 zvol_dumpio_vdev(vdev_t *vd, void *addr, uint64_t offset, uint64_t origoffset,
1428     uint64_t size, boolean_t doread, boolean_t isdump)
1429 {
1430 	vdev_disk_t *dvd;
1431 	int c;
1432 	int numerrors = 0;
1433 
1434 	if (vd->vdev_ops == &vdev_mirror_ops ||
1435 	    vd->vdev_ops == &vdev_replacing_ops ||
1436 	    vd->vdev_ops == &vdev_spare_ops) {
1437 		for (c = 0; c < vd->vdev_children; c++) {
1438 			int err = zvol_dumpio_vdev(vd->vdev_child[c],
1439 			    addr, offset, origoffset, size, doread, isdump);
1440 			if (err != 0) {
1441 				numerrors++;
1442 			} else if (doread) {
1443 				break;
1444 			}
1445 		}
1446 	}
1447 
1448 	if (!vd->vdev_ops->vdev_op_leaf && vd->vdev_ops != &vdev_raidz_ops)
1449 		return (numerrors < vd->vdev_children ? 0 : EIO);
1450 
1451 	if (doread && !vdev_readable(vd))
1452 		return (SET_ERROR(EIO));
1453 	else if (!doread && !vdev_writeable(vd))
1454 		return (SET_ERROR(EIO));
1455 
1456 	if (vd->vdev_ops == &vdev_raidz_ops) {
1457 		return (vdev_raidz_physio(vd,
1458 		    addr, size, offset, origoffset, doread, isdump));
1459 	}
1460 
1461 	offset += VDEV_LABEL_START_SIZE;
1462 
1463 	if (ddi_in_panic() || isdump) {
1464 		ASSERT(!doread);
1465 		if (doread)
1466 			return (SET_ERROR(EIO));
1467 		dvd = vd->vdev_tsd;
1468 		ASSERT3P(dvd, !=, NULL);
1469 		return (ldi_dump(dvd->vd_lh, addr, lbtodb(offset),
1470 		    lbtodb(size)));
1471 	} else {
1472 		dvd = vd->vdev_tsd;
1473 		ASSERT3P(dvd, !=, NULL);
1474 		return (vdev_disk_ldi_physio(dvd->vd_lh, addr, size,
1475 		    offset, doread ? B_READ : B_WRITE));
1476 	}
1477 }
1478 
1479 static int
1480 zvol_dumpio(zvol_state_t *zv, void *addr, uint64_t offset, uint64_t size,
1481     boolean_t doread, boolean_t isdump)
1482 {
1483 	vdev_t *vd;
1484 	int error;
1485 	zvol_extent_t *ze;
1486 	spa_t *spa = dmu_objset_spa(zv->zv_objset);
1487 
1488 	/* Must be sector aligned, and not stradle a block boundary. */
1489 	if (P2PHASE(offset, DEV_BSIZE) || P2PHASE(size, DEV_BSIZE) ||
1490 	    P2BOUNDARY(offset, size, zv->zv_volblocksize)) {
1491 		return (SET_ERROR(EINVAL));
1492 	}
1493 	ASSERT(size <= zv->zv_volblocksize);
1494 
1495 	/* Locate the extent this belongs to */
1496 	ze = list_head(&zv->zv_extents);
1497 	while (offset >= ze->ze_nblks * zv->zv_volblocksize) {
1498 		offset -= ze->ze_nblks * zv->zv_volblocksize;
1499 		ze = list_next(&zv->zv_extents, ze);
1500 	}
1501 
1502 	if (ze == NULL)
1503 		return (SET_ERROR(EINVAL));
1504 
1505 	if (!ddi_in_panic())
1506 		spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
1507 
1508 	vd = vdev_lookup_top(spa, DVA_GET_VDEV(&ze->ze_dva));
1509 	offset += DVA_GET_OFFSET(&ze->ze_dva);
1510 	error = zvol_dumpio_vdev(vd, addr, offset, DVA_GET_OFFSET(&ze->ze_dva),
1511 	    size, doread, isdump);
1512 
1513 	if (!ddi_in_panic())
1514 		spa_config_exit(spa, SCL_STATE, FTAG);
1515 
1516 	return (error);
1517 }
1518 
1519 int
1520 zvol_strategy(buf_t *bp)
1521 {
1522 	zfs_soft_state_t *zs = NULL;
1523 #else	/* !illumos */
1524 void
1525 zvol_strategy(struct bio *bp)
1526 {
1527 #endif	/* illumos */
1528 	zvol_state_t *zv;
1529 	uint64_t off, volsize;
1530 	size_t resid;
1531 	char *addr;
1532 	objset_t *os;
1533 	rl_t *rl;
1534 	int error = 0;
1535 #ifdef illumos
1536 	boolean_t doread = bp->b_flags & B_READ;
1537 #else
1538 	boolean_t doread = 0;
1539 #endif
1540 	boolean_t is_dumpified;
1541 	boolean_t sync;
1542 
1543 #ifdef illumos
1544 	if (getminor(bp->b_edev) == 0) {
1545 		error = SET_ERROR(EINVAL);
1546 	} else {
1547 		zs = ddi_get_soft_state(zfsdev_state, getminor(bp->b_edev));
1548 		if (zs == NULL)
1549 			error = SET_ERROR(ENXIO);
1550 		else if (zs->zss_type != ZSST_ZVOL)
1551 			error = SET_ERROR(EINVAL);
1552 	}
1553 
1554 	if (error) {
1555 		bioerror(bp, error);
1556 		biodone(bp);
1557 		return (0);
1558 	}
1559 
1560 	zv = zs->zss_data;
1561 
1562 	if (!(bp->b_flags & B_READ) && (zv->zv_flags & ZVOL_RDONLY)) {
1563 		bioerror(bp, EROFS);
1564 		biodone(bp);
1565 		return (0);
1566 	}
1567 
1568 	off = ldbtob(bp->b_blkno);
1569 #else	/* !illumos */
1570 	if (bp->bio_to)
1571 		zv = bp->bio_to->private;
1572 	else
1573 		zv = bp->bio_dev->si_drv2;
1574 
1575 	if (zv == NULL) {
1576 		error = SET_ERROR(ENXIO);
1577 		goto out;
1578 	}
1579 
1580 	if (bp->bio_cmd != BIO_READ && (zv->zv_flags & ZVOL_RDONLY)) {
1581 		error = SET_ERROR(EROFS);
1582 		goto out;
1583 	}
1584 
1585 	switch (bp->bio_cmd) {
1586 	case BIO_FLUSH:
1587 		goto sync;
1588 	case BIO_READ:
1589 		doread = 1;
1590 	case BIO_WRITE:
1591 	case BIO_DELETE:
1592 		break;
1593 	default:
1594 		error = EOPNOTSUPP;
1595 		goto out;
1596 	}
1597 
1598 	off = bp->bio_offset;
1599 #endif	/* illumos */
1600 	volsize = zv->zv_volsize;
1601 
1602 	os = zv->zv_objset;
1603 	ASSERT(os != NULL);
1604 
1605 #ifdef illumos
1606 	bp_mapin(bp);
1607 	addr = bp->b_un.b_addr;
1608 	resid = bp->b_bcount;
1609 
1610 	if (resid > 0 && (off < 0 || off >= volsize)) {
1611 		bioerror(bp, EIO);
1612 		biodone(bp);
1613 		return (0);
1614 	}
1615 
1616 	is_dumpified = zv->zv_flags & ZVOL_DUMPIFIED;
1617 	sync = ((!(bp->b_flags & B_ASYNC) &&
1618 	    !(zv->zv_flags & ZVOL_WCE)) ||
1619 	    (zv->zv_objset->os_sync == ZFS_SYNC_ALWAYS)) &&
1620 	    !doread && !is_dumpified;
1621 #else	/* !illumos */
1622 	addr = bp->bio_data;
1623 	resid = bp->bio_length;
1624 
1625 	if (resid > 0 && (off < 0 || off >= volsize)) {
1626 		error = SET_ERROR(EIO);
1627 		goto out;
1628 	}
1629 
1630 	is_dumpified = B_FALSE;
1631 	sync = !doread && !is_dumpified &&
1632 	    zv->zv_objset->os_sync == ZFS_SYNC_ALWAYS;
1633 #endif	/* illumos */
1634 
1635 	/*
1636 	 * There must be no buffer changes when doing a dmu_sync() because
1637 	 * we can't change the data whilst calculating the checksum.
1638 	 */
1639 	rl = zfs_range_lock(&zv->zv_znode, off, resid,
1640 	    doread ? RL_READER : RL_WRITER);
1641 
1642 #ifndef illumos
1643 	if (bp->bio_cmd == BIO_DELETE) {
1644 		dmu_tx_t *tx = dmu_tx_create(zv->zv_objset);
1645 		error = dmu_tx_assign(tx, TXG_WAIT);
1646 		if (error != 0) {
1647 			dmu_tx_abort(tx);
1648 		} else {
1649 			zvol_log_truncate(zv, tx, off, resid, B_TRUE);
1650 			dmu_tx_commit(tx);
1651 			error = dmu_free_long_range(zv->zv_objset, ZVOL_OBJ,
1652 			    off, resid);
1653 			resid = 0;
1654 		}
1655 		goto unlock;
1656 	}
1657 #endif
1658 	while (resid != 0 && off < volsize) {
1659 		size_t size = MIN(resid, zvol_maxphys);
1660 #ifdef illumos
1661 		if (is_dumpified) {
1662 			size = MIN(size, P2END(off, zv->zv_volblocksize) - off);
1663 			error = zvol_dumpio(zv, addr, off, size,
1664 			    doread, B_FALSE);
1665 		} else if (doread) {
1666 #else
1667 		if (doread) {
1668 #endif
1669 			error = dmu_read(os, ZVOL_OBJ, off, size, addr,
1670 			    DMU_READ_PREFETCH);
1671 		} else {
1672 			dmu_tx_t *tx = dmu_tx_create(os);
1673 			dmu_tx_hold_write(tx, ZVOL_OBJ, off, size);
1674 			error = dmu_tx_assign(tx, TXG_WAIT);
1675 			if (error) {
1676 				dmu_tx_abort(tx);
1677 			} else {
1678 				dmu_write(os, ZVOL_OBJ, off, size, addr, tx);
1679 				zvol_log_write(zv, tx, off, size, sync);
1680 				dmu_tx_commit(tx);
1681 			}
1682 		}
1683 		if (error) {
1684 			/* convert checksum errors into IO errors */
1685 			if (error == ECKSUM)
1686 				error = SET_ERROR(EIO);
1687 			break;
1688 		}
1689 		off += size;
1690 		addr += size;
1691 		resid -= size;
1692 	}
1693 #ifndef illumos
1694 unlock:
1695 #endif
1696 	zfs_range_unlock(rl);
1697 
1698 #ifdef illumos
1699 	if ((bp->b_resid = resid) == bp->b_bcount)
1700 		bioerror(bp, off > volsize ? EINVAL : error);
1701 
1702 	if (sync)
1703 		zil_commit(zv->zv_zilog, ZVOL_OBJ);
1704 	biodone(bp);
1705 
1706 	return (0);
1707 #else	/* !illumos */
1708 	bp->bio_completed = bp->bio_length - resid;
1709 	if (bp->bio_completed < bp->bio_length && off > volsize)
1710 		error = EINVAL;
1711 
1712 	if (sync) {
1713 sync:
1714 		zil_commit(zv->zv_zilog, ZVOL_OBJ);
1715 	}
1716 out:
1717 	if (bp->bio_to)
1718 		g_io_deliver(bp, error);
1719 	else
1720 		biofinish(bp, NULL, error);
1721 #endif	/* illumos */
1722 }
1723 
1724 #ifdef illumos
1725 /*
1726  * Set the buffer count to the zvol maximum transfer.
1727  * Using our own routine instead of the default minphys()
1728  * means that for larger writes we write bigger buffers on X86
1729  * (128K instead of 56K) and flush the disk write cache less often
1730  * (every zvol_maxphys - currently 1MB) instead of minphys (currently
1731  * 56K on X86 and 128K on sparc).
1732  */
1733 void
1734 zvol_minphys(struct buf *bp)
1735 {
1736 	if (bp->b_bcount > zvol_maxphys)
1737 		bp->b_bcount = zvol_maxphys;
1738 }
1739 
1740 int
1741 zvol_dump(dev_t dev, caddr_t addr, daddr_t blkno, int nblocks)
1742 {
1743 	minor_t minor = getminor(dev);
1744 	zvol_state_t *zv;
1745 	int error = 0;
1746 	uint64_t size;
1747 	uint64_t boff;
1748 	uint64_t resid;
1749 
1750 	zv = zfsdev_get_soft_state(minor, ZSST_ZVOL);
1751 	if (zv == NULL)
1752 		return (SET_ERROR(ENXIO));
1753 
1754 	if ((zv->zv_flags & ZVOL_DUMPIFIED) == 0)
1755 		return (SET_ERROR(EINVAL));
1756 
1757 	boff = ldbtob(blkno);
1758 	resid = ldbtob(nblocks);
1759 
1760 	VERIFY3U(boff + resid, <=, zv->zv_volsize);
1761 
1762 	while (resid) {
1763 		size = MIN(resid, P2END(boff, zv->zv_volblocksize) - boff);
1764 		error = zvol_dumpio(zv, addr, boff, size, B_FALSE, B_TRUE);
1765 		if (error)
1766 			break;
1767 		boff += size;
1768 		addr += size;
1769 		resid -= size;
1770 	}
1771 
1772 	return (error);
1773 }
1774 
1775 /*ARGSUSED*/
1776 int
1777 zvol_read(dev_t dev, uio_t *uio, cred_t *cr)
1778 {
1779 	minor_t minor = getminor(dev);
1780 #else	/* !illumos */
1781 int
1782 zvol_read(struct cdev *dev, struct uio *uio, int ioflag)
1783 {
1784 #endif	/* illumos */
1785 	zvol_state_t *zv;
1786 	uint64_t volsize;
1787 	rl_t *rl;
1788 	int error = 0;
1789 
1790 #ifdef illumos
1791 	zv = zfsdev_get_soft_state(minor, ZSST_ZVOL);
1792 	if (zv == NULL)
1793 		return (SET_ERROR(ENXIO));
1794 #else
1795 	zv = dev->si_drv2;
1796 #endif
1797 
1798 	volsize = zv->zv_volsize;
1799 	/* uio_loffset == volsize isn't an error as its required for EOF processing. */
1800 	if (uio->uio_resid > 0 &&
1801 	    (uio->uio_loffset < 0 || uio->uio_loffset > volsize))
1802 		return (SET_ERROR(EIO));
1803 
1804 #ifdef illumos
1805 	if (zv->zv_flags & ZVOL_DUMPIFIED) {
1806 		error = physio(zvol_strategy, NULL, dev, B_READ,
1807 		    zvol_minphys, uio);
1808 		return (error);
1809 	}
1810 #endif
1811 
1812 	rl = zfs_range_lock(&zv->zv_znode, uio->uio_loffset, uio->uio_resid,
1813 	    RL_READER);
1814 	while (uio->uio_resid > 0 && uio->uio_loffset < volsize) {
1815 		uint64_t bytes = MIN(uio->uio_resid, DMU_MAX_ACCESS >> 1);
1816 
1817 		/* don't read past the end */
1818 		if (bytes > volsize - uio->uio_loffset)
1819 			bytes = volsize - uio->uio_loffset;
1820 
1821 		error =  dmu_read_uio_dbuf(zv->zv_dbuf, uio, bytes);
1822 		if (error) {
1823 			/* convert checksum errors into IO errors */
1824 			if (error == ECKSUM)
1825 				error = SET_ERROR(EIO);
1826 			break;
1827 		}
1828 	}
1829 	zfs_range_unlock(rl);
1830 	return (error);
1831 }
1832 
1833 #ifdef illumos
1834 /*ARGSUSED*/
1835 int
1836 zvol_write(dev_t dev, uio_t *uio, cred_t *cr)
1837 {
1838 	minor_t minor = getminor(dev);
1839 #else	/* !illumos */
1840 int
1841 zvol_write(struct cdev *dev, struct uio *uio, int ioflag)
1842 {
1843 #endif	/* illumos */
1844 	zvol_state_t *zv;
1845 	uint64_t volsize;
1846 	rl_t *rl;
1847 	int error = 0;
1848 	boolean_t sync;
1849 
1850 #ifdef illumos
1851 	zv = zfsdev_get_soft_state(minor, ZSST_ZVOL);
1852 	if (zv == NULL)
1853 		return (SET_ERROR(ENXIO));
1854 #else
1855 	zv = dev->si_drv2;
1856 #endif
1857 
1858 	volsize = zv->zv_volsize;
1859 	/* uio_loffset == volsize isn't an error as its required for EOF processing. */
1860 	if (uio->uio_resid > 0 &&
1861 	    (uio->uio_loffset < 0 || uio->uio_loffset > volsize))
1862 		return (SET_ERROR(EIO));
1863 
1864 #ifdef illumos
1865 	if (zv->zv_flags & ZVOL_DUMPIFIED) {
1866 		error = physio(zvol_strategy, NULL, dev, B_WRITE,
1867 		    zvol_minphys, uio);
1868 		return (error);
1869 	}
1870 
1871 	sync = !(zv->zv_flags & ZVOL_WCE) ||
1872 #else
1873 	sync = (ioflag & IO_SYNC) ||
1874 #endif
1875 	    (zv->zv_objset->os_sync == ZFS_SYNC_ALWAYS);
1876 
1877 	rl = zfs_range_lock(&zv->zv_znode, uio->uio_loffset, uio->uio_resid,
1878 	    RL_WRITER);
1879 	while (uio->uio_resid > 0 && uio->uio_loffset < volsize) {
1880 		uint64_t bytes = MIN(uio->uio_resid, DMU_MAX_ACCESS >> 1);
1881 		uint64_t off = uio->uio_loffset;
1882 		dmu_tx_t *tx = dmu_tx_create(zv->zv_objset);
1883 
1884 		if (bytes > volsize - off)	/* don't write past the end */
1885 			bytes = volsize - off;
1886 
1887 		dmu_tx_hold_write(tx, ZVOL_OBJ, off, bytes);
1888 		error = dmu_tx_assign(tx, TXG_WAIT);
1889 		if (error) {
1890 			dmu_tx_abort(tx);
1891 			break;
1892 		}
1893 		error = dmu_write_uio_dbuf(zv->zv_dbuf, uio, bytes, tx);
1894 		if (error == 0)
1895 			zvol_log_write(zv, tx, off, bytes, sync);
1896 		dmu_tx_commit(tx);
1897 
1898 		if (error)
1899 			break;
1900 	}
1901 	zfs_range_unlock(rl);
1902 	if (sync)
1903 		zil_commit(zv->zv_zilog, ZVOL_OBJ);
1904 	return (error);
1905 }
1906 
1907 #ifdef illumos
1908 int
1909 zvol_getefi(void *arg, int flag, uint64_t vs, uint8_t bs)
1910 {
1911 	struct uuid uuid = EFI_RESERVED;
1912 	efi_gpe_t gpe = { 0 };
1913 	uint32_t crc;
1914 	dk_efi_t efi;
1915 	int length;
1916 	char *ptr;
1917 
1918 	if (ddi_copyin(arg, &efi, sizeof (dk_efi_t), flag))
1919 		return (SET_ERROR(EFAULT));
1920 	ptr = (char *)(uintptr_t)efi.dki_data_64;
1921 	length = efi.dki_length;
1922 	/*
1923 	 * Some clients may attempt to request a PMBR for the
1924 	 * zvol.  Currently this interface will return EINVAL to
1925 	 * such requests.  These requests could be supported by
1926 	 * adding a check for lba == 0 and consing up an appropriate
1927 	 * PMBR.
1928 	 */
1929 	if (efi.dki_lba < 1 || efi.dki_lba > 2 || length <= 0)
1930 		return (SET_ERROR(EINVAL));
1931 
1932 	gpe.efi_gpe_StartingLBA = LE_64(34ULL);
1933 	gpe.efi_gpe_EndingLBA = LE_64((vs >> bs) - 1);
1934 	UUID_LE_CONVERT(gpe.efi_gpe_PartitionTypeGUID, uuid);
1935 
1936 	if (efi.dki_lba == 1) {
1937 		efi_gpt_t gpt = { 0 };
1938 
1939 		gpt.efi_gpt_Signature = LE_64(EFI_SIGNATURE);
1940 		gpt.efi_gpt_Revision = LE_32(EFI_VERSION_CURRENT);
1941 		gpt.efi_gpt_HeaderSize = LE_32(sizeof (gpt));
1942 		gpt.efi_gpt_MyLBA = LE_64(1ULL);
1943 		gpt.efi_gpt_FirstUsableLBA = LE_64(34ULL);
1944 		gpt.efi_gpt_LastUsableLBA = LE_64((vs >> bs) - 1);
1945 		gpt.efi_gpt_PartitionEntryLBA = LE_64(2ULL);
1946 		gpt.efi_gpt_NumberOfPartitionEntries = LE_32(1);
1947 		gpt.efi_gpt_SizeOfPartitionEntry =
1948 		    LE_32(sizeof (efi_gpe_t));
1949 		CRC32(crc, &gpe, sizeof (gpe), -1U, crc32_table);
1950 		gpt.efi_gpt_PartitionEntryArrayCRC32 = LE_32(~crc);
1951 		CRC32(crc, &gpt, sizeof (gpt), -1U, crc32_table);
1952 		gpt.efi_gpt_HeaderCRC32 = LE_32(~crc);
1953 		if (ddi_copyout(&gpt, ptr, MIN(sizeof (gpt), length),
1954 		    flag))
1955 			return (SET_ERROR(EFAULT));
1956 		ptr += sizeof (gpt);
1957 		length -= sizeof (gpt);
1958 	}
1959 	if (length > 0 && ddi_copyout(&gpe, ptr, MIN(sizeof (gpe),
1960 	    length), flag))
1961 		return (SET_ERROR(EFAULT));
1962 	return (0);
1963 }
1964 
1965 /*
1966  * BEGIN entry points to allow external callers access to the volume.
1967  */
1968 /*
1969  * Return the volume parameters needed for access from an external caller.
1970  * These values are invariant as long as the volume is held open.
1971  */
1972 int
1973 zvol_get_volume_params(minor_t minor, uint64_t *blksize,
1974     uint64_t *max_xfer_len, void **minor_hdl, void **objset_hdl, void **zil_hdl,
1975     void **rl_hdl, void **bonus_hdl)
1976 {
1977 	zvol_state_t *zv;
1978 
1979 	zv = zfsdev_get_soft_state(minor, ZSST_ZVOL);
1980 	if (zv == NULL)
1981 		return (SET_ERROR(ENXIO));
1982 	if (zv->zv_flags & ZVOL_DUMPIFIED)
1983 		return (SET_ERROR(ENXIO));
1984 
1985 	ASSERT(blksize && max_xfer_len && minor_hdl &&
1986 	    objset_hdl && zil_hdl && rl_hdl && bonus_hdl);
1987 
1988 	*blksize = zv->zv_volblocksize;
1989 	*max_xfer_len = (uint64_t)zvol_maxphys;
1990 	*minor_hdl = zv;
1991 	*objset_hdl = zv->zv_objset;
1992 	*zil_hdl = zv->zv_zilog;
1993 	*rl_hdl = &zv->zv_znode;
1994 	*bonus_hdl = zv->zv_dbuf;
1995 	return (0);
1996 }
1997 
1998 /*
1999  * Return the current volume size to an external caller.
2000  * The size can change while the volume is open.
2001  */
2002 uint64_t
2003 zvol_get_volume_size(void *minor_hdl)
2004 {
2005 	zvol_state_t *zv = minor_hdl;
2006 
2007 	return (zv->zv_volsize);
2008 }
2009 
2010 /*
2011  * Return the current WCE setting to an external caller.
2012  * The WCE setting can change while the volume is open.
2013  */
2014 int
2015 zvol_get_volume_wce(void *minor_hdl)
2016 {
2017 	zvol_state_t *zv = minor_hdl;
2018 
2019 	return ((zv->zv_flags & ZVOL_WCE) ? 1 : 0);
2020 }
2021 
2022 /*
2023  * Entry point for external callers to zvol_log_write
2024  */
2025 void
2026 zvol_log_write_minor(void *minor_hdl, dmu_tx_t *tx, offset_t off, ssize_t resid,
2027     boolean_t sync)
2028 {
2029 	zvol_state_t *zv = minor_hdl;
2030 
2031 	zvol_log_write(zv, tx, off, resid, sync);
2032 }
2033 /*
2034  * END entry points to allow external callers access to the volume.
2035  */
2036 #endif	/* illumos */
2037 
2038 /*
2039  * Log a DKIOCFREE/free-long-range to the ZIL with TX_TRUNCATE.
2040  */
2041 static void
2042 zvol_log_truncate(zvol_state_t *zv, dmu_tx_t *tx, uint64_t off, uint64_t len,
2043     boolean_t sync)
2044 {
2045 	itx_t *itx;
2046 	lr_truncate_t *lr;
2047 	zilog_t *zilog = zv->zv_zilog;
2048 
2049 	if (zil_replaying(zilog, tx))
2050 		return;
2051 
2052 	itx = zil_itx_create(TX_TRUNCATE, sizeof (*lr));
2053 	lr = (lr_truncate_t *)&itx->itx_lr;
2054 	lr->lr_foid = ZVOL_OBJ;
2055 	lr->lr_offset = off;
2056 	lr->lr_length = len;
2057 
2058 	itx->itx_sync = sync;
2059 	zil_itx_assign(zilog, itx, tx);
2060 }
2061 
2062 #ifdef illumos
2063 /*
2064  * Dirtbag ioctls to support mkfs(1M) for UFS filesystems.  See dkio(7I).
2065  * Also a dirtbag dkio ioctl for unmap/free-block functionality.
2066  */
2067 /*ARGSUSED*/
2068 int
2069 zvol_ioctl(dev_t dev, int cmd, intptr_t arg, int flag, cred_t *cr, int *rvalp)
2070 {
2071 	zvol_state_t *zv;
2072 	struct dk_callback *dkc;
2073 	int error = 0;
2074 	rl_t *rl;
2075 
2076 	mutex_enter(&zfsdev_state_lock);
2077 
2078 	zv = zfsdev_get_soft_state(getminor(dev), ZSST_ZVOL);
2079 
2080 	if (zv == NULL) {
2081 		mutex_exit(&zfsdev_state_lock);
2082 		return (SET_ERROR(ENXIO));
2083 	}
2084 	ASSERT(zv->zv_total_opens > 0);
2085 
2086 	switch (cmd) {
2087 
2088 	case DKIOCINFO:
2089 	{
2090 		struct dk_cinfo dki;
2091 
2092 		bzero(&dki, sizeof (dki));
2093 		(void) strcpy(dki.dki_cname, "zvol");
2094 		(void) strcpy(dki.dki_dname, "zvol");
2095 		dki.dki_ctype = DKC_UNKNOWN;
2096 		dki.dki_unit = getminor(dev);
2097 		dki.dki_maxtransfer =
2098 		    1 << (SPA_OLD_MAXBLOCKSHIFT - zv->zv_min_bs);
2099 		mutex_exit(&zfsdev_state_lock);
2100 		if (ddi_copyout(&dki, (void *)arg, sizeof (dki), flag))
2101 			error = SET_ERROR(EFAULT);
2102 		return (error);
2103 	}
2104 
2105 	case DKIOCGMEDIAINFO:
2106 	{
2107 		struct dk_minfo dkm;
2108 
2109 		bzero(&dkm, sizeof (dkm));
2110 		dkm.dki_lbsize = 1U << zv->zv_min_bs;
2111 		dkm.dki_capacity = zv->zv_volsize >> zv->zv_min_bs;
2112 		dkm.dki_media_type = DK_UNKNOWN;
2113 		mutex_exit(&zfsdev_state_lock);
2114 		if (ddi_copyout(&dkm, (void *)arg, sizeof (dkm), flag))
2115 			error = SET_ERROR(EFAULT);
2116 		return (error);
2117 	}
2118 
2119 	case DKIOCGMEDIAINFOEXT:
2120 	{
2121 		struct dk_minfo_ext dkmext;
2122 
2123 		bzero(&dkmext, sizeof (dkmext));
2124 		dkmext.dki_lbsize = 1U << zv->zv_min_bs;
2125 		dkmext.dki_pbsize = zv->zv_volblocksize;
2126 		dkmext.dki_capacity = zv->zv_volsize >> zv->zv_min_bs;
2127 		dkmext.dki_media_type = DK_UNKNOWN;
2128 		mutex_exit(&zfsdev_state_lock);
2129 		if (ddi_copyout(&dkmext, (void *)arg, sizeof (dkmext), flag))
2130 			error = SET_ERROR(EFAULT);
2131 		return (error);
2132 	}
2133 
2134 	case DKIOCGETEFI:
2135 	{
2136 		uint64_t vs = zv->zv_volsize;
2137 		uint8_t bs = zv->zv_min_bs;
2138 
2139 		mutex_exit(&zfsdev_state_lock);
2140 		error = zvol_getefi((void *)arg, flag, vs, bs);
2141 		return (error);
2142 	}
2143 
2144 	case DKIOCFLUSHWRITECACHE:
2145 		dkc = (struct dk_callback *)arg;
2146 		mutex_exit(&zfsdev_state_lock);
2147 		zil_commit(zv->zv_zilog, ZVOL_OBJ);
2148 		if ((flag & FKIOCTL) && dkc != NULL && dkc->dkc_callback) {
2149 			(*dkc->dkc_callback)(dkc->dkc_cookie, error);
2150 			error = 0;
2151 		}
2152 		return (error);
2153 
2154 	case DKIOCGETWCE:
2155 	{
2156 		int wce = (zv->zv_flags & ZVOL_WCE) ? 1 : 0;
2157 		if (ddi_copyout(&wce, (void *)arg, sizeof (int),
2158 		    flag))
2159 			error = SET_ERROR(EFAULT);
2160 		break;
2161 	}
2162 	case DKIOCSETWCE:
2163 	{
2164 		int wce;
2165 		if (ddi_copyin((void *)arg, &wce, sizeof (int),
2166 		    flag)) {
2167 			error = SET_ERROR(EFAULT);
2168 			break;
2169 		}
2170 		if (wce) {
2171 			zv->zv_flags |= ZVOL_WCE;
2172 			mutex_exit(&zfsdev_state_lock);
2173 		} else {
2174 			zv->zv_flags &= ~ZVOL_WCE;
2175 			mutex_exit(&zfsdev_state_lock);
2176 			zil_commit(zv->zv_zilog, ZVOL_OBJ);
2177 		}
2178 		return (0);
2179 	}
2180 
2181 	case DKIOCGGEOM:
2182 	case DKIOCGVTOC:
2183 		/*
2184 		 * commands using these (like prtvtoc) expect ENOTSUP
2185 		 * since we're emulating an EFI label
2186 		 */
2187 		error = SET_ERROR(ENOTSUP);
2188 		break;
2189 
2190 	case DKIOCDUMPINIT:
2191 		rl = zfs_range_lock(&zv->zv_znode, 0, zv->zv_volsize,
2192 		    RL_WRITER);
2193 		error = zvol_dumpify(zv);
2194 		zfs_range_unlock(rl);
2195 		break;
2196 
2197 	case DKIOCDUMPFINI:
2198 		if (!(zv->zv_flags & ZVOL_DUMPIFIED))
2199 			break;
2200 		rl = zfs_range_lock(&zv->zv_znode, 0, zv->zv_volsize,
2201 		    RL_WRITER);
2202 		error = zvol_dump_fini(zv);
2203 		zfs_range_unlock(rl);
2204 		break;
2205 
2206 	case DKIOCFREE:
2207 	{
2208 		dkioc_free_t df;
2209 		dmu_tx_t *tx;
2210 
2211 		if (!zvol_unmap_enabled)
2212 			break;
2213 
2214 		if (ddi_copyin((void *)arg, &df, sizeof (df), flag)) {
2215 			error = SET_ERROR(EFAULT);
2216 			break;
2217 		}
2218 
2219 		/*
2220 		 * Apply Postel's Law to length-checking.  If they overshoot,
2221 		 * just blank out until the end, if there's a need to blank
2222 		 * out anything.
2223 		 */
2224 		if (df.df_start >= zv->zv_volsize)
2225 			break;	/* No need to do anything... */
2226 
2227 		mutex_exit(&zfsdev_state_lock);
2228 
2229 		rl = zfs_range_lock(&zv->zv_znode, df.df_start, df.df_length,
2230 		    RL_WRITER);
2231 		tx = dmu_tx_create(zv->zv_objset);
2232 		dmu_tx_mark_netfree(tx);
2233 		error = dmu_tx_assign(tx, TXG_WAIT);
2234 		if (error != 0) {
2235 			dmu_tx_abort(tx);
2236 		} else {
2237 			zvol_log_truncate(zv, tx, df.df_start,
2238 			    df.df_length, B_TRUE);
2239 			dmu_tx_commit(tx);
2240 			error = dmu_free_long_range(zv->zv_objset, ZVOL_OBJ,
2241 			    df.df_start, df.df_length);
2242 		}
2243 
2244 		zfs_range_unlock(rl);
2245 
2246 		if (error == 0) {
2247 			/*
2248 			 * If the write-cache is disabled or 'sync' property
2249 			 * is set to 'always' then treat this as a synchronous
2250 			 * operation (i.e. commit to zil).
2251 			 */
2252 			if (!(zv->zv_flags & ZVOL_WCE) ||
2253 			    (zv->zv_objset->os_sync == ZFS_SYNC_ALWAYS))
2254 				zil_commit(zv->zv_zilog, ZVOL_OBJ);
2255 
2256 			/*
2257 			 * If the caller really wants synchronous writes, and
2258 			 * can't wait for them, don't return until the write
2259 			 * is done.
2260 			 */
2261 			if (df.df_flags & DF_WAIT_SYNC) {
2262 				txg_wait_synced(
2263 				    dmu_objset_pool(zv->zv_objset), 0);
2264 			}
2265 		}
2266 		return (error);
2267 	}
2268 
2269 	default:
2270 		error = SET_ERROR(ENOTTY);
2271 		break;
2272 
2273 	}
2274 	mutex_exit(&zfsdev_state_lock);
2275 	return (error);
2276 }
2277 #endif	/* illumos */
2278 
2279 int
2280 zvol_busy(void)
2281 {
2282 	return (zvol_minors != 0);
2283 }
2284 
2285 void
2286 zvol_init(void)
2287 {
2288 	VERIFY(ddi_soft_state_init(&zfsdev_state, sizeof (zfs_soft_state_t),
2289 	    1) == 0);
2290 #ifdef illumos
2291 	mutex_init(&zfsdev_state_lock, NULL, MUTEX_DEFAULT, NULL);
2292 #else
2293 	ZFS_LOG(1, "ZVOL Initialized.");
2294 #endif
2295 }
2296 
2297 void
2298 zvol_fini(void)
2299 {
2300 #ifdef illumos
2301 	mutex_destroy(&zfsdev_state_lock);
2302 #endif
2303 	ddi_soft_state_fini(&zfsdev_state);
2304 	ZFS_LOG(1, "ZVOL Deinitialized.");
2305 }
2306 
2307 #ifdef illumos
2308 /*ARGSUSED*/
2309 static int
2310 zfs_mvdev_dump_feature_check(void *arg, dmu_tx_t *tx)
2311 {
2312 	spa_t *spa = dmu_tx_pool(tx)->dp_spa;
2313 
2314 	if (spa_feature_is_active(spa, SPA_FEATURE_MULTI_VDEV_CRASH_DUMP))
2315 		return (1);
2316 	return (0);
2317 }
2318 
2319 /*ARGSUSED*/
2320 static void
2321 zfs_mvdev_dump_activate_feature_sync(void *arg, dmu_tx_t *tx)
2322 {
2323 	spa_t *spa = dmu_tx_pool(tx)->dp_spa;
2324 
2325 	spa_feature_incr(spa, SPA_FEATURE_MULTI_VDEV_CRASH_DUMP, tx);
2326 }
2327 
2328 static int
2329 zvol_dump_init(zvol_state_t *zv, boolean_t resize)
2330 {
2331 	dmu_tx_t *tx;
2332 	int error;
2333 	objset_t *os = zv->zv_objset;
2334 	spa_t *spa = dmu_objset_spa(os);
2335 	vdev_t *vd = spa->spa_root_vdev;
2336 	nvlist_t *nv = NULL;
2337 	uint64_t version = spa_version(spa);
2338 	uint64_t checksum, compress, refresrv, vbs, dedup;
2339 
2340 	ASSERT(MUTEX_HELD(&zfsdev_state_lock));
2341 	ASSERT(vd->vdev_ops == &vdev_root_ops);
2342 
2343 	error = dmu_free_long_range(zv->zv_objset, ZVOL_OBJ, 0,
2344 	    DMU_OBJECT_END);
2345 	if (error != 0)
2346 		return (error);
2347 	/* wait for dmu_free_long_range to actually free the blocks */
2348 	txg_wait_synced(dmu_objset_pool(zv->zv_objset), 0);
2349 
2350 	/*
2351 	 * If the pool on which the dump device is being initialized has more
2352 	 * than one child vdev, check that the MULTI_VDEV_CRASH_DUMP feature is
2353 	 * enabled.  If so, bump that feature's counter to indicate that the
2354 	 * feature is active. We also check the vdev type to handle the
2355 	 * following case:
2356 	 *   # zpool create test raidz disk1 disk2 disk3
2357 	 *   Now have spa_root_vdev->vdev_children == 1 (the raidz vdev),
2358 	 *   the raidz vdev itself has 3 children.
2359 	 */
2360 	if (vd->vdev_children > 1 || vd->vdev_ops == &vdev_raidz_ops) {
2361 		if (!spa_feature_is_enabled(spa,
2362 		    SPA_FEATURE_MULTI_VDEV_CRASH_DUMP))
2363 			return (SET_ERROR(ENOTSUP));
2364 		(void) dsl_sync_task(spa_name(spa),
2365 		    zfs_mvdev_dump_feature_check,
2366 		    zfs_mvdev_dump_activate_feature_sync, NULL,
2367 		    2, ZFS_SPACE_CHECK_RESERVED);
2368 	}
2369 
2370 	if (!resize) {
2371 		error = dsl_prop_get_integer(zv->zv_name,
2372 		    zfs_prop_to_name(ZFS_PROP_COMPRESSION), &compress, NULL);
2373 		if (error == 0) {
2374 			error = dsl_prop_get_integer(zv->zv_name,
2375 			    zfs_prop_to_name(ZFS_PROP_CHECKSUM), &checksum,
2376 			    NULL);
2377 		}
2378 		if (error == 0) {
2379 			error = dsl_prop_get_integer(zv->zv_name,
2380 			    zfs_prop_to_name(ZFS_PROP_REFRESERVATION),
2381 			    &refresrv, NULL);
2382 		}
2383 		if (error == 0) {
2384 			error = dsl_prop_get_integer(zv->zv_name,
2385 			    zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE), &vbs,
2386 			    NULL);
2387 		}
2388 		if (version >= SPA_VERSION_DEDUP && error == 0) {
2389 			error = dsl_prop_get_integer(zv->zv_name,
2390 			    zfs_prop_to_name(ZFS_PROP_DEDUP), &dedup, NULL);
2391 		}
2392 	}
2393 	if (error != 0)
2394 		return (error);
2395 
2396 	tx = dmu_tx_create(os);
2397 	dmu_tx_hold_zap(tx, ZVOL_ZAP_OBJ, TRUE, NULL);
2398 	dmu_tx_hold_bonus(tx, ZVOL_OBJ);
2399 	error = dmu_tx_assign(tx, TXG_WAIT);
2400 	if (error != 0) {
2401 		dmu_tx_abort(tx);
2402 		return (error);
2403 	}
2404 
2405 	/*
2406 	 * If we are resizing the dump device then we only need to
2407 	 * update the refreservation to match the newly updated
2408 	 * zvolsize. Otherwise, we save off the original state of the
2409 	 * zvol so that we can restore them if the zvol is ever undumpified.
2410 	 */
2411 	if (resize) {
2412 		error = zap_update(os, ZVOL_ZAP_OBJ,
2413 		    zfs_prop_to_name(ZFS_PROP_REFRESERVATION), 8, 1,
2414 		    &zv->zv_volsize, tx);
2415 	} else {
2416 		error = zap_update(os, ZVOL_ZAP_OBJ,
2417 		    zfs_prop_to_name(ZFS_PROP_COMPRESSION), 8, 1,
2418 		    &compress, tx);
2419 		if (error == 0) {
2420 			error = zap_update(os, ZVOL_ZAP_OBJ,
2421 			    zfs_prop_to_name(ZFS_PROP_CHECKSUM), 8, 1,
2422 			    &checksum, tx);
2423 		}
2424 		if (error == 0) {
2425 			error = zap_update(os, ZVOL_ZAP_OBJ,
2426 			    zfs_prop_to_name(ZFS_PROP_REFRESERVATION), 8, 1,
2427 			    &refresrv, tx);
2428 		}
2429 		if (error == 0) {
2430 			error = zap_update(os, ZVOL_ZAP_OBJ,
2431 			    zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE), 8, 1,
2432 			    &vbs, tx);
2433 		}
2434 		if (error == 0) {
2435 			error = dmu_object_set_blocksize(
2436 			    os, ZVOL_OBJ, SPA_OLD_MAXBLOCKSIZE, 0, tx);
2437 		}
2438 		if (version >= SPA_VERSION_DEDUP && error == 0) {
2439 			error = zap_update(os, ZVOL_ZAP_OBJ,
2440 			    zfs_prop_to_name(ZFS_PROP_DEDUP), 8, 1,
2441 			    &dedup, tx);
2442 		}
2443 		if (error == 0)
2444 			zv->zv_volblocksize = SPA_OLD_MAXBLOCKSIZE;
2445 	}
2446 	dmu_tx_commit(tx);
2447 
2448 	/*
2449 	 * We only need update the zvol's property if we are initializing
2450 	 * the dump area for the first time.
2451 	 */
2452 	if (error == 0 && !resize) {
2453 		/*
2454 		 * If MULTI_VDEV_CRASH_DUMP is active, use the NOPARITY checksum
2455 		 * function.  Otherwise, use the old default -- OFF.
2456 		 */
2457 		checksum = spa_feature_is_active(spa,
2458 		    SPA_FEATURE_MULTI_VDEV_CRASH_DUMP) ? ZIO_CHECKSUM_NOPARITY :
2459 		    ZIO_CHECKSUM_OFF;
2460 
2461 		VERIFY(nvlist_alloc(&nv, NV_UNIQUE_NAME, KM_SLEEP) == 0);
2462 		VERIFY(nvlist_add_uint64(nv,
2463 		    zfs_prop_to_name(ZFS_PROP_REFRESERVATION), 0) == 0);
2464 		VERIFY(nvlist_add_uint64(nv,
2465 		    zfs_prop_to_name(ZFS_PROP_COMPRESSION),
2466 		    ZIO_COMPRESS_OFF) == 0);
2467 		VERIFY(nvlist_add_uint64(nv,
2468 		    zfs_prop_to_name(ZFS_PROP_CHECKSUM),
2469 		    checksum) == 0);
2470 		if (version >= SPA_VERSION_DEDUP) {
2471 			VERIFY(nvlist_add_uint64(nv,
2472 			    zfs_prop_to_name(ZFS_PROP_DEDUP),
2473 			    ZIO_CHECKSUM_OFF) == 0);
2474 		}
2475 
2476 		error = zfs_set_prop_nvlist(zv->zv_name, ZPROP_SRC_LOCAL,
2477 		    nv, NULL);
2478 		nvlist_free(nv);
2479 	}
2480 
2481 	/* Allocate the space for the dump */
2482 	if (error == 0)
2483 		error = zvol_prealloc(zv);
2484 	return (error);
2485 }
2486 
2487 static int
2488 zvol_dumpify(zvol_state_t *zv)
2489 {
2490 	int error = 0;
2491 	uint64_t dumpsize = 0;
2492 	dmu_tx_t *tx;
2493 	objset_t *os = zv->zv_objset;
2494 
2495 	if (zv->zv_flags & ZVOL_RDONLY)
2496 		return (SET_ERROR(EROFS));
2497 
2498 	if (zap_lookup(zv->zv_objset, ZVOL_ZAP_OBJ, ZVOL_DUMPSIZE,
2499 	    8, 1, &dumpsize) != 0 || dumpsize != zv->zv_volsize) {
2500 		boolean_t resize = (dumpsize > 0);
2501 
2502 		if ((error = zvol_dump_init(zv, resize)) != 0) {
2503 			(void) zvol_dump_fini(zv);
2504 			return (error);
2505 		}
2506 	}
2507 
2508 	/*
2509 	 * Build up our lba mapping.
2510 	 */
2511 	error = zvol_get_lbas(zv);
2512 	if (error) {
2513 		(void) zvol_dump_fini(zv);
2514 		return (error);
2515 	}
2516 
2517 	tx = dmu_tx_create(os);
2518 	dmu_tx_hold_zap(tx, ZVOL_ZAP_OBJ, TRUE, NULL);
2519 	error = dmu_tx_assign(tx, TXG_WAIT);
2520 	if (error) {
2521 		dmu_tx_abort(tx);
2522 		(void) zvol_dump_fini(zv);
2523 		return (error);
2524 	}
2525 
2526 	zv->zv_flags |= ZVOL_DUMPIFIED;
2527 	error = zap_update(os, ZVOL_ZAP_OBJ, ZVOL_DUMPSIZE, 8, 1,
2528 	    &zv->zv_volsize, tx);
2529 	dmu_tx_commit(tx);
2530 
2531 	if (error) {
2532 		(void) zvol_dump_fini(zv);
2533 		return (error);
2534 	}
2535 
2536 	txg_wait_synced(dmu_objset_pool(os), 0);
2537 	return (0);
2538 }
2539 
2540 static int
2541 zvol_dump_fini(zvol_state_t *zv)
2542 {
2543 	dmu_tx_t *tx;
2544 	objset_t *os = zv->zv_objset;
2545 	nvlist_t *nv;
2546 	int error = 0;
2547 	uint64_t checksum, compress, refresrv, vbs, dedup;
2548 	uint64_t version = spa_version(dmu_objset_spa(zv->zv_objset));
2549 
2550 	/*
2551 	 * Attempt to restore the zvol back to its pre-dumpified state.
2552 	 * This is a best-effort attempt as it's possible that not all
2553 	 * of these properties were initialized during the dumpify process
2554 	 * (i.e. error during zvol_dump_init).
2555 	 */
2556 
2557 	tx = dmu_tx_create(os);
2558 	dmu_tx_hold_zap(tx, ZVOL_ZAP_OBJ, TRUE, NULL);
2559 	error = dmu_tx_assign(tx, TXG_WAIT);
2560 	if (error) {
2561 		dmu_tx_abort(tx);
2562 		return (error);
2563 	}
2564 	(void) zap_remove(os, ZVOL_ZAP_OBJ, ZVOL_DUMPSIZE, tx);
2565 	dmu_tx_commit(tx);
2566 
2567 	(void) zap_lookup(zv->zv_objset, ZVOL_ZAP_OBJ,
2568 	    zfs_prop_to_name(ZFS_PROP_CHECKSUM), 8, 1, &checksum);
2569 	(void) zap_lookup(zv->zv_objset, ZVOL_ZAP_OBJ,
2570 	    zfs_prop_to_name(ZFS_PROP_COMPRESSION), 8, 1, &compress);
2571 	(void) zap_lookup(zv->zv_objset, ZVOL_ZAP_OBJ,
2572 	    zfs_prop_to_name(ZFS_PROP_REFRESERVATION), 8, 1, &refresrv);
2573 	(void) zap_lookup(zv->zv_objset, ZVOL_ZAP_OBJ,
2574 	    zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE), 8, 1, &vbs);
2575 
2576 	VERIFY(nvlist_alloc(&nv, NV_UNIQUE_NAME, KM_SLEEP) == 0);
2577 	(void) nvlist_add_uint64(nv,
2578 	    zfs_prop_to_name(ZFS_PROP_CHECKSUM), checksum);
2579 	(void) nvlist_add_uint64(nv,
2580 	    zfs_prop_to_name(ZFS_PROP_COMPRESSION), compress);
2581 	(void) nvlist_add_uint64(nv,
2582 	    zfs_prop_to_name(ZFS_PROP_REFRESERVATION), refresrv);
2583 	if (version >= SPA_VERSION_DEDUP &&
2584 	    zap_lookup(zv->zv_objset, ZVOL_ZAP_OBJ,
2585 	    zfs_prop_to_name(ZFS_PROP_DEDUP), 8, 1, &dedup) == 0) {
2586 		(void) nvlist_add_uint64(nv,
2587 		    zfs_prop_to_name(ZFS_PROP_DEDUP), dedup);
2588 	}
2589 	(void) zfs_set_prop_nvlist(zv->zv_name, ZPROP_SRC_LOCAL,
2590 	    nv, NULL);
2591 	nvlist_free(nv);
2592 
2593 	zvol_free_extents(zv);
2594 	zv->zv_flags &= ~ZVOL_DUMPIFIED;
2595 	(void) dmu_free_long_range(os, ZVOL_OBJ, 0, DMU_OBJECT_END);
2596 	/* wait for dmu_free_long_range to actually free the blocks */
2597 	txg_wait_synced(dmu_objset_pool(zv->zv_objset), 0);
2598 	tx = dmu_tx_create(os);
2599 	dmu_tx_hold_bonus(tx, ZVOL_OBJ);
2600 	error = dmu_tx_assign(tx, TXG_WAIT);
2601 	if (error) {
2602 		dmu_tx_abort(tx);
2603 		return (error);
2604 	}
2605 	if (dmu_object_set_blocksize(os, ZVOL_OBJ, vbs, 0, tx) == 0)
2606 		zv->zv_volblocksize = vbs;
2607 	dmu_tx_commit(tx);
2608 
2609 	return (0);
2610 }
2611 #else	/* !illumos */
2612 
2613 static void
2614 zvol_geom_run(zvol_state_t *zv)
2615 {
2616 	struct g_provider *pp;
2617 
2618 	pp = zv->zv_provider;
2619 	g_error_provider(pp, 0);
2620 
2621 	kproc_kthread_add(zvol_geom_worker, zv, &zfsproc, NULL, 0, 0,
2622 	    "zfskern", "zvol %s", pp->name + sizeof(ZVOL_DRIVER));
2623 }
2624 
2625 static void
2626 zvol_geom_destroy(zvol_state_t *zv)
2627 {
2628 	struct g_provider *pp;
2629 
2630 	g_topology_assert();
2631 
2632 	mtx_lock(&zv->zv_queue_mtx);
2633 	zv->zv_state = 1;
2634 	wakeup_one(&zv->zv_queue);
2635 	while (zv->zv_state != 2)
2636 		msleep(&zv->zv_state, &zv->zv_queue_mtx, 0, "zvol:w", 0);
2637 	mtx_destroy(&zv->zv_queue_mtx);
2638 
2639 	pp = zv->zv_provider;
2640 	zv->zv_provider = NULL;
2641 	pp->private = NULL;
2642 	g_wither_geom(pp->geom, ENXIO);
2643 }
2644 
2645 static int
2646 zvol_geom_access(struct g_provider *pp, int acr, int acw, int ace)
2647 {
2648 	int count, error, flags;
2649 
2650 	g_topology_assert();
2651 
2652 	/*
2653 	 * To make it easier we expect either open or close, but not both
2654 	 * at the same time.
2655 	 */
2656 	KASSERT((acr >= 0 && acw >= 0 && ace >= 0) ||
2657 	    (acr <= 0 && acw <= 0 && ace <= 0),
2658 	    ("Unsupported access request to %s (acr=%d, acw=%d, ace=%d).",
2659 	    pp->name, acr, acw, ace));
2660 
2661 	if (pp->private == NULL) {
2662 		if (acr <= 0 && acw <= 0 && ace <= 0)
2663 			return (0);
2664 		return (pp->error);
2665 	}
2666 
2667 	/*
2668 	 * We don't pass FEXCL flag to zvol_open()/zvol_close() if ace != 0,
2669 	 * because GEOM already handles that and handles it a bit differently.
2670 	 * GEOM allows for multiple read/exclusive consumers and ZFS allows
2671 	 * only one exclusive consumer, no matter if it is reader or writer.
2672 	 * I like better the way GEOM works so I'll leave it for GEOM to
2673 	 * decide what to do.
2674 	 */
2675 
2676 	count = acr + acw + ace;
2677 	if (count == 0)
2678 		return (0);
2679 
2680 	flags = 0;
2681 	if (acr != 0 || ace != 0)
2682 		flags |= FREAD;
2683 	if (acw != 0)
2684 		flags |= FWRITE;
2685 
2686 	g_topology_unlock();
2687 	if (count > 0)
2688 		error = zvol_open(pp, flags, count);
2689 	else
2690 		error = zvol_close(pp, flags, -count);
2691 	g_topology_lock();
2692 	return (error);
2693 }
2694 
2695 static void
2696 zvol_geom_start(struct bio *bp)
2697 {
2698 	zvol_state_t *zv;
2699 	boolean_t first;
2700 
2701 	zv = bp->bio_to->private;
2702 	ASSERT(zv != NULL);
2703 	switch (bp->bio_cmd) {
2704 	case BIO_FLUSH:
2705 		if (!THREAD_CAN_SLEEP())
2706 			goto enqueue;
2707 		zil_commit(zv->zv_zilog, ZVOL_OBJ);
2708 		g_io_deliver(bp, 0);
2709 		break;
2710 	case BIO_READ:
2711 	case BIO_WRITE:
2712 	case BIO_DELETE:
2713 		if (!THREAD_CAN_SLEEP())
2714 			goto enqueue;
2715 		zvol_strategy(bp);
2716 		break;
2717 	case BIO_GETATTR: {
2718 		spa_t *spa = dmu_objset_spa(zv->zv_objset);
2719 		uint64_t refd, avail, usedobjs, availobjs, val;
2720 
2721 		if (g_handleattr_int(bp, "GEOM::candelete", 1))
2722 			return;
2723 		if (strcmp(bp->bio_attribute, "blocksavail") == 0) {
2724 			dmu_objset_space(zv->zv_objset, &refd, &avail,
2725 			    &usedobjs, &availobjs);
2726 			if (g_handleattr_off_t(bp, "blocksavail",
2727 			    avail / DEV_BSIZE))
2728 				return;
2729 		} else if (strcmp(bp->bio_attribute, "blocksused") == 0) {
2730 			dmu_objset_space(zv->zv_objset, &refd, &avail,
2731 			    &usedobjs, &availobjs);
2732 			if (g_handleattr_off_t(bp, "blocksused",
2733 			    refd / DEV_BSIZE))
2734 				return;
2735 		} else if (strcmp(bp->bio_attribute, "poolblocksavail") == 0) {
2736 			avail = metaslab_class_get_space(spa_normal_class(spa));
2737 			avail -= metaslab_class_get_alloc(spa_normal_class(spa));
2738 			if (g_handleattr_off_t(bp, "poolblocksavail",
2739 			    avail / DEV_BSIZE))
2740 				return;
2741 		} else if (strcmp(bp->bio_attribute, "poolblocksused") == 0) {
2742 			refd = metaslab_class_get_alloc(spa_normal_class(spa));
2743 			if (g_handleattr_off_t(bp, "poolblocksused",
2744 			    refd / DEV_BSIZE))
2745 				return;
2746 		}
2747 		/* FALLTHROUGH */
2748 	}
2749 	default:
2750 		g_io_deliver(bp, EOPNOTSUPP);
2751 		break;
2752 	}
2753 	return;
2754 
2755 enqueue:
2756 	mtx_lock(&zv->zv_queue_mtx);
2757 	first = (bioq_first(&zv->zv_queue) == NULL);
2758 	bioq_insert_tail(&zv->zv_queue, bp);
2759 	mtx_unlock(&zv->zv_queue_mtx);
2760 	if (first)
2761 		wakeup_one(&zv->zv_queue);
2762 }
2763 
2764 static void
2765 zvol_geom_worker(void *arg)
2766 {
2767 	zvol_state_t *zv;
2768 	struct bio *bp;
2769 
2770 	thread_lock(curthread);
2771 	sched_prio(curthread, PRIBIO);
2772 	thread_unlock(curthread);
2773 
2774 	zv = arg;
2775 	for (;;) {
2776 		mtx_lock(&zv->zv_queue_mtx);
2777 		bp = bioq_takefirst(&zv->zv_queue);
2778 		if (bp == NULL) {
2779 			if (zv->zv_state == 1) {
2780 				zv->zv_state = 2;
2781 				wakeup(&zv->zv_state);
2782 				mtx_unlock(&zv->zv_queue_mtx);
2783 				kthread_exit();
2784 			}
2785 			msleep(&zv->zv_queue, &zv->zv_queue_mtx, PRIBIO | PDROP,
2786 			    "zvol:io", 0);
2787 			continue;
2788 		}
2789 		mtx_unlock(&zv->zv_queue_mtx);
2790 		switch (bp->bio_cmd) {
2791 		case BIO_FLUSH:
2792 			zil_commit(zv->zv_zilog, ZVOL_OBJ);
2793 			g_io_deliver(bp, 0);
2794 			break;
2795 		case BIO_READ:
2796 		case BIO_WRITE:
2797 		case BIO_DELETE:
2798 			zvol_strategy(bp);
2799 			break;
2800 		default:
2801 			g_io_deliver(bp, EOPNOTSUPP);
2802 			break;
2803 		}
2804 	}
2805 }
2806 
2807 extern boolean_t dataset_name_hidden(const char *name);
2808 
2809 static int
2810 zvol_create_snapshots(objset_t *os, const char *name)
2811 {
2812 	uint64_t cookie, obj;
2813 	char *sname;
2814 	int error, len;
2815 
2816 	cookie = obj = 0;
2817 	sname = kmem_alloc(MAXPATHLEN, KM_SLEEP);
2818 
2819 #if 0
2820 	(void) dmu_objset_find(name, dmu_objset_prefetch, NULL,
2821 	    DS_FIND_SNAPSHOTS);
2822 #endif
2823 
2824 	for (;;) {
2825 		len = snprintf(sname, MAXPATHLEN, "%s@", name);
2826 		if (len >= MAXPATHLEN) {
2827 			dmu_objset_rele(os, FTAG);
2828 			error = ENAMETOOLONG;
2829 			break;
2830 		}
2831 
2832 		dsl_pool_config_enter(dmu_objset_pool(os), FTAG);
2833 		error = dmu_snapshot_list_next(os, MAXPATHLEN - len,
2834 		    sname + len, &obj, &cookie, NULL);
2835 		dsl_pool_config_exit(dmu_objset_pool(os), FTAG);
2836 		if (error != 0) {
2837 			if (error == ENOENT)
2838 				error = 0;
2839 			break;
2840 		}
2841 
2842 		if ((error = zvol_create_minor(sname)) != 0) {
2843 			printf("ZFS WARNING: Unable to create ZVOL %s (error=%d).\n",
2844 			    sname, error);
2845 			break;
2846 		}
2847 	}
2848 
2849 	kmem_free(sname, MAXPATHLEN);
2850 	return (error);
2851 }
2852 
2853 int
2854 zvol_create_minors(const char *name)
2855 {
2856 	uint64_t cookie;
2857 	objset_t *os;
2858 	char *osname, *p;
2859 	int error, len;
2860 
2861 	if (dataset_name_hidden(name))
2862 		return (0);
2863 
2864 	if ((error = dmu_objset_hold(name, FTAG, &os)) != 0) {
2865 		printf("ZFS WARNING: Unable to put hold on %s (error=%d).\n",
2866 		    name, error);
2867 		return (error);
2868 	}
2869 	if (dmu_objset_type(os) == DMU_OST_ZVOL) {
2870 		dsl_dataset_long_hold(os->os_dsl_dataset, FTAG);
2871 		dsl_pool_rele(dmu_objset_pool(os), FTAG);
2872 		error = zvol_create_minor(name);
2873 		if (error == 0 || error == EEXIST) {
2874 			error = zvol_create_snapshots(os, name);
2875 		} else {
2876 			printf("ZFS WARNING: Unable to create ZVOL %s (error=%d).\n",
2877 			    name, error);
2878 		}
2879 		dsl_dataset_long_rele(os->os_dsl_dataset, FTAG);
2880 		dsl_dataset_rele(os->os_dsl_dataset, FTAG);
2881 		return (error);
2882 	}
2883 	if (dmu_objset_type(os) != DMU_OST_ZFS) {
2884 		dmu_objset_rele(os, FTAG);
2885 		return (0);
2886 	}
2887 
2888 	osname = kmem_alloc(MAXPATHLEN, KM_SLEEP);
2889 	if (snprintf(osname, MAXPATHLEN, "%s/", name) >= MAXPATHLEN) {
2890 		dmu_objset_rele(os, FTAG);
2891 		kmem_free(osname, MAXPATHLEN);
2892 		return (ENOENT);
2893 	}
2894 	p = osname + strlen(osname);
2895 	len = MAXPATHLEN - (p - osname);
2896 
2897 #if 0
2898 	/* Prefetch the datasets. */
2899 	cookie = 0;
2900 	while (dmu_dir_list_next(os, len, p, NULL, &cookie) == 0) {
2901 		if (!dataset_name_hidden(osname))
2902 			(void) dmu_objset_prefetch(osname, NULL);
2903 	}
2904 #endif
2905 
2906 	cookie = 0;
2907 	while (dmu_dir_list_next(os, MAXPATHLEN - (p - osname), p, NULL,
2908 	    &cookie) == 0) {
2909 		dmu_objset_rele(os, FTAG);
2910 		(void)zvol_create_minors(osname);
2911 		if ((error = dmu_objset_hold(name, FTAG, &os)) != 0) {
2912 			printf("ZFS WARNING: Unable to put hold on %s (error=%d).\n",
2913 			    name, error);
2914 			return (error);
2915 		}
2916 	}
2917 
2918 	dmu_objset_rele(os, FTAG);
2919 	kmem_free(osname, MAXPATHLEN);
2920 	return (0);
2921 }
2922 
2923 static void
2924 zvol_rename_minor(zvol_state_t *zv, const char *newname)
2925 {
2926 	struct g_geom *gp;
2927 	struct g_provider *pp;
2928 	struct cdev *dev;
2929 
2930 	ASSERT(MUTEX_HELD(&zfsdev_state_lock));
2931 
2932 	if (zv->zv_volmode == ZFS_VOLMODE_GEOM) {
2933 		g_topology_lock();
2934 		pp = zv->zv_provider;
2935 		ASSERT(pp != NULL);
2936 		gp = pp->geom;
2937 		ASSERT(gp != NULL);
2938 
2939 		zv->zv_provider = NULL;
2940 		g_wither_provider(pp, ENXIO);
2941 
2942 		pp = g_new_providerf(gp, "%s/%s", ZVOL_DRIVER, newname);
2943 		pp->flags |= G_PF_DIRECT_RECEIVE | G_PF_DIRECT_SEND;
2944 		pp->sectorsize = DEV_BSIZE;
2945 		pp->mediasize = zv->zv_volsize;
2946 		pp->private = zv;
2947 		zv->zv_provider = pp;
2948 		g_error_provider(pp, 0);
2949 		g_topology_unlock();
2950 	} else if (zv->zv_volmode == ZFS_VOLMODE_DEV) {
2951 		dev = zv->zv_dev;
2952 		ASSERT(dev != NULL);
2953 		zv->zv_dev = NULL;
2954 		destroy_dev(dev);
2955 
2956 		if (make_dev_p(MAKEDEV_CHECKNAME | MAKEDEV_WAITOK,
2957 		    &dev, &zvol_cdevsw, NULL, UID_ROOT, GID_OPERATOR,
2958 		    0640, "%s/%s", ZVOL_DRIVER, newname) == 0) {
2959 			zv->zv_dev = dev;
2960 			dev->si_iosize_max = MAXPHYS;
2961 			dev->si_drv2 = zv;
2962 		}
2963 	}
2964 	strlcpy(zv->zv_name, newname, sizeof(zv->zv_name));
2965 }
2966 
2967 void
2968 zvol_rename_minors(const char *oldname, const char *newname)
2969 {
2970 	char name[MAXPATHLEN];
2971 	struct g_provider *pp;
2972 	struct g_geom *gp;
2973 	size_t oldnamelen, newnamelen;
2974 	zvol_state_t *zv;
2975 	char *namebuf;
2976 	boolean_t locked = B_FALSE;
2977 
2978 	oldnamelen = strlen(oldname);
2979 	newnamelen = strlen(newname);
2980 
2981 	DROP_GIANT();
2982 	/* See comment in zvol_open(). */
2983 	if (!MUTEX_HELD(&zfsdev_state_lock)) {
2984 		mutex_enter(&zfsdev_state_lock);
2985 		locked = B_TRUE;
2986 	}
2987 
2988 	LIST_FOREACH(zv, &all_zvols, zv_links) {
2989 		if (strcmp(zv->zv_name, oldname) == 0) {
2990 			zvol_rename_minor(zv, newname);
2991 		} else if (strncmp(zv->zv_name, oldname, oldnamelen) == 0 &&
2992 		    (zv->zv_name[oldnamelen] == '/' ||
2993 		     zv->zv_name[oldnamelen] == '@')) {
2994 			snprintf(name, sizeof(name), "%s%c%s", newname,
2995 			    zv->zv_name[oldnamelen],
2996 			    zv->zv_name + oldnamelen + 1);
2997 			zvol_rename_minor(zv, name);
2998 		}
2999 	}
3000 
3001 	if (locked)
3002 		mutex_exit(&zfsdev_state_lock);
3003 	PICKUP_GIANT();
3004 }
3005 
3006 static int
3007 zvol_d_open(struct cdev *dev, int flags, int fmt, struct thread *td)
3008 {
3009 	zvol_state_t *zv;
3010 	int err = 0;
3011 
3012 	mutex_enter(&zfsdev_state_lock);
3013 	zv = dev->si_drv2;
3014 	if (zv == NULL) {
3015 		mutex_exit(&zfsdev_state_lock);
3016 		return(ENXIO);		/* zvol_create_minor() not done yet */
3017 	}
3018 
3019 	if (zv->zv_total_opens == 0)
3020 		err = zvol_first_open(zv);
3021 	if (err) {
3022 		mutex_exit(&zfsdev_state_lock);
3023 		return (err);
3024 	}
3025 	if ((flags & FWRITE) && (zv->zv_flags & ZVOL_RDONLY)) {
3026 		err = SET_ERROR(EROFS);
3027 		goto out;
3028 	}
3029 	if (zv->zv_flags & ZVOL_EXCL) {
3030 		err = SET_ERROR(EBUSY);
3031 		goto out;
3032 	}
3033 #ifdef FEXCL
3034 	if (flags & FEXCL) {
3035 		if (zv->zv_total_opens != 0) {
3036 			err = SET_ERROR(EBUSY);
3037 			goto out;
3038 		}
3039 		zv->zv_flags |= ZVOL_EXCL;
3040 	}
3041 #endif
3042 
3043 	zv->zv_total_opens++;
3044 	mutex_exit(&zfsdev_state_lock);
3045 	return (err);
3046 out:
3047 	if (zv->zv_total_opens == 0)
3048 		zvol_last_close(zv);
3049 	mutex_exit(&zfsdev_state_lock);
3050 	return (err);
3051 }
3052 
3053 static int
3054 zvol_d_close(struct cdev *dev, int flags, int fmt, struct thread *td)
3055 {
3056 	zvol_state_t *zv;
3057 	int err = 0;
3058 
3059 	mutex_enter(&zfsdev_state_lock);
3060 	zv = dev->si_drv2;
3061 	if (zv == NULL) {
3062 		mutex_exit(&zfsdev_state_lock);
3063 		return(ENXIO);
3064 	}
3065 
3066 	if (zv->zv_flags & ZVOL_EXCL) {
3067 		ASSERT(zv->zv_total_opens == 1);
3068 		zv->zv_flags &= ~ZVOL_EXCL;
3069 	}
3070 
3071 	/*
3072 	 * If the open count is zero, this is a spurious close.
3073 	 * That indicates a bug in the kernel / DDI framework.
3074 	 */
3075 	ASSERT(zv->zv_total_opens != 0);
3076 
3077 	/*
3078 	 * You may get multiple opens, but only one close.
3079 	 */
3080 	zv->zv_total_opens--;
3081 
3082 	if (zv->zv_total_opens == 0)
3083 		zvol_last_close(zv);
3084 
3085 	mutex_exit(&zfsdev_state_lock);
3086 	return (0);
3087 }
3088 
3089 static int
3090 zvol_d_ioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag, struct thread *td)
3091 {
3092 	zvol_state_t *zv;
3093 	rl_t *rl;
3094 	off_t offset, length, chunk;
3095 	int i, error;
3096 	u_int u;
3097 
3098 	zv = dev->si_drv2;
3099 
3100 	error = 0;
3101 	KASSERT(zv->zv_total_opens > 0,
3102 	    ("Device with zero access count in zvol_d_ioctl"));
3103 
3104 	i = IOCPARM_LEN(cmd);
3105 	switch (cmd) {
3106 	case DIOCGSECTORSIZE:
3107 		*(u_int *)data = DEV_BSIZE;
3108 		break;
3109 	case DIOCGMEDIASIZE:
3110 		*(off_t *)data = zv->zv_volsize;
3111 		break;
3112 	case DIOCGFLUSH:
3113 		zil_commit(zv->zv_zilog, ZVOL_OBJ);
3114 		break;
3115 	case DIOCGDELETE:
3116 		if (!zvol_unmap_enabled)
3117 			break;
3118 
3119 		offset = ((off_t *)data)[0];
3120 		length = ((off_t *)data)[1];
3121 		if ((offset % DEV_BSIZE) != 0 || (length % DEV_BSIZE) != 0 ||
3122 		    offset < 0 || offset >= zv->zv_volsize ||
3123 		    length <= 0) {
3124 			printf("%s: offset=%jd length=%jd\n", __func__, offset,
3125 			    length);
3126 			error = EINVAL;
3127 			break;
3128 		}
3129 
3130 		rl = zfs_range_lock(&zv->zv_znode, offset, length, RL_WRITER);
3131 		dmu_tx_t *tx = dmu_tx_create(zv->zv_objset);
3132 		error = dmu_tx_assign(tx, TXG_WAIT);
3133 		if (error != 0) {
3134 			dmu_tx_abort(tx);
3135 		} else {
3136 			zvol_log_truncate(zv, tx, offset, length, B_TRUE);
3137 			dmu_tx_commit(tx);
3138 			error = dmu_free_long_range(zv->zv_objset, ZVOL_OBJ,
3139 			    offset, length);
3140 		}
3141 		zfs_range_unlock(rl);
3142 		if (zv->zv_objset->os_sync == ZFS_SYNC_ALWAYS)
3143 			zil_commit(zv->zv_zilog, ZVOL_OBJ);
3144 		break;
3145 	case DIOCGSTRIPESIZE:
3146 		*(off_t *)data = zv->zv_volblocksize;
3147 		break;
3148 	case DIOCGSTRIPEOFFSET:
3149 		*(off_t *)data = 0;
3150 		break;
3151 	case DIOCGATTR: {
3152 		spa_t *spa = dmu_objset_spa(zv->zv_objset);
3153 		struct diocgattr_arg *arg = (struct diocgattr_arg *)data;
3154 		uint64_t refd, avail, usedobjs, availobjs;
3155 
3156 		if (strcmp(arg->name, "GEOM::candelete") == 0)
3157 			arg->value.i = 1;
3158 		else if (strcmp(arg->name, "blocksavail") == 0) {
3159 			dmu_objset_space(zv->zv_objset, &refd, &avail,
3160 			    &usedobjs, &availobjs);
3161 			arg->value.off = avail / DEV_BSIZE;
3162 		} else if (strcmp(arg->name, "blocksused") == 0) {
3163 			dmu_objset_space(zv->zv_objset, &refd, &avail,
3164 			    &usedobjs, &availobjs);
3165 			arg->value.off = refd / DEV_BSIZE;
3166 		} else if (strcmp(arg->name, "poolblocksavail") == 0) {
3167 			avail = metaslab_class_get_space(spa_normal_class(spa));
3168 			avail -= metaslab_class_get_alloc(spa_normal_class(spa));
3169 			arg->value.off = avail / DEV_BSIZE;
3170 		} else if (strcmp(arg->name, "poolblocksused") == 0) {
3171 			refd = metaslab_class_get_alloc(spa_normal_class(spa));
3172 			arg->value.off = refd / DEV_BSIZE;
3173 		} else
3174 			error = ENOIOCTL;
3175 		break;
3176 	}
3177 	case FIOSEEKHOLE:
3178 	case FIOSEEKDATA: {
3179 		off_t *off = (off_t *)data;
3180 		uint64_t noff;
3181 		boolean_t hole;
3182 
3183 		hole = (cmd == FIOSEEKHOLE);
3184 		noff = *off;
3185 		error = dmu_offset_next(zv->zv_objset, ZVOL_OBJ, hole, &noff);
3186 		*off = noff;
3187 		break;
3188 	}
3189 	default:
3190 		error = ENOIOCTL;
3191 	}
3192 
3193 	return (error);
3194 }
3195 #endif	/* illumos */
3196