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