]> CyberLeo.Net >> Repos - FreeBSD/releng/8.1.git/blob - sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zvol.c
Copy stable/8 to releng/8.1 in preparation for 8.1-RC1.
[FreeBSD/releng/8.1.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) 2006 Pawel Jakub Dawidek <pjd@FreeBSD.org>
23  * All rights reserved.
24  */
25 /*
26  * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
27  * Use is subject to license terms.
28  */
29
30 /*
31  * ZFS volume emulation driver.
32  *
33  * Makes a DMU object look like a volume of arbitrary size, up to 2^64 bytes.
34  * Volumes are accessed through the symbolic links named:
35  *
36  * /dev/zvol/dsk/<pool_name>/<dataset_name>
37  * /dev/zvol/rdsk/<pool_name>/<dataset_name>
38  *
39  * These links are created by the ZFS-specific devfsadm link generator.
40  * Volumes are persistent through reboot.  No user command needs to be
41  * run before opening and using a device.
42  */
43
44 #include <sys/types.h>
45 #include <sys/param.h>
46 #include <sys/kernel.h>
47 #include <sys/errno.h>
48 #include <sys/uio.h>
49 #include <sys/bio.h>
50 #include <sys/buf.h>
51 #include <sys/kmem.h>
52 #include <sys/conf.h>
53 #include <sys/cmn_err.h>
54 #include <sys/stat.h>
55 #include <sys/zap.h>
56 #include <sys/spa.h>
57 #include <sys/zio.h>
58 #include <sys/dmu_traverse.h>
59 #include <sys/dnode.h>
60 #include <sys/dsl_dataset.h>
61 #include <sys/dsl_prop.h>
62 #include <sys/dkio.h>
63 #include <sys/byteorder.h>
64 #include <sys/sunddi.h>
65 #include <sys/dirent.h>
66 #include <sys/policy.h>
67 #include <sys/fs/zfs.h>
68 #include <sys/zfs_ioctl.h>
69 #include <sys/zil.h>
70 #include <sys/refcount.h>
71 #include <sys/zfs_znode.h>
72 #include <sys/zfs_rlock.h>
73 #include <sys/vdev_impl.h>
74 #include <sys/zvol.h>
75 #include <geom/geom.h>
76
77 #include "zfs_namecheck.h"
78
79 #define ZVOL_DUMPSIZE   "dumpsize"
80
81 struct g_class zfs_zvol_class = {
82         .name = "ZFS::ZVOL",
83         .version = G_VERSION,
84 };
85
86 DECLARE_GEOM_CLASS(zfs_zvol_class, zfs_zvol);
87
88 /*
89  * This lock protects the zvol_state structure from being modified
90  * while it's being used, e.g. an open that comes in before a create
91  * finishes.  It also protects temporary opens of the dataset so that,
92  * e.g., an open doesn't get a spurious EBUSY.
93  */
94 static kmutex_t zvol_state_lock;
95 static uint32_t zvol_minors;
96
97 typedef struct zvol_extent {
98         list_node_t     ze_node;
99         dva_t           ze_dva;         /* dva associated with this extent */
100         uint64_t        ze_nblks;       /* number of blocks in extent */
101 } zvol_extent_t;
102
103 /*
104  * The in-core state of each volume.
105  */
106 typedef struct zvol_state {
107         char            zv_name[MAXPATHLEN]; /* pool/dd name */
108         uint64_t        zv_volsize;     /* amount of space we advertise */
109         uint64_t        zv_volblocksize; /* volume block size */
110         struct g_provider *zv_provider; /* GEOM provider */
111         uint8_t         zv_min_bs;      /* minimum addressable block shift */
112         uint8_t         zv_flags;       /* readonly; dumpified */
113         objset_t        *zv_objset;     /* objset handle */
114         uint32_t        zv_mode;        /* DS_MODE_* flags at open time */
115         uint32_t        zv_total_opens; /* total open count */
116         zilog_t         *zv_zilog;      /* ZIL handle */
117         list_t          zv_extents;     /* List of extents for dump */
118         uint64_t        zv_txg_assign;  /* txg to assign during ZIL replay */
119         znode_t         zv_znode;       /* for range locking */
120         int             zv_state;
121         struct bio_queue_head zv_queue;
122         struct mtx      zv_queue_mtx;   /* zv_queue mutex */
123 } zvol_state_t;
124
125 /*
126  * zvol specific flags
127  */
128 #define ZVOL_RDONLY     0x1
129 #define ZVOL_DUMPIFIED  0x2
130 #define ZVOL_EXCL       0x4
131
132 /*
133  * zvol maximum transfer in one DMU tx.
134  */
135 int zvol_maxphys = DMU_MAX_ACCESS/2;
136
137 extern int zfs_set_prop_nvlist(const char *, nvlist_t *);
138 static int zvol_get_data(void *arg, lr_write_t *lr, char *buf, zio_t *zio);
139 static int zvol_dumpify(zvol_state_t *zv);
140 static int zvol_dump_fini(zvol_state_t *zv);
141 static int zvol_dump_init(zvol_state_t *zv, boolean_t resize);
142
143 static void
144 zvol_size_changed(zvol_state_t *zv, major_t maj)
145 {
146         struct g_provider *pp;
147
148         g_topology_assert();
149
150         pp = zv->zv_provider;
151         if (pp == NULL)
152                 return;
153         if (zv->zv_volsize == pp->mediasize)
154                 return;
155         /*
156          * Changing provider size is not really supported by GEOM, but it
157          * should be safe when provider is closed.
158          */
159         if (zv->zv_total_opens > 0)
160                 return;
161         pp->mediasize = zv->zv_volsize;
162 }
163
164 int
165 zvol_check_volsize(uint64_t volsize, uint64_t blocksize)
166 {
167         if (volsize == 0)
168                 return (EINVAL);
169
170         if (volsize % blocksize != 0)
171                 return (EINVAL);
172
173 #ifdef _ILP32
174         if (volsize - 1 > SPEC_MAXOFFSET_T)
175                 return (EOVERFLOW);
176 #endif
177         return (0);
178 }
179
180 int
181 zvol_check_volblocksize(uint64_t volblocksize)
182 {
183         if (volblocksize < SPA_MINBLOCKSIZE ||
184             volblocksize > SPA_MAXBLOCKSIZE ||
185             !ISP2(volblocksize))
186                 return (EDOM);
187
188         return (0);
189 }
190
191 static void
192 zvol_readonly_changed_cb(void *arg, uint64_t newval)
193 {
194         zvol_state_t *zv = arg;
195
196         if (newval)
197                 zv->zv_flags |= ZVOL_RDONLY;
198         else
199                 zv->zv_flags &= ~ZVOL_RDONLY;
200 }
201
202 int
203 zvol_get_stats(objset_t *os, nvlist_t *nv)
204 {
205         int error;
206         dmu_object_info_t doi;
207         uint64_t val;
208
209
210         error = zap_lookup(os, ZVOL_ZAP_OBJ, "size", 8, 1, &val);
211         if (error)
212                 return (error);
213
214         dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_VOLSIZE, val);
215
216         error = dmu_object_info(os, ZVOL_OBJ, &doi);
217
218         if (error == 0) {
219                 dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_VOLBLOCKSIZE,
220                     doi.doi_data_block_size);
221         }
222
223         return (error);
224 }
225
226 static zvol_state_t *
227 zvol_minor_lookup(const char *name)
228 {
229         struct g_provider *pp;
230         struct g_geom *gp;
231
232         g_topology_assert();
233         ASSERT(MUTEX_HELD(&zvol_state_lock));
234
235         LIST_FOREACH(gp, &zfs_zvol_class.geom, geom) {
236                 LIST_FOREACH(pp, &gp->provider, provider) {
237                         if (strcmp(pp->name + sizeof(ZVOL_DEV_DIR), name) == 0)
238                                 return (pp->private);
239                 }
240         }
241
242         return (NULL);
243 }
244
245 static int
246 zvol_access(struct g_provider *pp, int acr, int acw, int ace)
247 {
248         zvol_state_t *zv;
249
250         g_topology_assert();
251         mutex_enter(&zvol_state_lock);
252
253         zv = pp->private;
254         if (zv == NULL) {
255                 if (acr <= 0 && acw <= 0 && ace <= 0)
256                         return (0);
257                 mutex_exit(&zvol_state_lock);
258                 return (pp->error);
259         }
260
261         ASSERT(zv->zv_objset != NULL);
262
263         if (acw > 0 &&
264             ((zv->zv_flags & ZVOL_RDONLY) ||
265              (zv->zv_mode & DS_MODE_READONLY))) {
266                 mutex_exit(&zvol_state_lock);
267                 return (EROFS);
268         }
269
270         zv->zv_total_opens += acr + acw + ace;
271         zvol_size_changed(zv, 0);
272
273         mutex_exit(&zvol_state_lock);
274
275         return (0);
276 }
277
278 /*
279  * zvol_log_write() handles synchronous writes using TX_WRITE ZIL transactions.
280  *
281  * We store data in the log buffers if it's small enough.
282  * Otherwise we will later flush the data out via dmu_sync().
283  */
284 ssize_t zvol_immediate_write_sz = 32768;
285
286 static void
287 zvol_log_write(zvol_state_t *zv, dmu_tx_t *tx, offset_t off, ssize_t len)
288 {
289         uint32_t blocksize = zv->zv_volblocksize;
290         lr_write_t *lr;
291
292         while (len) {
293                 ssize_t nbytes = MIN(len, blocksize - P2PHASE(off, blocksize));
294                 itx_t *itx = zil_itx_create(TX_WRITE, sizeof (*lr));
295
296                 itx->itx_wr_state =
297                     len > zvol_immediate_write_sz ?  WR_INDIRECT : WR_NEED_COPY;
298                 itx->itx_private = zv;
299                 lr = (lr_write_t *)&itx->itx_lr;
300                 lr->lr_foid = ZVOL_OBJ;
301                 lr->lr_offset = off;
302                 lr->lr_length = nbytes;
303                 lr->lr_blkoff = off - P2ALIGN_TYPED(off, blocksize, uint64_t);
304                 BP_ZERO(&lr->lr_blkptr);
305
306                 (void) zil_itx_assign(zv->zv_zilog, itx, tx);
307                 len -= nbytes;
308                 off += nbytes;
309         }
310 }
311
312 static void
313 zvol_start(struct bio *bp)
314 {
315         zvol_state_t *zv;
316
317         switch (bp->bio_cmd) {
318         case BIO_READ:
319         case BIO_WRITE:
320         case BIO_FLUSH:
321                 zv = bp->bio_to->private;
322                 ASSERT(zv != NULL);
323                 mtx_lock(&zv->zv_queue_mtx);
324                 bioq_insert_tail(&zv->zv_queue, bp);
325                 wakeup_one(&zv->zv_queue);
326                 mtx_unlock(&zv->zv_queue_mtx);
327                 break;
328         case BIO_GETATTR:
329                 if (g_handleattr_int(bp, "ZFS::iszvol", 1))
330                         break;
331                 /* FALLTHROUGH */
332         case BIO_DELETE:
333         default:
334                 g_io_deliver(bp, EOPNOTSUPP);
335                 break;
336         }
337 }
338
339 static void
340 zvol_serve_one(zvol_state_t *zv, struct bio *bp)
341 {
342         uint64_t off, volsize;
343         size_t resid;
344         char *addr;
345         objset_t *os;
346         rl_t *rl;
347         int error = 0;
348         boolean_t doread = (bp->bio_cmd == BIO_READ);
349
350         off = bp->bio_offset;
351         volsize = zv->zv_volsize;
352
353         os = zv->zv_objset;
354         ASSERT(os != NULL);
355
356         addr = bp->bio_data;
357         resid = bp->bio_length;
358
359         error = 0;
360
361         /*
362          * There must be no buffer changes when doing a dmu_sync() because
363          * we can't change the data whilst calculating the checksum.
364          * A better approach than a per zvol rwlock would be to lock ranges.
365          */
366         rl = zfs_range_lock(&zv->zv_znode, off, resid,
367             doread ? RL_READER : RL_WRITER);
368
369         while (resid != 0 && off < volsize) {
370                 size_t size = MIN(resid, zvol_maxphys); /* zvol_maxphys per tx */
371
372                 if (size > volsize - off)       /* don't write past the end */
373                         size = volsize - off;
374
375                 if (doread) {
376                         error = dmu_read(os, ZVOL_OBJ, off, size, addr);
377                 } else {
378                         dmu_tx_t *tx = dmu_tx_create(os);
379                         dmu_tx_hold_write(tx, ZVOL_OBJ, off, size);
380                         error = dmu_tx_assign(tx, TXG_WAIT);
381                         if (error) {
382                                 dmu_tx_abort(tx);
383                         } else {
384                                 dmu_write(os, ZVOL_OBJ, off, size, addr, tx);
385                                 zvol_log_write(zv, tx, off, size);
386                                 dmu_tx_commit(tx);
387                         }
388                 }
389                 if (error) {
390                         /* convert checksum errors into IO errors */
391                         if (error == ECKSUM)
392                                 error = EIO;
393                         break;
394                 }
395                 off += size;
396                 addr += size;
397                 resid -= size;
398         }
399         zfs_range_unlock(rl);
400
401         bp->bio_completed = bp->bio_length - resid;
402         if (bp->bio_completed < bp->bio_length)
403                 bp->bio_error = (off > volsize ? EINVAL : error);
404 }
405
406 static void
407 zvol_worker(void *arg)
408 {
409         zvol_state_t *zv;
410         struct bio *bp;
411
412         thread_lock(curthread);
413         sched_prio(curthread, PRIBIO);
414         thread_unlock(curthread);
415
416         zv = arg;
417         for (;;) {
418                 mtx_lock(&zv->zv_queue_mtx);
419                 bp = bioq_takefirst(&zv->zv_queue);
420                 if (bp == NULL) {
421                         if (zv->zv_state == 1) {
422                                 zv->zv_state = 2;
423                                 wakeup(&zv->zv_state);
424                                 mtx_unlock(&zv->zv_queue_mtx);
425                                 kthread_exit();
426                         }
427                         msleep(&zv->zv_queue, &zv->zv_queue_mtx, PRIBIO | PDROP,
428                             "zvol:io", 0);
429                         continue;
430                 }
431                 mtx_unlock(&zv->zv_queue_mtx);
432                 switch (bp->bio_cmd) {
433                 case BIO_FLUSH:
434                         break;
435                 case BIO_READ:
436                 case BIO_WRITE:
437                         zvol_serve_one(zv, bp);
438                         break;
439                 }
440
441                 if (bp->bio_cmd == BIO_FLUSH && !zil_disable)
442                         zil_commit(zv->zv_zilog, UINT64_MAX, ZVOL_OBJ);
443
444                 g_io_deliver(bp, bp->bio_error);
445         }
446 }
447
448 /* extent mapping arg */
449 struct maparg {
450         zvol_state_t    *ma_zv;
451         uint64_t        ma_blks;
452 };
453
454 /*ARGSUSED*/
455 static int
456 zvol_map_block(spa_t *spa, blkptr_t *bp, const zbookmark_t *zb,
457     const dnode_phys_t *dnp, void *arg)
458 {
459         struct maparg *ma = arg;
460         zvol_extent_t *ze;
461         int bs = ma->ma_zv->zv_volblocksize;
462
463         if (bp == NULL || zb->zb_object != ZVOL_OBJ || zb->zb_level != 0)
464                 return (0);
465
466         VERIFY3U(ma->ma_blks, ==, zb->zb_blkid);
467         ma->ma_blks++;
468
469         /* Abort immediately if we have encountered gang blocks */
470         if (BP_IS_GANG(bp))
471                 return (EFRAGS);
472
473         /*
474          * See if the block is at the end of the previous extent.
475          */
476         ze = list_tail(&ma->ma_zv->zv_extents);
477         if (ze &&
478             DVA_GET_VDEV(BP_IDENTITY(bp)) == DVA_GET_VDEV(&ze->ze_dva) &&
479             DVA_GET_OFFSET(BP_IDENTITY(bp)) ==
480             DVA_GET_OFFSET(&ze->ze_dva) + ze->ze_nblks * bs) {
481                 ze->ze_nblks++;
482                 return (0);
483         }
484
485         dprintf_bp(bp, "%s", "next blkptr:");
486
487         /* start a new extent */
488         ze = kmem_zalloc(sizeof (zvol_extent_t), KM_SLEEP);
489         ze->ze_dva = bp->blk_dva[0];    /* structure assignment */
490         ze->ze_nblks = 1;
491         list_insert_tail(&ma->ma_zv->zv_extents, ze);
492         return (0);
493 }
494
495 static void
496 zvol_free_extents(zvol_state_t *zv)
497 {
498         zvol_extent_t *ze;
499
500         while (ze = list_head(&zv->zv_extents)) {
501                 list_remove(&zv->zv_extents, ze);
502                 kmem_free(ze, sizeof (zvol_extent_t));
503         }
504 }
505
506 static int
507 zvol_get_lbas(zvol_state_t *zv)
508 {
509         struct maparg   ma;
510         int             err;
511
512         ma.ma_zv = zv;
513         ma.ma_blks = 0;
514         zvol_free_extents(zv);
515
516         err = traverse_dataset(dmu_objset_ds(zv->zv_objset), 0,
517             TRAVERSE_PRE | TRAVERSE_PREFETCH_METADATA, zvol_map_block, &ma);
518         if (err || ma.ma_blks != (zv->zv_volsize / zv->zv_volblocksize)) {
519                 zvol_free_extents(zv);
520                 return (err ? err : EIO);
521         }
522
523         return (0);
524 }
525
526 /* ARGSUSED */
527 void
528 zvol_create_cb(objset_t *os, void *arg, cred_t *cr, dmu_tx_t *tx)
529 {
530         zfs_creat_t *zct = arg;
531         nvlist_t *nvprops = zct->zct_props;
532         int error;
533         uint64_t volblocksize, volsize;
534
535         VERIFY(nvlist_lookup_uint64(nvprops,
536             zfs_prop_to_name(ZFS_PROP_VOLSIZE), &volsize) == 0);
537         if (nvlist_lookup_uint64(nvprops,
538             zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE), &volblocksize) != 0)
539                 volblocksize = zfs_prop_default_numeric(ZFS_PROP_VOLBLOCKSIZE);
540
541         /*
542          * These properties must be removed from the list so the generic
543          * property setting step won't apply to them.
544          */
545         VERIFY(nvlist_remove_all(nvprops,
546             zfs_prop_to_name(ZFS_PROP_VOLSIZE)) == 0);
547         (void) nvlist_remove_all(nvprops,
548             zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE));
549
550         error = dmu_object_claim(os, ZVOL_OBJ, DMU_OT_ZVOL, volblocksize,
551             DMU_OT_NONE, 0, tx);
552         ASSERT(error == 0);
553
554         error = zap_create_claim(os, ZVOL_ZAP_OBJ, DMU_OT_ZVOL_PROP,
555             DMU_OT_NONE, 0, tx);
556         ASSERT(error == 0);
557
558         error = zap_update(os, ZVOL_ZAP_OBJ, "size", 8, 1, &volsize, tx);
559         ASSERT(error == 0);
560 }
561
562 /*
563  * Replay a TX_WRITE ZIL transaction that didn't get committed
564  * after a system failure
565  */
566 static int
567 zvol_replay_write(zvol_state_t *zv, lr_write_t *lr, boolean_t byteswap)
568 {
569         objset_t *os = zv->zv_objset;
570         char *data = (char *)(lr + 1);  /* data follows lr_write_t */
571         uint64_t off = lr->lr_offset;
572         uint64_t len = lr->lr_length;
573         dmu_tx_t *tx;
574         int error;
575
576         if (byteswap)
577                 byteswap_uint64_array(lr, sizeof (*lr));
578
579         tx = dmu_tx_create(os);
580         dmu_tx_hold_write(tx, ZVOL_OBJ, off, len);
581         error = dmu_tx_assign(tx, zv->zv_txg_assign);
582         if (error) {
583                 dmu_tx_abort(tx);
584         } else {
585                 dmu_write(os, ZVOL_OBJ, off, len, data, tx);
586                 dmu_tx_commit(tx);
587         }
588
589         return (error);
590 }
591
592 /* ARGSUSED */
593 static int
594 zvol_replay_err(zvol_state_t *zv, lr_t *lr, boolean_t byteswap)
595 {
596         return (ENOTSUP);
597 }
598
599 /*
600  * Callback vectors for replaying records.
601  * Only TX_WRITE is needed for zvol.
602  */
603 zil_replay_func_t *zvol_replay_vector[TX_MAX_TYPE] = {
604         zvol_replay_err,        /* 0 no such transaction type */
605         zvol_replay_err,        /* TX_CREATE */
606         zvol_replay_err,        /* TX_MKDIR */
607         zvol_replay_err,        /* TX_MKXATTR */
608         zvol_replay_err,        /* TX_SYMLINK */
609         zvol_replay_err,        /* TX_REMOVE */
610         zvol_replay_err,        /* TX_RMDIR */
611         zvol_replay_err,        /* TX_LINK */
612         zvol_replay_err,        /* TX_RENAME */
613         zvol_replay_write,      /* TX_WRITE */
614         zvol_replay_err,        /* TX_TRUNCATE */
615         zvol_replay_err,        /* TX_SETATTR */
616         zvol_replay_err,        /* TX_ACL */
617 };
618
619 /*
620  * Create a minor node (plus a whole lot more) for the specified volume.
621  */
622 int
623 zvol_create_minor(const char *name, major_t maj)
624 {
625         struct g_provider *pp;
626         struct g_geom *gp;
627         zvol_state_t *zv;
628         objset_t *os;
629         dmu_object_info_t doi;
630         uint64_t volsize;
631         int ds_mode = DS_MODE_OWNER;
632         int error;
633
634         DROP_GIANT();
635         g_topology_lock();
636         mutex_enter(&zvol_state_lock);
637
638         if ((zv = zvol_minor_lookup(name)) != NULL) {
639                 error = EEXIST;
640                 goto end;
641         }
642
643         if (strchr(name, '@') != 0)
644                 ds_mode |= DS_MODE_READONLY;
645
646         error = dmu_objset_open(name, DMU_OST_ZVOL, ds_mode, &os);
647         if (error)
648                 goto end;
649
650         error = zap_lookup(os, ZVOL_ZAP_OBJ, "size", 8, 1, &volsize);
651         if (error) {
652                 dmu_objset_close(os);
653                 goto end;
654         }
655
656         gp = g_new_geomf(&zfs_zvol_class, "zfs::zvol::%s", name);
657         gp->start = zvol_start;
658         gp->access = zvol_access;
659         pp = g_new_providerf(gp, "%s/%s", ZVOL_DEV_DIR, name);
660         pp->mediasize = volsize;
661         pp->sectorsize = DEV_BSIZE;
662
663         zv = kmem_zalloc(sizeof(*zv), KM_SLEEP);
664         (void) strcpy(zv->zv_name, name);
665         zv->zv_min_bs = DEV_BSHIFT;
666         zv->zv_provider = pp;
667         zv->zv_volsize = pp->mediasize;
668         zv->zv_objset = os;
669         zv->zv_mode = ds_mode;
670         zv->zv_zilog = zil_open(os, zvol_get_data);
671         mutex_init(&zv->zv_znode.z_range_lock, NULL, MUTEX_DEFAULT, NULL);
672         avl_create(&zv->zv_znode.z_range_avl, zfs_range_compare,
673             sizeof (rl_t), offsetof(rl_t, r_node));
674         list_create(&zv->zv_extents, sizeof (zvol_extent_t),
675             offsetof(zvol_extent_t, ze_node));
676         /* get and cache the blocksize */
677         error = dmu_object_info(os, ZVOL_OBJ, &doi);
678         ASSERT(error == 0);
679         zv->zv_volblocksize = doi.doi_data_block_size;
680
681         zil_replay(os, zv, &zv->zv_txg_assign, zvol_replay_vector, NULL);
682
683         /* XXX this should handle the possible i/o error */
684         VERIFY(dsl_prop_register(dmu_objset_ds(zv->zv_objset),
685             "readonly", zvol_readonly_changed_cb, zv) == 0);
686
687         pp->private = zv;
688         g_error_provider(pp, 0);
689
690         bioq_init(&zv->zv_queue);
691         mtx_init(&zv->zv_queue_mtx, "zvol", NULL, MTX_DEF);
692         zv->zv_state = 0;
693         kproc_kthread_add(zvol_worker, zv, &zfsproc, NULL, 0, 0, "zfskern",
694             "zvol %s", pp->name + strlen(ZVOL_DEV_DIR) + 1);
695
696         zvol_minors++;
697 end:
698         mutex_exit(&zvol_state_lock);
699         g_topology_unlock();
700         PICKUP_GIANT();
701
702         return (error);
703 }
704
705 /*
706  * Remove minor node for the specified volume.
707  */
708 int
709 zvol_remove_minor(const char *name)
710 {
711         struct g_provider *pp;
712         zvol_state_t *zv;
713         int error = 0;
714
715         DROP_GIANT();
716         g_topology_lock();
717         mutex_enter(&zvol_state_lock);
718
719         if ((zv = zvol_minor_lookup(name)) == NULL) {
720                 error = ENXIO;
721                 goto end;
722         }
723
724         if (zv->zv_total_opens != 0) {
725                 error = EBUSY;
726                 goto end;
727         }
728
729         VERIFY(dsl_prop_unregister(dmu_objset_ds(zv->zv_objset),
730             "readonly", zvol_readonly_changed_cb, zv) == 0);
731
732         mtx_lock(&zv->zv_queue_mtx);
733         zv->zv_state = 1;
734         wakeup_one(&zv->zv_queue);
735         while (zv->zv_state != 2)
736                 msleep(&zv->zv_state, &zv->zv_queue_mtx, 0, "zvol:w", 0);
737         mtx_unlock(&zv->zv_queue_mtx);
738         mtx_destroy(&zv->zv_queue_mtx);
739
740         pp = zv->zv_provider;
741         pp->private = NULL;
742         g_wither_geom(pp->geom, ENXIO);
743
744         zil_close(zv->zv_zilog);
745         zv->zv_zilog = NULL;
746         dmu_objset_close(zv->zv_objset);
747         zv->zv_objset = NULL;
748         avl_destroy(&zv->zv_znode.z_range_avl);
749         mutex_destroy(&zv->zv_znode.z_range_lock);
750
751         kmem_free(zv, sizeof(*zv));
752
753         zvol_minors--;
754 end:
755         mutex_exit(&zvol_state_lock);
756         g_topology_unlock();
757         PICKUP_GIANT();
758
759         return (error);
760 }
761
762 int
763 zvol_prealloc(zvol_state_t *zv)
764 {
765         objset_t *os = zv->zv_objset;
766         dmu_tx_t *tx;
767         void *data;
768         uint64_t refd, avail, usedobjs, availobjs;
769         uint64_t resid = zv->zv_volsize;
770         uint64_t off = 0;
771
772         /* Check the space usage before attempting to allocate the space */
773         dmu_objset_space(os, &refd, &avail, &usedobjs, &availobjs);
774         if (avail < zv->zv_volsize)
775                 return (ENOSPC);
776
777         /* Free old extents if they exist */
778         zvol_free_extents(zv);
779
780         /* allocate the blocks by writing each one */
781         data = kmem_zalloc(SPA_MAXBLOCKSIZE, KM_SLEEP);
782
783         while (resid != 0) {
784                 int error;
785                 uint64_t bytes = MIN(resid, SPA_MAXBLOCKSIZE);
786
787                 tx = dmu_tx_create(os);
788                 dmu_tx_hold_write(tx, ZVOL_OBJ, off, bytes);
789                 error = dmu_tx_assign(tx, TXG_WAIT);
790                 if (error) {
791                         dmu_tx_abort(tx);
792                         kmem_free(data, SPA_MAXBLOCKSIZE);
793                         (void) dmu_free_long_range(os, ZVOL_OBJ, 0, off);
794                         return (error);
795                 }
796                 dmu_write(os, ZVOL_OBJ, off, bytes, data, tx);
797                 dmu_tx_commit(tx);
798                 off += bytes;
799                 resid -= bytes;
800         }
801         kmem_free(data, SPA_MAXBLOCKSIZE);
802         txg_wait_synced(dmu_objset_pool(os), 0);
803
804         return (0);
805 }
806
807 int
808 zvol_update_volsize(zvol_state_t *zv, major_t maj, uint64_t volsize)
809 {
810         dmu_tx_t *tx;
811         int error;
812
813         ASSERT(MUTEX_HELD(&zvol_state_lock));
814
815         tx = dmu_tx_create(zv->zv_objset);
816         dmu_tx_hold_zap(tx, ZVOL_ZAP_OBJ, TRUE, NULL);
817         error = dmu_tx_assign(tx, TXG_WAIT);
818         if (error) {
819                 dmu_tx_abort(tx);
820                 return (error);
821         }
822
823         error = zap_update(zv->zv_objset, ZVOL_ZAP_OBJ, "size", 8, 1,
824             &volsize, tx);
825         dmu_tx_commit(tx);
826
827         if (error == 0)
828                 error = dmu_free_long_range(zv->zv_objset,
829                     ZVOL_OBJ, volsize, DMU_OBJECT_END);
830
831         /*
832          * If we are using a faked-up state (zv_provider == NULL) then don't
833          * try to update the in-core zvol state.
834          */
835         if (error == 0 && zv->zv_provider) {
836                 zv->zv_volsize = volsize;
837                 zvol_size_changed(zv, maj);
838         }
839         return (error);
840 }
841
842 int
843 zvol_set_volsize(const char *name, major_t maj, uint64_t volsize)
844 {
845         zvol_state_t *zv;
846         int error;
847         dmu_object_info_t doi;
848         uint64_t old_volsize = 0ULL;
849         zvol_state_t state = { 0 };
850
851         DROP_GIANT();
852         g_topology_lock();
853         mutex_enter(&zvol_state_lock);
854
855         if ((zv = zvol_minor_lookup(name)) == NULL) {
856                 /*
857                  * If we are doing a "zfs clone -o volsize=", then the
858                  * minor node won't exist yet.
859                  */
860                 error = dmu_objset_open(name, DMU_OST_ZVOL, DS_MODE_OWNER,
861                     &state.zv_objset);
862                 if (error != 0)
863                         goto out;
864                 zv = &state;
865         }
866         old_volsize = zv->zv_volsize;
867
868         if ((error = dmu_object_info(zv->zv_objset, ZVOL_OBJ, &doi)) != 0 ||
869             (error = zvol_check_volsize(volsize,
870             doi.doi_data_block_size)) != 0)
871                 goto out;
872
873         if (zv->zv_flags & ZVOL_RDONLY || (zv->zv_mode & DS_MODE_READONLY)) {
874                 error = EROFS;
875                 goto out;
876         }
877
878         error = zvol_update_volsize(zv, maj, volsize);
879
880 #if 0
881         /*
882          * Reinitialize the dump area to the new size. If we
883          * failed to resize the dump area then restore the it back to
884          * it's original size.
885          */
886         if (error == 0 && zv->zv_flags & ZVOL_DUMPIFIED) {
887                 if ((error = zvol_dumpify(zv)) != 0 ||
888                     (error = dumpvp_resize()) != 0) {
889                         (void) zvol_update_volsize(zv, maj, old_volsize);
890                         error = zvol_dumpify(zv);
891                 }
892         }
893 #endif
894
895 out:
896         if (state.zv_objset)
897                 dmu_objset_close(state.zv_objset);
898
899         mutex_exit(&zvol_state_lock);
900         g_topology_unlock();
901         PICKUP_GIANT();
902
903         return (error);
904 }
905
906 int
907 zvol_set_volblocksize(const char *name, uint64_t volblocksize)
908 {
909         zvol_state_t *zv;
910         dmu_tx_t *tx;
911         int error;
912
913         DROP_GIANT();
914         g_topology_lock();
915         mutex_enter(&zvol_state_lock);
916
917         if ((zv = zvol_minor_lookup(name)) == NULL) {
918                 error = ENXIO;
919                 goto end;
920         }
921         if (zv->zv_flags & ZVOL_RDONLY || (zv->zv_mode & DS_MODE_READONLY)) {
922                 error = EROFS;
923                 goto end;
924         }
925
926         tx = dmu_tx_create(zv->zv_objset);
927         dmu_tx_hold_bonus(tx, ZVOL_OBJ);
928         error = dmu_tx_assign(tx, TXG_WAIT);
929         if (error) {
930                 dmu_tx_abort(tx);
931         } else {
932                 error = dmu_object_set_blocksize(zv->zv_objset, ZVOL_OBJ,
933                     volblocksize, 0, tx);
934                 if (error == ENOTSUP)
935                         error = EBUSY;
936                 dmu_tx_commit(tx);
937                 if (error == 0)
938                         zv->zv_volblocksize = volblocksize;
939         }
940 end:
941         mutex_exit(&zvol_state_lock);
942         g_topology_unlock();
943         PICKUP_GIANT();
944
945         return (error);
946 }
947
948 void
949 zvol_get_done(dmu_buf_t *db, void *vzgd)
950 {
951         zgd_t *zgd = (zgd_t *)vzgd;
952         rl_t *rl = zgd->zgd_rl;
953
954         dmu_buf_rele(db, vzgd);
955         zfs_range_unlock(rl);
956         zil_add_block(zgd->zgd_zilog, zgd->zgd_bp);
957         kmem_free(zgd, sizeof (zgd_t));
958 }
959
960 /*
961  * Get data to generate a TX_WRITE intent log record.
962  */
963 static int
964 zvol_get_data(void *arg, lr_write_t *lr, char *buf, zio_t *zio)
965 {
966         zvol_state_t *zv = arg;
967         objset_t *os = zv->zv_objset;
968         dmu_buf_t *db;
969         rl_t *rl;
970         zgd_t *zgd;
971         uint64_t boff;                  /* block starting offset */
972         int dlen = lr->lr_length;       /* length of user data */
973         int error;
974
975         ASSERT(zio);
976         ASSERT(dlen != 0);
977
978         /*
979          * Write records come in two flavors: immediate and indirect.
980          * For small writes it's cheaper to store the data with the
981          * log record (immediate); for large writes it's cheaper to
982          * sync the data and get a pointer to it (indirect) so that
983          * we don't have to write the data twice.
984          */
985         if (buf != NULL) /* immediate write */
986                 return (dmu_read(os, ZVOL_OBJ, lr->lr_offset, dlen, buf));
987
988         zgd = (zgd_t *)kmem_alloc(sizeof (zgd_t), KM_SLEEP);
989         zgd->zgd_zilog = zv->zv_zilog;
990         zgd->zgd_bp = &lr->lr_blkptr;
991
992         /*
993          * Lock the range of the block to ensure that when the data is
994          * written out and its checksum is being calculated that no other
995          * thread can change the block.
996          */
997         boff = P2ALIGN_TYPED(lr->lr_offset, zv->zv_volblocksize, uint64_t);
998         rl = zfs_range_lock(&zv->zv_znode, boff, zv->zv_volblocksize,
999             RL_READER);
1000         zgd->zgd_rl = rl;
1001
1002         VERIFY(0 == dmu_buf_hold(os, ZVOL_OBJ, lr->lr_offset, zgd, &db));
1003         error = dmu_sync(zio, db, &lr->lr_blkptr,
1004             lr->lr_common.lrc_txg, zvol_get_done, zgd);
1005         if (error == 0)
1006                 zil_add_block(zv->zv_zilog, &lr->lr_blkptr);
1007         /*
1008          * If we get EINPROGRESS, then we need to wait for a
1009          * write IO initiated by dmu_sync() to complete before
1010          * we can release this dbuf.  We will finish everything
1011          * up in the zvol_get_done() callback.
1012          */
1013         if (error == EINPROGRESS)
1014                 return (0);
1015         dmu_buf_rele(db, zgd);
1016         zfs_range_unlock(rl);
1017         kmem_free(zgd, sizeof (zgd_t));
1018         return (error);
1019 }
1020
1021 int
1022 zvol_busy(void)
1023 {
1024         return (zvol_minors != 0);
1025 }
1026
1027 void
1028 zvol_init(void)
1029 {
1030         mutex_init(&zvol_state_lock, NULL, MUTEX_DEFAULT, NULL);
1031         ZFS_LOG(1, "ZVOL Initialized.");
1032 }
1033
1034 void
1035 zvol_fini(void)
1036 {
1037         mutex_destroy(&zvol_state_lock);
1038         ZFS_LOG(1, "ZVOL Deinitialized.");
1039 }
1040
1041 static boolean_t
1042 zvol_is_swap(zvol_state_t *zv)
1043 {
1044         vnode_t *vp;
1045         boolean_t ret = B_FALSE;
1046         char *devpath;
1047         size_t devpathlen;
1048         int error;
1049
1050 #if 0
1051         devpathlen = strlen(ZVOL_FULL_DEV_DIR) + strlen(zv->zv_name) + 1;
1052         devpath = kmem_alloc(devpathlen, KM_SLEEP);
1053         (void) sprintf(devpath, "%s%s", ZVOL_FULL_DEV_DIR, zv->zv_name);
1054         error = lookupname(devpath, UIO_SYSSPACE, FOLLOW, NULLVPP, &vp);
1055         kmem_free(devpath, devpathlen);
1056
1057         ret = !error && IS_SWAPVP(common_specvp(vp));
1058
1059         if (vp != NULL)
1060                 VN_RELE(vp);
1061 #endif
1062
1063         return (ret);
1064 }
1065
1066 static int
1067 zvol_dump_init(zvol_state_t *zv, boolean_t resize)
1068 {
1069         dmu_tx_t *tx;
1070         int error = 0;
1071         objset_t *os = zv->zv_objset;
1072         nvlist_t *nv = NULL;
1073
1074         ASSERT(MUTEX_HELD(&zvol_state_lock));
1075
1076         tx = dmu_tx_create(os);
1077         dmu_tx_hold_zap(tx, ZVOL_ZAP_OBJ, TRUE, NULL);
1078         error = dmu_tx_assign(tx, TXG_WAIT);
1079         if (error) {
1080                 dmu_tx_abort(tx);
1081                 return (error);
1082         }
1083
1084         /*
1085          * If we are resizing the dump device then we only need to
1086          * update the refreservation to match the newly updated
1087          * zvolsize. Otherwise, we save off the original state of the
1088          * zvol so that we can restore them if the zvol is ever undumpified.
1089          */
1090         if (resize) {
1091                 error = zap_update(os, ZVOL_ZAP_OBJ,
1092                     zfs_prop_to_name(ZFS_PROP_REFRESERVATION), 8, 1,
1093                     &zv->zv_volsize, tx);
1094         } else {
1095                 uint64_t checksum, compress, refresrv, vbs;
1096
1097                 error = dsl_prop_get_integer(zv->zv_name,
1098                     zfs_prop_to_name(ZFS_PROP_COMPRESSION), &compress, NULL);
1099                 error = error ? error : dsl_prop_get_integer(zv->zv_name,
1100                     zfs_prop_to_name(ZFS_PROP_CHECKSUM), &checksum, NULL);
1101                 error = error ? error : dsl_prop_get_integer(zv->zv_name,
1102                     zfs_prop_to_name(ZFS_PROP_REFRESERVATION), &refresrv, NULL);
1103                 error = error ? error : dsl_prop_get_integer(zv->zv_name,
1104                     zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE), &vbs, NULL);
1105
1106                 error = error ? error : zap_update(os, ZVOL_ZAP_OBJ,
1107                     zfs_prop_to_name(ZFS_PROP_COMPRESSION), 8, 1,
1108                     &compress, tx);
1109                 error = error ? error : zap_update(os, ZVOL_ZAP_OBJ,
1110                     zfs_prop_to_name(ZFS_PROP_CHECKSUM), 8, 1, &checksum, tx);
1111                 error = error ? error : zap_update(os, ZVOL_ZAP_OBJ,
1112                     zfs_prop_to_name(ZFS_PROP_REFRESERVATION), 8, 1,
1113                     &refresrv, tx);
1114                 error = error ? error : zap_update(os, ZVOL_ZAP_OBJ,
1115                     zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE), 8, 1,
1116                     &vbs, tx);
1117         }
1118         dmu_tx_commit(tx);
1119
1120         /* Truncate the file */
1121         if (!error)
1122                 error = dmu_free_long_range(zv->zv_objset,
1123                     ZVOL_OBJ, 0, DMU_OBJECT_END);
1124
1125         if (error)
1126                 return (error);
1127
1128         /*
1129          * We only need update the zvol's property if we are initializing
1130          * the dump area for the first time.
1131          */
1132         if (!resize) {
1133                 VERIFY(nvlist_alloc(&nv, NV_UNIQUE_NAME, KM_SLEEP) == 0);
1134                 VERIFY(nvlist_add_uint64(nv,
1135                     zfs_prop_to_name(ZFS_PROP_REFRESERVATION), 0) == 0);
1136                 VERIFY(nvlist_add_uint64(nv,
1137                     zfs_prop_to_name(ZFS_PROP_COMPRESSION),
1138                     ZIO_COMPRESS_OFF) == 0);
1139                 VERIFY(nvlist_add_uint64(nv,
1140                     zfs_prop_to_name(ZFS_PROP_CHECKSUM),
1141                     ZIO_CHECKSUM_OFF) == 0);
1142                 VERIFY(nvlist_add_uint64(nv,
1143                     zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE),
1144                     SPA_MAXBLOCKSIZE) == 0);
1145
1146                 error = zfs_set_prop_nvlist(zv->zv_name, nv);
1147                 nvlist_free(nv);
1148
1149                 if (error)
1150                         return (error);
1151         }
1152
1153         /* Allocate the space for the dump */
1154         error = zvol_prealloc(zv);
1155         return (error);
1156 }
1157
1158 static int
1159 zvol_dumpify(zvol_state_t *zv)
1160 {
1161         int error = 0;
1162         uint64_t dumpsize = 0;
1163         dmu_tx_t *tx;
1164         objset_t *os = zv->zv_objset;
1165
1166         if (zv->zv_flags & ZVOL_RDONLY || (zv->zv_mode & DS_MODE_READONLY))
1167                 return (EROFS);
1168
1169         /*
1170          * We do not support swap devices acting as dump devices.
1171          */
1172         if (zvol_is_swap(zv))
1173                 return (ENOTSUP);
1174
1175         if (zap_lookup(zv->zv_objset, ZVOL_ZAP_OBJ, ZVOL_DUMPSIZE,
1176             8, 1, &dumpsize) != 0 || dumpsize != zv->zv_volsize) {
1177                 boolean_t resize = (dumpsize > 0) ? B_TRUE : B_FALSE;
1178
1179                 if ((error = zvol_dump_init(zv, resize)) != 0) {
1180                         (void) zvol_dump_fini(zv);
1181                         return (error);
1182                 }
1183         }
1184
1185         /*
1186          * Build up our lba mapping.
1187          */
1188         error = zvol_get_lbas(zv);
1189         if (error) {
1190                 (void) zvol_dump_fini(zv);
1191                 return (error);
1192         }
1193
1194         tx = dmu_tx_create(os);
1195         dmu_tx_hold_zap(tx, ZVOL_ZAP_OBJ, TRUE, NULL);
1196         error = dmu_tx_assign(tx, TXG_WAIT);
1197         if (error) {
1198                 dmu_tx_abort(tx);
1199                 (void) zvol_dump_fini(zv);
1200                 return (error);
1201         }
1202
1203         zv->zv_flags |= ZVOL_DUMPIFIED;
1204         error = zap_update(os, ZVOL_ZAP_OBJ, ZVOL_DUMPSIZE, 8, 1,
1205             &zv->zv_volsize, tx);
1206         dmu_tx_commit(tx);
1207
1208         if (error) {
1209                 (void) zvol_dump_fini(zv);
1210                 return (error);
1211         }
1212
1213         txg_wait_synced(dmu_objset_pool(os), 0);
1214         return (0);
1215 }
1216
1217 static int
1218 zvol_dump_fini(zvol_state_t *zv)
1219 {
1220         dmu_tx_t *tx;
1221         objset_t *os = zv->zv_objset;
1222         nvlist_t *nv;
1223         int error = 0;
1224         uint64_t checksum, compress, refresrv, vbs;
1225
1226         /*
1227          * Attempt to restore the zvol back to its pre-dumpified state.
1228          * This is a best-effort attempt as it's possible that not all
1229          * of these properties were initialized during the dumpify process
1230          * (i.e. error during zvol_dump_init).
1231          */
1232
1233         tx = dmu_tx_create(os);
1234         dmu_tx_hold_zap(tx, ZVOL_ZAP_OBJ, TRUE, NULL);
1235         error = dmu_tx_assign(tx, TXG_WAIT);
1236         if (error) {
1237                 dmu_tx_abort(tx);
1238                 return (error);
1239         }
1240         (void) zap_remove(os, ZVOL_ZAP_OBJ, ZVOL_DUMPSIZE, tx);
1241         dmu_tx_commit(tx);
1242
1243         (void) zap_lookup(zv->zv_objset, ZVOL_ZAP_OBJ,
1244             zfs_prop_to_name(ZFS_PROP_CHECKSUM), 8, 1, &checksum);
1245         (void) zap_lookup(zv->zv_objset, ZVOL_ZAP_OBJ,
1246             zfs_prop_to_name(ZFS_PROP_COMPRESSION), 8, 1, &compress);
1247         (void) zap_lookup(zv->zv_objset, ZVOL_ZAP_OBJ,
1248             zfs_prop_to_name(ZFS_PROP_REFRESERVATION), 8, 1, &refresrv);
1249         (void) zap_lookup(zv->zv_objset, ZVOL_ZAP_OBJ,
1250             zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE), 8, 1, &vbs);
1251
1252         VERIFY(nvlist_alloc(&nv, NV_UNIQUE_NAME, KM_SLEEP) == 0);
1253         (void) nvlist_add_uint64(nv,
1254             zfs_prop_to_name(ZFS_PROP_CHECKSUM), checksum);
1255         (void) nvlist_add_uint64(nv,
1256             zfs_prop_to_name(ZFS_PROP_COMPRESSION), compress);
1257         (void) nvlist_add_uint64(nv,
1258             zfs_prop_to_name(ZFS_PROP_REFRESERVATION), refresrv);
1259         (void) nvlist_add_uint64(nv,
1260             zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE), vbs);
1261         (void) zfs_set_prop_nvlist(zv->zv_name, nv);
1262         nvlist_free(nv);
1263
1264         zvol_free_extents(zv);
1265         zv->zv_flags &= ~ZVOL_DUMPIFIED;
1266         (void) dmu_free_long_range(os, ZVOL_OBJ, 0, DMU_OBJECT_END);
1267
1268         return (0);
1269 }