Add linux kernel disk support
[zfs.git] / module / 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) 2008-2010 Lawrence Livermore National Security, LLC.
23  * Produced at Lawrence Livermore National Laboratory (cf, DISCLAIMER).
24  * Rewritten for Linux by Brian Behlendorf <behlendorf1@llnl.gov>.
25  * LLNL-CODE-403049.
26  *
27  * ZFS volume emulation driver.
28  *
29  * Makes a DMU object look like a volume of arbitrary size, up to 2^64 bytes.
30  * Volumes are accessed through the symbolic links named:
31  *
32  * /dev/<pool_name>/<dataset_name>
33  *
34  * Volumes are persistent through reboot and module load.  No user command
35  * needs to be run before opening and using a device.
36  */
37
38 #include <sys/dmu_traverse.h>
39 #include <sys/dsl_dataset.h>
40 #include <sys/dsl_prop.h>
41 #include <sys/zap.h>
42 #include <sys/zil_impl.h>
43 #include <sys/zio.h>
44 #include <sys/zfs_rlock.h>
45 #include <sys/zfs_znode.h>
46 #include <sys/zvol.h>
47
48 unsigned int zvol_major = ZVOL_MAJOR;
49 unsigned int zvol_threads = 0;
50
51 static taskq_t *zvol_taskq;
52 static kmutex_t zvol_state_lock;
53 static list_t zvol_state_list;
54 static char *zvol_tag = "zvol_tag";
55
56 /*
57  * The in-core state of each volume.
58  */
59 typedef struct zvol_state {
60         char                    zv_name[DISK_NAME_LEN]; /* name */
61         uint64_t                zv_volsize;     /* advertised space */
62         uint64_t                zv_volblocksize;/* volume block size */
63         objset_t                *zv_objset;     /* objset handle */
64         uint32_t                zv_flags;       /* ZVOL_* flags */
65         uint32_t                zv_open_count;  /* open counts */
66         uint32_t                zv_changed;     /* disk changed */
67         zilog_t                 *zv_zilog;      /* ZIL handle */
68         znode_t                 zv_znode;       /* for range locking */
69         dmu_buf_t               *zv_dbuf;       /* bonus handle */
70         dev_t                   zv_dev;         /* device id */
71         struct gendisk          *zv_disk;       /* generic disk */
72         struct request_queue    *zv_queue;      /* request queue */
73         spinlock_t              zv_lock;        /* request queue lock */
74         list_node_t             zv_next;        /* next zvol_state_t linkage */
75 } zvol_state_t;
76
77 #define ZVOL_RDONLY     0x1
78
79 /*
80  * Find the next available range of ZVOL_MINORS minor numbers.  The
81  * zvol_state_list is kept in ascending minor order so we simply need
82  * to scan the list for the first gap in the sequence.  This allows us
83  * to recycle minor number as devices are created and removed.
84  */
85 static int
86 zvol_find_minor(unsigned *minor)
87 {
88         zvol_state_t *zv;
89
90         *minor = 0;
91         ASSERT(MUTEX_HELD(&zvol_state_lock));
92         for (zv = list_head(&zvol_state_list); zv != NULL;
93              zv = list_next(&zvol_state_list, zv), *minor += ZVOL_MINORS) {
94                 if (MINOR(zv->zv_dev) != MINOR(*minor))
95                         break;
96         }
97
98         /* All minors are in use */
99         if (*minor >= (1 << MINORBITS))
100                 return ENXIO;
101
102         return 0;
103 }
104
105 /*
106  * Find a zvol_state_t given the full major+minor dev_t.
107  */
108 static zvol_state_t *
109 zvol_find_by_dev(dev_t dev)
110 {
111         zvol_state_t *zv;
112
113         ASSERT(MUTEX_HELD(&zvol_state_lock));
114         for (zv = list_head(&zvol_state_list); zv != NULL;
115              zv = list_next(&zvol_state_list, zv)) {
116                 if (zv->zv_dev == dev)
117                         return zv;
118         }
119
120         return NULL;
121 }
122
123 /*
124  * Find a zvol_state_t given the name provided at zvol_alloc() time.
125  */
126 static zvol_state_t *
127 zvol_find_by_name(const char *name)
128 {
129         zvol_state_t *zv;
130
131         ASSERT(MUTEX_HELD(&zvol_state_lock));
132         for (zv = list_head(&zvol_state_list); zv != NULL;
133              zv = list_next(&zvol_state_list, zv)) {
134                 if (!strncmp(zv->zv_name, name, DISK_NAME_LEN))
135                         return zv;
136         }
137
138         return NULL;
139 }
140
141 /*
142  * ZFS_IOC_CREATE callback handles dmu zvol and zap object creation.
143  */
144 void
145 zvol_create_cb(objset_t *os, void *arg, cred_t *cr, dmu_tx_t *tx)
146 {
147         zfs_creat_t *zct = arg;
148         nvlist_t *nvprops = zct->zct_props;
149         int error;
150         uint64_t volblocksize, volsize;
151
152         VERIFY(nvlist_lookup_uint64(nvprops,
153             zfs_prop_to_name(ZFS_PROP_VOLSIZE), &volsize) == 0);
154         if (nvlist_lookup_uint64(nvprops,
155             zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE), &volblocksize) != 0)
156                 volblocksize = zfs_prop_default_numeric(ZFS_PROP_VOLBLOCKSIZE);
157
158         /*
159          * These properties must be removed from the list so the generic
160          * property setting step won't apply to them.
161          */
162         VERIFY(nvlist_remove_all(nvprops,
163             zfs_prop_to_name(ZFS_PROP_VOLSIZE)) == 0);
164         (void) nvlist_remove_all(nvprops,
165             zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE));
166
167         error = dmu_object_claim(os, ZVOL_OBJ, DMU_OT_ZVOL, volblocksize,
168             DMU_OT_NONE, 0, tx);
169         ASSERT(error == 0);
170
171         error = zap_create_claim(os, ZVOL_ZAP_OBJ, DMU_OT_ZVOL_PROP,
172             DMU_OT_NONE, 0, tx);
173         ASSERT(error == 0);
174
175         error = zap_update(os, ZVOL_ZAP_OBJ, "size", 8, 1, &volsize, tx);
176         ASSERT(error == 0);
177 }
178
179 /*
180  * ZFS_IOC_OBJSET_STATS entry point.
181  */
182 int
183 zvol_get_stats(objset_t *os, nvlist_t *nv)
184 {
185         int error;
186         dmu_object_info_t *doi;
187         uint64_t val;
188
189         error = zap_lookup(os, ZVOL_ZAP_OBJ, "size", 8, 1, &val);
190         if (error)
191                 return (error);
192
193         dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_VOLSIZE, val);
194         doi = kmem_alloc(sizeof(dmu_object_info_t), KM_SLEEP);
195         error = dmu_object_info(os, ZVOL_OBJ, doi);
196
197         if (error == 0) {
198                 dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_VOLBLOCKSIZE,
199                     doi->doi_data_block_size);
200         }
201
202         kmem_free(doi, sizeof(dmu_object_info_t));
203
204         return (error);
205 }
206
207 /*
208  * Sanity check volume size.
209  */
210 int
211 zvol_check_volsize(uint64_t volsize, uint64_t blocksize)
212 {
213         if (volsize == 0)
214                 return (EINVAL);
215
216         if (volsize % blocksize != 0)
217                 return (EINVAL);
218
219 #ifdef _ILP32
220         if (volsize - 1 > MAXOFFSET_T)
221                 return (EOVERFLOW);
222 #endif
223         return (0);
224 }
225
226 /*
227  * Ensure the zap is flushed then inform the VFS of the capacity change.
228  */
229 static int
230 zvol_update_volsize(zvol_state_t *zv, uint64_t volsize)
231 {
232         struct block_device *bdev;
233         dmu_tx_t *tx;
234         int error;
235
236         ASSERT(MUTEX_HELD(&zvol_state_lock));
237
238         tx = dmu_tx_create(zv->zv_objset);
239         dmu_tx_hold_zap(tx, ZVOL_ZAP_OBJ, TRUE, NULL);
240         error = dmu_tx_assign(tx, TXG_WAIT);
241         if (error) {
242                 dmu_tx_abort(tx);
243                 return (error);
244         }
245
246         error = zap_update(zv->zv_objset, ZVOL_ZAP_OBJ, "size", 8, 1,
247             &volsize, tx);
248         dmu_tx_commit(tx);
249
250         if (error)
251                 return (error);
252
253         error = dmu_free_long_range(zv->zv_objset,
254             ZVOL_OBJ, volsize, DMU_OBJECT_END);
255         if (error)
256                 return (error);
257
258         zv->zv_volsize = volsize;
259         zv->zv_changed = 1;
260
261         bdev = bdget_disk(zv->zv_disk, 0);
262         if (!bdev)
263                 return EIO;
264
265         error = check_disk_change(bdev);
266         ASSERT3U(error, !=, 0);
267         bdput(bdev);
268
269         return (0);
270 }
271
272 /*
273  * Set ZFS_PROP_VOLSIZE set entry point.
274  */
275 int
276 zvol_set_volsize(const char *name, uint64_t volsize)
277 {
278         zvol_state_t *zv;
279         dmu_object_info_t *doi;
280         objset_t *os = NULL;
281         uint64_t readonly;
282         int error;
283
284         mutex_enter(&zvol_state_lock);
285
286         zv = zvol_find_by_name(name);
287         if (zv == NULL) {
288                 error = ENXIO;
289                 goto out;
290         }
291
292         doi = kmem_alloc(sizeof(dmu_object_info_t), KM_SLEEP);
293
294         error = dmu_objset_hold(name, FTAG, &os);
295         if (error)
296                 goto out_doi;
297
298         if ((error = dmu_object_info(os, ZVOL_OBJ, doi)) != 0 ||
299             (error = zvol_check_volsize(volsize,doi->doi_data_block_size)) != 0)
300                 goto out_doi;
301
302         VERIFY(dsl_prop_get_integer(name, "readonly", &readonly, NULL) == 0);
303         if (readonly) {
304                 error = EROFS;
305                 goto out_doi;
306         }
307
308         if (get_disk_ro(zv->zv_disk) || (zv->zv_flags & ZVOL_RDONLY)) {
309                 error = EROFS;
310                 goto out_doi;
311         }
312
313         error = zvol_update_volsize(zv, volsize);
314 out_doi:
315         kmem_free(doi, sizeof(dmu_object_info_t));
316 out:
317         if (os)
318                 dmu_objset_rele(os, FTAG);
319
320         mutex_exit(&zvol_state_lock);
321
322         return (error);
323 }
324
325 /*
326  * Sanity check volume block size.
327  */
328 int
329 zvol_check_volblocksize(uint64_t volblocksize)
330 {
331         if (volblocksize < SPA_MINBLOCKSIZE ||
332             volblocksize > SPA_MAXBLOCKSIZE ||
333             !ISP2(volblocksize))
334                 return (EDOM);
335
336         return (0);
337 }
338
339 /*
340  * Set ZFS_PROP_VOLBLOCKSIZE set entry point.
341  */
342 int
343 zvol_set_volblocksize(const char *name, uint64_t volblocksize)
344 {
345         zvol_state_t *zv;
346         dmu_tx_t *tx;
347         int error;
348
349         mutex_enter(&zvol_state_lock);
350
351         zv = zvol_find_by_name(name);
352         if (zv == NULL) {
353                 error = ENXIO;
354                 goto out;
355         }
356
357         if (get_disk_ro(zv->zv_disk) || (zv->zv_flags & ZVOL_RDONLY)) {
358                 error = EROFS;
359                 goto out;
360         }
361
362         tx = dmu_tx_create(zv->zv_objset);
363         dmu_tx_hold_bonus(tx, ZVOL_OBJ);
364         error = dmu_tx_assign(tx, TXG_WAIT);
365         if (error) {
366                 dmu_tx_abort(tx);
367         } else {
368                 error = dmu_object_set_blocksize(zv->zv_objset, ZVOL_OBJ,
369                     volblocksize, 0, tx);
370                 if (error == ENOTSUP)
371                         error = EBUSY;
372                 dmu_tx_commit(tx);
373                 if (error == 0)
374                         zv->zv_volblocksize = volblocksize;
375         }
376 out:
377         mutex_exit(&zvol_state_lock);
378
379         return (error);
380 }
381
382 /*
383  * Replay a TX_WRITE ZIL transaction that didn't get committed
384  * after a system failure
385  */
386 static int
387 zvol_replay_write(zvol_state_t *zv, lr_write_t *lr, boolean_t byteswap)
388 {
389         objset_t *os = zv->zv_objset;
390         char *data = (char *)(lr + 1);  /* data follows lr_write_t */
391         uint64_t off = lr->lr_offset;
392         uint64_t len = lr->lr_length;
393         dmu_tx_t *tx;
394         int error;
395
396         if (byteswap)
397                 byteswap_uint64_array(lr, sizeof (*lr));
398
399         tx = dmu_tx_create(os);
400         dmu_tx_hold_write(tx, ZVOL_OBJ, off, len);
401         error = dmu_tx_assign(tx, TXG_WAIT);
402         if (error) {
403                 dmu_tx_abort(tx);
404         } else {
405                 dmu_write(os, ZVOL_OBJ, off, len, data, tx);
406                 dmu_tx_commit(tx);
407         }
408
409         return (error);
410 }
411
412 static int
413 zvol_replay_err(zvol_state_t *zv, lr_t *lr, boolean_t byteswap)
414 {
415         return (ENOTSUP);
416 }
417
418 /*
419  * Callback vectors for replaying records.
420  * Only TX_WRITE is needed for zvol.
421  */
422 zil_replay_func_t *zvol_replay_vector[TX_MAX_TYPE] = {
423         (zil_replay_func_t *)zvol_replay_err,   /* no such transaction type */
424         (zil_replay_func_t *)zvol_replay_err,   /* TX_CREATE */
425         (zil_replay_func_t *)zvol_replay_err,   /* TX_MKDIR */
426         (zil_replay_func_t *)zvol_replay_err,   /* TX_MKXATTR */
427         (zil_replay_func_t *)zvol_replay_err,   /* TX_SYMLINK */
428         (zil_replay_func_t *)zvol_replay_err,   /* TX_REMOVE */
429         (zil_replay_func_t *)zvol_replay_err,   /* TX_RMDIR */
430         (zil_replay_func_t *)zvol_replay_err,   /* TX_LINK */
431         (zil_replay_func_t *)zvol_replay_err,   /* TX_RENAME */
432         (zil_replay_func_t *)zvol_replay_write, /* TX_WRITE */
433         (zil_replay_func_t *)zvol_replay_err,   /* TX_TRUNCATE */
434         (zil_replay_func_t *)zvol_replay_err,   /* TX_SETATTR */
435         (zil_replay_func_t *)zvol_replay_err,   /* TX_ACL */
436 };
437
438 /*
439  * zvol_log_write() handles synchronous writes using TX_WRITE ZIL transactions.
440  *
441  * We store data in the log buffers if it's small enough.
442  * Otherwise we will later flush the data out via dmu_sync().
443  */
444 ssize_t zvol_immediate_write_sz = 32768;
445
446 static void
447 zvol_log_write(zvol_state_t *zv, dmu_tx_t *tx,
448                uint64_t offset, uint64_t size, int sync)
449 {
450         uint32_t blocksize = zv->zv_volblocksize;
451         zilog_t *zilog = zv->zv_zilog;
452         boolean_t slogging;
453
454         if (zil_replaying(zilog, tx))
455                 return;
456
457         slogging = spa_has_slogs(zilog->zl_spa);
458
459         while (size) {
460                 itx_t *itx;
461                 lr_write_t *lr;
462                 ssize_t len;
463                 itx_wr_state_t write_state;
464
465                 /*
466                  * Unlike zfs_log_write() we can be called with
467                  * up to DMU_MAX_ACCESS/2 (5MB) writes.
468                  */
469                 if (blocksize > zvol_immediate_write_sz && !slogging &&
470                     size >= blocksize && offset % blocksize == 0) {
471                         write_state = WR_INDIRECT; /* uses dmu_sync */
472                         len = blocksize;
473                 } else if (sync) {
474                         write_state = WR_COPIED;
475                         len = MIN(ZIL_MAX_LOG_DATA, size);
476                 } else {
477                         write_state = WR_NEED_COPY;
478                         len = MIN(ZIL_MAX_LOG_DATA, size);
479                 }
480
481                 itx = zil_itx_create(TX_WRITE, sizeof (*lr) +
482                     (write_state == WR_COPIED ? len : 0));
483                 lr = (lr_write_t *)&itx->itx_lr;
484                 if (write_state == WR_COPIED && dmu_read(zv->zv_objset,
485                     ZVOL_OBJ, offset, len, lr+1, DMU_READ_NO_PREFETCH) != 0) {
486                         zil_itx_destroy(itx);
487                         itx = zil_itx_create(TX_WRITE, sizeof (*lr));
488                         lr = (lr_write_t *)&itx->itx_lr;
489                         write_state = WR_NEED_COPY;
490                 }
491
492                 itx->itx_wr_state = write_state;
493                 if (write_state == WR_NEED_COPY)
494                         itx->itx_sod += len;
495                 lr->lr_foid = ZVOL_OBJ;
496                 lr->lr_offset = offset;
497                 lr->lr_length = len;
498                 lr->lr_blkoff = 0;
499                 BP_ZERO(&lr->lr_blkptr);
500
501                 itx->itx_private = zv;
502                 itx->itx_sync = sync;
503
504                 (void) zil_itx_assign(zilog, itx, tx);
505
506                 offset += len;
507                 size -= len;
508         }
509 }
510
511 /*
512  * Common write path running under the zvol taskq context.  This function
513  * is responsible for copying the request structure data in to the DMU and
514  * signaling the request queue with the result of the copy.
515  */
516 static void
517 zvol_write(void *arg)
518 {
519         struct request *req = (struct request *)arg;
520         struct request_queue *q = req->q;
521         zvol_state_t *zv = q->queuedata;
522         uint64_t offset = blk_rq_pos(req) << 9;
523         uint64_t size = blk_rq_bytes(req);
524         int error = 0;
525         dmu_tx_t *tx;
526         rl_t *rl;
527
528         rl = zfs_range_lock(&zv->zv_znode, offset, size, RL_WRITER);
529
530         tx = dmu_tx_create(zv->zv_objset);
531         dmu_tx_hold_write(tx, ZVOL_OBJ, offset, size);
532
533         /* This will only fail for ENOSPC */
534         error = dmu_tx_assign(tx, TXG_WAIT);
535         if (error) {
536                 dmu_tx_abort(tx);
537                 zfs_range_unlock(rl);
538                 blk_end_request(req, -error, size);
539                 return;
540         }
541
542         error = dmu_write_req(zv->zv_objset, ZVOL_OBJ, req, tx);
543         if (error == 0)
544                 zvol_log_write(zv, tx, offset, size, rq_is_sync(req));
545
546         dmu_tx_commit(tx);
547         zfs_range_unlock(rl);
548
549         if (rq_is_sync(req))
550                 zil_commit(zv->zv_zilog, ZVOL_OBJ);
551
552         blk_end_request(req, -error, size);
553 }
554
555 /*
556  * Common read path running under the zvol taskq context.  This function
557  * is responsible for copying the requested data out of the DMU and in to
558  * a linux request structure.  It then must signal the request queue with
559  * an error code describing the result of the copy.
560  */
561 static void
562 zvol_read(void *arg)
563 {
564         struct request *req = (struct request *)arg;
565         struct request_queue *q = req->q;
566         zvol_state_t *zv = q->queuedata;
567         uint64_t offset = blk_rq_pos(req) << 9;
568         uint64_t size = blk_rq_bytes(req);
569         int error;
570         rl_t *rl;
571
572         rl = zfs_range_lock(&zv->zv_znode, offset, size, RL_READER);
573
574         error = dmu_read_req(zv->zv_objset, ZVOL_OBJ, req);
575
576         zfs_range_unlock(rl);
577
578         /* convert checksum errors into IO errors */
579         if (error == ECKSUM)
580                 error = EIO;
581
582         blk_end_request(req, -error, size);
583 }
584
585 /*
586  * Request will be added back to the request queue and retried if
587  * it cannot be immediately dispatched to the taskq for handling
588  */
589 static inline void
590 zvol_dispatch(task_func_t func, struct request *req)
591 {
592         if (!taskq_dispatch(zvol_taskq, func, (void *)req, TQ_NOSLEEP))
593                 blk_requeue_request(req->q, req);
594 }
595
596 /*
597  * Common request path.  Rather than registering a custom make_request()
598  * function we use the generic Linux version.  This is done because it allows
599  * us to easily merge read requests which would otherwise we performed
600  * synchronously by the DMU.  This is less critical in write case where the
601  * DMU will perform the correct merging within a transaction group.  Using
602  * the generic make_request() also let's use leverage the fact that the
603  * elevator with ensure correct ordering in regards to barrior IOs.  On
604  * the downside it means that in the write case we end up doing request
605  * merging twice once in the elevator and once in the DMU.
606  *
607  * The request handler is called under a spin lock so all the real work
608  * is handed off to be done in the context of the zvol taskq.  This function
609  * simply performs basic request sanity checking and hands off the request.
610  */
611 static void
612 zvol_request(struct request_queue *q)
613 {
614         zvol_state_t *zv = q->queuedata;
615         struct request *req;
616         unsigned int size;
617
618         while ((req = blk_fetch_request(q)) != NULL) {
619                 size = blk_rq_bytes(req);
620
621                 if (blk_rq_pos(req) + blk_rq_sectors(req) >
622                     get_capacity(zv->zv_disk)) {
623                         printk(KERN_INFO
624                                "%s: bad access: block=%llu, count=%lu\n",
625                                req->rq_disk->disk_name,
626                                (long long unsigned)blk_rq_pos(req),
627                                (long unsigned)blk_rq_sectors(req));
628                         __blk_end_request(req, -EIO, size);
629                         continue;
630                 }
631
632                 if (!blk_fs_request(req)) {
633                         printk(KERN_INFO "%s: non-fs cmd\n",
634                                req->rq_disk->disk_name);
635                         __blk_end_request(req, -EIO, size);
636                         continue;
637                 }
638
639                 switch (rq_data_dir(req)) {
640                 case READ:
641                         zvol_dispatch(zvol_read, req);
642                         break;
643                 case WRITE:
644                         if (unlikely(get_disk_ro(zv->zv_disk)) ||
645                             unlikely(zv->zv_flags & ZVOL_RDONLY)) {
646                                 __blk_end_request(req, -EROFS, size);
647                                 break;
648                         }
649
650                         zvol_dispatch(zvol_write, req);
651                         break;
652                 default:
653                         printk(KERN_INFO "%s: unknown cmd: %d\n",
654                                req->rq_disk->disk_name, (int)rq_data_dir(req));
655                         __blk_end_request(req, -EIO, size);
656                         break;
657                 }
658         }
659 }
660
661 static void
662 zvol_get_done(zgd_t *zgd, int error)
663 {
664         if (zgd->zgd_db)
665                 dmu_buf_rele(zgd->zgd_db, zgd);
666
667         zfs_range_unlock(zgd->zgd_rl);
668
669         if (error == 0 && zgd->zgd_bp)
670                 zil_add_block(zgd->zgd_zilog, zgd->zgd_bp);
671
672         kmem_free(zgd, sizeof (zgd_t));
673 }
674
675 /*
676  * Get data to generate a TX_WRITE intent log record.
677  */
678 static int
679 zvol_get_data(void *arg, lr_write_t *lr, char *buf, zio_t *zio)
680 {
681         zvol_state_t *zv = arg;
682         objset_t *os = zv->zv_objset;
683         uint64_t offset = lr->lr_offset;
684         uint64_t size = lr->lr_length;
685         dmu_buf_t *db;
686         zgd_t *zgd;
687         int error;
688
689         ASSERT(zio != NULL);
690         ASSERT(size != 0);
691
692         zgd = (zgd_t *)kmem_zalloc(sizeof (zgd_t), KM_SLEEP);
693         zgd->zgd_zilog = zv->zv_zilog;
694         zgd->zgd_rl = zfs_range_lock(&zv->zv_znode, offset, size, RL_READER);
695
696         /*
697          * Write records come in two flavors: immediate and indirect.
698          * For small writes it's cheaper to store the data with the
699          * log record (immediate); for large writes it's cheaper to
700          * sync the data and get a pointer to it (indirect) so that
701          * we don't have to write the data twice.
702          */
703         if (buf != NULL) { /* immediate write */
704                 error = dmu_read(os, ZVOL_OBJ, offset, size, buf,
705                     DMU_READ_NO_PREFETCH);
706         } else {
707                 size = zv->zv_volblocksize;
708                 offset = P2ALIGN_TYPED(offset, size, uint64_t);
709                 error = dmu_buf_hold(os, ZVOL_OBJ, offset, zgd, &db,
710                     DMU_READ_NO_PREFETCH);
711                 if (error == 0) {
712                         zgd->zgd_db = db;
713                         zgd->zgd_bp = &lr->lr_blkptr;
714
715                         ASSERT(db != NULL);
716                         ASSERT(db->db_offset == offset);
717                         ASSERT(db->db_size == size);
718
719                         error = dmu_sync(zio, lr->lr_common.lrc_txg,
720                             zvol_get_done, zgd);
721
722                         if (error == 0)
723                                 return (0);
724                 }
725         }
726
727         zvol_get_done(zgd, error);
728
729         return (error);
730 }
731
732 /*
733  * The zvol_state_t's are inserted in increasing MINOR(dev_t) order.
734  */
735 static void
736 zvol_insert(zvol_state_t *zv_insert)
737 {
738         zvol_state_t *zv = NULL;
739
740         ASSERT(MUTEX_HELD(&zvol_state_lock));
741         ASSERT3U(MINOR(zv_insert->zv_dev) & ZVOL_MINOR_MASK, ==, 0);
742         for (zv = list_head(&zvol_state_list); zv != NULL;
743              zv = list_next(&zvol_state_list, zv)) {
744                 if (MINOR(zv->zv_dev) > MINOR(zv_insert->zv_dev))
745                         break;
746         }
747
748         list_insert_before(&zvol_state_list, zv, zv_insert);
749 }
750
751 /*
752  * Simply remove the zvol from to list of zvols.
753  */
754 static void
755 zvol_remove(zvol_state_t *zv_remove)
756 {
757         ASSERT(MUTEX_HELD(&zvol_state_lock));
758         list_remove(&zvol_state_list, zv_remove);
759 }
760
761 static int
762 zvol_first_open(zvol_state_t *zv)
763 {
764         objset_t *os;
765         uint64_t volsize;
766         int error;
767         uint64_t ro;
768
769         /* lie and say we're read-only */
770         error = dmu_objset_own(zv->zv_name, DMU_OST_ZVOL, 1, zvol_tag, &os);
771         if (error)
772                 return (-error);
773
774         error = zap_lookup(os, ZVOL_ZAP_OBJ, "size", 8, 1, &volsize);
775         if (error) {
776                 dmu_objset_disown(os, zvol_tag);
777                 return (-error);
778         }
779
780         zv->zv_objset = os;
781         error = dmu_bonus_hold(os, ZVOL_OBJ, zvol_tag, &zv->zv_dbuf);
782         if (error) {
783                 dmu_objset_disown(os, zvol_tag);
784                 return (-error);
785         }
786
787         set_capacity(zv->zv_disk, volsize >> 9);
788         zv->zv_volsize = volsize;
789         zv->zv_zilog = zil_open(os, zvol_get_data);
790
791         VERIFY(dsl_prop_get_integer(zv->zv_name, "readonly", &ro, NULL) == 0);
792         if (ro || dmu_objset_is_snapshot(os)) {
793                 set_disk_ro(zv->zv_disk, 1);
794                 zv->zv_flags |= ZVOL_RDONLY;
795         } else {
796                 set_disk_ro(zv->zv_disk, 0);
797                 zv->zv_flags &= ~ZVOL_RDONLY;
798         }
799
800         return (-error);
801 }
802
803 static void
804 zvol_last_close(zvol_state_t *zv)
805 {
806         zil_close(zv->zv_zilog);
807         zv->zv_zilog = NULL;
808         dmu_buf_rele(zv->zv_dbuf, zvol_tag);
809         zv->zv_dbuf = NULL;
810         dmu_objset_disown(zv->zv_objset, zvol_tag);
811         zv->zv_objset = NULL;
812 }
813
814 static int
815 zvol_open(struct block_device *bdev, fmode_t flag)
816 {
817         zvol_state_t *zv = bdev->bd_disk->private_data;
818         int error = 0, drop_mutex = 0;
819
820         /*
821          * If the caller is already holding the mutex do not take it
822          * again, this will happen as part of zvol_create_minor().
823          * Once add_disk() is called the device is live and the kernel
824          * will attempt to open it to read the partition information.
825          */
826         if (!mutex_owned(&zvol_state_lock)) {
827                 mutex_enter(&zvol_state_lock);
828                 drop_mutex = 1;
829         }
830
831         ASSERT3P(zv, !=, NULL);
832
833         if (zv->zv_open_count == 0) {
834                 error = zvol_first_open(zv);
835                 if (error)
836                         goto out_mutex;
837         }
838
839         if ((flag & FMODE_WRITE) &&
840             (get_disk_ro(zv->zv_disk) || (zv->zv_flags & ZVOL_RDONLY))) {
841                 error = -EROFS;
842                 goto out_open_count;
843         }
844
845         zv->zv_open_count++;
846
847 out_open_count:
848         if (zv->zv_open_count == 0)
849                 zvol_last_close(zv);
850
851 out_mutex:
852         if (drop_mutex)
853                 mutex_exit(&zvol_state_lock);
854
855         check_disk_change(bdev);
856
857         return (error);
858 }
859
860 static int
861 zvol_release(struct gendisk *disk, fmode_t mode)
862 {
863         zvol_state_t *zv = disk->private_data;
864         int drop_mutex = 0;
865
866         if (!mutex_owned(&zvol_state_lock)) {
867                 mutex_enter(&zvol_state_lock);
868                 drop_mutex = 1;
869         }
870
871         ASSERT3P(zv, !=, NULL);
872         ASSERT3U(zv->zv_open_count, >, 0);
873         zv->zv_open_count--;
874         if (zv->zv_open_count == 0)
875                 zvol_last_close(zv);
876
877         if (drop_mutex)
878                 mutex_exit(&zvol_state_lock);
879
880         return (0);
881 }
882
883 static int
884 zvol_ioctl(struct block_device *bdev, fmode_t mode,
885            unsigned int cmd, unsigned long arg)
886 {
887         zvol_state_t *zv = bdev->bd_disk->private_data;
888         int error = 0;
889
890         if (zv == NULL)
891                 return (-ENXIO);
892
893         switch (cmd) {
894         case BLKFLSBUF:
895                 zil_commit(zv->zv_zilog, ZVOL_OBJ);
896                 break;
897
898         default:
899                 error = -ENOTTY;
900                 break;
901
902         }
903
904         return (error);
905 }
906
907 #ifdef CONFIG_COMPAT
908 static int
909 zvol_compat_ioctl(struct block_device *bdev, fmode_t mode,
910                   unsigned cmd, unsigned long arg)
911 {
912         return zvol_ioctl(bdev, mode, cmd, arg);
913 }
914 #else
915 #define zvol_compat_ioctl   NULL
916 #endif
917
918 static int zvol_media_changed(struct gendisk *disk)
919 {
920         zvol_state_t *zv = disk->private_data;
921
922         return zv->zv_changed;
923 }
924
925 static int zvol_revalidate_disk(struct gendisk *disk)
926 {
927         zvol_state_t *zv = disk->private_data;
928
929         zv->zv_changed = 0;
930         set_capacity(zv->zv_disk, zv->zv_volsize >> 9);
931
932         return 0;
933 }
934
935 /*
936  * Provide a simple virtual geometry for legacy compatibility.  For devices
937  * smaller than 1 MiB a small head and sector count is used to allow very
938  * tiny devices.  For devices over 1 Mib a standard head and sector count
939  * is used to keep the cylinders count reasonable.
940  */
941 static int
942 zvol_getgeo(struct block_device *bdev, struct hd_geometry *geo)
943 {
944         zvol_state_t *zv = bdev->bd_disk->private_data;
945         sector_t sectors = get_capacity(zv->zv_disk);
946
947         if (sectors > 2048) {
948                 geo->heads = 16;
949                 geo->sectors = 63;
950         } else {
951                 geo->heads = 2;
952                 geo->sectors = 4;
953         }
954
955         geo->start = 0;
956         geo->cylinders = sectors / (geo->heads * geo->sectors);
957
958         return 0;
959 }
960
961 static struct kobject *
962 zvol_probe(dev_t dev, int *part, void *arg)
963 {
964         zvol_state_t *zv;
965         struct kobject *kobj;
966
967         mutex_enter(&zvol_state_lock);
968         zv = zvol_find_by_dev(dev);
969         kobj = zv ? get_disk(zv->zv_disk) : ERR_PTR(-ENOENT);
970         mutex_exit(&zvol_state_lock);
971
972         return kobj;
973 }
974
975 #ifdef HAVE_BDEV_BLOCK_DEVICE_OPERATIONS
976 static struct block_device_operations zvol_ops = {
977         .open            = zvol_open,
978         .release         = zvol_release,
979         .ioctl           = zvol_ioctl,
980         .compat_ioctl    = zvol_compat_ioctl,
981         .media_changed   = zvol_media_changed,
982         .revalidate_disk = zvol_revalidate_disk,
983         .getgeo          = zvol_getgeo,
984         .owner           = THIS_MODULE,
985 };
986
987 #else /* HAVE_BDEV_BLOCK_DEVICE_OPERATIONS */
988
989 static int
990 zvol_open_by_inode(struct inode *inode, struct file *file)
991 {
992         return zvol_open(inode->i_bdev, file->f_mode);
993 }
994
995 static int
996 zvol_release_by_inode(struct inode *inode, struct file *file)
997 {
998         return zvol_release(inode->i_bdev->bd_disk, file->f_mode);
999 }
1000
1001 static int
1002 zvol_ioctl_by_inode(struct inode *inode, struct file *file,
1003                     unsigned int cmd, unsigned long arg)
1004 {
1005         return zvol_ioctl(inode->i_bdev, file->f_mode, cmd, arg);
1006 }
1007
1008 # ifdef CONFIG_COMPAT
1009 static long
1010 zvol_compat_ioctl_by_inode(struct file *file,
1011                            unsigned int cmd, unsigned long arg)
1012 {
1013         return zvol_compat_ioctl(file->f_dentry->d_inode->i_bdev,
1014                                  file->f_mode, cmd, arg);
1015 }
1016 # else
1017 # define zvol_compat_ioctl_by_inode   NULL
1018 # endif
1019
1020 static struct block_device_operations zvol_ops = {
1021         .open            = zvol_open_by_inode,
1022         .release         = zvol_release_by_inode,
1023         .ioctl           = zvol_ioctl_by_inode,
1024         .compat_ioctl    = zvol_compat_ioctl_by_inode,
1025         .media_changed   = zvol_media_changed,
1026         .revalidate_disk = zvol_revalidate_disk,
1027         .getgeo          = zvol_getgeo,
1028         .owner           = THIS_MODULE,
1029 };
1030 #endif /* HAVE_BDEV_BLOCK_DEVICE_OPERATIONS */
1031
1032 /*
1033  * Allocate memory for a new zvol_state_t and setup the required
1034  * request queue and generic disk structures for the block device.
1035  */
1036 static zvol_state_t *
1037 zvol_alloc(dev_t dev, const char *name)
1038 {
1039         zvol_state_t *zv;
1040
1041         zv = kmem_zalloc(sizeof (zvol_state_t), KM_SLEEP);
1042         if (zv == NULL)
1043                 goto out;
1044
1045         zv->zv_queue = blk_init_queue(zvol_request, &zv->zv_lock);
1046         if (zv->zv_queue == NULL)
1047                 goto out_kmem;
1048
1049         zv->zv_disk = alloc_disk(ZVOL_MINORS);
1050         if (zv->zv_disk == NULL)
1051                 goto out_queue;
1052
1053         zv->zv_queue->queuedata = zv;
1054         zv->zv_dev = dev;
1055         zv->zv_open_count = 0;
1056         strlcpy(zv->zv_name, name, DISK_NAME_LEN);
1057
1058         mutex_init(&zv->zv_znode.z_range_lock, NULL, MUTEX_DEFAULT, NULL);
1059         avl_create(&zv->zv_znode.z_range_avl, zfs_range_compare,
1060             sizeof (rl_t), offsetof(rl_t, r_node));
1061         spin_lock_init(&zv->zv_lock);
1062         list_link_init(&zv->zv_next);
1063
1064         zv->zv_disk->major = zvol_major;
1065         zv->zv_disk->first_minor = (dev & MINORMASK);
1066         zv->zv_disk->fops = &zvol_ops;
1067         zv->zv_disk->private_data = zv;
1068         zv->zv_disk->queue = zv->zv_queue;
1069         snprintf(zv->zv_disk->disk_name, DISK_NAME_LEN, "%s", name);
1070
1071         return zv;
1072
1073 out_queue:
1074         blk_cleanup_queue(zv->zv_queue);
1075 out_kmem:
1076         kmem_free(zv, sizeof (zvol_state_t));
1077 out:
1078         return NULL;
1079 }
1080
1081 /*
1082  * Cleanup then free a zvol_state_t which was created by zvol_alloc().
1083  */
1084 static void
1085 zvol_free(zvol_state_t *zv)
1086 {
1087         avl_destroy(&zv->zv_znode.z_range_avl);
1088         mutex_destroy(&zv->zv_znode.z_range_lock);
1089
1090         del_gendisk(zv->zv_disk);
1091         blk_cleanup_queue(zv->zv_queue);
1092         put_disk(zv->zv_disk);
1093
1094         kmem_free(zv, sizeof (zvol_state_t));
1095 }
1096
1097 static int
1098 __zvol_create_minor(const char *name)
1099 {
1100         zvol_state_t *zv;
1101         objset_t *os;
1102         dmu_object_info_t *doi;
1103         uint64_t volsize;
1104         unsigned minor = 0;
1105         int error = 0;
1106
1107         ASSERT(MUTEX_HELD(&zvol_state_lock));
1108
1109         zv = zvol_find_by_name(name);
1110         if (zv) {
1111                 error = EEXIST;
1112                 goto out;
1113         }
1114
1115         doi = kmem_alloc(sizeof(dmu_object_info_t), KM_SLEEP);
1116
1117         error = dmu_objset_own(name, DMU_OST_ZVOL, B_TRUE, zvol_tag, &os);
1118         if (error)
1119                 goto out_doi;
1120
1121         error = dmu_object_info(os, ZVOL_OBJ, doi);
1122         if (error)
1123                 goto out_dmu_objset_disown;
1124
1125         error = zap_lookup(os, ZVOL_ZAP_OBJ, "size", 8, 1, &volsize);
1126         if (error)
1127                 goto out_dmu_objset_disown;
1128
1129         error = zvol_find_minor(&minor);
1130         if (error)
1131                 goto out_dmu_objset_disown;
1132
1133         zv = zvol_alloc(MKDEV(zvol_major, minor), name);
1134         if (zv == NULL) {
1135                 error = EAGAIN;
1136                 goto out_dmu_objset_disown;
1137         }
1138
1139         if (dmu_objset_is_snapshot(os))
1140                 zv->zv_flags |= ZVOL_RDONLY;
1141
1142         zv->zv_volblocksize = doi->doi_data_block_size;
1143         zv->zv_volsize = volsize;
1144         zv->zv_objset = os;
1145
1146         set_capacity(zv->zv_disk, zv->zv_volsize >> 9);
1147
1148         if (zil_replay_disable)
1149                 zil_destroy(dmu_objset_zil(os), B_FALSE);
1150         else
1151                 zil_replay(os, zv, zvol_replay_vector);
1152
1153 out_dmu_objset_disown:
1154         dmu_objset_disown(os, zvol_tag);
1155         zv->zv_objset = NULL;
1156 out_doi:
1157         kmem_free(doi, sizeof(dmu_object_info_t));
1158 out:
1159
1160         if (error == 0) {
1161                 zvol_insert(zv);
1162                 add_disk(zv->zv_disk);
1163         }
1164
1165         return (error);
1166 }
1167
1168 /*
1169  * Create a block device minor node and setup the linkage between it
1170  * and the specified volume.  Once this function returns the block
1171  * device is live and ready for use.
1172  */
1173 int
1174 zvol_create_minor(const char *name)
1175 {
1176         int error;
1177
1178         mutex_enter(&zvol_state_lock);
1179         error = __zvol_create_minor(name);
1180         mutex_exit(&zvol_state_lock);
1181
1182         return (error);
1183 }
1184
1185 static int
1186 __zvol_remove_minor(const char *name)
1187 {
1188         zvol_state_t *zv;
1189
1190         ASSERT(MUTEX_HELD(&zvol_state_lock));
1191
1192         zv = zvol_find_by_name(name);
1193         if (zv == NULL)
1194                 return (ENXIO);
1195
1196         if (zv->zv_open_count > 0)
1197                 return (EBUSY);
1198
1199         zvol_remove(zv);
1200         zvol_free(zv);
1201
1202         return (0);
1203 }
1204
1205 /*
1206  * Remove a block device minor node for the specified volume.
1207  */
1208 int
1209 zvol_remove_minor(const char *name)
1210 {
1211         int error;
1212
1213         mutex_enter(&zvol_state_lock);
1214         error = __zvol_remove_minor(name);
1215         mutex_exit(&zvol_state_lock);
1216
1217         return (error);
1218 }
1219
1220 static int
1221 zvol_create_minors_cb(spa_t *spa, uint64_t dsobj,
1222                       const char *dsname, void *arg)
1223 {
1224         if (strchr(dsname, '/') == NULL)
1225                 return 0;
1226
1227         return __zvol_create_minor(dsname);
1228 }
1229
1230 /*
1231  * Create minors for specified pool, if pool is NULL create minors
1232  * for all available pools.
1233  */
1234 int
1235 zvol_create_minors(const char *pool)
1236 {
1237         spa_t *spa = NULL;
1238         int error = 0;
1239
1240         mutex_enter(&zvol_state_lock);
1241         if (pool) {
1242                 error = dmu_objset_find_spa(NULL, pool, zvol_create_minors_cb,
1243                     NULL, DS_FIND_CHILDREN | DS_FIND_SNAPSHOTS);
1244         } else {
1245                 mutex_enter(&spa_namespace_lock);
1246                 while ((spa = spa_next(spa)) != NULL) {
1247                         error = dmu_objset_find_spa(NULL,
1248                             spa_name(spa), zvol_create_minors_cb, NULL,
1249                             DS_FIND_CHILDREN | DS_FIND_SNAPSHOTS);
1250                         if (error)
1251                                 break;
1252                 }
1253                 mutex_exit(&spa_namespace_lock);
1254         }
1255         mutex_exit(&zvol_state_lock);
1256
1257         return error;
1258 }
1259
1260 /*
1261  * Remove minors for specified pool, if pool is NULL remove all minors.
1262  */
1263 void
1264 zvol_remove_minors(const char *pool)
1265 {
1266         zvol_state_t *zv, *zv_next;
1267         char *str;
1268
1269         str = kmem_zalloc(DISK_NAME_LEN, KM_SLEEP);
1270         if (pool) {
1271                 (void) strncpy(str, pool, strlen(pool));
1272                 (void) strcat(str, "/");
1273         }
1274
1275         mutex_enter(&zvol_state_lock);
1276         for (zv = list_head(&zvol_state_list); zv != NULL; zv = zv_next) {
1277                 zv_next = list_next(&zvol_state_list, zv);
1278
1279                 if (pool == NULL || !strncmp(str, zv->zv_name, strlen(str))) {
1280                         zvol_remove(zv);
1281                         zvol_free(zv);
1282                 }
1283         }
1284         mutex_exit(&zvol_state_lock);
1285         kmem_free(str, DISK_NAME_LEN);
1286 }
1287
1288 int
1289 zvol_init(void)
1290 {
1291         int error;
1292
1293         if (!zvol_threads)
1294                 zvol_threads = num_online_cpus();
1295
1296         zvol_taskq = taskq_create(ZVOL_DRIVER, zvol_threads, maxclsyspri,
1297                                   zvol_threads, INT_MAX, TASKQ_PREPOPULATE);
1298         if (zvol_taskq == NULL) {
1299                 printk(KERN_INFO "ZFS: taskq_create() failed\n");
1300                 return (-ENOMEM);
1301         }
1302
1303         error = register_blkdev(zvol_major, ZVOL_DRIVER);
1304         if (error) {
1305                 printk(KERN_INFO "ZFS: register_blkdev() failed %d\n", error);
1306                 taskq_destroy(zvol_taskq);
1307                 return (error);
1308         }
1309
1310         blk_register_region(MKDEV(zvol_major, 0), 1UL << MINORBITS,
1311                             THIS_MODULE, zvol_probe, NULL, NULL);
1312
1313         mutex_init(&zvol_state_lock, NULL, MUTEX_DEFAULT, NULL);
1314         list_create(&zvol_state_list, sizeof (zvol_state_t),
1315                     offsetof(zvol_state_t, zv_next));
1316
1317         (void) zvol_create_minors(NULL);
1318
1319         return (0);
1320 }
1321
1322 void
1323 zvol_fini(void)
1324 {
1325         zvol_remove_minors(NULL);
1326         blk_unregister_region(MKDEV(zvol_major, 0), 1UL << MINORBITS);
1327         unregister_blkdev(zvol_major, ZVOL_DRIVER);
1328         taskq_destroy(zvol_taskq);
1329         mutex_destroy(&zvol_state_lock);
1330         list_destroy(&zvol_state_list);
1331 }
1332
1333 module_param(zvol_major, uint, 0);
1334 MODULE_PARM_DESC(zvol_major, "Major number for zvol device");
1335
1336 module_param(zvol_threads, uint, 0);
1337 MODULE_PARM_DESC(zvol_threads, "Number of threads for zvol device");