]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zvol.c
Update Subversion to 1.14.0 LTS. See contrib/subversion/CHANGES for a
[FreeBSD/FreeBSD.git] / sys / cddl / contrib / opensolaris / uts / common / fs / zfs / zvol.c
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) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
23  *
24  * Copyright (c) 2006-2010 Pawel Jakub Dawidek <pjd@FreeBSD.org>
25  * All rights reserved.
26  *
27  * Portions Copyright 2010 Robert Milkowski
28  *
29  * Copyright 2017 Nexenta Systems, Inc.  All rights reserved.
30  * Copyright (c) 2012, 2017 by Delphix. All rights reserved.
31  * Copyright (c) 2013, Joyent, Inc. All rights reserved.
32  * Copyright (c) 2014 Integros [integros.com]
33  */
34
35 /* Portions Copyright 2011 Martin Matuska <mm@FreeBSD.org> */
36
37 /*
38  * ZFS volume emulation driver.
39  *
40  * Makes a DMU object look like a volume of arbitrary size, up to 2^64 bytes.
41  * Volumes are accessed through the symbolic links named:
42  *
43  * /dev/zvol/dsk/<pool_name>/<dataset_name>
44  * /dev/zvol/rdsk/<pool_name>/<dataset_name>
45  *
46  * These links are created by the /dev filesystem (sdev_zvolops.c).
47  * Volumes are persistent through reboot.  No user command needs to be
48  * run before opening and using a device.
49  *
50  * FreeBSD notes.
51  * On FreeBSD ZVOLs are simply GEOM providers like any other storage device
52  * in the system.
53  */
54
55 #include <sys/types.h>
56 #include <sys/param.h>
57 #include <sys/kernel.h>
58 #include <sys/errno.h>
59 #include <sys/uio.h>
60 #include <sys/bio.h>
61 #include <sys/buf.h>
62 #include <sys/kmem.h>
63 #include <sys/conf.h>
64 #include <sys/cmn_err.h>
65 #include <sys/stat.h>
66 #include <sys/zap.h>
67 #include <sys/spa.h>
68 #include <sys/spa_impl.h>
69 #include <sys/zio.h>
70 #include <sys/disk.h>
71 #include <sys/dmu_traverse.h>
72 #include <sys/dnode.h>
73 #include <sys/dsl_dataset.h>
74 #include <sys/dsl_prop.h>
75 #include <sys/dkio.h>
76 #include <sys/byteorder.h>
77 #include <sys/sunddi.h>
78 #include <sys/dirent.h>
79 #include <sys/policy.h>
80 #include <sys/queue.h>
81 #include <sys/fs/zfs.h>
82 #include <sys/zfs_ioctl.h>
83 #include <sys/zil.h>
84 #include <sys/refcount.h>
85 #include <sys/zfs_znode.h>
86 #include <sys/zfs_rlock.h>
87 #include <sys/vdev_impl.h>
88 #include <sys/vdev_raidz.h>
89 #include <sys/zvol.h>
90 #include <sys/zil_impl.h>
91 #include <sys/dbuf.h>
92 #include <sys/dmu_tx.h>
93 #include <sys/zfeature.h>
94 #include <sys/zio_checksum.h>
95 #include <sys/zil_impl.h>
96 #include <sys/filio.h>
97 #include <sys/zfs_rlock.h>
98
99 #include <geom/geom.h>
100
101 #include "zfs_namecheck.h"
102
103 #ifndef illumos
104 struct g_class zfs_zvol_class = {
105         .name = "ZFS::ZVOL",
106         .version = G_VERSION,
107 };
108
109 DECLARE_GEOM_CLASS(zfs_zvol_class, zfs_zvol);
110
111 #endif
112 void *zfsdev_state;
113 static char *zvol_tag = "zvol_tag";
114
115 #define ZVOL_DUMPSIZE           "dumpsize"
116
117 /*
118  * This lock protects the zfsdev_state structure from being modified
119  * while it's being used, e.g. an open that comes in before a create
120  * finishes.  It also protects temporary opens of the dataset so that,
121  * e.g., an open doesn't get a spurious EBUSY.
122  */
123 #ifdef illumos
124 kmutex_t zfsdev_state_lock;
125 #else
126 /*
127  * In FreeBSD we've replaced the upstream zfsdev_state_lock with the
128  * spa_namespace_lock in the ZVOL code.
129  */
130 #define zfsdev_state_lock spa_namespace_lock
131 #endif
132 static uint32_t zvol_minors;
133
134 #ifndef illumos
135 SYSCTL_DECL(_vfs_zfs);
136 SYSCTL_NODE(_vfs_zfs, OID_AUTO, vol, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
137     "ZFS VOLUME");
138 static int      volmode = ZFS_VOLMODE_GEOM;
139 SYSCTL_INT(_vfs_zfs_vol, OID_AUTO, mode, CTLFLAG_RWTUN, &volmode, 0,
140     "Expose as GEOM providers (1), device files (2) or neither");
141 static boolean_t zpool_on_zvol = B_FALSE;
142 SYSCTL_INT(_vfs_zfs_vol, OID_AUTO, recursive, CTLFLAG_RWTUN, &zpool_on_zvol, 0,
143     "Allow zpools to use zvols as vdevs (DANGEROUS)");
144
145 #endif
146 typedef struct zvol_extent {
147         list_node_t     ze_node;
148         dva_t           ze_dva;         /* dva associated with this extent */
149         uint64_t        ze_nblks;       /* number of blocks in extent */
150 } zvol_extent_t;
151
152 /*
153  * The in-core state of each volume.
154  */
155 typedef struct zvol_state {
156 #ifndef illumos
157         LIST_ENTRY(zvol_state)  zv_links;
158 #endif
159         char            zv_name[MAXPATHLEN]; /* pool/dd name */
160         uint64_t        zv_volsize;     /* amount of space we advertise */
161         uint64_t        zv_volblocksize; /* volume block size */
162 #ifdef illumos
163         minor_t         zv_minor;       /* minor number */
164 #else
165         struct cdev     *zv_dev;        /* non-GEOM device */
166         struct g_provider *zv_provider; /* GEOM provider */
167 #endif
168         uint8_t         zv_min_bs;      /* minimum addressable block shift */
169         uint8_t         zv_flags;       /* readonly, dumpified, etc. */
170         objset_t        *zv_objset;     /* objset handle */
171 #ifdef illumos
172         uint32_t        zv_open_count[OTYPCNT]; /* open counts */
173 #endif
174         uint32_t        zv_total_opens; /* total open count */
175         uint32_t        zv_sync_cnt;    /* synchronous open count */
176         zilog_t         *zv_zilog;      /* ZIL handle */
177         list_t          zv_extents;     /* List of extents for dump */
178         rangelock_t     zv_rangelock;
179         dnode_t         *zv_dn;         /* dnode hold */
180 #ifndef illumos
181         int             zv_state;
182         int             zv_volmode;     /* Provide GEOM or cdev */
183         struct bio_queue_head zv_queue;
184         struct mtx      zv_queue_mtx;   /* zv_queue mutex */
185 #endif
186 } zvol_state_t;
187
188 #ifndef illumos
189 static LIST_HEAD(, zvol_state) all_zvols;
190 #endif
191 /*
192  * zvol specific flags
193  */
194 #define ZVOL_RDONLY     0x1
195 #define ZVOL_DUMPIFIED  0x2
196 #define ZVOL_EXCL       0x4
197 #define ZVOL_WCE        0x8
198
199 /*
200  * zvol maximum transfer in one DMU tx.
201  */
202 int zvol_maxphys = DMU_MAX_ACCESS/2;
203
204 /*
205  * Toggle unmap functionality.
206  */
207 boolean_t zvol_unmap_enabled = B_TRUE;
208
209 /*
210  * If true, unmaps requested as synchronous are executed synchronously,
211  * otherwise all unmaps are asynchronous.
212  */
213 boolean_t zvol_unmap_sync_enabled = B_FALSE;
214
215 #ifndef illumos
216 SYSCTL_INT(_vfs_zfs_vol, OID_AUTO, unmap_enabled, CTLFLAG_RWTUN,
217     &zvol_unmap_enabled, 0,
218     "Enable UNMAP functionality");
219
220 SYSCTL_INT(_vfs_zfs_vol, OID_AUTO, unmap_sync_enabled, CTLFLAG_RWTUN,
221     &zvol_unmap_sync_enabled, 0,
222     "UNMAPs requested as sync are executed synchronously");
223
224 static d_open_t         zvol_d_open;
225 static d_close_t        zvol_d_close;
226 static d_read_t         zvol_read;
227 static d_write_t        zvol_write;
228 static d_ioctl_t        zvol_d_ioctl;
229 static d_strategy_t     zvol_strategy;
230
231 static struct cdevsw zvol_cdevsw = {
232         .d_version =    D_VERSION,
233         .d_open =       zvol_d_open,
234         .d_close =      zvol_d_close,
235         .d_read =       zvol_read,
236         .d_write =      zvol_write,
237         .d_ioctl =      zvol_d_ioctl,
238         .d_strategy =   zvol_strategy,
239         .d_name =       "zvol",
240         .d_flags =      D_DISK | D_TRACKCLOSE,
241 };
242
243 static void zvol_geom_run(zvol_state_t *zv);
244 static void zvol_geom_destroy(zvol_state_t *zv);
245 static int zvol_geom_access(struct g_provider *pp, int acr, int acw, int ace);
246 static void zvol_geom_start(struct bio *bp);
247 static void zvol_geom_worker(void *arg);
248 static void zvol_log_truncate(zvol_state_t *zv, dmu_tx_t *tx, uint64_t off,
249     uint64_t len, boolean_t sync);
250 #endif  /* !illumos */
251
252 extern int zfs_set_prop_nvlist(const char *, zprop_source_t,
253     nvlist_t *, nvlist_t *);
254 static int zvol_remove_zv(zvol_state_t *);
255 static int zvol_get_data(void *arg, lr_write_t *lr, char *buf,
256     struct lwb *lwb, zio_t *zio);
257 static int zvol_dumpify(zvol_state_t *zv);
258 static int zvol_dump_fini(zvol_state_t *zv);
259 static int zvol_dump_init(zvol_state_t *zv, boolean_t resize);
260
261 static void
262 zvol_size_changed(zvol_state_t *zv, uint64_t volsize)
263 {
264 #ifdef illumos
265         dev_t dev = makedevice(ddi_driver_major(zfs_dip), zv->zv_minor);
266
267         zv->zv_volsize = volsize;
268         VERIFY(ddi_prop_update_int64(dev, zfs_dip,
269             "Size", volsize) == DDI_SUCCESS);
270         VERIFY(ddi_prop_update_int64(dev, zfs_dip,
271             "Nblocks", lbtodb(volsize)) == DDI_SUCCESS);
272
273         /* Notify specfs to invalidate the cached size */
274         spec_size_invalidate(dev, VBLK);
275         spec_size_invalidate(dev, VCHR);
276 #else   /* !illumos */
277         zv->zv_volsize = volsize;
278         if (zv->zv_volmode == ZFS_VOLMODE_GEOM) {
279                 struct g_provider *pp;
280
281                 pp = zv->zv_provider;
282                 if (pp == NULL)
283                         return;
284                 g_topology_lock();
285
286                 /*
287                  * Do not invoke resize event when initial size was zero.
288                  * ZVOL initializes the size on first open, this is not
289                  * real resizing.
290                  */
291                 if (pp->mediasize == 0)
292                         pp->mediasize = zv->zv_volsize;
293                 else
294                         g_resize_provider(pp, zv->zv_volsize);
295                 g_topology_unlock();
296         }
297 #endif  /* illumos */
298 }
299
300 int
301 zvol_check_volsize(uint64_t volsize, uint64_t blocksize)
302 {
303         if (volsize == 0)
304                 return (SET_ERROR(EINVAL));
305
306         if (volsize % blocksize != 0)
307                 return (SET_ERROR(EINVAL));
308
309 #ifdef _ILP32
310         if (volsize - 1 > SPEC_MAXOFFSET_T)
311                 return (SET_ERROR(EOVERFLOW));
312 #endif
313         return (0);
314 }
315
316 int
317 zvol_check_volblocksize(uint64_t volblocksize)
318 {
319         if (volblocksize < SPA_MINBLOCKSIZE ||
320             volblocksize > SPA_OLD_MAXBLOCKSIZE ||
321             !ISP2(volblocksize))
322                 return (SET_ERROR(EDOM));
323
324         return (0);
325 }
326
327 int
328 zvol_get_stats(objset_t *os, nvlist_t *nv)
329 {
330         int error;
331         dmu_object_info_t doi;
332         uint64_t val;
333
334         error = zap_lookup(os, ZVOL_ZAP_OBJ, "size", 8, 1, &val);
335         if (error)
336                 return (error);
337
338         dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_VOLSIZE, val);
339
340         error = dmu_object_info(os, ZVOL_OBJ, &doi);
341
342         if (error == 0) {
343                 dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_VOLBLOCKSIZE,
344                     doi.doi_data_block_size);
345         }
346
347         return (error);
348 }
349
350 static zvol_state_t *
351 zvol_minor_lookup(const char *name)
352 {
353 #ifdef illumos
354         minor_t minor;
355 #endif
356         zvol_state_t *zv;
357
358         ASSERT(MUTEX_HELD(&zfsdev_state_lock));
359
360 #ifdef illumos
361         for (minor = 1; minor <= ZFSDEV_MAX_MINOR; minor++) {
362                 zv = zfsdev_get_soft_state(minor, ZSST_ZVOL);
363                 if (zv == NULL)
364                         continue;
365 #else
366         LIST_FOREACH(zv, &all_zvols, zv_links) {
367 #endif
368                 if (strcmp(zv->zv_name, name) == 0)
369                         return (zv);
370         }
371
372         return (NULL);
373 }
374
375 /* extent mapping arg */
376 struct maparg {
377         zvol_state_t    *ma_zv;
378         uint64_t        ma_blks;
379 };
380
381 /*ARGSUSED*/
382 static int
383 zvol_map_block(spa_t *spa, zilog_t *zilog, const blkptr_t *bp,
384     const zbookmark_phys_t *zb, const dnode_phys_t *dnp, void *arg)
385 {
386         struct maparg *ma = arg;
387         zvol_extent_t *ze;
388         int bs = ma->ma_zv->zv_volblocksize;
389
390         if (bp == NULL || BP_IS_HOLE(bp) ||
391             zb->zb_object != ZVOL_OBJ || zb->zb_level != 0)
392                 return (0);
393
394         VERIFY(!BP_IS_EMBEDDED(bp));
395
396         VERIFY3U(ma->ma_blks, ==, zb->zb_blkid);
397         ma->ma_blks++;
398
399         /* Abort immediately if we have encountered gang blocks */
400         if (BP_IS_GANG(bp))
401                 return (SET_ERROR(EFRAGS));
402
403         /*
404          * See if the block is at the end of the previous extent.
405          */
406         ze = list_tail(&ma->ma_zv->zv_extents);
407         if (ze &&
408             DVA_GET_VDEV(BP_IDENTITY(bp)) == DVA_GET_VDEV(&ze->ze_dva) &&
409             DVA_GET_OFFSET(BP_IDENTITY(bp)) ==
410             DVA_GET_OFFSET(&ze->ze_dva) + ze->ze_nblks * bs) {
411                 ze->ze_nblks++;
412                 return (0);
413         }
414
415         dprintf_bp(bp, "%s", "next blkptr:");
416
417         /* start a new extent */
418         ze = kmem_zalloc(sizeof (zvol_extent_t), KM_SLEEP);
419         ze->ze_dva = bp->blk_dva[0];    /* structure assignment */
420         ze->ze_nblks = 1;
421         list_insert_tail(&ma->ma_zv->zv_extents, ze);
422         return (0);
423 }
424
425 static void
426 zvol_free_extents(zvol_state_t *zv)
427 {
428         zvol_extent_t *ze;
429
430         while (ze = list_head(&zv->zv_extents)) {
431                 list_remove(&zv->zv_extents, ze);
432                 kmem_free(ze, sizeof (zvol_extent_t));
433         }
434 }
435
436 static int
437 zvol_get_lbas(zvol_state_t *zv)
438 {
439         objset_t *os = zv->zv_objset;
440         struct maparg   ma;
441         int             err;
442
443         ma.ma_zv = zv;
444         ma.ma_blks = 0;
445         zvol_free_extents(zv);
446
447         /* commit any in-flight changes before traversing the dataset */
448         txg_wait_synced(dmu_objset_pool(os), 0);
449         err = traverse_dataset(dmu_objset_ds(os), 0,
450             TRAVERSE_PRE | TRAVERSE_PREFETCH_METADATA, zvol_map_block, &ma);
451         if (err || ma.ma_blks != (zv->zv_volsize / zv->zv_volblocksize)) {
452                 zvol_free_extents(zv);
453                 return (err ? err : EIO);
454         }
455
456         return (0);
457 }
458
459 /* ARGSUSED */
460 void
461 zvol_create_cb(objset_t *os, void *arg, cred_t *cr, dmu_tx_t *tx)
462 {
463         zfs_creat_t *zct = arg;
464         nvlist_t *nvprops = zct->zct_props;
465         int error;
466         uint64_t volblocksize, volsize;
467
468         VERIFY(nvlist_lookup_uint64(nvprops,
469             zfs_prop_to_name(ZFS_PROP_VOLSIZE), &volsize) == 0);
470         if (nvlist_lookup_uint64(nvprops,
471             zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE), &volblocksize) != 0)
472                 volblocksize = zfs_prop_default_numeric(ZFS_PROP_VOLBLOCKSIZE);
473
474         /*
475          * These properties must be removed from the list so the generic
476          * property setting step won't apply to them.
477          */
478         VERIFY(nvlist_remove_all(nvprops,
479             zfs_prop_to_name(ZFS_PROP_VOLSIZE)) == 0);
480         (void) nvlist_remove_all(nvprops,
481             zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE));
482
483         error = dmu_object_claim(os, ZVOL_OBJ, DMU_OT_ZVOL, volblocksize,
484             DMU_OT_NONE, 0, tx);
485         ASSERT(error == 0);
486
487         error = zap_create_claim(os, ZVOL_ZAP_OBJ, DMU_OT_ZVOL_PROP,
488             DMU_OT_NONE, 0, tx);
489         ASSERT(error == 0);
490
491         error = zap_update(os, ZVOL_ZAP_OBJ, "size", 8, 1, &volsize, tx);
492         ASSERT(error == 0);
493 }
494
495 /*
496  * Replay a TX_TRUNCATE ZIL transaction if asked.  TX_TRUNCATE is how we
497  * implement DKIOCFREE/free-long-range.
498  */
499 static int
500 zvol_replay_truncate(void *arg1, void *arg2, boolean_t byteswap)
501 {
502         zvol_state_t *zv = arg1;
503         lr_truncate_t *lr = arg2;
504         uint64_t offset, length;
505
506         if (byteswap)
507                 byteswap_uint64_array(lr, sizeof (*lr));
508
509         offset = lr->lr_offset;
510         length = lr->lr_length;
511
512         return (dmu_free_long_range(zv->zv_objset, ZVOL_OBJ, offset, length));
513 }
514
515 /*
516  * Replay a TX_WRITE ZIL transaction that didn't get committed
517  * after a system failure
518  */
519 static int
520 zvol_replay_write(void *arg1, void *arg2, boolean_t byteswap)
521 {
522         zvol_state_t *zv = arg1;
523         lr_write_t *lr = arg2;
524         objset_t *os = zv->zv_objset;
525         char *data = (char *)(lr + 1);  /* data follows lr_write_t */
526         uint64_t offset, length;
527         dmu_tx_t *tx;
528         int error;
529
530         if (byteswap)
531                 byteswap_uint64_array(lr, sizeof (*lr));
532
533         offset = lr->lr_offset;
534         length = lr->lr_length;
535
536         /* If it's a dmu_sync() block, write the whole block */
537         if (lr->lr_common.lrc_reclen == sizeof (lr_write_t)) {
538                 uint64_t blocksize = BP_GET_LSIZE(&lr->lr_blkptr);
539                 if (length < blocksize) {
540                         offset -= offset % blocksize;
541                         length = blocksize;
542                 }
543         }
544
545         tx = dmu_tx_create(os);
546         dmu_tx_hold_write(tx, ZVOL_OBJ, offset, length);
547         error = dmu_tx_assign(tx, TXG_WAIT);
548         if (error) {
549                 dmu_tx_abort(tx);
550         } else {
551                 dmu_write(os, ZVOL_OBJ, offset, length, data, tx);
552                 dmu_tx_commit(tx);
553         }
554
555         return (error);
556 }
557
558 /* ARGSUSED */
559 static int
560 zvol_replay_err(void *arg1, void *arg2, boolean_t byteswap)
561 {
562         return (SET_ERROR(ENOTSUP));
563 }
564
565 /*
566  * Callback vectors for replaying records.
567  * Only TX_WRITE and TX_TRUNCATE are needed for zvol.
568  */
569 zil_replay_func_t *zvol_replay_vector[TX_MAX_TYPE] = {
570         zvol_replay_err,        /* 0 no such transaction type */
571         zvol_replay_err,        /* TX_CREATE */
572         zvol_replay_err,        /* TX_MKDIR */
573         zvol_replay_err,        /* TX_MKXATTR */
574         zvol_replay_err,        /* TX_SYMLINK */
575         zvol_replay_err,        /* TX_REMOVE */
576         zvol_replay_err,        /* TX_RMDIR */
577         zvol_replay_err,        /* TX_LINK */
578         zvol_replay_err,        /* TX_RENAME */
579         zvol_replay_write,      /* TX_WRITE */
580         zvol_replay_truncate,   /* TX_TRUNCATE */
581         zvol_replay_err,        /* TX_SETATTR */
582         zvol_replay_err,        /* TX_ACL */
583         zvol_replay_err,        /* TX_CREATE_ACL */
584         zvol_replay_err,        /* TX_CREATE_ATTR */
585         zvol_replay_err,        /* TX_CREATE_ACL_ATTR */
586         zvol_replay_err,        /* TX_MKDIR_ACL */
587         zvol_replay_err,        /* TX_MKDIR_ATTR */
588         zvol_replay_err,        /* TX_MKDIR_ACL_ATTR */
589         zvol_replay_err,        /* TX_WRITE2 */
590 };
591
592 #ifdef illumos
593 int
594 zvol_name2minor(const char *name, minor_t *minor)
595 {
596         zvol_state_t *zv;
597
598         mutex_enter(&zfsdev_state_lock);
599         zv = zvol_minor_lookup(name);
600         if (minor && zv)
601                 *minor = zv->zv_minor;
602         mutex_exit(&zfsdev_state_lock);
603         return (zv ? 0 : -1);
604 }
605 #endif  /* illumos */
606
607 /*
608  * Create a minor node (plus a whole lot more) for the specified volume.
609  */
610 int
611 zvol_create_minor(const char *name)
612 {
613         zfs_soft_state_t *zs;
614         zvol_state_t *zv;
615         objset_t *os;
616 #ifdef illumos
617         dmu_object_info_t doi;
618         minor_t minor = 0;
619         char chrbuf[30], blkbuf[30];
620 #else
621         struct g_provider *pp;
622         struct g_geom *gp;
623         uint64_t mode;
624 #endif
625         int error;
626
627 #ifndef illumos
628         ZFS_LOG(1, "Creating ZVOL %s...", name);
629 #endif
630
631         mutex_enter(&zfsdev_state_lock);
632
633         if (zvol_minor_lookup(name) != NULL) {
634                 mutex_exit(&zfsdev_state_lock);
635                 return (SET_ERROR(EEXIST));
636         }
637
638         /* lie and say we're read-only */
639         error = dmu_objset_own(name, DMU_OST_ZVOL, B_TRUE, FTAG, &os);
640
641         if (error) {
642                 mutex_exit(&zfsdev_state_lock);
643                 return (error);
644         }
645
646 #ifdef illumos
647         if ((minor = zfsdev_minor_alloc()) == 0) {
648                 dmu_objset_disown(os, FTAG);
649                 mutex_exit(&zfsdev_state_lock);
650                 return (SET_ERROR(ENXIO));
651         }
652
653         if (ddi_soft_state_zalloc(zfsdev_state, minor) != DDI_SUCCESS) {
654                 dmu_objset_disown(os, FTAG);
655                 mutex_exit(&zfsdev_state_lock);
656                 return (SET_ERROR(EAGAIN));
657         }
658         (void) ddi_prop_update_string(minor, zfs_dip, ZVOL_PROP_NAME,
659             (char *)name);
660
661         (void) snprintf(chrbuf, sizeof (chrbuf), "%u,raw", minor);
662
663         if (ddi_create_minor_node(zfs_dip, chrbuf, S_IFCHR,
664             minor, DDI_PSEUDO, 0) == DDI_FAILURE) {
665                 ddi_soft_state_free(zfsdev_state, minor);
666                 dmu_objset_disown(os, FTAG);
667                 mutex_exit(&zfsdev_state_lock);
668                 return (SET_ERROR(EAGAIN));
669         }
670
671         (void) snprintf(blkbuf, sizeof (blkbuf), "%u", minor);
672
673         if (ddi_create_minor_node(zfs_dip, blkbuf, S_IFBLK,
674             minor, DDI_PSEUDO, 0) == DDI_FAILURE) {
675                 ddi_remove_minor_node(zfs_dip, chrbuf);
676                 ddi_soft_state_free(zfsdev_state, minor);
677                 dmu_objset_disown(os, FTAG);
678                 mutex_exit(&zfsdev_state_lock);
679                 return (SET_ERROR(EAGAIN));
680         }
681
682         zs = ddi_get_soft_state(zfsdev_state, minor);
683         zs->zss_type = ZSST_ZVOL;
684         zv = zs->zss_data = kmem_zalloc(sizeof (zvol_state_t), KM_SLEEP);
685 #else   /* !illumos */
686
687         zv = kmem_zalloc(sizeof(*zv), KM_SLEEP);
688         zv->zv_state = 0;
689         error = dsl_prop_get_integer(name,
690             zfs_prop_to_name(ZFS_PROP_VOLMODE), &mode, NULL);
691         if (error != 0 || mode == ZFS_VOLMODE_DEFAULT)
692                 mode = volmode;
693
694         DROP_GIANT();
695         zv->zv_volmode = mode;
696         if (zv->zv_volmode == ZFS_VOLMODE_GEOM) {
697                 g_topology_lock();
698                 gp = g_new_geomf(&zfs_zvol_class, "zfs::zvol::%s", name);
699                 gp->start = zvol_geom_start;
700                 gp->access = zvol_geom_access;
701                 pp = g_new_providerf(gp, "%s/%s", ZVOL_DRIVER, name);
702                 pp->flags |= G_PF_DIRECT_RECEIVE | G_PF_DIRECT_SEND;
703                 pp->sectorsize = DEV_BSIZE;
704                 pp->mediasize = 0;
705                 pp->private = zv;
706
707                 zv->zv_provider = pp;
708                 bioq_init(&zv->zv_queue);
709                 mtx_init(&zv->zv_queue_mtx, "zvol", NULL, MTX_DEF);
710         } else if (zv->zv_volmode == ZFS_VOLMODE_DEV) {
711                 struct make_dev_args args;
712
713                 make_dev_args_init(&args);
714                 args.mda_flags = MAKEDEV_CHECKNAME | MAKEDEV_WAITOK;
715                 args.mda_devsw = &zvol_cdevsw;
716                 args.mda_cr = NULL;
717                 args.mda_uid = UID_ROOT;
718                 args.mda_gid = GID_OPERATOR;
719                 args.mda_mode = 0640;
720                 args.mda_si_drv2 = zv;
721                 error = make_dev_s(&args, &zv->zv_dev,
722                     "%s/%s", ZVOL_DRIVER, name);
723                 if (error != 0) {
724                         kmem_free(zv, sizeof(*zv));
725                         dmu_objset_disown(os, FTAG);
726                         mutex_exit(&zfsdev_state_lock);
727                         return (error);
728                 }
729                 zv->zv_dev->si_iosize_max = MAXPHYS;
730         }
731         LIST_INSERT_HEAD(&all_zvols, zv, zv_links);
732 #endif  /* illumos */
733
734         (void) strlcpy(zv->zv_name, name, MAXPATHLEN);
735         zv->zv_min_bs = DEV_BSHIFT;
736 #ifdef illumos
737         zv->zv_minor = minor;
738 #endif
739         zv->zv_objset = os;
740         if (dmu_objset_is_snapshot(os) || !spa_writeable(dmu_objset_spa(os)))
741                 zv->zv_flags |= ZVOL_RDONLY;
742         rangelock_init(&zv->zv_rangelock, NULL, NULL);
743         list_create(&zv->zv_extents, sizeof (zvol_extent_t),
744             offsetof(zvol_extent_t, ze_node));
745 #ifdef illumos
746         /* get and cache the blocksize */
747         error = dmu_object_info(os, ZVOL_OBJ, &doi);
748         ASSERT(error == 0);
749         zv->zv_volblocksize = doi.doi_data_block_size;
750 #endif
751
752         if (spa_writeable(dmu_objset_spa(os))) {
753                 if (zil_replay_disable)
754                         zil_destroy(dmu_objset_zil(os), B_FALSE);
755                 else
756                         zil_replay(os, zv, zvol_replay_vector);
757         }
758         dmu_objset_disown(os, FTAG);
759         zv->zv_objset = NULL;
760
761         zvol_minors++;
762
763         mutex_exit(&zfsdev_state_lock);
764 #ifndef illumos
765         if (zv->zv_volmode == ZFS_VOLMODE_GEOM) {
766                 zvol_geom_run(zv);
767                 g_topology_unlock();
768         }
769         PICKUP_GIANT();
770
771         ZFS_LOG(1, "ZVOL %s created.", name);
772 #endif
773
774         return (0);
775 }
776
777 /*
778  * Remove minor node for the specified volume.
779  */
780 static int
781 zvol_remove_zv(zvol_state_t *zv)
782 {
783 #ifdef illumos
784         char nmbuf[20];
785         minor_t minor = zv->zv_minor;
786 #endif
787
788         ASSERT(MUTEX_HELD(&zfsdev_state_lock));
789         if (zv->zv_total_opens != 0)
790                 return (SET_ERROR(EBUSY));
791
792 #ifdef illumos
793         (void) snprintf(nmbuf, sizeof (nmbuf), "%u,raw", minor);
794         ddi_remove_minor_node(zfs_dip, nmbuf);
795
796         (void) snprintf(nmbuf, sizeof (nmbuf), "%u", minor);
797         ddi_remove_minor_node(zfs_dip, nmbuf);
798 #else
799         ZFS_LOG(1, "ZVOL %s destroyed.", zv->zv_name);
800
801         LIST_REMOVE(zv, zv_links);
802         if (zv->zv_volmode == ZFS_VOLMODE_GEOM) {
803                 g_topology_lock();
804                 zvol_geom_destroy(zv);
805                 g_topology_unlock();
806         } else if (zv->zv_volmode == ZFS_VOLMODE_DEV) {
807                 if (zv->zv_dev != NULL)
808                         destroy_dev(zv->zv_dev);
809         }
810 #endif
811
812         rangelock_fini(&zv->zv_rangelock);
813
814         kmem_free(zv, sizeof (zvol_state_t));
815 #ifdef illumos
816         ddi_soft_state_free(zfsdev_state, minor);
817 #endif
818         zvol_minors--;
819         return (0);
820 }
821
822 int
823 zvol_remove_minor(const char *name)
824 {
825         zvol_state_t *zv;
826         int rc;
827
828         mutex_enter(&zfsdev_state_lock);
829         if ((zv = zvol_minor_lookup(name)) == NULL) {
830                 mutex_exit(&zfsdev_state_lock);
831                 return (SET_ERROR(ENXIO));
832         }
833         rc = zvol_remove_zv(zv);
834         mutex_exit(&zfsdev_state_lock);
835         return (rc);
836 }
837
838 int
839 zvol_first_open(zvol_state_t *zv)
840 {
841         dmu_object_info_t doi;
842         objset_t *os;
843         uint64_t volsize;
844         int error;
845         uint64_t readonly;
846
847         /* lie and say we're read-only */
848         error = dmu_objset_own(zv->zv_name, DMU_OST_ZVOL, B_TRUE,
849             zvol_tag, &os);
850         if (error)
851                 return (error);
852
853         zv->zv_objset = os;
854         error = zap_lookup(os, ZVOL_ZAP_OBJ, "size", 8, 1, &volsize);
855         if (error) {
856                 ASSERT(error == 0);
857                 dmu_objset_disown(os, zvol_tag);
858                 return (error);
859         }
860
861         /* get and cache the blocksize */
862         error = dmu_object_info(os, ZVOL_OBJ, &doi);
863         if (error) {
864                 ASSERT(error == 0);
865                 dmu_objset_disown(os, zvol_tag);
866                 return (error);
867         }
868         zv->zv_volblocksize = doi.doi_data_block_size;
869
870         error = dnode_hold(os, ZVOL_OBJ, zvol_tag, &zv->zv_dn);
871         if (error) {
872                 dmu_objset_disown(os, zvol_tag);
873                 return (error);
874         }
875
876         zvol_size_changed(zv, volsize);
877         zv->zv_zilog = zil_open(os, zvol_get_data);
878
879         VERIFY(dsl_prop_get_integer(zv->zv_name, "readonly", &readonly,
880             NULL) == 0);
881         if (readonly || dmu_objset_is_snapshot(os) ||
882             !spa_writeable(dmu_objset_spa(os)))
883                 zv->zv_flags |= ZVOL_RDONLY;
884         else
885                 zv->zv_flags &= ~ZVOL_RDONLY;
886         return (error);
887 }
888
889 void
890 zvol_last_close(zvol_state_t *zv)
891 {
892         zil_close(zv->zv_zilog);
893         zv->zv_zilog = NULL;
894
895         dnode_rele(zv->zv_dn, zvol_tag);
896         zv->zv_dn = NULL;
897
898         /*
899          * Evict cached data
900          */
901         if (dsl_dataset_is_dirty(dmu_objset_ds(zv->zv_objset)) &&
902             !(zv->zv_flags & ZVOL_RDONLY))
903                 txg_wait_synced(dmu_objset_pool(zv->zv_objset), 0);
904         dmu_objset_evict_dbufs(zv->zv_objset);
905
906         dmu_objset_disown(zv->zv_objset, zvol_tag);
907         zv->zv_objset = NULL;
908 }
909
910 #ifdef illumos
911 int
912 zvol_prealloc(zvol_state_t *zv)
913 {
914         objset_t *os = zv->zv_objset;
915         dmu_tx_t *tx;
916         uint64_t refd, avail, usedobjs, availobjs;
917         uint64_t resid = zv->zv_volsize;
918         uint64_t off = 0;
919
920         /* Check the space usage before attempting to allocate the space */
921         dmu_objset_space(os, &refd, &avail, &usedobjs, &availobjs);
922         if (avail < zv->zv_volsize)
923                 return (SET_ERROR(ENOSPC));
924
925         /* Free old extents if they exist */
926         zvol_free_extents(zv);
927
928         while (resid != 0) {
929                 int error;
930                 uint64_t bytes = MIN(resid, SPA_OLD_MAXBLOCKSIZE);
931
932                 tx = dmu_tx_create(os);
933                 dmu_tx_hold_write(tx, ZVOL_OBJ, off, bytes);
934                 error = dmu_tx_assign(tx, TXG_WAIT);
935                 if (error) {
936                         dmu_tx_abort(tx);
937                         (void) dmu_free_long_range(os, ZVOL_OBJ, 0, off);
938                         return (error);
939                 }
940                 dmu_prealloc(os, ZVOL_OBJ, off, bytes, tx);
941                 dmu_tx_commit(tx);
942                 off += bytes;
943                 resid -= bytes;
944         }
945         txg_wait_synced(dmu_objset_pool(os), 0);
946
947         return (0);
948 }
949 #endif  /* illumos */
950
951 static int
952 zvol_update_volsize(objset_t *os, uint64_t volsize)
953 {
954         dmu_tx_t *tx;
955         int error;
956
957         ASSERT(MUTEX_HELD(&zfsdev_state_lock));
958
959         tx = dmu_tx_create(os);
960         dmu_tx_hold_zap(tx, ZVOL_ZAP_OBJ, TRUE, NULL);
961         dmu_tx_mark_netfree(tx);
962         error = dmu_tx_assign(tx, TXG_WAIT);
963         if (error) {
964                 dmu_tx_abort(tx);
965                 return (error);
966         }
967
968         error = zap_update(os, ZVOL_ZAP_OBJ, "size", 8, 1,
969             &volsize, tx);
970         dmu_tx_commit(tx);
971
972         if (error == 0)
973                 error = dmu_free_long_range(os,
974                     ZVOL_OBJ, volsize, DMU_OBJECT_END);
975         return (error);
976 }
977
978 void
979 zvol_remove_minors(const char *name)
980 {
981 #ifdef illumos
982         zvol_state_t *zv;
983         char *namebuf;
984         minor_t minor;
985
986         namebuf = kmem_zalloc(strlen(name) + 2, KM_SLEEP);
987         (void) strncpy(namebuf, name, strlen(name));
988         (void) strcat(namebuf, "/");
989         mutex_enter(&zfsdev_state_lock);
990         for (minor = 1; minor <= ZFSDEV_MAX_MINOR; minor++) {
991
992                 zv = zfsdev_get_soft_state(minor, ZSST_ZVOL);
993                 if (zv == NULL)
994                         continue;
995                 if (strncmp(namebuf, zv->zv_name, strlen(namebuf)) == 0)
996                         (void) zvol_remove_zv(zv);
997         }
998         kmem_free(namebuf, strlen(name) + 2);
999
1000         mutex_exit(&zfsdev_state_lock);
1001 #else   /* !illumos */
1002         zvol_state_t *zv, *tzv;
1003         size_t namelen;
1004
1005         namelen = strlen(name);
1006
1007         DROP_GIANT();
1008         mutex_enter(&zfsdev_state_lock);
1009
1010         LIST_FOREACH_SAFE(zv, &all_zvols, zv_links, tzv) {
1011                 if (strcmp(zv->zv_name, name) == 0 ||
1012                     (strncmp(zv->zv_name, name, namelen) == 0 &&
1013                     strlen(zv->zv_name) > namelen && (zv->zv_name[namelen] == '/' ||
1014                     zv->zv_name[namelen] == '@'))) {
1015                         (void) zvol_remove_zv(zv);
1016                 }
1017         }
1018
1019         mutex_exit(&zfsdev_state_lock);
1020         PICKUP_GIANT();
1021 #endif  /* illumos */
1022 }
1023
1024 static int
1025 zvol_update_live_volsize(zvol_state_t *zv, uint64_t volsize)
1026 {
1027         uint64_t old_volsize = 0ULL;
1028         int error = 0;
1029
1030         ASSERT(MUTEX_HELD(&zfsdev_state_lock));
1031
1032         /*
1033          * Reinitialize the dump area to the new size. If we
1034          * failed to resize the dump area then restore it back to
1035          * its original size.  We must set the new volsize prior
1036          * to calling dumpvp_resize() to ensure that the devices'
1037          * size(9P) is not visible by the dump subsystem.
1038          */
1039         old_volsize = zv->zv_volsize;
1040         zvol_size_changed(zv, volsize);
1041
1042 #ifdef ZVOL_DUMP
1043         if (zv->zv_flags & ZVOL_DUMPIFIED) {
1044                 if ((error = zvol_dumpify(zv)) != 0 ||
1045                     (error = dumpvp_resize()) != 0) {
1046                         int dumpify_error;
1047
1048                         (void) zvol_update_volsize(zv->zv_objset, old_volsize);
1049                         zvol_size_changed(zv, old_volsize);
1050                         dumpify_error = zvol_dumpify(zv);
1051                         error = dumpify_error ? dumpify_error : error;
1052                 }
1053         }
1054 #endif  /* ZVOL_DUMP */
1055
1056 #ifdef illumos
1057         /*
1058          * Generate a LUN expansion event.
1059          */
1060         if (error == 0) {
1061                 sysevent_id_t eid;
1062                 nvlist_t *attr;
1063                 char *physpath = kmem_zalloc(MAXPATHLEN, KM_SLEEP);
1064
1065                 (void) snprintf(physpath, MAXPATHLEN, "%s%u", ZVOL_PSEUDO_DEV,
1066                     zv->zv_minor);
1067
1068                 VERIFY(nvlist_alloc(&attr, NV_UNIQUE_NAME, KM_SLEEP) == 0);
1069                 VERIFY(nvlist_add_string(attr, DEV_PHYS_PATH, physpath) == 0);
1070
1071                 (void) ddi_log_sysevent(zfs_dip, SUNW_VENDOR, EC_DEV_STATUS,
1072                     ESC_DEV_DLE, attr, &eid, DDI_SLEEP);
1073
1074                 nvlist_free(attr);
1075                 kmem_free(physpath, MAXPATHLEN);
1076         }
1077 #endif  /* illumos */
1078         return (error);
1079 }
1080
1081 int
1082 zvol_set_volsize(const char *name, uint64_t volsize)
1083 {
1084         zvol_state_t *zv = NULL;
1085         objset_t *os;
1086         int error;
1087         dmu_object_info_t doi;
1088         uint64_t readonly;
1089         boolean_t owned = B_FALSE;
1090
1091         error = dsl_prop_get_integer(name,
1092             zfs_prop_to_name(ZFS_PROP_READONLY), &readonly, NULL);
1093         if (error != 0)
1094                 return (error);
1095         if (readonly)
1096                 return (SET_ERROR(EROFS));
1097
1098         mutex_enter(&zfsdev_state_lock);
1099         zv = zvol_minor_lookup(name);
1100
1101         if (zv == NULL || zv->zv_objset == NULL) {
1102                 if ((error = dmu_objset_own(name, DMU_OST_ZVOL, B_FALSE,
1103                     FTAG, &os)) != 0) {
1104                         mutex_exit(&zfsdev_state_lock);
1105                         return (error);
1106                 }
1107                 owned = B_TRUE;
1108                 if (zv != NULL)
1109                         zv->zv_objset = os;
1110         } else {
1111                 os = zv->zv_objset;
1112         }
1113
1114         if ((error = dmu_object_info(os, ZVOL_OBJ, &doi)) != 0 ||
1115             (error = zvol_check_volsize(volsize, doi.doi_data_block_size)) != 0)
1116                 goto out;
1117
1118         error = zvol_update_volsize(os, volsize);
1119
1120         if (error == 0 && zv != NULL)
1121                 error = zvol_update_live_volsize(zv, volsize);
1122 out:
1123         if (owned) {
1124                 dmu_objset_disown(os, FTAG);
1125                 if (zv != NULL)
1126                         zv->zv_objset = NULL;
1127         }
1128         mutex_exit(&zfsdev_state_lock);
1129         return (error);
1130 }
1131
1132 /*ARGSUSED*/
1133 #ifdef illumos
1134 int
1135 zvol_open(dev_t *devp, int flag, int otyp, cred_t *cr)
1136 #else
1137 static int
1138 zvol_open(struct g_provider *pp, int flag, int count)
1139 #endif
1140 {
1141         zvol_state_t *zv;
1142         int err = 0;
1143 #ifdef illumos
1144
1145         mutex_enter(&zfsdev_state_lock);
1146
1147         zv = zfsdev_get_soft_state(getminor(*devp), ZSST_ZVOL);
1148         if (zv == NULL) {
1149                 mutex_exit(&zfsdev_state_lock);
1150                 return (SET_ERROR(ENXIO));
1151         }
1152
1153         if (zv->zv_total_opens == 0)
1154                 err = zvol_first_open(zv);
1155         if (err) {
1156                 mutex_exit(&zfsdev_state_lock);
1157                 return (err);
1158         }
1159 #else   /* !illumos */
1160         boolean_t locked = B_FALSE;
1161
1162         if (!zpool_on_zvol && tsd_get(zfs_geom_probe_vdev_key) != NULL) {
1163                 /*
1164                  * if zfs_geom_probe_vdev_key is set, that means that zfs is
1165                  * attempting to probe geom providers while looking for a
1166                  * replacement for a missing VDEV.  In this case, the
1167                  * spa_namespace_lock will not be held, but it is still illegal
1168                  * to use a zvol as a vdev.  Deadlocks can result if another
1169                  * thread has spa_namespace_lock
1170                  */
1171                 return (EOPNOTSUPP);
1172         }
1173         /*
1174          * Protect against recursively entering spa_namespace_lock
1175          * when spa_open() is used for a pool on a (local) ZVOL(s).
1176          * This is needed since we replaced upstream zfsdev_state_lock
1177          * with spa_namespace_lock in the ZVOL code.
1178          * We are using the same trick as spa_open().
1179          * Note that calls in zvol_first_open which need to resolve
1180          * pool name to a spa object will enter spa_open()
1181          * recursively, but that function already has all the
1182          * necessary protection.
1183          */
1184         if (!MUTEX_HELD(&zfsdev_state_lock)) {
1185                 mutex_enter(&zfsdev_state_lock);
1186                 locked = B_TRUE;
1187         }
1188
1189         zv = pp->private;
1190         if (zv == NULL) {
1191                 if (locked)
1192                         mutex_exit(&zfsdev_state_lock);
1193                 return (SET_ERROR(ENXIO));
1194         }
1195
1196         if (zv->zv_total_opens == 0) {
1197                 err = zvol_first_open(zv);
1198                 if (err) {
1199                         if (locked)
1200                                 mutex_exit(&zfsdev_state_lock);
1201                         return (err);
1202                 }
1203                 pp->mediasize = zv->zv_volsize;
1204                 pp->stripeoffset = 0;
1205                 pp->stripesize = zv->zv_volblocksize;
1206         }
1207 #endif  /* illumos */
1208         if ((flag & FWRITE) && (zv->zv_flags & ZVOL_RDONLY)) {
1209                 err = SET_ERROR(EROFS);
1210                 goto out;
1211         }
1212         if (zv->zv_flags & ZVOL_EXCL) {
1213                 err = SET_ERROR(EBUSY);
1214                 goto out;
1215         }
1216 #ifdef FEXCL
1217         if (flag & FEXCL) {
1218                 if (zv->zv_total_opens != 0) {
1219                         err = SET_ERROR(EBUSY);
1220                         goto out;
1221                 }
1222                 zv->zv_flags |= ZVOL_EXCL;
1223         }
1224 #endif
1225
1226 #ifdef illumos
1227         if (zv->zv_open_count[otyp] == 0 || otyp == OTYP_LYR) {
1228                 zv->zv_open_count[otyp]++;
1229                 zv->zv_total_opens++;
1230         }
1231         mutex_exit(&zfsdev_state_lock);
1232 #else
1233         zv->zv_total_opens += count;
1234         if (locked)
1235                 mutex_exit(&zfsdev_state_lock);
1236 #endif
1237
1238         return (err);
1239 out:
1240         if (zv->zv_total_opens == 0)
1241                 zvol_last_close(zv);
1242 #ifdef illumos
1243         mutex_exit(&zfsdev_state_lock);
1244 #else
1245         if (locked)
1246                 mutex_exit(&zfsdev_state_lock);
1247 #endif
1248         return (err);
1249 }
1250
1251 /*ARGSUSED*/
1252 #ifdef illumos
1253 int
1254 zvol_close(dev_t dev, int flag, int otyp, cred_t *cr)
1255 {
1256         minor_t minor = getminor(dev);
1257         zvol_state_t *zv;
1258         int error = 0;
1259
1260         mutex_enter(&zfsdev_state_lock);
1261
1262         zv = zfsdev_get_soft_state(minor, ZSST_ZVOL);
1263         if (zv == NULL) {
1264                 mutex_exit(&zfsdev_state_lock);
1265 #else   /* !illumos */
1266 static int
1267 zvol_close(struct g_provider *pp, int flag, int count)
1268 {
1269         zvol_state_t *zv;
1270         int error = 0;
1271         boolean_t locked = B_FALSE;
1272
1273         /* See comment in zvol_open(). */
1274         if (!MUTEX_HELD(&zfsdev_state_lock)) {
1275                 mutex_enter(&zfsdev_state_lock);
1276                 locked = B_TRUE;
1277         }
1278
1279         zv = pp->private;
1280         if (zv == NULL) {
1281                 if (locked)
1282                         mutex_exit(&zfsdev_state_lock);
1283 #endif  /* illumos */
1284                 return (SET_ERROR(ENXIO));
1285         }
1286
1287         if (zv->zv_flags & ZVOL_EXCL) {
1288                 ASSERT(zv->zv_total_opens == 1);
1289                 zv->zv_flags &= ~ZVOL_EXCL;
1290         }
1291
1292         /*
1293          * If the open count is zero, this is a spurious close.
1294          * That indicates a bug in the kernel / DDI framework.
1295          */
1296 #ifdef illumos
1297         ASSERT(zv->zv_open_count[otyp] != 0);
1298 #endif
1299         ASSERT(zv->zv_total_opens != 0);
1300
1301         /*
1302          * You may get multiple opens, but only one close.
1303          */
1304 #ifdef illumos
1305         zv->zv_open_count[otyp]--;
1306         zv->zv_total_opens--;
1307 #else
1308         zv->zv_total_opens -= count;
1309 #endif
1310
1311         if (zv->zv_total_opens == 0)
1312                 zvol_last_close(zv);
1313
1314 #ifdef illumos
1315         mutex_exit(&zfsdev_state_lock);
1316 #else
1317         if (locked)
1318                 mutex_exit(&zfsdev_state_lock);
1319 #endif
1320         return (error);
1321 }
1322
1323 /* ARGSUSED */
1324 static void
1325 zvol_get_done(zgd_t *zgd, int error)
1326 {
1327         if (zgd->zgd_db)
1328                 dmu_buf_rele(zgd->zgd_db, zgd);
1329
1330         rangelock_exit(zgd->zgd_lr);
1331
1332         kmem_free(zgd, sizeof (zgd_t));
1333 }
1334
1335 /*
1336  * Get data to generate a TX_WRITE intent log record.
1337  */
1338 static int
1339 zvol_get_data(void *arg, lr_write_t *lr, char *buf, struct lwb *lwb, zio_t *zio)
1340 {
1341         zvol_state_t *zv = arg;
1342         uint64_t offset = lr->lr_offset;
1343         uint64_t size = lr->lr_length;  /* length of user data */
1344         dmu_buf_t *db;
1345         zgd_t *zgd;
1346         int error;
1347
1348         ASSERT3P(lwb, !=, NULL);
1349         ASSERT3P(zio, !=, NULL);
1350         ASSERT3U(size, !=, 0);
1351
1352         zgd = kmem_zalloc(sizeof (zgd_t), KM_SLEEP);
1353         zgd->zgd_lwb = lwb;
1354
1355         /*
1356          * Write records come in two flavors: immediate and indirect.
1357          * For small writes it's cheaper to store the data with the
1358          * log record (immediate); for large writes it's cheaper to
1359          * sync the data and get a pointer to it (indirect) so that
1360          * we don't have to write the data twice.
1361          */
1362         if (buf != NULL) { /* immediate write */
1363                 zgd->zgd_lr = rangelock_enter(&zv->zv_rangelock, offset, size,
1364                     RL_READER);
1365                 error = dmu_read_by_dnode(zv->zv_dn, offset, size, buf,
1366                     DMU_READ_NO_PREFETCH);
1367         } else { /* indirect write */
1368                 /*
1369                  * Have to lock the whole block to ensure when it's written out
1370                  * and its checksum is being calculated that no one can change
1371                  * the data. Contrarily to zfs_get_data we need not re-check
1372                  * blocksize after we get the lock because it cannot be changed.
1373                  */
1374                 size = zv->zv_volblocksize;
1375                 offset = P2ALIGN(offset, size);
1376                 zgd->zgd_lr = rangelock_enter(&zv->zv_rangelock, offset, size,
1377                     RL_READER);
1378                 error = dmu_buf_hold_by_dnode(zv->zv_dn, offset, zgd, &db,
1379                     DMU_READ_NO_PREFETCH);
1380                 if (error == 0) {
1381                         blkptr_t *bp = &lr->lr_blkptr;
1382
1383                         zgd->zgd_db = db;
1384                         zgd->zgd_bp = bp;
1385
1386                         ASSERT(db->db_offset == offset);
1387                         ASSERT(db->db_size == size);
1388
1389                         error = dmu_sync(zio, lr->lr_common.lrc_txg,
1390                             zvol_get_done, zgd);
1391
1392                         if (error == 0)
1393                                 return (0);
1394                 }
1395         }
1396
1397         zvol_get_done(zgd, error);
1398
1399         return (error);
1400 }
1401
1402 /*
1403  * zvol_log_write() handles synchronous writes using TX_WRITE ZIL transactions.
1404  *
1405  * We store data in the log buffers if it's small enough.
1406  * Otherwise we will later flush the data out via dmu_sync().
1407  */
1408 ssize_t zvol_immediate_write_sz = 32768;
1409 #ifdef _KERNEL
1410 SYSCTL_LONG(_vfs_zfs_vol, OID_AUTO, immediate_write_sz, CTLFLAG_RWTUN,
1411     &zvol_immediate_write_sz, 0, "Minimal size for indirect log write");
1412 #endif
1413
1414 static void
1415 zvol_log_write(zvol_state_t *zv, dmu_tx_t *tx, offset_t off, ssize_t resid,
1416     boolean_t sync)
1417 {
1418         uint32_t blocksize = zv->zv_volblocksize;
1419         zilog_t *zilog = zv->zv_zilog;
1420         itx_wr_state_t write_state;
1421
1422         if (zil_replaying(zilog, tx))
1423                 return;
1424
1425         if (zilog->zl_logbias == ZFS_LOGBIAS_THROUGHPUT)
1426                 write_state = WR_INDIRECT;
1427         else if (!spa_has_slogs(zilog->zl_spa) &&
1428             resid >= blocksize && blocksize > zvol_immediate_write_sz)
1429                 write_state = WR_INDIRECT;
1430         else if (sync)
1431                 write_state = WR_COPIED;
1432         else
1433                 write_state = WR_NEED_COPY;
1434
1435         while (resid) {
1436                 itx_t *itx;
1437                 lr_write_t *lr;
1438                 itx_wr_state_t wr_state = write_state;
1439                 ssize_t len = resid;
1440
1441                 if (wr_state == WR_COPIED && resid > zil_max_copied_data(zilog))
1442                         wr_state = WR_NEED_COPY;
1443                 else if (wr_state == WR_INDIRECT)
1444                         len = MIN(blocksize - P2PHASE(off, blocksize), resid);
1445
1446                 itx = zil_itx_create(TX_WRITE, sizeof (*lr) +
1447                     (wr_state == WR_COPIED ? len : 0));
1448                 lr = (lr_write_t *)&itx->itx_lr;
1449                 if (wr_state == WR_COPIED && dmu_read_by_dnode(zv->zv_dn,
1450                     off, len, lr + 1, DMU_READ_NO_PREFETCH) != 0) {
1451                         zil_itx_destroy(itx);
1452                         itx = zil_itx_create(TX_WRITE, sizeof (*lr));
1453                         lr = (lr_write_t *)&itx->itx_lr;
1454                         wr_state = WR_NEED_COPY;
1455                 }
1456
1457                 itx->itx_wr_state = wr_state;
1458                 lr->lr_foid = ZVOL_OBJ;
1459                 lr->lr_offset = off;
1460                 lr->lr_length = len;
1461                 lr->lr_blkoff = 0;
1462                 BP_ZERO(&lr->lr_blkptr);
1463
1464                 itx->itx_private = zv;
1465
1466                 if (!sync && (zv->zv_sync_cnt == 0))
1467                         itx->itx_sync = B_FALSE;
1468
1469                 zil_itx_assign(zilog, itx, tx);
1470
1471                 off += len;
1472                 resid -= len;
1473         }
1474 }
1475
1476 #ifdef illumos
1477 static int
1478 zvol_dumpio_vdev(vdev_t *vd, void *addr, uint64_t offset, uint64_t origoffset,
1479     uint64_t size, boolean_t doread, boolean_t isdump)
1480 {
1481         vdev_disk_t *dvd;
1482         int c;
1483         int numerrors = 0;
1484
1485         if (vd->vdev_ops == &vdev_mirror_ops ||
1486             vd->vdev_ops == &vdev_replacing_ops ||
1487             vd->vdev_ops == &vdev_spare_ops) {
1488                 for (c = 0; c < vd->vdev_children; c++) {
1489                         int err = zvol_dumpio_vdev(vd->vdev_child[c],
1490                             addr, offset, origoffset, size, doread, isdump);
1491                         if (err != 0) {
1492                                 numerrors++;
1493                         } else if (doread) {
1494                                 break;
1495                         }
1496                 }
1497         }
1498
1499         if (!vd->vdev_ops->vdev_op_leaf && vd->vdev_ops != &vdev_raidz_ops)
1500                 return (numerrors < vd->vdev_children ? 0 : EIO);
1501
1502         if (doread && !vdev_readable(vd))
1503                 return (SET_ERROR(EIO));
1504         else if (!doread && !vdev_writeable(vd))
1505                 return (SET_ERROR(EIO));
1506
1507         if (vd->vdev_ops == &vdev_raidz_ops) {
1508                 return (vdev_raidz_physio(vd,
1509                     addr, size, offset, origoffset, doread, isdump));
1510         }
1511
1512         offset += VDEV_LABEL_START_SIZE;
1513
1514         if (ddi_in_panic() || isdump) {
1515                 ASSERT(!doread);
1516                 if (doread)
1517                         return (SET_ERROR(EIO));
1518                 dvd = vd->vdev_tsd;
1519                 ASSERT3P(dvd, !=, NULL);
1520                 return (ldi_dump(dvd->vd_lh, addr, lbtodb(offset),
1521                     lbtodb(size)));
1522         } else {
1523                 dvd = vd->vdev_tsd;
1524                 ASSERT3P(dvd, !=, NULL);
1525                 return (vdev_disk_ldi_physio(dvd->vd_lh, addr, size,
1526                     offset, doread ? B_READ : B_WRITE));
1527         }
1528 }
1529
1530 static int
1531 zvol_dumpio(zvol_state_t *zv, void *addr, uint64_t offset, uint64_t size,
1532     boolean_t doread, boolean_t isdump)
1533 {
1534         vdev_t *vd;
1535         int error;
1536         zvol_extent_t *ze;
1537         spa_t *spa = dmu_objset_spa(zv->zv_objset);
1538
1539         /* Must be sector aligned, and not stradle a block boundary. */
1540         if (P2PHASE(offset, DEV_BSIZE) || P2PHASE(size, DEV_BSIZE) ||
1541             P2BOUNDARY(offset, size, zv->zv_volblocksize)) {
1542                 return (SET_ERROR(EINVAL));
1543         }
1544         ASSERT(size <= zv->zv_volblocksize);
1545
1546         /* Locate the extent this belongs to */
1547         ze = list_head(&zv->zv_extents);
1548         while (offset >= ze->ze_nblks * zv->zv_volblocksize) {
1549                 offset -= ze->ze_nblks * zv->zv_volblocksize;
1550                 ze = list_next(&zv->zv_extents, ze);
1551         }
1552
1553         if (ze == NULL)
1554                 return (SET_ERROR(EINVAL));
1555
1556         if (!ddi_in_panic())
1557                 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
1558
1559         vd = vdev_lookup_top(spa, DVA_GET_VDEV(&ze->ze_dva));
1560         offset += DVA_GET_OFFSET(&ze->ze_dva);
1561         error = zvol_dumpio_vdev(vd, addr, offset, DVA_GET_OFFSET(&ze->ze_dva),
1562             size, doread, isdump);
1563
1564         if (!ddi_in_panic())
1565                 spa_config_exit(spa, SCL_STATE, FTAG);
1566
1567         return (error);
1568 }
1569
1570 int
1571 zvol_strategy(buf_t *bp)
1572 {
1573         zfs_soft_state_t *zs = NULL;
1574 #else   /* !illumos */
1575 void
1576 zvol_strategy(struct bio *bp)
1577 {
1578 #endif  /* illumos */
1579         zvol_state_t *zv;
1580         uint64_t off, volsize;
1581         size_t resid;
1582         char *addr;
1583         objset_t *os;
1584         int error = 0;
1585 #ifdef illumos
1586         boolean_t doread = bp->b_flags & B_READ;
1587 #else
1588         boolean_t doread = 0;
1589 #endif
1590         boolean_t is_dumpified;
1591         boolean_t sync;
1592
1593 #ifdef illumos
1594         if (getminor(bp->b_edev) == 0) {
1595                 error = SET_ERROR(EINVAL);
1596         } else {
1597                 zs = ddi_get_soft_state(zfsdev_state, getminor(bp->b_edev));
1598                 if (zs == NULL)
1599                         error = SET_ERROR(ENXIO);
1600                 else if (zs->zss_type != ZSST_ZVOL)
1601                         error = SET_ERROR(EINVAL);
1602         }
1603
1604         if (error) {
1605                 bioerror(bp, error);
1606                 biodone(bp);
1607                 return (0);
1608         }
1609
1610         zv = zs->zss_data;
1611
1612         if (!(bp->b_flags & B_READ) && (zv->zv_flags & ZVOL_RDONLY)) {
1613                 bioerror(bp, EROFS);
1614                 biodone(bp);
1615                 return (0);
1616         }
1617
1618         off = ldbtob(bp->b_blkno);
1619 #else   /* !illumos */
1620         if (bp->bio_to)
1621                 zv = bp->bio_to->private;
1622         else
1623                 zv = bp->bio_dev->si_drv2;
1624
1625         if (zv == NULL) {
1626                 error = SET_ERROR(ENXIO);
1627                 goto out;
1628         }
1629
1630         if (bp->bio_cmd != BIO_READ && (zv->zv_flags & ZVOL_RDONLY)) {
1631                 error = SET_ERROR(EROFS);
1632                 goto out;
1633         }
1634
1635         switch (bp->bio_cmd) {
1636         case BIO_FLUSH:
1637                 goto sync;
1638         case BIO_READ:
1639                 doread = 1;
1640         case BIO_WRITE:
1641         case BIO_DELETE:
1642                 break;
1643         default:
1644                 error = EOPNOTSUPP;
1645                 goto out;
1646         }
1647
1648         off = bp->bio_offset;
1649 #endif  /* illumos */
1650         volsize = zv->zv_volsize;
1651
1652         os = zv->zv_objset;
1653         ASSERT(os != NULL);
1654
1655 #ifdef illumos
1656         bp_mapin(bp);
1657         addr = bp->b_un.b_addr;
1658         resid = bp->b_bcount;
1659
1660         if (resid > 0 && (off < 0 || off >= volsize)) {
1661                 bioerror(bp, EIO);
1662                 biodone(bp);
1663                 return (0);
1664         }
1665
1666         is_dumpified = zv->zv_flags & ZVOL_DUMPIFIED;
1667         sync = ((!(bp->b_flags & B_ASYNC) &&
1668             !(zv->zv_flags & ZVOL_WCE)) ||
1669             (zv->zv_objset->os_sync == ZFS_SYNC_ALWAYS)) &&
1670             !doread && !is_dumpified;
1671 #else   /* !illumos */
1672         addr = bp->bio_data;
1673         resid = bp->bio_length;
1674
1675         if (resid > 0 && (off < 0 || off >= volsize)) {
1676                 error = SET_ERROR(EIO);
1677                 goto out;
1678         }
1679
1680         is_dumpified = B_FALSE;
1681         sync = !doread && !is_dumpified &&
1682             zv->zv_objset->os_sync == ZFS_SYNC_ALWAYS;
1683 #endif  /* illumos */
1684
1685         /*
1686          * There must be no buffer changes when doing a dmu_sync() because
1687          * we can't change the data whilst calculating the checksum.
1688          */
1689         locked_range_t *lr = rangelock_enter(&zv->zv_rangelock, off, resid,
1690             doread ? RL_READER : RL_WRITER);
1691
1692 #ifndef illumos
1693         if (bp->bio_cmd == BIO_DELETE) {
1694                 dmu_tx_t *tx = dmu_tx_create(zv->zv_objset);
1695                 error = dmu_tx_assign(tx, TXG_WAIT);
1696                 if (error != 0) {
1697                         dmu_tx_abort(tx);
1698                 } else {
1699                         zvol_log_truncate(zv, tx, off, resid, sync);
1700                         dmu_tx_commit(tx);
1701                         error = dmu_free_long_range(zv->zv_objset, ZVOL_OBJ,
1702                             off, resid);
1703                         resid = 0;
1704                 }
1705                 goto unlock;
1706         }
1707 #endif
1708         while (resid != 0 && off < volsize) {
1709                 size_t size = MIN(resid, zvol_maxphys);
1710 #ifdef illumos
1711                 if (is_dumpified) {
1712                         size = MIN(size, P2END(off, zv->zv_volblocksize) - off);
1713                         error = zvol_dumpio(zv, addr, off, size,
1714                             doread, B_FALSE);
1715                 } else if (doread) {
1716 #else
1717                 if (doread) {
1718 #endif
1719                         error = dmu_read(os, ZVOL_OBJ, off, size, addr,
1720                             DMU_READ_PREFETCH);
1721                 } else {
1722                         dmu_tx_t *tx = dmu_tx_create(os);
1723                         dmu_tx_hold_write(tx, ZVOL_OBJ, off, size);
1724                         error = dmu_tx_assign(tx, TXG_WAIT);
1725                         if (error) {
1726                                 dmu_tx_abort(tx);
1727                         } else {
1728                                 dmu_write(os, ZVOL_OBJ, off, size, addr, tx);
1729                                 zvol_log_write(zv, tx, off, size, sync);
1730                                 dmu_tx_commit(tx);
1731                         }
1732                 }
1733                 if (error) {
1734                         /* convert checksum errors into IO errors */
1735                         if (error == ECKSUM)
1736                                 error = SET_ERROR(EIO);
1737                         break;
1738                 }
1739                 off += size;
1740                 addr += size;
1741                 resid -= size;
1742         }
1743 #ifndef illumos
1744 unlock:
1745 #endif
1746         rangelock_exit(lr);
1747
1748 #ifdef illumos
1749         if ((bp->b_resid = resid) == bp->b_bcount)
1750                 bioerror(bp, off > volsize ? EINVAL : error);
1751
1752         if (sync)
1753                 zil_commit(zv->zv_zilog, ZVOL_OBJ);
1754         biodone(bp);
1755
1756         return (0);
1757 #else   /* !illumos */
1758         bp->bio_completed = bp->bio_length - resid;
1759         if (bp->bio_completed < bp->bio_length && off > volsize)
1760                 error = EINVAL;
1761
1762         if (sync) {
1763 sync:
1764                 zil_commit(zv->zv_zilog, ZVOL_OBJ);
1765         }
1766 out:
1767         if (bp->bio_to)
1768                 g_io_deliver(bp, error);
1769         else
1770                 biofinish(bp, NULL, error);
1771 #endif  /* illumos */
1772 }
1773
1774 #ifdef illumos
1775 /*
1776  * Set the buffer count to the zvol maximum transfer.
1777  * Using our own routine instead of the default minphys()
1778  * means that for larger writes we write bigger buffers on X86
1779  * (128K instead of 56K) and flush the disk write cache less often
1780  * (every zvol_maxphys - currently 1MB) instead of minphys (currently
1781  * 56K on X86 and 128K on sparc).
1782  */
1783 void
1784 zvol_minphys(struct buf *bp)
1785 {
1786         if (bp->b_bcount > zvol_maxphys)
1787                 bp->b_bcount = zvol_maxphys;
1788 }
1789
1790 int
1791 zvol_dump(dev_t dev, caddr_t addr, daddr_t blkno, int nblocks)
1792 {
1793         minor_t minor = getminor(dev);
1794         zvol_state_t *zv;
1795         int error = 0;
1796         uint64_t size;
1797         uint64_t boff;
1798         uint64_t resid;
1799
1800         zv = zfsdev_get_soft_state(minor, ZSST_ZVOL);
1801         if (zv == NULL)
1802                 return (SET_ERROR(ENXIO));
1803
1804         if ((zv->zv_flags & ZVOL_DUMPIFIED) == 0)
1805                 return (SET_ERROR(EINVAL));
1806
1807         boff = ldbtob(blkno);
1808         resid = ldbtob(nblocks);
1809
1810         VERIFY3U(boff + resid, <=, zv->zv_volsize);
1811
1812         while (resid) {
1813                 size = MIN(resid, P2END(boff, zv->zv_volblocksize) - boff);
1814                 error = zvol_dumpio(zv, addr, boff, size, B_FALSE, B_TRUE);
1815                 if (error)
1816                         break;
1817                 boff += size;
1818                 addr += size;
1819                 resid -= size;
1820         }
1821
1822         return (error);
1823 }
1824
1825 /*ARGSUSED*/
1826 int
1827 zvol_read(dev_t dev, uio_t *uio, cred_t *cr)
1828 {
1829         minor_t minor = getminor(dev);
1830 #else   /* !illumos */
1831 int
1832 zvol_read(struct cdev *dev, struct uio *uio, int ioflag)
1833 {
1834 #endif  /* illumos */
1835         zvol_state_t *zv;
1836         uint64_t volsize;
1837         int error = 0;
1838
1839 #ifdef illumos
1840         zv = zfsdev_get_soft_state(minor, ZSST_ZVOL);
1841         if (zv == NULL)
1842                 return (SET_ERROR(ENXIO));
1843 #else
1844         zv = dev->si_drv2;
1845 #endif
1846
1847         volsize = zv->zv_volsize;
1848         /* uio_loffset == volsize isn't an error as its required for EOF processing. */
1849         if (uio->uio_resid > 0 &&
1850             (uio->uio_loffset < 0 || uio->uio_loffset > volsize))
1851                 return (SET_ERROR(EIO));
1852
1853 #ifdef illumos
1854         if (zv->zv_flags & ZVOL_DUMPIFIED) {
1855                 error = physio(zvol_strategy, NULL, dev, B_READ,
1856                     zvol_minphys, uio);
1857                 return (error);
1858         }
1859 #endif
1860
1861         locked_range_t *lr = rangelock_enter(&zv->zv_rangelock,
1862             uio->uio_loffset, uio->uio_resid, RL_READER);
1863         while (uio->uio_resid > 0 && uio->uio_loffset < volsize) {
1864                 uint64_t bytes = MIN(uio->uio_resid, DMU_MAX_ACCESS >> 1);
1865
1866                 /* don't read past the end */
1867                 if (bytes > volsize - uio->uio_loffset)
1868                         bytes = volsize - uio->uio_loffset;
1869
1870                 error =  dmu_read_uio_dnode(zv->zv_dn, uio, bytes);
1871                 if (error) {
1872                         /* convert checksum errors into IO errors */
1873                         if (error == ECKSUM)
1874                                 error = SET_ERROR(EIO);
1875                         break;
1876                 }
1877         }
1878         rangelock_exit(lr);
1879
1880         return (error);
1881 }
1882
1883 #ifdef illumos
1884 /*ARGSUSED*/
1885 int
1886 zvol_write(dev_t dev, uio_t *uio, cred_t *cr)
1887 {
1888         minor_t minor = getminor(dev);
1889 #else   /* !illumos */
1890 int
1891 zvol_write(struct cdev *dev, struct uio *uio, int ioflag)
1892 {
1893 #endif  /* illumos */
1894         zvol_state_t *zv;
1895         uint64_t volsize;
1896         int error = 0;
1897         boolean_t sync;
1898
1899 #ifdef illumos
1900         zv = zfsdev_get_soft_state(minor, ZSST_ZVOL);
1901         if (zv == NULL)
1902                 return (SET_ERROR(ENXIO));
1903 #else
1904         zv = dev->si_drv2;
1905 #endif
1906
1907         volsize = zv->zv_volsize;
1908         /* uio_loffset == volsize isn't an error as its required for EOF processing. */
1909         if (uio->uio_resid > 0 &&
1910             (uio->uio_loffset < 0 || uio->uio_loffset > volsize))
1911                 return (SET_ERROR(EIO));
1912
1913 #ifdef illumos
1914         if (zv->zv_flags & ZVOL_DUMPIFIED) {
1915                 error = physio(zvol_strategy, NULL, dev, B_WRITE,
1916                     zvol_minphys, uio);
1917                 return (error);
1918         }
1919
1920         sync = !(zv->zv_flags & ZVOL_WCE) ||
1921 #else
1922         sync = (ioflag & IO_SYNC) ||
1923 #endif
1924             (zv->zv_objset->os_sync == ZFS_SYNC_ALWAYS);
1925
1926         locked_range_t *lr = rangelock_enter(&zv->zv_rangelock,
1927             uio->uio_loffset, uio->uio_resid, RL_WRITER);
1928         while (uio->uio_resid > 0 && uio->uio_loffset < volsize) {
1929                 uint64_t bytes = MIN(uio->uio_resid, DMU_MAX_ACCESS >> 1);
1930                 uint64_t off = uio->uio_loffset;
1931                 dmu_tx_t *tx = dmu_tx_create(zv->zv_objset);
1932
1933                 if (bytes > volsize - off)      /* don't write past the end */
1934                         bytes = volsize - off;
1935
1936                 dmu_tx_hold_write(tx, ZVOL_OBJ, off, bytes);
1937                 error = dmu_tx_assign(tx, TXG_WAIT);
1938                 if (error) {
1939                         dmu_tx_abort(tx);
1940                         break;
1941                 }
1942                 error = dmu_write_uio_dnode(zv->zv_dn, uio, bytes, tx);
1943                 if (error == 0)
1944                         zvol_log_write(zv, tx, off, bytes, sync);
1945                 dmu_tx_commit(tx);
1946
1947                 if (error)
1948                         break;
1949         }
1950         rangelock_exit(lr);
1951
1952         if (sync)
1953                 zil_commit(zv->zv_zilog, ZVOL_OBJ);
1954         return (error);
1955 }
1956
1957 #ifdef illumos
1958 int
1959 zvol_getefi(void *arg, int flag, uint64_t vs, uint8_t bs)
1960 {
1961         struct uuid uuid = EFI_RESERVED;
1962         efi_gpe_t gpe = { 0 };
1963         uint32_t crc;
1964         dk_efi_t efi;
1965         int length;
1966         char *ptr;
1967
1968         if (ddi_copyin(arg, &efi, sizeof (dk_efi_t), flag))
1969                 return (SET_ERROR(EFAULT));
1970         ptr = (char *)(uintptr_t)efi.dki_data_64;
1971         length = efi.dki_length;
1972         /*
1973          * Some clients may attempt to request a PMBR for the
1974          * zvol.  Currently this interface will return EINVAL to
1975          * such requests.  These requests could be supported by
1976          * adding a check for lba == 0 and consing up an appropriate
1977          * PMBR.
1978          */
1979         if (efi.dki_lba < 1 || efi.dki_lba > 2 || length <= 0)
1980                 return (SET_ERROR(EINVAL));
1981
1982         gpe.efi_gpe_StartingLBA = LE_64(34ULL);
1983         gpe.efi_gpe_EndingLBA = LE_64((vs >> bs) - 1);
1984         UUID_LE_CONVERT(gpe.efi_gpe_PartitionTypeGUID, uuid);
1985
1986         if (efi.dki_lba == 1) {
1987                 efi_gpt_t gpt = { 0 };
1988
1989                 gpt.efi_gpt_Signature = LE_64(EFI_SIGNATURE);
1990                 gpt.efi_gpt_Revision = LE_32(EFI_VERSION_CURRENT);
1991                 gpt.efi_gpt_HeaderSize = LE_32(sizeof (gpt));
1992                 gpt.efi_gpt_MyLBA = LE_64(1ULL);
1993                 gpt.efi_gpt_FirstUsableLBA = LE_64(34ULL);
1994                 gpt.efi_gpt_LastUsableLBA = LE_64((vs >> bs) - 1);
1995                 gpt.efi_gpt_PartitionEntryLBA = LE_64(2ULL);
1996                 gpt.efi_gpt_NumberOfPartitionEntries = LE_32(1);
1997                 gpt.efi_gpt_SizeOfPartitionEntry =
1998                     LE_32(sizeof (efi_gpe_t));
1999                 CRC32(crc, &gpe, sizeof (gpe), -1U, crc32_table);
2000                 gpt.efi_gpt_PartitionEntryArrayCRC32 = LE_32(~crc);
2001                 CRC32(crc, &gpt, sizeof (gpt), -1U, crc32_table);
2002                 gpt.efi_gpt_HeaderCRC32 = LE_32(~crc);
2003                 if (ddi_copyout(&gpt, ptr, MIN(sizeof (gpt), length),
2004                     flag))
2005                         return (SET_ERROR(EFAULT));
2006                 ptr += sizeof (gpt);
2007                 length -= sizeof (gpt);
2008         }
2009         if (length > 0 && ddi_copyout(&gpe, ptr, MIN(sizeof (gpe),
2010             length), flag))
2011                 return (SET_ERROR(EFAULT));
2012         return (0);
2013 }
2014
2015 /*
2016  * BEGIN entry points to allow external callers access to the volume.
2017  */
2018 /*
2019  * Return the volume parameters needed for access from an external caller.
2020  * These values are invariant as long as the volume is held open.
2021  */
2022 int
2023 zvol_get_volume_params(minor_t minor, uint64_t *blksize,
2024     uint64_t *max_xfer_len, void **minor_hdl, void **objset_hdl, void **zil_hdl,
2025     void **rl_hdl, void **dnode_hdl)
2026 {
2027         zvol_state_t *zv;
2028
2029         zv = zfsdev_get_soft_state(minor, ZSST_ZVOL);
2030         if (zv == NULL)
2031                 return (SET_ERROR(ENXIO));
2032         if (zv->zv_flags & ZVOL_DUMPIFIED)
2033                 return (SET_ERROR(ENXIO));
2034
2035         ASSERT(blksize && max_xfer_len && minor_hdl &&
2036             objset_hdl && zil_hdl && rl_hdl && dnode_hdl);
2037
2038         *blksize = zv->zv_volblocksize;
2039         *max_xfer_len = (uint64_t)zvol_maxphys;
2040         *minor_hdl = zv;
2041         *objset_hdl = zv->zv_objset;
2042         *zil_hdl = zv->zv_zilog;
2043         *rl_hdl = &zv->zv_rangelock;
2044         *dnode_hdl = zv->zv_dn;
2045         return (0);
2046 }
2047
2048 /*
2049  * Return the current volume size to an external caller.
2050  * The size can change while the volume is open.
2051  */
2052 uint64_t
2053 zvol_get_volume_size(void *minor_hdl)
2054 {
2055         zvol_state_t *zv = minor_hdl;
2056
2057         return (zv->zv_volsize);
2058 }
2059
2060 /*
2061  * Return the current WCE setting to an external caller.
2062  * The WCE setting can change while the volume is open.
2063  */
2064 int
2065 zvol_get_volume_wce(void *minor_hdl)
2066 {
2067         zvol_state_t *zv = minor_hdl;
2068
2069         return ((zv->zv_flags & ZVOL_WCE) ? 1 : 0);
2070 }
2071
2072 /*
2073  * Entry point for external callers to zvol_log_write
2074  */
2075 void
2076 zvol_log_write_minor(void *minor_hdl, dmu_tx_t *tx, offset_t off, ssize_t resid,
2077     boolean_t sync)
2078 {
2079         zvol_state_t *zv = minor_hdl;
2080
2081         zvol_log_write(zv, tx, off, resid, sync);
2082 }
2083 /*
2084  * END entry points to allow external callers access to the volume.
2085  */
2086 #endif  /* illumos */
2087
2088 /*
2089  * Log a DKIOCFREE/free-long-range to the ZIL with TX_TRUNCATE.
2090  */
2091 static void
2092 zvol_log_truncate(zvol_state_t *zv, dmu_tx_t *tx, uint64_t off, uint64_t len,
2093     boolean_t sync)
2094 {
2095         itx_t *itx;
2096         lr_truncate_t *lr;
2097         zilog_t *zilog = zv->zv_zilog;
2098
2099         if (zil_replaying(zilog, tx))
2100                 return;
2101
2102         itx = zil_itx_create(TX_TRUNCATE, sizeof (*lr));
2103         lr = (lr_truncate_t *)&itx->itx_lr;
2104         lr->lr_foid = ZVOL_OBJ;
2105         lr->lr_offset = off;
2106         lr->lr_length = len;
2107
2108         itx->itx_sync = (sync || zv->zv_sync_cnt != 0);
2109         zil_itx_assign(zilog, itx, tx);
2110 }
2111
2112 #ifdef illumos
2113 /*
2114  * Dirtbag ioctls to support mkfs(1M) for UFS filesystems.  See dkio(7I).
2115  * Also a dirtbag dkio ioctl for unmap/free-block functionality.
2116  */
2117 /*ARGSUSED*/
2118 int
2119 zvol_ioctl(dev_t dev, int cmd, intptr_t arg, int flag, cred_t *cr, int *rvalp)
2120 {
2121         zvol_state_t *zv;
2122         struct dk_callback *dkc;
2123         int error = 0;
2124         locked_range_t *lr;
2125
2126         mutex_enter(&zfsdev_state_lock);
2127
2128         zv = zfsdev_get_soft_state(getminor(dev), ZSST_ZVOL);
2129
2130         if (zv == NULL) {
2131                 mutex_exit(&zfsdev_state_lock);
2132                 return (SET_ERROR(ENXIO));
2133         }
2134         ASSERT(zv->zv_total_opens > 0);
2135
2136         switch (cmd) {
2137
2138         case DKIOCINFO:
2139         {
2140                 struct dk_cinfo dki;
2141
2142                 bzero(&dki, sizeof (dki));
2143                 (void) strcpy(dki.dki_cname, "zvol");
2144                 (void) strcpy(dki.dki_dname, "zvol");
2145                 dki.dki_ctype = DKC_UNKNOWN;
2146                 dki.dki_unit = getminor(dev);
2147                 dki.dki_maxtransfer =
2148                     1 << (SPA_OLD_MAXBLOCKSHIFT - zv->zv_min_bs);
2149                 mutex_exit(&zfsdev_state_lock);
2150                 if (ddi_copyout(&dki, (void *)arg, sizeof (dki), flag))
2151                         error = SET_ERROR(EFAULT);
2152                 return (error);
2153         }
2154
2155         case DKIOCGMEDIAINFO:
2156         {
2157                 struct dk_minfo dkm;
2158
2159                 bzero(&dkm, sizeof (dkm));
2160                 dkm.dki_lbsize = 1U << zv->zv_min_bs;
2161                 dkm.dki_capacity = zv->zv_volsize >> zv->zv_min_bs;
2162                 dkm.dki_media_type = DK_UNKNOWN;
2163                 mutex_exit(&zfsdev_state_lock);
2164                 if (ddi_copyout(&dkm, (void *)arg, sizeof (dkm), flag))
2165                         error = SET_ERROR(EFAULT);
2166                 return (error);
2167         }
2168
2169         case DKIOCGMEDIAINFOEXT:
2170         {
2171                 struct dk_minfo_ext dkmext;
2172
2173                 bzero(&dkmext, sizeof (dkmext));
2174                 dkmext.dki_lbsize = 1U << zv->zv_min_bs;
2175                 dkmext.dki_pbsize = zv->zv_volblocksize;
2176                 dkmext.dki_capacity = zv->zv_volsize >> zv->zv_min_bs;
2177                 dkmext.dki_media_type = DK_UNKNOWN;
2178                 mutex_exit(&zfsdev_state_lock);
2179                 if (ddi_copyout(&dkmext, (void *)arg, sizeof (dkmext), flag))
2180                         error = SET_ERROR(EFAULT);
2181                 return (error);
2182         }
2183
2184         case DKIOCGETEFI:
2185         {
2186                 uint64_t vs = zv->zv_volsize;
2187                 uint8_t bs = zv->zv_min_bs;
2188
2189                 mutex_exit(&zfsdev_state_lock);
2190                 error = zvol_getefi((void *)arg, flag, vs, bs);
2191                 return (error);
2192         }
2193
2194         case DKIOCFLUSHWRITECACHE:
2195                 dkc = (struct dk_callback *)arg;
2196                 mutex_exit(&zfsdev_state_lock);
2197                 zil_commit(zv->zv_zilog, ZVOL_OBJ);
2198                 if ((flag & FKIOCTL) && dkc != NULL && dkc->dkc_callback) {
2199                         (*dkc->dkc_callback)(dkc->dkc_cookie, error);
2200                         error = 0;
2201                 }
2202                 return (error);
2203
2204         case DKIOCGETWCE:
2205         {
2206                 int wce = (zv->zv_flags & ZVOL_WCE) ? 1 : 0;
2207                 if (ddi_copyout(&wce, (void *)arg, sizeof (int),
2208                     flag))
2209                         error = SET_ERROR(EFAULT);
2210                 break;
2211         }
2212         case DKIOCSETWCE:
2213         {
2214                 int wce;
2215                 if (ddi_copyin((void *)arg, &wce, sizeof (int),
2216                     flag)) {
2217                         error = SET_ERROR(EFAULT);
2218                         break;
2219                 }
2220                 if (wce) {
2221                         zv->zv_flags |= ZVOL_WCE;
2222                         mutex_exit(&zfsdev_state_lock);
2223                 } else {
2224                         zv->zv_flags &= ~ZVOL_WCE;
2225                         mutex_exit(&zfsdev_state_lock);
2226                         zil_commit(zv->zv_zilog, ZVOL_OBJ);
2227                 }
2228                 return (0);
2229         }
2230
2231         case DKIOCGGEOM:
2232         case DKIOCGVTOC:
2233                 /*
2234                  * commands using these (like prtvtoc) expect ENOTSUP
2235                  * since we're emulating an EFI label
2236                  */
2237                 error = SET_ERROR(ENOTSUP);
2238                 break;
2239
2240         case DKIOCDUMPINIT:
2241                 lr = rangelock_enter(&zv->zv_rangelock, 0, zv->zv_volsize,
2242                     RL_WRITER);
2243                 error = zvol_dumpify(zv);
2244                 rangelock_exit(lr);
2245                 break;
2246
2247         case DKIOCDUMPFINI:
2248                 if (!(zv->zv_flags & ZVOL_DUMPIFIED))
2249                         break;
2250                 lr = rangelock_enter(&zv->zv_rangelock, 0, zv->zv_volsize,
2251                     RL_WRITER);
2252                 error = zvol_dump_fini(zv);
2253                 rangelock_exit(lr);
2254                 break;
2255
2256         case DKIOCFREE:
2257         {
2258                 dkioc_free_list_t *dfl;
2259                 dmu_tx_t *tx;
2260
2261                 if (!zvol_unmap_enabled)
2262                         break;
2263
2264                 if (!(flag & FKIOCTL)) {
2265                         error = dfl_copyin((void *)arg, &dfl, flag, KM_SLEEP);
2266                         if (error != 0)
2267                                 break;
2268                 } else {
2269                         dfl = (dkioc_free_list_t *)arg;
2270                         ASSERT3U(dfl->dfl_num_exts, <=, DFL_COPYIN_MAX_EXTS);
2271                         if (dfl->dfl_num_exts > DFL_COPYIN_MAX_EXTS) {
2272                                 error = SET_ERROR(EINVAL);
2273                                 break;
2274                         }
2275                 }
2276
2277                 mutex_exit(&zfsdev_state_lock);
2278
2279                 for (int i = 0; i < dfl->dfl_num_exts; i++) {
2280                         uint64_t start = dfl->dfl_exts[i].dfle_start,
2281                             length = dfl->dfl_exts[i].dfle_length,
2282                             end = start + length;
2283
2284                         /*
2285                          * Apply Postel's Law to length-checking.  If they
2286                          * overshoot, just blank out until the end, if there's
2287                          * a need to blank out anything.
2288                          */
2289                         if (start >= zv->zv_volsize)
2290                                 continue;       /* No need to do anything... */
2291                         if (end > zv->zv_volsize) {
2292                                 end = DMU_OBJECT_END;
2293                                 length = end - start;
2294                         }
2295
2296                         lr = rangelock_enter(&zv->zv_rangelock, start, length,
2297                             RL_WRITER);
2298                         tx = dmu_tx_create(zv->zv_objset);
2299                         error = dmu_tx_assign(tx, TXG_WAIT);
2300                         if (error != 0) {
2301                                 dmu_tx_abort(tx);
2302                         } else {
2303                                 zvol_log_truncate(zv, tx, start, length,
2304                                     B_TRUE);
2305                                 dmu_tx_commit(tx);
2306                                 error = dmu_free_long_range(zv->zv_objset,
2307                                     ZVOL_OBJ, start, length);
2308                         }
2309
2310                         rangelock_exit(lr);
2311
2312                         if (error != 0)
2313                                 break;
2314                 }
2315
2316                 /*
2317                  * If the write-cache is disabled, 'sync' property
2318                  * is set to 'always', or if the caller is asking for
2319                  * a synchronous free, commit this operation to the zil.
2320                  * This will sync any previous uncommitted writes to the
2321                  * zvol object.
2322                  * Can be overridden by the zvol_unmap_sync_enabled tunable.
2323                  */
2324                 if ((error == 0) && zvol_unmap_sync_enabled &&
2325                     (!(zv->zv_flags & ZVOL_WCE) ||
2326                     (zv->zv_objset->os_sync == ZFS_SYNC_ALWAYS) ||
2327                     (dfl->dfl_flags & DF_WAIT_SYNC))) {
2328                         zil_commit(zv->zv_zilog, ZVOL_OBJ);
2329                 }
2330
2331                 if (!(flag & FKIOCTL))
2332                         dfl_free(dfl);
2333
2334                 return (error);
2335         }
2336
2337         default:
2338                 error = SET_ERROR(ENOTTY);
2339                 break;
2340
2341         }
2342         mutex_exit(&zfsdev_state_lock);
2343         return (error);
2344 }
2345 #endif  /* illumos */
2346
2347 int
2348 zvol_busy(void)
2349 {
2350         return (zvol_minors != 0);
2351 }
2352
2353 void
2354 zvol_init(void)
2355 {
2356         VERIFY(ddi_soft_state_init(&zfsdev_state, sizeof (zfs_soft_state_t),
2357             1) == 0);
2358 #ifdef illumos
2359         mutex_init(&zfsdev_state_lock, NULL, MUTEX_DEFAULT, NULL);
2360 #else
2361         ZFS_LOG(1, "ZVOL Initialized.");
2362 #endif
2363 }
2364
2365 void
2366 zvol_fini(void)
2367 {
2368 #ifdef illumos
2369         mutex_destroy(&zfsdev_state_lock);
2370 #endif
2371         ddi_soft_state_fini(&zfsdev_state);
2372         ZFS_LOG(1, "ZVOL Deinitialized.");
2373 }
2374
2375 #ifdef illumos
2376 /*ARGSUSED*/
2377 static int
2378 zfs_mvdev_dump_feature_check(void *arg, dmu_tx_t *tx)
2379 {
2380         spa_t *spa = dmu_tx_pool(tx)->dp_spa;
2381
2382         if (spa_feature_is_active(spa, SPA_FEATURE_MULTI_VDEV_CRASH_DUMP))
2383                 return (1);
2384         return (0);
2385 }
2386
2387 /*ARGSUSED*/
2388 static void
2389 zfs_mvdev_dump_activate_feature_sync(void *arg, dmu_tx_t *tx)
2390 {
2391         spa_t *spa = dmu_tx_pool(tx)->dp_spa;
2392
2393         spa_feature_incr(spa, SPA_FEATURE_MULTI_VDEV_CRASH_DUMP, tx);
2394 }
2395
2396 static int
2397 zvol_dump_init(zvol_state_t *zv, boolean_t resize)
2398 {
2399         dmu_tx_t *tx;
2400         int error;
2401         objset_t *os = zv->zv_objset;
2402         spa_t *spa = dmu_objset_spa(os);
2403         vdev_t *vd = spa->spa_root_vdev;
2404         nvlist_t *nv = NULL;
2405         uint64_t version = spa_version(spa);
2406         uint64_t checksum, compress, refresrv, vbs, dedup;
2407
2408         ASSERT(MUTEX_HELD(&zfsdev_state_lock));
2409         ASSERT(vd->vdev_ops == &vdev_root_ops);
2410
2411         error = dmu_free_long_range(zv->zv_objset, ZVOL_OBJ, 0,
2412             DMU_OBJECT_END);
2413         if (error != 0)
2414                 return (error);
2415         /* wait for dmu_free_long_range to actually free the blocks */
2416         txg_wait_synced(dmu_objset_pool(zv->zv_objset), 0);
2417
2418         /*
2419          * If the pool on which the dump device is being initialized has more
2420          * than one child vdev, check that the MULTI_VDEV_CRASH_DUMP feature is
2421          * enabled.  If so, bump that feature's counter to indicate that the
2422          * feature is active. We also check the vdev type to handle the
2423          * following case:
2424          *   # zpool create test raidz disk1 disk2 disk3
2425          *   Now have spa_root_vdev->vdev_children == 1 (the raidz vdev),
2426          *   the raidz vdev itself has 3 children.
2427          */
2428         if (vd->vdev_children > 1 || vd->vdev_ops == &vdev_raidz_ops) {
2429                 if (!spa_feature_is_enabled(spa,
2430                     SPA_FEATURE_MULTI_VDEV_CRASH_DUMP))
2431                         return (SET_ERROR(ENOTSUP));
2432                 (void) dsl_sync_task(spa_name(spa),
2433                     zfs_mvdev_dump_feature_check,
2434                     zfs_mvdev_dump_activate_feature_sync, NULL,
2435                     2, ZFS_SPACE_CHECK_RESERVED);
2436         }
2437
2438         if (!resize) {
2439                 error = dsl_prop_get_integer(zv->zv_name,
2440                     zfs_prop_to_name(ZFS_PROP_COMPRESSION), &compress, NULL);
2441                 if (error == 0) {
2442                         error = dsl_prop_get_integer(zv->zv_name,
2443                             zfs_prop_to_name(ZFS_PROP_CHECKSUM), &checksum,
2444                             NULL);
2445                 }
2446                 if (error == 0) {
2447                         error = dsl_prop_get_integer(zv->zv_name,
2448                             zfs_prop_to_name(ZFS_PROP_REFRESERVATION),
2449                             &refresrv, NULL);
2450                 }
2451                 if (error == 0) {
2452                         error = dsl_prop_get_integer(zv->zv_name,
2453                             zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE), &vbs,
2454                             NULL);
2455                 }
2456                 if (version >= SPA_VERSION_DEDUP && error == 0) {
2457                         error = dsl_prop_get_integer(zv->zv_name,
2458                             zfs_prop_to_name(ZFS_PROP_DEDUP), &dedup, NULL);
2459                 }
2460         }
2461         if (error != 0)
2462                 return (error);
2463
2464         tx = dmu_tx_create(os);
2465         dmu_tx_hold_zap(tx, ZVOL_ZAP_OBJ, TRUE, NULL);
2466         dmu_tx_hold_bonus(tx, ZVOL_OBJ);
2467         error = dmu_tx_assign(tx, TXG_WAIT);
2468         if (error != 0) {
2469                 dmu_tx_abort(tx);
2470                 return (error);
2471         }
2472
2473         /*
2474          * If we are resizing the dump device then we only need to
2475          * update the refreservation to match the newly updated
2476          * zvolsize. Otherwise, we save off the original state of the
2477          * zvol so that we can restore them if the zvol is ever undumpified.
2478          */
2479         if (resize) {
2480                 error = zap_update(os, ZVOL_ZAP_OBJ,
2481                     zfs_prop_to_name(ZFS_PROP_REFRESERVATION), 8, 1,
2482                     &zv->zv_volsize, tx);
2483         } else {
2484                 error = zap_update(os, ZVOL_ZAP_OBJ,
2485                     zfs_prop_to_name(ZFS_PROP_COMPRESSION), 8, 1,
2486                     &compress, tx);
2487                 if (error == 0) {
2488                         error = zap_update(os, ZVOL_ZAP_OBJ,
2489                             zfs_prop_to_name(ZFS_PROP_CHECKSUM), 8, 1,
2490                             &checksum, tx);
2491                 }
2492                 if (error == 0) {
2493                         error = zap_update(os, ZVOL_ZAP_OBJ,
2494                             zfs_prop_to_name(ZFS_PROP_REFRESERVATION), 8, 1,
2495                             &refresrv, tx);
2496                 }
2497                 if (error == 0) {
2498                         error = zap_update(os, ZVOL_ZAP_OBJ,
2499                             zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE), 8, 1,
2500                             &vbs, tx);
2501                 }
2502                 if (error == 0) {
2503                         error = dmu_object_set_blocksize(
2504                             os, ZVOL_OBJ, SPA_OLD_MAXBLOCKSIZE, 0, tx);
2505                 }
2506                 if (version >= SPA_VERSION_DEDUP && error == 0) {
2507                         error = zap_update(os, ZVOL_ZAP_OBJ,
2508                             zfs_prop_to_name(ZFS_PROP_DEDUP), 8, 1,
2509                             &dedup, tx);
2510                 }
2511                 if (error == 0)
2512                         zv->zv_volblocksize = SPA_OLD_MAXBLOCKSIZE;
2513         }
2514         dmu_tx_commit(tx);
2515
2516         /*
2517          * We only need update the zvol's property if we are initializing
2518          * the dump area for the first time.
2519          */
2520         if (error == 0 && !resize) {
2521                 /*
2522                  * If MULTI_VDEV_CRASH_DUMP is active, use the NOPARITY checksum
2523                  * function.  Otherwise, use the old default -- OFF.
2524                  */
2525                 checksum = spa_feature_is_active(spa,
2526                     SPA_FEATURE_MULTI_VDEV_CRASH_DUMP) ? ZIO_CHECKSUM_NOPARITY :
2527                     ZIO_CHECKSUM_OFF;
2528
2529                 VERIFY(nvlist_alloc(&nv, NV_UNIQUE_NAME, KM_SLEEP) == 0);
2530                 VERIFY(nvlist_add_uint64(nv,
2531                     zfs_prop_to_name(ZFS_PROP_REFRESERVATION), 0) == 0);
2532                 VERIFY(nvlist_add_uint64(nv,
2533                     zfs_prop_to_name(ZFS_PROP_COMPRESSION),
2534                     ZIO_COMPRESS_OFF) == 0);
2535                 VERIFY(nvlist_add_uint64(nv,
2536                     zfs_prop_to_name(ZFS_PROP_CHECKSUM),
2537                     checksum) == 0);
2538                 if (version >= SPA_VERSION_DEDUP) {
2539                         VERIFY(nvlist_add_uint64(nv,
2540                             zfs_prop_to_name(ZFS_PROP_DEDUP),
2541                             ZIO_CHECKSUM_OFF) == 0);
2542                 }
2543
2544                 error = zfs_set_prop_nvlist(zv->zv_name, ZPROP_SRC_LOCAL,
2545                     nv, NULL);
2546                 nvlist_free(nv);
2547         }
2548
2549         /* Allocate the space for the dump */
2550         if (error == 0)
2551                 error = zvol_prealloc(zv);
2552         return (error);
2553 }
2554
2555 static int
2556 zvol_dumpify(zvol_state_t *zv)
2557 {
2558         int error = 0;
2559         uint64_t dumpsize = 0;
2560         dmu_tx_t *tx;
2561         objset_t *os = zv->zv_objset;
2562
2563         if (zv->zv_flags & ZVOL_RDONLY)
2564                 return (SET_ERROR(EROFS));
2565
2566         if (zap_lookup(zv->zv_objset, ZVOL_ZAP_OBJ, ZVOL_DUMPSIZE,
2567             8, 1, &dumpsize) != 0 || dumpsize != zv->zv_volsize) {
2568                 boolean_t resize = (dumpsize > 0);
2569
2570                 if ((error = zvol_dump_init(zv, resize)) != 0) {
2571                         (void) zvol_dump_fini(zv);
2572                         return (error);
2573                 }
2574         }
2575
2576         /*
2577          * Build up our lba mapping.
2578          */
2579         error = zvol_get_lbas(zv);
2580         if (error) {
2581                 (void) zvol_dump_fini(zv);
2582                 return (error);
2583         }
2584
2585         tx = dmu_tx_create(os);
2586         dmu_tx_hold_zap(tx, ZVOL_ZAP_OBJ, TRUE, NULL);
2587         error = dmu_tx_assign(tx, TXG_WAIT);
2588         if (error) {
2589                 dmu_tx_abort(tx);
2590                 (void) zvol_dump_fini(zv);
2591                 return (error);
2592         }
2593
2594         zv->zv_flags |= ZVOL_DUMPIFIED;
2595         error = zap_update(os, ZVOL_ZAP_OBJ, ZVOL_DUMPSIZE, 8, 1,
2596             &zv->zv_volsize, tx);
2597         dmu_tx_commit(tx);
2598
2599         if (error) {
2600                 (void) zvol_dump_fini(zv);
2601                 return (error);
2602         }
2603
2604         txg_wait_synced(dmu_objset_pool(os), 0);
2605         return (0);
2606 }
2607
2608 static int
2609 zvol_dump_fini(zvol_state_t *zv)
2610 {
2611         dmu_tx_t *tx;
2612         objset_t *os = zv->zv_objset;
2613         nvlist_t *nv;
2614         int error = 0;
2615         uint64_t checksum, compress, refresrv, vbs, dedup;
2616         uint64_t version = spa_version(dmu_objset_spa(zv->zv_objset));
2617
2618         /*
2619          * Attempt to restore the zvol back to its pre-dumpified state.
2620          * This is a best-effort attempt as it's possible that not all
2621          * of these properties were initialized during the dumpify process
2622          * (i.e. error during zvol_dump_init).
2623          */
2624
2625         tx = dmu_tx_create(os);
2626         dmu_tx_hold_zap(tx, ZVOL_ZAP_OBJ, TRUE, NULL);
2627         error = dmu_tx_assign(tx, TXG_WAIT);
2628         if (error) {
2629                 dmu_tx_abort(tx);
2630                 return (error);
2631         }
2632         (void) zap_remove(os, ZVOL_ZAP_OBJ, ZVOL_DUMPSIZE, tx);
2633         dmu_tx_commit(tx);
2634
2635         (void) zap_lookup(zv->zv_objset, ZVOL_ZAP_OBJ,
2636             zfs_prop_to_name(ZFS_PROP_CHECKSUM), 8, 1, &checksum);
2637         (void) zap_lookup(zv->zv_objset, ZVOL_ZAP_OBJ,
2638             zfs_prop_to_name(ZFS_PROP_COMPRESSION), 8, 1, &compress);
2639         (void) zap_lookup(zv->zv_objset, ZVOL_ZAP_OBJ,
2640             zfs_prop_to_name(ZFS_PROP_REFRESERVATION), 8, 1, &refresrv);
2641         (void) zap_lookup(zv->zv_objset, ZVOL_ZAP_OBJ,
2642             zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE), 8, 1, &vbs);
2643
2644         VERIFY(nvlist_alloc(&nv, NV_UNIQUE_NAME, KM_SLEEP) == 0);
2645         (void) nvlist_add_uint64(nv,
2646             zfs_prop_to_name(ZFS_PROP_CHECKSUM), checksum);
2647         (void) nvlist_add_uint64(nv,
2648             zfs_prop_to_name(ZFS_PROP_COMPRESSION), compress);
2649         (void) nvlist_add_uint64(nv,
2650             zfs_prop_to_name(ZFS_PROP_REFRESERVATION), refresrv);
2651         if (version >= SPA_VERSION_DEDUP &&
2652             zap_lookup(zv->zv_objset, ZVOL_ZAP_OBJ,
2653             zfs_prop_to_name(ZFS_PROP_DEDUP), 8, 1, &dedup) == 0) {
2654                 (void) nvlist_add_uint64(nv,
2655                     zfs_prop_to_name(ZFS_PROP_DEDUP), dedup);
2656         }
2657         (void) zfs_set_prop_nvlist(zv->zv_name, ZPROP_SRC_LOCAL,
2658             nv, NULL);
2659         nvlist_free(nv);
2660
2661         zvol_free_extents(zv);
2662         zv->zv_flags &= ~ZVOL_DUMPIFIED;
2663         (void) dmu_free_long_range(os, ZVOL_OBJ, 0, DMU_OBJECT_END);
2664         /* wait for dmu_free_long_range to actually free the blocks */
2665         txg_wait_synced(dmu_objset_pool(zv->zv_objset), 0);
2666         tx = dmu_tx_create(os);
2667         dmu_tx_hold_bonus(tx, ZVOL_OBJ);
2668         error = dmu_tx_assign(tx, TXG_WAIT);
2669         if (error) {
2670                 dmu_tx_abort(tx);
2671                 return (error);
2672         }
2673         if (dmu_object_set_blocksize(os, ZVOL_OBJ, vbs, 0, tx) == 0)
2674                 zv->zv_volblocksize = vbs;
2675         dmu_tx_commit(tx);
2676
2677         return (0);
2678 }
2679 #else   /* !illumos */
2680
2681 static void
2682 zvol_geom_run(zvol_state_t *zv)
2683 {
2684         struct g_provider *pp;
2685
2686         pp = zv->zv_provider;
2687         g_error_provider(pp, 0);
2688
2689         kproc_kthread_add(zvol_geom_worker, zv, &system_proc, NULL, 0, 0,
2690             "zfskern", "zvol %s", pp->name + sizeof(ZVOL_DRIVER));
2691 }
2692
2693 static void
2694 zvol_geom_destroy(zvol_state_t *zv)
2695 {
2696         struct g_provider *pp;
2697
2698         g_topology_assert();
2699
2700         mtx_lock(&zv->zv_queue_mtx);
2701         zv->zv_state = 1;
2702         wakeup_one(&zv->zv_queue);
2703         while (zv->zv_state != 2)
2704                 msleep(&zv->zv_state, &zv->zv_queue_mtx, 0, "zvol:w", 0);
2705         mtx_destroy(&zv->zv_queue_mtx);
2706
2707         pp = zv->zv_provider;
2708         zv->zv_provider = NULL;
2709         pp->private = NULL;
2710         g_wither_geom(pp->geom, ENXIO);
2711 }
2712
2713 static int
2714 zvol_geom_access(struct g_provider *pp, int acr, int acw, int ace)
2715 {
2716         int count, error, flags;
2717
2718         g_topology_assert();
2719
2720         /*
2721          * To make it easier we expect either open or close, but not both
2722          * at the same time.
2723          */
2724         KASSERT((acr >= 0 && acw >= 0 && ace >= 0) ||
2725             (acr <= 0 && acw <= 0 && ace <= 0),
2726             ("Unsupported access request to %s (acr=%d, acw=%d, ace=%d).",
2727             pp->name, acr, acw, ace));
2728
2729         if (pp->private == NULL) {
2730                 if (acr <= 0 && acw <= 0 && ace <= 0)
2731                         return (0);
2732                 return (pp->error);
2733         }
2734
2735         /*
2736          * We don't pass FEXCL flag to zvol_open()/zvol_close() if ace != 0,
2737          * because GEOM already handles that and handles it a bit differently.
2738          * GEOM allows for multiple read/exclusive consumers and ZFS allows
2739          * only one exclusive consumer, no matter if it is reader or writer.
2740          * I like better the way GEOM works so I'll leave it for GEOM to
2741          * decide what to do.
2742          */
2743
2744         count = acr + acw + ace;
2745         if (count == 0)
2746                 return (0);
2747
2748         flags = 0;
2749         if (acr != 0 || ace != 0)
2750                 flags |= FREAD;
2751         if (acw != 0)
2752                 flags |= FWRITE;
2753
2754         g_topology_unlock();
2755         if (count > 0)
2756                 error = zvol_open(pp, flags, count);
2757         else
2758                 error = zvol_close(pp, flags, -count);
2759         g_topology_lock();
2760         return (error);
2761 }
2762
2763 static void
2764 zvol_geom_start(struct bio *bp)
2765 {
2766         zvol_state_t *zv;
2767         boolean_t first;
2768
2769         zv = bp->bio_to->private;
2770         ASSERT(zv != NULL);
2771         switch (bp->bio_cmd) {
2772         case BIO_FLUSH:
2773                 if (!THREAD_CAN_SLEEP())
2774                         goto enqueue;
2775                 zil_commit(zv->zv_zilog, ZVOL_OBJ);
2776                 g_io_deliver(bp, 0);
2777                 break;
2778         case BIO_READ:
2779         case BIO_WRITE:
2780         case BIO_DELETE:
2781                 if (!THREAD_CAN_SLEEP())
2782                         goto enqueue;
2783                 zvol_strategy(bp);
2784                 break;
2785         case BIO_GETATTR: {
2786                 spa_t *spa = dmu_objset_spa(zv->zv_objset);
2787                 uint64_t refd, avail, usedobjs, availobjs, val;
2788
2789                 if (g_handleattr_int(bp, "GEOM::candelete", 1))
2790                         return;
2791                 if (strcmp(bp->bio_attribute, "blocksavail") == 0) {
2792                         dmu_objset_space(zv->zv_objset, &refd, &avail,
2793                             &usedobjs, &availobjs);
2794                         if (g_handleattr_off_t(bp, "blocksavail",
2795                             avail / DEV_BSIZE))
2796                                 return;
2797                 } else if (strcmp(bp->bio_attribute, "blocksused") == 0) {
2798                         dmu_objset_space(zv->zv_objset, &refd, &avail,
2799                             &usedobjs, &availobjs);
2800                         if (g_handleattr_off_t(bp, "blocksused",
2801                             refd / DEV_BSIZE))
2802                                 return;
2803                 } else if (strcmp(bp->bio_attribute, "poolblocksavail") == 0) {
2804                         avail = metaslab_class_get_space(spa_normal_class(spa));
2805                         avail -= metaslab_class_get_alloc(spa_normal_class(spa));
2806                         if (g_handleattr_off_t(bp, "poolblocksavail",
2807                             avail / DEV_BSIZE))
2808                                 return;
2809                 } else if (strcmp(bp->bio_attribute, "poolblocksused") == 0) {
2810                         refd = metaslab_class_get_alloc(spa_normal_class(spa));
2811                         if (g_handleattr_off_t(bp, "poolblocksused",
2812                             refd / DEV_BSIZE))
2813                                 return;
2814                 }
2815                 /* FALLTHROUGH */
2816         }
2817         default:
2818                 g_io_deliver(bp, EOPNOTSUPP);
2819                 break;
2820         }
2821         return;
2822
2823 enqueue:
2824         mtx_lock(&zv->zv_queue_mtx);
2825         first = (bioq_first(&zv->zv_queue) == NULL);
2826         bioq_insert_tail(&zv->zv_queue, bp);
2827         mtx_unlock(&zv->zv_queue_mtx);
2828         if (first)
2829                 wakeup_one(&zv->zv_queue);
2830 }
2831
2832 static void
2833 zvol_geom_worker(void *arg)
2834 {
2835         zvol_state_t *zv;
2836         struct bio *bp;
2837
2838         thread_lock(curthread);
2839         sched_prio(curthread, PRIBIO);
2840         thread_unlock(curthread);
2841
2842         zv = arg;
2843         for (;;) {
2844                 mtx_lock(&zv->zv_queue_mtx);
2845                 bp = bioq_takefirst(&zv->zv_queue);
2846                 if (bp == NULL) {
2847                         if (zv->zv_state == 1) {
2848                                 zv->zv_state = 2;
2849                                 wakeup(&zv->zv_state);
2850                                 mtx_unlock(&zv->zv_queue_mtx);
2851                                 kthread_exit();
2852                         }
2853                         msleep(&zv->zv_queue, &zv->zv_queue_mtx, PRIBIO | PDROP,
2854                             "zvol:io", 0);
2855                         continue;
2856                 }
2857                 mtx_unlock(&zv->zv_queue_mtx);
2858                 switch (bp->bio_cmd) {
2859                 case BIO_FLUSH:
2860                         zil_commit(zv->zv_zilog, ZVOL_OBJ);
2861                         g_io_deliver(bp, 0);
2862                         break;
2863                 case BIO_READ:
2864                 case BIO_WRITE:
2865                 case BIO_DELETE:
2866                         zvol_strategy(bp);
2867                         break;
2868                 default:
2869                         g_io_deliver(bp, EOPNOTSUPP);
2870                         break;
2871                 }
2872         }
2873 }
2874
2875 extern boolean_t dataset_name_hidden(const char *name);
2876
2877 static int
2878 zvol_create_snapshots(objset_t *os, const char *name)
2879 {
2880         uint64_t cookie, obj;
2881         char *sname;
2882         int error, len;
2883
2884         cookie = obj = 0;
2885         sname = kmem_alloc(MAXPATHLEN, KM_SLEEP);
2886
2887 #if 0
2888         (void) dmu_objset_find(name, dmu_objset_prefetch, NULL,
2889             DS_FIND_SNAPSHOTS);
2890 #endif
2891
2892         for (;;) {
2893                 len = snprintf(sname, MAXPATHLEN, "%s@", name);
2894                 if (len >= MAXPATHLEN) {
2895                         dmu_objset_rele(os, FTAG);
2896                         error = ENAMETOOLONG;
2897                         break;
2898                 }
2899
2900                 dsl_pool_config_enter(dmu_objset_pool(os), FTAG);
2901                 error = dmu_snapshot_list_next(os, MAXPATHLEN - len,
2902                     sname + len, &obj, &cookie, NULL);
2903                 dsl_pool_config_exit(dmu_objset_pool(os), FTAG);
2904                 if (error != 0) {
2905                         if (error == ENOENT)
2906                                 error = 0;
2907                         break;
2908                 }
2909
2910                 error = zvol_create_minor(sname);
2911                 if (error != 0 && error != EEXIST) {
2912                         printf("ZFS WARNING: Unable to create ZVOL %s (error=%d).\n",
2913                             sname, error);
2914                         break;
2915                 }
2916         }
2917
2918         kmem_free(sname, MAXPATHLEN);
2919         return (error);
2920 }
2921
2922 int
2923 zvol_create_minors(const char *name)
2924 {
2925         uint64_t cookie;
2926         objset_t *os;
2927         char *osname, *p;
2928         int error, len;
2929
2930         if (dataset_name_hidden(name))
2931                 return (0);
2932
2933         if ((error = dmu_objset_hold(name, FTAG, &os)) != 0) {
2934                 printf("ZFS WARNING: Unable to put hold on %s (error=%d).\n",
2935                     name, error);
2936                 return (error);
2937         }
2938         if (dmu_objset_type(os) == DMU_OST_ZVOL) {
2939                 dsl_dataset_long_hold(os->os_dsl_dataset, FTAG);
2940                 dsl_pool_rele(dmu_objset_pool(os), FTAG);
2941                 error = zvol_create_minor(name);
2942                 if (error == 0 || error == EEXIST) {
2943                         error = zvol_create_snapshots(os, name);
2944                 } else {
2945                         printf("ZFS WARNING: Unable to create ZVOL %s (error=%d).\n",
2946                             name, error);
2947                 }
2948                 dsl_dataset_long_rele(os->os_dsl_dataset, FTAG);
2949                 dsl_dataset_rele(os->os_dsl_dataset, FTAG);
2950                 return (error);
2951         }
2952         if (dmu_objset_type(os) != DMU_OST_ZFS) {
2953                 dmu_objset_rele(os, FTAG);
2954                 return (0);
2955         }
2956
2957         osname = kmem_alloc(MAXPATHLEN, KM_SLEEP);
2958         if (snprintf(osname, MAXPATHLEN, "%s/", name) >= MAXPATHLEN) {
2959                 dmu_objset_rele(os, FTAG);
2960                 kmem_free(osname, MAXPATHLEN);
2961                 return (ENOENT);
2962         }
2963         p = osname + strlen(osname);
2964         len = MAXPATHLEN - (p - osname);
2965
2966 #if 0
2967         /* Prefetch the datasets. */
2968         cookie = 0;
2969         while (dmu_dir_list_next(os, len, p, NULL, &cookie) == 0) {
2970                 if (!dataset_name_hidden(osname))
2971                         (void) dmu_objset_prefetch(osname, NULL);
2972         }
2973 #endif
2974
2975         cookie = 0;
2976         while (dmu_dir_list_next(os, MAXPATHLEN - (p - osname), p, NULL,
2977             &cookie) == 0) {
2978                 dmu_objset_rele(os, FTAG);
2979                 (void)zvol_create_minors(osname);
2980                 if ((error = dmu_objset_hold(name, FTAG, &os)) != 0) {
2981                         printf("ZFS WARNING: Unable to put hold on %s (error=%d).\n",
2982                             name, error);
2983                         return (error);
2984                 }
2985         }
2986
2987         dmu_objset_rele(os, FTAG);
2988         kmem_free(osname, MAXPATHLEN);
2989         return (0);
2990 }
2991
2992 static void
2993 zvol_rename_minor(zvol_state_t *zv, const char *newname)
2994 {
2995         struct g_geom *gp;
2996         struct g_provider *pp;
2997         struct cdev *dev;
2998
2999         ASSERT(MUTEX_HELD(&zfsdev_state_lock));
3000
3001         if (zv->zv_volmode == ZFS_VOLMODE_GEOM) {
3002                 g_topology_lock();
3003                 pp = zv->zv_provider;
3004                 ASSERT(pp != NULL);
3005                 gp = pp->geom;
3006                 ASSERT(gp != NULL);
3007
3008                 zv->zv_provider = NULL;
3009                 g_wither_provider(pp, ENXIO);
3010
3011                 pp = g_new_providerf(gp, "%s/%s", ZVOL_DRIVER, newname);
3012                 pp->flags |= G_PF_DIRECT_RECEIVE | G_PF_DIRECT_SEND;
3013                 pp->sectorsize = DEV_BSIZE;
3014                 pp->mediasize = zv->zv_volsize;
3015                 pp->private = zv;
3016                 zv->zv_provider = pp;
3017                 g_error_provider(pp, 0);
3018                 g_topology_unlock();
3019         } else if (zv->zv_volmode == ZFS_VOLMODE_DEV) {
3020                 struct make_dev_args args;
3021
3022                 if ((dev = zv->zv_dev) != NULL) {
3023                         zv->zv_dev = NULL;
3024                         destroy_dev(dev);
3025                         if (zv->zv_total_opens > 0) {
3026                                 zv->zv_flags &= ~ZVOL_EXCL;
3027                                 zv->zv_total_opens = 0;
3028                                 zvol_last_close(zv);
3029                         }
3030                 }
3031
3032                 make_dev_args_init(&args);
3033                 args.mda_flags = MAKEDEV_CHECKNAME | MAKEDEV_WAITOK;
3034                 args.mda_devsw = &zvol_cdevsw;
3035                 args.mda_cr = NULL;
3036                 args.mda_uid = UID_ROOT;
3037                 args.mda_gid = GID_OPERATOR;
3038                 args.mda_mode = 0640;
3039                 args.mda_si_drv2 = zv;
3040                 if (make_dev_s(&args, &zv->zv_dev,
3041                     "%s/%s", ZVOL_DRIVER, newname) == 0)
3042                         zv->zv_dev->si_iosize_max = MAXPHYS;
3043         }
3044         strlcpy(zv->zv_name, newname, sizeof(zv->zv_name));
3045 }
3046
3047 void
3048 zvol_rename_minors(const char *oldname, const char *newname)
3049 {
3050         char name[MAXPATHLEN];
3051         struct g_provider *pp;
3052         struct g_geom *gp;
3053         size_t oldnamelen, newnamelen;
3054         zvol_state_t *zv;
3055         char *namebuf;
3056         boolean_t locked = B_FALSE;
3057
3058         oldnamelen = strlen(oldname);
3059         newnamelen = strlen(newname);
3060
3061         DROP_GIANT();
3062         /* See comment in zvol_open(). */
3063         if (!MUTEX_HELD(&zfsdev_state_lock)) {
3064                 mutex_enter(&zfsdev_state_lock);
3065                 locked = B_TRUE;
3066         }
3067
3068         LIST_FOREACH(zv, &all_zvols, zv_links) {
3069                 if (strcmp(zv->zv_name, oldname) == 0) {
3070                         zvol_rename_minor(zv, newname);
3071                 } else if (strncmp(zv->zv_name, oldname, oldnamelen) == 0 &&
3072                     (zv->zv_name[oldnamelen] == '/' ||
3073                      zv->zv_name[oldnamelen] == '@')) {
3074                         snprintf(name, sizeof(name), "%s%c%s", newname,
3075                             zv->zv_name[oldnamelen],
3076                             zv->zv_name + oldnamelen + 1);
3077                         zvol_rename_minor(zv, name);
3078                 }
3079         }
3080
3081         if (locked)
3082                 mutex_exit(&zfsdev_state_lock);
3083         PICKUP_GIANT();
3084 }
3085
3086 static int
3087 zvol_d_open(struct cdev *dev, int flags, int fmt, struct thread *td)
3088 {
3089         zvol_state_t *zv = dev->si_drv2;
3090         int err = 0;
3091
3092         mutex_enter(&zfsdev_state_lock);
3093         if (zv->zv_total_opens == 0)
3094                 err = zvol_first_open(zv);
3095         if (err) {
3096                 mutex_exit(&zfsdev_state_lock);
3097                 return (err);
3098         }
3099         if ((flags & FWRITE) && (zv->zv_flags & ZVOL_RDONLY)) {
3100                 err = SET_ERROR(EROFS);
3101                 goto out;
3102         }
3103         if (zv->zv_flags & ZVOL_EXCL) {
3104                 err = SET_ERROR(EBUSY);
3105                 goto out;
3106         }
3107 #ifdef FEXCL
3108         if (flags & FEXCL) {
3109                 if (zv->zv_total_opens != 0) {
3110                         err = SET_ERROR(EBUSY);
3111                         goto out;
3112                 }
3113                 zv->zv_flags |= ZVOL_EXCL;
3114         }
3115 #endif
3116
3117         zv->zv_total_opens++;
3118         if (flags & (FSYNC | FDSYNC)) {
3119                 zv->zv_sync_cnt++;
3120                 if (zv->zv_sync_cnt == 1)
3121                         zil_async_to_sync(zv->zv_zilog, ZVOL_OBJ);
3122         }
3123         mutex_exit(&zfsdev_state_lock);
3124         return (err);
3125 out:
3126         if (zv->zv_total_opens == 0)
3127                 zvol_last_close(zv);
3128         mutex_exit(&zfsdev_state_lock);
3129         return (err);
3130 }
3131
3132 static int
3133 zvol_d_close(struct cdev *dev, int flags, int fmt, struct thread *td)
3134 {
3135         zvol_state_t *zv = dev->si_drv2;
3136
3137         mutex_enter(&zfsdev_state_lock);
3138         if (zv->zv_flags & ZVOL_EXCL) {
3139                 ASSERT(zv->zv_total_opens == 1);
3140                 zv->zv_flags &= ~ZVOL_EXCL;
3141         }
3142
3143         /*
3144          * If the open count is zero, this is a spurious close.
3145          * That indicates a bug in the kernel / DDI framework.
3146          */
3147         ASSERT(zv->zv_total_opens != 0);
3148
3149         /*
3150          * You may get multiple opens, but only one close.
3151          */
3152         zv->zv_total_opens--;
3153         if (flags & (FSYNC | FDSYNC))
3154                 zv->zv_sync_cnt--;
3155
3156         if (zv->zv_total_opens == 0)
3157                 zvol_last_close(zv);
3158
3159         mutex_exit(&zfsdev_state_lock);
3160         return (0);
3161 }
3162
3163 static int
3164 zvol_d_ioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag, struct thread *td)
3165 {
3166         zvol_state_t *zv;
3167         locked_range_t *lr;
3168         off_t offset, length;
3169         int i, error;
3170         boolean_t sync;
3171
3172         zv = dev->si_drv2;
3173
3174         error = 0;
3175         KASSERT(zv->zv_total_opens > 0,
3176             ("Device with zero access count in zvol_d_ioctl"));
3177
3178         i = IOCPARM_LEN(cmd);
3179         switch (cmd) {
3180         case DIOCGSECTORSIZE:
3181                 *(u_int *)data = DEV_BSIZE;
3182                 break;
3183         case DIOCGMEDIASIZE:
3184                 *(off_t *)data = zv->zv_volsize;
3185                 break;
3186         case DIOCGFLUSH:
3187                 zil_commit(zv->zv_zilog, ZVOL_OBJ);
3188                 break;
3189         case DIOCGDELETE:
3190                 if (!zvol_unmap_enabled)
3191                         break;
3192
3193                 offset = ((off_t *)data)[0];
3194                 length = ((off_t *)data)[1];
3195                 if ((offset % DEV_BSIZE) != 0 || (length % DEV_BSIZE) != 0 ||
3196                     offset < 0 || offset >= zv->zv_volsize ||
3197                     length <= 0) {
3198                         printf("%s: offset=%jd length=%jd\n", __func__, offset,
3199                             length);
3200                         error = EINVAL;
3201                         break;
3202                 }
3203
3204                 lr = rangelock_enter(&zv->zv_rangelock, offset, length,
3205                     RL_WRITER);
3206                 dmu_tx_t *tx = dmu_tx_create(zv->zv_objset);
3207                 error = dmu_tx_assign(tx, TXG_WAIT);
3208                 if (error != 0) {
3209                         sync = FALSE;
3210                         dmu_tx_abort(tx);
3211                 } else {
3212                         sync = (zv->zv_objset->os_sync == ZFS_SYNC_ALWAYS);
3213                         zvol_log_truncate(zv, tx, offset, length, sync);
3214                         dmu_tx_commit(tx);
3215                         error = dmu_free_long_range(zv->zv_objset, ZVOL_OBJ,
3216                             offset, length);
3217                 }
3218                 rangelock_exit(lr);
3219                 if (sync)
3220                         zil_commit(zv->zv_zilog, ZVOL_OBJ);
3221                 break;
3222         case DIOCGSTRIPESIZE:
3223                 *(off_t *)data = zv->zv_volblocksize;
3224                 break;
3225         case DIOCGSTRIPEOFFSET:
3226                 *(off_t *)data = 0;
3227                 break;
3228         case DIOCGATTR: {
3229                 spa_t *spa = dmu_objset_spa(zv->zv_objset);
3230                 struct diocgattr_arg *arg = (struct diocgattr_arg *)data;
3231                 uint64_t refd, avail, usedobjs, availobjs;
3232
3233                 if (strcmp(arg->name, "GEOM::candelete") == 0)
3234                         arg->value.i = 1;
3235                 else if (strcmp(arg->name, "blocksavail") == 0) {
3236                         dmu_objset_space(zv->zv_objset, &refd, &avail,
3237                             &usedobjs, &availobjs);
3238                         arg->value.off = avail / DEV_BSIZE;
3239                 } else if (strcmp(arg->name, "blocksused") == 0) {
3240                         dmu_objset_space(zv->zv_objset, &refd, &avail,
3241                             &usedobjs, &availobjs);
3242                         arg->value.off = refd / DEV_BSIZE;
3243                 } else if (strcmp(arg->name, "poolblocksavail") == 0) {
3244                         avail = metaslab_class_get_space(spa_normal_class(spa));
3245                         avail -= metaslab_class_get_alloc(spa_normal_class(spa));
3246                         arg->value.off = avail / DEV_BSIZE;
3247                 } else if (strcmp(arg->name, "poolblocksused") == 0) {
3248                         refd = metaslab_class_get_alloc(spa_normal_class(spa));
3249                         arg->value.off = refd / DEV_BSIZE;
3250                 } else
3251                         error = ENOIOCTL;
3252                 break;
3253         }
3254         case FIOSEEKHOLE:
3255         case FIOSEEKDATA: {
3256                 off_t *off = (off_t *)data;
3257                 uint64_t noff;
3258                 boolean_t hole;
3259
3260                 hole = (cmd == FIOSEEKHOLE);
3261                 noff = *off;
3262                 error = dmu_offset_next(zv->zv_objset, ZVOL_OBJ, hole, &noff);
3263                 *off = noff;
3264                 break;
3265         }
3266         default:
3267                 error = ENOIOCTL;
3268         }
3269
3270         return (error);
3271 }
3272 #endif  /* illumos */