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