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