xref: /freebsd/sys/contrib/openzfs/module/zfs/zvol.c (revision b670c9bafc0e31c7609969bf374b2e80bdc00211)
1 // SPDX-License-Identifier: CDDL-1.0
2 /*
3  * CDDL HEADER START
4  *
5  * The contents of this file are subject to the terms of the
6  * Common Development and Distribution License (the "License").
7  * You may not use this file except in compliance with the License.
8  *
9  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10  * or https://opensource.org/licenses/CDDL-1.0.
11  * See the License for the specific language governing permissions
12  * and limitations under the License.
13  *
14  * When distributing Covered Code, include this CDDL HEADER in each
15  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16  * If applicable, add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your own identifying
18  * information: Portions Copyright [yyyy] [name of copyright owner]
19  *
20  * CDDL HEADER END
21  */
22 /*
23  * Copyright (C) 2008-2010 Lawrence Livermore National Security, LLC.
24  * Produced at Lawrence Livermore National Laboratory (cf, DISCLAIMER).
25  * Rewritten for Linux by Brian Behlendorf <behlendorf1@llnl.gov>.
26  * LLNL-CODE-403049.
27  *
28  * ZFS volume emulation driver.
29  *
30  * Makes a DMU object look like a volume of arbitrary size, up to 2^64 bytes.
31  * Volumes are accessed through the symbolic links named:
32  *
33  * /dev/<pool_name>/<dataset_name>
34  *
35  * Volumes are persistent through reboot and module load.  No user command
36  * needs to be run before opening and using a device.
37  *
38  * Copyright 2014 Nexenta Systems, Inc.  All rights reserved.
39  * Copyright (c) 2016 Actifio, Inc. All rights reserved.
40  * Copyright (c) 2012, 2019 by Delphix. All rights reserved.
41  * Copyright (c) 2024, Klara, Inc.
42  */
43 
44 /*
45  * Note on locking of zvol state structures.
46  *
47  * These structures are used to maintain internal state used to emulate block
48  * devices on top of zvols. In particular, management of device minor number
49  * operations - create, remove, rename, and set_snapdev - involves access to
50  * these structures. The zvol_state_lock is primarily used to protect the
51  * zvol_state_list. The zv->zv_state_lock is used to protect the contents
52  * of the zvol_state_t structures, as well as to make sure that when the
53  * time comes to remove the structure from the list, it is not in use, and
54  * therefore, it can be taken off zvol_state_list and freed.
55  *
56  * The zv_suspend_lock was introduced to allow for suspending I/O to a zvol,
57  * e.g. for the duration of receive and rollback operations. This lock can be
58  * held for significant periods of time. Given that it is undesirable to hold
59  * mutexes for long periods of time, the following lock ordering applies:
60  * - take zvol_state_lock if necessary, to protect zvol_state_list
61  * - take zv_suspend_lock if necessary, by the code path in question
62  * - take zv_state_lock to protect zvol_state_t
63  *
64  * The minor operations are issued to spa->spa_zvol_taskq queues, that are
65  * single-threaded (to preserve order of minor operations), and are executed
66  * through the zvol_task_cb that dispatches the specific operations. Therefore,
67  * these operations are serialized per pool. Consequently, we can be certain
68  * that for a given zvol, there is only one operation at a time in progress.
69  * That is why one can be sure that first, zvol_state_t for a given zvol is
70  * allocated and placed on zvol_state_list, and then other minor operations
71  * for this zvol are going to proceed in the order of issue.
72  *
73  */
74 
75 #include <sys/dataset_kstats.h>
76 #include <sys/dbuf.h>
77 #include <sys/dmu_traverse.h>
78 #include <sys/dsl_dataset.h>
79 #include <sys/dsl_prop.h>
80 #include <sys/dsl_dir.h>
81 #include <sys/zap.h>
82 #include <sys/zfeature.h>
83 #include <sys/zil_impl.h>
84 #include <sys/dmu_tx.h>
85 #include <sys/zio.h>
86 #include <sys/zfs_rlock.h>
87 #include <sys/spa_impl.h>
88 #include <sys/zvol.h>
89 #include <sys/zvol_impl.h>
90 
91 unsigned int zvol_inhibit_dev = 0;
92 unsigned int zvol_volmode = ZFS_VOLMODE_GEOM;
93 unsigned int zvol_threads = 0;
94 unsigned int zvol_num_taskqs = 0;
95 unsigned int zvol_request_sync = 0;
96 
97 struct hlist_head *zvol_htable;
98 static list_t zvol_state_list;
99 krwlock_t zvol_state_lock;
100 extern int zfs_bclone_wait_dirty;
101 zv_taskq_t zvol_taskqs;
102 
103 typedef enum {
104 	ZVOL_ASYNC_REMOVE_MINORS,
105 	ZVOL_ASYNC_RENAME_MINORS,
106 	ZVOL_ASYNC_SET_SNAPDEV,
107 	ZVOL_ASYNC_SET_VOLMODE,
108 	ZVOL_ASYNC_MAX
109 } zvol_async_op_t;
110 
111 typedef struct {
112 	zvol_async_op_t op;
113 	char name1[MAXNAMELEN];
114 	char name2[MAXNAMELEN];
115 	uint64_t value;
116 } zvol_task_t;
117 
118 zv_request_task_t *
119 zv_request_task_create(zv_request_t zvr)
120 {
121 	zv_request_task_t *task;
122 	task = kmem_alloc(sizeof (zv_request_task_t), KM_SLEEP);
123 	taskq_init_ent(&task->ent);
124 	task->zvr = zvr;
125 	return (task);
126 }
127 
128 void
129 zv_request_task_free(zv_request_task_t *task)
130 {
131 	kmem_free(task, sizeof (*task));
132 }
133 
134 uint64_t
135 zvol_name_hash(const char *name)
136 {
137 	uint64_t crc = -1ULL;
138 	ASSERT(zfs_crc64_table[128] == ZFS_CRC64_POLY);
139 	for (const uint8_t *p = (const uint8_t *)name; *p != 0; p++)
140 		crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ (*p)) & 0xFF];
141 	return (crc);
142 }
143 
144 /*
145  * Find a zvol_state_t given the name and hash generated by zvol_name_hash.
146  * If found, return with zv_suspend_lock and zv_state_lock taken, otherwise,
147  * return (NULL) without the taking locks. The zv_suspend_lock is always taken
148  * before zv_state_lock. The mode argument indicates the mode (including none)
149  * for zv_suspend_lock to be taken.
150  */
151 zvol_state_t *
152 zvol_find_by_name_hash(const char *name, uint64_t hash, int mode)
153 {
154 	zvol_state_t *zv;
155 	struct hlist_node *p = NULL;
156 
157 	rw_enter(&zvol_state_lock, RW_READER);
158 	hlist_for_each(p, ZVOL_HT_HEAD(hash)) {
159 		zv = hlist_entry(p, zvol_state_t, zv_hlink);
160 		mutex_enter(&zv->zv_state_lock);
161 		if (zv->zv_hash == hash && strcmp(zv->zv_name, name) == 0) {
162 			/*
163 			 * this is the right zvol, take the locks in the
164 			 * right order
165 			 */
166 			if (mode != RW_NONE &&
167 			    !rw_tryenter(&zv->zv_suspend_lock, mode)) {
168 				mutex_exit(&zv->zv_state_lock);
169 				rw_enter(&zv->zv_suspend_lock, mode);
170 				mutex_enter(&zv->zv_state_lock);
171 				/*
172 				 * zvol cannot be renamed as we continue
173 				 * to hold zvol_state_lock
174 				 */
175 				ASSERT(zv->zv_hash == hash &&
176 				    strcmp(zv->zv_name, name) == 0);
177 			}
178 			rw_exit(&zvol_state_lock);
179 			return (zv);
180 		}
181 		mutex_exit(&zv->zv_state_lock);
182 	}
183 	rw_exit(&zvol_state_lock);
184 
185 	return (NULL);
186 }
187 
188 /*
189  * Find a zvol_state_t given the name.
190  * If found, return with zv_suspend_lock and zv_state_lock taken, otherwise,
191  * return (NULL) without the taking locks. The zv_suspend_lock is always taken
192  * before zv_state_lock. The mode argument indicates the mode (including none)
193  * for zv_suspend_lock to be taken.
194  */
195 static zvol_state_t *
196 zvol_find_by_name(const char *name, int mode)
197 {
198 	return (zvol_find_by_name_hash(name, zvol_name_hash(name), mode));
199 }
200 
201 /*
202  * ZFS_IOC_CREATE callback handles dmu zvol and zap object creation.
203  */
204 void
205 zvol_create_cb(objset_t *os, void *arg, cred_t *cr, dmu_tx_t *tx)
206 {
207 	zfs_creat_t *zct = arg;
208 	nvlist_t *nvprops = zct->zct_props;
209 	int error;
210 	uint64_t volblocksize, volsize;
211 
212 	VERIFY(nvlist_lookup_uint64(nvprops,
213 	    zfs_prop_to_name(ZFS_PROP_VOLSIZE), &volsize) == 0);
214 	if (nvlist_lookup_uint64(nvprops,
215 	    zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE), &volblocksize) != 0)
216 		volblocksize = zfs_prop_default_numeric(ZFS_PROP_VOLBLOCKSIZE);
217 
218 	/*
219 	 * These properties must be removed from the list so the generic
220 	 * property setting step won't apply to them.
221 	 */
222 	VERIFY(nvlist_remove_all(nvprops,
223 	    zfs_prop_to_name(ZFS_PROP_VOLSIZE)) == 0);
224 	(void) nvlist_remove_all(nvprops,
225 	    zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE));
226 
227 	error = dmu_object_claim(os, ZVOL_OBJ, DMU_OT_ZVOL, volblocksize,
228 	    DMU_OT_NONE, 0, tx);
229 	ASSERT(error == 0);
230 
231 	error = zap_create_claim(os, ZVOL_ZAP_OBJ, DMU_OT_ZVOL_PROP,
232 	    DMU_OT_NONE, 0, tx);
233 	ASSERT(error == 0);
234 
235 	error = zap_update(os, ZVOL_ZAP_OBJ, "size", 8, 1, &volsize, tx);
236 	ASSERT(error == 0);
237 }
238 
239 /*
240  * ZFS_IOC_OBJSET_STATS entry point.
241  */
242 int
243 zvol_get_stats(objset_t *os, nvlist_t *nv)
244 {
245 	int error;
246 	dmu_object_info_t *doi;
247 	uint64_t val;
248 
249 	error = zap_lookup(os, ZVOL_ZAP_OBJ, "size", 8, 1, &val);
250 	if (error)
251 		return (SET_ERROR(error));
252 
253 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_VOLSIZE, val);
254 	doi = kmem_alloc(sizeof (dmu_object_info_t), KM_SLEEP);
255 	error = dmu_object_info(os, ZVOL_OBJ, doi);
256 
257 	if (error == 0) {
258 		dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_VOLBLOCKSIZE,
259 		    doi->doi_data_block_size);
260 	}
261 
262 	kmem_free(doi, sizeof (dmu_object_info_t));
263 
264 	return (SET_ERROR(error));
265 }
266 
267 /*
268  * Sanity check volume size.
269  */
270 int
271 zvol_check_volsize(uint64_t volsize, uint64_t blocksize)
272 {
273 	if (volsize == 0)
274 		return (SET_ERROR(EINVAL));
275 
276 	if (volsize % blocksize != 0)
277 		return (SET_ERROR(EINVAL));
278 
279 #ifdef _ILP32
280 	if (volsize - 1 > SPEC_MAXOFFSET_T)
281 		return (SET_ERROR(EOVERFLOW));
282 #endif
283 	return (0);
284 }
285 
286 /*
287  * Ensure the zap is flushed then inform the VFS of the capacity change.
288  */
289 static int
290 zvol_update_volsize(uint64_t volsize, objset_t *os)
291 {
292 	dmu_tx_t *tx;
293 	int error;
294 	uint64_t txg;
295 
296 	tx = dmu_tx_create(os);
297 	dmu_tx_hold_zap(tx, ZVOL_ZAP_OBJ, TRUE, NULL);
298 	dmu_tx_mark_netfree(tx);
299 	error = dmu_tx_assign(tx, DMU_TX_WAIT);
300 	if (error) {
301 		dmu_tx_abort(tx);
302 		return (SET_ERROR(error));
303 	}
304 	txg = dmu_tx_get_txg(tx);
305 
306 	error = zap_update(os, ZVOL_ZAP_OBJ, "size", 8, 1,
307 	    &volsize, tx);
308 	dmu_tx_commit(tx);
309 
310 	txg_wait_synced(dmu_objset_pool(os), txg);
311 
312 	if (error == 0)
313 		error = dmu_free_long_range(os,
314 		    ZVOL_OBJ, volsize, DMU_OBJECT_END);
315 
316 	return (error);
317 }
318 
319 /*
320  * Set ZFS_PROP_VOLSIZE set entry point.  Note that modifying the volume
321  * size will result in a udev "change" event being generated.
322  */
323 int
324 zvol_set_volsize(const char *name, uint64_t volsize)
325 {
326 	objset_t *os = NULL;
327 	uint64_t readonly;
328 	int error;
329 	boolean_t owned = B_FALSE;
330 
331 	error = dsl_prop_get_integer(name,
332 	    zfs_prop_to_name(ZFS_PROP_READONLY), &readonly, NULL);
333 	if (error != 0)
334 		return (SET_ERROR(error));
335 	if (readonly)
336 		return (SET_ERROR(EROFS));
337 
338 	zvol_state_t *zv = zvol_find_by_name(name, RW_READER);
339 
340 	ASSERT(zv == NULL || (MUTEX_HELD(&zv->zv_state_lock) &&
341 	    RW_READ_HELD(&zv->zv_suspend_lock)));
342 
343 	if (zv == NULL || zv->zv_objset == NULL) {
344 		if (zv != NULL)
345 			rw_exit(&zv->zv_suspend_lock);
346 		if ((error = dmu_objset_own(name, DMU_OST_ZVOL, B_FALSE, B_TRUE,
347 		    FTAG, &os)) != 0) {
348 			if (zv != NULL)
349 				mutex_exit(&zv->zv_state_lock);
350 			return (SET_ERROR(error));
351 		}
352 		owned = B_TRUE;
353 		if (zv != NULL)
354 			zv->zv_objset = os;
355 	} else {
356 		os = zv->zv_objset;
357 	}
358 
359 	dmu_object_info_t *doi = kmem_alloc(sizeof (*doi), KM_SLEEP);
360 
361 	if ((error = dmu_object_info(os, ZVOL_OBJ, doi)) ||
362 	    (error = zvol_check_volsize(volsize, doi->doi_data_block_size)))
363 		goto out;
364 
365 	error = zvol_update_volsize(volsize, os);
366 	if (error == 0 && zv != NULL) {
367 		zv->zv_volsize = volsize;
368 		zv->zv_changed = 1;
369 	}
370 out:
371 	kmem_free(doi, sizeof (dmu_object_info_t));
372 
373 	if (owned) {
374 		dmu_objset_disown(os, B_TRUE, FTAG);
375 		if (zv != NULL)
376 			zv->zv_objset = NULL;
377 	} else {
378 		rw_exit(&zv->zv_suspend_lock);
379 	}
380 
381 	if (zv != NULL)
382 		mutex_exit(&zv->zv_state_lock);
383 
384 	if (error == 0 && zv != NULL)
385 		zvol_os_update_volsize(zv, volsize);
386 
387 	return (SET_ERROR(error));
388 }
389 
390 /*
391  * Update volthreading.
392  */
393 int
394 zvol_set_volthreading(const char *name, boolean_t value)
395 {
396 	zvol_state_t *zv = zvol_find_by_name(name, RW_NONE);
397 	if (zv == NULL)
398 		return (ENOENT);
399 	zv->zv_threading = value;
400 	mutex_exit(&zv->zv_state_lock);
401 	return (0);
402 }
403 
404 /*
405  * Update zvol ro property.
406  */
407 int
408 zvol_set_ro(const char *name, boolean_t value)
409 {
410 	zvol_state_t *zv = zvol_find_by_name(name, RW_NONE);
411 	if (zv == NULL)
412 		return (-1);
413 	if (value) {
414 		zvol_os_set_disk_ro(zv, 1);
415 		zv->zv_flags |= ZVOL_RDONLY;
416 	} else {
417 		zvol_os_set_disk_ro(zv, 0);
418 		zv->zv_flags &= ~ZVOL_RDONLY;
419 	}
420 	mutex_exit(&zv->zv_state_lock);
421 	return (0);
422 }
423 
424 /*
425  * Sanity check volume block size.
426  */
427 int
428 zvol_check_volblocksize(const char *name, uint64_t volblocksize)
429 {
430 	/* Record sizes above 128k need the feature to be enabled */
431 	if (volblocksize > SPA_OLD_MAXBLOCKSIZE) {
432 		spa_t *spa;
433 		int error;
434 
435 		if ((error = spa_open(name, &spa, FTAG)) != 0)
436 			return (error);
437 
438 		if (!spa_feature_is_enabled(spa, SPA_FEATURE_LARGE_BLOCKS)) {
439 			spa_close(spa, FTAG);
440 			return (SET_ERROR(ENOTSUP));
441 		}
442 
443 		/*
444 		 * We don't allow setting the property above 1MB,
445 		 * unless the tunable has been changed.
446 		 */
447 		if (volblocksize > zfs_max_recordsize)
448 			return (SET_ERROR(EDOM));
449 
450 		spa_close(spa, FTAG);
451 	}
452 
453 	if (volblocksize < SPA_MINBLOCKSIZE ||
454 	    volblocksize > SPA_MAXBLOCKSIZE ||
455 	    !ISP2(volblocksize))
456 		return (SET_ERROR(EDOM));
457 
458 	return (0);
459 }
460 
461 /*
462  * Replay a TX_TRUNCATE ZIL transaction if asked.  TX_TRUNCATE is how we
463  * implement DKIOCFREE/free-long-range.
464  */
465 static int
466 zvol_replay_truncate(void *arg1, void *arg2, boolean_t byteswap)
467 {
468 	zvol_state_t *zv = arg1;
469 	lr_truncate_t *lr = arg2;
470 	uint64_t offset, length;
471 
472 	ASSERT3U(lr->lr_common.lrc_reclen, >=, sizeof (*lr));
473 
474 	if (byteswap)
475 		byteswap_uint64_array(lr, sizeof (*lr));
476 
477 	offset = lr->lr_offset;
478 	length = lr->lr_length;
479 
480 	dmu_tx_t *tx = dmu_tx_create(zv->zv_objset);
481 	dmu_tx_mark_netfree(tx);
482 	int error = dmu_tx_assign(tx, DMU_TX_WAIT);
483 	if (error != 0) {
484 		dmu_tx_abort(tx);
485 	} else {
486 		(void) zil_replaying(zv->zv_zilog, tx);
487 		dmu_tx_commit(tx);
488 		error = dmu_free_long_range(zv->zv_objset, ZVOL_OBJ, offset,
489 		    length);
490 	}
491 
492 	return (error);
493 }
494 
495 /*
496  * Replay a TX_WRITE ZIL transaction that didn't get committed
497  * after a system failure
498  */
499 static int
500 zvol_replay_write(void *arg1, void *arg2, boolean_t byteswap)
501 {
502 	zvol_state_t *zv = arg1;
503 	lr_write_t *lr = arg2;
504 	objset_t *os = zv->zv_objset;
505 	char *data = (char *)(lr + 1);  /* data follows lr_write_t */
506 	uint64_t offset, length;
507 	dmu_tx_t *tx;
508 	int error;
509 
510 	ASSERT3U(lr->lr_common.lrc_reclen, >=, sizeof (*lr));
511 
512 	if (byteswap)
513 		byteswap_uint64_array(lr, sizeof (*lr));
514 
515 	offset = lr->lr_offset;
516 	length = lr->lr_length;
517 
518 	/* If it's a dmu_sync() block, write the whole block */
519 	if (lr->lr_common.lrc_reclen == sizeof (lr_write_t)) {
520 		uint64_t blocksize = BP_GET_LSIZE(&lr->lr_blkptr);
521 		if (length < blocksize) {
522 			offset -= offset % blocksize;
523 			length = blocksize;
524 		}
525 	}
526 
527 	tx = dmu_tx_create(os);
528 	dmu_tx_hold_write(tx, ZVOL_OBJ, offset, length);
529 	error = dmu_tx_assign(tx, DMU_TX_WAIT);
530 	if (error) {
531 		dmu_tx_abort(tx);
532 	} else {
533 		dmu_write(os, ZVOL_OBJ, offset, length, data, tx);
534 		(void) zil_replaying(zv->zv_zilog, tx);
535 		dmu_tx_commit(tx);
536 	}
537 
538 	return (error);
539 }
540 
541 /*
542  * Replay a TX_CLONE_RANGE ZIL transaction that didn't get committed
543  * after a system failure
544  */
545 static int
546 zvol_replay_clone_range(void *arg1, void *arg2, boolean_t byteswap)
547 {
548 	zvol_state_t *zv = arg1;
549 	lr_clone_range_t *lr = arg2;
550 	objset_t *os = zv->zv_objset;
551 	dmu_tx_t *tx;
552 	int error;
553 	uint64_t blksz;
554 	uint64_t off;
555 	uint64_t len;
556 
557 	ASSERT3U(lr->lr_common.lrc_reclen, >=, sizeof (*lr));
558 	ASSERT3U(lr->lr_common.lrc_reclen, >=, offsetof(lr_clone_range_t,
559 	    lr_bps[lr->lr_nbps]));
560 
561 	if (byteswap)
562 		byteswap_uint64_array(lr, sizeof (*lr));
563 
564 	ASSERT(spa_feature_is_enabled(dmu_objset_spa(os),
565 	    SPA_FEATURE_BLOCK_CLONING));
566 
567 	off = lr->lr_offset;
568 	len = lr->lr_length;
569 	blksz = lr->lr_blksz;
570 
571 	if ((off % blksz) != 0) {
572 		return (SET_ERROR(EINVAL));
573 	}
574 
575 	error = dnode_hold(os, ZVOL_OBJ, zv, &zv->zv_dn);
576 	if (error != 0 || !zv->zv_dn)
577 		return (error);
578 	tx = dmu_tx_create(os);
579 	dmu_tx_hold_clone_by_dnode(tx, zv->zv_dn, off, len);
580 	error = dmu_tx_assign(tx, DMU_TX_WAIT);
581 	if (error != 0) {
582 		dmu_tx_abort(tx);
583 		goto out;
584 	}
585 	error = dmu_brt_clone(zv->zv_objset, ZVOL_OBJ, off, len,
586 	    tx, lr->lr_bps, lr->lr_nbps);
587 	if (error != 0) {
588 		dmu_tx_commit(tx);
589 		goto out;
590 	}
591 
592 	/*
593 	 * zil_replaying() not only check if we are replaying ZIL, but also
594 	 * updates the ZIL header to record replay progress.
595 	 */
596 	VERIFY(zil_replaying(zv->zv_zilog, tx));
597 	dmu_tx_commit(tx);
598 
599 out:
600 	dnode_rele(zv->zv_dn, zv);
601 	zv->zv_dn = NULL;
602 	return (error);
603 }
604 
605 int
606 zvol_clone_range(zvol_state_t *zv_src, uint64_t inoff, zvol_state_t *zv_dst,
607     uint64_t outoff, uint64_t len)
608 {
609 	zilog_t	*zilog_dst;
610 	zfs_locked_range_t *inlr, *outlr;
611 	objset_t *inos, *outos;
612 	dmu_tx_t *tx;
613 	blkptr_t *bps;
614 	size_t maxblocks;
615 	int error = EINVAL;
616 
617 	rw_enter(&zv_dst->zv_suspend_lock, RW_READER);
618 	if (zv_dst->zv_zilog == NULL) {
619 		rw_exit(&zv_dst->zv_suspend_lock);
620 		rw_enter(&zv_dst->zv_suspend_lock, RW_WRITER);
621 		if (zv_dst->zv_zilog == NULL) {
622 			zv_dst->zv_zilog = zil_open(zv_dst->zv_objset,
623 			    zvol_get_data, &zv_dst->zv_kstat.dk_zil_sums);
624 			zv_dst->zv_flags |= ZVOL_WRITTEN_TO;
625 			VERIFY0((zv_dst->zv_zilog->zl_header->zh_flags &
626 			    ZIL_REPLAY_NEEDED));
627 		}
628 		rw_downgrade(&zv_dst->zv_suspend_lock);
629 	}
630 	if (zv_src != zv_dst)
631 		rw_enter(&zv_src->zv_suspend_lock, RW_READER);
632 
633 	inos = zv_src->zv_objset;
634 	outos = zv_dst->zv_objset;
635 
636 	/*
637 	 * Sanity checks
638 	 */
639 	if (!spa_feature_is_enabled(dmu_objset_spa(outos),
640 	    SPA_FEATURE_BLOCK_CLONING)) {
641 		error = EOPNOTSUPP;
642 		goto out;
643 	}
644 	if (dmu_objset_spa(inos) != dmu_objset_spa(outos)) {
645 		error = EXDEV;
646 		goto out;
647 	}
648 	if (inos->os_encrypted != outos->os_encrypted) {
649 		error = EXDEV;
650 		goto out;
651 	}
652 	if (zv_src->zv_volblocksize != zv_dst->zv_volblocksize) {
653 		error = EINVAL;
654 		goto out;
655 	}
656 	if (inoff >= zv_src->zv_volsize || outoff >= zv_dst->zv_volsize) {
657 		error = 0;
658 		goto out;
659 	}
660 
661 	/*
662 	 * Do not read beyond boundary
663 	 */
664 	if (len > zv_src->zv_volsize - inoff)
665 		len = zv_src->zv_volsize - inoff;
666 	if (len > zv_dst->zv_volsize - outoff)
667 		len = zv_dst->zv_volsize - outoff;
668 	if (len == 0) {
669 		error = 0;
670 		goto out;
671 	}
672 
673 	/*
674 	 * No overlapping if we are cloning within the same file
675 	 */
676 	if (zv_src == zv_dst) {
677 		if (inoff < outoff + len && outoff < inoff + len) {
678 			error = EINVAL;
679 			goto out;
680 		}
681 	}
682 
683 	/*
684 	 * Offsets and length must be at block boundaries
685 	 */
686 	if ((inoff % zv_src->zv_volblocksize) != 0 ||
687 	    (outoff % zv_dst->zv_volblocksize) != 0) {
688 		error = EINVAL;
689 		goto out;
690 	}
691 
692 	/*
693 	 * Length must be multiple of block size
694 	 */
695 	if ((len % zv_src->zv_volblocksize) != 0) {
696 		error = EINVAL;
697 		goto out;
698 	}
699 
700 	zilog_dst = zv_dst->zv_zilog;
701 	maxblocks = zil_max_log_data(zilog_dst, sizeof (lr_clone_range_t)) /
702 	    sizeof (bps[0]);
703 	bps = vmem_alloc(sizeof (bps[0]) * maxblocks, KM_SLEEP);
704 	/*
705 	 * Maintain predictable lock order.
706 	 */
707 	if (zv_src < zv_dst || (zv_src == zv_dst && inoff < outoff)) {
708 		inlr = zfs_rangelock_enter(&zv_src->zv_rangelock, inoff, len,
709 		    RL_READER);
710 		outlr = zfs_rangelock_enter(&zv_dst->zv_rangelock, outoff, len,
711 		    RL_WRITER);
712 	} else {
713 		outlr = zfs_rangelock_enter(&zv_dst->zv_rangelock, outoff, len,
714 		    RL_WRITER);
715 		inlr = zfs_rangelock_enter(&zv_src->zv_rangelock, inoff, len,
716 		    RL_READER);
717 	}
718 
719 	while (len > 0) {
720 		uint64_t size, last_synced_txg;
721 		size_t nbps = maxblocks;
722 		size = MIN(zv_src->zv_volblocksize * maxblocks, len);
723 		last_synced_txg = spa_last_synced_txg(
724 		    dmu_objset_spa(zv_src->zv_objset));
725 		error = dmu_read_l0_bps(zv_src->zv_objset, ZVOL_OBJ, inoff,
726 		    size, bps, &nbps);
727 		if (error != 0) {
728 			/*
729 			 * If we are trying to clone a block that was created
730 			 * in the current transaction group, the error will be
731 			 * EAGAIN here.  Based on zfs_bclone_wait_dirty either
732 			 * return a shortened range to the caller so it can
733 			 * fallback, or wait for the next TXG and check again.
734 			 */
735 			if (error == EAGAIN && zfs_bclone_wait_dirty) {
736 				txg_wait_synced(dmu_objset_pool
737 				    (zv_src->zv_objset), last_synced_txg + 1);
738 					continue;
739 			}
740 			break;
741 		}
742 
743 		tx = dmu_tx_create(zv_dst->zv_objset);
744 		dmu_tx_hold_clone_by_dnode(tx, zv_dst->zv_dn, outoff, size);
745 		error = dmu_tx_assign(tx, DMU_TX_WAIT);
746 		if (error != 0) {
747 			dmu_tx_abort(tx);
748 			break;
749 		}
750 		error = dmu_brt_clone(zv_dst->zv_objset, ZVOL_OBJ, outoff, size,
751 		    tx, bps, nbps);
752 		if (error != 0) {
753 			dmu_tx_commit(tx);
754 			break;
755 		}
756 		zvol_log_clone_range(zilog_dst, tx, TX_CLONE_RANGE, outoff,
757 		    size, zv_src->zv_volblocksize, bps, nbps);
758 		dmu_tx_commit(tx);
759 		inoff += size;
760 		outoff += size;
761 		len -= size;
762 	}
763 	vmem_free(bps, sizeof (bps[0]) * maxblocks);
764 	zfs_rangelock_exit(outlr);
765 	zfs_rangelock_exit(inlr);
766 	if (error == 0 && zv_dst->zv_objset->os_sync == ZFS_SYNC_ALWAYS) {
767 		zil_commit(zilog_dst, ZVOL_OBJ);
768 	}
769 out:
770 	if (zv_src != zv_dst)
771 		rw_exit(&zv_src->zv_suspend_lock);
772 	rw_exit(&zv_dst->zv_suspend_lock);
773 	return (SET_ERROR(error));
774 }
775 
776 /*
777  * Handles TX_CLONE_RANGE transactions.
778  */
779 void
780 zvol_log_clone_range(zilog_t *zilog, dmu_tx_t *tx, int txtype, uint64_t off,
781     uint64_t len, uint64_t blksz, const blkptr_t *bps, size_t nbps)
782 {
783 	itx_t *itx;
784 	lr_clone_range_t *lr;
785 	uint64_t partlen, max_log_data;
786 	size_t partnbps;
787 
788 	if (zil_replaying(zilog, tx))
789 		return;
790 
791 	max_log_data = zil_max_log_data(zilog, sizeof (lr_clone_range_t));
792 
793 	while (nbps > 0) {
794 		partnbps = MIN(nbps, max_log_data / sizeof (bps[0]));
795 		partlen = partnbps * blksz;
796 		ASSERT3U(partlen, <, len + blksz);
797 		partlen = MIN(partlen, len);
798 
799 		itx = zil_itx_create(txtype,
800 		    sizeof (*lr) + sizeof (bps[0]) * partnbps);
801 		lr = (lr_clone_range_t *)&itx->itx_lr;
802 		lr->lr_foid = ZVOL_OBJ;
803 		lr->lr_offset = off;
804 		lr->lr_length = partlen;
805 		lr->lr_blksz = blksz;
806 		lr->lr_nbps = partnbps;
807 		memcpy(lr->lr_bps, bps, sizeof (bps[0]) * partnbps);
808 
809 		zil_itx_assign(zilog, itx, tx);
810 
811 		bps += partnbps;
812 		ASSERT3U(nbps, >=, partnbps);
813 		nbps -= partnbps;
814 		off += partlen;
815 		ASSERT3U(len, >=, partlen);
816 		len -= partlen;
817 	}
818 }
819 
820 static int
821 zvol_replay_err(void *arg1, void *arg2, boolean_t byteswap)
822 {
823 	(void) arg1, (void) arg2, (void) byteswap;
824 	return (SET_ERROR(ENOTSUP));
825 }
826 
827 /*
828  * Callback vectors for replaying records.
829  * Only TX_WRITE and TX_TRUNCATE are needed for zvol.
830  */
831 zil_replay_func_t *const zvol_replay_vector[TX_MAX_TYPE] = {
832 	zvol_replay_err,	/* no such transaction type */
833 	zvol_replay_err,	/* TX_CREATE */
834 	zvol_replay_err,	/* TX_MKDIR */
835 	zvol_replay_err,	/* TX_MKXATTR */
836 	zvol_replay_err,	/* TX_SYMLINK */
837 	zvol_replay_err,	/* TX_REMOVE */
838 	zvol_replay_err,	/* TX_RMDIR */
839 	zvol_replay_err,	/* TX_LINK */
840 	zvol_replay_err,	/* TX_RENAME */
841 	zvol_replay_write,	/* TX_WRITE */
842 	zvol_replay_truncate,	/* TX_TRUNCATE */
843 	zvol_replay_err,	/* TX_SETATTR */
844 	zvol_replay_err,	/* TX_ACL_V0 */
845 	zvol_replay_err,	/* TX_ACL */
846 	zvol_replay_err,	/* TX_CREATE_ACL */
847 	zvol_replay_err,	/* TX_CREATE_ATTR */
848 	zvol_replay_err,	/* TX_CREATE_ACL_ATTR */
849 	zvol_replay_err,	/* TX_MKDIR_ACL */
850 	zvol_replay_err,	/* TX_MKDIR_ATTR */
851 	zvol_replay_err,	/* TX_MKDIR_ACL_ATTR */
852 	zvol_replay_err,	/* TX_WRITE2 */
853 	zvol_replay_err,	/* TX_SETSAXATTR */
854 	zvol_replay_err,	/* TX_RENAME_EXCHANGE */
855 	zvol_replay_err,	/* TX_RENAME_WHITEOUT */
856 	zvol_replay_clone_range,	/* TX_CLONE_RANGE */
857 };
858 
859 /*
860  * zvol_log_write() handles synchronous writes using TX_WRITE ZIL transactions.
861  *
862  * We store data in the log buffers if it's small enough.
863  * Otherwise we will later flush the data out via dmu_sync().
864  */
865 static const ssize_t zvol_immediate_write_sz = 32768;
866 
867 void
868 zvol_log_write(zvol_state_t *zv, dmu_tx_t *tx, uint64_t offset,
869     uint64_t size, boolean_t commit)
870 {
871 	uint32_t blocksize = zv->zv_volblocksize;
872 	zilog_t *zilog = zv->zv_zilog;
873 	itx_wr_state_t write_state;
874 	uint64_t log_size = 0;
875 
876 	if (zil_replaying(zilog, tx))
877 		return;
878 
879 	if (zilog->zl_logbias == ZFS_LOGBIAS_THROUGHPUT)
880 		write_state = WR_INDIRECT;
881 	else if (!spa_has_slogs(zilog->zl_spa) &&
882 	    size >= blocksize && blocksize > zvol_immediate_write_sz)
883 		write_state = WR_INDIRECT;
884 	else if (commit)
885 		write_state = WR_COPIED;
886 	else
887 		write_state = WR_NEED_COPY;
888 
889 	while (size) {
890 		itx_t *itx;
891 		lr_write_t *lr;
892 		itx_wr_state_t wr_state = write_state;
893 		ssize_t len = size;
894 
895 		if (wr_state == WR_COPIED && size > zil_max_copied_data(zilog))
896 			wr_state = WR_NEED_COPY;
897 		else if (wr_state == WR_INDIRECT)
898 			len = MIN(blocksize - P2PHASE(offset, blocksize), size);
899 
900 		itx = zil_itx_create(TX_WRITE, sizeof (*lr) +
901 		    (wr_state == WR_COPIED ? len : 0));
902 		lr = (lr_write_t *)&itx->itx_lr;
903 		if (wr_state == WR_COPIED &&
904 		    dmu_read_by_dnode(zv->zv_dn, offset, len, lr + 1,
905 		    DMU_READ_NO_PREFETCH | DMU_KEEP_CACHING) != 0) {
906 			zil_itx_destroy(itx);
907 			itx = zil_itx_create(TX_WRITE, sizeof (*lr));
908 			lr = (lr_write_t *)&itx->itx_lr;
909 			wr_state = WR_NEED_COPY;
910 		}
911 
912 		log_size += itx->itx_size;
913 		if (wr_state == WR_NEED_COPY)
914 			log_size += len;
915 
916 		itx->itx_wr_state = wr_state;
917 		lr->lr_foid = ZVOL_OBJ;
918 		lr->lr_offset = offset;
919 		lr->lr_length = len;
920 		lr->lr_blkoff = 0;
921 		BP_ZERO(&lr->lr_blkptr);
922 
923 		itx->itx_private = zv;
924 
925 		(void) zil_itx_assign(zilog, itx, tx);
926 
927 		offset += len;
928 		size -= len;
929 	}
930 
931 	dsl_pool_wrlog_count(zilog->zl_dmu_pool, log_size, tx->tx_txg);
932 }
933 
934 /*
935  * Log a DKIOCFREE/free-long-range to the ZIL with TX_TRUNCATE.
936  */
937 void
938 zvol_log_truncate(zvol_state_t *zv, dmu_tx_t *tx, uint64_t off, uint64_t len)
939 {
940 	itx_t *itx;
941 	lr_truncate_t *lr;
942 	zilog_t *zilog = zv->zv_zilog;
943 
944 	if (zil_replaying(zilog, tx))
945 		return;
946 
947 	itx = zil_itx_create(TX_TRUNCATE, sizeof (*lr));
948 	lr = (lr_truncate_t *)&itx->itx_lr;
949 	lr->lr_foid = ZVOL_OBJ;
950 	lr->lr_offset = off;
951 	lr->lr_length = len;
952 
953 	zil_itx_assign(zilog, itx, tx);
954 }
955 
956 
957 static void
958 zvol_get_done(zgd_t *zgd, int error)
959 {
960 	(void) error;
961 	if (zgd->zgd_db)
962 		dmu_buf_rele(zgd->zgd_db, zgd);
963 
964 	zfs_rangelock_exit(zgd->zgd_lr);
965 
966 	kmem_free(zgd, sizeof (zgd_t));
967 }
968 
969 /*
970  * Get data to generate a TX_WRITE intent log record.
971  */
972 int
973 zvol_get_data(void *arg, uint64_t arg2, lr_write_t *lr, char *buf,
974     struct lwb *lwb, zio_t *zio)
975 {
976 	zvol_state_t *zv = arg;
977 	uint64_t offset = lr->lr_offset;
978 	uint64_t size = lr->lr_length;
979 	dmu_buf_t *db;
980 	zgd_t *zgd;
981 	int error;
982 
983 	ASSERT3P(lwb, !=, NULL);
984 	ASSERT3U(size, !=, 0);
985 
986 	zgd = kmem_zalloc(sizeof (zgd_t), KM_SLEEP);
987 	zgd->zgd_lwb = lwb;
988 
989 	/*
990 	 * Write records come in two flavors: immediate and indirect.
991 	 * For small writes it's cheaper to store the data with the
992 	 * log record (immediate); for large writes it's cheaper to
993 	 * sync the data and get a pointer to it (indirect) so that
994 	 * we don't have to write the data twice.
995 	 */
996 	if (buf != NULL) { /* immediate write */
997 		zgd->zgd_lr = zfs_rangelock_enter(&zv->zv_rangelock, offset,
998 		    size, RL_READER);
999 		error = dmu_read_by_dnode(zv->zv_dn, offset, size, buf,
1000 		    DMU_READ_NO_PREFETCH | DMU_KEEP_CACHING);
1001 	} else { /* indirect write */
1002 		ASSERT3P(zio, !=, NULL);
1003 		/*
1004 		 * Have to lock the whole block to ensure when it's written out
1005 		 * and its checksum is being calculated that no one can change
1006 		 * the data. Contrarily to zfs_get_data we need not re-check
1007 		 * blocksize after we get the lock because it cannot be changed.
1008 		 */
1009 		size = zv->zv_volblocksize;
1010 		offset = P2ALIGN_TYPED(offset, size, uint64_t);
1011 		zgd->zgd_lr = zfs_rangelock_enter(&zv->zv_rangelock, offset,
1012 		    size, RL_READER);
1013 		error = dmu_buf_hold_noread_by_dnode(zv->zv_dn, offset, zgd,
1014 		    &db);
1015 		if (error == 0) {
1016 			blkptr_t *bp = &lr->lr_blkptr;
1017 
1018 			zgd->zgd_db = db;
1019 			zgd->zgd_bp = bp;
1020 
1021 			ASSERT(db != NULL);
1022 			ASSERT(db->db_offset == offset);
1023 			ASSERT(db->db_size == size);
1024 
1025 			error = dmu_sync(zio, lr->lr_common.lrc_txg,
1026 			    zvol_get_done, zgd);
1027 
1028 			if (error == 0)
1029 				return (0);
1030 		}
1031 	}
1032 
1033 	zvol_get_done(zgd, error);
1034 
1035 	return (SET_ERROR(error));
1036 }
1037 
1038 /*
1039  * The zvol_state_t's are inserted into zvol_state_list and zvol_htable.
1040  */
1041 
1042 void
1043 zvol_insert(zvol_state_t *zv)
1044 {
1045 	ASSERT(RW_WRITE_HELD(&zvol_state_lock));
1046 	list_insert_head(&zvol_state_list, zv);
1047 	hlist_add_head(&zv->zv_hlink, ZVOL_HT_HEAD(zv->zv_hash));
1048 }
1049 
1050 /*
1051  * Simply remove the zvol from to list of zvols.
1052  */
1053 static void
1054 zvol_remove(zvol_state_t *zv)
1055 {
1056 	ASSERT(RW_WRITE_HELD(&zvol_state_lock));
1057 	list_remove(&zvol_state_list, zv);
1058 	hlist_del(&zv->zv_hlink);
1059 }
1060 
1061 /*
1062  * Setup zv after we just own the zv->objset
1063  */
1064 static int
1065 zvol_setup_zv(zvol_state_t *zv)
1066 {
1067 	uint64_t volsize;
1068 	int error;
1069 	uint64_t ro;
1070 	objset_t *os = zv->zv_objset;
1071 
1072 	ASSERT(MUTEX_HELD(&zv->zv_state_lock));
1073 	ASSERT(RW_LOCK_HELD(&zv->zv_suspend_lock));
1074 
1075 	zv->zv_zilog = NULL;
1076 	zv->zv_flags &= ~ZVOL_WRITTEN_TO;
1077 
1078 	error = dsl_prop_get_integer(zv->zv_name, "readonly", &ro, NULL);
1079 	if (error)
1080 		return (SET_ERROR(error));
1081 
1082 	error = zap_lookup(os, ZVOL_ZAP_OBJ, "size", 8, 1, &volsize);
1083 	if (error)
1084 		return (SET_ERROR(error));
1085 
1086 	error = dnode_hold(os, ZVOL_OBJ, zv, &zv->zv_dn);
1087 	if (error)
1088 		return (SET_ERROR(error));
1089 
1090 	zvol_os_set_capacity(zv, volsize >> 9);
1091 	zv->zv_volsize = volsize;
1092 
1093 	if (ro || dmu_objset_is_snapshot(os) ||
1094 	    !spa_writeable(dmu_objset_spa(os))) {
1095 		zvol_os_set_disk_ro(zv, 1);
1096 		zv->zv_flags |= ZVOL_RDONLY;
1097 	} else {
1098 		zvol_os_set_disk_ro(zv, 0);
1099 		zv->zv_flags &= ~ZVOL_RDONLY;
1100 	}
1101 	return (0);
1102 }
1103 
1104 /*
1105  * Shutdown every zv_objset related stuff except zv_objset itself.
1106  * The is the reverse of zvol_setup_zv.
1107  */
1108 static void
1109 zvol_shutdown_zv(zvol_state_t *zv)
1110 {
1111 	ASSERT(MUTEX_HELD(&zv->zv_state_lock) &&
1112 	    RW_LOCK_HELD(&zv->zv_suspend_lock));
1113 
1114 	if (zv->zv_flags & ZVOL_WRITTEN_TO) {
1115 		ASSERT(zv->zv_zilog != NULL);
1116 		zil_close(zv->zv_zilog);
1117 	}
1118 
1119 	zv->zv_zilog = NULL;
1120 
1121 	dnode_rele(zv->zv_dn, zv);
1122 	zv->zv_dn = NULL;
1123 
1124 	/*
1125 	 * Evict cached data. We must write out any dirty data before
1126 	 * disowning the dataset.
1127 	 */
1128 	if (zv->zv_flags & ZVOL_WRITTEN_TO)
1129 		txg_wait_synced(dmu_objset_pool(zv->zv_objset), 0);
1130 	(void) dmu_objset_evict_dbufs(zv->zv_objset);
1131 }
1132 
1133 /*
1134  * return the proper tag for rollback and recv
1135  */
1136 void *
1137 zvol_tag(zvol_state_t *zv)
1138 {
1139 	ASSERT(RW_WRITE_HELD(&zv->zv_suspend_lock));
1140 	return (zv->zv_open_count > 0 ? zv : NULL);
1141 }
1142 
1143 /*
1144  * Suspend the zvol for recv and rollback.
1145  */
1146 zvol_state_t *
1147 zvol_suspend(const char *name)
1148 {
1149 	zvol_state_t *zv;
1150 
1151 	zv = zvol_find_by_name(name, RW_WRITER);
1152 
1153 	if (zv == NULL)
1154 		return (NULL);
1155 
1156 	/* block all I/O, release in zvol_resume. */
1157 	ASSERT(MUTEX_HELD(&zv->zv_state_lock));
1158 	ASSERT(RW_WRITE_HELD(&zv->zv_suspend_lock));
1159 
1160 	atomic_inc(&zv->zv_suspend_ref);
1161 
1162 	if (zv->zv_open_count > 0)
1163 		zvol_shutdown_zv(zv);
1164 
1165 	/*
1166 	 * do not hold zv_state_lock across suspend/resume to
1167 	 * avoid locking up zvol lookups
1168 	 */
1169 	mutex_exit(&zv->zv_state_lock);
1170 
1171 	/* zv_suspend_lock is released in zvol_resume() */
1172 	return (zv);
1173 }
1174 
1175 int
1176 zvol_resume(zvol_state_t *zv)
1177 {
1178 	int error = 0;
1179 
1180 	ASSERT(RW_WRITE_HELD(&zv->zv_suspend_lock));
1181 
1182 	mutex_enter(&zv->zv_state_lock);
1183 
1184 	if (zv->zv_open_count > 0) {
1185 		VERIFY0(dmu_objset_hold(zv->zv_name, zv, &zv->zv_objset));
1186 		VERIFY3P(zv->zv_objset->os_dsl_dataset->ds_owner, ==, zv);
1187 		VERIFY(dsl_dataset_long_held(zv->zv_objset->os_dsl_dataset));
1188 		dmu_objset_rele(zv->zv_objset, zv);
1189 
1190 		error = zvol_setup_zv(zv);
1191 	}
1192 
1193 	mutex_exit(&zv->zv_state_lock);
1194 
1195 	rw_exit(&zv->zv_suspend_lock);
1196 	/*
1197 	 * We need this because we don't hold zvol_state_lock while releasing
1198 	 * zv_suspend_lock. zvol_remove_minors_impl thus cannot check
1199 	 * zv_suspend_lock to determine it is safe to free because rwlock is
1200 	 * not inherent atomic.
1201 	 */
1202 	atomic_dec(&zv->zv_suspend_ref);
1203 
1204 	if (zv->zv_flags & ZVOL_REMOVING)
1205 		cv_broadcast(&zv->zv_removing_cv);
1206 
1207 	return (SET_ERROR(error));
1208 }
1209 
1210 int
1211 zvol_first_open(zvol_state_t *zv, boolean_t readonly)
1212 {
1213 	objset_t *os;
1214 	int error;
1215 
1216 	ASSERT(RW_READ_HELD(&zv->zv_suspend_lock));
1217 	ASSERT(MUTEX_HELD(&zv->zv_state_lock));
1218 	ASSERT(mutex_owned(&spa_namespace_lock));
1219 
1220 	boolean_t ro = (readonly || (strchr(zv->zv_name, '@') != NULL));
1221 	error = dmu_objset_own(zv->zv_name, DMU_OST_ZVOL, ro, B_TRUE, zv, &os);
1222 	if (error)
1223 		return (SET_ERROR(error));
1224 
1225 	zv->zv_objset = os;
1226 
1227 	error = zvol_setup_zv(zv);
1228 	if (error) {
1229 		dmu_objset_disown(os, 1, zv);
1230 		zv->zv_objset = NULL;
1231 	}
1232 
1233 	return (error);
1234 }
1235 
1236 void
1237 zvol_last_close(zvol_state_t *zv)
1238 {
1239 	ASSERT(RW_READ_HELD(&zv->zv_suspend_lock));
1240 	ASSERT(MUTEX_HELD(&zv->zv_state_lock));
1241 
1242 	if (zv->zv_flags & ZVOL_REMOVING)
1243 		cv_broadcast(&zv->zv_removing_cv);
1244 
1245 	zvol_shutdown_zv(zv);
1246 
1247 	dmu_objset_disown(zv->zv_objset, 1, zv);
1248 	zv->zv_objset = NULL;
1249 }
1250 
1251 typedef struct minors_job {
1252 	list_t *list;
1253 	list_node_t link;
1254 	/* input */
1255 	char *name;
1256 	/* output */
1257 	int error;
1258 } minors_job_t;
1259 
1260 /*
1261  * Prefetch zvol dnodes for the minors_job
1262  */
1263 static void
1264 zvol_prefetch_minors_impl(void *arg)
1265 {
1266 	minors_job_t *job = arg;
1267 	char *dsname = job->name;
1268 	objset_t *os = NULL;
1269 
1270 	job->error = dmu_objset_own(dsname, DMU_OST_ZVOL, B_TRUE, B_TRUE,
1271 	    FTAG, &os);
1272 	if (job->error == 0) {
1273 		dmu_prefetch_dnode(os, ZVOL_OBJ, ZIO_PRIORITY_SYNC_READ);
1274 		dmu_objset_disown(os, B_TRUE, FTAG);
1275 	}
1276 }
1277 
1278 /*
1279  * Mask errors to continue dmu_objset_find() traversal
1280  */
1281 static int
1282 zvol_create_snap_minor_cb(const char *dsname, void *arg)
1283 {
1284 	minors_job_t *j = arg;
1285 	list_t *minors_list = j->list;
1286 	const char *name = j->name;
1287 
1288 	ASSERT0(MUTEX_HELD(&spa_namespace_lock));
1289 
1290 	/* skip the designated dataset */
1291 	if (name && strcmp(dsname, name) == 0)
1292 		return (0);
1293 
1294 	/* at this point, the dsname should name a snapshot */
1295 	if (strchr(dsname, '@') == 0) {
1296 		dprintf("zvol_create_snap_minor_cb(): "
1297 		    "%s is not a snapshot name\n", dsname);
1298 	} else {
1299 		minors_job_t *job;
1300 		char *n = kmem_strdup(dsname);
1301 		if (n == NULL)
1302 			return (0);
1303 
1304 		job = kmem_alloc(sizeof (minors_job_t), KM_SLEEP);
1305 		job->name = n;
1306 		job->list = minors_list;
1307 		job->error = 0;
1308 		list_insert_tail(minors_list, job);
1309 		/* don't care if dispatch fails, because job->error is 0 */
1310 		taskq_dispatch(system_taskq, zvol_prefetch_minors_impl, job,
1311 		    TQ_SLEEP);
1312 	}
1313 
1314 	return (0);
1315 }
1316 
1317 /*
1318  * If spa_keystore_load_wkey() is called for an encrypted zvol,
1319  * we need to look for any clones also using the key. This function
1320  * is "best effort" - so we just skip over it if there are failures.
1321  */
1322 static void
1323 zvol_add_clones(const char *dsname, list_t *minors_list)
1324 {
1325 	/* Also check if it has clones */
1326 	dsl_dir_t *dd = NULL;
1327 	dsl_pool_t *dp = NULL;
1328 
1329 	if (dsl_pool_hold(dsname, FTAG, &dp) != 0)
1330 		return;
1331 
1332 	if (!spa_feature_is_enabled(dp->dp_spa,
1333 	    SPA_FEATURE_ENCRYPTION))
1334 		goto out;
1335 
1336 	if (dsl_dir_hold(dp, dsname, FTAG, &dd, NULL) != 0)
1337 		goto out;
1338 
1339 	if (dsl_dir_phys(dd)->dd_clones == 0)
1340 		goto out;
1341 
1342 	zap_cursor_t *zc = kmem_alloc(sizeof (zap_cursor_t), KM_SLEEP);
1343 	zap_attribute_t *za = zap_attribute_alloc();
1344 	objset_t *mos = dd->dd_pool->dp_meta_objset;
1345 
1346 	for (zap_cursor_init(zc, mos, dsl_dir_phys(dd)->dd_clones);
1347 	    zap_cursor_retrieve(zc, za) == 0;
1348 	    zap_cursor_advance(zc)) {
1349 		dsl_dataset_t *clone;
1350 		minors_job_t *job;
1351 
1352 		if (dsl_dataset_hold_obj(dd->dd_pool,
1353 		    za->za_first_integer, FTAG, &clone) == 0) {
1354 
1355 			char name[ZFS_MAX_DATASET_NAME_LEN];
1356 			dsl_dataset_name(clone, name);
1357 
1358 			char *n = kmem_strdup(name);
1359 			job = kmem_alloc(sizeof (minors_job_t), KM_SLEEP);
1360 			job->name = n;
1361 			job->list = minors_list;
1362 			job->error = 0;
1363 			list_insert_tail(minors_list, job);
1364 
1365 			dsl_dataset_rele(clone, FTAG);
1366 		}
1367 	}
1368 	zap_cursor_fini(zc);
1369 	zap_attribute_free(za);
1370 	kmem_free(zc, sizeof (zap_cursor_t));
1371 
1372 out:
1373 	if (dd != NULL)
1374 		dsl_dir_rele(dd, FTAG);
1375 	dsl_pool_rele(dp, FTAG);
1376 }
1377 
1378 /*
1379  * Mask errors to continue dmu_objset_find() traversal
1380  */
1381 static int
1382 zvol_create_minors_cb(const char *dsname, void *arg)
1383 {
1384 	uint64_t snapdev;
1385 	int error;
1386 	list_t *minors_list = arg;
1387 
1388 	ASSERT0(MUTEX_HELD(&spa_namespace_lock));
1389 
1390 	error = dsl_prop_get_integer(dsname, "snapdev", &snapdev, NULL);
1391 	if (error)
1392 		return (0);
1393 
1394 	/*
1395 	 * Given the name and the 'snapdev' property, create device minor nodes
1396 	 * with the linkages to zvols/snapshots as needed.
1397 	 * If the name represents a zvol, create a minor node for the zvol, then
1398 	 * check if its snapshots are 'visible', and if so, iterate over the
1399 	 * snapshots and create device minor nodes for those.
1400 	 */
1401 	if (strchr(dsname, '@') == 0) {
1402 		minors_job_t *job;
1403 		char *n = kmem_strdup(dsname);
1404 		if (n == NULL)
1405 			return (0);
1406 
1407 		job = kmem_alloc(sizeof (minors_job_t), KM_SLEEP);
1408 		job->name = n;
1409 		job->list = minors_list;
1410 		job->error = 0;
1411 		list_insert_tail(minors_list, job);
1412 		/* don't care if dispatch fails, because job->error is 0 */
1413 		taskq_dispatch(system_taskq, zvol_prefetch_minors_impl, job,
1414 		    TQ_SLEEP);
1415 
1416 		zvol_add_clones(dsname, minors_list);
1417 
1418 		if (snapdev == ZFS_SNAPDEV_VISIBLE) {
1419 			/*
1420 			 * traverse snapshots only, do not traverse children,
1421 			 * and skip the 'dsname'
1422 			 */
1423 			(void) dmu_objset_find(dsname,
1424 			    zvol_create_snap_minor_cb, (void *)job,
1425 			    DS_FIND_SNAPSHOTS);
1426 		}
1427 	} else {
1428 		dprintf("zvol_create_minors_cb(): %s is not a zvol name\n",
1429 		    dsname);
1430 	}
1431 
1432 	return (0);
1433 }
1434 
1435 /*
1436  * Create minors for the specified dataset, including children and snapshots.
1437  * Pay attention to the 'snapdev' property and iterate over the snapshots
1438  * only if they are 'visible'. This approach allows one to assure that the
1439  * snapshot metadata is read from disk only if it is needed.
1440  *
1441  * The name can represent a dataset to be recursively scanned for zvols and
1442  * their snapshots, or a single zvol snapshot. If the name represents a
1443  * dataset, the scan is performed in two nested stages:
1444  * - scan the dataset for zvols, and
1445  * - for each zvol, create a minor node, then check if the zvol's snapshots
1446  *   are 'visible', and only then iterate over the snapshots if needed
1447  *
1448  * If the name represents a snapshot, a check is performed if the snapshot is
1449  * 'visible' (which also verifies that the parent is a zvol), and if so,
1450  * a minor node for that snapshot is created.
1451  */
1452 void
1453 zvol_create_minors_recursive(const char *name)
1454 {
1455 	list_t minors_list;
1456 	minors_job_t *job;
1457 
1458 	if (zvol_inhibit_dev)
1459 		return;
1460 
1461 	/*
1462 	 * This is the list for prefetch jobs. Whenever we found a match
1463 	 * during dmu_objset_find, we insert a minors_job to the list and do
1464 	 * taskq_dispatch to parallel prefetch zvol dnodes. Note we don't need
1465 	 * any lock because all list operation is done on the current thread.
1466 	 *
1467 	 * We will use this list to do zvol_os_create_minor after prefetch
1468 	 * so we don't have to traverse using dmu_objset_find again.
1469 	 */
1470 	list_create(&minors_list, sizeof (minors_job_t),
1471 	    offsetof(minors_job_t, link));
1472 
1473 
1474 	if (strchr(name, '@') != NULL) {
1475 		uint64_t snapdev;
1476 
1477 		int error = dsl_prop_get_integer(name, "snapdev",
1478 		    &snapdev, NULL);
1479 
1480 		if (error == 0 && snapdev == ZFS_SNAPDEV_VISIBLE)
1481 			(void) zvol_os_create_minor(name);
1482 	} else {
1483 		fstrans_cookie_t cookie = spl_fstrans_mark();
1484 		(void) dmu_objset_find(name, zvol_create_minors_cb,
1485 		    &minors_list, DS_FIND_CHILDREN);
1486 		spl_fstrans_unmark(cookie);
1487 	}
1488 
1489 	taskq_wait_outstanding(system_taskq, 0);
1490 
1491 	/*
1492 	 * Prefetch is completed, we can do zvol_os_create_minor
1493 	 * sequentially.
1494 	 */
1495 	while ((job = list_remove_head(&minors_list)) != NULL) {
1496 		if (!job->error)
1497 			(void) zvol_os_create_minor(job->name);
1498 		kmem_strfree(job->name);
1499 		kmem_free(job, sizeof (minors_job_t));
1500 	}
1501 
1502 	list_destroy(&minors_list);
1503 }
1504 
1505 void
1506 zvol_create_minor(const char *name)
1507 {
1508 	/*
1509 	 * Note: the dsl_pool_config_lock must not be held.
1510 	 * Minor node creation needs to obtain the zvol_state_lock.
1511 	 * zvol_open() obtains the zvol_state_lock and then the dsl pool
1512 	 * config lock.  Therefore, we can't have the config lock now if
1513 	 * we are going to wait for the zvol_state_lock, because it
1514 	 * would be a lock order inversion which could lead to deadlock.
1515 	 */
1516 
1517 	if (zvol_inhibit_dev)
1518 		return;
1519 
1520 	if (strchr(name, '@') != NULL) {
1521 		uint64_t snapdev;
1522 
1523 		int error = dsl_prop_get_integer(name,
1524 		    "snapdev", &snapdev, NULL);
1525 
1526 		if (error == 0 && snapdev == ZFS_SNAPDEV_VISIBLE)
1527 			(void) zvol_os_create_minor(name);
1528 	} else {
1529 		(void) zvol_os_create_minor(name);
1530 	}
1531 }
1532 
1533 /*
1534  * Remove minors for specified dataset including children and snapshots.
1535  */
1536 
1537 /*
1538  * Remove the minor for a given zvol. This will do it all:
1539  *  - flag the zvol for removal, so new requests are rejected
1540  *  - wait until outstanding requests are completed
1541  *  - remove it from lists
1542  *  - free it
1543  * It's also usable as a taskq task, and smells nice too.
1544  */
1545 static void
1546 zvol_remove_minor_task(void *arg)
1547 {
1548 	zvol_state_t *zv = (zvol_state_t *)arg;
1549 
1550 	ASSERT(!RW_LOCK_HELD(&zvol_state_lock));
1551 	ASSERT(!MUTEX_HELD(&zv->zv_state_lock));
1552 
1553 	mutex_enter(&zv->zv_state_lock);
1554 	while (zv->zv_open_count > 0 || atomic_read(&zv->zv_suspend_ref)) {
1555 		zv->zv_flags |= ZVOL_REMOVING;
1556 		cv_wait(&zv->zv_removing_cv, &zv->zv_state_lock);
1557 	}
1558 	mutex_exit(&zv->zv_state_lock);
1559 
1560 	rw_enter(&zvol_state_lock, RW_WRITER);
1561 	mutex_enter(&zv->zv_state_lock);
1562 
1563 	zvol_remove(zv);
1564 	zvol_os_clear_private(zv);
1565 
1566 	mutex_exit(&zv->zv_state_lock);
1567 	rw_exit(&zvol_state_lock);
1568 
1569 	zvol_os_free(zv);
1570 }
1571 
1572 static void
1573 zvol_free_task(void *arg)
1574 {
1575 	zvol_os_free(arg);
1576 }
1577 
1578 void
1579 zvol_remove_minors_impl(const char *name)
1580 {
1581 	zvol_state_t *zv, *zv_next;
1582 	int namelen = ((name) ? strlen(name) : 0);
1583 	taskqid_t t;
1584 	list_t delay_list, free_list;
1585 
1586 	if (zvol_inhibit_dev)
1587 		return;
1588 
1589 	list_create(&delay_list, sizeof (zvol_state_t),
1590 	    offsetof(zvol_state_t, zv_next));
1591 	list_create(&free_list, sizeof (zvol_state_t),
1592 	    offsetof(zvol_state_t, zv_next));
1593 
1594 	rw_enter(&zvol_state_lock, RW_WRITER);
1595 
1596 	for (zv = list_head(&zvol_state_list); zv != NULL; zv = zv_next) {
1597 		zv_next = list_next(&zvol_state_list, zv);
1598 
1599 		mutex_enter(&zv->zv_state_lock);
1600 		if (name == NULL || strcmp(zv->zv_name, name) == 0 ||
1601 		    (strncmp(zv->zv_name, name, namelen) == 0 &&
1602 		    (zv->zv_name[namelen] == '/' ||
1603 		    zv->zv_name[namelen] == '@'))) {
1604 			/*
1605 			 * By holding zv_state_lock here, we guarantee that no
1606 			 * one is currently using this zv
1607 			 */
1608 
1609 			/*
1610 			 * If in use, try to throw everyone off and try again
1611 			 * later.
1612 			 */
1613 			if (zv->zv_open_count > 0 ||
1614 			    atomic_read(&zv->zv_suspend_ref)) {
1615 				zv->zv_flags |= ZVOL_REMOVING;
1616 				t = taskq_dispatch(
1617 				    zv->zv_objset->os_spa->spa_zvol_taskq,
1618 				    zvol_remove_minor_task, zv, TQ_SLEEP);
1619 				if (t == TASKQID_INVALID) {
1620 					/*
1621 					 * Couldn't create the task, so we'll
1622 					 * do it in place once the loop is
1623 					 * finished.
1624 					 */
1625 					list_insert_head(&delay_list, zv);
1626 				}
1627 				mutex_exit(&zv->zv_state_lock);
1628 				continue;
1629 			}
1630 
1631 			zvol_remove(zv);
1632 
1633 			/*
1634 			 * Cleared while holding zvol_state_lock as a writer
1635 			 * which will prevent zvol_open() from opening it.
1636 			 */
1637 			zvol_os_clear_private(zv);
1638 
1639 			/* Drop zv_state_lock before zvol_free() */
1640 			mutex_exit(&zv->zv_state_lock);
1641 
1642 			/* Try parallel zv_free, if failed do it in place */
1643 			t = taskq_dispatch(system_taskq, zvol_free_task, zv,
1644 			    TQ_SLEEP);
1645 			if (t == TASKQID_INVALID)
1646 				list_insert_head(&free_list, zv);
1647 		} else {
1648 			mutex_exit(&zv->zv_state_lock);
1649 		}
1650 	}
1651 	rw_exit(&zvol_state_lock);
1652 
1653 	/* Wait for zvols that we couldn't create a remove task for */
1654 	while ((zv = list_remove_head(&delay_list)) != NULL)
1655 		zvol_remove_minor_task(zv);
1656 
1657 	/* Free any that we couldn't free in parallel earlier */
1658 	while ((zv = list_remove_head(&free_list)) != NULL)
1659 		zvol_os_free(zv);
1660 }
1661 
1662 /* Remove minor for this specific volume only */
1663 static void
1664 zvol_remove_minor_impl(const char *name)
1665 {
1666 	zvol_state_t *zv = NULL, *zv_next;
1667 
1668 	if (zvol_inhibit_dev)
1669 		return;
1670 
1671 	rw_enter(&zvol_state_lock, RW_WRITER);
1672 
1673 	for (zv = list_head(&zvol_state_list); zv != NULL; zv = zv_next) {
1674 		zv_next = list_next(&zvol_state_list, zv);
1675 
1676 		mutex_enter(&zv->zv_state_lock);
1677 		if (strcmp(zv->zv_name, name) == 0)
1678 			/* Found, leave the the loop with zv_lock held */
1679 			break;
1680 		mutex_exit(&zv->zv_state_lock);
1681 	}
1682 
1683 	if (zv == NULL) {
1684 		rw_exit(&zvol_state_lock);
1685 		return;
1686 	}
1687 
1688 	ASSERT(MUTEX_HELD(&zv->zv_state_lock));
1689 
1690 	if (zv->zv_open_count > 0 || atomic_read(&zv->zv_suspend_ref)) {
1691 		/*
1692 		 * In use, so try to throw everyone off, then wait
1693 		 * until finished.
1694 		 */
1695 		zv->zv_flags |= ZVOL_REMOVING;
1696 		mutex_exit(&zv->zv_state_lock);
1697 		rw_exit(&zvol_state_lock);
1698 		zvol_remove_minor_task(zv);
1699 		return;
1700 	}
1701 
1702 	zvol_remove(zv);
1703 	zvol_os_clear_private(zv);
1704 
1705 	mutex_exit(&zv->zv_state_lock);
1706 	rw_exit(&zvol_state_lock);
1707 
1708 	zvol_os_free(zv);
1709 }
1710 
1711 /*
1712  * Rename minors for specified dataset including children and snapshots.
1713  */
1714 static void
1715 zvol_rename_minors_impl(const char *oldname, const char *newname)
1716 {
1717 	zvol_state_t *zv, *zv_next;
1718 	int oldnamelen;
1719 
1720 	if (zvol_inhibit_dev)
1721 		return;
1722 
1723 	oldnamelen = strlen(oldname);
1724 
1725 	rw_enter(&zvol_state_lock, RW_READER);
1726 
1727 	for (zv = list_head(&zvol_state_list); zv != NULL; zv = zv_next) {
1728 		zv_next = list_next(&zvol_state_list, zv);
1729 
1730 		mutex_enter(&zv->zv_state_lock);
1731 
1732 		if (strcmp(zv->zv_name, oldname) == 0) {
1733 			zvol_os_rename_minor(zv, newname);
1734 		} else if (strncmp(zv->zv_name, oldname, oldnamelen) == 0 &&
1735 		    (zv->zv_name[oldnamelen] == '/' ||
1736 		    zv->zv_name[oldnamelen] == '@')) {
1737 			char *name = kmem_asprintf("%s%c%s", newname,
1738 			    zv->zv_name[oldnamelen],
1739 			    zv->zv_name + oldnamelen + 1);
1740 			zvol_os_rename_minor(zv, name);
1741 			kmem_strfree(name);
1742 		}
1743 
1744 		mutex_exit(&zv->zv_state_lock);
1745 	}
1746 
1747 	rw_exit(&zvol_state_lock);
1748 }
1749 
1750 typedef struct zvol_snapdev_cb_arg {
1751 	uint64_t snapdev;
1752 } zvol_snapdev_cb_arg_t;
1753 
1754 static int
1755 zvol_set_snapdev_cb(const char *dsname, void *param)
1756 {
1757 	zvol_snapdev_cb_arg_t *arg = param;
1758 
1759 	if (strchr(dsname, '@') == NULL)
1760 		return (0);
1761 
1762 	switch (arg->snapdev) {
1763 		case ZFS_SNAPDEV_VISIBLE:
1764 			(void) zvol_os_create_minor(dsname);
1765 			break;
1766 		case ZFS_SNAPDEV_HIDDEN:
1767 			(void) zvol_remove_minor_impl(dsname);
1768 			break;
1769 	}
1770 
1771 	return (0);
1772 }
1773 
1774 static void
1775 zvol_set_snapdev_impl(char *name, uint64_t snapdev)
1776 {
1777 	zvol_snapdev_cb_arg_t arg = {snapdev};
1778 	fstrans_cookie_t cookie = spl_fstrans_mark();
1779 	/*
1780 	 * The zvol_set_snapdev_sync() sets snapdev appropriately
1781 	 * in the dataset hierarchy. Here, we only scan snapshots.
1782 	 */
1783 	dmu_objset_find(name, zvol_set_snapdev_cb, &arg, DS_FIND_SNAPSHOTS);
1784 	spl_fstrans_unmark(cookie);
1785 }
1786 
1787 static void
1788 zvol_set_volmode_impl(char *name, uint64_t volmode)
1789 {
1790 	fstrans_cookie_t cookie;
1791 	uint64_t old_volmode;
1792 	zvol_state_t *zv;
1793 
1794 	if (strchr(name, '@') != NULL)
1795 		return;
1796 
1797 	/*
1798 	 * It's unfortunate we need to remove minors before we create new ones:
1799 	 * this is necessary because our backing gendisk (zvol_state->zv_disk)
1800 	 * could be different when we set, for instance, volmode from "geom"
1801 	 * to "dev" (or vice versa).
1802 	 */
1803 	zv = zvol_find_by_name(name, RW_NONE);
1804 	if (zv == NULL && volmode == ZFS_VOLMODE_NONE)
1805 			return;
1806 	if (zv != NULL) {
1807 		old_volmode = zv->zv_volmode;
1808 		mutex_exit(&zv->zv_state_lock);
1809 		if (old_volmode == volmode)
1810 			return;
1811 		zvol_wait_close(zv);
1812 	}
1813 	cookie = spl_fstrans_mark();
1814 	switch (volmode) {
1815 		case ZFS_VOLMODE_NONE:
1816 			(void) zvol_remove_minor_impl(name);
1817 			break;
1818 		case ZFS_VOLMODE_GEOM:
1819 		case ZFS_VOLMODE_DEV:
1820 			(void) zvol_remove_minor_impl(name);
1821 			(void) zvol_os_create_minor(name);
1822 			break;
1823 		case ZFS_VOLMODE_DEFAULT:
1824 			(void) zvol_remove_minor_impl(name);
1825 			if (zvol_volmode == ZFS_VOLMODE_NONE)
1826 				break;
1827 			else /* if zvol_volmode is invalid defaults to "geom" */
1828 				(void) zvol_os_create_minor(name);
1829 			break;
1830 	}
1831 	spl_fstrans_unmark(cookie);
1832 }
1833 
1834 static zvol_task_t *
1835 zvol_task_alloc(zvol_async_op_t op, const char *name1, const char *name2,
1836     uint64_t value)
1837 {
1838 	zvol_task_t *task;
1839 
1840 	/* Never allow tasks on hidden names. */
1841 	if (name1[0] == '$')
1842 		return (NULL);
1843 
1844 	task = kmem_zalloc(sizeof (zvol_task_t), KM_SLEEP);
1845 	task->op = op;
1846 	task->value = value;
1847 
1848 	strlcpy(task->name1, name1, sizeof (task->name1));
1849 	if (name2 != NULL)
1850 		strlcpy(task->name2, name2, sizeof (task->name2));
1851 
1852 	return (task);
1853 }
1854 
1855 static void
1856 zvol_task_free(zvol_task_t *task)
1857 {
1858 	kmem_free(task, sizeof (zvol_task_t));
1859 }
1860 
1861 /*
1862  * The worker thread function performed asynchronously.
1863  */
1864 static void
1865 zvol_task_cb(void *arg)
1866 {
1867 	zvol_task_t *task = arg;
1868 
1869 	switch (task->op) {
1870 	case ZVOL_ASYNC_REMOVE_MINORS:
1871 		zvol_remove_minors_impl(task->name1);
1872 		break;
1873 	case ZVOL_ASYNC_RENAME_MINORS:
1874 		zvol_rename_minors_impl(task->name1, task->name2);
1875 		break;
1876 	case ZVOL_ASYNC_SET_SNAPDEV:
1877 		zvol_set_snapdev_impl(task->name1, task->value);
1878 		break;
1879 	case ZVOL_ASYNC_SET_VOLMODE:
1880 		zvol_set_volmode_impl(task->name1, task->value);
1881 		break;
1882 	default:
1883 		VERIFY(0);
1884 		break;
1885 	}
1886 
1887 	zvol_task_free(task);
1888 }
1889 
1890 typedef struct zvol_set_prop_int_arg {
1891 	const char *zsda_name;
1892 	uint64_t zsda_value;
1893 	zprop_source_t zsda_source;
1894 	zfs_prop_t zsda_prop;
1895 } zvol_set_prop_int_arg_t;
1896 
1897 /*
1898  * Sanity check the dataset for safe use by the sync task.  No additional
1899  * conditions are imposed.
1900  */
1901 static int
1902 zvol_set_common_check(void *arg, dmu_tx_t *tx)
1903 {
1904 	zvol_set_prop_int_arg_t *zsda = arg;
1905 	dsl_pool_t *dp = dmu_tx_pool(tx);
1906 	dsl_dir_t *dd;
1907 	int error;
1908 
1909 	error = dsl_dir_hold(dp, zsda->zsda_name, FTAG, &dd, NULL);
1910 	if (error != 0)
1911 		return (error);
1912 
1913 	dsl_dir_rele(dd, FTAG);
1914 
1915 	return (error);
1916 }
1917 
1918 static int
1919 zvol_set_common_sync_cb(dsl_pool_t *dp, dsl_dataset_t *ds, void *arg)
1920 {
1921 	zvol_set_prop_int_arg_t *zsda = arg;
1922 	char dsname[ZFS_MAX_DATASET_NAME_LEN];
1923 	zvol_task_t *task;
1924 	uint64_t prop;
1925 
1926 	const char *prop_name = zfs_prop_to_name(zsda->zsda_prop);
1927 	dsl_dataset_name(ds, dsname);
1928 
1929 	if (dsl_prop_get_int_ds(ds, prop_name, &prop) != 0)
1930 		return (0);
1931 
1932 	switch (zsda->zsda_prop) {
1933 		case ZFS_PROP_VOLMODE:
1934 			task = zvol_task_alloc(ZVOL_ASYNC_SET_VOLMODE, dsname,
1935 			    NULL, prop);
1936 			break;
1937 		case ZFS_PROP_SNAPDEV:
1938 			task = zvol_task_alloc(ZVOL_ASYNC_SET_SNAPDEV, dsname,
1939 			    NULL, prop);
1940 			break;
1941 		default:
1942 			task = NULL;
1943 			break;
1944 	}
1945 
1946 	if (task == NULL)
1947 		return (0);
1948 
1949 	(void) taskq_dispatch(dp->dp_spa->spa_zvol_taskq, zvol_task_cb,
1950 	    task, TQ_SLEEP);
1951 	return (0);
1952 }
1953 
1954 /*
1955  * Traverse all child datasets and apply the property appropriately.
1956  * We call dsl_prop_set_sync_impl() here to set the value only on the toplevel
1957  * dataset and read the effective "property" on every child in the callback
1958  * function: this is because the value is not guaranteed to be the same in the
1959  * whole dataset hierarchy.
1960  */
1961 static void
1962 zvol_set_common_sync(void *arg, dmu_tx_t *tx)
1963 {
1964 	zvol_set_prop_int_arg_t *zsda = arg;
1965 	dsl_pool_t *dp = dmu_tx_pool(tx);
1966 	dsl_dir_t *dd;
1967 	dsl_dataset_t *ds;
1968 	int error;
1969 
1970 	VERIFY0(dsl_dir_hold(dp, zsda->zsda_name, FTAG, &dd, NULL));
1971 
1972 	error = dsl_dataset_hold(dp, zsda->zsda_name, FTAG, &ds);
1973 	if (error == 0) {
1974 		dsl_prop_set_sync_impl(ds, zfs_prop_to_name(zsda->zsda_prop),
1975 		    zsda->zsda_source, sizeof (zsda->zsda_value), 1,
1976 		    &zsda->zsda_value, tx);
1977 		dsl_dataset_rele(ds, FTAG);
1978 	}
1979 
1980 	dmu_objset_find_dp(dp, dd->dd_object, zvol_set_common_sync_cb,
1981 	    zsda, DS_FIND_CHILDREN);
1982 
1983 	dsl_dir_rele(dd, FTAG);
1984 }
1985 
1986 int
1987 zvol_set_common(const char *ddname, zfs_prop_t prop, zprop_source_t source,
1988     uint64_t val)
1989 {
1990 	zvol_set_prop_int_arg_t zsda;
1991 
1992 	zsda.zsda_name = ddname;
1993 	zsda.zsda_source = source;
1994 	zsda.zsda_value = val;
1995 	zsda.zsda_prop = prop;
1996 
1997 	return (dsl_sync_task(ddname, zvol_set_common_check,
1998 	    zvol_set_common_sync, &zsda, 0, ZFS_SPACE_CHECK_NONE));
1999 }
2000 
2001 void
2002 zvol_remove_minors(spa_t *spa, const char *name, boolean_t async)
2003 {
2004 	zvol_task_t *task;
2005 	taskqid_t id;
2006 
2007 	task = zvol_task_alloc(ZVOL_ASYNC_REMOVE_MINORS, name, NULL, ~0ULL);
2008 	if (task == NULL)
2009 		return;
2010 
2011 	id = taskq_dispatch(spa->spa_zvol_taskq, zvol_task_cb, task, TQ_SLEEP);
2012 	if ((async == B_FALSE) && (id != TASKQID_INVALID))
2013 		taskq_wait_id(spa->spa_zvol_taskq, id);
2014 }
2015 
2016 void
2017 zvol_rename_minors(spa_t *spa, const char *name1, const char *name2,
2018     boolean_t async)
2019 {
2020 	zvol_task_t *task;
2021 	taskqid_t id;
2022 
2023 	task = zvol_task_alloc(ZVOL_ASYNC_RENAME_MINORS, name1, name2, ~0ULL);
2024 	if (task == NULL)
2025 		return;
2026 
2027 	id = taskq_dispatch(spa->spa_zvol_taskq, zvol_task_cb, task, TQ_SLEEP);
2028 	if ((async == B_FALSE) && (id != TASKQID_INVALID))
2029 		taskq_wait_id(spa->spa_zvol_taskq, id);
2030 }
2031 
2032 boolean_t
2033 zvol_is_zvol(const char *name)
2034 {
2035 
2036 	return (zvol_os_is_zvol(name));
2037 }
2038 
2039 int
2040 zvol_init_impl(void)
2041 {
2042 	int i;
2043 
2044 	/*
2045 	 * zvol_threads is the module param the user passes in.
2046 	 *
2047 	 * zvol_actual_threads is what we use internally, since the user can
2048 	 * pass zvol_thread = 0 to mean "use all the CPUs" (the default).
2049 	 */
2050 	static unsigned int zvol_actual_threads;
2051 
2052 	if (zvol_threads == 0) {
2053 		/*
2054 		 * See dde9380a1 for why 32 was chosen here.  This should
2055 		 * probably be refined to be some multiple of the number
2056 		 * of CPUs.
2057 		 */
2058 		zvol_actual_threads = MAX(max_ncpus, 32);
2059 	} else {
2060 		zvol_actual_threads = MIN(MAX(zvol_threads, 1), 1024);
2061 	}
2062 
2063 	/*
2064 	 * Use at least 32 zvol_threads but for many core system,
2065 	 * prefer 6 threads per taskq, but no more taskqs
2066 	 * than threads in them on large systems.
2067 	 *
2068 	 *                 taskq   total
2069 	 * cpus    taskqs  threads threads
2070 	 * ------- ------- ------- -------
2071 	 * 1       1       32       32
2072 	 * 2       1       32       32
2073 	 * 4       1       32       32
2074 	 * 8       2       16       32
2075 	 * 16      3       11       33
2076 	 * 32      5       7        35
2077 	 * 64      8       8        64
2078 	 * 128     11      12       132
2079 	 * 256     16      16       256
2080 	 */
2081 	zv_taskq_t *ztqs = &zvol_taskqs;
2082 	int num_tqs = MIN(max_ncpus, zvol_num_taskqs);
2083 	if (num_tqs == 0) {
2084 		num_tqs = 1 + max_ncpus / 6;
2085 		while (num_tqs * num_tqs > zvol_actual_threads)
2086 			num_tqs--;
2087 	}
2088 
2089 	int per_tq_thread = zvol_actual_threads / num_tqs;
2090 	if (per_tq_thread * num_tqs < zvol_actual_threads)
2091 		per_tq_thread++;
2092 
2093 	ztqs->tqs_cnt = num_tqs;
2094 	ztqs->tqs_taskq = kmem_alloc(num_tqs * sizeof (taskq_t *), KM_SLEEP);
2095 
2096 	for (uint_t i = 0; i < num_tqs; i++) {
2097 		char name[32];
2098 		(void) snprintf(name, sizeof (name), "%s_tq-%u",
2099 		    ZVOL_DRIVER, i);
2100 		ztqs->tqs_taskq[i] = taskq_create(name, per_tq_thread,
2101 		    maxclsyspri, per_tq_thread, INT_MAX,
2102 		    TASKQ_PREPOPULATE | TASKQ_DYNAMIC);
2103 		if (ztqs->tqs_taskq[i] == NULL) {
2104 			for (int j = i - 1; j >= 0; j--)
2105 				taskq_destroy(ztqs->tqs_taskq[j]);
2106 			kmem_free(ztqs->tqs_taskq, ztqs->tqs_cnt *
2107 			    sizeof (taskq_t *));
2108 			ztqs->tqs_taskq = NULL;
2109 			return (SET_ERROR(ENOMEM));
2110 		}
2111 	}
2112 
2113 	list_create(&zvol_state_list, sizeof (zvol_state_t),
2114 	    offsetof(zvol_state_t, zv_next));
2115 	rw_init(&zvol_state_lock, NULL, RW_DEFAULT, NULL);
2116 
2117 	zvol_htable = kmem_alloc(ZVOL_HT_SIZE * sizeof (struct hlist_head),
2118 	    KM_SLEEP);
2119 	for (i = 0; i < ZVOL_HT_SIZE; i++)
2120 		INIT_HLIST_HEAD(&zvol_htable[i]);
2121 
2122 	return (0);
2123 }
2124 
2125 void
2126 zvol_fini_impl(void)
2127 {
2128 	zv_taskq_t *ztqs = &zvol_taskqs;
2129 
2130 	zvol_remove_minors_impl(NULL);
2131 
2132 	/*
2133 	 * The call to "zvol_remove_minors_impl" may dispatch entries to
2134 	 * the system_taskq, but it doesn't wait for those entries to
2135 	 * complete before it returns. Thus, we must wait for all of the
2136 	 * removals to finish, before we can continue.
2137 	 */
2138 	taskq_wait_outstanding(system_taskq, 0);
2139 
2140 	kmem_free(zvol_htable, ZVOL_HT_SIZE * sizeof (struct hlist_head));
2141 	list_destroy(&zvol_state_list);
2142 	rw_destroy(&zvol_state_lock);
2143 
2144 	if (ztqs->tqs_taskq == NULL) {
2145 		ASSERT3U(ztqs->tqs_cnt, ==, 0);
2146 	} else {
2147 		for (uint_t i = 0; i < ztqs->tqs_cnt; i++) {
2148 			ASSERT3P(ztqs->tqs_taskq[i], !=, NULL);
2149 			taskq_destroy(ztqs->tqs_taskq[i]);
2150 		}
2151 		kmem_free(ztqs->tqs_taskq, ztqs->tqs_cnt *
2152 		    sizeof (taskq_t *));
2153 		ztqs->tqs_taskq = NULL;
2154 	}
2155 }
2156 
2157 ZFS_MODULE_PARAM(zfs_vol, zvol_, inhibit_dev, UINT, ZMOD_RW,
2158 	"Do not create zvol device nodes");
2159 ZFS_MODULE_PARAM(zfs_vol, zvol_, threads, UINT, ZMOD_RW,
2160 	"Number of threads for I/O requests. Set to 0 to use all active CPUs");
2161 ZFS_MODULE_PARAM(zfs_vol, zvol_, num_taskqs, UINT, ZMOD_RW,
2162 	"Number of zvol taskqs");
2163 ZFS_MODULE_PARAM(zfs_vol, zvol_, request_sync, UINT, ZMOD_RW,
2164 	"Synchronously handle bio requests");
2165