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