xref: /illumos-gate/usr/src/uts/common/fs/zfs/zvol.c (revision 1a7b528f36ec61147fc237b7b9a23642fab7ad13)
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 2007 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 #pragma ident	"%Z%%M%	%I%	%E% SMI"
27 
28 /*
29  * ZFS volume emulation driver.
30  *
31  * Makes a DMU object look like a volume of arbitrary size, up to 2^64 bytes.
32  * Volumes are accessed through the symbolic links named:
33  *
34  * /dev/zvol/dsk/<pool_name>/<dataset_name>
35  * /dev/zvol/rdsk/<pool_name>/<dataset_name>
36  *
37  * These links are created by the ZFS-specific devfsadm link generator.
38  * Volumes are persistent through reboot.  No user command needs to be
39  * run before opening and using a device.
40  */
41 
42 #include <sys/types.h>
43 #include <sys/param.h>
44 #include <sys/errno.h>
45 #include <sys/uio.h>
46 #include <sys/buf.h>
47 #include <sys/modctl.h>
48 #include <sys/open.h>
49 #include <sys/kmem.h>
50 #include <sys/conf.h>
51 #include <sys/cmn_err.h>
52 #include <sys/stat.h>
53 #include <sys/zap.h>
54 #include <sys/spa.h>
55 #include <sys/zio.h>
56 #include <sys/dsl_prop.h>
57 #include <sys/dkio.h>
58 #include <sys/efi_partition.h>
59 #include <sys/byteorder.h>
60 #include <sys/pathname.h>
61 #include <sys/ddi.h>
62 #include <sys/sunddi.h>
63 #include <sys/crc32.h>
64 #include <sys/dirent.h>
65 #include <sys/policy.h>
66 #include <sys/fs/zfs.h>
67 #include <sys/zfs_ioctl.h>
68 #include <sys/mkdev.h>
69 #include <sys/zil.h>
70 #include <sys/refcount.h>
71 #include <sys/zfs_znode.h>
72 #include <sys/zfs_rlock.h>
73 
74 #include "zfs_namecheck.h"
75 
76 #define	ZVOL_OBJ		1ULL
77 #define	ZVOL_ZAP_OBJ		2ULL
78 
79 static void *zvol_state;
80 
81 /*
82  * This lock protects the zvol_state structure from being modified
83  * while it's being used, e.g. an open that comes in before a create
84  * finishes.  It also protects temporary opens of the dataset so that,
85  * e.g., an open doesn't get a spurious EBUSY.
86  */
87 static kmutex_t zvol_state_lock;
88 static uint32_t zvol_minors;
89 
90 /*
91  * The in-core state of each volume.
92  */
93 typedef struct zvol_state {
94 	char		zv_name[MAXPATHLEN]; /* pool/dd name */
95 	uint64_t	zv_volsize;	/* amount of space we advertise */
96 	uint64_t	zv_volblocksize; /* volume block size */
97 	minor_t		zv_minor;	/* minor number */
98 	uint8_t		zv_min_bs;	/* minimum addressable block shift */
99 	uint8_t		zv_readonly;	/* hard readonly; like write-protect */
100 	objset_t	*zv_objset;	/* objset handle */
101 	uint32_t	zv_mode;	/* DS_MODE_* flags at open time */
102 	uint32_t	zv_open_count[OTYPCNT];	/* open counts */
103 	uint32_t	zv_total_opens;	/* total open count */
104 	zilog_t		*zv_zilog;	/* ZIL handle */
105 	uint64_t	zv_txg_assign;	/* txg to assign during ZIL replay */
106 	znode_t		zv_znode;	/* for range locking */
107 } zvol_state_t;
108 
109 /*
110  * zvol maximum transfer in one DMU tx.
111  */
112 int zvol_maxphys = DMU_MAX_ACCESS/2;
113 
114 static int zvol_get_data(void *arg, lr_write_t *lr, char *buf, zio_t *zio);
115 
116 static void
117 zvol_size_changed(zvol_state_t *zv, major_t maj)
118 {
119 	dev_t dev = makedevice(maj, zv->zv_minor);
120 
121 	VERIFY(ddi_prop_update_int64(dev, zfs_dip,
122 	    "Size", zv->zv_volsize) == DDI_SUCCESS);
123 	VERIFY(ddi_prop_update_int64(dev, zfs_dip,
124 	    "Nblocks", lbtodb(zv->zv_volsize)) == DDI_SUCCESS);
125 }
126 
127 int
128 zvol_check_volsize(uint64_t volsize, uint64_t blocksize)
129 {
130 	if (volsize == 0)
131 		return (EINVAL);
132 
133 	if (volsize % blocksize != 0)
134 		return (EINVAL);
135 
136 #ifdef _ILP32
137 	if (volsize - 1 > SPEC_MAXOFFSET_T)
138 		return (EOVERFLOW);
139 #endif
140 	return (0);
141 }
142 
143 int
144 zvol_check_volblocksize(uint64_t volblocksize)
145 {
146 	if (volblocksize < SPA_MINBLOCKSIZE ||
147 	    volblocksize > SPA_MAXBLOCKSIZE ||
148 	    !ISP2(volblocksize))
149 		return (EDOM);
150 
151 	return (0);
152 }
153 
154 static void
155 zvol_readonly_changed_cb(void *arg, uint64_t newval)
156 {
157 	zvol_state_t *zv = arg;
158 
159 	zv->zv_readonly = (uint8_t)newval;
160 }
161 
162 int
163 zvol_get_stats(objset_t *os, nvlist_t *nv)
164 {
165 	int error;
166 	dmu_object_info_t doi;
167 	uint64_t val;
168 
169 
170 	error = zap_lookup(os, ZVOL_ZAP_OBJ, "size", 8, 1, &val);
171 	if (error)
172 		return (error);
173 
174 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_VOLSIZE, val);
175 
176 	error = dmu_object_info(os, ZVOL_OBJ, &doi);
177 
178 	if (error == 0) {
179 		dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_VOLBLOCKSIZE,
180 		    doi.doi_data_block_size);
181 	}
182 
183 	return (error);
184 }
185 
186 /*
187  * Find a free minor number.
188  */
189 static minor_t
190 zvol_minor_alloc(void)
191 {
192 	minor_t minor;
193 
194 	ASSERT(MUTEX_HELD(&zvol_state_lock));
195 
196 	for (minor = 1; minor <= ZVOL_MAX_MINOR; minor++)
197 		if (ddi_get_soft_state(zvol_state, minor) == NULL)
198 			return (minor);
199 
200 	return (0);
201 }
202 
203 static zvol_state_t *
204 zvol_minor_lookup(const char *name)
205 {
206 	minor_t minor;
207 	zvol_state_t *zv;
208 
209 	ASSERT(MUTEX_HELD(&zvol_state_lock));
210 
211 	for (minor = 1; minor <= ZVOL_MAX_MINOR; minor++) {
212 		zv = ddi_get_soft_state(zvol_state, minor);
213 		if (zv == NULL)
214 			continue;
215 		if (strcmp(zv->zv_name, name) == 0)
216 			break;
217 	}
218 
219 	return (zv);
220 }
221 
222 /* ARGSUSED */
223 void
224 zvol_create_cb(objset_t *os, void *arg, cred_t *cr, dmu_tx_t *tx)
225 {
226 	nvlist_t *nvprops = arg;
227 	int error;
228 	uint64_t volblocksize, volsize;
229 
230 	VERIFY(nvlist_lookup_uint64(nvprops,
231 	    zfs_prop_to_name(ZFS_PROP_VOLSIZE), &volsize) == 0);
232 	if (nvlist_lookup_uint64(nvprops,
233 	    zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE), &volblocksize) != 0)
234 		volblocksize = zfs_prop_default_numeric(ZFS_PROP_VOLBLOCKSIZE);
235 
236 	/*
237 	 * These properites must be removed from the list so the generic
238 	 * property setting step won't apply to them.
239 	 */
240 	VERIFY(nvlist_remove_all(nvprops,
241 	    zfs_prop_to_name(ZFS_PROP_VOLSIZE)) == 0);
242 	(void) nvlist_remove_all(nvprops,
243 	    zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE));
244 
245 	error = dmu_object_claim(os, ZVOL_OBJ, DMU_OT_ZVOL, volblocksize,
246 	    DMU_OT_NONE, 0, tx);
247 	ASSERT(error == 0);
248 
249 	error = zap_create_claim(os, ZVOL_ZAP_OBJ, DMU_OT_ZVOL_PROP,
250 	    DMU_OT_NONE, 0, tx);
251 	ASSERT(error == 0);
252 
253 	error = zap_update(os, ZVOL_ZAP_OBJ, "size", 8, 1, &volsize, tx);
254 	ASSERT(error == 0);
255 }
256 
257 /*
258  * Replay a TX_WRITE ZIL transaction that didn't get committed
259  * after a system failure
260  */
261 static int
262 zvol_replay_write(zvol_state_t *zv, lr_write_t *lr, boolean_t byteswap)
263 {
264 	objset_t *os = zv->zv_objset;
265 	char *data = (char *)(lr + 1);	/* data follows lr_write_t */
266 	uint64_t off = lr->lr_offset;
267 	uint64_t len = lr->lr_length;
268 	dmu_tx_t *tx;
269 	int error;
270 
271 	if (byteswap)
272 		byteswap_uint64_array(lr, sizeof (*lr));
273 
274 	tx = dmu_tx_create(os);
275 	dmu_tx_hold_write(tx, ZVOL_OBJ, off, len);
276 	error = dmu_tx_assign(tx, zv->zv_txg_assign);
277 	if (error) {
278 		dmu_tx_abort(tx);
279 	} else {
280 		dmu_write(os, ZVOL_OBJ, off, len, data, tx);
281 		dmu_tx_commit(tx);
282 	}
283 
284 	return (error);
285 }
286 
287 /* ARGSUSED */
288 static int
289 zvol_replay_err(zvol_state_t *zv, lr_t *lr, boolean_t byteswap)
290 {
291 	return (ENOTSUP);
292 }
293 
294 /*
295  * Callback vectors for replaying records.
296  * Only TX_WRITE is needed for zvol.
297  */
298 zil_replay_func_t *zvol_replay_vector[TX_MAX_TYPE] = {
299 	zvol_replay_err,	/* 0 no such transaction type */
300 	zvol_replay_err,	/* TX_CREATE */
301 	zvol_replay_err,	/* TX_MKDIR */
302 	zvol_replay_err,	/* TX_MKXATTR */
303 	zvol_replay_err,	/* TX_SYMLINK */
304 	zvol_replay_err,	/* TX_REMOVE */
305 	zvol_replay_err,	/* TX_RMDIR */
306 	zvol_replay_err,	/* TX_LINK */
307 	zvol_replay_err,	/* TX_RENAME */
308 	zvol_replay_write,	/* TX_WRITE */
309 	zvol_replay_err,	/* TX_TRUNCATE */
310 	zvol_replay_err,	/* TX_SETATTR */
311 	zvol_replay_err,	/* TX_ACL */
312 };
313 
314 /*
315  * Create a minor node for the specified volume.
316  */
317 int
318 zvol_create_minor(const char *name, major_t maj)
319 {
320 	zvol_state_t *zv;
321 	objset_t *os;
322 	dmu_object_info_t doi;
323 	uint64_t volsize;
324 	minor_t minor = 0;
325 	struct pathname linkpath;
326 	int ds_mode = DS_MODE_PRIMARY;
327 	vnode_t *vp = NULL;
328 	char *devpath;
329 	size_t devpathlen = strlen(ZVOL_FULL_DEV_DIR) + 1 + strlen(name) + 1;
330 	char chrbuf[30], blkbuf[30];
331 	int error;
332 
333 	mutex_enter(&zvol_state_lock);
334 
335 	if ((zv = zvol_minor_lookup(name)) != NULL) {
336 		mutex_exit(&zvol_state_lock);
337 		return (EEXIST);
338 	}
339 
340 	if (strchr(name, '@') != 0)
341 		ds_mode |= DS_MODE_READONLY;
342 
343 	error = dmu_objset_open(name, DMU_OST_ZVOL, ds_mode, &os);
344 
345 	if (error) {
346 		mutex_exit(&zvol_state_lock);
347 		return (error);
348 	}
349 
350 	error = zap_lookup(os, ZVOL_ZAP_OBJ, "size", 8, 1, &volsize);
351 
352 	if (error) {
353 		dmu_objset_close(os);
354 		mutex_exit(&zvol_state_lock);
355 		return (error);
356 	}
357 
358 	/*
359 	 * If there's an existing /dev/zvol symlink, try to use the
360 	 * same minor number we used last time.
361 	 */
362 	devpath = kmem_alloc(devpathlen, KM_SLEEP);
363 
364 	(void) sprintf(devpath, "%s/%s", ZVOL_FULL_DEV_DIR, name);
365 
366 	error = lookupname(devpath, UIO_SYSSPACE, NO_FOLLOW, NULL, &vp);
367 
368 	kmem_free(devpath, devpathlen);
369 
370 	if (error == 0 && vp->v_type != VLNK)
371 		error = EINVAL;
372 
373 	if (error == 0) {
374 		pn_alloc(&linkpath);
375 		error = pn_getsymlink(vp, &linkpath, kcred);
376 		if (error == 0) {
377 			char *ms = strstr(linkpath.pn_path, ZVOL_PSEUDO_DEV);
378 			if (ms != NULL) {
379 				ms += strlen(ZVOL_PSEUDO_DEV);
380 				minor = stoi(&ms);
381 			}
382 		}
383 		pn_free(&linkpath);
384 	}
385 
386 	if (vp != NULL)
387 		VN_RELE(vp);
388 
389 	/*
390 	 * If we found a minor but it's already in use, we must pick a new one.
391 	 */
392 	if (minor != 0 && ddi_get_soft_state(zvol_state, minor) != NULL)
393 		minor = 0;
394 
395 	if (minor == 0)
396 		minor = zvol_minor_alloc();
397 
398 	if (minor == 0) {
399 		dmu_objset_close(os);
400 		mutex_exit(&zvol_state_lock);
401 		return (ENXIO);
402 	}
403 
404 	if (ddi_soft_state_zalloc(zvol_state, minor) != DDI_SUCCESS) {
405 		dmu_objset_close(os);
406 		mutex_exit(&zvol_state_lock);
407 		return (EAGAIN);
408 	}
409 
410 	(void) ddi_prop_update_string(minor, zfs_dip, ZVOL_PROP_NAME,
411 	    (char *)name);
412 
413 	(void) sprintf(chrbuf, "%uc,raw", minor);
414 
415 	if (ddi_create_minor_node(zfs_dip, chrbuf, S_IFCHR,
416 	    minor, DDI_PSEUDO, 0) == DDI_FAILURE) {
417 		ddi_soft_state_free(zvol_state, minor);
418 		dmu_objset_close(os);
419 		mutex_exit(&zvol_state_lock);
420 		return (EAGAIN);
421 	}
422 
423 	(void) sprintf(blkbuf, "%uc", minor);
424 
425 	if (ddi_create_minor_node(zfs_dip, blkbuf, S_IFBLK,
426 	    minor, DDI_PSEUDO, 0) == DDI_FAILURE) {
427 		ddi_remove_minor_node(zfs_dip, chrbuf);
428 		ddi_soft_state_free(zvol_state, minor);
429 		dmu_objset_close(os);
430 		mutex_exit(&zvol_state_lock);
431 		return (EAGAIN);
432 	}
433 
434 	zv = ddi_get_soft_state(zvol_state, minor);
435 
436 	(void) strcpy(zv->zv_name, name);
437 	zv->zv_min_bs = DEV_BSHIFT;
438 	zv->zv_minor = minor;
439 	zv->zv_volsize = volsize;
440 	zv->zv_objset = os;
441 	zv->zv_mode = ds_mode;
442 	zv->zv_zilog = zil_open(os, zvol_get_data);
443 	mutex_init(&zv->zv_znode.z_range_lock, NULL, MUTEX_DEFAULT, NULL);
444 	avl_create(&zv->zv_znode.z_range_avl, zfs_range_compare,
445 	    sizeof (rl_t), offsetof(rl_t, r_node));
446 
447 
448 	/* get and cache the blocksize */
449 	error = dmu_object_info(os, ZVOL_OBJ, &doi);
450 	ASSERT(error == 0);
451 	zv->zv_volblocksize = doi.doi_data_block_size;
452 
453 	zil_replay(os, zv, &zv->zv_txg_assign, zvol_replay_vector);
454 
455 	zvol_size_changed(zv, maj);
456 
457 	/* XXX this should handle the possible i/o error */
458 	VERIFY(dsl_prop_register(dmu_objset_ds(zv->zv_objset),
459 	    "readonly", zvol_readonly_changed_cb, zv) == 0);
460 
461 	zvol_minors++;
462 
463 	mutex_exit(&zvol_state_lock);
464 
465 	return (0);
466 }
467 
468 /*
469  * Remove minor node for the specified volume.
470  */
471 int
472 zvol_remove_minor(const char *name)
473 {
474 	zvol_state_t *zv;
475 	char namebuf[30];
476 
477 	mutex_enter(&zvol_state_lock);
478 
479 	if ((zv = zvol_minor_lookup(name)) == NULL) {
480 		mutex_exit(&zvol_state_lock);
481 		return (ENXIO);
482 	}
483 
484 	if (zv->zv_total_opens != 0) {
485 		mutex_exit(&zvol_state_lock);
486 		return (EBUSY);
487 	}
488 
489 	(void) sprintf(namebuf, "%uc,raw", zv->zv_minor);
490 	ddi_remove_minor_node(zfs_dip, namebuf);
491 
492 	(void) sprintf(namebuf, "%uc", zv->zv_minor);
493 	ddi_remove_minor_node(zfs_dip, namebuf);
494 
495 	VERIFY(dsl_prop_unregister(dmu_objset_ds(zv->zv_objset),
496 	    "readonly", zvol_readonly_changed_cb, zv) == 0);
497 
498 	zil_close(zv->zv_zilog);
499 	zv->zv_zilog = NULL;
500 	dmu_objset_close(zv->zv_objset);
501 	zv->zv_objset = NULL;
502 	avl_destroy(&zv->zv_znode.z_range_avl);
503 	mutex_destroy(&zv->zv_znode.z_range_lock);
504 
505 	ddi_soft_state_free(zvol_state, zv->zv_minor);
506 
507 	zvol_minors--;
508 
509 	mutex_exit(&zvol_state_lock);
510 
511 	return (0);
512 }
513 
514 int
515 zvol_set_volsize(const char *name, major_t maj, uint64_t volsize)
516 {
517 	zvol_state_t *zv;
518 	dmu_tx_t *tx;
519 	int error;
520 	dmu_object_info_t doi;
521 
522 	mutex_enter(&zvol_state_lock);
523 
524 	if ((zv = zvol_minor_lookup(name)) == NULL) {
525 		mutex_exit(&zvol_state_lock);
526 		return (ENXIO);
527 	}
528 
529 	if ((error = dmu_object_info(zv->zv_objset, ZVOL_OBJ, &doi)) != 0 ||
530 	    (error = zvol_check_volsize(volsize,
531 	    doi.doi_data_block_size)) != 0) {
532 		mutex_exit(&zvol_state_lock);
533 		return (error);
534 	}
535 
536 	if (zv->zv_readonly || (zv->zv_mode & DS_MODE_READONLY)) {
537 		mutex_exit(&zvol_state_lock);
538 		return (EROFS);
539 	}
540 
541 	tx = dmu_tx_create(zv->zv_objset);
542 	dmu_tx_hold_zap(tx, ZVOL_ZAP_OBJ, TRUE, NULL);
543 	dmu_tx_hold_free(tx, ZVOL_OBJ, volsize, DMU_OBJECT_END);
544 	error = dmu_tx_assign(tx, TXG_WAIT);
545 	if (error) {
546 		dmu_tx_abort(tx);
547 		mutex_exit(&zvol_state_lock);
548 		return (error);
549 	}
550 
551 	error = zap_update(zv->zv_objset, ZVOL_ZAP_OBJ, "size", 8, 1,
552 	    &volsize, tx);
553 	if (error == 0) {
554 		error = dmu_free_range(zv->zv_objset, ZVOL_OBJ, volsize,
555 		    DMU_OBJECT_END, tx);
556 	}
557 
558 	dmu_tx_commit(tx);
559 
560 	if (error == 0) {
561 		zv->zv_volsize = volsize;
562 		zvol_size_changed(zv, maj);
563 	}
564 
565 	mutex_exit(&zvol_state_lock);
566 
567 	return (error);
568 }
569 
570 int
571 zvol_set_volblocksize(const char *name, uint64_t volblocksize)
572 {
573 	zvol_state_t *zv;
574 	dmu_tx_t *tx;
575 	int error;
576 
577 	mutex_enter(&zvol_state_lock);
578 
579 	if ((zv = zvol_minor_lookup(name)) == NULL) {
580 		mutex_exit(&zvol_state_lock);
581 		return (ENXIO);
582 	}
583 
584 	if (zv->zv_readonly || (zv->zv_mode & DS_MODE_READONLY)) {
585 		mutex_exit(&zvol_state_lock);
586 		return (EROFS);
587 	}
588 
589 	tx = dmu_tx_create(zv->zv_objset);
590 	dmu_tx_hold_bonus(tx, ZVOL_OBJ);
591 	error = dmu_tx_assign(tx, TXG_WAIT);
592 	if (error) {
593 		dmu_tx_abort(tx);
594 	} else {
595 		error = dmu_object_set_blocksize(zv->zv_objset, ZVOL_OBJ,
596 		    volblocksize, 0, tx);
597 		if (error == ENOTSUP)
598 			error = EBUSY;
599 		dmu_tx_commit(tx);
600 	}
601 
602 	mutex_exit(&zvol_state_lock);
603 
604 	return (error);
605 }
606 
607 /*ARGSUSED*/
608 int
609 zvol_open(dev_t *devp, int flag, int otyp, cred_t *cr)
610 {
611 	minor_t minor = getminor(*devp);
612 	zvol_state_t *zv;
613 
614 	if (minor == 0)			/* This is the control device */
615 		return (0);
616 
617 	mutex_enter(&zvol_state_lock);
618 
619 	zv = ddi_get_soft_state(zvol_state, minor);
620 	if (zv == NULL) {
621 		mutex_exit(&zvol_state_lock);
622 		return (ENXIO);
623 	}
624 
625 	ASSERT(zv->zv_objset != NULL);
626 
627 	if ((flag & FWRITE) &&
628 	    (zv->zv_readonly || (zv->zv_mode & DS_MODE_READONLY))) {
629 		mutex_exit(&zvol_state_lock);
630 		return (EROFS);
631 	}
632 
633 	if (zv->zv_open_count[otyp] == 0 || otyp == OTYP_LYR) {
634 		zv->zv_open_count[otyp]++;
635 		zv->zv_total_opens++;
636 	}
637 
638 	mutex_exit(&zvol_state_lock);
639 
640 	return (0);
641 }
642 
643 /*ARGSUSED*/
644 int
645 zvol_close(dev_t dev, int flag, int otyp, cred_t *cr)
646 {
647 	minor_t minor = getminor(dev);
648 	zvol_state_t *zv;
649 
650 	if (minor == 0)		/* This is the control device */
651 		return (0);
652 
653 	mutex_enter(&zvol_state_lock);
654 
655 	zv = ddi_get_soft_state(zvol_state, minor);
656 	if (zv == NULL) {
657 		mutex_exit(&zvol_state_lock);
658 		return (ENXIO);
659 	}
660 
661 	/*
662 	 * The next statement is a workaround for the following DDI bug:
663 	 * 6343604 specfs race: multiple "last-close" of the same device
664 	 */
665 	if (zv->zv_total_opens == 0) {
666 		mutex_exit(&zvol_state_lock);
667 		return (0);
668 	}
669 
670 	/*
671 	 * If the open count is zero, this is a spurious close.
672 	 * That indicates a bug in the kernel / DDI framework.
673 	 */
674 	ASSERT(zv->zv_open_count[otyp] != 0);
675 	ASSERT(zv->zv_total_opens != 0);
676 
677 	/*
678 	 * You may get multiple opens, but only one close.
679 	 */
680 	zv->zv_open_count[otyp]--;
681 	zv->zv_total_opens--;
682 
683 	mutex_exit(&zvol_state_lock);
684 
685 	return (0);
686 }
687 
688 static void
689 zvol_get_done(dmu_buf_t *db, void *vzgd)
690 {
691 	zgd_t *zgd = (zgd_t *)vzgd;
692 	rl_t *rl = zgd->zgd_rl;
693 
694 	dmu_buf_rele(db, vzgd);
695 	zfs_range_unlock(rl);
696 	zil_add_vdev(zgd->zgd_zilog, DVA_GET_VDEV(BP_IDENTITY(zgd->zgd_bp)));
697 	kmem_free(zgd, sizeof (zgd_t));
698 }
699 
700 /*
701  * Get data to generate a TX_WRITE intent log record.
702  */
703 static int
704 zvol_get_data(void *arg, lr_write_t *lr, char *buf, zio_t *zio)
705 {
706 	zvol_state_t *zv = arg;
707 	objset_t *os = zv->zv_objset;
708 	dmu_buf_t *db;
709 	rl_t *rl;
710 	zgd_t *zgd;
711 	uint64_t boff; 			/* block starting offset */
712 	int dlen = lr->lr_length;	/* length of user data */
713 	int error;
714 
715 	ASSERT(zio);
716 	ASSERT(dlen != 0);
717 
718 	/*
719 	 * Write records come in two flavors: immediate and indirect.
720 	 * For small writes it's cheaper to store the data with the
721 	 * log record (immediate); for large writes it's cheaper to
722 	 * sync the data and get a pointer to it (indirect) so that
723 	 * we don't have to write the data twice.
724 	 */
725 	if (buf != NULL) /* immediate write */
726 		return (dmu_read(os, ZVOL_OBJ, lr->lr_offset, dlen, buf));
727 
728 	zgd = (zgd_t *)kmem_alloc(sizeof (zgd_t), KM_SLEEP);
729 	zgd->zgd_zilog = zv->zv_zilog;
730 	zgd->zgd_bp = &lr->lr_blkptr;
731 
732 	/*
733 	 * Lock the range of the block to ensure that when the data is
734 	 * written out and it's checksum is being calculated that no other
735 	 * thread can change the block.
736 	 */
737 	boff = P2ALIGN_TYPED(lr->lr_offset, zv->zv_volblocksize, uint64_t);
738 	rl = zfs_range_lock(&zv->zv_znode, boff, zv->zv_volblocksize,
739 	    RL_READER);
740 	zgd->zgd_rl = rl;
741 
742 	VERIFY(0 == dmu_buf_hold(os, ZVOL_OBJ, lr->lr_offset, zgd, &db));
743 	error = dmu_sync(zio, db, &lr->lr_blkptr,
744 	    lr->lr_common.lrc_txg, zvol_get_done, zgd);
745 	if (error == 0)
746 		zil_add_vdev(zv->zv_zilog,
747 		    DVA_GET_VDEV(BP_IDENTITY(&lr->lr_blkptr)));
748 	/*
749 	 * If we get EINPROGRESS, then we need to wait for a
750 	 * write IO initiated by dmu_sync() to complete before
751 	 * we can release this dbuf.  We will finish everything
752 	 * up in the zvol_get_done() callback.
753 	 */
754 	if (error == EINPROGRESS)
755 		return (0);
756 	dmu_buf_rele(db, zgd);
757 	zfs_range_unlock(rl);
758 	kmem_free(zgd, sizeof (zgd_t));
759 	return (error);
760 }
761 
762 /*
763  * zvol_log_write() handles synchronous writes using TX_WRITE ZIL transactions.
764  *
765  * We store data in the log buffers if it's small enough.
766  * Otherwise we will later flush the data out via dmu_sync().
767  */
768 ssize_t zvol_immediate_write_sz = 32768;
769 
770 static void
771 zvol_log_write(zvol_state_t *zv, dmu_tx_t *tx, offset_t off, ssize_t len)
772 {
773 	uint32_t blocksize = zv->zv_volblocksize;
774 	lr_write_t *lr;
775 
776 	while (len) {
777 		ssize_t nbytes = MIN(len, blocksize - P2PHASE(off, blocksize));
778 		itx_t *itx = zil_itx_create(TX_WRITE, sizeof (*lr));
779 
780 		itx->itx_wr_state =
781 		    len > zvol_immediate_write_sz ?  WR_INDIRECT : WR_NEED_COPY;
782 		itx->itx_private = zv;
783 		lr = (lr_write_t *)&itx->itx_lr;
784 		lr->lr_foid = ZVOL_OBJ;
785 		lr->lr_offset = off;
786 		lr->lr_length = nbytes;
787 		lr->lr_blkoff = off - P2ALIGN_TYPED(off, blocksize, uint64_t);
788 		BP_ZERO(&lr->lr_blkptr);
789 
790 		(void) zil_itx_assign(zv->zv_zilog, itx, tx);
791 		len -= nbytes;
792 		off += nbytes;
793 	}
794 }
795 
796 int
797 zvol_strategy(buf_t *bp)
798 {
799 	zvol_state_t *zv = ddi_get_soft_state(zvol_state, getminor(bp->b_edev));
800 	uint64_t off, volsize;
801 	size_t size, resid;
802 	char *addr;
803 	objset_t *os;
804 	rl_t *rl;
805 	int error = 0;
806 	boolean_t reading;
807 
808 	if (zv == NULL) {
809 		bioerror(bp, ENXIO);
810 		biodone(bp);
811 		return (0);
812 	}
813 
814 	if (getminor(bp->b_edev) == 0) {
815 		bioerror(bp, EINVAL);
816 		biodone(bp);
817 		return (0);
818 	}
819 
820 	if ((zv->zv_readonly || (zv->zv_mode & DS_MODE_READONLY)) &&
821 	    !(bp->b_flags & B_READ)) {
822 		bioerror(bp, EROFS);
823 		biodone(bp);
824 		return (0);
825 	}
826 
827 	off = ldbtob(bp->b_blkno);
828 	volsize = zv->zv_volsize;
829 
830 	os = zv->zv_objset;
831 	ASSERT(os != NULL);
832 
833 	bp_mapin(bp);
834 	addr = bp->b_un.b_addr;
835 	resid = bp->b_bcount;
836 
837 	/*
838 	 * There must be no buffer changes when doing a dmu_sync() because
839 	 * we can't change the data whilst calculating the checksum.
840 	 */
841 	reading = bp->b_flags & B_READ;
842 	rl = zfs_range_lock(&zv->zv_znode, off, resid,
843 	    reading ? RL_READER : RL_WRITER);
844 
845 	while (resid != 0 && off < volsize) {
846 
847 		size = MIN(resid, zvol_maxphys); /* zvol_maxphys per tx */
848 
849 		if (size > volsize - off)	/* don't write past the end */
850 			size = volsize - off;
851 
852 		if (reading) {
853 			error = dmu_read(os, ZVOL_OBJ, off, size, addr);
854 		} else {
855 			dmu_tx_t *tx = dmu_tx_create(os);
856 			dmu_tx_hold_write(tx, ZVOL_OBJ, off, size);
857 			error = dmu_tx_assign(tx, TXG_WAIT);
858 			if (error) {
859 				dmu_tx_abort(tx);
860 			} else {
861 				dmu_write(os, ZVOL_OBJ, off, size, addr, tx);
862 				zvol_log_write(zv, tx, off, size);
863 				dmu_tx_commit(tx);
864 			}
865 		}
866 		if (error)
867 			break;
868 		off += size;
869 		addr += size;
870 		resid -= size;
871 	}
872 	zfs_range_unlock(rl);
873 
874 	if ((bp->b_resid = resid) == bp->b_bcount)
875 		bioerror(bp, off > volsize ? EINVAL : error);
876 
877 	if (!(bp->b_flags & B_ASYNC) && !reading && !zil_disable)
878 		zil_commit(zv->zv_zilog, UINT64_MAX, ZVOL_OBJ);
879 
880 	biodone(bp);
881 
882 	return (0);
883 }
884 
885 /*
886  * Set the buffer count to the zvol maximum transfer.
887  * Using our own routine instead of the default minphys()
888  * means that for larger writes we write bigger buffers on X86
889  * (128K instead of 56K) and flush the disk write cache less often
890  * (every zvol_maxphys - currently 1MB) instead of minphys (currently
891  * 56K on X86 and 128K on sparc).
892  */
893 void
894 zvol_minphys(struct buf *bp)
895 {
896 	if (bp->b_bcount > zvol_maxphys)
897 		bp->b_bcount = zvol_maxphys;
898 }
899 
900 /*ARGSUSED*/
901 int
902 zvol_read(dev_t dev, uio_t *uio, cred_t *cr)
903 {
904 	minor_t minor = getminor(dev);
905 	zvol_state_t *zv;
906 	rl_t *rl;
907 	int error = 0;
908 
909 	if (minor == 0)			/* This is the control device */
910 		return (ENXIO);
911 
912 	zv = ddi_get_soft_state(zvol_state, minor);
913 	if (zv == NULL)
914 		return (ENXIO);
915 
916 	rl = zfs_range_lock(&zv->zv_znode, uio->uio_loffset, uio->uio_resid,
917 	    RL_READER);
918 	while (uio->uio_resid > 0) {
919 		uint64_t bytes = MIN(uio->uio_resid, DMU_MAX_ACCESS >> 1);
920 
921 		error =  dmu_read_uio(zv->zv_objset, ZVOL_OBJ, uio, bytes);
922 		if (error)
923 			break;
924 	}
925 	zfs_range_unlock(rl);
926 	return (error);
927 }
928 
929 /*ARGSUSED*/
930 int
931 zvol_write(dev_t dev, uio_t *uio, cred_t *cr)
932 {
933 	minor_t minor = getminor(dev);
934 	zvol_state_t *zv;
935 	rl_t *rl;
936 	int error = 0;
937 
938 	if (minor == 0)			/* This is the control device */
939 		return (ENXIO);
940 
941 	zv = ddi_get_soft_state(zvol_state, minor);
942 	if (zv == NULL)
943 		return (ENXIO);
944 
945 	rl = zfs_range_lock(&zv->zv_znode, uio->uio_loffset, uio->uio_resid,
946 	    RL_WRITER);
947 	while (uio->uio_resid > 0) {
948 		uint64_t bytes = MIN(uio->uio_resid, DMU_MAX_ACCESS >> 1);
949 		uint64_t off = uio->uio_loffset;
950 
951 		dmu_tx_t *tx = dmu_tx_create(zv->zv_objset);
952 		dmu_tx_hold_write(tx, ZVOL_OBJ, off, bytes);
953 		error = dmu_tx_assign(tx, TXG_WAIT);
954 		if (error) {
955 			dmu_tx_abort(tx);
956 			break;
957 		}
958 		error = dmu_write_uio(zv->zv_objset, ZVOL_OBJ, uio, bytes, tx);
959 		if (error == 0)
960 			zvol_log_write(zv, tx, off, bytes);
961 		dmu_tx_commit(tx);
962 
963 		if (error)
964 			break;
965 	}
966 	zfs_range_unlock(rl);
967 	return (error);
968 }
969 
970 /*
971  * Dirtbag ioctls to support mkfs(1M) for UFS filesystems.  See dkio(7I).
972  */
973 /*ARGSUSED*/
974 int
975 zvol_ioctl(dev_t dev, int cmd, intptr_t arg, int flag, cred_t *cr, int *rvalp)
976 {
977 	zvol_state_t *zv;
978 	struct dk_cinfo dki;
979 	struct dk_minfo dkm;
980 	dk_efi_t efi;
981 	struct dk_callback *dkc;
982 	struct uuid uuid = EFI_RESERVED;
983 	uint32_t crc;
984 	int error = 0;
985 
986 	mutex_enter(&zvol_state_lock);
987 
988 	zv = ddi_get_soft_state(zvol_state, getminor(dev));
989 
990 	if (zv == NULL) {
991 		mutex_exit(&zvol_state_lock);
992 		return (ENXIO);
993 	}
994 
995 	switch (cmd) {
996 
997 	case DKIOCINFO:
998 		bzero(&dki, sizeof (dki));
999 		(void) strcpy(dki.dki_cname, "zvol");
1000 		(void) strcpy(dki.dki_dname, "zvol");
1001 		dki.dki_ctype = DKC_UNKNOWN;
1002 		dki.dki_maxtransfer = 1 << (SPA_MAXBLOCKSHIFT - zv->zv_min_bs);
1003 		mutex_exit(&zvol_state_lock);
1004 		if (ddi_copyout(&dki, (void *)arg, sizeof (dki), flag))
1005 			error = EFAULT;
1006 		return (error);
1007 
1008 	case DKIOCGMEDIAINFO:
1009 		bzero(&dkm, sizeof (dkm));
1010 		dkm.dki_lbsize = 1U << zv->zv_min_bs;
1011 		dkm.dki_capacity = zv->zv_volsize >> zv->zv_min_bs;
1012 		dkm.dki_media_type = DK_UNKNOWN;
1013 		mutex_exit(&zvol_state_lock);
1014 		if (ddi_copyout(&dkm, (void *)arg, sizeof (dkm), flag))
1015 			error = EFAULT;
1016 		return (error);
1017 
1018 	case DKIOCGETEFI:
1019 		if (ddi_copyin((void *)arg, &efi, sizeof (dk_efi_t), flag)) {
1020 			mutex_exit(&zvol_state_lock);
1021 			return (EFAULT);
1022 		}
1023 		efi.dki_data = (void *)(uintptr_t)efi.dki_data_64;
1024 
1025 		/*
1026 		 * Some clients may attempt to request a PMBR for the
1027 		 * zvol.  Currently this interface will return ENOTTY to
1028 		 * such requests.  These requests could be supported by
1029 		 * adding a check for lba == 0 and consing up an appropriate
1030 		 * RMBR.
1031 		 */
1032 		if (efi.dki_lba == 1) {
1033 			efi_gpt_t gpt;
1034 			efi_gpe_t gpe;
1035 
1036 			bzero(&gpt, sizeof (gpt));
1037 			bzero(&gpe, sizeof (gpe));
1038 
1039 			if (efi.dki_length < sizeof (gpt)) {
1040 				mutex_exit(&zvol_state_lock);
1041 				return (EINVAL);
1042 			}
1043 
1044 			gpt.efi_gpt_Signature = LE_64(EFI_SIGNATURE);
1045 			gpt.efi_gpt_Revision = LE_32(EFI_VERSION_CURRENT);
1046 			gpt.efi_gpt_HeaderSize = LE_32(sizeof (gpt));
1047 			gpt.efi_gpt_FirstUsableLBA = LE_64(34ULL);
1048 			gpt.efi_gpt_LastUsableLBA =
1049 			    LE_64((zv->zv_volsize >> zv->zv_min_bs) - 1);
1050 			gpt.efi_gpt_NumberOfPartitionEntries = LE_32(1);
1051 			gpt.efi_gpt_PartitionEntryLBA = LE_64(2ULL);
1052 			gpt.efi_gpt_SizeOfPartitionEntry = LE_32(sizeof (gpe));
1053 
1054 			UUID_LE_CONVERT(gpe.efi_gpe_PartitionTypeGUID, uuid);
1055 			gpe.efi_gpe_StartingLBA = gpt.efi_gpt_FirstUsableLBA;
1056 			gpe.efi_gpe_EndingLBA = gpt.efi_gpt_LastUsableLBA;
1057 
1058 			CRC32(crc, &gpe, sizeof (gpe), -1U, crc32_table);
1059 			gpt.efi_gpt_PartitionEntryArrayCRC32 = LE_32(~crc);
1060 
1061 			CRC32(crc, &gpt, sizeof (gpt), -1U, crc32_table);
1062 			gpt.efi_gpt_HeaderCRC32 = LE_32(~crc);
1063 
1064 			mutex_exit(&zvol_state_lock);
1065 			if (ddi_copyout(&gpt, efi.dki_data, sizeof (gpt), flag))
1066 				error = EFAULT;
1067 		} else if (efi.dki_lba == 2) {
1068 			efi_gpe_t gpe;
1069 
1070 			bzero(&gpe, sizeof (gpe));
1071 
1072 			if (efi.dki_length < sizeof (gpe)) {
1073 				mutex_exit(&zvol_state_lock);
1074 				return (EINVAL);
1075 			}
1076 
1077 			UUID_LE_CONVERT(gpe.efi_gpe_PartitionTypeGUID, uuid);
1078 			gpe.efi_gpe_StartingLBA = LE_64(34ULL);
1079 			gpe.efi_gpe_EndingLBA =
1080 			    LE_64((zv->zv_volsize >> zv->zv_min_bs) - 1);
1081 
1082 			mutex_exit(&zvol_state_lock);
1083 			if (ddi_copyout(&gpe, efi.dki_data, sizeof (gpe), flag))
1084 				error = EFAULT;
1085 		} else {
1086 			mutex_exit(&zvol_state_lock);
1087 			error = EINVAL;
1088 		}
1089 		return (error);
1090 
1091 	case DKIOCFLUSHWRITECACHE:
1092 		dkc = (struct dk_callback *)arg;
1093 		zil_commit(zv->zv_zilog, UINT64_MAX, ZVOL_OBJ);
1094 		if ((flag & FKIOCTL) && dkc != NULL && dkc->dkc_callback) {
1095 			(*dkc->dkc_callback)(dkc->dkc_cookie, error);
1096 			error = 0;
1097 		}
1098 		break;
1099 
1100 	case DKIOCGGEOM:
1101 	case DKIOCGVTOC:
1102 		/* commands using these (like prtvtoc) expect ENOTSUP */
1103 		error = ENOTSUP;
1104 		break;
1105 
1106 	default:
1107 		error = ENOTTY;
1108 		break;
1109 
1110 	}
1111 	mutex_exit(&zvol_state_lock);
1112 	return (error);
1113 }
1114 
1115 int
1116 zvol_busy(void)
1117 {
1118 	return (zvol_minors != 0);
1119 }
1120 
1121 void
1122 zvol_init(void)
1123 {
1124 	VERIFY(ddi_soft_state_init(&zvol_state, sizeof (zvol_state_t), 1) == 0);
1125 	mutex_init(&zvol_state_lock, NULL, MUTEX_DEFAULT, NULL);
1126 }
1127 
1128 void
1129 zvol_fini(void)
1130 {
1131 	mutex_destroy(&zvol_state_lock);
1132 	ddi_soft_state_fini(&zvol_state);
1133 }
1134