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