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