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