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