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