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