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