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