Fix using zvol as slog device
[freebsd.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 error;
895         uint64_t ro;
896
897         /* lie and say we're read-only */
898         error = dmu_objset_own(zv->zv_name, DMU_OST_ZVOL, 1, zvol_tag, &os);
899         if (error)
900                 return (-error);
901
902         error = zap_lookup(os, ZVOL_ZAP_OBJ, "size", 8, 1, &volsize);
903         if (error) {
904                 dmu_objset_disown(os, zvol_tag);
905                 return (-error);
906         }
907
908         zv->zv_objset = os;
909         error = dmu_bonus_hold(os, ZVOL_OBJ, zvol_tag, &zv->zv_dbuf);
910         if (error) {
911                 dmu_objset_disown(os, zvol_tag);
912                 return (-error);
913         }
914
915         set_capacity(zv->zv_disk, volsize >> 9);
916         zv->zv_volsize = volsize;
917         zv->zv_zilog = zil_open(os, zvol_get_data);
918
919         VERIFY(dsl_prop_get_integer(zv->zv_name, "readonly", &ro, NULL) == 0);
920         if (ro || dmu_objset_is_snapshot(os)) {
921                 set_disk_ro(zv->zv_disk, 1);
922                 zv->zv_flags |= ZVOL_RDONLY;
923         } else {
924                 set_disk_ro(zv->zv_disk, 0);
925                 zv->zv_flags &= ~ZVOL_RDONLY;
926         }
927
928         return (-error);
929 }
930
931 static void
932 zvol_last_close(zvol_state_t *zv)
933 {
934         zil_close(zv->zv_zilog);
935         zv->zv_zilog = NULL;
936
937         dmu_buf_rele(zv->zv_dbuf, zvol_tag);
938         zv->zv_dbuf = NULL;
939
940         /*
941          * Evict cached data
942          */
943         if (dsl_dataset_is_dirty(dmu_objset_ds(zv->zv_objset)) &&
944             !(zv->zv_flags & ZVOL_RDONLY))
945                 txg_wait_synced(dmu_objset_pool(zv->zv_objset), 0);
946         (void) dmu_objset_evict_dbufs(zv->zv_objset);
947
948         dmu_objset_disown(zv->zv_objset, zvol_tag);
949         zv->zv_objset = NULL;
950 }
951
952 static int
953 zvol_open(struct block_device *bdev, fmode_t flag)
954 {
955         zvol_state_t *zv = bdev->bd_disk->private_data;
956         int error = 0, drop_mutex = 0;
957
958         /*
959          * If the caller is already holding the mutex do not take it
960          * again, this will happen as part of zvol_create_minor().
961          * Once add_disk() is called the device is live and the kernel
962          * will attempt to open it to read the partition information.
963          */
964         if (!mutex_owned(&zvol_state_lock)) {
965                 mutex_enter(&zvol_state_lock);
966                 drop_mutex = 1;
967         }
968
969         ASSERT3P(zv, !=, NULL);
970
971         if (zv->zv_open_count == 0) {
972                 error = zvol_first_open(zv);
973                 if (error)
974                         goto out_mutex;
975         }
976
977         if ((flag & FMODE_WRITE) &&
978             (get_disk_ro(zv->zv_disk) || (zv->zv_flags & ZVOL_RDONLY))) {
979                 error = -EROFS;
980                 goto out_open_count;
981         }
982
983         zv->zv_open_count++;
984
985 out_open_count:
986         if (zv->zv_open_count == 0)
987                 zvol_last_close(zv);
988
989 out_mutex:
990         if (drop_mutex)
991                 mutex_exit(&zvol_state_lock);
992
993         check_disk_change(bdev);
994
995         return (error);
996 }
997
998 static int
999 zvol_release(struct gendisk *disk, fmode_t mode)
1000 {
1001         zvol_state_t *zv = disk->private_data;
1002         int drop_mutex = 0;
1003
1004         if (!mutex_owned(&zvol_state_lock)) {
1005                 mutex_enter(&zvol_state_lock);
1006                 drop_mutex = 1;
1007         }
1008
1009         ASSERT3P(zv, !=, NULL);
1010         ASSERT3U(zv->zv_open_count, >, 0);
1011         zv->zv_open_count--;
1012         if (zv->zv_open_count == 0)
1013                 zvol_last_close(zv);
1014
1015         if (drop_mutex)
1016                 mutex_exit(&zvol_state_lock);
1017
1018         return (0);
1019 }
1020
1021 static int
1022 zvol_ioctl(struct block_device *bdev, fmode_t mode,
1023            unsigned int cmd, unsigned long arg)
1024 {
1025         zvol_state_t *zv = bdev->bd_disk->private_data;
1026         int error = 0;
1027
1028         if (zv == NULL)
1029                 return (-ENXIO);
1030
1031         switch (cmd) {
1032         case BLKFLSBUF:
1033                 zil_commit(zv->zv_zilog, ZVOL_OBJ);
1034                 break;
1035         case BLKZNAME:
1036                 error = copy_to_user((void *)arg, zv->zv_name, MAXNAMELEN);
1037                 break;
1038
1039         default:
1040                 error = -ENOTTY;
1041                 break;
1042
1043         }
1044
1045         return (error);
1046 }
1047
1048 #ifdef CONFIG_COMPAT
1049 static int
1050 zvol_compat_ioctl(struct block_device *bdev, fmode_t mode,
1051                   unsigned cmd, unsigned long arg)
1052 {
1053         return zvol_ioctl(bdev, mode, cmd, arg);
1054 }
1055 #else
1056 #define zvol_compat_ioctl   NULL
1057 #endif
1058
1059 static int zvol_media_changed(struct gendisk *disk)
1060 {
1061         zvol_state_t *zv = disk->private_data;
1062
1063         return zv->zv_changed;
1064 }
1065
1066 static int zvol_revalidate_disk(struct gendisk *disk)
1067 {
1068         zvol_state_t *zv = disk->private_data;
1069
1070         zv->zv_changed = 0;
1071         set_capacity(zv->zv_disk, zv->zv_volsize >> 9);
1072
1073         return 0;
1074 }
1075
1076 /*
1077  * Provide a simple virtual geometry for legacy compatibility.  For devices
1078  * smaller than 1 MiB a small head and sector count is used to allow very
1079  * tiny devices.  For devices over 1 Mib a standard head and sector count
1080  * is used to keep the cylinders count reasonable.
1081  */
1082 static int
1083 zvol_getgeo(struct block_device *bdev, struct hd_geometry *geo)
1084 {
1085         zvol_state_t *zv = bdev->bd_disk->private_data;
1086         sector_t sectors = get_capacity(zv->zv_disk);
1087
1088         if (sectors > 2048) {
1089                 geo->heads = 16;
1090                 geo->sectors = 63;
1091         } else {
1092                 geo->heads = 2;
1093                 geo->sectors = 4;
1094         }
1095
1096         geo->start = 0;
1097         geo->cylinders = sectors / (geo->heads * geo->sectors);
1098
1099         return 0;
1100 }
1101
1102 static struct kobject *
1103 zvol_probe(dev_t dev, int *part, void *arg)
1104 {
1105         zvol_state_t *zv;
1106         struct kobject *kobj;
1107
1108         mutex_enter(&zvol_state_lock);
1109         zv = zvol_find_by_dev(dev);
1110         kobj = zv ? get_disk(zv->zv_disk) : NULL;
1111         mutex_exit(&zvol_state_lock);
1112
1113         return kobj;
1114 }
1115
1116 #ifdef HAVE_BDEV_BLOCK_DEVICE_OPERATIONS
1117 static struct block_device_operations zvol_ops = {
1118         .open            = zvol_open,
1119         .release         = zvol_release,
1120         .ioctl           = zvol_ioctl,
1121         .compat_ioctl    = zvol_compat_ioctl,
1122         .media_changed   = zvol_media_changed,
1123         .revalidate_disk = zvol_revalidate_disk,
1124         .getgeo          = zvol_getgeo,
1125         .owner           = THIS_MODULE,
1126 };
1127
1128 #else /* HAVE_BDEV_BLOCK_DEVICE_OPERATIONS */
1129
1130 static int
1131 zvol_open_by_inode(struct inode *inode, struct file *file)
1132 {
1133         return zvol_open(inode->i_bdev, file->f_mode);
1134 }
1135
1136 static int
1137 zvol_release_by_inode(struct inode *inode, struct file *file)
1138 {
1139         return zvol_release(inode->i_bdev->bd_disk, file->f_mode);
1140 }
1141
1142 static int
1143 zvol_ioctl_by_inode(struct inode *inode, struct file *file,
1144                     unsigned int cmd, unsigned long arg)
1145 {
1146         if (file == NULL || inode == NULL)
1147                 return -EINVAL;
1148         return zvol_ioctl(inode->i_bdev, file->f_mode, cmd, arg);
1149 }
1150
1151 # ifdef CONFIG_COMPAT
1152 static long
1153 zvol_compat_ioctl_by_inode(struct file *file,
1154                            unsigned int cmd, unsigned long arg)
1155 {
1156         if (file == NULL)
1157                 return -EINVAL;
1158         return zvol_compat_ioctl(file->f_dentry->d_inode->i_bdev,
1159                                  file->f_mode, cmd, arg);
1160 }
1161 # else
1162 # define zvol_compat_ioctl_by_inode   NULL
1163 # endif
1164
1165 static struct block_device_operations zvol_ops = {
1166         .open            = zvol_open_by_inode,
1167         .release         = zvol_release_by_inode,
1168         .ioctl           = zvol_ioctl_by_inode,
1169         .compat_ioctl    = zvol_compat_ioctl_by_inode,
1170         .media_changed   = zvol_media_changed,
1171         .revalidate_disk = zvol_revalidate_disk,
1172         .getgeo          = zvol_getgeo,
1173         .owner           = THIS_MODULE,
1174 };
1175 #endif /* HAVE_BDEV_BLOCK_DEVICE_OPERATIONS */
1176
1177 /*
1178  * Allocate memory for a new zvol_state_t and setup the required
1179  * request queue and generic disk structures for the block device.
1180  */
1181 static zvol_state_t *
1182 zvol_alloc(dev_t dev, const char *name)
1183 {
1184         zvol_state_t *zv;
1185         int error = 0;
1186
1187         zv = kmem_zalloc(sizeof (zvol_state_t), KM_SLEEP);
1188         if (zv == NULL)
1189                 goto out;
1190
1191         zv->zv_queue = blk_init_queue(zvol_request, &zv->zv_lock);
1192         if (zv->zv_queue == NULL)
1193                 goto out_kmem;
1194
1195 #ifdef HAVE_ELEVATOR_CHANGE
1196         error = elevator_change(zv->zv_queue, "noop");
1197 #endif /* HAVE_ELEVATOR_CHANGE */
1198         if (error) {
1199                 printk("ZFS: Unable to set \"%s\" scheduler for zvol %s: %d\n",
1200                     "noop", name, error);
1201                 goto out_queue;
1202         }
1203
1204 #ifdef HAVE_BLK_QUEUE_FLUSH
1205         blk_queue_flush(zv->zv_queue, VDEV_REQ_FLUSH | VDEV_REQ_FUA);
1206 #else
1207         blk_queue_ordered(zv->zv_queue, QUEUE_ORDERED_DRAIN, NULL);
1208 #endif /* HAVE_BLK_QUEUE_FLUSH */
1209
1210         zv->zv_disk = alloc_disk(ZVOL_MINORS);
1211         if (zv->zv_disk == NULL)
1212                 goto out_queue;
1213
1214         zv->zv_queue->queuedata = zv;
1215         zv->zv_dev = dev;
1216         zv->zv_open_count = 0;
1217         strlcpy(zv->zv_name, name, MAXNAMELEN);
1218
1219         mutex_init(&zv->zv_znode.z_range_lock, NULL, MUTEX_DEFAULT, NULL);
1220         avl_create(&zv->zv_znode.z_range_avl, zfs_range_compare,
1221             sizeof (rl_t), offsetof(rl_t, r_node));
1222         zv->zv_znode.z_is_zvol = TRUE;
1223
1224         spin_lock_init(&zv->zv_lock);
1225         list_link_init(&zv->zv_next);
1226
1227         zv->zv_disk->major = zvol_major;
1228         zv->zv_disk->first_minor = (dev & MINORMASK);
1229         zv->zv_disk->fops = &zvol_ops;
1230         zv->zv_disk->private_data = zv;
1231         zv->zv_disk->queue = zv->zv_queue;
1232         snprintf(zv->zv_disk->disk_name, DISK_NAME_LEN, "%s%d",
1233             ZVOL_DEV_NAME, (dev & MINORMASK));
1234
1235         return zv;
1236
1237 out_queue:
1238         blk_cleanup_queue(zv->zv_queue);
1239 out_kmem:
1240         kmem_free(zv, sizeof (zvol_state_t));
1241 out:
1242         return NULL;
1243 }
1244
1245 /*
1246  * Cleanup then free a zvol_state_t which was created by zvol_alloc().
1247  */
1248 static void
1249 zvol_free(zvol_state_t *zv)
1250 {
1251         avl_destroy(&zv->zv_znode.z_range_avl);
1252         mutex_destroy(&zv->zv_znode.z_range_lock);
1253
1254         del_gendisk(zv->zv_disk);
1255         blk_cleanup_queue(zv->zv_queue);
1256         put_disk(zv->zv_disk);
1257
1258         kmem_free(zv, sizeof (zvol_state_t));
1259 }
1260
1261 static int
1262 __zvol_create_minor(const char *name)
1263 {
1264         zvol_state_t *zv;
1265         objset_t *os;
1266         dmu_object_info_t *doi;
1267         uint64_t volsize;
1268         unsigned minor = 0;
1269         int error = 0;
1270
1271         ASSERT(MUTEX_HELD(&zvol_state_lock));
1272
1273         zv = zvol_find_by_name(name);
1274         if (zv) {
1275                 error = EEXIST;
1276                 goto out;
1277         }
1278
1279         doi = kmem_alloc(sizeof(dmu_object_info_t), KM_SLEEP);
1280
1281         error = dmu_objset_own(name, DMU_OST_ZVOL, B_TRUE, zvol_tag, &os);
1282         if (error)
1283                 goto out_doi;
1284
1285         error = dmu_object_info(os, ZVOL_OBJ, doi);
1286         if (error)
1287                 goto out_dmu_objset_disown;
1288
1289         error = zap_lookup(os, ZVOL_ZAP_OBJ, "size", 8, 1, &volsize);
1290         if (error)
1291                 goto out_dmu_objset_disown;
1292
1293         error = zvol_find_minor(&minor);
1294         if (error)
1295                 goto out_dmu_objset_disown;
1296
1297         zv = zvol_alloc(MKDEV(zvol_major, minor), name);
1298         if (zv == NULL) {
1299                 error = EAGAIN;
1300                 goto out_dmu_objset_disown;
1301         }
1302
1303         if (dmu_objset_is_snapshot(os))
1304                 zv->zv_flags |= ZVOL_RDONLY;
1305
1306         zv->zv_volblocksize = doi->doi_data_block_size;
1307         zv->zv_volsize = volsize;
1308         zv->zv_objset = os;
1309
1310         set_capacity(zv->zv_disk, zv->zv_volsize >> 9);
1311
1312         blk_queue_max_hw_sectors(zv->zv_queue, UINT_MAX);
1313         blk_queue_max_segments(zv->zv_queue, UINT16_MAX);
1314         blk_queue_max_segment_size(zv->zv_queue, UINT_MAX);
1315         blk_queue_physical_block_size(zv->zv_queue, zv->zv_volblocksize);
1316         blk_queue_io_opt(zv->zv_queue, zv->zv_volblocksize);
1317 #ifdef HAVE_BLK_QUEUE_DISCARD
1318         blk_queue_max_discard_sectors(zv->zv_queue,
1319             (zvol_max_discard_blocks * zv->zv_volblocksize) >> 9);
1320         blk_queue_discard_granularity(zv->zv_queue, zv->zv_volblocksize);
1321         queue_flag_set_unlocked(QUEUE_FLAG_DISCARD, zv->zv_queue);
1322 #endif
1323 #ifdef HAVE_BLK_QUEUE_NONROT
1324         queue_flag_set_unlocked(QUEUE_FLAG_NONROT, zv->zv_queue);
1325 #endif
1326
1327         if (zil_replay_disable)
1328                 zil_destroy(dmu_objset_zil(os), B_FALSE);
1329         else
1330                 zil_replay(os, zv, zvol_replay_vector);
1331
1332         zv->zv_objset = NULL;
1333 out_dmu_objset_disown:
1334         dmu_objset_disown(os, zvol_tag);
1335 out_doi:
1336         kmem_free(doi, sizeof(dmu_object_info_t));
1337 out:
1338
1339         if (error == 0) {
1340                 zvol_insert(zv);
1341                 add_disk(zv->zv_disk);
1342         }
1343
1344         return (error);
1345 }
1346
1347 /*
1348  * Create a block device minor node and setup the linkage between it
1349  * and the specified volume.  Once this function returns the block
1350  * device is live and ready for use.
1351  */
1352 int
1353 zvol_create_minor(const char *name)
1354 {
1355         int error;
1356
1357         mutex_enter(&zvol_state_lock);
1358         error = __zvol_create_minor(name);
1359         mutex_exit(&zvol_state_lock);
1360
1361         return (error);
1362 }
1363
1364 static int
1365 __zvol_remove_minor(const char *name)
1366 {
1367         zvol_state_t *zv;
1368
1369         ASSERT(MUTEX_HELD(&zvol_state_lock));
1370
1371         zv = zvol_find_by_name(name);
1372         if (zv == NULL)
1373                 return (ENXIO);
1374
1375         if (zv->zv_open_count > 0)
1376                 return (EBUSY);
1377
1378         zvol_remove(zv);
1379         zvol_free(zv);
1380
1381         return (0);
1382 }
1383
1384 /*
1385  * Remove a block device minor node for the specified volume.
1386  */
1387 int
1388 zvol_remove_minor(const char *name)
1389 {
1390         int error;
1391
1392         mutex_enter(&zvol_state_lock);
1393         error = __zvol_remove_minor(name);
1394         mutex_exit(&zvol_state_lock);
1395
1396         return (error);
1397 }
1398
1399 static int
1400 zvol_create_minors_cb(spa_t *spa, uint64_t dsobj,
1401                       const char *dsname, void *arg)
1402 {
1403         if (strchr(dsname, '/') == NULL)
1404                 return 0;
1405
1406         (void) __zvol_create_minor(dsname);
1407         return (0);
1408 }
1409
1410 /*
1411  * Create minors for specified pool, if pool is NULL create minors
1412  * for all available pools.
1413  */
1414 int
1415 zvol_create_minors(const char *pool)
1416 {
1417         spa_t *spa = NULL;
1418         int error = 0;
1419
1420         if (zvol_inhibit_dev)
1421                 return (0);
1422
1423         mutex_enter(&zvol_state_lock);
1424         if (pool) {
1425                 error = dmu_objset_find_spa(NULL, pool, zvol_create_minors_cb,
1426                     NULL, DS_FIND_CHILDREN | DS_FIND_SNAPSHOTS);
1427         } else {
1428                 mutex_enter(&spa_namespace_lock);
1429                 while ((spa = spa_next(spa)) != NULL) {
1430                         error = dmu_objset_find_spa(NULL,
1431                             spa_name(spa), zvol_create_minors_cb, NULL,
1432                             DS_FIND_CHILDREN | DS_FIND_SNAPSHOTS);
1433                         if (error)
1434                                 break;
1435                 }
1436                 mutex_exit(&spa_namespace_lock);
1437         }
1438         mutex_exit(&zvol_state_lock);
1439
1440         return error;
1441 }
1442
1443 /*
1444  * Remove minors for specified pool, if pool is NULL remove all minors.
1445  */
1446 void
1447 zvol_remove_minors(const char *pool)
1448 {
1449         zvol_state_t *zv, *zv_next;
1450         char *str;
1451
1452         if (zvol_inhibit_dev)
1453                 return;
1454
1455         str = kmem_zalloc(MAXNAMELEN, KM_SLEEP);
1456         if (pool) {
1457                 (void) strncpy(str, pool, strlen(pool));
1458                 (void) strcat(str, "/");
1459         }
1460
1461         mutex_enter(&zvol_state_lock);
1462         for (zv = list_head(&zvol_state_list); zv != NULL; zv = zv_next) {
1463                 zv_next = list_next(&zvol_state_list, zv);
1464
1465                 if (pool == NULL || !strncmp(str, zv->zv_name, strlen(str))) {
1466                         zvol_remove(zv);
1467                         zvol_free(zv);
1468                 }
1469         }
1470         mutex_exit(&zvol_state_lock);
1471         kmem_free(str, MAXNAMELEN);
1472 }
1473
1474 int
1475 zvol_init(void)
1476 {
1477         int error;
1478
1479         zvol_taskq = taskq_create(ZVOL_DRIVER, zvol_threads, maxclsyspri,
1480                                   zvol_threads, INT_MAX, TASKQ_PREPOPULATE);
1481         if (zvol_taskq == NULL) {
1482                 printk(KERN_INFO "ZFS: taskq_create() failed\n");
1483                 return (-ENOMEM);
1484         }
1485
1486         error = register_blkdev(zvol_major, ZVOL_DRIVER);
1487         if (error) {
1488                 printk(KERN_INFO "ZFS: register_blkdev() failed %d\n", error);
1489                 taskq_destroy(zvol_taskq);
1490                 return (error);
1491         }
1492
1493         blk_register_region(MKDEV(zvol_major, 0), 1UL << MINORBITS,
1494                             THIS_MODULE, zvol_probe, NULL, NULL);
1495
1496         mutex_init(&zvol_state_lock, NULL, MUTEX_DEFAULT, NULL);
1497         list_create(&zvol_state_list, sizeof (zvol_state_t),
1498                     offsetof(zvol_state_t, zv_next));
1499
1500         (void) zvol_create_minors(NULL);
1501
1502         return (0);
1503 }
1504
1505 void
1506 zvol_fini(void)
1507 {
1508         zvol_remove_minors(NULL);
1509         blk_unregister_region(MKDEV(zvol_major, 0), 1UL << MINORBITS);
1510         unregister_blkdev(zvol_major, ZVOL_DRIVER);
1511         taskq_destroy(zvol_taskq);
1512         mutex_destroy(&zvol_state_lock);
1513         list_destroy(&zvol_state_list);
1514 }
1515
1516 module_param(zvol_inhibit_dev, uint, 0644);
1517 MODULE_PARM_DESC(zvol_inhibit_dev, "Do not create zvol device nodes");
1518
1519 module_param(zvol_major, uint, 0444);
1520 MODULE_PARM_DESC(zvol_major, "Major number for zvol device");
1521
1522 module_param(zvol_threads, uint, 0444);
1523 MODULE_PARM_DESC(zvol_threads, "Number of threads for zvol device");
1524
1525 module_param(zvol_max_discard_blocks, ulong, 0444);
1526 MODULE_PARM_DESC(zvol_max_discard_blocks, "Max number of blocks to discard at once");