]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zvol.c
Merge sendmail 8.16.1 to HEAD: See contrib/sendmail/RELEASE_NOTES for details
[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 2017 Nexenta Systems, Inc.  All rights reserved.
30  * Copyright (c) 2012, 2017 by Delphix. All rights reserved.
31  * Copyright (c) 2013, Joyent, Inc. All rights reserved.
32  * Copyright (c) 2014 Integros [integros.com]
33  * Copyright (c) 2016 Actifio, Inc. All rights reserved.
34  */
35
36 /* Portions Copyright 2011 Martin Matuska <mm@FreeBSD.org> */
37
38 /*
39  * ZFS volume emulation driver.
40  *
41  * Makes a DMU object look like a volume of arbitrary size, up to 2^64 bytes.
42  * Volumes are accessed through the symbolic links named:
43  *
44  * /dev/zvol/dsk/<pool_name>/<dataset_name>
45  * /dev/zvol/rdsk/<pool_name>/<dataset_name>
46  *
47  * These links are created by the /dev filesystem (sdev_zvolops.c).
48  * Volumes are persistent through reboot.  No user command needs to be
49  * run before opening and using a device.
50  *
51  * FreeBSD notes.
52  * On FreeBSD ZVOLs are simply GEOM providers like any other storage device
53  * in the system.
54  */
55
56 #include <sys/types.h>
57 #include <sys/param.h>
58 #include <sys/kernel.h>
59 #include <sys/errno.h>
60 #include <sys/uio.h>
61 #include <sys/bio.h>
62 #include <sys/buf.h>
63 #include <sys/kmem.h>
64 #include <sys/conf.h>
65 #include <sys/cmn_err.h>
66 #include <sys/stat.h>
67 #include <sys/zap.h>
68 #include <sys/spa.h>
69 #include <sys/spa_impl.h>
70 #include <sys/zio.h>
71 #include <sys/disk.h>
72 #include <sys/dmu_traverse.h>
73 #include <sys/dnode.h>
74 #include <sys/dsl_dataset.h>
75 #include <sys/dsl_prop.h>
76 #include <sys/dkio.h>
77 #include <sys/byteorder.h>
78 #include <sys/sunddi.h>
79 #include <sys/dirent.h>
80 #include <sys/policy.h>
81 #include <sys/queue.h>
82 #include <sys/fs/zfs.h>
83 #include <sys/zfs_ioctl.h>
84 #include <sys/zil.h>
85 #include <sys/refcount.h>
86 #include <sys/zfs_znode.h>
87 #include <sys/zfs_rlock.h>
88 #include <sys/vdev_impl.h>
89 #include <sys/vdev_raidz.h>
90 #include <sys/zvol.h>
91 #include <sys/zil_impl.h>
92 #include <sys/dbuf.h>
93 #include <sys/dmu_tx.h>
94 #include <sys/zfeature.h>
95 #include <sys/zio_checksum.h>
96 #include <sys/zil_impl.h>
97 #include <sys/filio.h>
98 #include <sys/zfs_rlock.h>
99
100 #include <geom/geom.h>
101
102 #include "zfs_namecheck.h"
103
104 #ifndef illumos
105 struct g_class zfs_zvol_class = {
106         .name = "ZFS::ZVOL",
107         .version = G_VERSION,
108 };
109
110 DECLARE_GEOM_CLASS(zfs_zvol_class, zfs_zvol);
111
112 #endif
113 void *zfsdev_state;
114 static char *zvol_tag = "zvol_tag";
115
116 #define ZVOL_DUMPSIZE           "dumpsize"
117
118 /*
119  * This lock protects the zfsdev_state structure from being modified
120  * while it's being used, e.g. an open that comes in before a create
121  * finishes.  It also protects temporary opens of the dataset so that,
122  * e.g., an open doesn't get a spurious EBUSY.
123  */
124 #ifdef illumos
125 kmutex_t zfsdev_state_lock;
126 #else
127 /*
128  * In FreeBSD we've replaced the upstream zfsdev_state_lock with the
129  * spa_namespace_lock in the ZVOL code.
130  */
131 #define zfsdev_state_lock spa_namespace_lock
132 #endif
133 static uint32_t zvol_minors;
134
135 #ifndef illumos
136 SYSCTL_DECL(_vfs_zfs);
137 SYSCTL_NODE(_vfs_zfs, OID_AUTO, vol, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
138     "ZFS VOLUME");
139 static int      volmode = ZFS_VOLMODE_GEOM;
140 SYSCTL_INT(_vfs_zfs_vol, OID_AUTO, mode, CTLFLAG_RWTUN, &volmode, 0,
141     "Expose as GEOM providers (1), device files (2) or neither");
142 static boolean_t zpool_on_zvol = B_FALSE;
143 SYSCTL_INT(_vfs_zfs_vol, OID_AUTO, recursive, CTLFLAG_RWTUN, &zpool_on_zvol, 0,
144     "Allow zpools to use zvols as vdevs (DANGEROUS)");
145
146 #endif
147 typedef struct zvol_extent {
148         list_node_t     ze_node;
149         dva_t           ze_dva;         /* dva associated with this extent */
150         uint64_t        ze_nblks;       /* number of blocks in extent */
151 } zvol_extent_t;
152
153 /*
154  * The in-core state of each volume.
155  */
156 typedef struct zvol_state {
157 #ifndef illumos
158         LIST_ENTRY(zvol_state)  zv_links;
159 #endif
160         char            zv_name[MAXPATHLEN]; /* pool/dd name */
161         uint64_t        zv_volsize;     /* amount of space we advertise */
162         uint64_t        zv_volblocksize; /* volume block size */
163 #ifdef illumos
164         minor_t         zv_minor;       /* minor number */
165 #else
166         struct cdev     *zv_dev;        /* non-GEOM device */
167         struct g_provider *zv_provider; /* GEOM provider */
168 #endif
169         uint8_t         zv_min_bs;      /* minimum addressable block shift */
170         uint8_t         zv_flags;       /* readonly, dumpified, etc. */
171         objset_t        *zv_objset;     /* objset handle */
172 #ifdef illumos
173         uint32_t        zv_open_count[OTYPCNT]; /* open counts */
174 #endif
175         uint32_t        zv_total_opens; /* total open count */
176         uint32_t        zv_sync_cnt;    /* synchronous open count */
177         zilog_t         *zv_zilog;      /* ZIL handle */
178         list_t          zv_extents;     /* List of extents for dump */
179         rangelock_t     zv_rangelock;
180         dnode_t         *zv_dn;         /* dnode hold */
181 #ifndef illumos
182         int             zv_state;
183         int             zv_volmode;     /* Provide GEOM or cdev */
184         struct bio_queue_head zv_queue;
185         struct mtx      zv_queue_mtx;   /* zv_queue mutex */
186 #endif
187 } zvol_state_t;
188
189 typedef enum {
190         ZVOL_ASYNC_CREATE_MINORS,
191         ZVOL_ASYNC_REMOVE_MINORS,
192         ZVOL_ASYNC_RENAME_MINORS,
193         ZVOL_ASYNC_MAX
194 } zvol_async_op_t;
195
196 typedef struct {
197         zvol_async_op_t op;
198         char pool[ZFS_MAX_DATASET_NAME_LEN];
199         char name1[ZFS_MAX_DATASET_NAME_LEN];
200         char name2[ZFS_MAX_DATASET_NAME_LEN];
201 } zvol_task_t;
202
203 #ifndef illumos
204 static LIST_HEAD(, zvol_state) all_zvols;
205 #endif
206 /*
207  * zvol specific flags
208  */
209 #define ZVOL_RDONLY     0x1
210 #define ZVOL_DUMPIFIED  0x2
211 #define ZVOL_EXCL       0x4
212 #define ZVOL_WCE        0x8
213
214 /*
215  * zvol maximum transfer in one DMU tx.
216  */
217 int zvol_maxphys = DMU_MAX_ACCESS/2;
218
219 /*
220  * Toggle unmap functionality.
221  */
222 boolean_t zvol_unmap_enabled = B_TRUE;
223
224 /*
225  * If true, unmaps requested as synchronous are executed synchronously,
226  * otherwise all unmaps are asynchronous.
227  */
228 boolean_t zvol_unmap_sync_enabled = B_FALSE;
229
230 #ifndef illumos
231 SYSCTL_INT(_vfs_zfs_vol, OID_AUTO, unmap_enabled, CTLFLAG_RWTUN,
232     &zvol_unmap_enabled, 0,
233     "Enable UNMAP functionality");
234
235 SYSCTL_INT(_vfs_zfs_vol, OID_AUTO, unmap_sync_enabled, CTLFLAG_RWTUN,
236     &zvol_unmap_sync_enabled, 0,
237     "UNMAPs requested as sync are executed synchronously");
238
239 static d_open_t         zvol_d_open;
240 static d_close_t        zvol_d_close;
241 static d_read_t         zvol_read;
242 static d_write_t        zvol_write;
243 static d_ioctl_t        zvol_d_ioctl;
244 static d_strategy_t     zvol_strategy;
245
246 static struct cdevsw zvol_cdevsw = {
247         .d_version =    D_VERSION,
248         .d_open =       zvol_d_open,
249         .d_close =      zvol_d_close,
250         .d_read =       zvol_read,
251         .d_write =      zvol_write,
252         .d_ioctl =      zvol_d_ioctl,
253         .d_strategy =   zvol_strategy,
254         .d_name =       "zvol",
255         .d_flags =      D_DISK | D_TRACKCLOSE,
256 };
257
258 static void zvol_geom_run(zvol_state_t *zv);
259 static void zvol_geom_destroy(zvol_state_t *zv);
260 static int zvol_geom_access(struct g_provider *pp, int acr, int acw, int ace);
261 static void zvol_geom_start(struct bio *bp);
262 static void zvol_geom_worker(void *arg);
263 static void zvol_log_truncate(zvol_state_t *zv, dmu_tx_t *tx, uint64_t off,
264     uint64_t len, boolean_t sync);
265 #endif  /* !illumos */
266
267 extern int zfs_set_prop_nvlist(const char *, zprop_source_t,
268     nvlist_t *, nvlist_t *);
269 static int zvol_remove_zv(zvol_state_t *);
270 static int zvol_get_data(void *arg, lr_write_t *lr, char *buf,
271     struct lwb *lwb, zio_t *zio);
272 static int zvol_dumpify(zvol_state_t *zv);
273 static int zvol_dump_fini(zvol_state_t *zv);
274 static int zvol_dump_init(zvol_state_t *zv, boolean_t resize);
275
276 static void
277 zvol_size_changed(zvol_state_t *zv, uint64_t volsize)
278 {
279 #ifdef illumos
280         dev_t dev = makedevice(ddi_driver_major(zfs_dip), zv->zv_minor);
281
282         zv->zv_volsize = volsize;
283         VERIFY(ddi_prop_update_int64(dev, zfs_dip,
284             "Size", volsize) == DDI_SUCCESS);
285         VERIFY(ddi_prop_update_int64(dev, zfs_dip,
286             "Nblocks", lbtodb(volsize)) == DDI_SUCCESS);
287
288         /* Notify specfs to invalidate the cached size */
289         spec_size_invalidate(dev, VBLK);
290         spec_size_invalidate(dev, VCHR);
291 #else   /* !illumos */
292         zv->zv_volsize = volsize;
293         if (zv->zv_volmode == ZFS_VOLMODE_GEOM) {
294                 struct g_provider *pp;
295
296                 pp = zv->zv_provider;
297                 if (pp == NULL)
298                         return;
299                 g_topology_lock();
300
301                 /*
302                  * Do not invoke resize event when initial size was zero.
303                  * ZVOL initializes the size on first open, this is not
304                  * real resizing.
305                  */
306                 if (pp->mediasize == 0)
307                         pp->mediasize = zv->zv_volsize;
308                 else
309                         g_resize_provider(pp, zv->zv_volsize);
310                 g_topology_unlock();
311         }
312 #endif  /* illumos */
313 }
314
315 int
316 zvol_check_volsize(uint64_t volsize, uint64_t blocksize)
317 {
318         if (volsize == 0)
319                 return (SET_ERROR(EINVAL));
320
321         if (volsize % blocksize != 0)
322                 return (SET_ERROR(EINVAL));
323
324 #ifdef _ILP32
325         if (volsize - 1 > SPEC_MAXOFFSET_T)
326                 return (SET_ERROR(EOVERFLOW));
327 #endif
328         return (0);
329 }
330
331 int
332 zvol_check_volblocksize(uint64_t volblocksize)
333 {
334         if (volblocksize < SPA_MINBLOCKSIZE ||
335             volblocksize > SPA_OLD_MAXBLOCKSIZE ||
336             !ISP2(volblocksize))
337                 return (SET_ERROR(EDOM));
338
339         return (0);
340 }
341
342 int
343 zvol_get_stats(objset_t *os, nvlist_t *nv)
344 {
345         int error;
346         dmu_object_info_t doi;
347         uint64_t val;
348
349         error = zap_lookup(os, ZVOL_ZAP_OBJ, "size", 8, 1, &val);
350         if (error)
351                 return (error);
352
353         dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_VOLSIZE, val);
354
355         error = dmu_object_info(os, ZVOL_OBJ, &doi);
356
357         if (error == 0) {
358                 dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_VOLBLOCKSIZE,
359                     doi.doi_data_block_size);
360         }
361
362         return (error);
363 }
364
365 static zvol_state_t *
366 zvol_minor_lookup(const char *name)
367 {
368 #ifdef illumos
369         minor_t minor;
370 #endif
371         zvol_state_t *zv;
372
373         ASSERT(MUTEX_HELD(&zfsdev_state_lock));
374
375 #ifdef illumos
376         for (minor = 1; minor <= ZFSDEV_MAX_MINOR; minor++) {
377                 zv = zfsdev_get_soft_state(minor, ZSST_ZVOL);
378                 if (zv == NULL)
379                         continue;
380 #else
381         LIST_FOREACH(zv, &all_zvols, zv_links) {
382 #endif
383                 if (strcmp(zv->zv_name, name) == 0)
384                         return (zv);
385         }
386
387         return (NULL);
388 }
389
390 /* extent mapping arg */
391 struct maparg {
392         zvol_state_t    *ma_zv;
393         uint64_t        ma_blks;
394 };
395
396 /*ARGSUSED*/
397 static int
398 zvol_map_block(spa_t *spa, zilog_t *zilog, const blkptr_t *bp,
399     const zbookmark_phys_t *zb, const dnode_phys_t *dnp, void *arg)
400 {
401         struct maparg *ma = arg;
402         zvol_extent_t *ze;
403         int bs = ma->ma_zv->zv_volblocksize;
404
405         if (bp == NULL || BP_IS_HOLE(bp) ||
406             zb->zb_object != ZVOL_OBJ || zb->zb_level != 0)
407                 return (0);
408
409         VERIFY(!BP_IS_EMBEDDED(bp));
410
411         VERIFY3U(ma->ma_blks, ==, zb->zb_blkid);
412         ma->ma_blks++;
413
414         /* Abort immediately if we have encountered gang blocks */
415         if (BP_IS_GANG(bp))
416                 return (SET_ERROR(EFRAGS));
417
418         /*
419          * See if the block is at the end of the previous extent.
420          */
421         ze = list_tail(&ma->ma_zv->zv_extents);
422         if (ze &&
423             DVA_GET_VDEV(BP_IDENTITY(bp)) == DVA_GET_VDEV(&ze->ze_dva) &&
424             DVA_GET_OFFSET(BP_IDENTITY(bp)) ==
425             DVA_GET_OFFSET(&ze->ze_dva) + ze->ze_nblks * bs) {
426                 ze->ze_nblks++;
427                 return (0);
428         }
429
430         dprintf_bp(bp, "%s", "next blkptr:");
431
432         /* start a new extent */
433         ze = kmem_zalloc(sizeof (zvol_extent_t), KM_SLEEP);
434         ze->ze_dva = bp->blk_dva[0];    /* structure assignment */
435         ze->ze_nblks = 1;
436         list_insert_tail(&ma->ma_zv->zv_extents, ze);
437         return (0);
438 }
439
440 static void
441 zvol_free_extents(zvol_state_t *zv)
442 {
443         zvol_extent_t *ze;
444
445         while (ze = list_head(&zv->zv_extents)) {
446                 list_remove(&zv->zv_extents, ze);
447                 kmem_free(ze, sizeof (zvol_extent_t));
448         }
449 }
450
451 static int
452 zvol_get_lbas(zvol_state_t *zv)
453 {
454         objset_t *os = zv->zv_objset;
455         struct maparg   ma;
456         int             err;
457
458         ma.ma_zv = zv;
459         ma.ma_blks = 0;
460         zvol_free_extents(zv);
461
462         /* commit any in-flight changes before traversing the dataset */
463         txg_wait_synced(dmu_objset_pool(os), 0);
464         err = traverse_dataset(dmu_objset_ds(os), 0,
465             TRAVERSE_PRE | TRAVERSE_PREFETCH_METADATA, zvol_map_block, &ma);
466         if (err || ma.ma_blks != (zv->zv_volsize / zv->zv_volblocksize)) {
467                 zvol_free_extents(zv);
468                 return (err ? err : EIO);
469         }
470
471         return (0);
472 }
473
474 /* ARGSUSED */
475 void
476 zvol_create_cb(objset_t *os, void *arg, cred_t *cr, dmu_tx_t *tx)
477 {
478         zfs_creat_t *zct = arg;
479         nvlist_t *nvprops = zct->zct_props;
480         int error;
481         uint64_t volblocksize, volsize;
482
483         VERIFY(nvlist_lookup_uint64(nvprops,
484             zfs_prop_to_name(ZFS_PROP_VOLSIZE), &volsize) == 0);
485         if (nvlist_lookup_uint64(nvprops,
486             zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE), &volblocksize) != 0)
487                 volblocksize = zfs_prop_default_numeric(ZFS_PROP_VOLBLOCKSIZE);
488
489         /*
490          * These properties must be removed from the list so the generic
491          * property setting step won't apply to them.
492          */
493         VERIFY(nvlist_remove_all(nvprops,
494             zfs_prop_to_name(ZFS_PROP_VOLSIZE)) == 0);
495         (void) nvlist_remove_all(nvprops,
496             zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE));
497
498         error = dmu_object_claim(os, ZVOL_OBJ, DMU_OT_ZVOL, volblocksize,
499             DMU_OT_NONE, 0, tx);
500         ASSERT(error == 0);
501
502         error = zap_create_claim(os, ZVOL_ZAP_OBJ, DMU_OT_ZVOL_PROP,
503             DMU_OT_NONE, 0, tx);
504         ASSERT(error == 0);
505
506         error = zap_update(os, ZVOL_ZAP_OBJ, "size", 8, 1, &volsize, tx);
507         ASSERT(error == 0);
508 }
509
510 /*
511  * Replay a TX_TRUNCATE ZIL transaction if asked.  TX_TRUNCATE is how we
512  * implement DKIOCFREE/free-long-range.
513  */
514 static int
515 zvol_replay_truncate(void *arg1, void *arg2, boolean_t byteswap)
516 {
517         zvol_state_t *zv = arg1;
518         lr_truncate_t *lr = arg2;
519         uint64_t offset, length;
520
521         if (byteswap)
522                 byteswap_uint64_array(lr, sizeof (*lr));
523
524         offset = lr->lr_offset;
525         length = lr->lr_length;
526
527         return (dmu_free_long_range(zv->zv_objset, ZVOL_OBJ, offset, length));
528 }
529
530 /*
531  * Replay a TX_WRITE ZIL transaction that didn't get committed
532  * after a system failure
533  */
534 static int
535 zvol_replay_write(void *arg1, void *arg2, boolean_t byteswap)
536 {
537         zvol_state_t *zv = arg1;
538         lr_write_t *lr = arg2;
539         objset_t *os = zv->zv_objset;
540         char *data = (char *)(lr + 1);  /* data follows lr_write_t */
541         uint64_t offset, length;
542         dmu_tx_t *tx;
543         int error;
544
545         if (byteswap)
546                 byteswap_uint64_array(lr, sizeof (*lr));
547
548         offset = lr->lr_offset;
549         length = lr->lr_length;
550
551         /* If it's a dmu_sync() block, write the whole block */
552         if (lr->lr_common.lrc_reclen == sizeof (lr_write_t)) {
553                 uint64_t blocksize = BP_GET_LSIZE(&lr->lr_blkptr);
554                 if (length < blocksize) {
555                         offset -= offset % blocksize;
556                         length = blocksize;
557                 }
558         }
559
560         tx = dmu_tx_create(os);
561         dmu_tx_hold_write(tx, ZVOL_OBJ, offset, length);
562         error = dmu_tx_assign(tx, TXG_WAIT);
563         if (error) {
564                 dmu_tx_abort(tx);
565         } else {
566                 dmu_write(os, ZVOL_OBJ, offset, length, data, tx);
567                 dmu_tx_commit(tx);
568         }
569
570         return (error);
571 }
572
573 /* ARGSUSED */
574 static int
575 zvol_replay_err(void *arg1, void *arg2, boolean_t byteswap)
576 {
577         return (SET_ERROR(ENOTSUP));
578 }
579
580 /*
581  * Callback vectors for replaying records.
582  * Only TX_WRITE and TX_TRUNCATE are needed for zvol.
583  */
584 zil_replay_func_t *zvol_replay_vector[TX_MAX_TYPE] = {
585         zvol_replay_err,        /* 0 no such transaction type */
586         zvol_replay_err,        /* TX_CREATE */
587         zvol_replay_err,        /* TX_MKDIR */
588         zvol_replay_err,        /* TX_MKXATTR */
589         zvol_replay_err,        /* TX_SYMLINK */
590         zvol_replay_err,        /* TX_REMOVE */
591         zvol_replay_err,        /* TX_RMDIR */
592         zvol_replay_err,        /* TX_LINK */
593         zvol_replay_err,        /* TX_RENAME */
594         zvol_replay_write,      /* TX_WRITE */
595         zvol_replay_truncate,   /* TX_TRUNCATE */
596         zvol_replay_err,        /* TX_SETATTR */
597         zvol_replay_err,        /* TX_ACL */
598         zvol_replay_err,        /* TX_CREATE_ACL */
599         zvol_replay_err,        /* TX_CREATE_ATTR */
600         zvol_replay_err,        /* TX_CREATE_ACL_ATTR */
601         zvol_replay_err,        /* TX_MKDIR_ACL */
602         zvol_replay_err,        /* TX_MKDIR_ATTR */
603         zvol_replay_err,        /* TX_MKDIR_ACL_ATTR */
604         zvol_replay_err,        /* TX_WRITE2 */
605 };
606
607 #ifdef illumos
608 int
609 zvol_name2minor(const char *name, minor_t *minor)
610 {
611         zvol_state_t *zv;
612
613         mutex_enter(&zfsdev_state_lock);
614         zv = zvol_minor_lookup(name);
615         if (minor && zv)
616                 *minor = zv->zv_minor;
617         mutex_exit(&zfsdev_state_lock);
618         return (zv ? 0 : -1);
619 }
620 #endif  /* illumos */
621
622 /*
623  * Create a minor node (plus a whole lot more) for the specified volume.
624  */
625 static int
626 zvol_create_minor(const char *name)
627 {
628         zfs_soft_state_t *zs;
629         zvol_state_t *zv;
630         objset_t *os;
631 #ifdef illumos
632         dmu_object_info_t doi;
633         minor_t minor = 0;
634         char chrbuf[30], blkbuf[30];
635 #else
636         struct g_provider *pp;
637         struct g_geom *gp;
638         uint64_t mode;
639 #endif
640         int error;
641
642 #ifndef illumos
643         ZFS_LOG(1, "Creating ZVOL %s...", name);
644 #endif
645
646         mutex_enter(&zfsdev_state_lock);
647
648         if (zvol_minor_lookup(name) != NULL) {
649                 mutex_exit(&zfsdev_state_lock);
650                 return (SET_ERROR(EEXIST));
651         }
652
653         /* lie and say we're read-only */
654         error = dmu_objset_own(name, DMU_OST_ZVOL, B_TRUE, FTAG, &os);
655
656         if (error) {
657                 mutex_exit(&zfsdev_state_lock);
658                 return (error);
659         }
660
661 #ifdef illumos
662         if ((minor = zfsdev_minor_alloc()) == 0) {
663                 dmu_objset_disown(os, FTAG);
664                 mutex_exit(&zfsdev_state_lock);
665                 return (SET_ERROR(ENXIO));
666         }
667
668         if (ddi_soft_state_zalloc(zfsdev_state, minor) != DDI_SUCCESS) {
669                 dmu_objset_disown(os, FTAG);
670                 mutex_exit(&zfsdev_state_lock);
671                 return (SET_ERROR(EAGAIN));
672         }
673         (void) ddi_prop_update_string(minor, zfs_dip, ZVOL_PROP_NAME,
674             (char *)name);
675
676         (void) snprintf(chrbuf, sizeof (chrbuf), "%u,raw", minor);
677
678         if (ddi_create_minor_node(zfs_dip, chrbuf, S_IFCHR,
679             minor, DDI_PSEUDO, 0) == DDI_FAILURE) {
680                 ddi_soft_state_free(zfsdev_state, minor);
681                 dmu_objset_disown(os, FTAG);
682                 mutex_exit(&zfsdev_state_lock);
683                 return (SET_ERROR(EAGAIN));
684         }
685
686         (void) snprintf(blkbuf, sizeof (blkbuf), "%u", minor);
687
688         if (ddi_create_minor_node(zfs_dip, blkbuf, S_IFBLK,
689             minor, DDI_PSEUDO, 0) == DDI_FAILURE) {
690                 ddi_remove_minor_node(zfs_dip, chrbuf);
691                 ddi_soft_state_free(zfsdev_state, minor);
692                 dmu_objset_disown(os, FTAG);
693                 mutex_exit(&zfsdev_state_lock);
694                 return (SET_ERROR(EAGAIN));
695         }
696
697         zs = ddi_get_soft_state(zfsdev_state, minor);
698         zs->zss_type = ZSST_ZVOL;
699         zv = zs->zss_data = kmem_zalloc(sizeof (zvol_state_t), KM_SLEEP);
700 #else   /* !illumos */
701
702         zv = kmem_zalloc(sizeof(*zv), KM_SLEEP);
703         zv->zv_state = 0;
704         error = dsl_prop_get_integer(name,
705             zfs_prop_to_name(ZFS_PROP_VOLMODE), &mode, NULL);
706         if (error != 0 || mode == ZFS_VOLMODE_DEFAULT)
707                 mode = volmode;
708
709         zv->zv_volmode = mode;
710         if (zv->zv_volmode == ZFS_VOLMODE_GEOM) {
711                 g_topology_lock();
712                 gp = g_new_geomf(&zfs_zvol_class, "zfs::zvol::%s", name);
713                 gp->start = zvol_geom_start;
714                 gp->access = zvol_geom_access;
715                 pp = g_new_providerf(gp, "%s/%s", ZVOL_DRIVER, name);
716                 pp->flags |= G_PF_DIRECT_RECEIVE | G_PF_DIRECT_SEND;
717                 pp->sectorsize = DEV_BSIZE;
718                 pp->mediasize = 0;
719                 pp->private = zv;
720
721                 zv->zv_provider = pp;
722                 bioq_init(&zv->zv_queue);
723                 mtx_init(&zv->zv_queue_mtx, "zvol", NULL, MTX_DEF);
724         } else if (zv->zv_volmode == ZFS_VOLMODE_DEV) {
725                 struct make_dev_args args;
726
727                 make_dev_args_init(&args);
728                 args.mda_flags = MAKEDEV_CHECKNAME | MAKEDEV_WAITOK;
729                 args.mda_devsw = &zvol_cdevsw;
730                 args.mda_cr = NULL;
731                 args.mda_uid = UID_ROOT;
732                 args.mda_gid = GID_OPERATOR;
733                 args.mda_mode = 0640;
734                 args.mda_si_drv2 = zv;
735                 error = make_dev_s(&args, &zv->zv_dev,
736                     "%s/%s", ZVOL_DRIVER, name);
737                 if (error != 0) {
738                         kmem_free(zv, sizeof(*zv));
739                         dmu_objset_disown(os, FTAG);
740                         mutex_exit(&zfsdev_state_lock);
741                         return (error);
742                 }
743                 zv->zv_dev->si_iosize_max = MAXPHYS;
744         }
745         LIST_INSERT_HEAD(&all_zvols, zv, zv_links);
746 #endif  /* illumos */
747
748         (void) strlcpy(zv->zv_name, name, MAXPATHLEN);
749         zv->zv_min_bs = DEV_BSHIFT;
750 #ifdef illumos
751         zv->zv_minor = minor;
752 #endif
753         zv->zv_objset = os;
754         if (dmu_objset_is_snapshot(os) || !spa_writeable(dmu_objset_spa(os)))
755                 zv->zv_flags |= ZVOL_RDONLY;
756         rangelock_init(&zv->zv_rangelock, NULL, NULL);
757         list_create(&zv->zv_extents, sizeof (zvol_extent_t),
758             offsetof(zvol_extent_t, ze_node));
759 #ifdef illumos
760         /* get and cache the blocksize */
761         error = dmu_object_info(os, ZVOL_OBJ, &doi);
762         ASSERT(error == 0);
763         zv->zv_volblocksize = doi.doi_data_block_size;
764 #endif
765
766         if (spa_writeable(dmu_objset_spa(os))) {
767                 if (zil_replay_disable)
768                         zil_destroy(dmu_objset_zil(os), B_FALSE);
769                 else
770                         zil_replay(os, zv, zvol_replay_vector);
771         }
772         dmu_objset_disown(os, FTAG);
773         zv->zv_objset = NULL;
774
775         zvol_minors++;
776
777         mutex_exit(&zfsdev_state_lock);
778 #ifndef illumos
779         if (zv->zv_volmode == ZFS_VOLMODE_GEOM) {
780                 zvol_geom_run(zv);
781                 g_topology_unlock();
782         }
783
784         ZFS_LOG(1, "ZVOL %s created.", name);
785 #endif
786
787         return (0);
788 }
789
790 /*
791  * Remove minor node for the specified volume.
792  */
793 static int
794 zvol_remove_zv(zvol_state_t *zv)
795 {
796 #ifdef illumos
797         char nmbuf[20];
798         minor_t minor = zv->zv_minor;
799 #endif
800
801         ASSERT(MUTEX_HELD(&zfsdev_state_lock));
802         if (zv->zv_total_opens != 0)
803                 return (SET_ERROR(EBUSY));
804
805 #ifdef illumos
806         (void) snprintf(nmbuf, sizeof (nmbuf), "%u,raw", minor);
807         ddi_remove_minor_node(zfs_dip, nmbuf);
808
809         (void) snprintf(nmbuf, sizeof (nmbuf), "%u", minor);
810         ddi_remove_minor_node(zfs_dip, nmbuf);
811 #else
812         ZFS_LOG(1, "ZVOL %s destroyed.", zv->zv_name);
813
814         LIST_REMOVE(zv, zv_links);
815         if (zv->zv_volmode == ZFS_VOLMODE_GEOM) {
816                 g_topology_lock();
817                 zvol_geom_destroy(zv);
818                 g_topology_unlock();
819         } else if (zv->zv_volmode == ZFS_VOLMODE_DEV) {
820                 if (zv->zv_dev != NULL)
821                         destroy_dev(zv->zv_dev);
822         }
823 #endif
824
825         rangelock_fini(&zv->zv_rangelock);
826
827         kmem_free(zv, sizeof (zvol_state_t));
828 #ifdef illumos
829         ddi_soft_state_free(zfsdev_state, minor);
830 #endif
831         zvol_minors--;
832         return (0);
833 }
834
835 int
836 zvol_first_open(zvol_state_t *zv)
837 {
838         dmu_object_info_t doi;
839         objset_t *os;
840         uint64_t volsize;
841         int error;
842         uint64_t readonly;
843
844         /* lie and say we're read-only */
845         error = dmu_objset_own(zv->zv_name, DMU_OST_ZVOL, B_TRUE,
846             zvol_tag, &os);
847         if (error)
848                 return (error);
849
850         zv->zv_objset = os;
851         error = zap_lookup(os, ZVOL_ZAP_OBJ, "size", 8, 1, &volsize);
852         if (error) {
853                 ASSERT(error == 0);
854                 dmu_objset_disown(os, zvol_tag);
855                 return (error);
856         }
857
858         /* get and cache the blocksize */
859         error = dmu_object_info(os, ZVOL_OBJ, &doi);
860         if (error) {
861                 ASSERT(error == 0);
862                 dmu_objset_disown(os, zvol_tag);
863                 return (error);
864         }
865         zv->zv_volblocksize = doi.doi_data_block_size;
866
867         error = dnode_hold(os, ZVOL_OBJ, zvol_tag, &zv->zv_dn);
868         if (error) {
869                 dmu_objset_disown(os, zvol_tag);
870                 return (error);
871         }
872
873         zvol_size_changed(zv, volsize);
874         zv->zv_zilog = zil_open(os, zvol_get_data);
875
876         VERIFY(dsl_prop_get_integer(zv->zv_name, "readonly", &readonly,
877             NULL) == 0);
878         if (readonly || dmu_objset_is_snapshot(os) ||
879             !spa_writeable(dmu_objset_spa(os)))
880                 zv->zv_flags |= ZVOL_RDONLY;
881         else
882                 zv->zv_flags &= ~ZVOL_RDONLY;
883         return (error);
884 }
885
886 void
887 zvol_last_close(zvol_state_t *zv)
888 {
889         zil_close(zv->zv_zilog);
890         zv->zv_zilog = NULL;
891
892         dnode_rele(zv->zv_dn, zvol_tag);
893         zv->zv_dn = NULL;
894
895         /*
896          * Evict cached data
897          */
898         if (dsl_dataset_is_dirty(dmu_objset_ds(zv->zv_objset)) &&
899             !(zv->zv_flags & ZVOL_RDONLY))
900                 txg_wait_synced(dmu_objset_pool(zv->zv_objset), 0);
901         dmu_objset_evict_dbufs(zv->zv_objset);
902
903         dmu_objset_disown(zv->zv_objset, zvol_tag);
904         zv->zv_objset = NULL;
905 }
906
907 #ifdef illumos
908 int
909 zvol_prealloc(zvol_state_t *zv)
910 {
911         objset_t *os = zv->zv_objset;
912         dmu_tx_t *tx;
913         uint64_t refd, avail, usedobjs, availobjs;
914         uint64_t resid = zv->zv_volsize;
915         uint64_t off = 0;
916
917         /* Check the space usage before attempting to allocate the space */
918         dmu_objset_space(os, &refd, &avail, &usedobjs, &availobjs);
919         if (avail < zv->zv_volsize)
920                 return (SET_ERROR(ENOSPC));
921
922         /* Free old extents if they exist */
923         zvol_free_extents(zv);
924
925         while (resid != 0) {
926                 int error;
927                 uint64_t bytes = MIN(resid, SPA_OLD_MAXBLOCKSIZE);
928
929                 tx = dmu_tx_create(os);
930                 dmu_tx_hold_write(tx, ZVOL_OBJ, off, bytes);
931                 error = dmu_tx_assign(tx, TXG_WAIT);
932                 if (error) {
933                         dmu_tx_abort(tx);
934                         (void) dmu_free_long_range(os, ZVOL_OBJ, 0, off);
935                         return (error);
936                 }
937                 dmu_prealloc(os, ZVOL_OBJ, off, bytes, tx);
938                 dmu_tx_commit(tx);
939                 off += bytes;
940                 resid -= bytes;
941         }
942         txg_wait_synced(dmu_objset_pool(os), 0);
943
944         return (0);
945 }
946 #endif  /* illumos */
947
948 static int
949 zvol_update_volsize(objset_t *os, uint64_t volsize)
950 {
951         dmu_tx_t *tx;
952         int error;
953
954         ASSERT(MUTEX_HELD(&zfsdev_state_lock));
955
956         tx = dmu_tx_create(os);
957         dmu_tx_hold_zap(tx, ZVOL_ZAP_OBJ, TRUE, NULL);
958         dmu_tx_mark_netfree(tx);
959         error = dmu_tx_assign(tx, TXG_WAIT);
960         if (error) {
961                 dmu_tx_abort(tx);
962                 return (error);
963         }
964
965         error = zap_update(os, ZVOL_ZAP_OBJ, "size", 8, 1,
966             &volsize, tx);
967         dmu_tx_commit(tx);
968
969         if (error == 0)
970                 error = dmu_free_long_range(os,
971                     ZVOL_OBJ, volsize, DMU_OBJECT_END);
972         return (error);
973 }
974
975 void
976 zvol_remove_minors_impl(const char *name)
977 {
978 #ifdef illumos
979         zvol_state_t *zv;
980         char *namebuf;
981         minor_t minor;
982
983         namebuf = kmem_zalloc(strlen(name) + 2, KM_SLEEP);
984         (void) strncpy(namebuf, name, strlen(name));
985         (void) strcat(namebuf, "/");
986         mutex_enter(&zfsdev_state_lock);
987         for (minor = 1; minor <= ZFSDEV_MAX_MINOR; minor++) {
988
989                 zv = zfsdev_get_soft_state(minor, ZSST_ZVOL);
990                 if (zv == NULL)
991                         continue;
992                 if (strncmp(namebuf, zv->zv_name, strlen(namebuf)) == 0)
993                         (void) zvol_remove_zv(zv);
994         }
995         kmem_free(namebuf, strlen(name) + 2);
996
997         mutex_exit(&zfsdev_state_lock);
998 #else   /* !illumos */
999         zvol_state_t *zv, *tzv;
1000         size_t namelen;
1001
1002         namelen = strlen(name);
1003
1004         mutex_enter(&zfsdev_state_lock);
1005
1006         LIST_FOREACH_SAFE(zv, &all_zvols, zv_links, tzv) {
1007                 if (strcmp(zv->zv_name, name) == 0 ||
1008                     (strncmp(zv->zv_name, name, namelen) == 0 &&
1009                     strlen(zv->zv_name) > namelen && (zv->zv_name[namelen] == '/' ||
1010                     zv->zv_name[namelen] == '@'))) {
1011                         (void) zvol_remove_zv(zv);
1012                 }
1013         }
1014
1015         mutex_exit(&zfsdev_state_lock);
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 /* ARGSUSED */
1319 static void
1320 zvol_get_done(zgd_t *zgd, int error)
1321 {
1322         if (zgd->zgd_db)
1323                 dmu_buf_rele(zgd->zgd_db, zgd);
1324
1325         rangelock_exit(zgd->zgd_lr);
1326
1327         kmem_free(zgd, sizeof (zgd_t));
1328 }
1329
1330 /*
1331  * Get data to generate a TX_WRITE intent log record.
1332  */
1333 static int
1334 zvol_get_data(void *arg, lr_write_t *lr, char *buf, struct lwb *lwb, zio_t *zio)
1335 {
1336         zvol_state_t *zv = arg;
1337         uint64_t offset = lr->lr_offset;
1338         uint64_t size = lr->lr_length;  /* length of user data */
1339         dmu_buf_t *db;
1340         zgd_t *zgd;
1341         int error;
1342
1343         ASSERT3P(lwb, !=, NULL);
1344         ASSERT3P(zio, !=, NULL);
1345         ASSERT3U(size, !=, 0);
1346
1347         zgd = kmem_zalloc(sizeof (zgd_t), KM_SLEEP);
1348         zgd->zgd_lwb = lwb;
1349
1350         /*
1351          * Write records come in two flavors: immediate and indirect.
1352          * For small writes it's cheaper to store the data with the
1353          * log record (immediate); for large writes it's cheaper to
1354          * sync the data and get a pointer to it (indirect) so that
1355          * we don't have to write the data twice.
1356          */
1357         if (buf != NULL) { /* immediate write */
1358                 zgd->zgd_lr = rangelock_enter(&zv->zv_rangelock, offset, size,
1359                     RL_READER);
1360                 error = dmu_read_by_dnode(zv->zv_dn, offset, size, buf,
1361                     DMU_READ_NO_PREFETCH);
1362         } else { /* indirect write */
1363                 /*
1364                  * Have to lock the whole block to ensure when it's written out
1365                  * and its checksum is being calculated that no one can change
1366                  * the data. Contrarily to zfs_get_data we need not re-check
1367                  * blocksize after we get the lock because it cannot be changed.
1368                  */
1369                 size = zv->zv_volblocksize;
1370                 offset = P2ALIGN(offset, size);
1371                 zgd->zgd_lr = rangelock_enter(&zv->zv_rangelock, offset, size,
1372                     RL_READER);
1373                 error = dmu_buf_hold_by_dnode(zv->zv_dn, offset, zgd, &db,
1374                     DMU_READ_NO_PREFETCH);
1375                 if (error == 0) {
1376                         blkptr_t *bp = &lr->lr_blkptr;
1377
1378                         zgd->zgd_db = db;
1379                         zgd->zgd_bp = bp;
1380
1381                         ASSERT(db->db_offset == offset);
1382                         ASSERT(db->db_size == size);
1383
1384                         error = dmu_sync(zio, lr->lr_common.lrc_txg,
1385                             zvol_get_done, zgd);
1386
1387                         if (error == 0)
1388                                 return (0);
1389                 }
1390         }
1391
1392         zvol_get_done(zgd, error);
1393
1394         return (error);
1395 }
1396
1397 /*
1398  * zvol_log_write() handles synchronous writes using TX_WRITE ZIL transactions.
1399  *
1400  * We store data in the log buffers if it's small enough.
1401  * Otherwise we will later flush the data out via dmu_sync().
1402  */
1403 ssize_t zvol_immediate_write_sz = 32768;
1404 #ifdef _KERNEL
1405 SYSCTL_LONG(_vfs_zfs_vol, OID_AUTO, immediate_write_sz, CTLFLAG_RWTUN,
1406     &zvol_immediate_write_sz, 0, "Minimal size for indirect log write");
1407 #endif
1408
1409 static void
1410 zvol_log_write(zvol_state_t *zv, dmu_tx_t *tx, offset_t off, ssize_t resid,
1411     boolean_t sync)
1412 {
1413         uint32_t blocksize = zv->zv_volblocksize;
1414         zilog_t *zilog = zv->zv_zilog;
1415         itx_wr_state_t write_state;
1416
1417         if (zil_replaying(zilog, tx))
1418                 return;
1419
1420         if (zilog->zl_logbias == ZFS_LOGBIAS_THROUGHPUT)
1421                 write_state = WR_INDIRECT;
1422         else if (!spa_has_slogs(zilog->zl_spa) &&
1423             resid >= blocksize && blocksize > zvol_immediate_write_sz)
1424                 write_state = WR_INDIRECT;
1425         else if (sync)
1426                 write_state = WR_COPIED;
1427         else
1428                 write_state = WR_NEED_COPY;
1429
1430         while (resid) {
1431                 itx_t *itx;
1432                 lr_write_t *lr;
1433                 itx_wr_state_t wr_state = write_state;
1434                 ssize_t len = resid;
1435
1436                 if (wr_state == WR_COPIED && resid > zil_max_copied_data(zilog))
1437                         wr_state = WR_NEED_COPY;
1438                 else if (wr_state == WR_INDIRECT)
1439                         len = MIN(blocksize - P2PHASE(off, blocksize), resid);
1440
1441                 itx = zil_itx_create(TX_WRITE, sizeof (*lr) +
1442                     (wr_state == WR_COPIED ? len : 0));
1443                 lr = (lr_write_t *)&itx->itx_lr;
1444                 if (wr_state == WR_COPIED && dmu_read_by_dnode(zv->zv_dn,
1445                     off, len, lr + 1, DMU_READ_NO_PREFETCH) != 0) {
1446                         zil_itx_destroy(itx);
1447                         itx = zil_itx_create(TX_WRITE, sizeof (*lr));
1448                         lr = (lr_write_t *)&itx->itx_lr;
1449                         wr_state = WR_NEED_COPY;
1450                 }
1451
1452                 itx->itx_wr_state = wr_state;
1453                 lr->lr_foid = ZVOL_OBJ;
1454                 lr->lr_offset = off;
1455                 lr->lr_length = len;
1456                 lr->lr_blkoff = 0;
1457                 BP_ZERO(&lr->lr_blkptr);
1458
1459                 itx->itx_private = zv;
1460
1461                 if (!sync && (zv->zv_sync_cnt == 0))
1462                         itx->itx_sync = B_FALSE;
1463
1464                 zil_itx_assign(zilog, itx, tx);
1465
1466                 off += len;
1467                 resid -= len;
1468         }
1469 }
1470
1471 #ifdef illumos
1472 static int
1473 zvol_dumpio_vdev(vdev_t *vd, void *addr, uint64_t offset, uint64_t origoffset,
1474     uint64_t size, boolean_t doread, boolean_t isdump)
1475 {
1476         vdev_disk_t *dvd;
1477         int c;
1478         int numerrors = 0;
1479
1480         if (vd->vdev_ops == &vdev_mirror_ops ||
1481             vd->vdev_ops == &vdev_replacing_ops ||
1482             vd->vdev_ops == &vdev_spare_ops) {
1483                 for (c = 0; c < vd->vdev_children; c++) {
1484                         int err = zvol_dumpio_vdev(vd->vdev_child[c],
1485                             addr, offset, origoffset, size, doread, isdump);
1486                         if (err != 0) {
1487                                 numerrors++;
1488                         } else if (doread) {
1489                                 break;
1490                         }
1491                 }
1492         }
1493
1494         if (!vd->vdev_ops->vdev_op_leaf && vd->vdev_ops != &vdev_raidz_ops)
1495                 return (numerrors < vd->vdev_children ? 0 : EIO);
1496
1497         if (doread && !vdev_readable(vd))
1498                 return (SET_ERROR(EIO));
1499         else if (!doread && !vdev_writeable(vd))
1500                 return (SET_ERROR(EIO));
1501
1502         if (vd->vdev_ops == &vdev_raidz_ops) {
1503                 return (vdev_raidz_physio(vd,
1504                     addr, size, offset, origoffset, doread, isdump));
1505         }
1506
1507         offset += VDEV_LABEL_START_SIZE;
1508
1509         if (ddi_in_panic() || isdump) {
1510                 ASSERT(!doread);
1511                 if (doread)
1512                         return (SET_ERROR(EIO));
1513                 dvd = vd->vdev_tsd;
1514                 ASSERT3P(dvd, !=, NULL);
1515                 return (ldi_dump(dvd->vd_lh, addr, lbtodb(offset),
1516                     lbtodb(size)));
1517         } else {
1518                 dvd = vd->vdev_tsd;
1519                 ASSERT3P(dvd, !=, NULL);
1520                 return (vdev_disk_ldi_physio(dvd->vd_lh, addr, size,
1521                     offset, doread ? B_READ : B_WRITE));
1522         }
1523 }
1524
1525 static int
1526 zvol_dumpio(zvol_state_t *zv, void *addr, uint64_t offset, uint64_t size,
1527     boolean_t doread, boolean_t isdump)
1528 {
1529         vdev_t *vd;
1530         int error;
1531         zvol_extent_t *ze;
1532         spa_t *spa = dmu_objset_spa(zv->zv_objset);
1533
1534         /* Must be sector aligned, and not stradle a block boundary. */
1535         if (P2PHASE(offset, DEV_BSIZE) || P2PHASE(size, DEV_BSIZE) ||
1536             P2BOUNDARY(offset, size, zv->zv_volblocksize)) {
1537                 return (SET_ERROR(EINVAL));
1538         }
1539         ASSERT(size <= zv->zv_volblocksize);
1540
1541         /* Locate the extent this belongs to */
1542         ze = list_head(&zv->zv_extents);
1543         while (offset >= ze->ze_nblks * zv->zv_volblocksize) {
1544                 offset -= ze->ze_nblks * zv->zv_volblocksize;
1545                 ze = list_next(&zv->zv_extents, ze);
1546         }
1547
1548         if (ze == NULL)
1549                 return (SET_ERROR(EINVAL));
1550
1551         if (!ddi_in_panic())
1552                 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
1553
1554         vd = vdev_lookup_top(spa, DVA_GET_VDEV(&ze->ze_dva));
1555         offset += DVA_GET_OFFSET(&ze->ze_dva);
1556         error = zvol_dumpio_vdev(vd, addr, offset, DVA_GET_OFFSET(&ze->ze_dva),
1557             size, doread, isdump);
1558
1559         if (!ddi_in_panic())
1560                 spa_config_exit(spa, SCL_STATE, FTAG);
1561
1562         return (error);
1563 }
1564
1565 int
1566 zvol_strategy(buf_t *bp)
1567 {
1568         zfs_soft_state_t *zs = NULL;
1569 #else   /* !illumos */
1570 void
1571 zvol_strategy(struct bio *bp)
1572 {
1573 #endif  /* illumos */
1574         zvol_state_t *zv;
1575         uint64_t off, volsize;
1576         size_t resid;
1577         char *addr;
1578         objset_t *os;
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         locked_range_t *lr = rangelock_enter(&zv->zv_rangelock, 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         rangelock_exit(lr);
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         int error = 0;
1833
1834 #ifdef illumos
1835         zv = zfsdev_get_soft_state(minor, ZSST_ZVOL);
1836         if (zv == NULL)
1837                 return (SET_ERROR(ENXIO));
1838 #else
1839         zv = dev->si_drv2;
1840 #endif
1841
1842         volsize = zv->zv_volsize;
1843         /* uio_loffset == volsize isn't an error as its required for EOF processing. */
1844         if (uio->uio_resid > 0 &&
1845             (uio->uio_loffset < 0 || uio->uio_loffset > volsize))
1846                 return (SET_ERROR(EIO));
1847
1848 #ifdef illumos
1849         if (zv->zv_flags & ZVOL_DUMPIFIED) {
1850                 error = physio(zvol_strategy, NULL, dev, B_READ,
1851                     zvol_minphys, uio);
1852                 return (error);
1853         }
1854 #endif
1855
1856         locked_range_t *lr = rangelock_enter(&zv->zv_rangelock,
1857             uio->uio_loffset, uio->uio_resid, RL_READER);
1858         while (uio->uio_resid > 0 && uio->uio_loffset < volsize) {
1859                 uint64_t bytes = MIN(uio->uio_resid, DMU_MAX_ACCESS >> 1);
1860
1861                 /* don't read past the end */
1862                 if (bytes > volsize - uio->uio_loffset)
1863                         bytes = volsize - uio->uio_loffset;
1864
1865                 error =  dmu_read_uio_dnode(zv->zv_dn, uio, bytes);
1866                 if (error) {
1867                         /* convert checksum errors into IO errors */
1868                         if (error == ECKSUM)
1869                                 error = SET_ERROR(EIO);
1870                         break;
1871                 }
1872         }
1873         rangelock_exit(lr);
1874
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         int error = 0;
1892         boolean_t sync;
1893
1894 #ifdef illumos
1895         zv = zfsdev_get_soft_state(minor, ZSST_ZVOL);
1896         if (zv == NULL)
1897                 return (SET_ERROR(ENXIO));
1898 #else
1899         zv = dev->si_drv2;
1900 #endif
1901
1902         volsize = zv->zv_volsize;
1903         /* uio_loffset == volsize isn't an error as its required for EOF processing. */
1904         if (uio->uio_resid > 0 &&
1905             (uio->uio_loffset < 0 || uio->uio_loffset > volsize))
1906                 return (SET_ERROR(EIO));
1907
1908 #ifdef illumos
1909         if (zv->zv_flags & ZVOL_DUMPIFIED) {
1910                 error = physio(zvol_strategy, NULL, dev, B_WRITE,
1911                     zvol_minphys, uio);
1912                 return (error);
1913         }
1914
1915         sync = !(zv->zv_flags & ZVOL_WCE) ||
1916 #else
1917         sync = (ioflag & IO_SYNC) ||
1918 #endif
1919             (zv->zv_objset->os_sync == ZFS_SYNC_ALWAYS);
1920
1921         locked_range_t *lr = rangelock_enter(&zv->zv_rangelock,
1922             uio->uio_loffset, uio->uio_resid, RL_WRITER);
1923         while (uio->uio_resid > 0 && uio->uio_loffset < volsize) {
1924                 uint64_t bytes = MIN(uio->uio_resid, DMU_MAX_ACCESS >> 1);
1925                 uint64_t off = uio->uio_loffset;
1926                 dmu_tx_t *tx = dmu_tx_create(zv->zv_objset);
1927
1928                 if (bytes > volsize - off)      /* don't write past the end */
1929                         bytes = volsize - off;
1930
1931                 dmu_tx_hold_write(tx, ZVOL_OBJ, off, bytes);
1932                 error = dmu_tx_assign(tx, TXG_WAIT);
1933                 if (error) {
1934                         dmu_tx_abort(tx);
1935                         break;
1936                 }
1937                 error = dmu_write_uio_dnode(zv->zv_dn, uio, bytes, tx);
1938                 if (error == 0)
1939                         zvol_log_write(zv, tx, off, bytes, sync);
1940                 dmu_tx_commit(tx);
1941
1942                 if (error)
1943                         break;
1944         }
1945         rangelock_exit(lr);
1946
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 **dnode_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 && dnode_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_rangelock;
2039         *dnode_hdl = zv->zv_dn;
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         locked_range_t *lr;
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                 lr = rangelock_enter(&zv->zv_rangelock, 0, zv->zv_volsize,
2237                     RL_WRITER);
2238                 error = zvol_dumpify(zv);
2239                 rangelock_exit(lr);
2240                 break;
2241
2242         case DKIOCDUMPFINI:
2243                 if (!(zv->zv_flags & ZVOL_DUMPIFIED))
2244                         break;
2245                 lr = rangelock_enter(&zv->zv_rangelock, 0, zv->zv_volsize,
2246                     RL_WRITER);
2247                 error = zvol_dump_fini(zv);
2248                 rangelock_exit(lr);
2249                 break;
2250
2251         case DKIOCFREE:
2252         {
2253                 dkioc_free_list_t *dfl;
2254                 dmu_tx_t *tx;
2255
2256                 if (!zvol_unmap_enabled)
2257                         break;
2258
2259                 if (!(flag & FKIOCTL)) {
2260                         error = dfl_copyin((void *)arg, &dfl, flag, KM_SLEEP);
2261                         if (error != 0)
2262                                 break;
2263                 } else {
2264                         dfl = (dkioc_free_list_t *)arg;
2265                         ASSERT3U(dfl->dfl_num_exts, <=, DFL_COPYIN_MAX_EXTS);
2266                         if (dfl->dfl_num_exts > DFL_COPYIN_MAX_EXTS) {
2267                                 error = SET_ERROR(EINVAL);
2268                                 break;
2269                         }
2270                 }
2271
2272                 mutex_exit(&zfsdev_state_lock);
2273
2274                 for (int i = 0; i < dfl->dfl_num_exts; i++) {
2275                         uint64_t start = dfl->dfl_exts[i].dfle_start,
2276                             length = dfl->dfl_exts[i].dfle_length,
2277                             end = start + length;
2278
2279                         /*
2280                          * Apply Postel's Law to length-checking.  If they
2281                          * overshoot, just blank out until the end, if there's
2282                          * a need to blank out anything.
2283                          */
2284                         if (start >= zv->zv_volsize)
2285                                 continue;       /* No need to do anything... */
2286                         if (end > zv->zv_volsize) {
2287                                 end = DMU_OBJECT_END;
2288                                 length = end - start;
2289                         }
2290
2291                         lr = rangelock_enter(&zv->zv_rangelock, start, length,
2292                             RL_WRITER);
2293                         tx = dmu_tx_create(zv->zv_objset);
2294                         error = dmu_tx_assign(tx, TXG_WAIT);
2295                         if (error != 0) {
2296                                 dmu_tx_abort(tx);
2297                         } else {
2298                                 zvol_log_truncate(zv, tx, start, length,
2299                                     B_TRUE);
2300                                 dmu_tx_commit(tx);
2301                                 error = dmu_free_long_range(zv->zv_objset,
2302                                     ZVOL_OBJ, start, length);
2303                         }
2304
2305                         rangelock_exit(lr);
2306
2307                         if (error != 0)
2308                                 break;
2309                 }
2310
2311                 /*
2312                  * If the write-cache is disabled, 'sync' property
2313                  * is set to 'always', or if the caller is asking for
2314                  * a synchronous free, commit this operation to the zil.
2315                  * This will sync any previous uncommitted writes to the
2316                  * zvol object.
2317                  * Can be overridden by the zvol_unmap_sync_enabled tunable.
2318                  */
2319                 if ((error == 0) && zvol_unmap_sync_enabled &&
2320                     (!(zv->zv_flags & ZVOL_WCE) ||
2321                     (zv->zv_objset->os_sync == ZFS_SYNC_ALWAYS) ||
2322                     (dfl->dfl_flags & DF_WAIT_SYNC))) {
2323                         zil_commit(zv->zv_zilog, ZVOL_OBJ);
2324                 }
2325
2326                 if (!(flag & FKIOCTL))
2327                         dfl_free(dfl);
2328
2329                 return (error);
2330         }
2331
2332         default:
2333                 error = SET_ERROR(ENOTTY);
2334                 break;
2335
2336         }
2337         mutex_exit(&zfsdev_state_lock);
2338         return (error);
2339 }
2340 #endif  /* illumos */
2341
2342 int
2343 zvol_busy(void)
2344 {
2345         return (zvol_minors != 0);
2346 }
2347
2348 void
2349 zvol_init(void)
2350 {
2351         VERIFY(ddi_soft_state_init(&zfsdev_state, sizeof (zfs_soft_state_t),
2352             1) == 0);
2353 #ifdef illumos
2354         mutex_init(&zfsdev_state_lock, NULL, MUTEX_DEFAULT, NULL);
2355 #else
2356         ZFS_LOG(1, "ZVOL Initialized.");
2357 #endif
2358 }
2359
2360 void
2361 zvol_fini(void)
2362 {
2363 #ifdef illumos
2364         mutex_destroy(&zfsdev_state_lock);
2365 #endif
2366         ddi_soft_state_fini(&zfsdev_state);
2367         ZFS_LOG(1, "ZVOL Deinitialized.");
2368 }
2369
2370 #ifdef illumos
2371 /*ARGSUSED*/
2372 static int
2373 zfs_mvdev_dump_feature_check(void *arg, dmu_tx_t *tx)
2374 {
2375         spa_t *spa = dmu_tx_pool(tx)->dp_spa;
2376
2377         if (spa_feature_is_active(spa, SPA_FEATURE_MULTI_VDEV_CRASH_DUMP))
2378                 return (1);
2379         return (0);
2380 }
2381
2382 /*ARGSUSED*/
2383 static void
2384 zfs_mvdev_dump_activate_feature_sync(void *arg, dmu_tx_t *tx)
2385 {
2386         spa_t *spa = dmu_tx_pool(tx)->dp_spa;
2387
2388         spa_feature_incr(spa, SPA_FEATURE_MULTI_VDEV_CRASH_DUMP, tx);
2389 }
2390
2391 static int
2392 zvol_dump_init(zvol_state_t *zv, boolean_t resize)
2393 {
2394         dmu_tx_t *tx;
2395         int error;
2396         objset_t *os = zv->zv_objset;
2397         spa_t *spa = dmu_objset_spa(os);
2398         vdev_t *vd = spa->spa_root_vdev;
2399         nvlist_t *nv = NULL;
2400         uint64_t version = spa_version(spa);
2401         uint64_t checksum, compress, refresrv, vbs, dedup;
2402
2403         ASSERT(MUTEX_HELD(&zfsdev_state_lock));
2404         ASSERT(vd->vdev_ops == &vdev_root_ops);
2405
2406         error = dmu_free_long_range(zv->zv_objset, ZVOL_OBJ, 0,
2407             DMU_OBJECT_END);
2408         if (error != 0)
2409                 return (error);
2410         /* wait for dmu_free_long_range to actually free the blocks */
2411         txg_wait_synced(dmu_objset_pool(zv->zv_objset), 0);
2412
2413         /*
2414          * If the pool on which the dump device is being initialized has more
2415          * than one child vdev, check that the MULTI_VDEV_CRASH_DUMP feature is
2416          * enabled.  If so, bump that feature's counter to indicate that the
2417          * feature is active. We also check the vdev type to handle the
2418          * following case:
2419          *   # zpool create test raidz disk1 disk2 disk3
2420          *   Now have spa_root_vdev->vdev_children == 1 (the raidz vdev),
2421          *   the raidz vdev itself has 3 children.
2422          */
2423         if (vd->vdev_children > 1 || vd->vdev_ops == &vdev_raidz_ops) {
2424                 if (!spa_feature_is_enabled(spa,
2425                     SPA_FEATURE_MULTI_VDEV_CRASH_DUMP))
2426                         return (SET_ERROR(ENOTSUP));
2427                 (void) dsl_sync_task(spa_name(spa),
2428                     zfs_mvdev_dump_feature_check,
2429                     zfs_mvdev_dump_activate_feature_sync, NULL,
2430                     2, ZFS_SPACE_CHECK_RESERVED);
2431         }
2432
2433         if (!resize) {
2434                 error = dsl_prop_get_integer(zv->zv_name,
2435                     zfs_prop_to_name(ZFS_PROP_COMPRESSION), &compress, NULL);
2436                 if (error == 0) {
2437                         error = dsl_prop_get_integer(zv->zv_name,
2438                             zfs_prop_to_name(ZFS_PROP_CHECKSUM), &checksum,
2439                             NULL);
2440                 }
2441                 if (error == 0) {
2442                         error = dsl_prop_get_integer(zv->zv_name,
2443                             zfs_prop_to_name(ZFS_PROP_REFRESERVATION),
2444                             &refresrv, NULL);
2445                 }
2446                 if (error == 0) {
2447                         error = dsl_prop_get_integer(zv->zv_name,
2448                             zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE), &vbs,
2449                             NULL);
2450                 }
2451                 if (version >= SPA_VERSION_DEDUP && error == 0) {
2452                         error = dsl_prop_get_integer(zv->zv_name,
2453                             zfs_prop_to_name(ZFS_PROP_DEDUP), &dedup, NULL);
2454                 }
2455         }
2456         if (error != 0)
2457                 return (error);
2458
2459         tx = dmu_tx_create(os);
2460         dmu_tx_hold_zap(tx, ZVOL_ZAP_OBJ, TRUE, NULL);
2461         dmu_tx_hold_bonus(tx, ZVOL_OBJ);
2462         error = dmu_tx_assign(tx, TXG_WAIT);
2463         if (error != 0) {
2464                 dmu_tx_abort(tx);
2465                 return (error);
2466         }
2467
2468         /*
2469          * If we are resizing the dump device then we only need to
2470          * update the refreservation to match the newly updated
2471          * zvolsize. Otherwise, we save off the original state of the
2472          * zvol so that we can restore them if the zvol is ever undumpified.
2473          */
2474         if (resize) {
2475                 error = zap_update(os, ZVOL_ZAP_OBJ,
2476                     zfs_prop_to_name(ZFS_PROP_REFRESERVATION), 8, 1,
2477                     &zv->zv_volsize, tx);
2478         } else {
2479                 error = zap_update(os, ZVOL_ZAP_OBJ,
2480                     zfs_prop_to_name(ZFS_PROP_COMPRESSION), 8, 1,
2481                     &compress, tx);
2482                 if (error == 0) {
2483                         error = zap_update(os, ZVOL_ZAP_OBJ,
2484                             zfs_prop_to_name(ZFS_PROP_CHECKSUM), 8, 1,
2485                             &checksum, tx);
2486                 }
2487                 if (error == 0) {
2488                         error = zap_update(os, ZVOL_ZAP_OBJ,
2489                             zfs_prop_to_name(ZFS_PROP_REFRESERVATION), 8, 1,
2490                             &refresrv, tx);
2491                 }
2492                 if (error == 0) {
2493                         error = zap_update(os, ZVOL_ZAP_OBJ,
2494                             zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE), 8, 1,
2495                             &vbs, tx);
2496                 }
2497                 if (error == 0) {
2498                         error = dmu_object_set_blocksize(
2499                             os, ZVOL_OBJ, SPA_OLD_MAXBLOCKSIZE, 0, tx);
2500                 }
2501                 if (version >= SPA_VERSION_DEDUP && error == 0) {
2502                         error = zap_update(os, ZVOL_ZAP_OBJ,
2503                             zfs_prop_to_name(ZFS_PROP_DEDUP), 8, 1,
2504                             &dedup, tx);
2505                 }
2506                 if (error == 0)
2507                         zv->zv_volblocksize = SPA_OLD_MAXBLOCKSIZE;
2508         }
2509         dmu_tx_commit(tx);
2510
2511         /*
2512          * We only need update the zvol's property if we are initializing
2513          * the dump area for the first time.
2514          */
2515         if (error == 0 && !resize) {
2516                 /*
2517                  * If MULTI_VDEV_CRASH_DUMP is active, use the NOPARITY checksum
2518                  * function.  Otherwise, use the old default -- OFF.
2519                  */
2520                 checksum = spa_feature_is_active(spa,
2521                     SPA_FEATURE_MULTI_VDEV_CRASH_DUMP) ? ZIO_CHECKSUM_NOPARITY :
2522                     ZIO_CHECKSUM_OFF;
2523
2524                 VERIFY(nvlist_alloc(&nv, NV_UNIQUE_NAME, KM_SLEEP) == 0);
2525                 VERIFY(nvlist_add_uint64(nv,
2526                     zfs_prop_to_name(ZFS_PROP_REFRESERVATION), 0) == 0);
2527                 VERIFY(nvlist_add_uint64(nv,
2528                     zfs_prop_to_name(ZFS_PROP_COMPRESSION),
2529                     ZIO_COMPRESS_OFF) == 0);
2530                 VERIFY(nvlist_add_uint64(nv,
2531                     zfs_prop_to_name(ZFS_PROP_CHECKSUM),
2532                     checksum) == 0);
2533                 if (version >= SPA_VERSION_DEDUP) {
2534                         VERIFY(nvlist_add_uint64(nv,
2535                             zfs_prop_to_name(ZFS_PROP_DEDUP),
2536                             ZIO_CHECKSUM_OFF) == 0);
2537                 }
2538
2539                 error = zfs_set_prop_nvlist(zv->zv_name, ZPROP_SRC_LOCAL,
2540                     nv, NULL);
2541                 nvlist_free(nv);
2542         }
2543
2544         /* Allocate the space for the dump */
2545         if (error == 0)
2546                 error = zvol_prealloc(zv);
2547         return (error);
2548 }
2549
2550 static int
2551 zvol_dumpify(zvol_state_t *zv)
2552 {
2553         int error = 0;
2554         uint64_t dumpsize = 0;
2555         dmu_tx_t *tx;
2556         objset_t *os = zv->zv_objset;
2557
2558         if (zv->zv_flags & ZVOL_RDONLY)
2559                 return (SET_ERROR(EROFS));
2560
2561         if (zap_lookup(zv->zv_objset, ZVOL_ZAP_OBJ, ZVOL_DUMPSIZE,
2562             8, 1, &dumpsize) != 0 || dumpsize != zv->zv_volsize) {
2563                 boolean_t resize = (dumpsize > 0);
2564
2565                 if ((error = zvol_dump_init(zv, resize)) != 0) {
2566                         (void) zvol_dump_fini(zv);
2567                         return (error);
2568                 }
2569         }
2570
2571         /*
2572          * Build up our lba mapping.
2573          */
2574         error = zvol_get_lbas(zv);
2575         if (error) {
2576                 (void) zvol_dump_fini(zv);
2577                 return (error);
2578         }
2579
2580         tx = dmu_tx_create(os);
2581         dmu_tx_hold_zap(tx, ZVOL_ZAP_OBJ, TRUE, NULL);
2582         error = dmu_tx_assign(tx, TXG_WAIT);
2583         if (error) {
2584                 dmu_tx_abort(tx);
2585                 (void) zvol_dump_fini(zv);
2586                 return (error);
2587         }
2588
2589         zv->zv_flags |= ZVOL_DUMPIFIED;
2590         error = zap_update(os, ZVOL_ZAP_OBJ, ZVOL_DUMPSIZE, 8, 1,
2591             &zv->zv_volsize, tx);
2592         dmu_tx_commit(tx);
2593
2594         if (error) {
2595                 (void) zvol_dump_fini(zv);
2596                 return (error);
2597         }
2598
2599         txg_wait_synced(dmu_objset_pool(os), 0);
2600         return (0);
2601 }
2602
2603 static int
2604 zvol_dump_fini(zvol_state_t *zv)
2605 {
2606         dmu_tx_t *tx;
2607         objset_t *os = zv->zv_objset;
2608         nvlist_t *nv;
2609         int error = 0;
2610         uint64_t checksum, compress, refresrv, vbs, dedup;
2611         uint64_t version = spa_version(dmu_objset_spa(zv->zv_objset));
2612
2613         /*
2614          * Attempt to restore the zvol back to its pre-dumpified state.
2615          * This is a best-effort attempt as it's possible that not all
2616          * of these properties were initialized during the dumpify process
2617          * (i.e. error during zvol_dump_init).
2618          */
2619
2620         tx = dmu_tx_create(os);
2621         dmu_tx_hold_zap(tx, ZVOL_ZAP_OBJ, TRUE, NULL);
2622         error = dmu_tx_assign(tx, TXG_WAIT);
2623         if (error) {
2624                 dmu_tx_abort(tx);
2625                 return (error);
2626         }
2627         (void) zap_remove(os, ZVOL_ZAP_OBJ, ZVOL_DUMPSIZE, tx);
2628         dmu_tx_commit(tx);
2629
2630         (void) zap_lookup(zv->zv_objset, ZVOL_ZAP_OBJ,
2631             zfs_prop_to_name(ZFS_PROP_CHECKSUM), 8, 1, &checksum);
2632         (void) zap_lookup(zv->zv_objset, ZVOL_ZAP_OBJ,
2633             zfs_prop_to_name(ZFS_PROP_COMPRESSION), 8, 1, &compress);
2634         (void) zap_lookup(zv->zv_objset, ZVOL_ZAP_OBJ,
2635             zfs_prop_to_name(ZFS_PROP_REFRESERVATION), 8, 1, &refresrv);
2636         (void) zap_lookup(zv->zv_objset, ZVOL_ZAP_OBJ,
2637             zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE), 8, 1, &vbs);
2638
2639         VERIFY(nvlist_alloc(&nv, NV_UNIQUE_NAME, KM_SLEEP) == 0);
2640         (void) nvlist_add_uint64(nv,
2641             zfs_prop_to_name(ZFS_PROP_CHECKSUM), checksum);
2642         (void) nvlist_add_uint64(nv,
2643             zfs_prop_to_name(ZFS_PROP_COMPRESSION), compress);
2644         (void) nvlist_add_uint64(nv,
2645             zfs_prop_to_name(ZFS_PROP_REFRESERVATION), refresrv);
2646         if (version >= SPA_VERSION_DEDUP &&
2647             zap_lookup(zv->zv_objset, ZVOL_ZAP_OBJ,
2648             zfs_prop_to_name(ZFS_PROP_DEDUP), 8, 1, &dedup) == 0) {
2649                 (void) nvlist_add_uint64(nv,
2650                     zfs_prop_to_name(ZFS_PROP_DEDUP), dedup);
2651         }
2652         (void) zfs_set_prop_nvlist(zv->zv_name, ZPROP_SRC_LOCAL,
2653             nv, NULL);
2654         nvlist_free(nv);
2655
2656         zvol_free_extents(zv);
2657         zv->zv_flags &= ~ZVOL_DUMPIFIED;
2658         (void) dmu_free_long_range(os, ZVOL_OBJ, 0, DMU_OBJECT_END);
2659         /* wait for dmu_free_long_range to actually free the blocks */
2660         txg_wait_synced(dmu_objset_pool(zv->zv_objset), 0);
2661         tx = dmu_tx_create(os);
2662         dmu_tx_hold_bonus(tx, ZVOL_OBJ);
2663         error = dmu_tx_assign(tx, TXG_WAIT);
2664         if (error) {
2665                 dmu_tx_abort(tx);
2666                 return (error);
2667         }
2668         if (dmu_object_set_blocksize(os, ZVOL_OBJ, vbs, 0, tx) == 0)
2669                 zv->zv_volblocksize = vbs;
2670         dmu_tx_commit(tx);
2671
2672         return (0);
2673 }
2674 #else   /* !illumos */
2675
2676 static void
2677 zvol_geom_run(zvol_state_t *zv)
2678 {
2679         struct g_provider *pp;
2680
2681         pp = zv->zv_provider;
2682         g_error_provider(pp, 0);
2683
2684         kproc_kthread_add(zvol_geom_worker, zv, &system_proc, NULL, 0, 0,
2685             "zfskern", "zvol %s", pp->name + sizeof(ZVOL_DRIVER));
2686 }
2687
2688 static void
2689 zvol_geom_destroy(zvol_state_t *zv)
2690 {
2691         struct g_provider *pp;
2692
2693         g_topology_assert();
2694
2695         mtx_lock(&zv->zv_queue_mtx);
2696         zv->zv_state = 1;
2697         wakeup_one(&zv->zv_queue);
2698         while (zv->zv_state != 2)
2699                 msleep(&zv->zv_state, &zv->zv_queue_mtx, 0, "zvol:w", 0);
2700         mtx_destroy(&zv->zv_queue_mtx);
2701
2702         pp = zv->zv_provider;
2703         zv->zv_provider = NULL;
2704         pp->private = NULL;
2705         g_wither_geom(pp->geom, ENXIO);
2706 }
2707
2708 static int
2709 zvol_geom_access(struct g_provider *pp, int acr, int acw, int ace)
2710 {
2711         int count, error, flags;
2712
2713         g_topology_assert();
2714
2715         /*
2716          * To make it easier we expect either open or close, but not both
2717          * at the same time.
2718          */
2719         KASSERT((acr >= 0 && acw >= 0 && ace >= 0) ||
2720             (acr <= 0 && acw <= 0 && ace <= 0),
2721             ("Unsupported access request to %s (acr=%d, acw=%d, ace=%d).",
2722             pp->name, acr, acw, ace));
2723
2724         if (pp->private == NULL) {
2725                 if (acr <= 0 && acw <= 0 && ace <= 0)
2726                         return (0);
2727                 return (pp->error);
2728         }
2729
2730         /*
2731          * We don't pass FEXCL flag to zvol_open()/zvol_close() if ace != 0,
2732          * because GEOM already handles that and handles it a bit differently.
2733          * GEOM allows for multiple read/exclusive consumers and ZFS allows
2734          * only one exclusive consumer, no matter if it is reader or writer.
2735          * I like better the way GEOM works so I'll leave it for GEOM to
2736          * decide what to do.
2737          */
2738
2739         count = acr + acw + ace;
2740         if (count == 0)
2741                 return (0);
2742
2743         flags = 0;
2744         if (acr != 0 || ace != 0)
2745                 flags |= FREAD;
2746         if (acw != 0)
2747                 flags |= FWRITE;
2748
2749         g_topology_unlock();
2750         if (count > 0)
2751                 error = zvol_open(pp, flags, count);
2752         else
2753                 error = zvol_close(pp, flags, -count);
2754         g_topology_lock();
2755         return (error);
2756 }
2757
2758 static void
2759 zvol_geom_start(struct bio *bp)
2760 {
2761         zvol_state_t *zv;
2762         boolean_t first;
2763
2764         zv = bp->bio_to->private;
2765         ASSERT(zv != NULL);
2766         switch (bp->bio_cmd) {
2767         case BIO_FLUSH:
2768                 if (!THREAD_CAN_SLEEP())
2769                         goto enqueue;
2770                 zil_commit(zv->zv_zilog, ZVOL_OBJ);
2771                 g_io_deliver(bp, 0);
2772                 break;
2773         case BIO_READ:
2774         case BIO_WRITE:
2775         case BIO_DELETE:
2776                 if (!THREAD_CAN_SLEEP())
2777                         goto enqueue;
2778                 zvol_strategy(bp);
2779                 break;
2780         case BIO_GETATTR: {
2781                 spa_t *spa = dmu_objset_spa(zv->zv_objset);
2782                 uint64_t refd, avail, usedobjs, availobjs, val;
2783
2784                 if (g_handleattr_int(bp, "GEOM::candelete", 1))
2785                         return;
2786                 if (strcmp(bp->bio_attribute, "blocksavail") == 0) {
2787                         dmu_objset_space(zv->zv_objset, &refd, &avail,
2788                             &usedobjs, &availobjs);
2789                         if (g_handleattr_off_t(bp, "blocksavail",
2790                             avail / DEV_BSIZE))
2791                                 return;
2792                 } else if (strcmp(bp->bio_attribute, "blocksused") == 0) {
2793                         dmu_objset_space(zv->zv_objset, &refd, &avail,
2794                             &usedobjs, &availobjs);
2795                         if (g_handleattr_off_t(bp, "blocksused",
2796                             refd / DEV_BSIZE))
2797                                 return;
2798                 } else if (strcmp(bp->bio_attribute, "poolblocksavail") == 0) {
2799                         avail = metaslab_class_get_space(spa_normal_class(spa));
2800                         avail -= metaslab_class_get_alloc(spa_normal_class(spa));
2801                         if (g_handleattr_off_t(bp, "poolblocksavail",
2802                             avail / DEV_BSIZE))
2803                                 return;
2804                 } else if (strcmp(bp->bio_attribute, "poolblocksused") == 0) {
2805                         refd = metaslab_class_get_alloc(spa_normal_class(spa));
2806                         if (g_handleattr_off_t(bp, "poolblocksused",
2807                             refd / DEV_BSIZE))
2808                                 return;
2809                 }
2810                 /* FALLTHROUGH */
2811         }
2812         default:
2813                 g_io_deliver(bp, EOPNOTSUPP);
2814                 break;
2815         }
2816         return;
2817
2818 enqueue:
2819         mtx_lock(&zv->zv_queue_mtx);
2820         first = (bioq_first(&zv->zv_queue) == NULL);
2821         bioq_insert_tail(&zv->zv_queue, bp);
2822         mtx_unlock(&zv->zv_queue_mtx);
2823         if (first)
2824                 wakeup_one(&zv->zv_queue);
2825 }
2826
2827 static void
2828 zvol_geom_worker(void *arg)
2829 {
2830         zvol_state_t *zv;
2831         struct bio *bp;
2832
2833         thread_lock(curthread);
2834         sched_prio(curthread, PRIBIO);
2835         thread_unlock(curthread);
2836
2837         zv = arg;
2838         for (;;) {
2839                 mtx_lock(&zv->zv_queue_mtx);
2840                 bp = bioq_takefirst(&zv->zv_queue);
2841                 if (bp == NULL) {
2842                         if (zv->zv_state == 1) {
2843                                 zv->zv_state = 2;
2844                                 wakeup(&zv->zv_state);
2845                                 mtx_unlock(&zv->zv_queue_mtx);
2846                                 kthread_exit();
2847                         }
2848                         msleep(&zv->zv_queue, &zv->zv_queue_mtx, PRIBIO | PDROP,
2849                             "zvol:io", 0);
2850                         continue;
2851                 }
2852                 mtx_unlock(&zv->zv_queue_mtx);
2853                 switch (bp->bio_cmd) {
2854                 case BIO_FLUSH:
2855                         zil_commit(zv->zv_zilog, ZVOL_OBJ);
2856                         g_io_deliver(bp, 0);
2857                         break;
2858                 case BIO_READ:
2859                 case BIO_WRITE:
2860                 case BIO_DELETE:
2861                         zvol_strategy(bp);
2862                         break;
2863                 default:
2864                         g_io_deliver(bp, EOPNOTSUPP);
2865                         break;
2866                 }
2867         }
2868 }
2869
2870 extern boolean_t dataset_name_hidden(const char *name);
2871
2872 static int
2873 zvol_create_snapshots(objset_t *os, const char *name)
2874 {
2875         uint64_t cookie, obj;
2876         char *sname;
2877         int error, len;
2878
2879         cookie = obj = 0;
2880         sname = kmem_alloc(MAXPATHLEN, KM_SLEEP);
2881
2882 #if 0
2883         (void) dmu_objset_find(name, dmu_objset_prefetch, NULL,
2884             DS_FIND_SNAPSHOTS);
2885 #endif
2886
2887         for (;;) {
2888                 len = snprintf(sname, MAXPATHLEN, "%s@", name);
2889                 if (len >= MAXPATHLEN) {
2890                         dmu_objset_rele(os, FTAG);
2891                         error = ENAMETOOLONG;
2892                         break;
2893                 }
2894
2895                 dsl_pool_config_enter(dmu_objset_pool(os), FTAG);
2896                 error = dmu_snapshot_list_next(os, MAXPATHLEN - len,
2897                     sname + len, &obj, &cookie, NULL);
2898                 dsl_pool_config_exit(dmu_objset_pool(os), FTAG);
2899                 if (error != 0) {
2900                         if (error == ENOENT)
2901                                 error = 0;
2902                         break;
2903                 }
2904
2905                 error = zvol_create_minor(sname);
2906                 if (error != 0 && error != EEXIST) {
2907                         printf("ZFS WARNING: Unable to create ZVOL %s (error=%d).\n",
2908                             sname, error);
2909                         break;
2910                 }
2911         }
2912
2913         kmem_free(sname, MAXPATHLEN);
2914         return (error);
2915 }
2916
2917 int
2918 zvol_create_minors_impl(const char *name)
2919 {
2920         uint64_t cookie;
2921         objset_t *os;
2922         char *osname, *p;
2923         int error, len;
2924
2925         if (dataset_name_hidden(name))
2926                 return (0);
2927
2928         if ((error = dmu_objset_hold(name, FTAG, &os)) != 0) {
2929                 printf("ZFS WARNING: Unable to put hold on %s (error=%d).\n",
2930                     name, error);
2931                 return (error);
2932         }
2933         if (dmu_objset_type(os) == DMU_OST_ZVOL) {
2934                 dsl_dataset_long_hold(os->os_dsl_dataset, FTAG);
2935                 dsl_pool_rele(dmu_objset_pool(os), FTAG);
2936                 error = zvol_create_minor(name);
2937                 if (error == 0 || error == EEXIST) {
2938                         error = zvol_create_snapshots(os, name);
2939                 } else {
2940                         printf("ZFS WARNING: Unable to create ZVOL %s (error=%d).\n",
2941                             name, error);
2942                 }
2943                 dsl_dataset_long_rele(os->os_dsl_dataset, FTAG);
2944                 dsl_dataset_rele(os->os_dsl_dataset, FTAG);
2945                 return (error);
2946         }
2947         if (dmu_objset_type(os) != DMU_OST_ZFS) {
2948                 dmu_objset_rele(os, FTAG);
2949                 return (0);
2950         }
2951
2952         osname = kmem_alloc(MAXPATHLEN, KM_SLEEP);
2953         if (snprintf(osname, MAXPATHLEN, "%s/", name) >= MAXPATHLEN) {
2954                 dmu_objset_rele(os, FTAG);
2955                 kmem_free(osname, MAXPATHLEN);
2956                 return (ENOENT);
2957         }
2958         p = osname + strlen(osname);
2959         len = MAXPATHLEN - (p - osname);
2960
2961 #if 0
2962         /* Prefetch the datasets. */
2963         cookie = 0;
2964         while (dmu_dir_list_next(os, len, p, NULL, &cookie) == 0) {
2965                 if (!dataset_name_hidden(osname))
2966                         (void) dmu_objset_prefetch(osname, NULL);
2967         }
2968 #endif
2969
2970         cookie = 0;
2971         while (dmu_dir_list_next(os, MAXPATHLEN - (p - osname), p, NULL,
2972             &cookie) == 0) {
2973                 dmu_objset_rele(os, FTAG);
2974                 (void)zvol_create_minors_impl(osname);
2975                 if ((error = dmu_objset_hold(name, FTAG, &os)) != 0) {
2976                         printf("ZFS WARNING: Unable to put hold on %s (error=%d).\n",
2977                             name, error);
2978                         return (error);
2979                 }
2980         }
2981
2982         dmu_objset_rele(os, FTAG);
2983         kmem_free(osname, MAXPATHLEN);
2984         return (0);
2985 }
2986
2987 static void
2988 zvol_rename_minor(zvol_state_t *zv, const char *newname)
2989 {
2990         struct g_geom *gp;
2991         struct g_provider *pp;
2992         struct cdev *dev;
2993
2994         ASSERT(MUTEX_HELD(&zfsdev_state_lock));
2995
2996         if (zv->zv_volmode == ZFS_VOLMODE_GEOM) {
2997                 g_topology_lock();
2998                 pp = zv->zv_provider;
2999                 ASSERT(pp != NULL);
3000                 gp = pp->geom;
3001                 ASSERT(gp != NULL);
3002
3003                 zv->zv_provider = NULL;
3004                 g_wither_provider(pp, ENXIO);
3005
3006                 pp = g_new_providerf(gp, "%s/%s", ZVOL_DRIVER, newname);
3007                 pp->flags |= G_PF_DIRECT_RECEIVE | G_PF_DIRECT_SEND;
3008                 pp->sectorsize = DEV_BSIZE;
3009                 pp->mediasize = zv->zv_volsize;
3010                 pp->private = zv;
3011                 zv->zv_provider = pp;
3012                 g_error_provider(pp, 0);
3013                 g_topology_unlock();
3014         } else if (zv->zv_volmode == ZFS_VOLMODE_DEV) {
3015                 struct make_dev_args args;
3016
3017                 if ((dev = zv->zv_dev) != NULL) {
3018                         zv->zv_dev = NULL;
3019                         destroy_dev(dev);
3020                         if (zv->zv_total_opens > 0) {
3021                                 zv->zv_flags &= ~ZVOL_EXCL;
3022                                 zv->zv_total_opens = 0;
3023                                 zvol_last_close(zv);
3024                         }
3025                 }
3026
3027                 make_dev_args_init(&args);
3028                 args.mda_flags = MAKEDEV_CHECKNAME | MAKEDEV_WAITOK;
3029                 args.mda_devsw = &zvol_cdevsw;
3030                 args.mda_cr = NULL;
3031                 args.mda_uid = UID_ROOT;
3032                 args.mda_gid = GID_OPERATOR;
3033                 args.mda_mode = 0640;
3034                 args.mda_si_drv2 = zv;
3035                 if (make_dev_s(&args, &zv->zv_dev,
3036                     "%s/%s", ZVOL_DRIVER, newname) == 0)
3037                         zv->zv_dev->si_iosize_max = MAXPHYS;
3038         }
3039         strlcpy(zv->zv_name, newname, sizeof(zv->zv_name));
3040 }
3041
3042 void
3043 zvol_rename_minors_impl(const char *oldname, const char *newname)
3044 {
3045         char name[MAXPATHLEN];
3046         struct g_provider *pp;
3047         struct g_geom *gp;
3048         size_t oldnamelen, newnamelen;
3049         zvol_state_t *zv;
3050         char *namebuf;
3051         boolean_t locked = B_FALSE;
3052
3053         oldnamelen = strlen(oldname);
3054         newnamelen = strlen(newname);
3055
3056         /* See comment in zvol_open(). */
3057         if (!MUTEX_HELD(&zfsdev_state_lock)) {
3058                 mutex_enter(&zfsdev_state_lock);
3059                 locked = B_TRUE;
3060         }
3061
3062         LIST_FOREACH(zv, &all_zvols, zv_links) {
3063                 if (strcmp(zv->zv_name, oldname) == 0) {
3064                         zvol_rename_minor(zv, newname);
3065                 } else if (strncmp(zv->zv_name, oldname, oldnamelen) == 0 &&
3066                     (zv->zv_name[oldnamelen] == '/' ||
3067                      zv->zv_name[oldnamelen] == '@')) {
3068                         snprintf(name, sizeof(name), "%s%c%s", newname,
3069                             zv->zv_name[oldnamelen],
3070                             zv->zv_name + oldnamelen + 1);
3071                         zvol_rename_minor(zv, name);
3072                 }
3073         }
3074
3075         if (locked)
3076                 mutex_exit(&zfsdev_state_lock);
3077 }
3078
3079 static zvol_task_t *
3080 zvol_task_alloc(zvol_async_op_t op, const char *name1, const char *name2)
3081 {
3082         zvol_task_t *task;
3083         char *delim;
3084
3085         task = kmem_zalloc(sizeof (zvol_task_t), KM_SLEEP);
3086         task->op = op;
3087         delim = strchr(name1, '/');
3088         strlcpy(task->pool, name1, delim ? (delim - name1 + 1) : MAXNAMELEN);
3089
3090         strlcpy(task->name1, name1, MAXNAMELEN);
3091         if (name2 != NULL)
3092                 strlcpy(task->name2, name2, MAXNAMELEN);
3093
3094         return (task);
3095 }
3096
3097 static void
3098 zvol_task_free(zvol_task_t *task)
3099 {
3100         kmem_free(task, sizeof (zvol_task_t));
3101 }
3102
3103 /*
3104  * The worker thread function performed asynchronously.
3105  */
3106 static void
3107 zvol_task_cb(void *param)
3108 {
3109         zvol_task_t *task = (zvol_task_t *)param;
3110
3111         switch (task->op) {
3112         case ZVOL_ASYNC_CREATE_MINORS:
3113                 (void) zvol_create_minors_impl(task->name1);
3114                 break;
3115         case ZVOL_ASYNC_REMOVE_MINORS:
3116                 zvol_remove_minors_impl(task->name1);
3117                 break;
3118         case ZVOL_ASYNC_RENAME_MINORS:
3119                 zvol_rename_minors_impl(task->name1, task->name2);
3120                 break;
3121         default:
3122                 VERIFY(0);
3123                 break;
3124         }
3125
3126         zvol_task_free(task);
3127 }
3128
3129 static void
3130 zvol_minors_helper(spa_t *spa, zvol_async_op_t op, const char *name1,
3131     const char *name2)
3132 {
3133         zvol_task_t *task;
3134
3135         if (dataset_name_hidden(name1))
3136                 return;
3137         if (name2 != NULL && dataset_name_hidden(name2))
3138                 return;
3139         task = zvol_task_alloc(op, name1, name2);
3140         (void)taskq_dispatch(spa->spa_zvol_taskq, zvol_task_cb, task, TQ_SLEEP);
3141 }
3142
3143 void
3144 zvol_create_minors(spa_t *spa, const char *name)
3145 {
3146         zvol_minors_helper(spa, ZVOL_ASYNC_CREATE_MINORS, name, NULL);
3147 }
3148
3149 void
3150 zvol_remove_minors(spa_t *spa, const char *name)
3151 {
3152         zvol_minors_helper(spa, ZVOL_ASYNC_REMOVE_MINORS, name, NULL);
3153 }
3154
3155 void
3156 zvol_rename_minors(spa_t *spa, const char *oldname, const char *newname)
3157 {
3158         zvol_minors_helper(spa, ZVOL_ASYNC_RENAME_MINORS, oldname, newname);
3159 }
3160
3161 static int
3162 zvol_d_open(struct cdev *dev, int flags, int fmt, struct thread *td)
3163 {
3164         zvol_state_t *zv = dev->si_drv2;
3165         int err = 0;
3166
3167         mutex_enter(&zfsdev_state_lock);
3168         if (zv->zv_total_opens == 0)
3169                 err = zvol_first_open(zv);
3170         if (err) {
3171                 mutex_exit(&zfsdev_state_lock);
3172                 return (err);
3173         }
3174         if ((flags & FWRITE) && (zv->zv_flags & ZVOL_RDONLY)) {
3175                 err = SET_ERROR(EROFS);
3176                 goto out;
3177         }
3178         if (zv->zv_flags & ZVOL_EXCL) {
3179                 err = SET_ERROR(EBUSY);
3180                 goto out;
3181         }
3182 #ifdef FEXCL
3183         if (flags & FEXCL) {
3184                 if (zv->zv_total_opens != 0) {
3185                         err = SET_ERROR(EBUSY);
3186                         goto out;
3187                 }
3188                 zv->zv_flags |= ZVOL_EXCL;
3189         }
3190 #endif
3191
3192         zv->zv_total_opens++;
3193         if (flags & (FSYNC | FDSYNC)) {
3194                 zv->zv_sync_cnt++;
3195                 if (zv->zv_sync_cnt == 1)
3196                         zil_async_to_sync(zv->zv_zilog, ZVOL_OBJ);
3197         }
3198         mutex_exit(&zfsdev_state_lock);
3199         return (err);
3200 out:
3201         if (zv->zv_total_opens == 0)
3202                 zvol_last_close(zv);
3203         mutex_exit(&zfsdev_state_lock);
3204         return (err);
3205 }
3206
3207 static int
3208 zvol_d_close(struct cdev *dev, int flags, int fmt, struct thread *td)
3209 {
3210         zvol_state_t *zv = dev->si_drv2;
3211
3212         mutex_enter(&zfsdev_state_lock);
3213         if (zv->zv_flags & ZVOL_EXCL) {
3214                 ASSERT(zv->zv_total_opens == 1);
3215                 zv->zv_flags &= ~ZVOL_EXCL;
3216         }
3217
3218         /*
3219          * If the open count is zero, this is a spurious close.
3220          * That indicates a bug in the kernel / DDI framework.
3221          */
3222         ASSERT(zv->zv_total_opens != 0);
3223
3224         /*
3225          * You may get multiple opens, but only one close.
3226          */
3227         zv->zv_total_opens--;
3228         if (flags & (FSYNC | FDSYNC))
3229                 zv->zv_sync_cnt--;
3230
3231         if (zv->zv_total_opens == 0)
3232                 zvol_last_close(zv);
3233
3234         mutex_exit(&zfsdev_state_lock);
3235         return (0);
3236 }
3237
3238 static int
3239 zvol_d_ioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag, struct thread *td)
3240 {
3241         zvol_state_t *zv;
3242         locked_range_t *lr;
3243         off_t offset, length;
3244         int i, error;
3245         boolean_t sync;
3246
3247         zv = dev->si_drv2;
3248
3249         error = 0;
3250         KASSERT(zv->zv_total_opens > 0,
3251             ("Device with zero access count in zvol_d_ioctl"));
3252
3253         i = IOCPARM_LEN(cmd);
3254         switch (cmd) {
3255         case DIOCGSECTORSIZE:
3256                 *(u_int *)data = DEV_BSIZE;
3257                 break;
3258         case DIOCGMEDIASIZE:
3259                 *(off_t *)data = zv->zv_volsize;
3260                 break;
3261         case DIOCGFLUSH:
3262                 zil_commit(zv->zv_zilog, ZVOL_OBJ);
3263                 break;
3264         case DIOCGDELETE:
3265                 if (!zvol_unmap_enabled)
3266                         break;
3267
3268                 offset = ((off_t *)data)[0];
3269                 length = ((off_t *)data)[1];
3270                 if ((offset % DEV_BSIZE) != 0 || (length % DEV_BSIZE) != 0 ||
3271                     offset < 0 || offset >= zv->zv_volsize ||
3272                     length <= 0) {
3273                         printf("%s: offset=%jd length=%jd\n", __func__, offset,
3274                             length);
3275                         error = EINVAL;
3276                         break;
3277                 }
3278
3279                 lr = rangelock_enter(&zv->zv_rangelock, offset, length,
3280                     RL_WRITER);
3281                 dmu_tx_t *tx = dmu_tx_create(zv->zv_objset);
3282                 error = dmu_tx_assign(tx, TXG_WAIT);
3283                 if (error != 0) {
3284                         sync = FALSE;
3285                         dmu_tx_abort(tx);
3286                 } else {
3287                         sync = (zv->zv_objset->os_sync == ZFS_SYNC_ALWAYS);
3288                         zvol_log_truncate(zv, tx, offset, length, sync);
3289                         dmu_tx_commit(tx);
3290                         error = dmu_free_long_range(zv->zv_objset, ZVOL_OBJ,
3291                             offset, length);
3292                 }
3293                 rangelock_exit(lr);
3294                 if (sync)
3295                         zil_commit(zv->zv_zilog, ZVOL_OBJ);
3296                 break;
3297         case DIOCGSTRIPESIZE:
3298                 *(off_t *)data = zv->zv_volblocksize;
3299                 break;
3300         case DIOCGSTRIPEOFFSET:
3301                 *(off_t *)data = 0;
3302                 break;
3303         case DIOCGATTR: {
3304                 spa_t *spa = dmu_objset_spa(zv->zv_objset);
3305                 struct diocgattr_arg *arg = (struct diocgattr_arg *)data;
3306                 uint64_t refd, avail, usedobjs, availobjs;
3307
3308                 if (strcmp(arg->name, "GEOM::candelete") == 0)
3309                         arg->value.i = 1;
3310                 else if (strcmp(arg->name, "blocksavail") == 0) {
3311                         dmu_objset_space(zv->zv_objset, &refd, &avail,
3312                             &usedobjs, &availobjs);
3313                         arg->value.off = avail / DEV_BSIZE;
3314                 } else if (strcmp(arg->name, "blocksused") == 0) {
3315                         dmu_objset_space(zv->zv_objset, &refd, &avail,
3316                             &usedobjs, &availobjs);
3317                         arg->value.off = refd / DEV_BSIZE;
3318                 } else if (strcmp(arg->name, "poolblocksavail") == 0) {
3319                         avail = metaslab_class_get_space(spa_normal_class(spa));
3320                         avail -= metaslab_class_get_alloc(spa_normal_class(spa));
3321                         arg->value.off = avail / DEV_BSIZE;
3322                 } else if (strcmp(arg->name, "poolblocksused") == 0) {
3323                         refd = metaslab_class_get_alloc(spa_normal_class(spa));
3324                         arg->value.off = refd / DEV_BSIZE;
3325                 } else
3326                         error = ENOIOCTL;
3327                 break;
3328         }
3329         case FIOSEEKHOLE:
3330         case FIOSEEKDATA: {
3331                 off_t *off = (off_t *)data;
3332                 uint64_t noff;
3333                 boolean_t hole;
3334
3335                 hole = (cmd == FIOSEEKHOLE);
3336                 noff = *off;
3337                 error = dmu_offset_next(zv->zv_objset, ZVOL_OBJ, hole, &noff);
3338                 *off = noff;
3339                 break;
3340         }
3341         default:
3342                 error = ENOIOCTL;
3343         }
3344
3345         return (error);
3346 }
3347 #endif  /* illumos */