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