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 * Portions Copyright 2010 Robert Milkowski
25 *
26 * Copyright 2017 Nexenta Systems, Inc.  All rights reserved.
27 * Copyright (c) 2012, 2017 by Delphix. All rights reserved.
28 * Copyright (c) 2014 Integros [integros.com]
29 * Copyright 2019 Joyent, Inc.
30 */
31
32/*
33 * ZFS volume emulation driver.
34 *
35 * Makes a DMU object look like a volume of arbitrary size, up to 2^64 bytes.
36 * Volumes are accessed through the symbolic links named:
37 *
38 * /dev/zvol/dsk/<pool_name>/<dataset_name>
39 * /dev/zvol/rdsk/<pool_name>/<dataset_name>
40 *
41 * These links are created by the /dev filesystem (sdev_zvolops.c).
42 * Volumes are persistent through reboot.  No user command needs to be
43 * run before opening and using a device.
44 */
45
46#include <sys/types.h>
47#include <sys/param.h>
48#include <sys/errno.h>
49#include <sys/uio.h>
50#include <sys/buf.h>
51#include <sys/modctl.h>
52#include <sys/open.h>
53#include <sys/kmem.h>
54#include <sys/conf.h>
55#include <sys/cmn_err.h>
56#include <sys/stat.h>
57#include <sys/zap.h>
58#include <sys/spa.h>
59#include <sys/spa_impl.h>
60#include <sys/zio.h>
61#include <sys/dmu_traverse.h>
62#include <sys/dnode.h>
63#include <sys/dsl_dataset.h>
64#include <sys/dsl_prop.h>
65#include <sys/dkio.h>
66#include <sys/efi_partition.h>
67#include <sys/byteorder.h>
68#include <sys/pathname.h>
69#include <sys/ddi.h>
70#include <sys/sunddi.h>
71#include <sys/crc32.h>
72#include <sys/dirent.h>
73#include <sys/policy.h>
74#include <sys/fs/zfs.h>
75#include <sys/zfs_ioctl.h>
76#include <sys/mkdev.h>
77#include <sys/zil.h>
78#include <sys/refcount.h>
79#include <sys/zfs_znode.h>
80#include <sys/zfs_rlock.h>
81#include <sys/vdev_disk.h>
82#include <sys/vdev_impl.h>
83#include <sys/vdev_raidz.h>
84#include <sys/zvol.h>
85#include <sys/dumphdr.h>
86#include <sys/zil_impl.h>
87#include <sys/dbuf.h>
88#include <sys/dmu_tx.h>
89#include <sys/zfeature.h>
90#include <sys/zio_checksum.h>
91#include <sys/zil_impl.h>
92#include <sys/smt.h>
93#include <sys/dkioc_free_util.h>
94#include <sys/zfs_rlock.h>
95
96#include "zfs_namecheck.h"
97
98void *zfsdev_state;
99static char *zvol_tag = "zvol_tag";
100
101#define	ZVOL_DUMPSIZE		"dumpsize"
102
103/*
104 * This lock protects the zfsdev_state structure from being modified
105 * while it's being used, e.g. an open that comes in before a create
106 * finishes.  It also protects temporary opens of the dataset so that,
107 * e.g., an open doesn't get a spurious EBUSY.
108 */
109kmutex_t zfsdev_state_lock;
110static uint32_t zvol_minors;
111
112typedef struct zvol_extent {
113	list_node_t	ze_node;
114	dva_t		ze_dva;		/* dva associated with this extent */
115	uint64_t	ze_nblks;	/* number of blocks in extent */
116} zvol_extent_t;
117
118/*
119 * The in-core state of each volume.
120 */
121typedef struct zvol_state {
122	char		zv_name[MAXPATHLEN]; /* pool/dd name */
123	uint64_t	zv_volsize;	/* amount of space we advertise */
124	uint64_t	zv_volblocksize; /* volume block size */
125	minor_t		zv_minor;	/* minor number */
126	uint8_t		zv_min_bs;	/* minimum addressable block shift */
127	uint8_t		zv_flags;	/* readonly, dumpified, etc. */
128	objset_t	*zv_objset;	/* objset handle */
129	uint32_t	zv_open_count[OTYPCNT];	/* open counts */
130	uint32_t	zv_total_opens;	/* total open count */
131	zilog_t		*zv_zilog;	/* ZIL handle */
132	list_t		zv_extents;	/* List of extents for dump */
133	rangelock_t	zv_rangelock;
134	dnode_t		*zv_dn;		/* dnode hold */
135} zvol_state_t;
136
137/*
138 * zvol specific flags
139 */
140#define	ZVOL_RDONLY	0x1
141#define	ZVOL_DUMPIFIED	0x2
142#define	ZVOL_EXCL	0x4
143#define	ZVOL_WCE	0x8
144
145/*
146 * zvol maximum transfer in one DMU tx.
147 */
148int zvol_maxphys = DMU_MAX_ACCESS/2;
149
150/*
151 * Toggle unmap functionality.
152 */
153boolean_t zvol_unmap_enabled = B_TRUE;
154
155/*
156 * If true, unmaps requested as synchronous are executed synchronously,
157 * otherwise all unmaps are asynchronous.
158 */
159boolean_t zvol_unmap_sync_enabled = B_FALSE;
160
161extern int zfs_set_prop_nvlist(const char *, zprop_source_t,
162    nvlist_t *, nvlist_t *);
163static int zvol_remove_zv(zvol_state_t *);
164static int zvol_get_data(void *arg, lr_write_t *lr, char *buf,
165    struct lwb *lwb, zio_t *zio);
166static int zvol_dumpify(zvol_state_t *zv);
167static int zvol_dump_fini(zvol_state_t *zv);
168static int zvol_dump_init(zvol_state_t *zv, boolean_t resize);
169
170static void
171zvol_size_changed(zvol_state_t *zv, uint64_t volsize)
172{
173	dev_t dev = makedevice(ddi_driver_major(zfs_dip), zv->zv_minor);
174
175	zv->zv_volsize = volsize;
176	VERIFY(ddi_prop_update_int64(dev, zfs_dip,
177	    "Size", volsize) == DDI_SUCCESS);
178	VERIFY(ddi_prop_update_int64(dev, zfs_dip,
179	    "Nblocks", lbtodb(volsize)) == DDI_SUCCESS);
180
181	/* Notify specfs to invalidate the cached size */
182	spec_size_invalidate(dev, VBLK);
183	spec_size_invalidate(dev, VCHR);
184}
185
186int
187zvol_check_volsize(uint64_t volsize, uint64_t blocksize)
188{
189	if (volsize == 0)
190		return (SET_ERROR(EINVAL));
191
192	if (volsize % blocksize != 0)
193		return (SET_ERROR(EINVAL));
194
195#ifdef _ILP32
196	if (volsize - 1 > SPEC_MAXOFFSET_T)
197		return (SET_ERROR(EOVERFLOW));
198#endif
199	return (0);
200}
201
202int
203zvol_check_volblocksize(uint64_t volblocksize)
204{
205	if (volblocksize < SPA_MINBLOCKSIZE ||
206	    volblocksize > SPA_OLD_MAXBLOCKSIZE ||
207	    !ISP2(volblocksize))
208		return (SET_ERROR(EDOM));
209
210	return (0);
211}
212
213int
214zvol_get_stats(objset_t *os, nvlist_t *nv)
215{
216	int error;
217	dmu_object_info_t doi;
218	uint64_t val;
219
220	error = zap_lookup(os, ZVOL_ZAP_OBJ, "size", 8, 1, &val);
221	if (error)
222		return (error);
223
224	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_VOLSIZE, val);
225
226	error = dmu_object_info(os, ZVOL_OBJ, &doi);
227
228	if (error == 0) {
229		dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_VOLBLOCKSIZE,
230		    doi.doi_data_block_size);
231	}
232
233	return (error);
234}
235
236static zvol_state_t *
237zvol_minor_lookup(const char *name)
238{
239	minor_t minor;
240	zvol_state_t *zv;
241
242	ASSERT(MUTEX_HELD(&zfsdev_state_lock));
243
244	for (minor = 1; minor <= ZFSDEV_MAX_MINOR; minor++) {
245		zv = zfsdev_get_soft_state(minor, ZSST_ZVOL);
246		if (zv == NULL)
247			continue;
248		if (strcmp(zv->zv_name, name) == 0)
249			return (zv);
250	}
251
252	return (NULL);
253}
254
255/* extent mapping arg */
256struct maparg {
257	zvol_state_t	*ma_zv;
258	uint64_t	ma_blks;
259};
260
261/*ARGSUSED*/
262static int
263zvol_map_block(spa_t *spa, zilog_t *zilog, const blkptr_t *bp,
264    const zbookmark_phys_t *zb, const dnode_phys_t *dnp, void *arg)
265{
266	struct maparg *ma = arg;
267	zvol_extent_t *ze;
268	int bs = ma->ma_zv->zv_volblocksize;
269
270	if (bp == NULL || BP_IS_HOLE(bp) ||
271	    zb->zb_object != ZVOL_OBJ || zb->zb_level != 0)
272		return (0);
273
274	VERIFY(!BP_IS_EMBEDDED(bp));
275
276	VERIFY3U(ma->ma_blks, ==, zb->zb_blkid);
277	ma->ma_blks++;
278
279	/* Abort immediately if we have encountered gang blocks */
280	if (BP_IS_GANG(bp))
281		return (SET_ERROR(EFRAGS));
282
283	/*
284	 * See if the block is at the end of the previous extent.
285	 */
286	ze = list_tail(&ma->ma_zv->zv_extents);
287	if (ze &&
288	    DVA_GET_VDEV(BP_IDENTITY(bp)) == DVA_GET_VDEV(&ze->ze_dva) &&
289	    DVA_GET_OFFSET(BP_IDENTITY(bp)) ==
290	    DVA_GET_OFFSET(&ze->ze_dva) + ze->ze_nblks * bs) {
291		ze->ze_nblks++;
292		return (0);
293	}
294
295	dprintf_bp(bp, "%s", "next blkptr:");
296
297	/* start a new extent */
298	ze = kmem_zalloc(sizeof (zvol_extent_t), KM_SLEEP);
299	ze->ze_dva = bp->blk_dva[0];	/* structure assignment */
300	ze->ze_nblks = 1;
301	list_insert_tail(&ma->ma_zv->zv_extents, ze);
302	return (0);
303}
304
305static void
306zvol_free_extents(zvol_state_t *zv)
307{
308	zvol_extent_t *ze;
309
310	while (ze = list_head(&zv->zv_extents)) {
311		list_remove(&zv->zv_extents, ze);
312		kmem_free(ze, sizeof (zvol_extent_t));
313	}
314}
315
316static int
317zvol_get_lbas(zvol_state_t *zv)
318{
319	objset_t *os = zv->zv_objset;
320	struct maparg	ma;
321	int		err;
322
323	ma.ma_zv = zv;
324	ma.ma_blks = 0;
325	zvol_free_extents(zv);
326
327	/* commit any in-flight changes before traversing the dataset */
328	txg_wait_synced(dmu_objset_pool(os), 0);
329	err = traverse_dataset(dmu_objset_ds(os), 0,
330	    TRAVERSE_PRE | TRAVERSE_PREFETCH_METADATA, zvol_map_block, &ma);
331	if (err || ma.ma_blks != (zv->zv_volsize / zv->zv_volblocksize)) {
332		zvol_free_extents(zv);
333		return (err ? err : EIO);
334	}
335
336	return (0);
337}
338
339/* ARGSUSED */
340void
341zvol_create_cb(objset_t *os, void *arg, cred_t *cr, dmu_tx_t *tx)
342{
343	zfs_creat_t *zct = arg;
344	nvlist_t *nvprops = zct->zct_props;
345	int error;
346	uint64_t volblocksize, volsize;
347
348	VERIFY(nvlist_lookup_uint64(nvprops,
349	    zfs_prop_to_name(ZFS_PROP_VOLSIZE), &volsize) == 0);
350	if (nvlist_lookup_uint64(nvprops,
351	    zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE), &volblocksize) != 0)
352		volblocksize = zfs_prop_default_numeric(ZFS_PROP_VOLBLOCKSIZE);
353
354	/*
355	 * These properties must be removed from the list so the generic
356	 * property setting step won't apply to them.
357	 */
358	VERIFY(nvlist_remove_all(nvprops,
359	    zfs_prop_to_name(ZFS_PROP_VOLSIZE)) == 0);
360	(void) nvlist_remove_all(nvprops,
361	    zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE));
362
363	error = dmu_object_claim(os, ZVOL_OBJ, DMU_OT_ZVOL, volblocksize,
364	    DMU_OT_NONE, 0, tx);
365	ASSERT(error == 0);
366
367	error = zap_create_claim(os, ZVOL_ZAP_OBJ, DMU_OT_ZVOL_PROP,
368	    DMU_OT_NONE, 0, tx);
369	ASSERT(error == 0);
370
371	error = zap_update(os, ZVOL_ZAP_OBJ, "size", 8, 1, &volsize, tx);
372	ASSERT(error == 0);
373}
374
375/*
376 * Replay a TX_TRUNCATE ZIL transaction if asked.  TX_TRUNCATE is how we
377 * implement DKIOCFREE/free-long-range.
378 */
379static int
380zvol_replay_truncate(void *arg1, void *arg2, boolean_t byteswap)
381{
382	zvol_state_t *zv = arg1;
383	lr_truncate_t *lr = arg2;
384	uint64_t offset, length;
385
386	if (byteswap)
387		byteswap_uint64_array(lr, sizeof (*lr));
388
389	offset = lr->lr_offset;
390	length = lr->lr_length;
391
392	return (dmu_free_long_range(zv->zv_objset, ZVOL_OBJ, offset, length));
393}
394
395/*
396 * Replay a TX_WRITE ZIL transaction that didn't get committed
397 * after a system failure
398 */
399/* ARGSUSED */
400static int
401zvol_replay_write(void *arg1, void *arg2, boolean_t byteswap)
402{
403	zvol_state_t *zv = arg1;
404	lr_write_t *lr = arg2;
405	objset_t *os = zv->zv_objset;
406	char *data = (char *)(lr + 1);	/* data follows lr_write_t */
407	uint64_t offset, length;
408	dmu_tx_t *tx;
409	int error;
410
411	if (byteswap)
412		byteswap_uint64_array(lr, sizeof (*lr));
413
414	offset = lr->lr_offset;
415	length = lr->lr_length;
416
417	/* If it's a dmu_sync() block, write the whole block */
418	if (lr->lr_common.lrc_reclen == sizeof (lr_write_t)) {
419		uint64_t blocksize = BP_GET_LSIZE(&lr->lr_blkptr);
420		if (length < blocksize) {
421			offset -= offset % blocksize;
422			length = blocksize;
423		}
424	}
425
426	tx = dmu_tx_create(os);
427	dmu_tx_hold_write(tx, ZVOL_OBJ, offset, length);
428	error = dmu_tx_assign(tx, TXG_WAIT);
429	if (error) {
430		dmu_tx_abort(tx);
431	} else {
432		dmu_write(os, ZVOL_OBJ, offset, length, data, tx);
433		dmu_tx_commit(tx);
434	}
435
436	return (error);
437}
438
439/* ARGSUSED */
440static int
441zvol_replay_err(void *arg1, void *arg2, boolean_t byteswap)
442{
443	return (SET_ERROR(ENOTSUP));
444}
445
446/*
447 * Callback vectors for replaying records.
448 * Only TX_WRITE and TX_TRUNCATE are needed for zvol.
449 */
450zil_replay_func_t *zvol_replay_vector[TX_MAX_TYPE] = {
451	zvol_replay_err,	/* 0 no such transaction type */
452	zvol_replay_err,	/* TX_CREATE */
453	zvol_replay_err,	/* TX_MKDIR */
454	zvol_replay_err,	/* TX_MKXATTR */
455	zvol_replay_err,	/* TX_SYMLINK */
456	zvol_replay_err,	/* TX_REMOVE */
457	zvol_replay_err,	/* TX_RMDIR */
458	zvol_replay_err,	/* TX_LINK */
459	zvol_replay_err,	/* TX_RENAME */
460	zvol_replay_write,	/* TX_WRITE */
461	zvol_replay_truncate,	/* TX_TRUNCATE */
462	zvol_replay_err,	/* TX_SETATTR */
463	zvol_replay_err,	/* TX_ACL */
464	zvol_replay_err,	/* TX_CREATE_ACL */
465	zvol_replay_err,	/* TX_CREATE_ATTR */
466	zvol_replay_err,	/* TX_CREATE_ACL_ATTR */
467	zvol_replay_err,	/* TX_MKDIR_ACL */
468	zvol_replay_err,	/* TX_MKDIR_ATTR */
469	zvol_replay_err,	/* TX_MKDIR_ACL_ATTR */
470	zvol_replay_err,	/* TX_WRITE2 */
471};
472
473int
474zvol_name2minor(const char *name, minor_t *minor)
475{
476	zvol_state_t *zv;
477
478	mutex_enter(&zfsdev_state_lock);
479	zv = zvol_minor_lookup(name);
480	if (minor && zv)
481		*minor = zv->zv_minor;
482	mutex_exit(&zfsdev_state_lock);
483	return (zv ? 0 : -1);
484}
485
486/*
487 * Create a minor node (plus a whole lot more) for the specified volume.
488 */
489int
490zvol_create_minor(const char *name)
491{
492	zfs_soft_state_t *zs;
493	zvol_state_t *zv;
494	objset_t *os;
495	dmu_object_info_t doi;
496	minor_t minor = 0;
497	char chrbuf[30], blkbuf[30];
498	int error;
499
500	mutex_enter(&zfsdev_state_lock);
501
502	if (zvol_minor_lookup(name) != NULL) {
503		mutex_exit(&zfsdev_state_lock);
504		return (SET_ERROR(EEXIST));
505	}
506
507	/* lie and say we're read-only */
508	error = dmu_objset_own(name, DMU_OST_ZVOL, B_TRUE, B_TRUE, FTAG, &os);
509
510	if (error) {
511		mutex_exit(&zfsdev_state_lock);
512		return (error);
513	}
514
515	if ((minor = zfsdev_minor_alloc()) == 0) {
516		dmu_objset_disown(os, 1, FTAG);
517		mutex_exit(&zfsdev_state_lock);
518		return (SET_ERROR(ENXIO));
519	}
520
521	if (ddi_soft_state_zalloc(zfsdev_state, minor) != DDI_SUCCESS) {
522		dmu_objset_disown(os, 1, FTAG);
523		mutex_exit(&zfsdev_state_lock);
524		return (SET_ERROR(EAGAIN));
525	}
526	(void) ddi_prop_update_string(minor, zfs_dip, ZVOL_PROP_NAME,
527	    (char *)name);
528
529	(void) snprintf(chrbuf, sizeof (chrbuf), "%u,raw", minor);
530
531	if (ddi_create_minor_node(zfs_dip, chrbuf, S_IFCHR,
532	    minor, DDI_PSEUDO, 0) == DDI_FAILURE) {
533		ddi_soft_state_free(zfsdev_state, minor);
534		dmu_objset_disown(os, 1, FTAG);
535		mutex_exit(&zfsdev_state_lock);
536		return (SET_ERROR(EAGAIN));
537	}
538
539	(void) snprintf(blkbuf, sizeof (blkbuf), "%u", minor);
540
541	if (ddi_create_minor_node(zfs_dip, blkbuf, S_IFBLK,
542	    minor, DDI_PSEUDO, 0) == DDI_FAILURE) {
543		ddi_remove_minor_node(zfs_dip, chrbuf);
544		ddi_soft_state_free(zfsdev_state, minor);
545		dmu_objset_disown(os, 1, FTAG);
546		mutex_exit(&zfsdev_state_lock);
547		return (SET_ERROR(EAGAIN));
548	}
549
550	zs = ddi_get_soft_state(zfsdev_state, minor);
551	zs->zss_type = ZSST_ZVOL;
552	zv = zs->zss_data = kmem_zalloc(sizeof (zvol_state_t), KM_SLEEP);
553	(void) strlcpy(zv->zv_name, name, MAXPATHLEN);
554	zv->zv_min_bs = DEV_BSHIFT;
555	zv->zv_minor = minor;
556	zv->zv_objset = os;
557	if (dmu_objset_is_snapshot(os) || !spa_writeable(dmu_objset_spa(os)))
558		zv->zv_flags |= ZVOL_RDONLY;
559	rangelock_init(&zv->zv_rangelock, NULL, NULL);
560	list_create(&zv->zv_extents, sizeof (zvol_extent_t),
561	    offsetof(zvol_extent_t, ze_node));
562	/* get and cache the blocksize */
563	error = dmu_object_info(os, ZVOL_OBJ, &doi);
564	ASSERT(error == 0);
565	zv->zv_volblocksize = doi.doi_data_block_size;
566
567	if (spa_writeable(dmu_objset_spa(os))) {
568		if (zil_replay_disable)
569			zil_destroy(dmu_objset_zil(os), B_FALSE);
570		else
571			zil_replay(os, zv, zvol_replay_vector);
572	}
573	dmu_objset_disown(os, 1, FTAG);
574	zv->zv_objset = NULL;
575
576	zvol_minors++;
577
578	mutex_exit(&zfsdev_state_lock);
579
580	return (0);
581}
582
583/*
584 * Remove minor node for the specified volume.
585 */
586static int
587zvol_remove_zv(zvol_state_t *zv)
588{
589	char nmbuf[20];
590	minor_t minor = zv->zv_minor;
591
592	ASSERT(MUTEX_HELD(&zfsdev_state_lock));
593	if (zv->zv_total_opens != 0)
594		return (SET_ERROR(EBUSY));
595
596	(void) snprintf(nmbuf, sizeof (nmbuf), "%u,raw", minor);
597	ddi_remove_minor_node(zfs_dip, nmbuf);
598
599	(void) snprintf(nmbuf, sizeof (nmbuf), "%u", minor);
600	ddi_remove_minor_node(zfs_dip, nmbuf);
601
602	rangelock_fini(&zv->zv_rangelock);
603
604	kmem_free(zv, sizeof (zvol_state_t));
605
606	ddi_soft_state_free(zfsdev_state, minor);
607
608	zvol_minors--;
609	return (0);
610}
611
612int
613zvol_remove_minor(const char *name)
614{
615	zvol_state_t *zv;
616	int rc;
617
618	mutex_enter(&zfsdev_state_lock);
619	if ((zv = zvol_minor_lookup(name)) == NULL) {
620		mutex_exit(&zfsdev_state_lock);
621		return (SET_ERROR(ENXIO));
622	}
623	rc = zvol_remove_zv(zv);
624	mutex_exit(&zfsdev_state_lock);
625	return (rc);
626}
627
628int
629zvol_first_open(zvol_state_t *zv, boolean_t rdonly)
630{
631	objset_t *os;
632	uint64_t volsize;
633	int error;
634	uint64_t readonly;
635	boolean_t ro;
636
637	ro = (rdonly || (strchr(zv->zv_name, '@') != NULL));
638	error = dmu_objset_own(zv->zv_name, DMU_OST_ZVOL, ro, B_TRUE, zv, &os);
639	if (error)
640		return (error);
641
642	zv->zv_objset = os;
643	error = zap_lookup(os, ZVOL_ZAP_OBJ, "size", 8, 1, &volsize);
644	if (error) {
645		ASSERT(error == 0);
646		dmu_objset_disown(os, 1, zv);
647		return (error);
648	}
649
650	error = dnode_hold(os, ZVOL_OBJ, zvol_tag, &zv->zv_dn);
651	if (error) {
652		dmu_objset_disown(os, 1, zv);
653		return (error);
654	}
655
656	zvol_size_changed(zv, volsize);
657	zv->zv_zilog = zil_open(os, zvol_get_data);
658
659	VERIFY(dsl_prop_get_integer(zv->zv_name, "readonly", &readonly,
660	    NULL) == 0);
661	if (readonly || dmu_objset_is_snapshot(os) ||
662	    !spa_writeable(dmu_objset_spa(os)))
663		zv->zv_flags |= ZVOL_RDONLY;
664	else
665		zv->zv_flags &= ~ZVOL_RDONLY;
666	return (error);
667}
668
669void
670zvol_last_close(zvol_state_t *zv)
671{
672	zil_close(zv->zv_zilog);
673	zv->zv_zilog = NULL;
674
675	dnode_rele(zv->zv_dn, zvol_tag);
676	zv->zv_dn = NULL;
677
678	/*
679	 * Evict cached data
680	 */
681	if (dsl_dataset_is_dirty(dmu_objset_ds(zv->zv_objset)) &&
682	    !(zv->zv_flags & ZVOL_RDONLY))
683		txg_wait_synced(dmu_objset_pool(zv->zv_objset), 0);
684	dmu_objset_evict_dbufs(zv->zv_objset);
685
686	dmu_objset_disown(zv->zv_objset, 1, zv);
687	zv->zv_objset = NULL;
688}
689
690int
691zvol_prealloc(zvol_state_t *zv)
692{
693	objset_t *os = zv->zv_objset;
694	dmu_tx_t *tx;
695	uint64_t refd, avail, usedobjs, availobjs;
696	uint64_t resid = zv->zv_volsize;
697	uint64_t off = 0;
698
699	/* Check the space usage before attempting to allocate the space */
700	dmu_objset_space(os, &refd, &avail, &usedobjs, &availobjs);
701	if (avail < zv->zv_volsize)
702		return (SET_ERROR(ENOSPC));
703
704	/* Free old extents if they exist */
705	zvol_free_extents(zv);
706
707	while (resid != 0) {
708		int error;
709		uint64_t bytes = MIN(resid, SPA_OLD_MAXBLOCKSIZE);
710
711		tx = dmu_tx_create(os);
712		dmu_tx_hold_write(tx, ZVOL_OBJ, off, bytes);
713		error = dmu_tx_assign(tx, TXG_WAIT);
714		if (error) {
715			dmu_tx_abort(tx);
716			(void) dmu_free_long_range(os, ZVOL_OBJ, 0, off);
717			return (error);
718		}
719		dmu_prealloc(os, ZVOL_OBJ, off, bytes, tx);
720		dmu_tx_commit(tx);
721		off += bytes;
722		resid -= bytes;
723	}
724	txg_wait_synced(dmu_objset_pool(os), 0);
725
726	return (0);
727}
728
729static int
730zvol_update_volsize(objset_t *os, uint64_t volsize)
731{
732	dmu_tx_t *tx;
733	int error;
734	uint64_t txg;
735
736	ASSERT(MUTEX_HELD(&zfsdev_state_lock));
737
738	tx = dmu_tx_create(os);
739	dmu_tx_hold_zap(tx, ZVOL_ZAP_OBJ, TRUE, NULL);
740	dmu_tx_mark_netfree(tx);
741	error = dmu_tx_assign(tx, TXG_WAIT);
742	if (error) {
743		dmu_tx_abort(tx);
744		return (error);
745	}
746	txg = dmu_tx_get_txg(tx);
747
748	error = zap_update(os, ZVOL_ZAP_OBJ, "size", 8, 1,
749	    &volsize, tx);
750	dmu_tx_commit(tx);
751
752	txg_wait_synced(dmu_objset_pool(os), txg);
753
754	if (error == 0)
755		error = dmu_free_long_range(os,
756		    ZVOL_OBJ, volsize, DMU_OBJECT_END);
757	return (error);
758}
759
760void
761zvol_remove_minors(const char *name)
762{
763	zvol_state_t *zv;
764	char *namebuf;
765	minor_t minor;
766
767	namebuf = kmem_zalloc(strlen(name) + 2, KM_SLEEP);
768	(void) strncpy(namebuf, name, strlen(name));
769	(void) strcat(namebuf, "/");
770	mutex_enter(&zfsdev_state_lock);
771	for (minor = 1; minor <= ZFSDEV_MAX_MINOR; minor++) {
772
773		zv = zfsdev_get_soft_state(minor, ZSST_ZVOL);
774		if (zv == NULL)
775			continue;
776		if (strncmp(namebuf, zv->zv_name, strlen(namebuf)) == 0)
777			(void) zvol_remove_zv(zv);
778	}
779	kmem_free(namebuf, strlen(name) + 2);
780
781	mutex_exit(&zfsdev_state_lock);
782}
783
784static int
785zvol_update_live_volsize(zvol_state_t *zv, uint64_t volsize)
786{
787	uint64_t old_volsize = 0ULL;
788	int error = 0;
789
790	ASSERT(MUTEX_HELD(&zfsdev_state_lock));
791
792	/*
793	 * Reinitialize the dump area to the new size. If we
794	 * failed to resize the dump area then restore it back to
795	 * its original size.  We must set the new volsize prior
796	 * to calling dumpvp_resize() to ensure that the devices'
797	 * size(9P) is not visible by the dump subsystem.
798	 */
799	old_volsize = zv->zv_volsize;
800	zvol_size_changed(zv, volsize);
801
802	if (zv->zv_flags & ZVOL_DUMPIFIED) {
803		if ((error = zvol_dumpify(zv)) != 0 ||
804		    (error = dumpvp_resize()) != 0) {
805			int dumpify_error;
806
807			(void) zvol_update_volsize(zv->zv_objset, old_volsize);
808			zvol_size_changed(zv, old_volsize);
809			dumpify_error = zvol_dumpify(zv);
810			error = dumpify_error ? dumpify_error : error;
811		}
812	}
813
814	/*
815	 * Generate a LUN expansion event.
816	 */
817	if (error == 0) {
818		sysevent_id_t eid;
819		nvlist_t *attr;
820		char *physpath = kmem_zalloc(MAXPATHLEN, KM_SLEEP);
821
822		(void) snprintf(physpath, MAXPATHLEN, "%s%u", ZVOL_PSEUDO_DEV,
823		    zv->zv_minor);
824
825		VERIFY(nvlist_alloc(&attr, NV_UNIQUE_NAME, KM_SLEEP) == 0);
826		VERIFY(nvlist_add_string(attr, DEV_PHYS_PATH, physpath) == 0);
827
828		(void) ddi_log_sysevent(zfs_dip, SUNW_VENDOR, EC_DEV_STATUS,
829		    ESC_DEV_DLE, attr, &eid, DDI_SLEEP);
830
831		nvlist_free(attr);
832		kmem_free(physpath, MAXPATHLEN);
833	}
834	return (error);
835}
836
837int
838zvol_set_volsize(const char *name, uint64_t volsize)
839{
840	zvol_state_t *zv = NULL;
841	objset_t *os;
842	int error;
843	dmu_object_info_t doi;
844	uint64_t readonly;
845	boolean_t owned = B_FALSE;
846
847	error = dsl_prop_get_integer(name,
848	    zfs_prop_to_name(ZFS_PROP_READONLY), &readonly, NULL);
849	if (error != 0)
850		return (error);
851	if (readonly)
852		return (SET_ERROR(EROFS));
853
854	mutex_enter(&zfsdev_state_lock);
855	zv = zvol_minor_lookup(name);
856
857	if (zv == NULL || zv->zv_objset == NULL) {
858		if ((error = dmu_objset_own(name, DMU_OST_ZVOL, B_FALSE, B_TRUE,
859		    FTAG, &os)) != 0) {
860			mutex_exit(&zfsdev_state_lock);
861			return (error);
862		}
863		owned = B_TRUE;
864		if (zv != NULL)
865			zv->zv_objset = os;
866	} else {
867		os = zv->zv_objset;
868	}
869
870	if ((error = dmu_object_info(os, ZVOL_OBJ, &doi)) != 0 ||
871	    (error = zvol_check_volsize(volsize, doi.doi_data_block_size)) != 0)
872		goto out;
873
874	error = zvol_update_volsize(os, volsize);
875
876	if (error == 0 && zv != NULL)
877		error = zvol_update_live_volsize(zv, volsize);
878out:
879	if (owned) {
880		dmu_objset_disown(os, B_TRUE, FTAG);
881		if (zv != NULL)
882			zv->zv_objset = NULL;
883	}
884	mutex_exit(&zfsdev_state_lock);
885	return (error);
886}
887
888/*ARGSUSED*/
889int
890zvol_open(dev_t *devp, int flag, int otyp, cred_t *cr)
891{
892	zvol_state_t *zv;
893	int err = 0;
894
895	mutex_enter(&zfsdev_state_lock);
896
897	zv = zfsdev_get_soft_state(getminor(*devp), ZSST_ZVOL);
898	if (zv == NULL) {
899		mutex_exit(&zfsdev_state_lock);
900		return (SET_ERROR(ENXIO));
901	}
902
903	if (zv->zv_total_opens == 0)
904		err = zvol_first_open(zv, !(flag & FWRITE));
905	if (err) {
906		mutex_exit(&zfsdev_state_lock);
907		return (err);
908	}
909
910	if ((flag & FWRITE) && (zv->zv_flags & ZVOL_RDONLY)) {
911		err = SET_ERROR(EROFS);
912		goto out;
913	}
914	if (zv->zv_flags & ZVOL_EXCL) {
915		err = SET_ERROR(EBUSY);
916		goto out;
917	}
918	if (flag & FEXCL) {
919		if (zv->zv_total_opens != 0) {
920			err = SET_ERROR(EBUSY);
921			goto out;
922		}
923		zv->zv_flags |= ZVOL_EXCL;
924	}
925
926	if (zv->zv_open_count[otyp] == 0 || otyp == OTYP_LYR) {
927		zv->zv_open_count[otyp]++;
928		zv->zv_total_opens++;
929	}
930	mutex_exit(&zfsdev_state_lock);
931
932	return (err);
933out:
934	if (zv->zv_total_opens == 0)
935		zvol_last_close(zv);
936	mutex_exit(&zfsdev_state_lock);
937	return (err);
938}
939
940/*ARGSUSED*/
941int
942zvol_close(dev_t dev, int flag, int otyp, cred_t *cr)
943{
944	minor_t minor = getminor(dev);
945	zvol_state_t *zv;
946	int error = 0;
947
948	mutex_enter(&zfsdev_state_lock);
949
950	zv = zfsdev_get_soft_state(minor, ZSST_ZVOL);
951	if (zv == NULL) {
952		mutex_exit(&zfsdev_state_lock);
953		return (SET_ERROR(ENXIO));
954	}
955
956	if (zv->zv_flags & ZVOL_EXCL) {
957		ASSERT(zv->zv_total_opens == 1);
958		zv->zv_flags &= ~ZVOL_EXCL;
959	}
960
961	/*
962	 * If the open count is zero, this is a spurious close.
963	 * That indicates a bug in the kernel / DDI framework.
964	 */
965	ASSERT(zv->zv_open_count[otyp] != 0);
966	ASSERT(zv->zv_total_opens != 0);
967
968	/*
969	 * You may get multiple opens, but only one close.
970	 */
971	zv->zv_open_count[otyp]--;
972	zv->zv_total_opens--;
973
974	if (zv->zv_total_opens == 0)
975		zvol_last_close(zv);
976
977	mutex_exit(&zfsdev_state_lock);
978	return (error);
979}
980
981/* ARGSUSED */
982static void
983zvol_get_done(zgd_t *zgd, int error)
984{
985	if (zgd->zgd_db)
986		dmu_buf_rele(zgd->zgd_db, zgd);
987
988	rangelock_exit(zgd->zgd_lr);
989
990	kmem_free(zgd, sizeof (zgd_t));
991}
992
993/*
994 * Get data to generate a TX_WRITE intent log record.
995 */
996static int
997zvol_get_data(void *arg, lr_write_t *lr, char *buf, struct lwb *lwb, zio_t *zio)
998{
999	zvol_state_t *zv = arg;
1000	uint64_t offset = lr->lr_offset;
1001	uint64_t size = lr->lr_length;	/* length of user data */
1002	dmu_buf_t *db;
1003	zgd_t *zgd;
1004	int error;
1005
1006	ASSERT3P(lwb, !=, NULL);
1007	ASSERT3P(zio, !=, NULL);
1008	ASSERT3U(size, !=, 0);
1009
1010	zgd = kmem_zalloc(sizeof (zgd_t), KM_SLEEP);
1011	zgd->zgd_lwb = lwb;
1012
1013	/*
1014	 * Write records come in two flavors: immediate and indirect.
1015	 * For small writes it's cheaper to store the data with the
1016	 * log record (immediate); for large writes it's cheaper to
1017	 * sync the data and get a pointer to it (indirect) so that
1018	 * we don't have to write the data twice.
1019	 */
1020	if (buf != NULL) { /* immediate write */
1021		zgd->zgd_lr = rangelock_enter(&zv->zv_rangelock, offset, size,
1022		    RL_READER);
1023		error = dmu_read_by_dnode(zv->zv_dn, offset, size, buf,
1024		    DMU_READ_NO_PREFETCH);
1025	} else { /* indirect write */
1026		/*
1027		 * Have to lock the whole block to ensure when it's written out
1028		 * and its checksum is being calculated that no one can change
1029		 * the data. Contrarily to zfs_get_data we need not re-check
1030		 * blocksize after we get the lock because it cannot be changed.
1031		 */
1032		size = zv->zv_volblocksize;
1033		offset = P2ALIGN(offset, size);
1034		zgd->zgd_lr = rangelock_enter(&zv->zv_rangelock, offset, size,
1035		    RL_READER);
1036		error = dmu_buf_hold_by_dnode(zv->zv_dn, offset, zgd, &db,
1037		    DMU_READ_NO_PREFETCH);
1038		if (error == 0) {
1039			blkptr_t *bp = &lr->lr_blkptr;
1040
1041			zgd->zgd_db = db;
1042			zgd->zgd_bp = bp;
1043
1044			ASSERT(db->db_offset == offset);
1045			ASSERT(db->db_size == size);
1046
1047			error = dmu_sync(zio, lr->lr_common.lrc_txg,
1048			    zvol_get_done, zgd);
1049
1050			if (error == 0)
1051				return (0);
1052		}
1053	}
1054
1055	zvol_get_done(zgd, error);
1056
1057	return (error);
1058}
1059
1060/*
1061 * zvol_log_write() handles synchronous writes using TX_WRITE ZIL transactions.
1062 *
1063 * We store data in the log buffers if it's small enough.
1064 * Otherwise we will later flush the data out via dmu_sync().
1065 */
1066ssize_t zvol_immediate_write_sz = 32768;
1067
1068static void
1069zvol_log_write(zvol_state_t *zv, dmu_tx_t *tx, offset_t off, ssize_t resid,
1070    boolean_t sync)
1071{
1072	uint32_t blocksize = zv->zv_volblocksize;
1073	zilog_t *zilog = zv->zv_zilog;
1074	itx_wr_state_t write_state;
1075
1076	if (zil_replaying(zilog, tx))
1077		return;
1078
1079	if (zilog->zl_logbias == ZFS_LOGBIAS_THROUGHPUT)
1080		write_state = WR_INDIRECT;
1081	else if (!spa_has_slogs(zilog->zl_spa) &&
1082	    resid >= blocksize && blocksize > zvol_immediate_write_sz)
1083		write_state = WR_INDIRECT;
1084	else if (sync)
1085		write_state = WR_COPIED;
1086	else
1087		write_state = WR_NEED_COPY;
1088
1089	while (resid) {
1090		itx_t *itx;
1091		lr_write_t *lr;
1092		itx_wr_state_t wr_state = write_state;
1093		ssize_t len = resid;
1094
1095		if (wr_state == WR_COPIED && resid > ZIL_MAX_COPIED_DATA)
1096			wr_state = WR_NEED_COPY;
1097		else if (wr_state == WR_INDIRECT)
1098			len = MIN(blocksize - P2PHASE(off, blocksize), resid);
1099
1100		itx = zil_itx_create(TX_WRITE, sizeof (*lr) +
1101		    (wr_state == WR_COPIED ? len : 0));
1102		lr = (lr_write_t *)&itx->itx_lr;
1103		if (wr_state == WR_COPIED && dmu_read_by_dnode(zv->zv_dn,
1104		    off, len, lr + 1, DMU_READ_NO_PREFETCH) != 0) {
1105			zil_itx_destroy(itx);
1106			itx = zil_itx_create(TX_WRITE, sizeof (*lr));
1107			lr = (lr_write_t *)&itx->itx_lr;
1108			wr_state = WR_NEED_COPY;
1109		}
1110
1111		itx->itx_wr_state = wr_state;
1112		lr->lr_foid = ZVOL_OBJ;
1113		lr->lr_offset = off;
1114		lr->lr_length = len;
1115		lr->lr_blkoff = 0;
1116		BP_ZERO(&lr->lr_blkptr);
1117
1118		itx->itx_private = zv;
1119		itx->itx_sync = sync;
1120
1121		zil_itx_assign(zilog, itx, tx);
1122
1123		off += len;
1124		resid -= len;
1125	}
1126}
1127
1128static int
1129zvol_dumpio_vdev(vdev_t *vd, void *addr, uint64_t offset, uint64_t origoffset,
1130    uint64_t size, boolean_t doread, boolean_t isdump)
1131{
1132	vdev_disk_t *dvd;
1133	int c;
1134	int numerrors = 0;
1135
1136	if (vd->vdev_ops == &vdev_mirror_ops ||
1137	    vd->vdev_ops == &vdev_replacing_ops ||
1138	    vd->vdev_ops == &vdev_spare_ops) {
1139		for (c = 0; c < vd->vdev_children; c++) {
1140			int err = zvol_dumpio_vdev(vd->vdev_child[c],
1141			    addr, offset, origoffset, size, doread, isdump);
1142			if (err != 0) {
1143				numerrors++;
1144			} else if (doread) {
1145				break;
1146			}
1147		}
1148	}
1149
1150	if (!vd->vdev_ops->vdev_op_leaf && vd->vdev_ops != &vdev_raidz_ops)
1151		return (numerrors < vd->vdev_children ? 0 : EIO);
1152
1153	if (doread && !vdev_readable(vd))
1154		return (SET_ERROR(EIO));
1155	else if (!doread && !vdev_writeable(vd))
1156		return (SET_ERROR(EIO));
1157
1158	if (vd->vdev_ops == &vdev_raidz_ops) {
1159		return (vdev_raidz_physio(vd,
1160		    addr, size, offset, origoffset, doread, isdump));
1161	}
1162
1163	offset += VDEV_LABEL_START_SIZE;
1164
1165	if (ddi_in_panic() || isdump) {
1166		ASSERT(!doread);
1167		if (doread)
1168			return (SET_ERROR(EIO));
1169		dvd = vd->vdev_tsd;
1170		ASSERT3P(dvd, !=, NULL);
1171		return (ldi_dump(dvd->vd_lh, addr, lbtodb(offset),
1172		    lbtodb(size)));
1173	} else {
1174		dvd = vd->vdev_tsd;
1175		ASSERT3P(dvd, !=, NULL);
1176		return (vdev_disk_ldi_physio(dvd->vd_lh, addr, size,
1177		    offset, doread ? B_READ : B_WRITE));
1178	}
1179}
1180
1181static int
1182zvol_dumpio(zvol_state_t *zv, void *addr, uint64_t offset, uint64_t size,
1183    boolean_t doread, boolean_t isdump)
1184{
1185	vdev_t *vd;
1186	int error;
1187	zvol_extent_t *ze;
1188	spa_t *spa = dmu_objset_spa(zv->zv_objset);
1189
1190	/* Must be sector aligned, and not stradle a block boundary. */
1191	if (P2PHASE(offset, DEV_BSIZE) || P2PHASE(size, DEV_BSIZE) ||
1192	    P2BOUNDARY(offset, size, zv->zv_volblocksize)) {
1193		return (SET_ERROR(EINVAL));
1194	}
1195	ASSERT(size <= zv->zv_volblocksize);
1196
1197	/* Locate the extent this belongs to */
1198	ze = list_head(&zv->zv_extents);
1199	while (offset >= ze->ze_nblks * zv->zv_volblocksize) {
1200		offset -= ze->ze_nblks * zv->zv_volblocksize;
1201		ze = list_next(&zv->zv_extents, ze);
1202	}
1203
1204	if (ze == NULL)
1205		return (SET_ERROR(EINVAL));
1206
1207	if (!ddi_in_panic())
1208		spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
1209
1210	vd = vdev_lookup_top(spa, DVA_GET_VDEV(&ze->ze_dva));
1211	offset += DVA_GET_OFFSET(&ze->ze_dva);
1212	error = zvol_dumpio_vdev(vd, addr, offset, DVA_GET_OFFSET(&ze->ze_dva),
1213	    size, doread, isdump);
1214
1215	if (!ddi_in_panic())
1216		spa_config_exit(spa, SCL_STATE, FTAG);
1217
1218	return (error);
1219}
1220
1221int
1222zvol_strategy(buf_t *bp)
1223{
1224	zfs_soft_state_t *zs = NULL;
1225	zvol_state_t *zv;
1226	uint64_t off, volsize;
1227	size_t resid;
1228	char *addr;
1229	objset_t *os;
1230	int error = 0;
1231	boolean_t doread = bp->b_flags & B_READ;
1232	boolean_t is_dumpified;
1233	boolean_t sync;
1234
1235	if (getminor(bp->b_edev) == 0) {
1236		error = SET_ERROR(EINVAL);
1237	} else {
1238		zs = ddi_get_soft_state(zfsdev_state, getminor(bp->b_edev));
1239		if (zs == NULL)
1240			error = SET_ERROR(ENXIO);
1241		else if (zs->zss_type != ZSST_ZVOL)
1242			error = SET_ERROR(EINVAL);
1243	}
1244
1245	if (error) {
1246		bioerror(bp, error);
1247		biodone(bp);
1248		return (0);
1249	}
1250
1251	zv = zs->zss_data;
1252
1253	if (!(bp->b_flags & B_READ) && (zv->zv_flags & ZVOL_RDONLY)) {
1254		bioerror(bp, EROFS);
1255		biodone(bp);
1256		return (0);
1257	}
1258
1259	off = ldbtob(bp->b_blkno);
1260	volsize = zv->zv_volsize;
1261
1262	os = zv->zv_objset;
1263	ASSERT(os != NULL);
1264
1265	bp_mapin(bp);
1266	addr = bp->b_un.b_addr;
1267	resid = bp->b_bcount;
1268
1269	if (resid > 0 && (off < 0 || off >= volsize)) {
1270		bioerror(bp, EIO);
1271		biodone(bp);
1272		return (0);
1273	}
1274
1275	is_dumpified = zv->zv_flags & ZVOL_DUMPIFIED;
1276	sync = ((!(bp->b_flags & B_ASYNC) &&
1277	    !(zv->zv_flags & ZVOL_WCE)) ||
1278	    (zv->zv_objset->os_sync == ZFS_SYNC_ALWAYS)) &&
1279	    !doread && !is_dumpified;
1280
1281	smt_begin_unsafe();
1282
1283	/*
1284	 * There must be no buffer changes when doing a dmu_sync() because
1285	 * we can't change the data whilst calculating the checksum.
1286	 */
1287	locked_range_t *lr = rangelock_enter(&zv->zv_rangelock, off, resid,
1288	    doread ? RL_READER : RL_WRITER);
1289
1290	while (resid != 0 && off < volsize) {
1291		size_t size = MIN(resid, zvol_maxphys);
1292		if (is_dumpified) {
1293			size = MIN(size, P2END(off, zv->zv_volblocksize) - off);
1294			error = zvol_dumpio(zv, addr, off, size,
1295			    doread, B_FALSE);
1296		} else if (doread) {
1297			error = dmu_read(os, ZVOL_OBJ, off, size, addr,
1298			    DMU_READ_PREFETCH);
1299		} else {
1300			dmu_tx_t *tx = dmu_tx_create(os);
1301			dmu_tx_hold_write(tx, ZVOL_OBJ, off, size);
1302			error = dmu_tx_assign(tx, TXG_WAIT);
1303			if (error) {
1304				dmu_tx_abort(tx);
1305			} else {
1306				dmu_write(os, ZVOL_OBJ, off, size, addr, tx);
1307				zvol_log_write(zv, tx, off, size, sync);
1308				dmu_tx_commit(tx);
1309			}
1310		}
1311		if (error) {
1312			/* convert checksum errors into IO errors */
1313			if (error == ECKSUM)
1314				error = SET_ERROR(EIO);
1315			break;
1316		}
1317		off += size;
1318		addr += size;
1319		resid -= size;
1320	}
1321	rangelock_exit(lr);
1322
1323	if ((bp->b_resid = resid) == bp->b_bcount)
1324		bioerror(bp, off > volsize ? EINVAL : error);
1325
1326	if (sync)
1327		zil_commit(zv->zv_zilog, ZVOL_OBJ);
1328	biodone(bp);
1329
1330	smt_end_unsafe();
1331
1332	return (0);
1333}
1334
1335/*
1336 * Set the buffer count to the zvol maximum transfer.
1337 * Using our own routine instead of the default minphys()
1338 * means that for larger writes we write bigger buffers on X86
1339 * (128K instead of 56K) and flush the disk write cache less often
1340 * (every zvol_maxphys - currently 1MB) instead of minphys (currently
1341 * 56K on X86 and 128K on sparc).
1342 */
1343void
1344zvol_minphys(struct buf *bp)
1345{
1346	if (bp->b_bcount > zvol_maxphys)
1347		bp->b_bcount = zvol_maxphys;
1348}
1349
1350int
1351zvol_dump(dev_t dev, caddr_t addr, daddr_t blkno, int nblocks)
1352{
1353	minor_t minor = getminor(dev);
1354	zvol_state_t *zv;
1355	int error = 0;
1356	uint64_t size;
1357	uint64_t boff;
1358	uint64_t resid;
1359
1360	zv = zfsdev_get_soft_state(minor, ZSST_ZVOL);
1361	if (zv == NULL)
1362		return (SET_ERROR(ENXIO));
1363
1364	if ((zv->zv_flags & ZVOL_DUMPIFIED) == 0)
1365		return (SET_ERROR(EINVAL));
1366
1367	boff = ldbtob(blkno);
1368	resid = ldbtob(nblocks);
1369
1370	VERIFY3U(boff + resid, <=, zv->zv_volsize);
1371
1372	while (resid) {
1373		size = MIN(resid, P2END(boff, zv->zv_volblocksize) - boff);
1374		error = zvol_dumpio(zv, addr, boff, size, B_FALSE, B_TRUE);
1375		if (error)
1376			break;
1377		boff += size;
1378		addr += size;
1379		resid -= size;
1380	}
1381
1382	return (error);
1383}
1384
1385/*ARGSUSED*/
1386int
1387zvol_read(dev_t dev, uio_t *uio, cred_t *cr)
1388{
1389	minor_t minor = getminor(dev);
1390	zvol_state_t *zv;
1391	uint64_t volsize;
1392	int error = 0;
1393
1394	zv = zfsdev_get_soft_state(minor, ZSST_ZVOL);
1395	if (zv == NULL)
1396		return (SET_ERROR(ENXIO));
1397
1398	volsize = zv->zv_volsize;
1399	if (uio->uio_resid > 0 &&
1400	    (uio->uio_loffset < 0 || uio->uio_loffset >= volsize))
1401		return (SET_ERROR(EIO));
1402
1403	if (zv->zv_flags & ZVOL_DUMPIFIED) {
1404		error = physio(zvol_strategy, NULL, dev, B_READ,
1405		    zvol_minphys, uio);
1406		return (error);
1407	}
1408
1409	smt_begin_unsafe();
1410
1411	locked_range_t *lr = rangelock_enter(&zv->zv_rangelock,
1412	    uio->uio_loffset, uio->uio_resid, RL_READER);
1413	while (uio->uio_resid > 0 && uio->uio_loffset < volsize) {
1414		uint64_t bytes = MIN(uio->uio_resid, DMU_MAX_ACCESS >> 1);
1415
1416		/* don't read past the end */
1417		if (bytes > volsize - uio->uio_loffset)
1418			bytes = volsize - uio->uio_loffset;
1419
1420		error =  dmu_read_uio(zv->zv_objset, ZVOL_OBJ, uio, bytes);
1421		if (error) {
1422			/* convert checksum errors into IO errors */
1423			if (error == ECKSUM)
1424				error = SET_ERROR(EIO);
1425			break;
1426		}
1427	}
1428	rangelock_exit(lr);
1429
1430	smt_end_unsafe();
1431
1432	return (error);
1433}
1434
1435/*ARGSUSED*/
1436int
1437zvol_write(dev_t dev, uio_t *uio, cred_t *cr)
1438{
1439	minor_t minor = getminor(dev);
1440	zvol_state_t *zv;
1441	uint64_t volsize;
1442	int error = 0;
1443	boolean_t sync;
1444
1445	zv = zfsdev_get_soft_state(minor, ZSST_ZVOL);
1446	if (zv == NULL)
1447		return (SET_ERROR(ENXIO));
1448
1449	volsize = zv->zv_volsize;
1450	if (uio->uio_resid > 0 &&
1451	    (uio->uio_loffset < 0 || uio->uio_loffset >= volsize))
1452		return (SET_ERROR(EIO));
1453
1454	if (zv->zv_flags & ZVOL_DUMPIFIED) {
1455		error = physio(zvol_strategy, NULL, dev, B_WRITE,
1456		    zvol_minphys, uio);
1457		return (error);
1458	}
1459
1460	smt_begin_unsafe();
1461
1462	sync = !(zv->zv_flags & ZVOL_WCE) ||
1463	    (zv->zv_objset->os_sync == ZFS_SYNC_ALWAYS);
1464
1465	locked_range_t *lr = rangelock_enter(&zv->zv_rangelock,
1466	    uio->uio_loffset, uio->uio_resid, RL_WRITER);
1467	while (uio->uio_resid > 0 && uio->uio_loffset < volsize) {
1468		uint64_t bytes = MIN(uio->uio_resid, DMU_MAX_ACCESS >> 1);
1469		uint64_t off = uio->uio_loffset;
1470		dmu_tx_t *tx = dmu_tx_create(zv->zv_objset);
1471
1472		if (bytes > volsize - off)	/* don't write past the end */
1473			bytes = volsize - off;
1474
1475		dmu_tx_hold_write(tx, ZVOL_OBJ, off, bytes);
1476		error = dmu_tx_assign(tx, TXG_WAIT);
1477		if (error) {
1478			dmu_tx_abort(tx);
1479			break;
1480		}
1481		error = dmu_write_uio_dnode(zv->zv_dn, uio, bytes, tx);
1482		if (error == 0)
1483			zvol_log_write(zv, tx, off, bytes, sync);
1484		dmu_tx_commit(tx);
1485
1486		if (error)
1487			break;
1488	}
1489	rangelock_exit(lr);
1490
1491	if (sync)
1492		zil_commit(zv->zv_zilog, ZVOL_OBJ);
1493
1494	smt_end_unsafe();
1495
1496	return (error);
1497}
1498
1499int
1500zvol_getefi(void *arg, int flag, uint64_t vs, uint8_t bs)
1501{
1502	struct uuid uuid = EFI_RESERVED;
1503	efi_gpe_t gpe = { 0 };
1504	uint32_t crc;
1505	dk_efi_t efi;
1506	int length;
1507	char *ptr;
1508
1509	if (ddi_copyin(arg, &efi, sizeof (dk_efi_t), flag))
1510		return (SET_ERROR(EFAULT));
1511	ptr = (char *)(uintptr_t)efi.dki_data_64;
1512	length = efi.dki_length;
1513	/*
1514	 * Some clients may attempt to request a PMBR for the
1515	 * zvol.  Currently this interface will return EINVAL to
1516	 * such requests.  These requests could be supported by
1517	 * adding a check for lba == 0 and consing up an appropriate
1518	 * PMBR.
1519	 */
1520	if (efi.dki_lba < 1 || efi.dki_lba > 2 || length <= 0)
1521		return (SET_ERROR(EINVAL));
1522
1523	gpe.efi_gpe_StartingLBA = LE_64(34ULL);
1524	gpe.efi_gpe_EndingLBA = LE_64((vs >> bs) - 1);
1525	UUID_LE_CONVERT(gpe.efi_gpe_PartitionTypeGUID, uuid);
1526
1527	if (efi.dki_lba == 1) {
1528		efi_gpt_t gpt = { 0 };
1529
1530		gpt.efi_gpt_Signature = LE_64(EFI_SIGNATURE);
1531		gpt.efi_gpt_Revision = LE_32(EFI_VERSION_CURRENT);
1532		gpt.efi_gpt_HeaderSize = LE_32(EFI_HEADER_SIZE);
1533		gpt.efi_gpt_MyLBA = LE_64(1ULL);
1534		gpt.efi_gpt_FirstUsableLBA = LE_64(34ULL);
1535		gpt.efi_gpt_LastUsableLBA = LE_64((vs >> bs) - 1);
1536		gpt.efi_gpt_PartitionEntryLBA = LE_64(2ULL);
1537		gpt.efi_gpt_NumberOfPartitionEntries = LE_32(1);
1538		gpt.efi_gpt_SizeOfPartitionEntry =
1539		    LE_32(sizeof (efi_gpe_t));
1540		CRC32(crc, &gpe, sizeof (gpe), -1U, crc32_table);
1541		gpt.efi_gpt_PartitionEntryArrayCRC32 = LE_32(~crc);
1542		CRC32(crc, &gpt, EFI_HEADER_SIZE, -1U, crc32_table);
1543		gpt.efi_gpt_HeaderCRC32 = LE_32(~crc);
1544		if (ddi_copyout(&gpt, ptr, MIN(sizeof (gpt), length),
1545		    flag))
1546			return (SET_ERROR(EFAULT));
1547		ptr += sizeof (gpt);
1548		length -= sizeof (gpt);
1549	}
1550	if (length > 0 && ddi_copyout(&gpe, ptr, MIN(sizeof (gpe),
1551	    length), flag))
1552		return (SET_ERROR(EFAULT));
1553	return (0);
1554}
1555
1556/*
1557 * BEGIN entry points to allow external callers access to the volume.
1558 */
1559/*
1560 * Return the volume parameters needed for access from an external caller.
1561 * These values are invariant as long as the volume is held open.
1562 */
1563int
1564zvol_get_volume_params(minor_t minor, uint64_t *blksize,
1565    uint64_t *max_xfer_len, void **minor_hdl, void **objset_hdl, void **zil_hdl,
1566    void **rl_hdl, void **dnode_hdl)
1567{
1568	zvol_state_t *zv;
1569
1570	zv = zfsdev_get_soft_state(minor, ZSST_ZVOL);
1571	if (zv == NULL)
1572		return (SET_ERROR(ENXIO));
1573	if (zv->zv_flags & ZVOL_DUMPIFIED)
1574		return (SET_ERROR(ENXIO));
1575
1576	ASSERT(blksize && max_xfer_len && minor_hdl &&
1577	    objset_hdl && zil_hdl && rl_hdl && dnode_hdl);
1578
1579	*blksize = zv->zv_volblocksize;
1580	*max_xfer_len = (uint64_t)zvol_maxphys;
1581	*minor_hdl = zv;
1582	*objset_hdl = zv->zv_objset;
1583	*zil_hdl = zv->zv_zilog;
1584	*rl_hdl = &zv->zv_rangelock;
1585	*dnode_hdl = zv->zv_dn;
1586	return (0);
1587}
1588
1589/*
1590 * Return the current volume size to an external caller.
1591 * The size can change while the volume is open.
1592 */
1593uint64_t
1594zvol_get_volume_size(void *minor_hdl)
1595{
1596	zvol_state_t *zv = minor_hdl;
1597
1598	return (zv->zv_volsize);
1599}
1600
1601/*
1602 * Return the current WCE setting to an external caller.
1603 * The WCE setting can change while the volume is open.
1604 */
1605int
1606zvol_get_volume_wce(void *minor_hdl)
1607{
1608	zvol_state_t *zv = minor_hdl;
1609
1610	return ((zv->zv_flags & ZVOL_WCE) ? 1 : 0);
1611}
1612
1613/*
1614 * Entry point for external callers to zvol_log_write
1615 */
1616void
1617zvol_log_write_minor(void *minor_hdl, dmu_tx_t *tx, offset_t off, ssize_t resid,
1618    boolean_t sync)
1619{
1620	zvol_state_t *zv = minor_hdl;
1621
1622	zvol_log_write(zv, tx, off, resid, sync);
1623}
1624/*
1625 * END entry points to allow external callers access to the volume.
1626 */
1627
1628/*
1629 * Log a DKIOCFREE/free-long-range to the ZIL with TX_TRUNCATE.
1630 */
1631static void
1632zvol_log_truncate(zvol_state_t *zv, dmu_tx_t *tx, uint64_t off, uint64_t len,
1633    boolean_t sync)
1634{
1635	itx_t *itx;
1636	lr_truncate_t *lr;
1637	zilog_t *zilog = zv->zv_zilog;
1638
1639	if (zil_replaying(zilog, tx))
1640		return;
1641
1642	itx = zil_itx_create(TX_TRUNCATE, sizeof (*lr));
1643	lr = (lr_truncate_t *)&itx->itx_lr;
1644	lr->lr_foid = ZVOL_OBJ;
1645	lr->lr_offset = off;
1646	lr->lr_length = len;
1647
1648	itx->itx_sync = sync;
1649	zil_itx_assign(zilog, itx, tx);
1650}
1651
1652/*
1653 * Dirtbag ioctls to support mkfs(1M) for UFS filesystems.  See dkio(7I).
1654 * Also a dirtbag dkio ioctl for unmap/free-block functionality.
1655 */
1656/*ARGSUSED*/
1657int
1658zvol_ioctl(dev_t dev, int cmd, intptr_t arg, int flag, cred_t *cr, int *rvalp)
1659{
1660	zvol_state_t *zv;
1661	struct dk_callback *dkc;
1662	int i, error = 0;
1663	locked_range_t *lr;
1664
1665	mutex_enter(&zfsdev_state_lock);
1666
1667	zv = zfsdev_get_soft_state(getminor(dev), ZSST_ZVOL);
1668
1669	if (zv == NULL) {
1670		mutex_exit(&zfsdev_state_lock);
1671		return (SET_ERROR(ENXIO));
1672	}
1673	ASSERT(zv->zv_total_opens > 0);
1674
1675	switch (cmd) {
1676
1677	case DKIOCINFO:
1678	{
1679		struct dk_cinfo dki;
1680
1681		bzero(&dki, sizeof (dki));
1682		(void) strcpy(dki.dki_cname, "zvol");
1683		(void) strcpy(dki.dki_dname, "zvol");
1684		dki.dki_ctype = DKC_UNKNOWN;
1685		dki.dki_unit = getminor(dev);
1686		dki.dki_maxtransfer =
1687		    1 << (SPA_OLD_MAXBLOCKSHIFT - zv->zv_min_bs);
1688		mutex_exit(&zfsdev_state_lock);
1689		if (ddi_copyout(&dki, (void *)arg, sizeof (dki), flag))
1690			error = SET_ERROR(EFAULT);
1691		return (error);
1692	}
1693
1694	case DKIOCGMEDIAINFO:
1695	{
1696		struct dk_minfo dkm;
1697
1698		bzero(&dkm, sizeof (dkm));
1699		dkm.dki_lbsize = 1U << zv->zv_min_bs;
1700		dkm.dki_capacity = zv->zv_volsize >> zv->zv_min_bs;
1701		dkm.dki_media_type = DK_UNKNOWN;
1702		mutex_exit(&zfsdev_state_lock);
1703		if (ddi_copyout(&dkm, (void *)arg, sizeof (dkm), flag))
1704			error = SET_ERROR(EFAULT);
1705		return (error);
1706	}
1707
1708	case DKIOCGMEDIAINFOEXT:
1709	{
1710		struct dk_minfo_ext dkmext;
1711
1712		bzero(&dkmext, sizeof (dkmext));
1713		dkmext.dki_lbsize = 1U << zv->zv_min_bs;
1714		dkmext.dki_pbsize = zv->zv_volblocksize;
1715		dkmext.dki_capacity = zv->zv_volsize >> zv->zv_min_bs;
1716		dkmext.dki_media_type = DK_UNKNOWN;
1717		mutex_exit(&zfsdev_state_lock);
1718		if (ddi_copyout(&dkmext, (void *)arg, sizeof (dkmext), flag))
1719			error = SET_ERROR(EFAULT);
1720		return (error);
1721	}
1722
1723	case DKIOCGETEFI:
1724	{
1725		uint64_t vs = zv->zv_volsize;
1726		uint8_t bs = zv->zv_min_bs;
1727
1728		mutex_exit(&zfsdev_state_lock);
1729		error = zvol_getefi((void *)arg, flag, vs, bs);
1730		return (error);
1731	}
1732
1733	case DKIOCFLUSHWRITECACHE:
1734		dkc = (struct dk_callback *)arg;
1735		mutex_exit(&zfsdev_state_lock);
1736
1737		smt_begin_unsafe();
1738
1739		zil_commit(zv->zv_zilog, ZVOL_OBJ);
1740		if ((flag & FKIOCTL) && dkc != NULL && dkc->dkc_callback) {
1741			(*dkc->dkc_callback)(dkc->dkc_cookie, error);
1742			error = 0;
1743		}
1744
1745		smt_end_unsafe();
1746
1747		return (error);
1748
1749	case DKIOCGETWCE:
1750	{
1751		int wce = (zv->zv_flags & ZVOL_WCE) ? 1 : 0;
1752		if (ddi_copyout(&wce, (void *)arg, sizeof (int),
1753		    flag))
1754			error = SET_ERROR(EFAULT);
1755		break;
1756	}
1757	case DKIOCSETWCE:
1758	{
1759		int wce;
1760		if (ddi_copyin((void *)arg, &wce, sizeof (int),
1761		    flag)) {
1762			error = SET_ERROR(EFAULT);
1763			break;
1764		}
1765		if (wce) {
1766			zv->zv_flags |= ZVOL_WCE;
1767			mutex_exit(&zfsdev_state_lock);
1768		} else {
1769			zv->zv_flags &= ~ZVOL_WCE;
1770			mutex_exit(&zfsdev_state_lock);
1771			smt_begin_unsafe();
1772			zil_commit(zv->zv_zilog, ZVOL_OBJ);
1773			smt_end_unsafe();
1774		}
1775		return (0);
1776	}
1777
1778	case DKIOCGGEOM:
1779	case DKIOCGVTOC:
1780		/*
1781		 * commands using these (like prtvtoc) expect ENOTSUP
1782		 * since we're emulating an EFI label
1783		 */
1784		error = SET_ERROR(ENOTSUP);
1785		break;
1786
1787	case DKIOCDUMPINIT:
1788		lr = rangelock_enter(&zv->zv_rangelock, 0, zv->zv_volsize,
1789		    RL_WRITER);
1790		error = zvol_dumpify(zv);
1791		rangelock_exit(lr);
1792		break;
1793
1794	case DKIOCDUMPFINI:
1795		if (!(zv->zv_flags & ZVOL_DUMPIFIED))
1796			break;
1797		lr = rangelock_enter(&zv->zv_rangelock, 0, zv->zv_volsize,
1798		    RL_WRITER);
1799		error = zvol_dump_fini(zv);
1800		rangelock_exit(lr);
1801		break;
1802
1803	case DKIOCFREE:
1804	{
1805		dkioc_free_list_t *dfl;
1806		dmu_tx_t *tx;
1807
1808		if (!zvol_unmap_enabled)
1809			break;
1810
1811		if (!(flag & FKIOCTL)) {
1812			error = dfl_copyin((void *)arg, &dfl, flag, KM_SLEEP);
1813			if (error != 0)
1814				break;
1815		} else {
1816			dfl = (dkioc_free_list_t *)arg;
1817			ASSERT3U(dfl->dfl_num_exts, <=, DFL_COPYIN_MAX_EXTS);
1818			if (dfl->dfl_num_exts > DFL_COPYIN_MAX_EXTS) {
1819				error = SET_ERROR(EINVAL);
1820				break;
1821			}
1822		}
1823
1824		mutex_exit(&zfsdev_state_lock);
1825
1826		smt_begin_unsafe();
1827
1828		for (int i = 0; i < dfl->dfl_num_exts; i++) {
1829			uint64_t start = dfl->dfl_exts[i].dfle_start,
1830			    length = dfl->dfl_exts[i].dfle_length,
1831			    end = start + length;
1832
1833			/*
1834			 * Apply Postel's Law to length-checking.  If they
1835			 * overshoot, just blank out until the end, if there's
1836			 * a need to blank out anything.
1837			 */
1838			if (start >= zv->zv_volsize)
1839				continue;	/* No need to do anything... */
1840			if (end > zv->zv_volsize) {
1841				end = DMU_OBJECT_END;
1842				length = end - start;
1843			}
1844
1845			lr = rangelock_enter(&zv->zv_rangelock, start, length,
1846			    RL_WRITER);
1847			tx = dmu_tx_create(zv->zv_objset);
1848			error = dmu_tx_assign(tx, TXG_WAIT);
1849			if (error != 0) {
1850				dmu_tx_abort(tx);
1851			} else {
1852				zvol_log_truncate(zv, tx, start, length,
1853				    B_TRUE);
1854				dmu_tx_commit(tx);
1855				error = dmu_free_long_range(zv->zv_objset,
1856				    ZVOL_OBJ, start, length);
1857			}
1858
1859			rangelock_exit(lr);
1860
1861			if (error != 0)
1862				break;
1863		}
1864
1865		/*
1866		 * If the write-cache is disabled, 'sync' property
1867		 * is set to 'always', or if the caller is asking for
1868		 * a synchronous free, commit this operation to the zil.
1869		 * This will sync any previous uncommitted writes to the
1870		 * zvol object.
1871		 * Can be overridden by the zvol_unmap_sync_enabled tunable.
1872		 */
1873		if ((error == 0) && zvol_unmap_sync_enabled &&
1874		    (!(zv->zv_flags & ZVOL_WCE) ||
1875		    (zv->zv_objset->os_sync == ZFS_SYNC_ALWAYS) ||
1876		    (dfl->dfl_flags & DF_WAIT_SYNC))) {
1877			zil_commit(zv->zv_zilog, ZVOL_OBJ);
1878		}
1879
1880		if (!(flag & FKIOCTL))
1881			dfl_free(dfl);
1882
1883		smt_end_unsafe();
1884
1885		return (error);
1886	}
1887
1888	case DKIOC_CANFREE:
1889		i = zvol_unmap_enabled ? 1 : 0;
1890		if (ddi_copyout(&i, (void *)arg, sizeof (int), flag) != 0) {
1891			error = EFAULT;
1892		} else {
1893			error = 0;
1894		}
1895		break;
1896
1897	default:
1898		error = SET_ERROR(ENOTTY);
1899		break;
1900
1901	}
1902	mutex_exit(&zfsdev_state_lock);
1903	return (error);
1904}
1905
1906int
1907zvol_busy(void)
1908{
1909	return (zvol_minors != 0);
1910}
1911
1912void
1913zvol_init(void)
1914{
1915	VERIFY(ddi_soft_state_init(&zfsdev_state, sizeof (zfs_soft_state_t),
1916	    1) == 0);
1917	mutex_init(&zfsdev_state_lock, NULL, MUTEX_DEFAULT, NULL);
1918}
1919
1920void
1921zvol_fini(void)
1922{
1923	mutex_destroy(&zfsdev_state_lock);
1924	ddi_soft_state_fini(&zfsdev_state);
1925}
1926
1927/*ARGSUSED*/
1928static int
1929zfs_mvdev_dump_feature_check(void *arg, dmu_tx_t *tx)
1930{
1931	spa_t *spa = dmu_tx_pool(tx)->dp_spa;
1932
1933	if (spa_feature_is_active(spa, SPA_FEATURE_MULTI_VDEV_CRASH_DUMP))
1934		return (1);
1935	return (0);
1936}
1937
1938/*ARGSUSED*/
1939static void
1940zfs_mvdev_dump_activate_feature_sync(void *arg, dmu_tx_t *tx)
1941{
1942	spa_t *spa = dmu_tx_pool(tx)->dp_spa;
1943
1944	spa_feature_incr(spa, SPA_FEATURE_MULTI_VDEV_CRASH_DUMP, tx);
1945}
1946
1947static int
1948zvol_dump_init(zvol_state_t *zv, boolean_t resize)
1949{
1950	dmu_tx_t *tx;
1951	int error;
1952	objset_t *os = zv->zv_objset;
1953	spa_t *spa = dmu_objset_spa(os);
1954	vdev_t *vd = spa->spa_root_vdev;
1955	nvlist_t *nv = NULL;
1956	uint64_t version = spa_version(spa);
1957	uint64_t checksum, compress, refresrv, vbs, dedup;
1958
1959	ASSERT(MUTEX_HELD(&zfsdev_state_lock));
1960	ASSERT(vd->vdev_ops == &vdev_root_ops);
1961
1962	error = dmu_free_long_range(zv->zv_objset, ZVOL_OBJ, 0,
1963	    DMU_OBJECT_END);
1964	if (error != 0)
1965		return (error);
1966	/* wait for dmu_free_long_range to actually free the blocks */
1967	txg_wait_synced(dmu_objset_pool(zv->zv_objset), 0);
1968
1969	/*
1970	 * If the pool on which the dump device is being initialized has more
1971	 * than one child vdev, check that the MULTI_VDEV_CRASH_DUMP feature is
1972	 * enabled.  If so, bump that feature's counter to indicate that the
1973	 * feature is active. We also check the vdev type to handle the
1974	 * following case:
1975	 *   # zpool create test raidz disk1 disk2 disk3
1976	 *   Now have spa_root_vdev->vdev_children == 1 (the raidz vdev),
1977	 *   the raidz vdev itself has 3 children.
1978	 */
1979	if (vd->vdev_children > 1 || vd->vdev_ops == &vdev_raidz_ops) {
1980		if (!spa_feature_is_enabled(spa,
1981		    SPA_FEATURE_MULTI_VDEV_CRASH_DUMP))
1982			return (SET_ERROR(ENOTSUP));
1983		(void) dsl_sync_task(spa_name(spa),
1984		    zfs_mvdev_dump_feature_check,
1985		    zfs_mvdev_dump_activate_feature_sync, NULL,
1986		    2, ZFS_SPACE_CHECK_RESERVED);
1987	}
1988
1989	if (!resize) {
1990		error = dsl_prop_get_integer(zv->zv_name,
1991		    zfs_prop_to_name(ZFS_PROP_COMPRESSION), &compress, NULL);
1992		if (error == 0) {
1993			error = dsl_prop_get_integer(zv->zv_name,
1994			    zfs_prop_to_name(ZFS_PROP_CHECKSUM), &checksum,
1995			    NULL);
1996		}
1997		if (error == 0) {
1998			error = dsl_prop_get_integer(zv->zv_name,
1999			    zfs_prop_to_name(ZFS_PROP_REFRESERVATION),
2000			    &refresrv, NULL);
2001		}
2002		if (error == 0) {
2003			error = dsl_prop_get_integer(zv->zv_name,
2004			    zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE), &vbs,
2005			    NULL);
2006		}
2007		if (version >= SPA_VERSION_DEDUP && error == 0) {
2008			error = dsl_prop_get_integer(zv->zv_name,
2009			    zfs_prop_to_name(ZFS_PROP_DEDUP), &dedup, NULL);
2010		}
2011	}
2012	if (error != 0)
2013		return (error);
2014
2015	tx = dmu_tx_create(os);
2016	dmu_tx_hold_zap(tx, ZVOL_ZAP_OBJ, TRUE, NULL);
2017	dmu_tx_hold_bonus(tx, ZVOL_OBJ);
2018	error = dmu_tx_assign(tx, TXG_WAIT);
2019	if (error != 0) {
2020		dmu_tx_abort(tx);
2021		return (error);
2022	}
2023
2024	/*
2025	 * If we are resizing the dump device then we only need to
2026	 * update the refreservation to match the newly updated
2027	 * zvolsize. Otherwise, we save off the original state of the
2028	 * zvol so that we can restore them if the zvol is ever undumpified.
2029	 */
2030	if (resize) {
2031		error = zap_update(os, ZVOL_ZAP_OBJ,
2032		    zfs_prop_to_name(ZFS_PROP_REFRESERVATION), 8, 1,
2033		    &zv->zv_volsize, tx);
2034	} else {
2035		error = zap_update(os, ZVOL_ZAP_OBJ,
2036		    zfs_prop_to_name(ZFS_PROP_COMPRESSION), 8, 1,
2037		    &compress, tx);
2038		if (error == 0) {
2039			error = zap_update(os, ZVOL_ZAP_OBJ,
2040			    zfs_prop_to_name(ZFS_PROP_CHECKSUM), 8, 1,
2041			    &checksum, tx);
2042		}
2043		if (error == 0) {
2044			error = zap_update(os, ZVOL_ZAP_OBJ,
2045			    zfs_prop_to_name(ZFS_PROP_REFRESERVATION), 8, 1,
2046			    &refresrv, tx);
2047		}
2048		if (error == 0) {
2049			error = zap_update(os, ZVOL_ZAP_OBJ,
2050			    zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE), 8, 1,
2051			    &vbs, tx);
2052		}
2053		if (error == 0) {
2054			error = dmu_object_set_blocksize(
2055			    os, ZVOL_OBJ, SPA_OLD_MAXBLOCKSIZE, 0, tx);
2056		}
2057		if (version >= SPA_VERSION_DEDUP && error == 0) {
2058			error = zap_update(os, ZVOL_ZAP_OBJ,
2059			    zfs_prop_to_name(ZFS_PROP_DEDUP), 8, 1,
2060			    &dedup, tx);
2061		}
2062		if (error == 0)
2063			zv->zv_volblocksize = SPA_OLD_MAXBLOCKSIZE;
2064	}
2065	dmu_tx_commit(tx);
2066
2067	/*
2068	 * We only need update the zvol's property if we are initializing
2069	 * the dump area for the first time.
2070	 */
2071	if (error == 0 && !resize) {
2072		/*
2073		 * If MULTI_VDEV_CRASH_DUMP is active, use the NOPARITY checksum
2074		 * function.  Otherwise, use the old default -- OFF.
2075		 */
2076		checksum = spa_feature_is_active(spa,
2077		    SPA_FEATURE_MULTI_VDEV_CRASH_DUMP) ? ZIO_CHECKSUM_NOPARITY :
2078		    ZIO_CHECKSUM_OFF;
2079
2080		VERIFY(nvlist_alloc(&nv, NV_UNIQUE_NAME, KM_SLEEP) == 0);
2081		VERIFY(nvlist_add_uint64(nv,
2082		    zfs_prop_to_name(ZFS_PROP_REFRESERVATION), 0) == 0);
2083		VERIFY(nvlist_add_uint64(nv,
2084		    zfs_prop_to_name(ZFS_PROP_COMPRESSION),
2085		    ZIO_COMPRESS_OFF) == 0);
2086		VERIFY(nvlist_add_uint64(nv,
2087		    zfs_prop_to_name(ZFS_PROP_CHECKSUM),
2088		    checksum) == 0);
2089		if (version >= SPA_VERSION_DEDUP) {
2090			VERIFY(nvlist_add_uint64(nv,
2091			    zfs_prop_to_name(ZFS_PROP_DEDUP),
2092			    ZIO_CHECKSUM_OFF) == 0);
2093		}
2094
2095		error = zfs_set_prop_nvlist(zv->zv_name, ZPROP_SRC_LOCAL,
2096		    nv, NULL);
2097		nvlist_free(nv);
2098	}
2099
2100	/* Allocate the space for the dump */
2101	if (error == 0)
2102		error = zvol_prealloc(zv);
2103	return (error);
2104}
2105
2106static int
2107zvol_dumpify(zvol_state_t *zv)
2108{
2109	int error = 0;
2110	uint64_t dumpsize = 0;
2111	dmu_tx_t *tx;
2112	objset_t *os = zv->zv_objset;
2113
2114	if (zv->zv_flags & ZVOL_RDONLY)
2115		return (SET_ERROR(EROFS));
2116
2117	if (os->os_encrypted)
2118		return (SET_ERROR(ENOTSUP));
2119
2120	if (zap_lookup(zv->zv_objset, ZVOL_ZAP_OBJ, ZVOL_DUMPSIZE,
2121	    8, 1, &dumpsize) != 0 || dumpsize != zv->zv_volsize) {
2122		boolean_t resize = (dumpsize > 0);
2123
2124		if ((error = zvol_dump_init(zv, resize)) != 0) {
2125			(void) zvol_dump_fini(zv);
2126			return (error);
2127		}
2128	}
2129
2130	/*
2131	 * Build up our lba mapping.
2132	 */
2133	error = zvol_get_lbas(zv);
2134	if (error) {
2135		(void) zvol_dump_fini(zv);
2136		return (error);
2137	}
2138
2139	tx = dmu_tx_create(os);
2140	dmu_tx_hold_zap(tx, ZVOL_ZAP_OBJ, TRUE, NULL);
2141	error = dmu_tx_assign(tx, TXG_WAIT);
2142	if (error) {
2143		dmu_tx_abort(tx);
2144		(void) zvol_dump_fini(zv);
2145		return (error);
2146	}
2147
2148	zv->zv_flags |= ZVOL_DUMPIFIED;
2149	error = zap_update(os, ZVOL_ZAP_OBJ, ZVOL_DUMPSIZE, 8, 1,
2150	    &zv->zv_volsize, tx);
2151	dmu_tx_commit(tx);
2152
2153	if (error) {
2154		(void) zvol_dump_fini(zv);
2155		return (error);
2156	}
2157
2158	txg_wait_synced(dmu_objset_pool(os), 0);
2159	return (0);
2160}
2161
2162static int
2163zvol_dump_fini(zvol_state_t *zv)
2164{
2165	dmu_tx_t *tx;
2166	objset_t *os = zv->zv_objset;
2167	nvlist_t *nv;
2168	int error = 0;
2169	uint64_t checksum, compress, refresrv, vbs, dedup;
2170	uint64_t version = spa_version(dmu_objset_spa(zv->zv_objset));
2171
2172	/*
2173	 * Attempt to restore the zvol back to its pre-dumpified state.
2174	 * This is a best-effort attempt as it's possible that not all
2175	 * of these properties were initialized during the dumpify process
2176	 * (i.e. error during zvol_dump_init).
2177	 */
2178
2179	tx = dmu_tx_create(os);
2180	dmu_tx_hold_zap(tx, ZVOL_ZAP_OBJ, TRUE, NULL);
2181	error = dmu_tx_assign(tx, TXG_WAIT);
2182	if (error) {
2183		dmu_tx_abort(tx);
2184		return (error);
2185	}
2186	(void) zap_remove(os, ZVOL_ZAP_OBJ, ZVOL_DUMPSIZE, tx);
2187	dmu_tx_commit(tx);
2188
2189	(void) zap_lookup(zv->zv_objset, ZVOL_ZAP_OBJ,
2190	    zfs_prop_to_name(ZFS_PROP_CHECKSUM), 8, 1, &checksum);
2191	(void) zap_lookup(zv->zv_objset, ZVOL_ZAP_OBJ,
2192	    zfs_prop_to_name(ZFS_PROP_COMPRESSION), 8, 1, &compress);
2193	(void) zap_lookup(zv->zv_objset, ZVOL_ZAP_OBJ,
2194	    zfs_prop_to_name(ZFS_PROP_REFRESERVATION), 8, 1, &refresrv);
2195	(void) zap_lookup(zv->zv_objset, ZVOL_ZAP_OBJ,
2196	    zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE), 8, 1, &vbs);
2197
2198	VERIFY(nvlist_alloc(&nv, NV_UNIQUE_NAME, KM_SLEEP) == 0);
2199	(void) nvlist_add_uint64(nv,
2200	    zfs_prop_to_name(ZFS_PROP_CHECKSUM), checksum);
2201	(void) nvlist_add_uint64(nv,
2202	    zfs_prop_to_name(ZFS_PROP_COMPRESSION), compress);
2203	(void) nvlist_add_uint64(nv,
2204	    zfs_prop_to_name(ZFS_PROP_REFRESERVATION), refresrv);
2205	if (version >= SPA_VERSION_DEDUP &&
2206	    zap_lookup(zv->zv_objset, ZVOL_ZAP_OBJ,
2207	    zfs_prop_to_name(ZFS_PROP_DEDUP), 8, 1, &dedup) == 0) {
2208		(void) nvlist_add_uint64(nv,
2209		    zfs_prop_to_name(ZFS_PROP_DEDUP), dedup);
2210	}
2211	(void) zfs_set_prop_nvlist(zv->zv_name, ZPROP_SRC_LOCAL,
2212	    nv, NULL);
2213	nvlist_free(nv);
2214
2215	zvol_free_extents(zv);
2216	zv->zv_flags &= ~ZVOL_DUMPIFIED;
2217	(void) dmu_free_long_range(os, ZVOL_OBJ, 0, DMU_OBJECT_END);
2218	/* wait for dmu_free_long_range to actually free the blocks */
2219	txg_wait_synced(dmu_objset_pool(zv->zv_objset), 0);
2220	tx = dmu_tx_create(os);
2221	dmu_tx_hold_bonus(tx, ZVOL_OBJ);
2222	error = dmu_tx_assign(tx, TXG_WAIT);
2223	if (error) {
2224		dmu_tx_abort(tx);
2225		return (error);
2226	}
2227	if (dmu_object_set_blocksize(os, ZVOL_OBJ, vbs, 0, tx) == 0)
2228		zv->zv_volblocksize = vbs;
2229	dmu_tx_commit(tx);
2230
2231	return (0);
2232}
2233