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