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