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