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