]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zvol.c
Fix bug in sync control in new "dev" mode of ZVOL (r265678).
[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         error = dmu_tx_assign(tx, TXG_WAIT);
855         if (error) {
856                 dmu_tx_abort(tx);
857                 return (error);
858         }
859
860         error = zap_update(os, ZVOL_ZAP_OBJ, "size", 8, 1,
861             &volsize, tx);
862         dmu_tx_commit(tx);
863
864         if (error == 0)
865                 error = dmu_free_long_range(os,
866                     ZVOL_OBJ, volsize, DMU_OBJECT_END);
867         return (error);
868 }
869
870 void
871 zvol_remove_minors(const char *name)
872 {
873         zvol_state_t *zv, *tzv;
874         size_t namelen;
875
876         namelen = strlen(name);
877
878         DROP_GIANT();
879         mutex_enter(&spa_namespace_lock);
880
881         LIST_FOREACH_SAFE(zv, &all_zvols, zv_links, tzv) {
882                 if (strcmp(zv->zv_name, name) == 0 ||
883                     (strncmp(zv->zv_name, name, namelen) == 0 &&
884                      zv->zv_name[namelen] == '/')) {
885                         (void) zvol_remove_zv(zv);
886                 }
887         }
888
889         mutex_exit(&spa_namespace_lock);
890         PICKUP_GIANT();
891 }
892
893 int
894 zvol_set_volsize(const char *name, major_t maj, uint64_t volsize)
895 {
896         zvol_state_t *zv = NULL;
897         objset_t *os;
898         int error;
899         dmu_object_info_t doi;
900         uint64_t old_volsize = 0ULL;
901         uint64_t readonly;
902
903         mutex_enter(&spa_namespace_lock);
904         zv = zvol_minor_lookup(name);
905         if ((error = dmu_objset_hold(name, FTAG, &os)) != 0) {
906                 mutex_exit(&spa_namespace_lock);
907                 return (error);
908         }
909
910         if ((error = dmu_object_info(os, ZVOL_OBJ, &doi)) != 0 ||
911             (error = zvol_check_volsize(volsize,
912             doi.doi_data_block_size)) != 0)
913                 goto out;
914
915         VERIFY(dsl_prop_get_integer(name, "readonly", &readonly,
916             NULL) == 0);
917         if (readonly) {
918                 error = EROFS;
919                 goto out;
920         }
921
922         error = zvol_update_volsize(os, volsize);
923         /*
924          * Reinitialize the dump area to the new size. If we
925          * failed to resize the dump area then restore it back to
926          * its original size.
927          */
928         if (zv && error == 0) {
929 #ifdef ZVOL_DUMP
930                 if (zv->zv_flags & ZVOL_DUMPIFIED) {
931                         old_volsize = zv->zv_volsize;
932                         zv->zv_volsize = volsize;
933                         if ((error = zvol_dumpify(zv)) != 0 ||
934                             (error = dumpvp_resize()) != 0) {
935                                 (void) zvol_update_volsize(os, old_volsize);
936                                 zv->zv_volsize = old_volsize;
937                                 error = zvol_dumpify(zv);
938                         }
939                 }
940 #endif  /* ZVOL_DUMP */
941                 if (error == 0) {
942                         zv->zv_volsize = volsize;
943                         zvol_size_changed(zv);
944                 }
945         }
946
947 #ifdef sun
948         /*
949          * Generate a LUN expansion event.
950          */
951         if (zv && error == 0) {
952                 sysevent_id_t eid;
953                 nvlist_t *attr;
954                 char *physpath = kmem_zalloc(MAXPATHLEN, KM_SLEEP);
955
956                 (void) snprintf(physpath, MAXPATHLEN, "%s%u", ZVOL_PSEUDO_DEV,
957                     zv->zv_minor);
958
959                 VERIFY(nvlist_alloc(&attr, NV_UNIQUE_NAME, KM_SLEEP) == 0);
960                 VERIFY(nvlist_add_string(attr, DEV_PHYS_PATH, physpath) == 0);
961
962                 (void) ddi_log_sysevent(zfs_dip, SUNW_VENDOR, EC_DEV_STATUS,
963                     ESC_DEV_DLE, attr, &eid, DDI_SLEEP);
964
965                 nvlist_free(attr);
966                 kmem_free(physpath, MAXPATHLEN);
967         }
968 #endif  /* sun */
969
970 out:
971         dmu_objset_rele(os, FTAG);
972
973         mutex_exit(&spa_namespace_lock);
974
975         return (error);
976 }
977
978 /*ARGSUSED*/
979 static int
980 zvol_open(struct g_provider *pp, int flag, int count)
981 {
982         zvol_state_t *zv;
983         int err = 0;
984         boolean_t locked = B_FALSE;
985
986         /*
987          * Protect against recursively entering spa_namespace_lock
988          * when spa_open() is used for a pool on a (local) ZVOL(s).
989          * This is needed since we replaced upstream zfsdev_state_lock
990          * with spa_namespace_lock in the ZVOL code.
991          * We are using the same trick as spa_open().
992          * Note that calls in zvol_first_open which need to resolve
993          * pool name to a spa object will enter spa_open()
994          * recursively, but that function already has all the
995          * necessary protection.
996          */
997         if (!MUTEX_HELD(&spa_namespace_lock)) {
998                 mutex_enter(&spa_namespace_lock);
999                 locked = B_TRUE;
1000         }
1001
1002         zv = pp->private;
1003         if (zv == NULL) {
1004                 if (locked)
1005                         mutex_exit(&spa_namespace_lock);
1006                 return (SET_ERROR(ENXIO));
1007         }
1008
1009         if (zv->zv_total_opens == 0) {
1010                 err = zvol_first_open(zv);
1011                 if (err) {
1012                         if (locked)
1013                                 mutex_exit(&spa_namespace_lock);
1014                         return (err);
1015                 }
1016                 pp->mediasize = zv->zv_volsize;
1017                 pp->stripeoffset = 0;
1018                 pp->stripesize = zv->zv_volblocksize;
1019         }
1020         if ((flag & FWRITE) && (zv->zv_flags & ZVOL_RDONLY)) {
1021                 err = SET_ERROR(EROFS);
1022                 goto out;
1023         }
1024         if (zv->zv_flags & ZVOL_EXCL) {
1025                 err = SET_ERROR(EBUSY);
1026                 goto out;
1027         }
1028 #ifdef FEXCL
1029         if (flag & FEXCL) {
1030                 if (zv->zv_total_opens != 0) {
1031                         err = SET_ERROR(EBUSY);
1032                         goto out;
1033                 }
1034                 zv->zv_flags |= ZVOL_EXCL;
1035         }
1036 #endif
1037
1038         zv->zv_total_opens += count;
1039         if (locked)
1040                 mutex_exit(&spa_namespace_lock);
1041
1042         return (err);
1043 out:
1044         if (zv->zv_total_opens == 0)
1045                 zvol_last_close(zv);
1046         if (locked)
1047                 mutex_exit(&spa_namespace_lock);
1048         return (err);
1049 }
1050
1051 /*ARGSUSED*/
1052 static int
1053 zvol_close(struct g_provider *pp, int flag, int count)
1054 {
1055         zvol_state_t *zv;
1056         int error = 0;
1057         boolean_t locked = B_FALSE;
1058
1059         /* See comment in zvol_open(). */
1060         if (!MUTEX_HELD(&spa_namespace_lock)) {
1061                 mutex_enter(&spa_namespace_lock);
1062                 locked = B_TRUE;
1063         }
1064
1065         zv = pp->private;
1066         if (zv == NULL) {
1067                 if (locked)
1068                         mutex_exit(&spa_namespace_lock);
1069                 return (SET_ERROR(ENXIO));
1070         }
1071
1072         if (zv->zv_flags & ZVOL_EXCL) {
1073                 ASSERT(zv->zv_total_opens == 1);
1074                 zv->zv_flags &= ~ZVOL_EXCL;
1075         }
1076
1077         /*
1078          * If the open count is zero, this is a spurious close.
1079          * That indicates a bug in the kernel / DDI framework.
1080          */
1081         ASSERT(zv->zv_total_opens != 0);
1082
1083         /*
1084          * You may get multiple opens, but only one close.
1085          */
1086         zv->zv_total_opens -= count;
1087
1088         if (zv->zv_total_opens == 0)
1089                 zvol_last_close(zv);
1090
1091         if (locked)
1092                 mutex_exit(&spa_namespace_lock);
1093         return (error);
1094 }
1095
1096 static void
1097 zvol_get_done(zgd_t *zgd, int error)
1098 {
1099         if (zgd->zgd_db)
1100                 dmu_buf_rele(zgd->zgd_db, zgd);
1101
1102         zfs_range_unlock(zgd->zgd_rl);
1103
1104         if (error == 0 && zgd->zgd_bp)
1105                 zil_add_block(zgd->zgd_zilog, zgd->zgd_bp);
1106
1107         kmem_free(zgd, sizeof (zgd_t));
1108 }
1109
1110 /*
1111  * Get data to generate a TX_WRITE intent log record.
1112  */
1113 static int
1114 zvol_get_data(void *arg, lr_write_t *lr, char *buf, zio_t *zio)
1115 {
1116         zvol_state_t *zv = arg;
1117         objset_t *os = zv->zv_objset;
1118         uint64_t object = ZVOL_OBJ;
1119         uint64_t offset = lr->lr_offset;
1120         uint64_t size = lr->lr_length;  /* length of user data */
1121         blkptr_t *bp = &lr->lr_blkptr;
1122         dmu_buf_t *db;
1123         zgd_t *zgd;
1124         int error;
1125
1126         ASSERT(zio != NULL);
1127         ASSERT(size != 0);
1128
1129         zgd = kmem_zalloc(sizeof (zgd_t), KM_SLEEP);
1130         zgd->zgd_zilog = zv->zv_zilog;
1131         zgd->zgd_rl = zfs_range_lock(&zv->zv_znode, offset, size, RL_READER);
1132
1133         /*
1134          * Write records come in two flavors: immediate and indirect.
1135          * For small writes it's cheaper to store the data with the
1136          * log record (immediate); for large writes it's cheaper to
1137          * sync the data and get a pointer to it (indirect) so that
1138          * we don't have to write the data twice.
1139          */
1140         if (buf != NULL) {      /* immediate write */
1141                 error = dmu_read(os, object, offset, size, buf,
1142                     DMU_READ_NO_PREFETCH);
1143         } else {
1144                 size = zv->zv_volblocksize;
1145                 offset = P2ALIGN(offset, size);
1146                 error = dmu_buf_hold(os, object, offset, zgd, &db,
1147                     DMU_READ_NO_PREFETCH);
1148                 if (error == 0) {
1149                         blkptr_t *obp = dmu_buf_get_blkptr(db);
1150                         if (obp) {
1151                                 ASSERT(BP_IS_HOLE(bp));
1152                                 *bp = *obp;
1153                         }
1154
1155                         zgd->zgd_db = db;
1156                         zgd->zgd_bp = bp;
1157
1158                         ASSERT(db->db_offset == offset);
1159                         ASSERT(db->db_size == size);
1160
1161                         error = dmu_sync(zio, lr->lr_common.lrc_txg,
1162                             zvol_get_done, zgd);
1163
1164                         if (error == 0)
1165                                 return (0);
1166                 }
1167         }
1168
1169         zvol_get_done(zgd, error);
1170
1171         return (error);
1172 }
1173
1174 /*
1175  * zvol_log_write() handles synchronous writes using TX_WRITE ZIL transactions.
1176  *
1177  * We store data in the log buffers if it's small enough.
1178  * Otherwise we will later flush the data out via dmu_sync().
1179  */
1180 ssize_t zvol_immediate_write_sz = 32768;
1181
1182 static void
1183 zvol_log_write(zvol_state_t *zv, dmu_tx_t *tx, offset_t off, ssize_t resid,
1184     boolean_t sync)
1185 {
1186         uint32_t blocksize = zv->zv_volblocksize;
1187         zilog_t *zilog = zv->zv_zilog;
1188         boolean_t slogging;
1189         ssize_t immediate_write_sz;
1190
1191         if (zil_replaying(zilog, tx))
1192                 return;
1193
1194         immediate_write_sz = (zilog->zl_logbias == ZFS_LOGBIAS_THROUGHPUT)
1195             ? 0 : zvol_immediate_write_sz;
1196
1197         slogging = spa_has_slogs(zilog->zl_spa) &&
1198             (zilog->zl_logbias == ZFS_LOGBIAS_LATENCY);
1199
1200         while (resid) {
1201                 itx_t *itx;
1202                 lr_write_t *lr;
1203                 ssize_t len;
1204                 itx_wr_state_t write_state;
1205
1206                 /*
1207                  * Unlike zfs_log_write() we can be called with
1208                  * upto DMU_MAX_ACCESS/2 (5MB) writes.
1209                  */
1210                 if (blocksize > immediate_write_sz && !slogging &&
1211                     resid >= blocksize && off % blocksize == 0) {
1212                         write_state = WR_INDIRECT; /* uses dmu_sync */
1213                         len = blocksize;
1214                 } else if (sync) {
1215                         write_state = WR_COPIED;
1216                         len = MIN(ZIL_MAX_LOG_DATA, resid);
1217                 } else {
1218                         write_state = WR_NEED_COPY;
1219                         len = MIN(ZIL_MAX_LOG_DATA, resid);
1220                 }
1221
1222                 itx = zil_itx_create(TX_WRITE, sizeof (*lr) +
1223                     (write_state == WR_COPIED ? len : 0));
1224                 lr = (lr_write_t *)&itx->itx_lr;
1225                 if (write_state == WR_COPIED && dmu_read(zv->zv_objset,
1226                     ZVOL_OBJ, off, len, lr + 1, DMU_READ_NO_PREFETCH) != 0) {
1227                         zil_itx_destroy(itx);
1228                         itx = zil_itx_create(TX_WRITE, sizeof (*lr));
1229                         lr = (lr_write_t *)&itx->itx_lr;
1230                         write_state = WR_NEED_COPY;
1231                 }
1232
1233                 itx->itx_wr_state = write_state;
1234                 if (write_state == WR_NEED_COPY)
1235                         itx->itx_sod += len;
1236                 lr->lr_foid = ZVOL_OBJ;
1237                 lr->lr_offset = off;
1238                 lr->lr_length = len;
1239                 lr->lr_blkoff = 0;
1240                 BP_ZERO(&lr->lr_blkptr);
1241
1242                 itx->itx_private = zv;
1243                 itx->itx_sync = sync;
1244
1245                 zil_itx_assign(zilog, itx, tx);
1246
1247                 off += len;
1248                 resid -= len;
1249         }
1250 }
1251
1252 #ifdef sun
1253 static int
1254 zvol_dumpio_vdev(vdev_t *vd, void *addr, uint64_t offset, uint64_t origoffset,
1255     uint64_t size, boolean_t doread, boolean_t isdump)
1256 {
1257         vdev_disk_t *dvd;
1258         int c;
1259         int numerrors = 0;
1260
1261         if (vd->vdev_ops == &vdev_mirror_ops ||
1262             vd->vdev_ops == &vdev_replacing_ops ||
1263             vd->vdev_ops == &vdev_spare_ops) {
1264                 for (c = 0; c < vd->vdev_children; c++) {
1265                         int err = zvol_dumpio_vdev(vd->vdev_child[c],
1266                             addr, offset, origoffset, size, doread, isdump);
1267                         if (err != 0) {
1268                                 numerrors++;
1269                         } else if (doread) {
1270                                 break;
1271                         }
1272                 }
1273         }
1274
1275         if (!vd->vdev_ops->vdev_op_leaf && vd->vdev_ops != &vdev_raidz_ops)
1276                 return (numerrors < vd->vdev_children ? 0 : EIO);
1277
1278         if (doread && !vdev_readable(vd))
1279                 return (SET_ERROR(EIO));
1280         else if (!doread && !vdev_writeable(vd))
1281                 return (SET_ERROR(EIO));
1282
1283         if (vd->vdev_ops == &vdev_raidz_ops) {
1284                 return (vdev_raidz_physio(vd,
1285                     addr, size, offset, origoffset, doread, isdump));
1286         }
1287
1288         offset += VDEV_LABEL_START_SIZE;
1289
1290         if (ddi_in_panic() || isdump) {
1291                 ASSERT(!doread);
1292                 if (doread)
1293                         return (SET_ERROR(EIO));
1294                 dvd = vd->vdev_tsd;
1295                 ASSERT3P(dvd, !=, NULL);
1296                 return (ldi_dump(dvd->vd_lh, addr, lbtodb(offset),
1297                     lbtodb(size)));
1298         } else {
1299                 dvd = vd->vdev_tsd;
1300                 ASSERT3P(dvd, !=, NULL);
1301                 return (vdev_disk_ldi_physio(dvd->vd_lh, addr, size,
1302                     offset, doread ? B_READ : B_WRITE));
1303         }
1304 }
1305
1306 static int
1307 zvol_dumpio(zvol_state_t *zv, void *addr, uint64_t offset, uint64_t size,
1308     boolean_t doread, boolean_t isdump)
1309 {
1310         vdev_t *vd;
1311         int error;
1312         zvol_extent_t *ze;
1313         spa_t *spa = dmu_objset_spa(zv->zv_objset);
1314
1315         /* Must be sector aligned, and not stradle a block boundary. */
1316         if (P2PHASE(offset, DEV_BSIZE) || P2PHASE(size, DEV_BSIZE) ||
1317             P2BOUNDARY(offset, size, zv->zv_volblocksize)) {
1318                 return (SET_ERROR(EINVAL));
1319         }
1320         ASSERT(size <= zv->zv_volblocksize);
1321
1322         /* Locate the extent this belongs to */
1323         ze = list_head(&zv->zv_extents);
1324         while (offset >= ze->ze_nblks * zv->zv_volblocksize) {
1325                 offset -= ze->ze_nblks * zv->zv_volblocksize;
1326                 ze = list_next(&zv->zv_extents, ze);
1327         }
1328
1329         if (ze == NULL)
1330                 return (SET_ERROR(EINVAL));
1331
1332         if (!ddi_in_panic())
1333                 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
1334
1335         vd = vdev_lookup_top(spa, DVA_GET_VDEV(&ze->ze_dva));
1336         offset += DVA_GET_OFFSET(&ze->ze_dva);
1337         error = zvol_dumpio_vdev(vd, addr, offset, DVA_GET_OFFSET(&ze->ze_dva),
1338             size, doread, isdump);
1339
1340         if (!ddi_in_panic())
1341                 spa_config_exit(spa, SCL_STATE, FTAG);
1342
1343         return (error);
1344 }
1345 #endif  /* sun */
1346
1347 void
1348 zvol_strategy(struct bio *bp)
1349 {
1350         zvol_state_t *zv;
1351         uint64_t off, volsize;
1352         size_t resid;
1353         char *addr;
1354         objset_t *os;
1355         rl_t *rl;
1356         int error = 0;
1357         boolean_t doread = 0;
1358         boolean_t is_dumpified;
1359         boolean_t sync;
1360
1361         if (bp->bio_to)
1362                 zv = bp->bio_to->private;
1363         else
1364                 zv = bp->bio_dev->si_drv2;
1365
1366         if (zv == NULL) {
1367                 error = ENXIO;
1368                 goto out;
1369         }
1370
1371         if (bp->bio_cmd != BIO_READ && (zv->zv_flags & ZVOL_RDONLY)) {
1372                 error = EROFS;
1373                 goto out;
1374         }
1375
1376         switch (bp->bio_cmd) {
1377         case BIO_FLUSH:
1378                 goto sync;
1379         case BIO_READ:
1380                 doread = 1;
1381         case BIO_WRITE:
1382         case BIO_DELETE:
1383                 break;
1384         default:
1385                 error = EOPNOTSUPP;
1386                 goto out;
1387         }
1388
1389         off = bp->bio_offset;
1390         volsize = zv->zv_volsize;
1391
1392         os = zv->zv_objset;
1393         ASSERT(os != NULL);
1394
1395         addr = bp->bio_data;
1396         resid = bp->bio_length;
1397
1398         if (resid > 0 && (off < 0 || off >= volsize)) {
1399                 error = EIO;
1400                 goto out;
1401         }
1402
1403 #ifdef illumos
1404         is_dumpified = zv->zv_flags & ZVOL_DUMPIFIED;
1405 #else
1406         is_dumpified = B_FALSE;
1407 #endif
1408         sync = !doread && !is_dumpified &&
1409             zv->zv_objset->os_sync == ZFS_SYNC_ALWAYS;
1410
1411         /*
1412          * There must be no buffer changes when doing a dmu_sync() because
1413          * we can't change the data whilst calculating the checksum.
1414          */
1415         rl = zfs_range_lock(&zv->zv_znode, off, resid,
1416             doread ? RL_READER : RL_WRITER);
1417
1418         if (bp->bio_cmd == BIO_DELETE) {
1419                 dmu_tx_t *tx = dmu_tx_create(zv->zv_objset);
1420                 error = dmu_tx_assign(tx, TXG_WAIT);
1421                 if (error != 0) {
1422                         dmu_tx_abort(tx);
1423                 } else {
1424                         zvol_log_truncate(zv, tx, off, resid, B_TRUE);
1425                         dmu_tx_commit(tx);
1426                         error = dmu_free_long_range(zv->zv_objset, ZVOL_OBJ,
1427                             off, resid);
1428                         resid = 0;
1429                 }
1430                 goto unlock;
1431         }
1432
1433         while (resid != 0 && off < volsize) {
1434                 size_t size = MIN(resid, zvol_maxphys);
1435 #ifdef illumos
1436                 if (is_dumpified) {
1437                         size = MIN(size, P2END(off, zv->zv_volblocksize) - off);
1438                         error = zvol_dumpio(zv, addr, off, size,
1439                             doread, B_FALSE);
1440                 } else if (doread) {
1441 #else
1442                 if (doread) {
1443 #endif
1444                         error = dmu_read(os, ZVOL_OBJ, off, size, addr,
1445                             DMU_READ_PREFETCH);
1446                 } else {
1447                         dmu_tx_t *tx = dmu_tx_create(os);
1448                         dmu_tx_hold_write(tx, ZVOL_OBJ, off, size);
1449                         error = dmu_tx_assign(tx, TXG_WAIT);
1450                         if (error) {
1451                                 dmu_tx_abort(tx);
1452                         } else {
1453                                 dmu_write(os, ZVOL_OBJ, off, size, addr, tx);
1454                                 zvol_log_write(zv, tx, off, size, sync);
1455                                 dmu_tx_commit(tx);
1456                         }
1457                 }
1458                 if (error) {
1459                         /* convert checksum errors into IO errors */
1460                         if (error == ECKSUM)
1461                                 error = SET_ERROR(EIO);
1462                         break;
1463                 }
1464                 off += size;
1465                 addr += size;
1466                 resid -= size;
1467         }
1468 unlock:
1469         zfs_range_unlock(rl);
1470
1471         bp->bio_completed = bp->bio_length - resid;
1472         if (bp->bio_completed < bp->bio_length && off > volsize)
1473                 error = EINVAL;
1474
1475         if (sync) {
1476 sync:
1477                 zil_commit(zv->zv_zilog, ZVOL_OBJ);
1478         }
1479 out:
1480         if (bp->bio_to)
1481                 g_io_deliver(bp, error);
1482         else
1483                 biofinish(bp, NULL, error);
1484 }
1485
1486 #ifdef sun
1487 /*
1488  * Set the buffer count to the zvol maximum transfer.
1489  * Using our own routine instead of the default minphys()
1490  * means that for larger writes we write bigger buffers on X86
1491  * (128K instead of 56K) and flush the disk write cache less often
1492  * (every zvol_maxphys - currently 1MB) instead of minphys (currently
1493  * 56K on X86 and 128K on sparc).
1494  */
1495 void
1496 zvol_minphys(struct buf *bp)
1497 {
1498         if (bp->b_bcount > zvol_maxphys)
1499                 bp->b_bcount = zvol_maxphys;
1500 }
1501
1502 int
1503 zvol_dump(dev_t dev, caddr_t addr, daddr_t blkno, int nblocks)
1504 {
1505         minor_t minor = getminor(dev);
1506         zvol_state_t *zv;
1507         int error = 0;
1508         uint64_t size;
1509         uint64_t boff;
1510         uint64_t resid;
1511
1512         zv = zfsdev_get_soft_state(minor, ZSST_ZVOL);
1513         if (zv == NULL)
1514                 return (SET_ERROR(ENXIO));
1515
1516         if ((zv->zv_flags & ZVOL_DUMPIFIED) == 0)
1517                 return (SET_ERROR(EINVAL));
1518
1519         boff = ldbtob(blkno);
1520         resid = ldbtob(nblocks);
1521
1522         VERIFY3U(boff + resid, <=, zv->zv_volsize);
1523
1524         while (resid) {
1525                 size = MIN(resid, P2END(boff, zv->zv_volblocksize) - boff);
1526                 error = zvol_dumpio(zv, addr, boff, size, B_FALSE, B_TRUE);
1527                 if (error)
1528                         break;
1529                 boff += size;
1530                 addr += size;
1531                 resid -= size;
1532         }
1533
1534         return (error);
1535 }
1536
1537 /*ARGSUSED*/
1538 int
1539 zvol_read(dev_t dev, uio_t *uio, cred_t *cr)
1540 {
1541         minor_t minor = getminor(dev);
1542 #else
1543 int
1544 zvol_read(struct cdev *dev, struct uio *uio, int ioflag)
1545 {
1546 #endif
1547         zvol_state_t *zv;
1548         uint64_t volsize;
1549         rl_t *rl;
1550         int error = 0;
1551
1552 #ifdef sun
1553         zv = zfsdev_get_soft_state(minor, ZSST_ZVOL);
1554         if (zv == NULL)
1555                 return (SET_ERROR(ENXIO));
1556 #else
1557         zv = dev->si_drv2;
1558 #endif
1559
1560         volsize = zv->zv_volsize;
1561         if (uio->uio_resid > 0 &&
1562             (uio->uio_loffset < 0 || uio->uio_loffset > volsize))
1563                 return (SET_ERROR(EIO));
1564
1565 #ifdef illumos
1566         if (zv->zv_flags & ZVOL_DUMPIFIED) {
1567                 error = physio(zvol_strategy, NULL, dev, B_READ,
1568                     zvol_minphys, uio);
1569                 return (error);
1570         }
1571 #endif
1572
1573         rl = zfs_range_lock(&zv->zv_znode, uio->uio_loffset, uio->uio_resid,
1574             RL_READER);
1575         while (uio->uio_resid > 0 && uio->uio_loffset < volsize) {
1576                 uint64_t bytes = MIN(uio->uio_resid, DMU_MAX_ACCESS >> 1);
1577
1578                 /* don't read past the end */
1579                 if (bytes > volsize - uio->uio_loffset)
1580                         bytes = volsize - uio->uio_loffset;
1581
1582                 error =  dmu_read_uio(zv->zv_objset, ZVOL_OBJ, uio, bytes);
1583                 if (error) {
1584                         /* convert checksum errors into IO errors */
1585                         if (error == ECKSUM)
1586                                 error = SET_ERROR(EIO);
1587                         break;
1588                 }
1589         }
1590         zfs_range_unlock(rl);
1591         return (error);
1592 }
1593
1594 #ifdef sun
1595 /*ARGSUSED*/
1596 int
1597 zvol_write(dev_t dev, uio_t *uio, cred_t *cr)
1598 {
1599         minor_t minor = getminor(dev);
1600 #else
1601 int
1602 zvol_write(struct cdev *dev, struct uio *uio, int ioflag)
1603 {
1604 #endif
1605         zvol_state_t *zv;
1606         uint64_t volsize;
1607         rl_t *rl;
1608         int error = 0;
1609         boolean_t sync;
1610
1611 #ifdef sun
1612         zv = zfsdev_get_soft_state(minor, ZSST_ZVOL);
1613         if (zv == NULL)
1614                 return (SET_ERROR(ENXIO));
1615 #else
1616         zv = dev->si_drv2;
1617 #endif
1618
1619         volsize = zv->zv_volsize;
1620         if (uio->uio_resid > 0 &&
1621             (uio->uio_loffset < 0 || uio->uio_loffset > volsize))
1622                 return (SET_ERROR(EIO));
1623
1624 #ifdef illumos
1625         if (zv->zv_flags & ZVOL_DUMPIFIED) {
1626                 error = physio(zvol_strategy, NULL, dev, B_WRITE,
1627                     zvol_minphys, uio);
1628                 return (error);
1629         }
1630 #endif
1631
1632 #ifdef sun
1633         sync = !(zv->zv_flags & ZVOL_WCE) ||
1634 #else
1635         sync =
1636 #endif
1637             (zv->zv_objset->os_sync == ZFS_SYNC_ALWAYS);
1638
1639         rl = zfs_range_lock(&zv->zv_znode, uio->uio_loffset, uio->uio_resid,
1640             RL_WRITER);
1641         while (uio->uio_resid > 0 && uio->uio_loffset < volsize) {
1642                 uint64_t bytes = MIN(uio->uio_resid, DMU_MAX_ACCESS >> 1);
1643                 uint64_t off = uio->uio_loffset;
1644                 dmu_tx_t *tx = dmu_tx_create(zv->zv_objset);
1645
1646                 if (bytes > volsize - off)      /* don't write past the end */
1647                         bytes = volsize - off;
1648
1649                 dmu_tx_hold_write(tx, ZVOL_OBJ, off, bytes);
1650                 error = dmu_tx_assign(tx, TXG_WAIT);
1651                 if (error) {
1652                         dmu_tx_abort(tx);
1653                         break;
1654                 }
1655                 error = dmu_write_uio_dbuf(zv->zv_dbuf, uio, bytes, tx);
1656                 if (error == 0)
1657                         zvol_log_write(zv, tx, off, bytes, sync);
1658                 dmu_tx_commit(tx);
1659
1660                 if (error)
1661                         break;
1662         }
1663         zfs_range_unlock(rl);
1664         if (sync)
1665                 zil_commit(zv->zv_zilog, ZVOL_OBJ);
1666         return (error);
1667 }
1668
1669 #ifdef sun
1670 int
1671 zvol_getefi(void *arg, int flag, uint64_t vs, uint8_t bs)
1672 {
1673         struct uuid uuid = EFI_RESERVED;
1674         efi_gpe_t gpe = { 0 };
1675         uint32_t crc;
1676         dk_efi_t efi;
1677         int length;
1678         char *ptr;
1679
1680         if (ddi_copyin(arg, &efi, sizeof (dk_efi_t), flag))
1681                 return (SET_ERROR(EFAULT));
1682         ptr = (char *)(uintptr_t)efi.dki_data_64;
1683         length = efi.dki_length;
1684         /*
1685          * Some clients may attempt to request a PMBR for the
1686          * zvol.  Currently this interface will return EINVAL to
1687          * such requests.  These requests could be supported by
1688          * adding a check for lba == 0 and consing up an appropriate
1689          * PMBR.
1690          */
1691         if (efi.dki_lba < 1 || efi.dki_lba > 2 || length <= 0)
1692                 return (SET_ERROR(EINVAL));
1693
1694         gpe.efi_gpe_StartingLBA = LE_64(34ULL);
1695         gpe.efi_gpe_EndingLBA = LE_64((vs >> bs) - 1);
1696         UUID_LE_CONVERT(gpe.efi_gpe_PartitionTypeGUID, uuid);
1697
1698         if (efi.dki_lba == 1) {
1699                 efi_gpt_t gpt = { 0 };
1700
1701                 gpt.efi_gpt_Signature = LE_64(EFI_SIGNATURE);
1702                 gpt.efi_gpt_Revision = LE_32(EFI_VERSION_CURRENT);
1703                 gpt.efi_gpt_HeaderSize = LE_32(sizeof (gpt));
1704                 gpt.efi_gpt_MyLBA = LE_64(1ULL);
1705                 gpt.efi_gpt_FirstUsableLBA = LE_64(34ULL);
1706                 gpt.efi_gpt_LastUsableLBA = LE_64((vs >> bs) - 1);
1707                 gpt.efi_gpt_PartitionEntryLBA = LE_64(2ULL);
1708                 gpt.efi_gpt_NumberOfPartitionEntries = LE_32(1);
1709                 gpt.efi_gpt_SizeOfPartitionEntry =
1710                     LE_32(sizeof (efi_gpe_t));
1711                 CRC32(crc, &gpe, sizeof (gpe), -1U, crc32_table);
1712                 gpt.efi_gpt_PartitionEntryArrayCRC32 = LE_32(~crc);
1713                 CRC32(crc, &gpt, sizeof (gpt), -1U, crc32_table);
1714                 gpt.efi_gpt_HeaderCRC32 = LE_32(~crc);
1715                 if (ddi_copyout(&gpt, ptr, MIN(sizeof (gpt), length),
1716                     flag))
1717                         return (SET_ERROR(EFAULT));
1718                 ptr += sizeof (gpt);
1719                 length -= sizeof (gpt);
1720         }
1721         if (length > 0 && ddi_copyout(&gpe, ptr, MIN(sizeof (gpe),
1722             length), flag))
1723                 return (SET_ERROR(EFAULT));
1724         return (0);
1725 }
1726
1727 /*
1728  * BEGIN entry points to allow external callers access to the volume.
1729  */
1730 /*
1731  * Return the volume parameters needed for access from an external caller.
1732  * These values are invariant as long as the volume is held open.
1733  */
1734 int
1735 zvol_get_volume_params(minor_t minor, uint64_t *blksize,
1736     uint64_t *max_xfer_len, void **minor_hdl, void **objset_hdl, void **zil_hdl,
1737     void **rl_hdl, void **bonus_hdl)
1738 {
1739         zvol_state_t *zv;
1740
1741         zv = zfsdev_get_soft_state(minor, ZSST_ZVOL);
1742         if (zv == NULL)
1743                 return (SET_ERROR(ENXIO));
1744         if (zv->zv_flags & ZVOL_DUMPIFIED)
1745                 return (SET_ERROR(ENXIO));
1746
1747         ASSERT(blksize && max_xfer_len && minor_hdl &&
1748             objset_hdl && zil_hdl && rl_hdl && bonus_hdl);
1749
1750         *blksize = zv->zv_volblocksize;
1751         *max_xfer_len = (uint64_t)zvol_maxphys;
1752         *minor_hdl = zv;
1753         *objset_hdl = zv->zv_objset;
1754         *zil_hdl = zv->zv_zilog;
1755         *rl_hdl = &zv->zv_znode;
1756         *bonus_hdl = zv->zv_dbuf;
1757         return (0);
1758 }
1759
1760 /*
1761  * Return the current volume size to an external caller.
1762  * The size can change while the volume is open.
1763  */
1764 uint64_t
1765 zvol_get_volume_size(void *minor_hdl)
1766 {
1767         zvol_state_t *zv = minor_hdl;
1768
1769         return (zv->zv_volsize);
1770 }
1771
1772 /*
1773  * Return the current WCE setting to an external caller.
1774  * The WCE setting can change while the volume is open.
1775  */
1776 int
1777 zvol_get_volume_wce(void *minor_hdl)
1778 {
1779         zvol_state_t *zv = minor_hdl;
1780
1781         return ((zv->zv_flags & ZVOL_WCE) ? 1 : 0);
1782 }
1783
1784 /*
1785  * Entry point for external callers to zvol_log_write
1786  */
1787 void
1788 zvol_log_write_minor(void *minor_hdl, dmu_tx_t *tx, offset_t off, ssize_t resid,
1789     boolean_t sync)
1790 {
1791         zvol_state_t *zv = minor_hdl;
1792
1793         zvol_log_write(zv, tx, off, resid, sync);
1794 }
1795 /*
1796  * END entry points to allow external callers access to the volume.
1797  */
1798 #endif  /* sun */
1799
1800 /*
1801  * Log a DKIOCFREE/free-long-range to the ZIL with TX_TRUNCATE.
1802  */
1803 static void
1804 zvol_log_truncate(zvol_state_t *zv, dmu_tx_t *tx, uint64_t off, uint64_t len,
1805     boolean_t sync)
1806 {
1807         itx_t *itx;
1808         lr_truncate_t *lr;
1809         zilog_t *zilog = zv->zv_zilog;
1810
1811         if (zil_replaying(zilog, tx))
1812                 return;
1813
1814         itx = zil_itx_create(TX_TRUNCATE, sizeof (*lr));
1815         lr = (lr_truncate_t *)&itx->itx_lr;
1816         lr->lr_foid = ZVOL_OBJ;
1817         lr->lr_offset = off;
1818         lr->lr_length = len;
1819
1820         itx->itx_sync = sync;
1821         zil_itx_assign(zilog, itx, tx);
1822 }
1823
1824 #ifdef sun
1825 /*
1826  * Dirtbag ioctls to support mkfs(1M) for UFS filesystems.  See dkio(7I).
1827  * Also a dirtbag dkio ioctl for unmap/free-block functionality.
1828  */
1829 /*ARGSUSED*/
1830 int
1831 zvol_ioctl(dev_t dev, int cmd, intptr_t arg, int flag, cred_t *cr, int *rvalp)
1832 {
1833         zvol_state_t *zv;
1834         struct dk_callback *dkc;
1835         int error = 0;
1836         rl_t *rl;
1837
1838         mutex_enter(&spa_namespace_lock);
1839
1840         zv = zfsdev_get_soft_state(getminor(dev), ZSST_ZVOL);
1841
1842         if (zv == NULL) {
1843                 mutex_exit(&spa_namespace_lock);
1844                 return (SET_ERROR(ENXIO));
1845         }
1846         ASSERT(zv->zv_total_opens > 0);
1847
1848         switch (cmd) {
1849
1850         case DKIOCINFO:
1851         {
1852                 struct dk_cinfo dki;
1853
1854                 bzero(&dki, sizeof (dki));
1855                 (void) strcpy(dki.dki_cname, "zvol");
1856                 (void) strcpy(dki.dki_dname, "zvol");
1857                 dki.dki_ctype = DKC_UNKNOWN;
1858                 dki.dki_unit = getminor(dev);
1859                 dki.dki_maxtransfer = 1 << (SPA_MAXBLOCKSHIFT - zv->zv_min_bs);
1860                 mutex_exit(&spa_namespace_lock);
1861                 if (ddi_copyout(&dki, (void *)arg, sizeof (dki), flag))
1862                         error = SET_ERROR(EFAULT);
1863                 return (error);
1864         }
1865
1866         case DKIOCGMEDIAINFO:
1867         {
1868                 struct dk_minfo dkm;
1869
1870                 bzero(&dkm, sizeof (dkm));
1871                 dkm.dki_lbsize = 1U << zv->zv_min_bs;
1872                 dkm.dki_capacity = zv->zv_volsize >> zv->zv_min_bs;
1873                 dkm.dki_media_type = DK_UNKNOWN;
1874                 mutex_exit(&spa_namespace_lock);
1875                 if (ddi_copyout(&dkm, (void *)arg, sizeof (dkm), flag))
1876                         error = SET_ERROR(EFAULT);
1877                 return (error);
1878         }
1879
1880         case DKIOCGMEDIAINFOEXT:
1881         {
1882                 struct dk_minfo_ext dkmext;
1883
1884                 bzero(&dkmext, sizeof (dkmext));
1885                 dkmext.dki_lbsize = 1U << zv->zv_min_bs;
1886                 dkmext.dki_pbsize = zv->zv_volblocksize;
1887                 dkmext.dki_capacity = zv->zv_volsize >> zv->zv_min_bs;
1888                 dkmext.dki_media_type = DK_UNKNOWN;
1889                 mutex_exit(&spa_namespace_lock);
1890                 if (ddi_copyout(&dkmext, (void *)arg, sizeof (dkmext), flag))
1891                         error = SET_ERROR(EFAULT);
1892                 return (error);
1893         }
1894
1895         case DKIOCGETEFI:
1896         {
1897                 uint64_t vs = zv->zv_volsize;
1898                 uint8_t bs = zv->zv_min_bs;
1899
1900                 mutex_exit(&spa_namespace_lock);
1901                 error = zvol_getefi((void *)arg, flag, vs, bs);
1902                 return (error);
1903         }
1904
1905         case DKIOCFLUSHWRITECACHE:
1906                 dkc = (struct dk_callback *)arg;
1907                 mutex_exit(&spa_namespace_lock);
1908                 zil_commit(zv->zv_zilog, ZVOL_OBJ);
1909                 if ((flag & FKIOCTL) && dkc != NULL && dkc->dkc_callback) {
1910                         (*dkc->dkc_callback)(dkc->dkc_cookie, error);
1911                         error = 0;
1912                 }
1913                 return (error);
1914
1915         case DKIOCGETWCE:
1916         {
1917                 int wce = (zv->zv_flags & ZVOL_WCE) ? 1 : 0;
1918                 if (ddi_copyout(&wce, (void *)arg, sizeof (int),
1919                     flag))
1920                         error = SET_ERROR(EFAULT);
1921                 break;
1922         }
1923         case DKIOCSETWCE:
1924         {
1925                 int wce;
1926                 if (ddi_copyin((void *)arg, &wce, sizeof (int),
1927                     flag)) {
1928                         error = SET_ERROR(EFAULT);
1929                         break;
1930                 }
1931                 if (wce) {
1932                         zv->zv_flags |= ZVOL_WCE;
1933                         mutex_exit(&spa_namespace_lock);
1934                 } else {
1935                         zv->zv_flags &= ~ZVOL_WCE;
1936                         mutex_exit(&spa_namespace_lock);
1937                         zil_commit(zv->zv_zilog, ZVOL_OBJ);
1938                 }
1939                 return (0);
1940         }
1941
1942         case DKIOCGGEOM:
1943         case DKIOCGVTOC:
1944                 /*
1945                  * commands using these (like prtvtoc) expect ENOTSUP
1946                  * since we're emulating an EFI label
1947                  */
1948                 error = SET_ERROR(ENOTSUP);
1949                 break;
1950
1951         case DKIOCDUMPINIT:
1952                 rl = zfs_range_lock(&zv->zv_znode, 0, zv->zv_volsize,
1953                     RL_WRITER);
1954                 error = zvol_dumpify(zv);
1955                 zfs_range_unlock(rl);
1956                 break;
1957
1958         case DKIOCDUMPFINI:
1959                 if (!(zv->zv_flags & ZVOL_DUMPIFIED))
1960                         break;
1961                 rl = zfs_range_lock(&zv->zv_znode, 0, zv->zv_volsize,
1962                     RL_WRITER);
1963                 error = zvol_dump_fini(zv);
1964                 zfs_range_unlock(rl);
1965                 break;
1966
1967         case DKIOCFREE:
1968         {
1969                 dkioc_free_t df;
1970                 dmu_tx_t *tx;
1971
1972                 if (ddi_copyin((void *)arg, &df, sizeof (df), flag)) {
1973                         error = SET_ERROR(EFAULT);
1974                         break;
1975                 }
1976
1977                 /*
1978                  * Apply Postel's Law to length-checking.  If they overshoot,
1979                  * just blank out until the end, if there's a need to blank
1980                  * out anything.
1981                  */
1982                 if (df.df_start >= zv->zv_volsize)
1983                         break;  /* No need to do anything... */
1984                 if (df.df_start + df.df_length > zv->zv_volsize)
1985                         df.df_length = DMU_OBJECT_END;
1986
1987                 rl = zfs_range_lock(&zv->zv_znode, df.df_start, df.df_length,
1988                     RL_WRITER);
1989                 tx = dmu_tx_create(zv->zv_objset);
1990                 error = dmu_tx_assign(tx, TXG_WAIT);
1991                 if (error != 0) {
1992                         dmu_tx_abort(tx);
1993                 } else {
1994                         zvol_log_truncate(zv, tx, df.df_start,
1995                             df.df_length, B_TRUE);
1996                         dmu_tx_commit(tx);
1997                         error = dmu_free_long_range(zv->zv_objset, ZVOL_OBJ,
1998                             df.df_start, df.df_length);
1999                 }
2000
2001                 zfs_range_unlock(rl);
2002
2003                 if (error == 0) {
2004                         /*
2005                          * If the write-cache is disabled or 'sync' property
2006                          * is set to 'always' then treat this as a synchronous
2007                          * operation (i.e. commit to zil).
2008                          */
2009                         if (!(zv->zv_flags & ZVOL_WCE) ||
2010                             (zv->zv_objset->os_sync == ZFS_SYNC_ALWAYS))
2011                                 zil_commit(zv->zv_zilog, ZVOL_OBJ);
2012
2013                         /*
2014                          * If the caller really wants synchronous writes, and
2015                          * can't wait for them, don't return until the write
2016                          * is done.
2017                          */
2018                         if (df.df_flags & DF_WAIT_SYNC) {
2019                                 txg_wait_synced(
2020                                     dmu_objset_pool(zv->zv_objset), 0);
2021                         }
2022                 }
2023                 break;
2024         }
2025
2026         default:
2027                 error = SET_ERROR(ENOTTY);
2028                 break;
2029
2030         }
2031         mutex_exit(&spa_namespace_lock);
2032         return (error);
2033 }
2034 #endif  /* sun */
2035
2036 int
2037 zvol_busy(void)
2038 {
2039         return (zvol_minors != 0);
2040 }
2041
2042 void
2043 zvol_init(void)
2044 {
2045         VERIFY(ddi_soft_state_init(&zfsdev_state, sizeof (zfs_soft_state_t),
2046             1) == 0);
2047         ZFS_LOG(1, "ZVOL Initialized.");
2048 }
2049
2050 void
2051 zvol_fini(void)
2052 {
2053         ddi_soft_state_fini(&zfsdev_state);
2054         ZFS_LOG(1, "ZVOL Deinitialized.");
2055 }
2056
2057 #ifdef sun
2058 /*ARGSUSED*/
2059 static int
2060 zfs_mvdev_dump_feature_check(void *arg, dmu_tx_t *tx)
2061 {
2062         spa_t *spa = dmu_tx_pool(tx)->dp_spa;
2063
2064         if (spa_feature_is_active(spa, SPA_FEATURE_MULTI_VDEV_CRASH_DUMP))
2065                 return (1);
2066         return (0);
2067 }
2068
2069 /*ARGSUSED*/
2070 static void
2071 zfs_mvdev_dump_activate_feature_sync(void *arg, dmu_tx_t *tx)
2072 {
2073         spa_t *spa = dmu_tx_pool(tx)->dp_spa;
2074
2075         spa_feature_incr(spa, SPA_FEATURE_MULTI_VDEV_CRASH_DUMP, tx);
2076 }
2077
2078 static int
2079 zvol_dump_init(zvol_state_t *zv, boolean_t resize)
2080 {
2081         dmu_tx_t *tx;
2082         int error;
2083         objset_t *os = zv->zv_objset;
2084         spa_t *spa = dmu_objset_spa(os);
2085         vdev_t *vd = spa->spa_root_vdev;
2086         nvlist_t *nv = NULL;
2087         uint64_t version = spa_version(spa);
2088         enum zio_checksum checksum;
2089
2090         ASSERT(MUTEX_HELD(&spa_namespace_lock));
2091         ASSERT(vd->vdev_ops == &vdev_root_ops);
2092
2093         error = dmu_free_long_range(zv->zv_objset, ZVOL_OBJ, 0,
2094             DMU_OBJECT_END);
2095         /* wait for dmu_free_long_range to actually free the blocks */
2096         txg_wait_synced(dmu_objset_pool(zv->zv_objset), 0);
2097
2098         /*
2099          * If the pool on which the dump device is being initialized has more
2100          * than one child vdev, check that the MULTI_VDEV_CRASH_DUMP feature is
2101          * enabled.  If so, bump that feature's counter to indicate that the
2102          * feature is active. We also check the vdev type to handle the
2103          * following case:
2104          *   # zpool create test raidz disk1 disk2 disk3
2105          *   Now have spa_root_vdev->vdev_children == 1 (the raidz vdev),
2106          *   the raidz vdev itself has 3 children.
2107          */
2108         if (vd->vdev_children > 1 || vd->vdev_ops == &vdev_raidz_ops) {
2109                 if (!spa_feature_is_enabled(spa,
2110                     SPA_FEATURE_MULTI_VDEV_CRASH_DUMP))
2111                         return (SET_ERROR(ENOTSUP));
2112                 (void) dsl_sync_task(spa_name(spa),
2113                     zfs_mvdev_dump_feature_check,
2114                     zfs_mvdev_dump_activate_feature_sync, NULL, 2);
2115         }
2116
2117         tx = dmu_tx_create(os);
2118         dmu_tx_hold_zap(tx, ZVOL_ZAP_OBJ, TRUE, NULL);
2119         dmu_tx_hold_bonus(tx, ZVOL_OBJ);
2120         error = dmu_tx_assign(tx, TXG_WAIT);
2121         if (error) {
2122                 dmu_tx_abort(tx);
2123                 return (error);
2124         }
2125
2126         /*
2127          * If MULTI_VDEV_CRASH_DUMP is active, use the NOPARITY checksum
2128          * function.  Otherwise, use the old default -- OFF.
2129          */
2130         checksum = spa_feature_is_active(spa,
2131             SPA_FEATURE_MULTI_VDEV_CRASH_DUMP) ? ZIO_CHECKSUM_NOPARITY :
2132             ZIO_CHECKSUM_OFF;
2133
2134         /*
2135          * If we are resizing the dump device then we only need to
2136          * update the refreservation to match the newly updated
2137          * zvolsize. Otherwise, we save off the original state of the
2138          * zvol so that we can restore them if the zvol is ever undumpified.
2139          */
2140         if (resize) {
2141                 error = zap_update(os, ZVOL_ZAP_OBJ,
2142                     zfs_prop_to_name(ZFS_PROP_REFRESERVATION), 8, 1,
2143                     &zv->zv_volsize, tx);
2144         } else {
2145                 uint64_t checksum, compress, refresrv, vbs, dedup;
2146
2147                 error = dsl_prop_get_integer(zv->zv_name,
2148                     zfs_prop_to_name(ZFS_PROP_COMPRESSION), &compress, NULL);
2149                 error = error ? error : dsl_prop_get_integer(zv->zv_name,
2150                     zfs_prop_to_name(ZFS_PROP_CHECKSUM), &checksum, NULL);
2151                 error = error ? error : dsl_prop_get_integer(zv->zv_name,
2152                     zfs_prop_to_name(ZFS_PROP_REFRESERVATION), &refresrv, NULL);
2153                 error = error ? error : dsl_prop_get_integer(zv->zv_name,
2154                     zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE), &vbs, NULL);
2155                 if (version >= SPA_VERSION_DEDUP) {
2156                         error = error ? error :
2157                             dsl_prop_get_integer(zv->zv_name,
2158                             zfs_prop_to_name(ZFS_PROP_DEDUP), &dedup, NULL);
2159                 }
2160
2161                 error = error ? error : zap_update(os, ZVOL_ZAP_OBJ,
2162                     zfs_prop_to_name(ZFS_PROP_COMPRESSION), 8, 1,
2163                     &compress, tx);
2164                 error = error ? error : zap_update(os, ZVOL_ZAP_OBJ,
2165                     zfs_prop_to_name(ZFS_PROP_CHECKSUM), 8, 1, &checksum, tx);
2166                 error = error ? error : zap_update(os, ZVOL_ZAP_OBJ,
2167                     zfs_prop_to_name(ZFS_PROP_REFRESERVATION), 8, 1,
2168                     &refresrv, tx);
2169                 error = error ? error : zap_update(os, ZVOL_ZAP_OBJ,
2170                     zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE), 8, 1,
2171                     &vbs, tx);
2172                 error = error ? error : dmu_object_set_blocksize(
2173                     os, ZVOL_OBJ, SPA_MAXBLOCKSIZE, 0, tx);
2174                 if (version >= SPA_VERSION_DEDUP) {
2175                         error = error ? error : zap_update(os, ZVOL_ZAP_OBJ,
2176                             zfs_prop_to_name(ZFS_PROP_DEDUP), 8, 1,
2177                             &dedup, tx);
2178                 }
2179                 if (error == 0)
2180                         zv->zv_volblocksize = SPA_MAXBLOCKSIZE;
2181         }
2182         dmu_tx_commit(tx);
2183
2184         /*
2185          * We only need update the zvol's property if we are initializing
2186          * the dump area for the first time.
2187          */
2188         if (!resize) {
2189                 VERIFY(nvlist_alloc(&nv, NV_UNIQUE_NAME, KM_SLEEP) == 0);
2190                 VERIFY(nvlist_add_uint64(nv,
2191                     zfs_prop_to_name(ZFS_PROP_REFRESERVATION), 0) == 0);
2192                 VERIFY(nvlist_add_uint64(nv,
2193                     zfs_prop_to_name(ZFS_PROP_COMPRESSION),
2194                     ZIO_COMPRESS_OFF) == 0);
2195                 VERIFY(nvlist_add_uint64(nv,
2196                     zfs_prop_to_name(ZFS_PROP_CHECKSUM),
2197                     checksum) == 0);
2198                 if (version >= SPA_VERSION_DEDUP) {
2199                         VERIFY(nvlist_add_uint64(nv,
2200                             zfs_prop_to_name(ZFS_PROP_DEDUP),
2201                             ZIO_CHECKSUM_OFF) == 0);
2202                 }
2203
2204                 error = zfs_set_prop_nvlist(zv->zv_name, ZPROP_SRC_LOCAL,
2205                     nv, NULL);
2206                 nvlist_free(nv);
2207
2208                 if (error)
2209                         return (error);
2210         }
2211
2212         /* Allocate the space for the dump */
2213         error = zvol_prealloc(zv);
2214         return (error);
2215 }
2216
2217 static int
2218 zvol_dumpify(zvol_state_t *zv)
2219 {
2220         int error = 0;
2221         uint64_t dumpsize = 0;
2222         dmu_tx_t *tx;
2223         objset_t *os = zv->zv_objset;
2224
2225         if (zv->zv_flags & ZVOL_RDONLY)
2226                 return (SET_ERROR(EROFS));
2227
2228         if (zap_lookup(zv->zv_objset, ZVOL_ZAP_OBJ, ZVOL_DUMPSIZE,
2229             8, 1, &dumpsize) != 0 || dumpsize != zv->zv_volsize) {
2230                 boolean_t resize = (dumpsize > 0);
2231
2232                 if ((error = zvol_dump_init(zv, resize)) != 0) {
2233                         (void) zvol_dump_fini(zv);
2234                         return (error);
2235                 }
2236         }
2237
2238         /*
2239          * Build up our lba mapping.
2240          */
2241         error = zvol_get_lbas(zv);
2242         if (error) {
2243                 (void) zvol_dump_fini(zv);
2244                 return (error);
2245         }
2246
2247         tx = dmu_tx_create(os);
2248         dmu_tx_hold_zap(tx, ZVOL_ZAP_OBJ, TRUE, NULL);
2249         error = dmu_tx_assign(tx, TXG_WAIT);
2250         if (error) {
2251                 dmu_tx_abort(tx);
2252                 (void) zvol_dump_fini(zv);
2253                 return (error);
2254         }
2255
2256         zv->zv_flags |= ZVOL_DUMPIFIED;
2257         error = zap_update(os, ZVOL_ZAP_OBJ, ZVOL_DUMPSIZE, 8, 1,
2258             &zv->zv_volsize, tx);
2259         dmu_tx_commit(tx);
2260
2261         if (error) {
2262                 (void) zvol_dump_fini(zv);
2263                 return (error);
2264         }
2265
2266         txg_wait_synced(dmu_objset_pool(os), 0);
2267         return (0);
2268 }
2269
2270 static int
2271 zvol_dump_fini(zvol_state_t *zv)
2272 {
2273         dmu_tx_t *tx;
2274         objset_t *os = zv->zv_objset;
2275         nvlist_t *nv;
2276         int error = 0;
2277         uint64_t checksum, compress, refresrv, vbs, dedup;
2278         uint64_t version = spa_version(dmu_objset_spa(zv->zv_objset));
2279
2280         /*
2281          * Attempt to restore the zvol back to its pre-dumpified state.
2282          * This is a best-effort attempt as it's possible that not all
2283          * of these properties were initialized during the dumpify process
2284          * (i.e. error during zvol_dump_init).
2285          */
2286
2287         tx = dmu_tx_create(os);
2288         dmu_tx_hold_zap(tx, ZVOL_ZAP_OBJ, TRUE, NULL);
2289         error = dmu_tx_assign(tx, TXG_WAIT);
2290         if (error) {
2291                 dmu_tx_abort(tx);
2292                 return (error);
2293         }
2294         (void) zap_remove(os, ZVOL_ZAP_OBJ, ZVOL_DUMPSIZE, tx);
2295         dmu_tx_commit(tx);
2296
2297         (void) zap_lookup(zv->zv_objset, ZVOL_ZAP_OBJ,
2298             zfs_prop_to_name(ZFS_PROP_CHECKSUM), 8, 1, &checksum);
2299         (void) zap_lookup(zv->zv_objset, ZVOL_ZAP_OBJ,
2300             zfs_prop_to_name(ZFS_PROP_COMPRESSION), 8, 1, &compress);
2301         (void) zap_lookup(zv->zv_objset, ZVOL_ZAP_OBJ,
2302             zfs_prop_to_name(ZFS_PROP_REFRESERVATION), 8, 1, &refresrv);
2303         (void) zap_lookup(zv->zv_objset, ZVOL_ZAP_OBJ,
2304             zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE), 8, 1, &vbs);
2305
2306         VERIFY(nvlist_alloc(&nv, NV_UNIQUE_NAME, KM_SLEEP) == 0);
2307         (void) nvlist_add_uint64(nv,
2308             zfs_prop_to_name(ZFS_PROP_CHECKSUM), checksum);
2309         (void) nvlist_add_uint64(nv,
2310             zfs_prop_to_name(ZFS_PROP_COMPRESSION), compress);
2311         (void) nvlist_add_uint64(nv,
2312             zfs_prop_to_name(ZFS_PROP_REFRESERVATION), refresrv);
2313         if (version >= SPA_VERSION_DEDUP &&
2314             zap_lookup(zv->zv_objset, ZVOL_ZAP_OBJ,
2315             zfs_prop_to_name(ZFS_PROP_DEDUP), 8, 1, &dedup) == 0) {
2316                 (void) nvlist_add_uint64(nv,
2317                     zfs_prop_to_name(ZFS_PROP_DEDUP), dedup);
2318         }
2319         (void) zfs_set_prop_nvlist(zv->zv_name, ZPROP_SRC_LOCAL,
2320             nv, NULL);
2321         nvlist_free(nv);
2322
2323         zvol_free_extents(zv);
2324         zv->zv_flags &= ~ZVOL_DUMPIFIED;
2325         (void) dmu_free_long_range(os, ZVOL_OBJ, 0, DMU_OBJECT_END);
2326         /* wait for dmu_free_long_range to actually free the blocks */
2327         txg_wait_synced(dmu_objset_pool(zv->zv_objset), 0);
2328         tx = dmu_tx_create(os);
2329         dmu_tx_hold_bonus(tx, ZVOL_OBJ);
2330         error = dmu_tx_assign(tx, TXG_WAIT);
2331         if (error) {
2332                 dmu_tx_abort(tx);
2333                 return (error);
2334         }
2335         if (dmu_object_set_blocksize(os, ZVOL_OBJ, vbs, 0, tx) == 0)
2336                 zv->zv_volblocksize = vbs;
2337         dmu_tx_commit(tx);
2338
2339         return (0);
2340 }
2341 #endif  /* sun */
2342
2343 static void
2344 zvol_geom_run(zvol_state_t *zv)
2345 {
2346         struct g_provider *pp;
2347
2348         pp = zv->zv_provider;
2349         g_error_provider(pp, 0);
2350
2351         kproc_kthread_add(zvol_geom_worker, zv, &zfsproc, NULL, 0, 0,
2352             "zfskern", "zvol %s", pp->name + sizeof(ZVOL_DRIVER));
2353 }
2354
2355 static void
2356 zvol_geom_destroy(zvol_state_t *zv)
2357 {
2358         struct g_provider *pp;
2359
2360         g_topology_assert();
2361
2362         mtx_lock(&zv->zv_queue_mtx);
2363         zv->zv_state = 1;
2364         wakeup_one(&zv->zv_queue);
2365         while (zv->zv_state != 2)
2366                 msleep(&zv->zv_state, &zv->zv_queue_mtx, 0, "zvol:w", 0);
2367         mtx_destroy(&zv->zv_queue_mtx);
2368
2369         pp = zv->zv_provider;
2370         zv->zv_provider = NULL;
2371         pp->private = NULL;
2372         g_wither_geom(pp->geom, ENXIO);
2373 }
2374
2375 static int
2376 zvol_geom_access(struct g_provider *pp, int acr, int acw, int ace)
2377 {
2378         int count, error, flags;
2379
2380         g_topology_assert();
2381
2382         /*
2383          * To make it easier we expect either open or close, but not both
2384          * at the same time.
2385          */
2386         KASSERT((acr >= 0 && acw >= 0 && ace >= 0) ||
2387             (acr <= 0 && acw <= 0 && ace <= 0),
2388             ("Unsupported access request to %s (acr=%d, acw=%d, ace=%d).",
2389             pp->name, acr, acw, ace));
2390
2391         if (pp->private == NULL) {
2392                 if (acr <= 0 && acw <= 0 && ace <= 0)
2393                         return (0);
2394                 return (pp->error);
2395         }
2396
2397         /*
2398          * We don't pass FEXCL flag to zvol_open()/zvol_close() if ace != 0,
2399          * because GEOM already handles that and handles it a bit differently.
2400          * GEOM allows for multiple read/exclusive consumers and ZFS allows
2401          * only one exclusive consumer, no matter if it is reader or writer.
2402          * I like better the way GEOM works so I'll leave it for GEOM to
2403          * decide what to do.
2404          */
2405
2406         count = acr + acw + ace;
2407         if (count == 0)
2408                 return (0);
2409
2410         flags = 0;
2411         if (acr != 0 || ace != 0)
2412                 flags |= FREAD;
2413         if (acw != 0)
2414                 flags |= FWRITE;
2415
2416         g_topology_unlock();
2417         if (count > 0)
2418                 error = zvol_open(pp, flags, count);
2419         else
2420                 error = zvol_close(pp, flags, -count);
2421         g_topology_lock();
2422         return (error);
2423 }
2424
2425 static void
2426 zvol_geom_start(struct bio *bp)
2427 {
2428         zvol_state_t *zv;
2429         boolean_t first;
2430
2431         zv = bp->bio_to->private;
2432         ASSERT(zv != NULL);
2433         switch (bp->bio_cmd) {
2434         case BIO_FLUSH:
2435                 if (!THREAD_CAN_SLEEP())
2436                         goto enqueue;
2437                 zil_commit(zv->zv_zilog, ZVOL_OBJ);
2438                 g_io_deliver(bp, 0);
2439                 break;
2440         case BIO_READ:
2441         case BIO_WRITE:
2442         case BIO_DELETE:
2443                 if (!THREAD_CAN_SLEEP())
2444                         goto enqueue;
2445                 zvol_strategy(bp);
2446                 break;
2447         case BIO_GETATTR:
2448                 if (g_handleattr_int(bp, "GEOM::candelete", 1))
2449                         return;
2450                 /* FALLTHROUGH */
2451         default:
2452                 g_io_deliver(bp, EOPNOTSUPP);
2453                 break;
2454         }
2455         return;
2456
2457 enqueue:
2458         mtx_lock(&zv->zv_queue_mtx);
2459         first = (bioq_first(&zv->zv_queue) == NULL);
2460         bioq_insert_tail(&zv->zv_queue, bp);
2461         mtx_unlock(&zv->zv_queue_mtx);
2462         if (first)
2463                 wakeup_one(&zv->zv_queue);
2464 }
2465
2466 static void
2467 zvol_geom_worker(void *arg)
2468 {
2469         zvol_state_t *zv;
2470         struct bio *bp;
2471
2472         thread_lock(curthread);
2473         sched_prio(curthread, PRIBIO);
2474         thread_unlock(curthread);
2475
2476         zv = arg;
2477         for (;;) {
2478                 mtx_lock(&zv->zv_queue_mtx);
2479                 bp = bioq_takefirst(&zv->zv_queue);
2480                 if (bp == NULL) {
2481                         if (zv->zv_state == 1) {
2482                                 zv->zv_state = 2;
2483                                 wakeup(&zv->zv_state);
2484                                 mtx_unlock(&zv->zv_queue_mtx);
2485                                 kthread_exit();
2486                         }
2487                         msleep(&zv->zv_queue, &zv->zv_queue_mtx, PRIBIO | PDROP,
2488                             "zvol:io", 0);
2489                         continue;
2490                 }
2491                 mtx_unlock(&zv->zv_queue_mtx);
2492                 switch (bp->bio_cmd) {
2493                 case BIO_FLUSH:
2494                         zil_commit(zv->zv_zilog, ZVOL_OBJ);
2495                         g_io_deliver(bp, 0);
2496                         break;
2497                 case BIO_READ:
2498                 case BIO_WRITE:
2499                         zvol_strategy(bp);
2500                         break;
2501                 }
2502         }
2503 }
2504
2505 extern boolean_t dataset_name_hidden(const char *name);
2506
2507 static int
2508 zvol_create_snapshots(objset_t *os, const char *name)
2509 {
2510         uint64_t cookie, obj;
2511         char *sname;
2512         int error, len;
2513
2514         cookie = obj = 0;
2515         sname = kmem_alloc(MAXPATHLEN, KM_SLEEP);
2516
2517 #if 0
2518         (void) dmu_objset_find(name, dmu_objset_prefetch, NULL,
2519             DS_FIND_SNAPSHOTS);
2520 #endif
2521
2522         for (;;) {
2523                 len = snprintf(sname, MAXPATHLEN, "%s@", name);
2524                 if (len >= MAXPATHLEN) {
2525                         dmu_objset_rele(os, FTAG);
2526                         error = ENAMETOOLONG;
2527                         break;
2528                 }
2529
2530                 dsl_pool_config_enter(dmu_objset_pool(os), FTAG);
2531                 error = dmu_snapshot_list_next(os, MAXPATHLEN - len,
2532                     sname + len, &obj, &cookie, NULL);
2533                 dsl_pool_config_exit(dmu_objset_pool(os), FTAG);
2534                 if (error != 0) {
2535                         if (error == ENOENT)
2536                                 error = 0;
2537                         break;
2538                 }
2539
2540                 if ((error = zvol_create_minor(sname)) != 0) {
2541                         printf("ZFS WARNING: Unable to create ZVOL %s (error=%d).\n",
2542                             sname, error);
2543                         break;
2544                 }
2545         }
2546
2547         kmem_free(sname, MAXPATHLEN);
2548         return (error);
2549 }
2550
2551 int
2552 zvol_create_minors(const char *name)
2553 {
2554         uint64_t cookie;
2555         objset_t *os;
2556         char *osname, *p;
2557         int error, len;
2558
2559         if (dataset_name_hidden(name))
2560                 return (0);
2561
2562         if ((error = dmu_objset_hold(name, FTAG, &os)) != 0) {
2563                 printf("ZFS WARNING: Unable to put hold on %s (error=%d).\n",
2564                     name, error);
2565                 return (error);
2566         }
2567         if (dmu_objset_type(os) == DMU_OST_ZVOL) {
2568                 dsl_dataset_long_hold(os->os_dsl_dataset, FTAG);
2569                 dsl_pool_rele(dmu_objset_pool(os), FTAG);
2570                 if ((error = zvol_create_minor(name)) == 0)
2571                         error = zvol_create_snapshots(os, name);
2572                 else {
2573                         printf("ZFS WARNING: Unable to create ZVOL %s (error=%d).\n",
2574                             name, error);
2575                 }
2576                 dsl_dataset_long_rele(os->os_dsl_dataset, FTAG);
2577                 dsl_dataset_rele(os->os_dsl_dataset, FTAG);
2578                 return (error);
2579         }
2580         if (dmu_objset_type(os) != DMU_OST_ZFS) {
2581                 dmu_objset_rele(os, FTAG);
2582                 return (0);
2583         }
2584
2585         osname = kmem_alloc(MAXPATHLEN, KM_SLEEP);
2586         if (snprintf(osname, MAXPATHLEN, "%s/", name) >= MAXPATHLEN) {
2587                 dmu_objset_rele(os, FTAG);
2588                 kmem_free(osname, MAXPATHLEN);
2589                 return (ENOENT);
2590         }
2591         p = osname + strlen(osname);
2592         len = MAXPATHLEN - (p - osname);
2593
2594 #if 0
2595         /* Prefetch the datasets. */
2596         cookie = 0;
2597         while (dmu_dir_list_next(os, len, p, NULL, &cookie) == 0) {
2598                 if (!dataset_name_hidden(osname))
2599                         (void) dmu_objset_prefetch(osname, NULL);
2600         }
2601 #endif
2602
2603         cookie = 0;
2604         while (dmu_dir_list_next(os, MAXPATHLEN - (p - osname), p, NULL,
2605             &cookie) == 0) {
2606                 dmu_objset_rele(os, FTAG);
2607                 (void)zvol_create_minors(osname);
2608                 if ((error = dmu_objset_hold(name, FTAG, &os)) != 0) {
2609                         printf("ZFS WARNING: Unable to put hold on %s (error=%d).\n",
2610                             name, error);
2611                         return (error);
2612                 }
2613         }
2614
2615         dmu_objset_rele(os, FTAG);
2616         kmem_free(osname, MAXPATHLEN);
2617         return (0);
2618 }
2619
2620 static void
2621 zvol_rename_minor(zvol_state_t *zv, const char *newname)
2622 {
2623         struct g_geom *gp;
2624         struct g_provider *pp;
2625         struct cdev *dev;
2626
2627         ASSERT(MUTEX_HELD(&spa_namespace_lock));
2628
2629         if (zv->zv_volmode == ZFS_VOLMODE_GEOM) {
2630                 g_topology_lock();
2631                 pp = zv->zv_provider;
2632                 ASSERT(pp != NULL);
2633                 gp = pp->geom;
2634                 ASSERT(gp != NULL);
2635
2636                 zv->zv_provider = NULL;
2637                 g_wither_provider(pp, ENXIO);
2638
2639                 pp = g_new_providerf(gp, "%s/%s", ZVOL_DRIVER, newname);
2640                 pp->flags |= G_PF_DIRECT_RECEIVE | G_PF_DIRECT_SEND;
2641                 pp->sectorsize = DEV_BSIZE;
2642                 pp->mediasize = zv->zv_volsize;
2643                 pp->private = zv;
2644                 zv->zv_provider = pp;
2645                 g_error_provider(pp, 0);
2646                 g_topology_unlock();
2647         } else if (zv->zv_volmode == ZFS_VOLMODE_DEV) {
2648                 dev = zv->zv_dev;
2649                 ASSERT(dev != NULL);
2650                 zv->zv_dev = NULL;
2651                 destroy_dev(dev);
2652
2653                 if (make_dev_p(MAKEDEV_CHECKNAME | MAKEDEV_WAITOK,
2654                     &dev, &zvol_cdevsw, NULL, UID_ROOT, GID_OPERATOR,
2655                     0640, "%s/%s", ZVOL_DRIVER, newname) == 0) {
2656                         zv->zv_dev = dev;
2657                         dev->si_iosize_max = MAXPHYS;
2658                         dev->si_drv2 = zv;
2659                 }
2660         }
2661         strlcpy(zv->zv_name, newname, sizeof(zv->zv_name));
2662 }
2663
2664 void
2665 zvol_rename_minors(const char *oldname, const char *newname)
2666 {
2667         char name[MAXPATHLEN];
2668         struct g_provider *pp;
2669         struct g_geom *gp;
2670         size_t oldnamelen, newnamelen;
2671         zvol_state_t *zv;
2672         char *namebuf;
2673
2674         oldnamelen = strlen(oldname);
2675         newnamelen = strlen(newname);
2676
2677         DROP_GIANT();
2678         mutex_enter(&spa_namespace_lock);
2679
2680         LIST_FOREACH(zv, &all_zvols, zv_links) {
2681                 if (strcmp(zv->zv_name, oldname) == 0) {
2682                         zvol_rename_minor(zv, newname);
2683                 } else if (strncmp(zv->zv_name, oldname, oldnamelen) == 0 &&
2684                     (zv->zv_name[oldnamelen] == '/' ||
2685                      zv->zv_name[oldnamelen] == '@')) {
2686                         snprintf(name, sizeof(name), "%s%c%s", newname,
2687                             zv->zv_name[oldnamelen],
2688                             zv->zv_name + oldnamelen + 1);
2689                         zvol_rename_minor(zv, name);
2690                 }
2691         }
2692
2693         mutex_exit(&spa_namespace_lock);
2694         PICKUP_GIANT();
2695 }
2696
2697 static int
2698 zvol_d_open(struct cdev *dev, int flags, int fmt, struct thread *td)
2699 {
2700         zvol_state_t *zv;
2701         int err = 0;
2702
2703         mutex_enter(&spa_namespace_lock);
2704         zv = dev->si_drv2;
2705         if (zv == NULL) {
2706                 mutex_exit(&spa_namespace_lock);
2707                 return(ENXIO);          /* zvol_create_minor() not done yet */
2708         }
2709
2710         if (zv->zv_total_opens == 0)
2711                 err = zvol_first_open(zv);
2712         if (err) {
2713                 mutex_exit(&spa_namespace_lock);
2714                 return (err);
2715         }
2716         if ((flags & FWRITE) && (zv->zv_flags & ZVOL_RDONLY)) {
2717                 err = SET_ERROR(EROFS);
2718                 goto out;
2719         }
2720         if (zv->zv_flags & ZVOL_EXCL) {
2721                 err = SET_ERROR(EBUSY);
2722                 goto out;
2723         }
2724 #ifdef FEXCL
2725         if (flags & FEXCL) {
2726                 if (zv->zv_total_opens != 0) {
2727                         err = SET_ERROR(EBUSY);
2728                         goto out;
2729                 }
2730                 zv->zv_flags |= ZVOL_EXCL;
2731         }
2732 #endif
2733
2734         zv->zv_total_opens++;
2735         mutex_exit(&spa_namespace_lock);
2736         return (err);
2737 out:
2738         if (zv->zv_total_opens == 0)
2739                 zvol_last_close(zv);
2740         mutex_exit(&spa_namespace_lock);
2741         return (err);
2742 }
2743
2744 static int
2745 zvol_d_close(struct cdev *dev, int flags, int fmt, struct thread *td)
2746 {
2747         zvol_state_t *zv;
2748         int err = 0;
2749
2750         mutex_enter(&spa_namespace_lock);
2751         zv = dev->si_drv2;
2752         if (zv == NULL) {
2753                 mutex_exit(&spa_namespace_lock);
2754                 return(ENXIO);
2755         }
2756
2757         if (zv->zv_flags & ZVOL_EXCL) {
2758                 ASSERT(zv->zv_total_opens == 1);
2759                 zv->zv_flags &= ~ZVOL_EXCL;
2760         }
2761
2762         /*
2763          * If the open count is zero, this is a spurious close.
2764          * That indicates a bug in the kernel / DDI framework.
2765          */
2766         ASSERT(zv->zv_total_opens != 0);
2767
2768         /*
2769          * You may get multiple opens, but only one close.
2770          */
2771         zv->zv_total_opens--;
2772
2773         if (zv->zv_total_opens == 0)
2774                 zvol_last_close(zv);
2775
2776         mutex_exit(&spa_namespace_lock);
2777         return (0);
2778 }
2779
2780 static int
2781 zvol_d_ioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag, struct thread *td)
2782 {
2783         zvol_state_t *zv;
2784         rl_t *rl;
2785         off_t offset, length, chunk;
2786         int i, error;
2787         u_int u;
2788
2789         zv = dev->si_drv2;
2790
2791         error = 0;
2792         KASSERT(zv->zv_total_opens > 0,
2793             ("Device with zero access count in zvol_d_ioctl"));
2794
2795         i = IOCPARM_LEN(cmd);
2796         switch (cmd) {
2797         case DIOCGSECTORSIZE:
2798                 *(u_int *)data = DEV_BSIZE;
2799                 break;
2800         case DIOCGMEDIASIZE:
2801                 *(off_t *)data = zv->zv_volsize;
2802                 break;
2803         case DIOCGFLUSH:
2804                 zil_commit(zv->zv_zilog, ZVOL_OBJ);
2805                 break;
2806         case DIOCGDELETE:
2807                 offset = ((off_t *)data)[0];
2808                 length = ((off_t *)data)[1];
2809                 if ((offset % DEV_BSIZE) != 0 || (length % DEV_BSIZE) != 0 ||
2810                     offset < 0 || offset >= zv->zv_volsize ||
2811                     length <= 0) {
2812                         printf("%s: offset=%jd length=%jd\n", __func__, offset,
2813                             length);
2814                         error = EINVAL;
2815                         break;
2816                 }
2817
2818                 rl = zfs_range_lock(&zv->zv_znode, offset, length, RL_WRITER);
2819                 dmu_tx_t *tx = dmu_tx_create(zv->zv_objset);
2820                 error = dmu_tx_assign(tx, TXG_WAIT);
2821                 if (error != 0) {
2822                         dmu_tx_abort(tx);
2823                 } else {
2824                         zvol_log_truncate(zv, tx, offset, length, B_TRUE);
2825                         dmu_tx_commit(tx);
2826                         error = dmu_free_long_range(zv->zv_objset, ZVOL_OBJ,
2827                             offset, length);
2828                 }
2829                 zfs_range_unlock(rl);
2830                 if (zv->zv_objset->os_sync == ZFS_SYNC_ALWAYS)
2831                         zil_commit(zv->zv_zilog, ZVOL_OBJ);
2832                 break;
2833         case DIOCGSTRIPESIZE:
2834                 *(off_t *)data = zv->zv_volblocksize;
2835                 break;
2836         case DIOCGSTRIPEOFFSET:
2837                 *(off_t *)data = 0;
2838                 break;
2839         default:
2840                 error = ENOIOCTL;
2841         }
2842
2843         return (error);
2844 }