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