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