Use uio for zvol_{read,write}
[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/dbuf.h>
39 #include <sys/dmu_traverse.h>
40 #include <sys/dsl_dataset.h>
41 #include <sys/dsl_prop.h>
42 #include <sys/zap.h>
43 #include <sys/zfeature.h>
44 #include <sys/zil_impl.h>
45 #include <sys/zio.h>
46 #include <sys/zfs_rlock.h>
47 #include <sys/zfs_znode.h>
48 #include <sys/zvol.h>
49 #include <linux/blkdev_compat.h>
50
51 unsigned int zvol_inhibit_dev = 0;
52 unsigned int zvol_major = ZVOL_MAJOR;
53 unsigned int zvol_prefetch_bytes = (128 * 1024);
54 unsigned long zvol_max_discard_blocks = 16384;
55
56 static kmutex_t zvol_state_lock;
57 static list_t zvol_state_list;
58 static char *zvol_tag = "zvol_tag";
59
60 /*
61  * The in-core state of each volume.
62  */
63 typedef struct zvol_state {
64         char                    zv_name[MAXNAMELEN];    /* name */
65         uint64_t                zv_volsize;             /* advertised space */
66         uint64_t                zv_volblocksize;        /* volume block size */
67         objset_t                *zv_objset;     /* objset handle */
68         uint32_t                zv_flags;       /* ZVOL_* flags */
69         uint32_t                zv_open_count;  /* open counts */
70         uint32_t                zv_changed;     /* disk changed */
71         zilog_t                 *zv_zilog;      /* ZIL handle */
72         znode_t                 zv_znode;       /* for range locking */
73         dmu_buf_t               *zv_dbuf;       /* bonus handle */
74         dev_t                   zv_dev;         /* device id */
75         struct gendisk          *zv_disk;       /* generic disk */
76         struct request_queue    *zv_queue;      /* request queue */
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 (SET_ERROR(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) == 0)
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 (SET_ERROR(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 (SET_ERROR(error));
231 }
232
233 static void
234 zvol_size_changed(zvol_state_t *zv, uint64_t volsize)
235 {
236         struct block_device *bdev;
237
238         bdev = bdget_disk(zv->zv_disk, 0);
239         if (bdev == NULL)
240                 return;
241 /*
242  * 2.6.28 API change
243  * Added check_disk_size_change() helper function.
244  */
245 #ifdef HAVE_CHECK_DISK_SIZE_CHANGE
246         set_capacity(zv->zv_disk, volsize >> 9);
247         zv->zv_volsize = volsize;
248         check_disk_size_change(zv->zv_disk, bdev);
249 #else
250         zv->zv_volsize = volsize;
251         zv->zv_changed = 1;
252         (void) check_disk_change(bdev);
253 #endif /* HAVE_CHECK_DISK_SIZE_CHANGE */
254
255         bdput(bdev);
256 }
257
258 /*
259  * Sanity check volume size.
260  */
261 int
262 zvol_check_volsize(uint64_t volsize, uint64_t blocksize)
263 {
264         if (volsize == 0)
265                 return (SET_ERROR(EINVAL));
266
267         if (volsize % blocksize != 0)
268                 return (SET_ERROR(EINVAL));
269
270 #ifdef _ILP32
271         if (volsize - 1 > MAXOFFSET_T)
272                 return (SET_ERROR(EOVERFLOW));
273 #endif
274         return (0);
275 }
276
277 /*
278  * Ensure the zap is flushed then inform the VFS of the capacity change.
279  */
280 static int
281 zvol_update_volsize(uint64_t volsize, objset_t *os)
282 {
283         dmu_tx_t *tx;
284         int error;
285
286         ASSERT(MUTEX_HELD(&zvol_state_lock));
287
288         tx = dmu_tx_create(os);
289         dmu_tx_hold_zap(tx, ZVOL_ZAP_OBJ, TRUE, NULL);
290         error = dmu_tx_assign(tx, TXG_WAIT);
291         if (error) {
292                 dmu_tx_abort(tx);
293                 return (SET_ERROR(error));
294         }
295
296         error = zap_update(os, ZVOL_ZAP_OBJ, "size", 8, 1,
297             &volsize, tx);
298         dmu_tx_commit(tx);
299
300         if (error == 0)
301                 error = dmu_free_long_range(os,
302                     ZVOL_OBJ, volsize, DMU_OBJECT_END);
303
304         return (error);
305 }
306
307 static int
308 zvol_update_live_volsize(zvol_state_t *zv, uint64_t volsize)
309 {
310         zvol_size_changed(zv, volsize);
311
312         /*
313          * We should post a event here describing the expansion.  However,
314          * the zfs_ereport_post() interface doesn't nicely support posting
315          * events for zvols, it assumes events relate to vdevs or zios.
316          */
317
318         return (0);
319 }
320
321 /*
322  * Set ZFS_PROP_VOLSIZE set entry point.
323  */
324 int
325 zvol_set_volsize(const char *name, uint64_t volsize)
326 {
327         zvol_state_t *zv = NULL;
328         objset_t *os = NULL;
329         int error;
330         dmu_object_info_t *doi;
331         uint64_t readonly;
332         boolean_t owned = B_FALSE;
333
334         error = dsl_prop_get_integer(name,
335             zfs_prop_to_name(ZFS_PROP_READONLY), &readonly, NULL);
336         if (error != 0)
337                 return (SET_ERROR(error));
338         if (readonly)
339                 return (SET_ERROR(EROFS));
340
341         mutex_enter(&zvol_state_lock);
342         zv = zvol_find_by_name(name);
343
344         if (zv == NULL || zv->zv_objset == NULL) {
345                 if ((error = dmu_objset_own(name, DMU_OST_ZVOL, B_FALSE,
346                     FTAG, &os)) != 0) {
347                         mutex_exit(&zvol_state_lock);
348                         return (SET_ERROR(error));
349                 }
350                 owned = B_TRUE;
351                 if (zv != NULL)
352                         zv->zv_objset = os;
353         } else {
354                 os = zv->zv_objset;
355         }
356
357         doi = kmem_alloc(sizeof (dmu_object_info_t), KM_SLEEP);
358
359         if ((error = dmu_object_info(os, ZVOL_OBJ, doi)) ||
360             (error = zvol_check_volsize(volsize, doi->doi_data_block_size)))
361                 goto out;
362
363         error = zvol_update_volsize(volsize, os);
364         kmem_free(doi, sizeof (dmu_object_info_t));
365
366         if (error == 0 && zv != NULL)
367                 error = zvol_update_live_volsize(zv, volsize);
368 out:
369         if (owned) {
370                 dmu_objset_disown(os, FTAG);
371                 if (zv != NULL)
372                         zv->zv_objset = NULL;
373         }
374         mutex_exit(&zvol_state_lock);
375         return (error);
376 }
377
378 /*
379  * Sanity check volume block size.
380  */
381 int
382 zvol_check_volblocksize(const char *name, uint64_t volblocksize)
383 {
384         /* Record sizes above 128k need the feature to be enabled */
385         if (volblocksize > SPA_OLD_MAXBLOCKSIZE) {
386                 spa_t *spa;
387                 int error;
388
389                 if ((error = spa_open(name, &spa, FTAG)) != 0)
390                         return (error);
391
392                 if (!spa_feature_is_enabled(spa, SPA_FEATURE_LARGE_BLOCKS)) {
393                         spa_close(spa, FTAG);
394                         return (SET_ERROR(ENOTSUP));
395                 }
396
397                 /*
398                  * We don't allow setting the property above 1MB,
399                  * unless the tunable has been changed.
400                  */
401                 if (volblocksize > zfs_max_recordsize)
402                         return (SET_ERROR(EDOM));
403
404                 spa_close(spa, FTAG);
405         }
406
407         if (volblocksize < SPA_MINBLOCKSIZE ||
408             volblocksize > SPA_MAXBLOCKSIZE ||
409             !ISP2(volblocksize))
410                 return (SET_ERROR(EDOM));
411
412         return (0);
413 }
414
415 /*
416  * Set ZFS_PROP_VOLBLOCKSIZE set entry point.
417  */
418 int
419 zvol_set_volblocksize(const char *name, uint64_t volblocksize)
420 {
421         zvol_state_t *zv;
422         dmu_tx_t *tx;
423         int error;
424
425         mutex_enter(&zvol_state_lock);
426
427         zv = zvol_find_by_name(name);
428         if (zv == NULL) {
429                 error = SET_ERROR(ENXIO);
430                 goto out;
431         }
432
433         if (zv->zv_flags & ZVOL_RDONLY) {
434                 error = SET_ERROR(EROFS);
435                 goto out;
436         }
437
438         tx = dmu_tx_create(zv->zv_objset);
439         dmu_tx_hold_bonus(tx, ZVOL_OBJ);
440         error = dmu_tx_assign(tx, TXG_WAIT);
441         if (error) {
442                 dmu_tx_abort(tx);
443         } else {
444                 error = dmu_object_set_blocksize(zv->zv_objset, ZVOL_OBJ,
445                     volblocksize, 0, tx);
446                 if (error == ENOTSUP)
447                         error = SET_ERROR(EBUSY);
448                 dmu_tx_commit(tx);
449                 if (error == 0)
450                         zv->zv_volblocksize = volblocksize;
451         }
452 out:
453         mutex_exit(&zvol_state_lock);
454
455         return (SET_ERROR(error));
456 }
457
458 /*
459  * Replay a TX_WRITE ZIL transaction that didn't get committed
460  * after a system failure
461  */
462 static int
463 zvol_replay_write(zvol_state_t *zv, lr_write_t *lr, boolean_t byteswap)
464 {
465         objset_t *os = zv->zv_objset;
466         char *data = (char *)(lr + 1);  /* data follows lr_write_t */
467         uint64_t off = lr->lr_offset;
468         uint64_t len = lr->lr_length;
469         dmu_tx_t *tx;
470         int error;
471
472         if (byteswap)
473                 byteswap_uint64_array(lr, sizeof (*lr));
474
475         tx = dmu_tx_create(os);
476         dmu_tx_hold_write(tx, ZVOL_OBJ, off, len);
477         error = dmu_tx_assign(tx, TXG_WAIT);
478         if (error) {
479                 dmu_tx_abort(tx);
480         } else {
481                 dmu_write(os, ZVOL_OBJ, off, len, data, tx);
482                 dmu_tx_commit(tx);
483         }
484
485         return (SET_ERROR(error));
486 }
487
488 static int
489 zvol_replay_err(zvol_state_t *zv, lr_t *lr, boolean_t byteswap)
490 {
491         return (SET_ERROR(ENOTSUP));
492 }
493
494 /*
495  * Callback vectors for replaying records.
496  * Only TX_WRITE is needed for zvol.
497  */
498 zil_replay_func_t zvol_replay_vector[TX_MAX_TYPE] = {
499         (zil_replay_func_t)zvol_replay_err,     /* no such transaction type */
500         (zil_replay_func_t)zvol_replay_err,     /* TX_CREATE */
501         (zil_replay_func_t)zvol_replay_err,     /* TX_MKDIR */
502         (zil_replay_func_t)zvol_replay_err,     /* TX_MKXATTR */
503         (zil_replay_func_t)zvol_replay_err,     /* TX_SYMLINK */
504         (zil_replay_func_t)zvol_replay_err,     /* TX_REMOVE */
505         (zil_replay_func_t)zvol_replay_err,     /* TX_RMDIR */
506         (zil_replay_func_t)zvol_replay_err,     /* TX_LINK */
507         (zil_replay_func_t)zvol_replay_err,     /* TX_RENAME */
508         (zil_replay_func_t)zvol_replay_write,   /* TX_WRITE */
509         (zil_replay_func_t)zvol_replay_err,     /* TX_TRUNCATE */
510         (zil_replay_func_t)zvol_replay_err,     /* TX_SETATTR */
511         (zil_replay_func_t)zvol_replay_err,     /* TX_ACL */
512 };
513
514 /*
515  * zvol_log_write() handles synchronous writes using TX_WRITE ZIL transactions.
516  *
517  * We store data in the log buffers if it's small enough.
518  * Otherwise we will later flush the data out via dmu_sync().
519  */
520 ssize_t zvol_immediate_write_sz = 32768;
521
522 static void
523 zvol_log_write(zvol_state_t *zv, dmu_tx_t *tx, uint64_t offset,
524     uint64_t size, int sync)
525 {
526         uint32_t blocksize = zv->zv_volblocksize;
527         zilog_t *zilog = zv->zv_zilog;
528         boolean_t slogging;
529         ssize_t immediate_write_sz;
530
531         if (zil_replaying(zilog, tx))
532                 return;
533
534         immediate_write_sz = (zilog->zl_logbias == ZFS_LOGBIAS_THROUGHPUT)
535                 ? 0 : zvol_immediate_write_sz;
536         slogging = spa_has_slogs(zilog->zl_spa) &&
537                 (zilog->zl_logbias == ZFS_LOGBIAS_LATENCY);
538
539         while (size) {
540                 itx_t *itx;
541                 lr_write_t *lr;
542                 ssize_t len;
543                 itx_wr_state_t write_state;
544
545                 /*
546                  * Unlike zfs_log_write() we can be called with
547                  * up to DMU_MAX_ACCESS/2 (5MB) writes.
548                  */
549                 if (blocksize > immediate_write_sz && !slogging &&
550                     size >= blocksize && offset % blocksize == 0) {
551                         write_state = WR_INDIRECT; /* uses dmu_sync */
552                         len = blocksize;
553                 } else if (sync) {
554                         write_state = WR_COPIED;
555                         len = MIN(ZIL_MAX_LOG_DATA, size);
556                 } else {
557                         write_state = WR_NEED_COPY;
558                         len = MIN(ZIL_MAX_LOG_DATA, size);
559                 }
560
561                 itx = zil_itx_create(TX_WRITE, sizeof (*lr) +
562                     (write_state == WR_COPIED ? len : 0));
563                 lr = (lr_write_t *)&itx->itx_lr;
564                 if (write_state == WR_COPIED && dmu_read(zv->zv_objset,
565                     ZVOL_OBJ, offset, len, lr+1, DMU_READ_NO_PREFETCH) != 0) {
566                         zil_itx_destroy(itx);
567                         itx = zil_itx_create(TX_WRITE, sizeof (*lr));
568                         lr = (lr_write_t *)&itx->itx_lr;
569                         write_state = WR_NEED_COPY;
570                 }
571
572                 itx->itx_wr_state = write_state;
573                 if (write_state == WR_NEED_COPY)
574                         itx->itx_sod += len;
575                 lr->lr_foid = ZVOL_OBJ;
576                 lr->lr_offset = offset;
577                 lr->lr_length = len;
578                 lr->lr_blkoff = 0;
579                 BP_ZERO(&lr->lr_blkptr);
580
581                 itx->itx_private = zv;
582                 itx->itx_sync = sync;
583
584                 (void) zil_itx_assign(zilog, itx, tx);
585
586                 offset += len;
587                 size -= len;
588         }
589 }
590
591 static int
592 zvol_write(struct bio *bio)
593 {
594         zvol_state_t *zv = bio->bi_bdev->bd_disk->private_data;
595         uint64_t offset = BIO_BI_SECTOR(bio) << 9;
596         uint64_t size = BIO_BI_SIZE(bio);
597         int error = 0;
598         dmu_tx_t *tx;
599         rl_t *rl;
600         uio_t uio;
601
602         if (bio->bi_rw & VDEV_REQ_FLUSH)
603                 zil_commit(zv->zv_zilog, ZVOL_OBJ);
604
605         /*
606          * Some requests are just for flush and nothing else.
607          */
608         if (size == 0)
609                 goto out;
610
611         uio.uio_bvec = &bio->bi_io_vec[BIO_BI_IDX(bio)];
612         uio.uio_skip = BIO_BI_SKIP(bio);
613         uio.uio_resid = size;
614         uio.uio_iovcnt = bio->bi_vcnt - BIO_BI_IDX(bio);
615         uio.uio_loffset = offset;
616         uio.uio_limit = MAXOFFSET_T;
617         uio.uio_segflg = UIO_BVEC;
618
619         rl = zfs_range_lock(&zv->zv_znode, offset, size, RL_WRITER);
620
621         tx = dmu_tx_create(zv->zv_objset);
622         dmu_tx_hold_write(tx, ZVOL_OBJ, offset, size);
623
624         /* This will only fail for ENOSPC */
625         error = dmu_tx_assign(tx, TXG_WAIT);
626         if (error) {
627                 dmu_tx_abort(tx);
628                 zfs_range_unlock(rl);
629                 goto out;
630         }
631
632         error = dmu_write_uio(zv->zv_objset, ZVOL_OBJ, &uio, size, tx);
633         if (error == 0)
634                 zvol_log_write(zv, tx, offset, size,
635                     !!(bio->bi_rw & VDEV_REQ_FUA));
636
637         dmu_tx_commit(tx);
638         zfs_range_unlock(rl);
639
640         if ((bio->bi_rw & VDEV_REQ_FUA) ||
641             zv->zv_objset->os_sync == ZFS_SYNC_ALWAYS)
642                 zil_commit(zv->zv_zilog, ZVOL_OBJ);
643
644 out:
645         return (error);
646 }
647
648 static int
649 zvol_discard(struct bio *bio)
650 {
651         zvol_state_t *zv = bio->bi_bdev->bd_disk->private_data;
652         uint64_t start = BIO_BI_SECTOR(bio) << 9;
653         uint64_t size = BIO_BI_SIZE(bio);
654         uint64_t end = start + size;
655         int error;
656         rl_t *rl;
657
658         if (end > zv->zv_volsize)
659                 return (SET_ERROR(EIO));
660
661         /*
662          * Align the request to volume block boundaries when REQ_SECURE is
663          * available, but not requested. If we don't, then this will force
664          * dnode_free_range() to zero out the unaligned parts, which is slow
665          * (read-modify-write) and useless since we are not freeing any space
666          * by doing so. Kernels that do not support REQ_SECURE (2.6.32 through
667          * 2.6.35) will not receive this optimization.
668          */
669 #ifdef REQ_SECURE
670         if (!(bio->bi_rw & REQ_SECURE)) {
671                 start = P2ROUNDUP(start, zv->zv_volblocksize);
672                 end = P2ALIGN(end, zv->zv_volblocksize);
673                 size = end - start;
674         }
675 #endif
676
677         if (start >= end)
678                 return (0);
679
680         rl = zfs_range_lock(&zv->zv_znode, start, size, RL_WRITER);
681
682         error = dmu_free_long_range(zv->zv_objset, ZVOL_OBJ, start, size);
683
684         /*
685          * TODO: maybe we should add the operation to the log.
686          */
687
688         zfs_range_unlock(rl);
689
690         return (error);
691 }
692
693 static int
694 zvol_read(struct bio *bio)
695 {
696         zvol_state_t *zv = bio->bi_bdev->bd_disk->private_data;
697         uint64_t offset = BIO_BI_SECTOR(bio) << 9;
698         uint64_t size = BIO_BI_SIZE(bio);
699         int error;
700         rl_t *rl;
701         uio_t uio;
702
703         if (size == 0)
704                 return (0);
705
706         uio.uio_bvec = &bio->bi_io_vec[BIO_BI_IDX(bio)];
707         uio.uio_skip = BIO_BI_SKIP(bio);
708         uio.uio_resid = size;
709         uio.uio_iovcnt = bio->bi_vcnt - BIO_BI_IDX(bio);
710         uio.uio_loffset = offset;
711         uio.uio_limit = MAXOFFSET_T;
712         uio.uio_segflg = UIO_BVEC;
713
714         rl = zfs_range_lock(&zv->zv_znode, offset, size, RL_READER);
715
716         error = dmu_read_uio(zv->zv_objset, ZVOL_OBJ, &uio, size);
717
718         zfs_range_unlock(rl);
719
720         /* convert checksum errors into IO errors */
721         if (error == ECKSUM)
722                 error = SET_ERROR(EIO);
723
724         return (error);
725 }
726
727 static MAKE_REQUEST_FN_RET
728 zvol_request(struct request_queue *q, struct bio *bio)
729 {
730         zvol_state_t *zv = q->queuedata;
731         fstrans_cookie_t cookie = spl_fstrans_mark();
732         uint64_t offset = BIO_BI_SECTOR(bio);
733         unsigned int sectors = bio_sectors(bio);
734         int rw = bio_data_dir(bio);
735 #ifdef HAVE_GENERIC_IO_ACCT
736         unsigned long start = jiffies;
737 #endif
738         int error = 0;
739
740         if (bio_has_data(bio) && offset + sectors >
741             get_capacity(zv->zv_disk)) {
742                 printk(KERN_INFO
743                     "%s: bad access: block=%llu, count=%lu\n",
744                     zv->zv_disk->disk_name,
745                     (long long unsigned)offset,
746                     (long unsigned)sectors);
747                 error = SET_ERROR(EIO);
748                 goto out1;
749         }
750
751         generic_start_io_acct(rw, sectors, &zv->zv_disk->part0);
752
753         if (rw == WRITE) {
754                 if (unlikely(zv->zv_flags & ZVOL_RDONLY)) {
755                         error = SET_ERROR(EROFS);
756                         goto out2;
757                 }
758
759                 if (bio->bi_rw & VDEV_REQ_DISCARD) {
760                         error = zvol_discard(bio);
761                         goto out2;
762                 }
763
764                 error = zvol_write(bio);
765         } else
766                 error = zvol_read(bio);
767
768 out2:
769         generic_end_io_acct(rw, &zv->zv_disk->part0, start);
770 out1:
771         BIO_END_IO(bio, -error);
772         spl_fstrans_unmark(cookie);
773 #ifdef HAVE_MAKE_REQUEST_FN_RET_INT
774         return (0);
775 #elif defined(HAVE_MAKE_REQUEST_FN_RET_QC)
776         return (BLK_QC_T_NONE);
777 #endif
778 }
779
780 static void
781 zvol_get_done(zgd_t *zgd, int error)
782 {
783         if (zgd->zgd_db)
784                 dmu_buf_rele(zgd->zgd_db, zgd);
785
786         zfs_range_unlock(zgd->zgd_rl);
787
788         if (error == 0 && zgd->zgd_bp)
789                 zil_add_block(zgd->zgd_zilog, zgd->zgd_bp);
790
791         kmem_free(zgd, sizeof (zgd_t));
792 }
793
794 /*
795  * Get data to generate a TX_WRITE intent log record.
796  */
797 static int
798 zvol_get_data(void *arg, lr_write_t *lr, char *buf, zio_t *zio)
799 {
800         zvol_state_t *zv = arg;
801         objset_t *os = zv->zv_objset;
802         uint64_t object = ZVOL_OBJ;
803         uint64_t offset = lr->lr_offset;
804         uint64_t size = lr->lr_length;
805         blkptr_t *bp = &lr->lr_blkptr;
806         dmu_buf_t *db;
807         zgd_t *zgd;
808         int error;
809
810         ASSERT(zio != NULL);
811         ASSERT(size != 0);
812
813         zgd = (zgd_t *)kmem_zalloc(sizeof (zgd_t), KM_SLEEP);
814         zgd->zgd_zilog = zv->zv_zilog;
815         zgd->zgd_rl = zfs_range_lock(&zv->zv_znode, offset, size, RL_READER);
816
817         /*
818          * Write records come in two flavors: immediate and indirect.
819          * For small writes it's cheaper to store the data with the
820          * log record (immediate); for large writes it's cheaper to
821          * sync the data and get a pointer to it (indirect) so that
822          * we don't have to write the data twice.
823          */
824         if (buf != NULL) { /* immediate write */
825                 error = dmu_read(os, object, offset, size, buf,
826                     DMU_READ_NO_PREFETCH);
827         } else {
828                 size = zv->zv_volblocksize;
829                 offset = P2ALIGN_TYPED(offset, size, uint64_t);
830                 error = dmu_buf_hold(os, object, offset, zgd, &db,
831                     DMU_READ_NO_PREFETCH);
832                 if (error == 0) {
833                         blkptr_t *obp = dmu_buf_get_blkptr(db);
834                         if (obp) {
835                                 ASSERT(BP_IS_HOLE(bp));
836                                 *bp = *obp;
837                         }
838
839                         zgd->zgd_db = db;
840                         zgd->zgd_bp = &lr->lr_blkptr;
841
842                         ASSERT(db != NULL);
843                         ASSERT(db->db_offset == offset);
844                         ASSERT(db->db_size == size);
845
846                         error = dmu_sync(zio, lr->lr_common.lrc_txg,
847                             zvol_get_done, zgd);
848
849                         if (error == 0)
850                                 return (0);
851                 }
852         }
853
854         zvol_get_done(zgd, error);
855
856         return (SET_ERROR(error));
857 }
858
859 /*
860  * The zvol_state_t's are inserted in increasing MINOR(dev_t) order.
861  */
862 static void
863 zvol_insert(zvol_state_t *zv_insert)
864 {
865         zvol_state_t *zv = NULL;
866
867         ASSERT(MUTEX_HELD(&zvol_state_lock));
868         ASSERT3U(MINOR(zv_insert->zv_dev) & ZVOL_MINOR_MASK, ==, 0);
869         for (zv = list_head(&zvol_state_list); zv != NULL;
870             zv = list_next(&zvol_state_list, zv)) {
871                 if (MINOR(zv->zv_dev) > MINOR(zv_insert->zv_dev))
872                         break;
873         }
874
875         list_insert_before(&zvol_state_list, zv, zv_insert);
876 }
877
878 /*
879  * Simply remove the zvol from to list of zvols.
880  */
881 static void
882 zvol_remove(zvol_state_t *zv_remove)
883 {
884         ASSERT(MUTEX_HELD(&zvol_state_lock));
885         list_remove(&zvol_state_list, zv_remove);
886 }
887
888 static int
889 zvol_first_open(zvol_state_t *zv)
890 {
891         objset_t *os;
892         uint64_t volsize;
893         int locked = 0;
894         int error;
895         uint64_t ro;
896
897         /*
898          * In all other cases the spa_namespace_lock is taken before the
899          * bdev->bd_mutex lock.  But in this case the Linux __blkdev_get()
900          * function calls fops->open() with the bdev->bd_mutex lock held.
901          *
902          * To avoid a potential lock inversion deadlock we preemptively
903          * try to take the spa_namespace_lock().  Normally it will not
904          * be contended and this is safe because spa_open_common() handles
905          * the case where the caller already holds the spa_namespace_lock.
906          *
907          * When it is contended we risk a lock inversion if we were to
908          * block waiting for the lock.  Luckily, the __blkdev_get()
909          * function allows us to return -ERESTARTSYS which will result in
910          * bdev->bd_mutex being dropped, reacquired, and fops->open() being
911          * called again.  This process can be repeated safely until both
912          * locks are acquired.
913          */
914         if (!mutex_owned(&spa_namespace_lock)) {
915                 locked = mutex_tryenter(&spa_namespace_lock);
916                 if (!locked)
917                         return (-SET_ERROR(ERESTARTSYS));
918         }
919
920         error = dsl_prop_get_integer(zv->zv_name, "readonly", &ro, NULL);
921         if (error)
922                 goto out_mutex;
923
924         /* lie and say we're read-only */
925         error = dmu_objset_own(zv->zv_name, DMU_OST_ZVOL, 1, zvol_tag, &os);
926         if (error)
927                 goto out_mutex;
928
929         error = zap_lookup(os, ZVOL_ZAP_OBJ, "size", 8, 1, &volsize);
930         if (error) {
931                 dmu_objset_disown(os, zvol_tag);
932                 goto out_mutex;
933         }
934
935         zv->zv_objset = os;
936         error = dmu_bonus_hold(os, ZVOL_OBJ, zvol_tag, &zv->zv_dbuf);
937         if (error) {
938                 dmu_objset_disown(os, zvol_tag);
939                 goto out_mutex;
940         }
941
942         set_capacity(zv->zv_disk, volsize >> 9);
943         zv->zv_volsize = volsize;
944         zv->zv_zilog = zil_open(os, zvol_get_data);
945
946         if (ro || dmu_objset_is_snapshot(os) ||
947             !spa_writeable(dmu_objset_spa(os))) {
948                 set_disk_ro(zv->zv_disk, 1);
949                 zv->zv_flags |= ZVOL_RDONLY;
950         } else {
951                 set_disk_ro(zv->zv_disk, 0);
952                 zv->zv_flags &= ~ZVOL_RDONLY;
953         }
954
955 out_mutex:
956         if (locked)
957                 mutex_exit(&spa_namespace_lock);
958
959         return (SET_ERROR(-error));
960 }
961
962 static void
963 zvol_last_close(zvol_state_t *zv)
964 {
965         zil_close(zv->zv_zilog);
966         zv->zv_zilog = NULL;
967
968         dmu_buf_rele(zv->zv_dbuf, zvol_tag);
969         zv->zv_dbuf = NULL;
970
971         /*
972          * Evict cached data
973          */
974         if (dsl_dataset_is_dirty(dmu_objset_ds(zv->zv_objset)) &&
975             !(zv->zv_flags & ZVOL_RDONLY))
976                 txg_wait_synced(dmu_objset_pool(zv->zv_objset), 0);
977         (void) dmu_objset_evict_dbufs(zv->zv_objset);
978
979         dmu_objset_disown(zv->zv_objset, zvol_tag);
980         zv->zv_objset = NULL;
981 }
982
983 static int
984 zvol_open(struct block_device *bdev, fmode_t flag)
985 {
986         zvol_state_t *zv = bdev->bd_disk->private_data;
987         int error = 0, drop_mutex = 0;
988
989         /*
990          * If the caller is already holding the mutex do not take it
991          * again, this will happen as part of zvol_create_minor().
992          * Once add_disk() is called the device is live and the kernel
993          * will attempt to open it to read the partition information.
994          */
995         if (!mutex_owned(&zvol_state_lock)) {
996                 mutex_enter(&zvol_state_lock);
997                 drop_mutex = 1;
998         }
999
1000         ASSERT3P(zv, !=, NULL);
1001
1002         if (zv->zv_open_count == 0) {
1003                 error = zvol_first_open(zv);
1004                 if (error)
1005                         goto out_mutex;
1006         }
1007
1008         if ((flag & FMODE_WRITE) && (zv->zv_flags & ZVOL_RDONLY)) {
1009                 error = -EROFS;
1010                 goto out_open_count;
1011         }
1012
1013         zv->zv_open_count++;
1014
1015 out_open_count:
1016         if (zv->zv_open_count == 0)
1017                 zvol_last_close(zv);
1018
1019 out_mutex:
1020         if (drop_mutex)
1021                 mutex_exit(&zvol_state_lock);
1022
1023         check_disk_change(bdev);
1024
1025         return (SET_ERROR(error));
1026 }
1027
1028 #ifdef HAVE_BLOCK_DEVICE_OPERATIONS_RELEASE_VOID
1029 static void
1030 #else
1031 static int
1032 #endif
1033 zvol_release(struct gendisk *disk, fmode_t mode)
1034 {
1035         zvol_state_t *zv = disk->private_data;
1036         int drop_mutex = 0;
1037
1038         if (!mutex_owned(&zvol_state_lock)) {
1039                 mutex_enter(&zvol_state_lock);
1040                 drop_mutex = 1;
1041         }
1042
1043         if (zv->zv_open_count > 0) {
1044                 zv->zv_open_count--;
1045                 if (zv->zv_open_count == 0)
1046                         zvol_last_close(zv);
1047         }
1048
1049         if (drop_mutex)
1050                 mutex_exit(&zvol_state_lock);
1051
1052 #ifndef HAVE_BLOCK_DEVICE_OPERATIONS_RELEASE_VOID
1053         return (0);
1054 #endif
1055 }
1056
1057 static int
1058 zvol_ioctl(struct block_device *bdev, fmode_t mode,
1059     unsigned int cmd, unsigned long arg)
1060 {
1061         zvol_state_t *zv = bdev->bd_disk->private_data;
1062         int error = 0;
1063
1064         if (zv == NULL)
1065                 return (SET_ERROR(-ENXIO));
1066
1067         switch (cmd) {
1068         case BLKFLSBUF:
1069                 zil_commit(zv->zv_zilog, ZVOL_OBJ);
1070                 break;
1071         case BLKZNAME:
1072                 error = copy_to_user((void *)arg, zv->zv_name, MAXNAMELEN);
1073                 break;
1074
1075         default:
1076                 error = -ENOTTY;
1077                 break;
1078
1079         }
1080
1081         return (SET_ERROR(error));
1082 }
1083
1084 #ifdef CONFIG_COMPAT
1085 static int
1086 zvol_compat_ioctl(struct block_device *bdev, fmode_t mode,
1087     unsigned cmd, unsigned long arg)
1088 {
1089         return (zvol_ioctl(bdev, mode, cmd, arg));
1090 }
1091 #else
1092 #define zvol_compat_ioctl       NULL
1093 #endif
1094
1095 static int zvol_media_changed(struct gendisk *disk)
1096 {
1097         zvol_state_t *zv = disk->private_data;
1098
1099         return (zv->zv_changed);
1100 }
1101
1102 static int zvol_revalidate_disk(struct gendisk *disk)
1103 {
1104         zvol_state_t *zv = disk->private_data;
1105
1106         zv->zv_changed = 0;
1107         set_capacity(zv->zv_disk, zv->zv_volsize >> 9);
1108
1109         return (0);
1110 }
1111
1112 /*
1113  * Provide a simple virtual geometry for legacy compatibility.  For devices
1114  * smaller than 1 MiB a small head and sector count is used to allow very
1115  * tiny devices.  For devices over 1 Mib a standard head and sector count
1116  * is used to keep the cylinders count reasonable.
1117  */
1118 static int
1119 zvol_getgeo(struct block_device *bdev, struct hd_geometry *geo)
1120 {
1121         zvol_state_t *zv = bdev->bd_disk->private_data;
1122         sector_t sectors = get_capacity(zv->zv_disk);
1123
1124         if (sectors > 2048) {
1125                 geo->heads = 16;
1126                 geo->sectors = 63;
1127         } else {
1128                 geo->heads = 2;
1129                 geo->sectors = 4;
1130         }
1131
1132         geo->start = 0;
1133         geo->cylinders = sectors / (geo->heads * geo->sectors);
1134
1135         return (0);
1136 }
1137
1138 static struct kobject *
1139 zvol_probe(dev_t dev, int *part, void *arg)
1140 {
1141         zvol_state_t *zv;
1142         struct kobject *kobj;
1143
1144         mutex_enter(&zvol_state_lock);
1145         zv = zvol_find_by_dev(dev);
1146         kobj = zv ? get_disk(zv->zv_disk) : NULL;
1147         mutex_exit(&zvol_state_lock);
1148
1149         return (kobj);
1150 }
1151
1152 #ifdef HAVE_BDEV_BLOCK_DEVICE_OPERATIONS
1153 static struct block_device_operations zvol_ops = {
1154         .open                   = zvol_open,
1155         .release                = zvol_release,
1156         .ioctl                  = zvol_ioctl,
1157         .compat_ioctl           = zvol_compat_ioctl,
1158         .media_changed          = zvol_media_changed,
1159         .revalidate_disk        = zvol_revalidate_disk,
1160         .getgeo                 = zvol_getgeo,
1161         .owner                  = THIS_MODULE,
1162 };
1163
1164 #else /* HAVE_BDEV_BLOCK_DEVICE_OPERATIONS */
1165
1166 static int
1167 zvol_open_by_inode(struct inode *inode, struct file *file)
1168 {
1169         return (zvol_open(inode->i_bdev, file->f_mode));
1170 }
1171
1172 static int
1173 zvol_release_by_inode(struct inode *inode, struct file *file)
1174 {
1175         return (zvol_release(inode->i_bdev->bd_disk, file->f_mode));
1176 }
1177
1178 static int
1179 zvol_ioctl_by_inode(struct inode *inode, struct file *file,
1180     unsigned int cmd, unsigned long arg)
1181 {
1182         if (file == NULL || inode == NULL)
1183                 return (SET_ERROR(-EINVAL));
1184
1185         return (zvol_ioctl(inode->i_bdev, file->f_mode, cmd, arg));
1186 }
1187
1188 #ifdef CONFIG_COMPAT
1189 static long
1190 zvol_compat_ioctl_by_inode(struct file *file,
1191     unsigned int cmd, unsigned long arg)
1192 {
1193         if (file == NULL)
1194                 return (SET_ERROR(-EINVAL));
1195
1196         return (zvol_compat_ioctl(file->f_dentry->d_inode->i_bdev,
1197             file->f_mode, cmd, arg));
1198 }
1199 #else
1200 #define zvol_compat_ioctl_by_inode      NULL
1201 #endif
1202
1203 static struct block_device_operations zvol_ops = {
1204         .open                   = zvol_open_by_inode,
1205         .release                = zvol_release_by_inode,
1206         .ioctl                  = zvol_ioctl_by_inode,
1207         .compat_ioctl           = zvol_compat_ioctl_by_inode,
1208         .media_changed          = zvol_media_changed,
1209         .revalidate_disk        = zvol_revalidate_disk,
1210         .getgeo                 = zvol_getgeo,
1211         .owner                  = THIS_MODULE,
1212 };
1213 #endif /* HAVE_BDEV_BLOCK_DEVICE_OPERATIONS */
1214
1215 /*
1216  * Allocate memory for a new zvol_state_t and setup the required
1217  * request queue and generic disk structures for the block device.
1218  */
1219 static zvol_state_t *
1220 zvol_alloc(dev_t dev, const char *name)
1221 {
1222         zvol_state_t *zv;
1223
1224         zv = kmem_zalloc(sizeof (zvol_state_t), KM_SLEEP);
1225
1226         list_link_init(&zv->zv_next);
1227
1228         zv->zv_queue = blk_alloc_queue(GFP_ATOMIC);
1229         if (zv->zv_queue == NULL)
1230                 goto out_kmem;
1231
1232         blk_queue_make_request(zv->zv_queue, zvol_request);
1233
1234 #ifdef HAVE_BLK_QUEUE_FLUSH
1235         blk_queue_flush(zv->zv_queue, VDEV_REQ_FLUSH | VDEV_REQ_FUA);
1236 #else
1237         blk_queue_ordered(zv->zv_queue, QUEUE_ORDERED_DRAIN, NULL);
1238 #endif /* HAVE_BLK_QUEUE_FLUSH */
1239
1240         zv->zv_disk = alloc_disk(ZVOL_MINORS);
1241         if (zv->zv_disk == NULL)
1242                 goto out_queue;
1243
1244         zv->zv_queue->queuedata = zv;
1245         zv->zv_dev = dev;
1246         zv->zv_open_count = 0;
1247         strlcpy(zv->zv_name, name, MAXNAMELEN);
1248
1249         mutex_init(&zv->zv_znode.z_range_lock, NULL, MUTEX_DEFAULT, NULL);
1250         avl_create(&zv->zv_znode.z_range_avl, zfs_range_compare,
1251             sizeof (rl_t), offsetof(rl_t, r_node));
1252         zv->zv_znode.z_is_zvol = TRUE;
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 = SET_ERROR(ENODEV);
1304         }
1305
1306         kmem_free(parent, MAXPATHLEN);
1307
1308         return (SET_ERROR(error));
1309 }
1310
1311 static int
1312 __zvol_create_minor(const char *name, boolean_t ignore_snapdev)
1313 {
1314         zvol_state_t *zv;
1315         objset_t *os;
1316         dmu_object_info_t *doi;
1317         uint64_t volsize;
1318         uint64_t len;
1319         unsigned minor = 0;
1320         int error = 0;
1321
1322         ASSERT(MUTEX_HELD(&zvol_state_lock));
1323
1324         zv = zvol_find_by_name(name);
1325         if (zv) {
1326                 error = SET_ERROR(EEXIST);
1327                 goto out;
1328         }
1329
1330         if (ignore_snapdev == B_FALSE) {
1331                 error = __zvol_snapdev_hidden(name);
1332                 if (error)
1333                         goto out;
1334         }
1335
1336         doi = kmem_alloc(sizeof (dmu_object_info_t), KM_SLEEP);
1337
1338         error = dmu_objset_own(name, DMU_OST_ZVOL, B_TRUE, zvol_tag, &os);
1339         if (error)
1340                 goto out_doi;
1341
1342         error = dmu_object_info(os, ZVOL_OBJ, doi);
1343         if (error)
1344                 goto out_dmu_objset_disown;
1345
1346         error = zap_lookup(os, ZVOL_ZAP_OBJ, "size", 8, 1, &volsize);
1347         if (error)
1348                 goto out_dmu_objset_disown;
1349
1350         error = zvol_find_minor(&minor);
1351         if (error)
1352                 goto out_dmu_objset_disown;
1353
1354         zv = zvol_alloc(MKDEV(zvol_major, minor), name);
1355         if (zv == NULL) {
1356                 error = SET_ERROR(EAGAIN);
1357                 goto out_dmu_objset_disown;
1358         }
1359
1360         if (dmu_objset_is_snapshot(os))
1361                 zv->zv_flags |= ZVOL_RDONLY;
1362
1363         zv->zv_volblocksize = doi->doi_data_block_size;
1364         zv->zv_volsize = volsize;
1365         zv->zv_objset = os;
1366
1367         set_capacity(zv->zv_disk, zv->zv_volsize >> 9);
1368
1369         blk_queue_max_hw_sectors(zv->zv_queue, (DMU_MAX_ACCESS / 4) >> 9);
1370         blk_queue_max_segments(zv->zv_queue, UINT16_MAX);
1371         blk_queue_max_segment_size(zv->zv_queue, UINT_MAX);
1372         blk_queue_physical_block_size(zv->zv_queue, zv->zv_volblocksize);
1373         blk_queue_io_opt(zv->zv_queue, zv->zv_volblocksize);
1374         blk_queue_max_discard_sectors(zv->zv_queue,
1375             (zvol_max_discard_blocks * zv->zv_volblocksize) >> 9);
1376         blk_queue_discard_granularity(zv->zv_queue, zv->zv_volblocksize);
1377         queue_flag_set_unlocked(QUEUE_FLAG_DISCARD, zv->zv_queue);
1378 #ifdef QUEUE_FLAG_NONROT
1379         queue_flag_set_unlocked(QUEUE_FLAG_NONROT, zv->zv_queue);
1380 #endif
1381 #ifdef QUEUE_FLAG_ADD_RANDOM
1382         queue_flag_clear_unlocked(QUEUE_FLAG_ADD_RANDOM, zv->zv_queue);
1383 #endif
1384
1385         if (spa_writeable(dmu_objset_spa(os))) {
1386                 if (zil_replay_disable)
1387                         zil_destroy(dmu_objset_zil(os), B_FALSE);
1388                 else
1389                         zil_replay(os, zv, zvol_replay_vector);
1390         }
1391
1392         /*
1393          * When udev detects the addition of the device it will immediately
1394          * invoke blkid(8) to determine the type of content on the device.
1395          * Prefetching the blocks commonly scanned by blkid(8) will speed
1396          * up this process.
1397          */
1398         len = MIN(MAX(zvol_prefetch_bytes, 0), SPA_MAXBLOCKSIZE);
1399         if (len > 0) {
1400                 dmu_prefetch(os, ZVOL_OBJ, 0, len);
1401                 dmu_prefetch(os, ZVOL_OBJ, volsize - len, len);
1402         }
1403
1404         zv->zv_objset = NULL;
1405 out_dmu_objset_disown:
1406         dmu_objset_disown(os, zvol_tag);
1407 out_doi:
1408         kmem_free(doi, sizeof (dmu_object_info_t));
1409 out:
1410
1411         if (error == 0) {
1412                 zvol_insert(zv);
1413                 add_disk(zv->zv_disk);
1414         }
1415
1416         return (SET_ERROR(error));
1417 }
1418
1419 /*
1420  * Create a block device minor node and setup the linkage between it
1421  * and the specified volume.  Once this function returns the block
1422  * device is live and ready for use.
1423  */
1424 int
1425 zvol_create_minor(const char *name)
1426 {
1427         int error;
1428
1429         mutex_enter(&zvol_state_lock);
1430         error = __zvol_create_minor(name, B_FALSE);
1431         mutex_exit(&zvol_state_lock);
1432
1433         return (SET_ERROR(error));
1434 }
1435
1436 static int
1437 __zvol_remove_minor(const char *name)
1438 {
1439         zvol_state_t *zv;
1440
1441         ASSERT(MUTEX_HELD(&zvol_state_lock));
1442
1443         zv = zvol_find_by_name(name);
1444         if (zv == NULL)
1445                 return (SET_ERROR(ENXIO));
1446
1447         if (zv->zv_open_count > 0)
1448                 return (SET_ERROR(EBUSY));
1449
1450         zvol_remove(zv);
1451         zvol_free(zv);
1452
1453         return (0);
1454 }
1455
1456 /*
1457  * Remove a block device minor node for the specified volume.
1458  */
1459 int
1460 zvol_remove_minor(const char *name)
1461 {
1462         int error;
1463
1464         mutex_enter(&zvol_state_lock);
1465         error = __zvol_remove_minor(name);
1466         mutex_exit(&zvol_state_lock);
1467
1468         return (SET_ERROR(error));
1469 }
1470
1471 /*
1472  * Rename a block device minor mode for the specified volume.
1473  */
1474 static void
1475 __zvol_rename_minor(zvol_state_t *zv, const char *newname)
1476 {
1477         int readonly = get_disk_ro(zv->zv_disk);
1478
1479         ASSERT(MUTEX_HELD(&zvol_state_lock));
1480
1481         strlcpy(zv->zv_name, newname, sizeof (zv->zv_name));
1482
1483         /*
1484          * The block device's read-only state is briefly changed causing
1485          * a KOBJ_CHANGE uevent to be issued.  This ensures udev detects
1486          * the name change and fixes the symlinks.  This does not change
1487          * ZVOL_RDONLY in zv->zv_flags so the actual read-only state never
1488          * changes.  This would normally be done using kobject_uevent() but
1489          * that is a GPL-only symbol which is why we need this workaround.
1490          */
1491         set_disk_ro(zv->zv_disk, !readonly);
1492         set_disk_ro(zv->zv_disk, readonly);
1493 }
1494
1495 static int
1496 zvol_create_minors_cb(const char *dsname, void *arg)
1497 {
1498         (void) zvol_create_minor(dsname);
1499
1500         return (0);
1501 }
1502
1503 /*
1504  * Create minors for specified dataset including children and snapshots.
1505  */
1506 int
1507 zvol_create_minors(const char *name)
1508 {
1509         int error = 0;
1510
1511         if (!zvol_inhibit_dev)
1512                 error = dmu_objset_find((char *)name, zvol_create_minors_cb,
1513                     NULL, DS_FIND_CHILDREN | DS_FIND_SNAPSHOTS);
1514
1515         return (SET_ERROR(error));
1516 }
1517
1518 /*
1519  * Remove minors for specified dataset including children and snapshots.
1520  */
1521 void
1522 zvol_remove_minors(const char *name)
1523 {
1524         zvol_state_t *zv, *zv_next;
1525         int namelen = ((name) ? strlen(name) : 0);
1526
1527         if (zvol_inhibit_dev)
1528                 return;
1529
1530         mutex_enter(&zvol_state_lock);
1531
1532         for (zv = list_head(&zvol_state_list); zv != NULL; zv = zv_next) {
1533                 zv_next = list_next(&zvol_state_list, zv);
1534
1535                 if (name == NULL || strcmp(zv->zv_name, name) == 0 ||
1536                     (strncmp(zv->zv_name, name, namelen) == 0 &&
1537                     zv->zv_name[namelen] == '/')) {
1538                         zvol_remove(zv);
1539                         zvol_free(zv);
1540                 }
1541         }
1542
1543         mutex_exit(&zvol_state_lock);
1544 }
1545
1546 /*
1547  * Rename minors for specified dataset including children and snapshots.
1548  */
1549 void
1550 zvol_rename_minors(const char *oldname, const char *newname)
1551 {
1552         zvol_state_t *zv, *zv_next;
1553         int oldnamelen, newnamelen;
1554         char *name;
1555
1556         if (zvol_inhibit_dev)
1557                 return;
1558
1559         oldnamelen = strlen(oldname);
1560         newnamelen = strlen(newname);
1561         name = kmem_alloc(MAXNAMELEN, KM_SLEEP);
1562
1563         mutex_enter(&zvol_state_lock);
1564
1565         for (zv = list_head(&zvol_state_list); zv != NULL; zv = zv_next) {
1566                 zv_next = list_next(&zvol_state_list, zv);
1567
1568                 if (strcmp(zv->zv_name, oldname) == 0) {
1569                         __zvol_rename_minor(zv, newname);
1570                 } else if (strncmp(zv->zv_name, oldname, oldnamelen) == 0 &&
1571                     (zv->zv_name[oldnamelen] == '/' ||
1572                     zv->zv_name[oldnamelen] == '@')) {
1573                         snprintf(name, MAXNAMELEN, "%s%c%s", newname,
1574                             zv->zv_name[oldnamelen],
1575                             zv->zv_name + oldnamelen + 1);
1576                         __zvol_rename_minor(zv, name);
1577                 }
1578         }
1579
1580         mutex_exit(&zvol_state_lock);
1581
1582         kmem_free(name, MAXNAMELEN);
1583 }
1584
1585 static int
1586 snapdev_snapshot_changed_cb(const char *dsname, void *arg) {
1587         uint64_t snapdev = *(uint64_t *) arg;
1588
1589         if (strchr(dsname, '@') == NULL)
1590                 return (0);
1591
1592         switch (snapdev) {
1593                 case ZFS_SNAPDEV_VISIBLE:
1594                         mutex_enter(&zvol_state_lock);
1595                         (void) __zvol_create_minor(dsname, B_TRUE);
1596                         mutex_exit(&zvol_state_lock);
1597                         break;
1598                 case ZFS_SNAPDEV_HIDDEN:
1599                         (void) zvol_remove_minor(dsname);
1600                         break;
1601         }
1602
1603         return (0);
1604 }
1605
1606 int
1607 zvol_set_snapdev(const char *dsname, uint64_t snapdev) {
1608         (void) dmu_objset_find((char *) dsname, snapdev_snapshot_changed_cb,
1609                 &snapdev, DS_FIND_SNAPSHOTS | DS_FIND_CHILDREN);
1610         /* caller should continue to modify snapdev property */
1611         return (-1);
1612 }
1613
1614 int
1615 zvol_init(void)
1616 {
1617         int error;
1618
1619         list_create(&zvol_state_list, sizeof (zvol_state_t),
1620             offsetof(zvol_state_t, zv_next));
1621
1622         mutex_init(&zvol_state_lock, NULL, MUTEX_DEFAULT, NULL);
1623
1624         error = register_blkdev(zvol_major, ZVOL_DRIVER);
1625         if (error) {
1626                 printk(KERN_INFO "ZFS: register_blkdev() failed %d\n", error);
1627                 goto out;
1628         }
1629
1630         blk_register_region(MKDEV(zvol_major, 0), 1UL << MINORBITS,
1631             THIS_MODULE, zvol_probe, NULL, NULL);
1632
1633         return (0);
1634
1635 out:
1636         mutex_destroy(&zvol_state_lock);
1637         list_destroy(&zvol_state_list);
1638
1639         return (SET_ERROR(error));
1640 }
1641
1642 void
1643 zvol_fini(void)
1644 {
1645         zvol_remove_minors(NULL);
1646         blk_unregister_region(MKDEV(zvol_major, 0), 1UL << MINORBITS);
1647         unregister_blkdev(zvol_major, ZVOL_DRIVER);
1648         mutex_destroy(&zvol_state_lock);
1649         list_destroy(&zvol_state_list);
1650 }
1651
1652 module_param(zvol_inhibit_dev, uint, 0644);
1653 MODULE_PARM_DESC(zvol_inhibit_dev, "Do not create zvol device nodes");
1654
1655 module_param(zvol_major, uint, 0444);
1656 MODULE_PARM_DESC(zvol_major, "Major number for zvol device");
1657
1658 module_param(zvol_max_discard_blocks, ulong, 0444);
1659 MODULE_PARM_DESC(zvol_max_discard_blocks, "Max number of blocks to discard");
1660
1661 module_param(zvol_prefetch_bytes, uint, 0644);
1662 MODULE_PARM_DESC(zvol_prefetch_bytes, "Prefetch N bytes at zvol start+end");