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