]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - module/zfs/zvol.c
ZTS: Fix mmp_interval failure
[FreeBSD/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  * Copyright (c) 2012, 2019 by Delphix. All rights reserved.
40  */
41
42 /*
43  * Note on locking of zvol state structures.
44  *
45  * These structures are used to maintain internal state used to emulate block
46  * devices on top of zvols. In particular, management of device minor number
47  * operations - create, remove, rename, and set_snapdev - involves access to
48  * these structures. The zvol_state_lock is primarily used to protect the
49  * zvol_state_list. The zv->zv_state_lock is used to protect the contents
50  * of the zvol_state_t structures, as well as to make sure that when the
51  * time comes to remove the structure from the list, it is not in use, and
52  * therefore, it can be taken off zvol_state_list and freed.
53  *
54  * The zv_suspend_lock was introduced to allow for suspending I/O to a zvol,
55  * e.g. for the duration of receive and rollback operations. This lock can be
56  * held for significant periods of time. Given that it is undesirable to hold
57  * mutexes for long periods of time, the following lock ordering applies:
58  * - take zvol_state_lock if necessary, to protect zvol_state_list
59  * - take zv_suspend_lock if necessary, by the code path in question
60  * - take zv_state_lock to protect zvol_state_t
61  *
62  * The minor operations are issued to spa->spa_zvol_taskq queues, that are
63  * single-threaded (to preserve order of minor operations), and are executed
64  * through the zvol_task_cb that dispatches the specific operations. Therefore,
65  * these operations are serialized per pool. Consequently, we can be certain
66  * that for a given zvol, there is only one operation at a time in progress.
67  * That is why one can be sure that first, zvol_state_t for a given zvol is
68  * allocated and placed on zvol_state_list, and then other minor operations
69  * for this zvol are going to proceed in the order of issue.
70  *
71  * It is also worth keeping in mind that once add_disk() is called, the zvol is
72  * announced to the world, and zvol_open()/zvol_release() can be called at any
73  * time. Incidentally, add_disk() itself calls zvol_open()->zvol_first_open()
74  * and zvol_release()->zvol_last_close() directly as well.
75  */
76
77 #include <sys/dataset_kstats.h>
78 #include <sys/dbuf.h>
79 #include <sys/dmu_traverse.h>
80 #include <sys/dsl_dataset.h>
81 #include <sys/dsl_prop.h>
82 #include <sys/dsl_dir.h>
83 #include <sys/zap.h>
84 #include <sys/zfeature.h>
85 #include <sys/zil_impl.h>
86 #include <sys/dmu_tx.h>
87 #include <sys/zio.h>
88 #include <sys/zfs_rlock.h>
89 #include <sys/spa_impl.h>
90 #include <sys/zvol.h>
91
92 #include <linux/blkdev_compat.h>
93 #include <linux/task_io_accounting_ops.h>
94
95 unsigned int zvol_inhibit_dev = 0;
96 unsigned int zvol_major = ZVOL_MAJOR;
97 unsigned int zvol_threads = 32;
98 unsigned int zvol_request_sync = 0;
99 unsigned int zvol_prefetch_bytes = (128 * 1024);
100 unsigned long zvol_max_discard_blocks = 16384;
101 unsigned int zvol_volmode = ZFS_VOLMODE_GEOM;
102
103 static taskq_t *zvol_taskq;
104 static krwlock_t zvol_state_lock;
105 static list_t zvol_state_list;
106
107 #define ZVOL_HT_SIZE    1024
108 static struct hlist_head *zvol_htable;
109 #define ZVOL_HT_HEAD(hash)      (&zvol_htable[(hash) & (ZVOL_HT_SIZE-1)])
110
111 static struct ida zvol_ida;
112
113 /*
114  * The in-core state of each volume.
115  */
116 struct zvol_state {
117         char                    zv_name[MAXNAMELEN];    /* name */
118         uint64_t                zv_volsize;             /* advertised space */
119         uint64_t                zv_volblocksize;        /* volume block size */
120         objset_t                *zv_objset;     /* objset handle */
121         uint32_t                zv_flags;       /* ZVOL_* flags */
122         uint32_t                zv_open_count;  /* open counts */
123         uint32_t                zv_changed;     /* disk changed */
124         zilog_t                 *zv_zilog;      /* ZIL handle */
125         rangelock_t             zv_rangelock;   /* for range locking */
126         dnode_t                 *zv_dn;         /* dnode hold */
127         dev_t                   zv_dev;         /* device id */
128         struct gendisk          *zv_disk;       /* generic disk */
129         struct request_queue    *zv_queue;      /* request queue */
130         dataset_kstats_t        zv_kstat;       /* zvol kstats */
131         list_node_t             zv_next;        /* next zvol_state_t linkage */
132         uint64_t                zv_hash;        /* name hash */
133         struct hlist_node       zv_hlink;       /* hash link */
134         kmutex_t                zv_state_lock;  /* protects zvol_state_t */
135         atomic_t                zv_suspend_ref; /* refcount for suspend */
136         krwlock_t               zv_suspend_lock;        /* suspend lock */
137 };
138
139 typedef enum {
140         ZVOL_ASYNC_CREATE_MINORS,
141         ZVOL_ASYNC_REMOVE_MINORS,
142         ZVOL_ASYNC_RENAME_MINORS,
143         ZVOL_ASYNC_SET_SNAPDEV,
144         ZVOL_ASYNC_SET_VOLMODE,
145         ZVOL_ASYNC_MAX
146 } zvol_async_op_t;
147
148 typedef struct {
149         zvol_async_op_t op;
150         char pool[MAXNAMELEN];
151         char name1[MAXNAMELEN];
152         char name2[MAXNAMELEN];
153         zprop_source_t source;
154         uint64_t value;
155 } zvol_task_t;
156
157 #define ZVOL_RDONLY     0x1
158 /*
159  * Whether the zvol has been written to (as opposed to ZVOL_RDONLY, which
160  * specifies whether or not the zvol _can_ be written to)
161  */
162 #define ZVOL_WRITTEN_TO 0x2
163
164 static uint64_t
165 zvol_name_hash(const char *name)
166 {
167         int i;
168         uint64_t crc = -1ULL;
169         uint8_t *p = (uint8_t *)name;
170         ASSERT(zfs_crc64_table[128] == ZFS_CRC64_POLY);
171         for (i = 0; i < MAXNAMELEN - 1 && *p; i++, p++) {
172                 crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ (*p)) & 0xFF];
173         }
174         return (crc);
175 }
176
177 /*
178  * Find a zvol_state_t given the full major+minor dev_t. If found,
179  * return with zv_state_lock taken, otherwise, return (NULL) without
180  * taking zv_state_lock.
181  */
182 static zvol_state_t *
183 zvol_find_by_dev(dev_t dev)
184 {
185         zvol_state_t *zv;
186
187         rw_enter(&zvol_state_lock, RW_READER);
188         for (zv = list_head(&zvol_state_list); zv != NULL;
189             zv = list_next(&zvol_state_list, zv)) {
190                 mutex_enter(&zv->zv_state_lock);
191                 if (zv->zv_dev == dev) {
192                         rw_exit(&zvol_state_lock);
193                         return (zv);
194                 }
195                 mutex_exit(&zv->zv_state_lock);
196         }
197         rw_exit(&zvol_state_lock);
198
199         return (NULL);
200 }
201
202 /*
203  * Find a zvol_state_t given the name and hash generated by zvol_name_hash.
204  * If found, return with zv_suspend_lock and zv_state_lock taken, otherwise,
205  * return (NULL) without the taking locks. The zv_suspend_lock is always taken
206  * before zv_state_lock. The mode argument indicates the mode (including none)
207  * for zv_suspend_lock to be taken.
208  */
209 static zvol_state_t *
210 zvol_find_by_name_hash(const char *name, uint64_t hash, int mode)
211 {
212         zvol_state_t *zv;
213         struct hlist_node *p = NULL;
214
215         rw_enter(&zvol_state_lock, RW_READER);
216         hlist_for_each(p, ZVOL_HT_HEAD(hash)) {
217                 zv = hlist_entry(p, zvol_state_t, zv_hlink);
218                 mutex_enter(&zv->zv_state_lock);
219                 if (zv->zv_hash == hash &&
220                     strncmp(zv->zv_name, name, MAXNAMELEN) == 0) {
221                         /*
222                          * this is the right zvol, take the locks in the
223                          * right order
224                          */
225                         if (mode != RW_NONE &&
226                             !rw_tryenter(&zv->zv_suspend_lock, mode)) {
227                                 mutex_exit(&zv->zv_state_lock);
228                                 rw_enter(&zv->zv_suspend_lock, mode);
229                                 mutex_enter(&zv->zv_state_lock);
230                                 /*
231                                  * zvol cannot be renamed as we continue
232                                  * to hold zvol_state_lock
233                                  */
234                                 ASSERT(zv->zv_hash == hash &&
235                                     strncmp(zv->zv_name, name, MAXNAMELEN)
236                                     == 0);
237                         }
238                         rw_exit(&zvol_state_lock);
239                         return (zv);
240                 }
241                 mutex_exit(&zv->zv_state_lock);
242         }
243         rw_exit(&zvol_state_lock);
244
245         return (NULL);
246 }
247
248 /*
249  * Find a zvol_state_t given the name.
250  * If found, return with zv_suspend_lock and zv_state_lock taken, otherwise,
251  * return (NULL) without the taking locks. The zv_suspend_lock is always taken
252  * before zv_state_lock. The mode argument indicates the mode (including none)
253  * for zv_suspend_lock to be taken.
254  */
255 static zvol_state_t *
256 zvol_find_by_name(const char *name, int mode)
257 {
258         return (zvol_find_by_name_hash(name, zvol_name_hash(name), mode));
259 }
260
261
262 /*
263  * Given a path, return TRUE if path is a ZVOL.
264  */
265 boolean_t
266 zvol_is_zvol(const char *device)
267 {
268         struct block_device *bdev;
269         unsigned int major;
270
271         bdev = vdev_lookup_bdev(device);
272         if (IS_ERR(bdev))
273                 return (B_FALSE);
274
275         major = MAJOR(bdev->bd_dev);
276         bdput(bdev);
277
278         if (major == zvol_major)
279                 return (B_TRUE);
280
281         return (B_FALSE);
282 }
283
284 /*
285  * ZFS_IOC_CREATE callback handles dmu zvol and zap object creation.
286  */
287 void
288 zvol_create_cb(objset_t *os, void *arg, cred_t *cr, dmu_tx_t *tx)
289 {
290         zfs_creat_t *zct = arg;
291         nvlist_t *nvprops = zct->zct_props;
292         int error;
293         uint64_t volblocksize, volsize;
294
295         VERIFY(nvlist_lookup_uint64(nvprops,
296             zfs_prop_to_name(ZFS_PROP_VOLSIZE), &volsize) == 0);
297         if (nvlist_lookup_uint64(nvprops,
298             zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE), &volblocksize) != 0)
299                 volblocksize = zfs_prop_default_numeric(ZFS_PROP_VOLBLOCKSIZE);
300
301         /*
302          * These properties must be removed from the list so the generic
303          * property setting step won't apply to them.
304          */
305         VERIFY(nvlist_remove_all(nvprops,
306             zfs_prop_to_name(ZFS_PROP_VOLSIZE)) == 0);
307         (void) nvlist_remove_all(nvprops,
308             zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE));
309
310         error = dmu_object_claim(os, ZVOL_OBJ, DMU_OT_ZVOL, volblocksize,
311             DMU_OT_NONE, 0, tx);
312         ASSERT(error == 0);
313
314         error = zap_create_claim(os, ZVOL_ZAP_OBJ, DMU_OT_ZVOL_PROP,
315             DMU_OT_NONE, 0, tx);
316         ASSERT(error == 0);
317
318         error = zap_update(os, ZVOL_ZAP_OBJ, "size", 8, 1, &volsize, tx);
319         ASSERT(error == 0);
320 }
321
322 /*
323  * ZFS_IOC_OBJSET_STATS entry point.
324  */
325 int
326 zvol_get_stats(objset_t *os, nvlist_t *nv)
327 {
328         int error;
329         dmu_object_info_t *doi;
330         uint64_t val;
331
332         error = zap_lookup(os, ZVOL_ZAP_OBJ, "size", 8, 1, &val);
333         if (error)
334                 return (SET_ERROR(error));
335
336         dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_VOLSIZE, val);
337         doi = kmem_alloc(sizeof (dmu_object_info_t), KM_SLEEP);
338         error = dmu_object_info(os, ZVOL_OBJ, doi);
339
340         if (error == 0) {
341                 dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_VOLBLOCKSIZE,
342                     doi->doi_data_block_size);
343         }
344
345         kmem_free(doi, sizeof (dmu_object_info_t));
346
347         return (SET_ERROR(error));
348 }
349
350 /*
351  * Sanity check volume size.
352  */
353 int
354 zvol_check_volsize(uint64_t volsize, uint64_t blocksize)
355 {
356         if (volsize == 0)
357                 return (SET_ERROR(EINVAL));
358
359         if (volsize % blocksize != 0)
360                 return (SET_ERROR(EINVAL));
361
362 #ifdef _ILP32
363         if (volsize - 1 > SPEC_MAXOFFSET_T)
364                 return (SET_ERROR(EOVERFLOW));
365 #endif
366         return (0);
367 }
368
369 /*
370  * Ensure the zap is flushed then inform the VFS of the capacity change.
371  */
372 static int
373 zvol_update_volsize(uint64_t volsize, objset_t *os)
374 {
375         dmu_tx_t *tx;
376         int error;
377         uint64_t txg;
378
379         tx = dmu_tx_create(os);
380         dmu_tx_hold_zap(tx, ZVOL_ZAP_OBJ, TRUE, NULL);
381         dmu_tx_mark_netfree(tx);
382         error = dmu_tx_assign(tx, TXG_WAIT);
383         if (error) {
384                 dmu_tx_abort(tx);
385                 return (SET_ERROR(error));
386         }
387         txg = dmu_tx_get_txg(tx);
388
389         error = zap_update(os, ZVOL_ZAP_OBJ, "size", 8, 1,
390             &volsize, tx);
391         dmu_tx_commit(tx);
392
393         txg_wait_synced(dmu_objset_pool(os), txg);
394
395         if (error == 0)
396                 error = dmu_free_long_range(os,
397                     ZVOL_OBJ, volsize, DMU_OBJECT_END);
398
399         return (error);
400 }
401
402 /*
403  * Set ZFS_PROP_VOLSIZE set entry point.  Note that modifying the volume
404  * size will result in a udev "change" event being generated.
405  */
406 int
407 zvol_set_volsize(const char *name, uint64_t volsize)
408 {
409         objset_t *os = NULL;
410         struct gendisk *disk = NULL;
411         uint64_t readonly;
412         int error;
413         boolean_t owned = B_FALSE;
414
415         error = dsl_prop_get_integer(name,
416             zfs_prop_to_name(ZFS_PROP_READONLY), &readonly, NULL);
417         if (error != 0)
418                 return (SET_ERROR(error));
419         if (readonly)
420                 return (SET_ERROR(EROFS));
421
422         zvol_state_t *zv = zvol_find_by_name(name, RW_READER);
423
424         ASSERT(zv == NULL || (MUTEX_HELD(&zv->zv_state_lock) &&
425             RW_READ_HELD(&zv->zv_suspend_lock)));
426
427         if (zv == NULL || zv->zv_objset == NULL) {
428                 if (zv != NULL)
429                         rw_exit(&zv->zv_suspend_lock);
430                 if ((error = dmu_objset_own(name, DMU_OST_ZVOL, B_FALSE, B_TRUE,
431                     FTAG, &os)) != 0) {
432                         if (zv != NULL)
433                                 mutex_exit(&zv->zv_state_lock);
434                         return (SET_ERROR(error));
435                 }
436                 owned = B_TRUE;
437                 if (zv != NULL)
438                         zv->zv_objset = os;
439         } else {
440                 os = zv->zv_objset;
441         }
442
443         dmu_object_info_t *doi = kmem_alloc(sizeof (*doi), KM_SLEEP);
444
445         if ((error = dmu_object_info(os, ZVOL_OBJ, doi)) ||
446             (error = zvol_check_volsize(volsize, doi->doi_data_block_size)))
447                 goto out;
448
449         error = zvol_update_volsize(volsize, os);
450         if (error == 0 && zv != NULL) {
451                 zv->zv_volsize = volsize;
452                 zv->zv_changed = 1;
453                 disk = zv->zv_disk;
454         }
455 out:
456         kmem_free(doi, sizeof (dmu_object_info_t));
457
458         if (owned) {
459                 dmu_objset_disown(os, B_TRUE, FTAG);
460                 if (zv != NULL)
461                         zv->zv_objset = NULL;
462         } else {
463                 rw_exit(&zv->zv_suspend_lock);
464         }
465
466         if (zv != NULL)
467                 mutex_exit(&zv->zv_state_lock);
468
469         if (disk != NULL)
470                 revalidate_disk(disk);
471
472         return (SET_ERROR(error));
473 }
474
475 /*
476  * Sanity check volume block size.
477  */
478 int
479 zvol_check_volblocksize(const char *name, uint64_t volblocksize)
480 {
481         /* Record sizes above 128k need the feature to be enabled */
482         if (volblocksize > SPA_OLD_MAXBLOCKSIZE) {
483                 spa_t *spa;
484                 int error;
485
486                 if ((error = spa_open(name, &spa, FTAG)) != 0)
487                         return (error);
488
489                 if (!spa_feature_is_enabled(spa, SPA_FEATURE_LARGE_BLOCKS)) {
490                         spa_close(spa, FTAG);
491                         return (SET_ERROR(ENOTSUP));
492                 }
493
494                 /*
495                  * We don't allow setting the property above 1MB,
496                  * unless the tunable has been changed.
497                  */
498                 if (volblocksize > zfs_max_recordsize)
499                         return (SET_ERROR(EDOM));
500
501                 spa_close(spa, FTAG);
502         }
503
504         if (volblocksize < SPA_MINBLOCKSIZE ||
505             volblocksize > SPA_MAXBLOCKSIZE ||
506             !ISP2(volblocksize))
507                 return (SET_ERROR(EDOM));
508
509         return (0);
510 }
511
512 /*
513  * Set ZFS_PROP_VOLBLOCKSIZE set entry point.
514  */
515 int
516 zvol_set_volblocksize(const char *name, uint64_t volblocksize)
517 {
518         zvol_state_t *zv;
519         dmu_tx_t *tx;
520         int error;
521
522         zv = zvol_find_by_name(name, RW_READER);
523
524         if (zv == NULL)
525                 return (SET_ERROR(ENXIO));
526
527         ASSERT(MUTEX_HELD(&zv->zv_state_lock));
528         ASSERT(RW_READ_HELD(&zv->zv_suspend_lock));
529
530         if (zv->zv_flags & ZVOL_RDONLY) {
531                 mutex_exit(&zv->zv_state_lock);
532                 rw_exit(&zv->zv_suspend_lock);
533                 return (SET_ERROR(EROFS));
534         }
535
536         tx = dmu_tx_create(zv->zv_objset);
537         dmu_tx_hold_bonus(tx, ZVOL_OBJ);
538         error = dmu_tx_assign(tx, TXG_WAIT);
539         if (error) {
540                 dmu_tx_abort(tx);
541         } else {
542                 error = dmu_object_set_blocksize(zv->zv_objset, ZVOL_OBJ,
543                     volblocksize, 0, tx);
544                 if (error == ENOTSUP)
545                         error = SET_ERROR(EBUSY);
546                 dmu_tx_commit(tx);
547                 if (error == 0)
548                         zv->zv_volblocksize = volblocksize;
549         }
550
551         mutex_exit(&zv->zv_state_lock);
552         rw_exit(&zv->zv_suspend_lock);
553
554         return (SET_ERROR(error));
555 }
556
557 /*
558  * Replay a TX_TRUNCATE ZIL transaction if asked.  TX_TRUNCATE is how we
559  * implement DKIOCFREE/free-long-range.
560  */
561 static int
562 zvol_replay_truncate(void *arg1, void *arg2, boolean_t byteswap)
563 {
564         zvol_state_t *zv = arg1;
565         lr_truncate_t *lr = arg2;
566         uint64_t offset, length;
567
568         if (byteswap)
569                 byteswap_uint64_array(lr, sizeof (*lr));
570
571         offset = lr->lr_offset;
572         length = lr->lr_length;
573
574         return (dmu_free_long_range(zv->zv_objset, ZVOL_OBJ, offset, length));
575 }
576
577 /*
578  * Replay a TX_WRITE ZIL transaction that didn't get committed
579  * after a system failure
580  */
581 static int
582 zvol_replay_write(void *arg1, void *arg2, boolean_t byteswap)
583 {
584         zvol_state_t *zv = arg1;
585         lr_write_t *lr = arg2;
586         objset_t *os = zv->zv_objset;
587         char *data = (char *)(lr + 1);  /* data follows lr_write_t */
588         uint64_t offset, length;
589         dmu_tx_t *tx;
590         int error;
591
592         if (byteswap)
593                 byteswap_uint64_array(lr, sizeof (*lr));
594
595         offset = lr->lr_offset;
596         length = lr->lr_length;
597
598         /* If it's a dmu_sync() block, write the whole block */
599         if (lr->lr_common.lrc_reclen == sizeof (lr_write_t)) {
600                 uint64_t blocksize = BP_GET_LSIZE(&lr->lr_blkptr);
601                 if (length < blocksize) {
602                         offset -= offset % blocksize;
603                         length = blocksize;
604                 }
605         }
606
607         tx = dmu_tx_create(os);
608         dmu_tx_hold_write(tx, ZVOL_OBJ, offset, length);
609         error = dmu_tx_assign(tx, TXG_WAIT);
610         if (error) {
611                 dmu_tx_abort(tx);
612         } else {
613                 dmu_write(os, ZVOL_OBJ, offset, length, data, tx);
614                 dmu_tx_commit(tx);
615         }
616
617         return (error);
618 }
619
620 static int
621 zvol_replay_err(void *arg1, void *arg2, boolean_t byteswap)
622 {
623         return (SET_ERROR(ENOTSUP));
624 }
625
626 /*
627  * Callback vectors for replaying records.
628  * Only TX_WRITE and TX_TRUNCATE are needed for zvol.
629  */
630 zil_replay_func_t *zvol_replay_vector[TX_MAX_TYPE] = {
631         zvol_replay_err,        /* no such transaction type */
632         zvol_replay_err,        /* TX_CREATE */
633         zvol_replay_err,        /* TX_MKDIR */
634         zvol_replay_err,        /* TX_MKXATTR */
635         zvol_replay_err,        /* TX_SYMLINK */
636         zvol_replay_err,        /* TX_REMOVE */
637         zvol_replay_err,        /* TX_RMDIR */
638         zvol_replay_err,        /* TX_LINK */
639         zvol_replay_err,        /* TX_RENAME */
640         zvol_replay_write,      /* TX_WRITE */
641         zvol_replay_truncate,   /* TX_TRUNCATE */
642         zvol_replay_err,        /* TX_SETATTR */
643         zvol_replay_err,        /* TX_ACL */
644         zvol_replay_err,        /* TX_CREATE_ATTR */
645         zvol_replay_err,        /* TX_CREATE_ACL_ATTR */
646         zvol_replay_err,        /* TX_MKDIR_ACL */
647         zvol_replay_err,        /* TX_MKDIR_ATTR */
648         zvol_replay_err,        /* TX_MKDIR_ACL_ATTR */
649         zvol_replay_err,        /* TX_WRITE2 */
650 };
651
652 /*
653  * zvol_log_write() handles synchronous writes using TX_WRITE ZIL transactions.
654  *
655  * We store data in the log buffers if it's small enough.
656  * Otherwise we will later flush the data out via dmu_sync().
657  */
658 ssize_t zvol_immediate_write_sz = 32768;
659
660 static void
661 zvol_log_write(zvol_state_t *zv, dmu_tx_t *tx, uint64_t offset,
662     uint64_t size, int sync)
663 {
664         uint32_t blocksize = zv->zv_volblocksize;
665         zilog_t *zilog = zv->zv_zilog;
666         itx_wr_state_t write_state;
667
668         if (zil_replaying(zilog, tx))
669                 return;
670
671         if (zilog->zl_logbias == ZFS_LOGBIAS_THROUGHPUT)
672                 write_state = WR_INDIRECT;
673         else if (!spa_has_slogs(zilog->zl_spa) &&
674             size >= blocksize && blocksize > zvol_immediate_write_sz)
675                 write_state = WR_INDIRECT;
676         else if (sync)
677                 write_state = WR_COPIED;
678         else
679                 write_state = WR_NEED_COPY;
680
681         while (size) {
682                 itx_t *itx;
683                 lr_write_t *lr;
684                 itx_wr_state_t wr_state = write_state;
685                 ssize_t len = size;
686
687                 if (wr_state == WR_COPIED && size > zil_max_copied_data(zilog))
688                         wr_state = WR_NEED_COPY;
689                 else if (wr_state == WR_INDIRECT)
690                         len = MIN(blocksize - P2PHASE(offset, blocksize), size);
691
692                 itx = zil_itx_create(TX_WRITE, sizeof (*lr) +
693                     (wr_state == WR_COPIED ? len : 0));
694                 lr = (lr_write_t *)&itx->itx_lr;
695                 if (wr_state == WR_COPIED && dmu_read_by_dnode(zv->zv_dn,
696                     offset, len, lr+1, DMU_READ_NO_PREFETCH) != 0) {
697                         zil_itx_destroy(itx);
698                         itx = zil_itx_create(TX_WRITE, sizeof (*lr));
699                         lr = (lr_write_t *)&itx->itx_lr;
700                         wr_state = WR_NEED_COPY;
701                 }
702
703                 itx->itx_wr_state = wr_state;
704                 lr->lr_foid = ZVOL_OBJ;
705                 lr->lr_offset = offset;
706                 lr->lr_length = len;
707                 lr->lr_blkoff = 0;
708                 BP_ZERO(&lr->lr_blkptr);
709
710                 itx->itx_private = zv;
711                 itx->itx_sync = sync;
712
713                 (void) zil_itx_assign(zilog, itx, tx);
714
715                 offset += len;
716                 size -= len;
717         }
718 }
719
720 typedef struct zv_request {
721         zvol_state_t    *zv;
722         struct bio      *bio;
723         locked_range_t  *lr;
724 } zv_request_t;
725
726 static void
727 uio_from_bio(uio_t *uio, struct bio *bio)
728 {
729         uio->uio_bvec = &bio->bi_io_vec[BIO_BI_IDX(bio)];
730         uio->uio_iovcnt = bio->bi_vcnt - BIO_BI_IDX(bio);
731         uio->uio_loffset = BIO_BI_SECTOR(bio) << 9;
732         uio->uio_segflg = UIO_BVEC;
733         uio->uio_limit = MAXOFFSET_T;
734         uio->uio_resid = BIO_BI_SIZE(bio);
735         uio->uio_skip = BIO_BI_SKIP(bio);
736 }
737
738 static void
739 zvol_write(void *arg)
740 {
741         int error = 0;
742
743         zv_request_t *zvr = arg;
744         struct bio *bio = zvr->bio;
745         uio_t uio = { { 0 }, 0 };
746         uio_from_bio(&uio, bio);
747
748         zvol_state_t *zv = zvr->zv;
749         ASSERT(zv && zv->zv_open_count > 0);
750         ASSERT(zv->zv_zilog != NULL);
751
752         ssize_t start_resid = uio.uio_resid;
753         unsigned long start_jif = jiffies;
754         blk_generic_start_io_acct(zv->zv_queue, WRITE, bio_sectors(bio),
755             &zv->zv_disk->part0);
756
757         boolean_t sync =
758             bio_is_fua(bio) || zv->zv_objset->os_sync == ZFS_SYNC_ALWAYS;
759
760         uint64_t volsize = zv->zv_volsize;
761         while (uio.uio_resid > 0 && uio.uio_loffset < volsize) {
762                 uint64_t bytes = MIN(uio.uio_resid, DMU_MAX_ACCESS >> 1);
763                 uint64_t off = uio.uio_loffset;
764                 dmu_tx_t *tx = dmu_tx_create(zv->zv_objset);
765
766                 if (bytes > volsize - off)      /* don't write past the end */
767                         bytes = volsize - off;
768
769                 dmu_tx_hold_write(tx, ZVOL_OBJ, off, bytes);
770
771                 /* This will only fail for ENOSPC */
772                 error = dmu_tx_assign(tx, TXG_WAIT);
773                 if (error) {
774                         dmu_tx_abort(tx);
775                         break;
776                 }
777                 error = dmu_write_uio_dnode(zv->zv_dn, &uio, bytes, tx);
778                 if (error == 0) {
779                         zvol_log_write(zv, tx, off, bytes, sync);
780                 }
781                 dmu_tx_commit(tx);
782
783                 if (error)
784                         break;
785         }
786         rangelock_exit(zvr->lr);
787
788         int64_t nwritten = start_resid - uio.uio_resid;
789         dataset_kstats_update_write_kstats(&zv->zv_kstat, nwritten);
790         task_io_account_write(nwritten);
791
792         if (sync)
793                 zil_commit(zv->zv_zilog, ZVOL_OBJ);
794
795         rw_exit(&zv->zv_suspend_lock);
796         blk_generic_end_io_acct(zv->zv_queue, WRITE, &zv->zv_disk->part0,
797             start_jif);
798         BIO_END_IO(bio, -error);
799         kmem_free(zvr, sizeof (zv_request_t));
800 }
801
802 /*
803  * Log a DKIOCFREE/free-long-range to the ZIL with TX_TRUNCATE.
804  */
805 static void
806 zvol_log_truncate(zvol_state_t *zv, dmu_tx_t *tx, uint64_t off, uint64_t len,
807     boolean_t sync)
808 {
809         itx_t *itx;
810         lr_truncate_t *lr;
811         zilog_t *zilog = zv->zv_zilog;
812
813         if (zil_replaying(zilog, tx))
814                 return;
815
816         itx = zil_itx_create(TX_TRUNCATE, sizeof (*lr));
817         lr = (lr_truncate_t *)&itx->itx_lr;
818         lr->lr_foid = ZVOL_OBJ;
819         lr->lr_offset = off;
820         lr->lr_length = len;
821
822         itx->itx_sync = sync;
823         zil_itx_assign(zilog, itx, tx);
824 }
825
826 static void
827 zvol_discard(void *arg)
828 {
829         zv_request_t *zvr = arg;
830         struct bio *bio = zvr->bio;
831         zvol_state_t *zv = zvr->zv;
832         uint64_t start = BIO_BI_SECTOR(bio) << 9;
833         uint64_t size = BIO_BI_SIZE(bio);
834         uint64_t end = start + size;
835         boolean_t sync;
836         int error = 0;
837         dmu_tx_t *tx;
838         unsigned long start_jif;
839
840         ASSERT(zv && zv->zv_open_count > 0);
841         ASSERT(zv->zv_zilog != NULL);
842
843         start_jif = jiffies;
844         blk_generic_start_io_acct(zv->zv_queue, WRITE, bio_sectors(bio),
845             &zv->zv_disk->part0);
846
847         sync = bio_is_fua(bio) || zv->zv_objset->os_sync == ZFS_SYNC_ALWAYS;
848
849         if (end > zv->zv_volsize) {
850                 error = SET_ERROR(EIO);
851                 goto unlock;
852         }
853
854         /*
855          * Align the request to volume block boundaries when a secure erase is
856          * not required.  This will prevent dnode_free_range() from zeroing out
857          * the unaligned parts which is slow (read-modify-write) and useless
858          * since we are not freeing any space by doing so.
859          */
860         if (!bio_is_secure_erase(bio)) {
861                 start = P2ROUNDUP(start, zv->zv_volblocksize);
862                 end = P2ALIGN(end, zv->zv_volblocksize);
863                 size = end - start;
864         }
865
866         if (start >= end)
867                 goto unlock;
868
869         tx = dmu_tx_create(zv->zv_objset);
870         dmu_tx_mark_netfree(tx);
871         error = dmu_tx_assign(tx, TXG_WAIT);
872         if (error != 0) {
873                 dmu_tx_abort(tx);
874         } else {
875                 zvol_log_truncate(zv, tx, start, size, B_TRUE);
876                 dmu_tx_commit(tx);
877                 error = dmu_free_long_range(zv->zv_objset,
878                     ZVOL_OBJ, start, size);
879         }
880 unlock:
881         rangelock_exit(zvr->lr);
882
883         if (error == 0 && sync)
884                 zil_commit(zv->zv_zilog, ZVOL_OBJ);
885
886         rw_exit(&zv->zv_suspend_lock);
887         blk_generic_end_io_acct(zv->zv_queue, WRITE, &zv->zv_disk->part0,
888             start_jif);
889         BIO_END_IO(bio, -error);
890         kmem_free(zvr, sizeof (zv_request_t));
891 }
892
893 static void
894 zvol_read(void *arg)
895 {
896         int error = 0;
897
898         zv_request_t *zvr = arg;
899         struct bio *bio = zvr->bio;
900         uio_t uio = { { 0 }, 0 };
901         uio_from_bio(&uio, bio);
902
903         zvol_state_t *zv = zvr->zv;
904         ASSERT(zv && zv->zv_open_count > 0);
905
906         ssize_t start_resid = uio.uio_resid;
907         unsigned long start_jif = jiffies;
908         blk_generic_start_io_acct(zv->zv_queue, READ, bio_sectors(bio),
909             &zv->zv_disk->part0);
910
911         uint64_t volsize = zv->zv_volsize;
912         while (uio.uio_resid > 0 && uio.uio_loffset < volsize) {
913                 uint64_t bytes = MIN(uio.uio_resid, DMU_MAX_ACCESS >> 1);
914
915                 /* don't read past the end */
916                 if (bytes > volsize - uio.uio_loffset)
917                         bytes = volsize - uio.uio_loffset;
918
919                 error = dmu_read_uio_dnode(zv->zv_dn, &uio, bytes);
920                 if (error) {
921                         /* convert checksum errors into IO errors */
922                         if (error == ECKSUM)
923                                 error = SET_ERROR(EIO);
924                         break;
925                 }
926         }
927         rangelock_exit(zvr->lr);
928
929         int64_t nread = start_resid - uio.uio_resid;
930         dataset_kstats_update_read_kstats(&zv->zv_kstat, nread);
931         task_io_account_read(nread);
932
933         rw_exit(&zv->zv_suspend_lock);
934         blk_generic_end_io_acct(zv->zv_queue, READ, &zv->zv_disk->part0,
935             start_jif);
936         BIO_END_IO(bio, -error);
937         kmem_free(zvr, sizeof (zv_request_t));
938 }
939
940 /* ARGSUSED */
941 static void
942 zvol_get_done(zgd_t *zgd, int error)
943 {
944         if (zgd->zgd_db)
945                 dmu_buf_rele(zgd->zgd_db, zgd);
946
947         rangelock_exit(zgd->zgd_lr);
948
949         kmem_free(zgd, sizeof (zgd_t));
950 }
951
952 /*
953  * Get data to generate a TX_WRITE intent log record.
954  */
955 static int
956 zvol_get_data(void *arg, lr_write_t *lr, char *buf, struct lwb *lwb, zio_t *zio)
957 {
958         zvol_state_t *zv = arg;
959         uint64_t offset = lr->lr_offset;
960         uint64_t size = lr->lr_length;
961         dmu_buf_t *db;
962         zgd_t *zgd;
963         int error;
964
965         ASSERT3P(lwb, !=, NULL);
966         ASSERT3P(zio, !=, NULL);
967         ASSERT3U(size, !=, 0);
968
969         zgd = (zgd_t *)kmem_zalloc(sizeof (zgd_t), KM_SLEEP);
970         zgd->zgd_lwb = lwb;
971
972         /*
973          * Write records come in two flavors: immediate and indirect.
974          * For small writes it's cheaper to store the data with the
975          * log record (immediate); for large writes it's cheaper to
976          * sync the data and get a pointer to it (indirect) so that
977          * we don't have to write the data twice.
978          */
979         if (buf != NULL) { /* immediate write */
980                 zgd->zgd_lr = rangelock_enter(&zv->zv_rangelock, offset, size,
981                     RL_READER);
982                 error = dmu_read_by_dnode(zv->zv_dn, offset, size, buf,
983                     DMU_READ_NO_PREFETCH);
984         } else { /* indirect write */
985                 /*
986                  * Have to lock the whole block to ensure when it's written out
987                  * and its checksum is being calculated that no one can change
988                  * the data. Contrarily to zfs_get_data we need not re-check
989                  * blocksize after we get the lock because it cannot be changed.
990                  */
991                 size = zv->zv_volblocksize;
992                 offset = P2ALIGN_TYPED(offset, size, uint64_t);
993                 zgd->zgd_lr = rangelock_enter(&zv->zv_rangelock, offset, size,
994                     RL_READER);
995                 error = dmu_buf_hold_by_dnode(zv->zv_dn, offset, zgd, &db,
996                     DMU_READ_NO_PREFETCH);
997                 if (error == 0) {
998                         blkptr_t *bp = &lr->lr_blkptr;
999
1000                         zgd->zgd_db = db;
1001                         zgd->zgd_bp = bp;
1002
1003                         ASSERT(db != NULL);
1004                         ASSERT(db->db_offset == offset);
1005                         ASSERT(db->db_size == size);
1006
1007                         error = dmu_sync(zio, lr->lr_common.lrc_txg,
1008                             zvol_get_done, zgd);
1009
1010                         if (error == 0)
1011                                 return (0);
1012                 }
1013         }
1014
1015         zvol_get_done(zgd, error);
1016
1017         return (SET_ERROR(error));
1018 }
1019
1020 static MAKE_REQUEST_FN_RET
1021 zvol_request(struct request_queue *q, struct bio *bio)
1022 {
1023         zvol_state_t *zv = q->queuedata;
1024         fstrans_cookie_t cookie = spl_fstrans_mark();
1025         uint64_t offset = BIO_BI_SECTOR(bio) << 9;
1026         uint64_t size = BIO_BI_SIZE(bio);
1027         int rw = bio_data_dir(bio);
1028         zv_request_t *zvr;
1029
1030         if (bio_has_data(bio) && offset + size > zv->zv_volsize) {
1031                 printk(KERN_INFO
1032                     "%s: bad access: offset=%llu, size=%lu\n",
1033                     zv->zv_disk->disk_name,
1034                     (long long unsigned)offset,
1035                     (long unsigned)size);
1036
1037                 BIO_END_IO(bio, -SET_ERROR(EIO));
1038                 goto out;
1039         }
1040
1041         if (rw == WRITE) {
1042                 boolean_t need_sync = B_FALSE;
1043
1044                 if (unlikely(zv->zv_flags & ZVOL_RDONLY)) {
1045                         BIO_END_IO(bio, -SET_ERROR(EROFS));
1046                         goto out;
1047                 }
1048
1049                 /*
1050                  * To be released in the I/O function. See the comment on
1051                  * rangelock_enter() below.
1052                  */
1053                 rw_enter(&zv->zv_suspend_lock, RW_READER);
1054
1055                 /*
1056                  * Open a ZIL if this is the first time we have written to this
1057                  * zvol. We protect zv->zv_zilog with zv_suspend_lock rather
1058                  * than zv_state_lock so that we don't need to acquire an
1059                  * additional lock in this path.
1060                  */
1061                 if (zv->zv_zilog == NULL) {
1062                         rw_exit(&zv->zv_suspend_lock);
1063                         rw_enter(&zv->zv_suspend_lock, RW_WRITER);
1064                         if (zv->zv_zilog == NULL) {
1065                                 zv->zv_zilog = zil_open(zv->zv_objset,
1066                                     zvol_get_data);
1067                                 zv->zv_flags |= ZVOL_WRITTEN_TO;
1068                         }
1069                         rw_downgrade(&zv->zv_suspend_lock);
1070                 }
1071
1072                 /* bio marked as FLUSH need to flush before write */
1073                 if (bio_is_flush(bio))
1074                         zil_commit(zv->zv_zilog, ZVOL_OBJ);
1075
1076                 /* Some requests are just for flush and nothing else. */
1077                 if (size == 0) {
1078                         rw_exit(&zv->zv_suspend_lock);
1079                         BIO_END_IO(bio, 0);
1080                         goto out;
1081                 }
1082
1083                 zvr = kmem_alloc(sizeof (zv_request_t), KM_SLEEP);
1084                 zvr->zv = zv;
1085                 zvr->bio = bio;
1086
1087                 /*
1088                  * To be released in the I/O function. Since the I/O functions
1089                  * are asynchronous, we take it here synchronously to make
1090                  * sure overlapped I/Os are properly ordered.
1091                  */
1092                 zvr->lr = rangelock_enter(&zv->zv_rangelock, offset, size,
1093                     RL_WRITER);
1094                 /*
1095                  * Sync writes and discards execute zil_commit() which may need
1096                  * to take a RL_READER lock on the whole block being modified
1097                  * via its zillog->zl_get_data(): to avoid circular dependency
1098                  * issues with taskq threads execute these requests
1099                  * synchronously here in zvol_request().
1100                  */
1101                 need_sync = bio_is_fua(bio) ||
1102                     zv->zv_objset->os_sync == ZFS_SYNC_ALWAYS;
1103                 if (bio_is_discard(bio) || bio_is_secure_erase(bio)) {
1104                         if (zvol_request_sync || need_sync ||
1105                             taskq_dispatch(zvol_taskq, zvol_discard, zvr,
1106                             TQ_SLEEP) == TASKQID_INVALID)
1107                                 zvol_discard(zvr);
1108                 } else {
1109                         if (zvol_request_sync || need_sync ||
1110                             taskq_dispatch(zvol_taskq, zvol_write, zvr,
1111                             TQ_SLEEP) == TASKQID_INVALID)
1112                                 zvol_write(zvr);
1113                 }
1114         } else {
1115                 /*
1116                  * The SCST driver, and possibly others, may issue READ I/Os
1117                  * with a length of zero bytes.  These empty I/Os contain no
1118                  * data and require no additional handling.
1119                  */
1120                 if (size == 0) {
1121                         BIO_END_IO(bio, 0);
1122                         goto out;
1123                 }
1124
1125                 zvr = kmem_alloc(sizeof (zv_request_t), KM_SLEEP);
1126                 zvr->zv = zv;
1127                 zvr->bio = bio;
1128
1129                 rw_enter(&zv->zv_suspend_lock, RW_READER);
1130
1131                 zvr->lr = rangelock_enter(&zv->zv_rangelock, offset, size,
1132                     RL_READER);
1133                 if (zvol_request_sync || taskq_dispatch(zvol_taskq,
1134                     zvol_read, zvr, TQ_SLEEP) == TASKQID_INVALID)
1135                         zvol_read(zvr);
1136         }
1137
1138 out:
1139         spl_fstrans_unmark(cookie);
1140 #ifdef HAVE_MAKE_REQUEST_FN_RET_INT
1141         return (0);
1142 #elif defined(HAVE_MAKE_REQUEST_FN_RET_QC)
1143         return (BLK_QC_T_NONE);
1144 #endif
1145 }
1146
1147 /*
1148  * The zvol_state_t's are inserted into zvol_state_list and zvol_htable.
1149  */
1150 static void
1151 zvol_insert(zvol_state_t *zv)
1152 {
1153         ASSERT(RW_WRITE_HELD(&zvol_state_lock));
1154         ASSERT3U(MINOR(zv->zv_dev) & ZVOL_MINOR_MASK, ==, 0);
1155         list_insert_head(&zvol_state_list, zv);
1156         hlist_add_head(&zv->zv_hlink, ZVOL_HT_HEAD(zv->zv_hash));
1157 }
1158
1159 /*
1160  * Simply remove the zvol from to list of zvols.
1161  */
1162 static void
1163 zvol_remove(zvol_state_t *zv)
1164 {
1165         ASSERT(RW_WRITE_HELD(&zvol_state_lock));
1166         list_remove(&zvol_state_list, zv);
1167         hlist_del(&zv->zv_hlink);
1168 }
1169
1170 /*
1171  * Setup zv after we just own the zv->objset
1172  */
1173 static int
1174 zvol_setup_zv(zvol_state_t *zv)
1175 {
1176         uint64_t volsize;
1177         int error;
1178         uint64_t ro;
1179         objset_t *os = zv->zv_objset;
1180
1181         ASSERT(MUTEX_HELD(&zv->zv_state_lock));
1182         ASSERT(RW_LOCK_HELD(&zv->zv_suspend_lock));
1183
1184         zv->zv_zilog = NULL;
1185         zv->zv_flags &= ~ZVOL_WRITTEN_TO;
1186
1187         error = dsl_prop_get_integer(zv->zv_name, "readonly", &ro, NULL);
1188         if (error)
1189                 return (SET_ERROR(error));
1190
1191         error = zap_lookup(os, ZVOL_ZAP_OBJ, "size", 8, 1, &volsize);
1192         if (error)
1193                 return (SET_ERROR(error));
1194
1195         error = dnode_hold(os, ZVOL_OBJ, FTAG, &zv->zv_dn);
1196         if (error)
1197                 return (SET_ERROR(error));
1198
1199         set_capacity(zv->zv_disk, volsize >> 9);
1200         zv->zv_volsize = volsize;
1201
1202         if (ro || dmu_objset_is_snapshot(os) ||
1203             !spa_writeable(dmu_objset_spa(os))) {
1204                 set_disk_ro(zv->zv_disk, 1);
1205                 zv->zv_flags |= ZVOL_RDONLY;
1206         } else {
1207                 set_disk_ro(zv->zv_disk, 0);
1208                 zv->zv_flags &= ~ZVOL_RDONLY;
1209         }
1210         return (0);
1211 }
1212
1213 /*
1214  * Shutdown every zv_objset related stuff except zv_objset itself.
1215  * The is the reverse of zvol_setup_zv.
1216  */
1217 static void
1218 zvol_shutdown_zv(zvol_state_t *zv)
1219 {
1220         ASSERT(MUTEX_HELD(&zv->zv_state_lock) &&
1221             RW_LOCK_HELD(&zv->zv_suspend_lock));
1222
1223         if (zv->zv_flags & ZVOL_WRITTEN_TO) {
1224                 ASSERT(zv->zv_zilog != NULL);
1225                 zil_close(zv->zv_zilog);
1226         }
1227
1228         zv->zv_zilog = NULL;
1229
1230         dnode_rele(zv->zv_dn, FTAG);
1231         zv->zv_dn = NULL;
1232
1233         /*
1234          * Evict cached data. We must write out any dirty data before
1235          * disowning the dataset.
1236          */
1237         if (zv->zv_flags & ZVOL_WRITTEN_TO)
1238                 txg_wait_synced(dmu_objset_pool(zv->zv_objset), 0);
1239         (void) dmu_objset_evict_dbufs(zv->zv_objset);
1240 }
1241
1242 /*
1243  * return the proper tag for rollback and recv
1244  */
1245 void *
1246 zvol_tag(zvol_state_t *zv)
1247 {
1248         ASSERT(RW_WRITE_HELD(&zv->zv_suspend_lock));
1249         return (zv->zv_open_count > 0 ? zv : NULL);
1250 }
1251
1252 /*
1253  * Suspend the zvol for recv and rollback.
1254  */
1255 zvol_state_t *
1256 zvol_suspend(const char *name)
1257 {
1258         zvol_state_t *zv;
1259
1260         zv = zvol_find_by_name(name, RW_WRITER);
1261
1262         if (zv == NULL)
1263                 return (NULL);
1264
1265         /* block all I/O, release in zvol_resume. */
1266         ASSERT(MUTEX_HELD(&zv->zv_state_lock));
1267         ASSERT(RW_WRITE_HELD(&zv->zv_suspend_lock));
1268
1269         atomic_inc(&zv->zv_suspend_ref);
1270
1271         if (zv->zv_open_count > 0)
1272                 zvol_shutdown_zv(zv);
1273
1274         /*
1275          * do not hold zv_state_lock across suspend/resume to
1276          * avoid locking up zvol lookups
1277          */
1278         mutex_exit(&zv->zv_state_lock);
1279
1280         /* zv_suspend_lock is released in zvol_resume() */
1281         return (zv);
1282 }
1283
1284 int
1285 zvol_resume(zvol_state_t *zv)
1286 {
1287         int error = 0;
1288
1289         ASSERT(RW_WRITE_HELD(&zv->zv_suspend_lock));
1290
1291         mutex_enter(&zv->zv_state_lock);
1292
1293         if (zv->zv_open_count > 0) {
1294                 VERIFY0(dmu_objset_hold(zv->zv_name, zv, &zv->zv_objset));
1295                 VERIFY3P(zv->zv_objset->os_dsl_dataset->ds_owner, ==, zv);
1296                 VERIFY(dsl_dataset_long_held(zv->zv_objset->os_dsl_dataset));
1297                 dmu_objset_rele(zv->zv_objset, zv);
1298
1299                 error = zvol_setup_zv(zv);
1300         }
1301
1302         mutex_exit(&zv->zv_state_lock);
1303
1304         rw_exit(&zv->zv_suspend_lock);
1305         /*
1306          * We need this because we don't hold zvol_state_lock while releasing
1307          * zv_suspend_lock. zvol_remove_minors_impl thus cannot check
1308          * zv_suspend_lock to determine it is safe to free because rwlock is
1309          * not inherent atomic.
1310          */
1311         atomic_dec(&zv->zv_suspend_ref);
1312
1313         return (SET_ERROR(error));
1314 }
1315
1316 static int
1317 zvol_first_open(zvol_state_t *zv, boolean_t readonly)
1318 {
1319         objset_t *os;
1320         int error, locked = 0;
1321         boolean_t ro;
1322
1323         ASSERT(RW_READ_HELD(&zv->zv_suspend_lock));
1324         ASSERT(MUTEX_HELD(&zv->zv_state_lock));
1325
1326         /*
1327          * In all other cases the spa_namespace_lock is taken before the
1328          * bdev->bd_mutex lock.  But in this case the Linux __blkdev_get()
1329          * function calls fops->open() with the bdev->bd_mutex lock held.
1330          * This deadlock can be easily observed with zvols used as vdevs.
1331          *
1332          * To avoid a potential lock inversion deadlock we preemptively
1333          * try to take the spa_namespace_lock().  Normally it will not
1334          * be contended and this is safe because spa_open_common() handles
1335          * the case where the caller already holds the spa_namespace_lock.
1336          *
1337          * When it is contended we risk a lock inversion if we were to
1338          * block waiting for the lock.  Luckily, the __blkdev_get()
1339          * function allows us to return -ERESTARTSYS which will result in
1340          * bdev->bd_mutex being dropped, reacquired, and fops->open() being
1341          * called again.  This process can be repeated safely until both
1342          * locks are acquired.
1343          */
1344         if (!mutex_owned(&spa_namespace_lock)) {
1345                 locked = mutex_tryenter(&spa_namespace_lock);
1346                 if (!locked)
1347                         return (-SET_ERROR(ERESTARTSYS));
1348         }
1349
1350         ro = (readonly || (strchr(zv->zv_name, '@') != NULL));
1351         error = dmu_objset_own(zv->zv_name, DMU_OST_ZVOL, ro, B_TRUE, zv, &os);
1352         if (error)
1353                 goto out_mutex;
1354
1355         zv->zv_objset = os;
1356
1357         error = zvol_setup_zv(zv);
1358
1359         if (error) {
1360                 dmu_objset_disown(os, 1, zv);
1361                 zv->zv_objset = NULL;
1362         }
1363
1364 out_mutex:
1365         if (locked)
1366                 mutex_exit(&spa_namespace_lock);
1367         return (SET_ERROR(-error));
1368 }
1369
1370 static void
1371 zvol_last_close(zvol_state_t *zv)
1372 {
1373         ASSERT(RW_READ_HELD(&zv->zv_suspend_lock));
1374         ASSERT(MUTEX_HELD(&zv->zv_state_lock));
1375
1376         zvol_shutdown_zv(zv);
1377
1378         dmu_objset_disown(zv->zv_objset, 1, zv);
1379         zv->zv_objset = NULL;
1380 }
1381
1382 static int
1383 zvol_open(struct block_device *bdev, fmode_t flag)
1384 {
1385         zvol_state_t *zv;
1386         int error = 0;
1387         boolean_t drop_suspend = B_TRUE;
1388
1389         rw_enter(&zvol_state_lock, RW_READER);
1390         /*
1391          * Obtain a copy of private_data under the zvol_state_lock to make
1392          * sure that either the result of zvol free code path setting
1393          * bdev->bd_disk->private_data to NULL is observed, or zvol_free()
1394          * is not called on this zv because of the positive zv_open_count.
1395          */
1396         zv = bdev->bd_disk->private_data;
1397         if (zv == NULL) {
1398                 rw_exit(&zvol_state_lock);
1399                 return (SET_ERROR(-ENXIO));
1400         }
1401
1402         mutex_enter(&zv->zv_state_lock);
1403         /*
1404          * make sure zvol is not suspended during first open
1405          * (hold zv_suspend_lock) and respect proper lock acquisition
1406          * ordering - zv_suspend_lock before zv_state_lock
1407          */
1408         if (zv->zv_open_count == 0) {
1409                 if (!rw_tryenter(&zv->zv_suspend_lock, RW_READER)) {
1410                         mutex_exit(&zv->zv_state_lock);
1411                         rw_enter(&zv->zv_suspend_lock, RW_READER);
1412                         mutex_enter(&zv->zv_state_lock);
1413                         /* check to see if zv_suspend_lock is needed */
1414                         if (zv->zv_open_count != 0) {
1415                                 rw_exit(&zv->zv_suspend_lock);
1416                                 drop_suspend = B_FALSE;
1417                         }
1418                 }
1419         } else {
1420                 drop_suspend = B_FALSE;
1421         }
1422         rw_exit(&zvol_state_lock);
1423
1424         ASSERT(MUTEX_HELD(&zv->zv_state_lock));
1425         ASSERT(zv->zv_open_count != 0 || RW_READ_HELD(&zv->zv_suspend_lock));
1426
1427         if (zv->zv_open_count == 0) {
1428                 error = zvol_first_open(zv, !(flag & FMODE_WRITE));
1429                 if (error)
1430                         goto out_mutex;
1431         }
1432
1433         if ((flag & FMODE_WRITE) && (zv->zv_flags & ZVOL_RDONLY)) {
1434                 error = -EROFS;
1435                 goto out_open_count;
1436         }
1437
1438         zv->zv_open_count++;
1439
1440         mutex_exit(&zv->zv_state_lock);
1441         if (drop_suspend)
1442                 rw_exit(&zv->zv_suspend_lock);
1443
1444         check_disk_change(bdev);
1445
1446         return (0);
1447
1448 out_open_count:
1449         if (zv->zv_open_count == 0)
1450                 zvol_last_close(zv);
1451
1452 out_mutex:
1453         mutex_exit(&zv->zv_state_lock);
1454         if (drop_suspend)
1455                 rw_exit(&zv->zv_suspend_lock);
1456         if (error == -ERESTARTSYS)
1457                 schedule();
1458
1459         return (SET_ERROR(error));
1460 }
1461
1462 #ifdef HAVE_BLOCK_DEVICE_OPERATIONS_RELEASE_VOID
1463 static void
1464 #else
1465 static int
1466 #endif
1467 zvol_release(struct gendisk *disk, fmode_t mode)
1468 {
1469         zvol_state_t *zv;
1470         boolean_t drop_suspend = B_TRUE;
1471
1472         rw_enter(&zvol_state_lock, RW_READER);
1473         zv = disk->private_data;
1474
1475         mutex_enter(&zv->zv_state_lock);
1476         ASSERT(zv->zv_open_count > 0);
1477         /*
1478          * make sure zvol is not suspended during last close
1479          * (hold zv_suspend_lock) and respect proper lock acquisition
1480          * ordering - zv_suspend_lock before zv_state_lock
1481          */
1482         if (zv->zv_open_count == 1) {
1483                 if (!rw_tryenter(&zv->zv_suspend_lock, RW_READER)) {
1484                         mutex_exit(&zv->zv_state_lock);
1485                         rw_enter(&zv->zv_suspend_lock, RW_READER);
1486                         mutex_enter(&zv->zv_state_lock);
1487                         /* check to see if zv_suspend_lock is needed */
1488                         if (zv->zv_open_count != 1) {
1489                                 rw_exit(&zv->zv_suspend_lock);
1490                                 drop_suspend = B_FALSE;
1491                         }
1492                 }
1493         } else {
1494                 drop_suspend = B_FALSE;
1495         }
1496         rw_exit(&zvol_state_lock);
1497
1498         ASSERT(MUTEX_HELD(&zv->zv_state_lock));
1499         ASSERT(zv->zv_open_count != 1 || RW_READ_HELD(&zv->zv_suspend_lock));
1500
1501         zv->zv_open_count--;
1502         if (zv->zv_open_count == 0)
1503                 zvol_last_close(zv);
1504
1505         mutex_exit(&zv->zv_state_lock);
1506
1507         if (drop_suspend)
1508                 rw_exit(&zv->zv_suspend_lock);
1509
1510 #ifndef HAVE_BLOCK_DEVICE_OPERATIONS_RELEASE_VOID
1511         return (0);
1512 #endif
1513 }
1514
1515 static int
1516 zvol_ioctl(struct block_device *bdev, fmode_t mode,
1517     unsigned int cmd, unsigned long arg)
1518 {
1519         zvol_state_t *zv = bdev->bd_disk->private_data;
1520         int error = 0;
1521
1522         ASSERT3U(zv->zv_open_count, >, 0);
1523
1524         switch (cmd) {
1525         case BLKFLSBUF:
1526                 fsync_bdev(bdev);
1527                 invalidate_bdev(bdev);
1528                 rw_enter(&zv->zv_suspend_lock, RW_READER);
1529
1530                 if (!(zv->zv_flags & ZVOL_RDONLY))
1531                         txg_wait_synced(dmu_objset_pool(zv->zv_objset), 0);
1532
1533                 rw_exit(&zv->zv_suspend_lock);
1534                 break;
1535
1536         case BLKZNAME:
1537                 mutex_enter(&zv->zv_state_lock);
1538                 error = copy_to_user((void *)arg, zv->zv_name, MAXNAMELEN);
1539                 mutex_exit(&zv->zv_state_lock);
1540                 break;
1541
1542         default:
1543                 error = -ENOTTY;
1544                 break;
1545         }
1546
1547         return (SET_ERROR(error));
1548 }
1549
1550 #ifdef CONFIG_COMPAT
1551 static int
1552 zvol_compat_ioctl(struct block_device *bdev, fmode_t mode,
1553     unsigned cmd, unsigned long arg)
1554 {
1555         return (zvol_ioctl(bdev, mode, cmd, arg));
1556 }
1557 #else
1558 #define zvol_compat_ioctl       NULL
1559 #endif
1560
1561 /*
1562  * Linux 2.6.38 preferred interface.
1563  */
1564 #ifdef HAVE_BLOCK_DEVICE_OPERATIONS_CHECK_EVENTS
1565 static unsigned int
1566 zvol_check_events(struct gendisk *disk, unsigned int clearing)
1567 {
1568         unsigned int mask = 0;
1569
1570         rw_enter(&zvol_state_lock, RW_READER);
1571
1572         zvol_state_t *zv = disk->private_data;
1573         if (zv != NULL) {
1574                 mutex_enter(&zv->zv_state_lock);
1575                 mask = zv->zv_changed ? DISK_EVENT_MEDIA_CHANGE : 0;
1576                 zv->zv_changed = 0;
1577                 mutex_exit(&zv->zv_state_lock);
1578         }
1579
1580         rw_exit(&zvol_state_lock);
1581
1582         return (mask);
1583 }
1584 #else
1585 static int zvol_media_changed(struct gendisk *disk)
1586 {
1587         int changed = 0;
1588
1589         rw_enter(&zvol_state_lock, RW_READER);
1590
1591         zvol_state_t *zv = disk->private_data;
1592         if (zv != NULL) {
1593                 mutex_enter(&zv->zv_state_lock);
1594                 changed = zv->zv_changed;
1595                 zv->zv_changed = 0;
1596                 mutex_exit(&zv->zv_state_lock);
1597         }
1598
1599         rw_exit(&zvol_state_lock);
1600
1601         return (changed);
1602 }
1603 #endif
1604
1605 static int zvol_revalidate_disk(struct gendisk *disk)
1606 {
1607         rw_enter(&zvol_state_lock, RW_READER);
1608
1609         zvol_state_t *zv = disk->private_data;
1610         if (zv != NULL) {
1611                 mutex_enter(&zv->zv_state_lock);
1612                 set_capacity(zv->zv_disk, zv->zv_volsize >> SECTOR_BITS);
1613                 mutex_exit(&zv->zv_state_lock);
1614         }
1615
1616         rw_exit(&zvol_state_lock);
1617
1618         return (0);
1619 }
1620
1621 /*
1622  * Provide a simple virtual geometry for legacy compatibility.  For devices
1623  * smaller than 1 MiB a small head and sector count is used to allow very
1624  * tiny devices.  For devices over 1 Mib a standard head and sector count
1625  * is used to keep the cylinders count reasonable.
1626  */
1627 static int
1628 zvol_getgeo(struct block_device *bdev, struct hd_geometry *geo)
1629 {
1630         zvol_state_t *zv = bdev->bd_disk->private_data;
1631         sector_t sectors;
1632
1633         ASSERT3U(zv->zv_open_count, >, 0);
1634
1635         sectors = get_capacity(zv->zv_disk);
1636
1637         if (sectors > 2048) {
1638                 geo->heads = 16;
1639                 geo->sectors = 63;
1640         } else {
1641                 geo->heads = 2;
1642                 geo->sectors = 4;
1643         }
1644
1645         geo->start = 0;
1646         geo->cylinders = sectors / (geo->heads * geo->sectors);
1647
1648         return (0);
1649 }
1650
1651 static struct kobject *
1652 zvol_probe(dev_t dev, int *part, void *arg)
1653 {
1654         zvol_state_t *zv;
1655         struct kobject *kobj;
1656
1657         zv = zvol_find_by_dev(dev);
1658         kobj = zv ? get_disk_and_module(zv->zv_disk) : NULL;
1659         ASSERT(zv == NULL || MUTEX_HELD(&zv->zv_state_lock));
1660         if (zv)
1661                 mutex_exit(&zv->zv_state_lock);
1662
1663         return (kobj);
1664 }
1665
1666 static struct block_device_operations zvol_ops = {
1667         .open                   = zvol_open,
1668         .release                = zvol_release,
1669         .ioctl                  = zvol_ioctl,
1670         .compat_ioctl           = zvol_compat_ioctl,
1671 #ifdef HAVE_BLOCK_DEVICE_OPERATIONS_CHECK_EVENTS
1672         .check_events           = zvol_check_events,
1673 #else
1674         .media_changed          = zvol_media_changed,
1675 #endif
1676         .revalidate_disk        = zvol_revalidate_disk,
1677         .getgeo                 = zvol_getgeo,
1678         .owner                  = THIS_MODULE,
1679 };
1680
1681 /*
1682  * Allocate memory for a new zvol_state_t and setup the required
1683  * request queue and generic disk structures for the block device.
1684  */
1685 static zvol_state_t *
1686 zvol_alloc(dev_t dev, const char *name)
1687 {
1688         zvol_state_t *zv;
1689         uint64_t volmode;
1690
1691         if (dsl_prop_get_integer(name, "volmode", &volmode, NULL) != 0)
1692                 return (NULL);
1693
1694         if (volmode == ZFS_VOLMODE_DEFAULT)
1695                 volmode = zvol_volmode;
1696
1697         if (volmode == ZFS_VOLMODE_NONE)
1698                 return (NULL);
1699
1700         zv = kmem_zalloc(sizeof (zvol_state_t), KM_SLEEP);
1701
1702         list_link_init(&zv->zv_next);
1703
1704         mutex_init(&zv->zv_state_lock, NULL, MUTEX_DEFAULT, NULL);
1705
1706         zv->zv_queue = blk_alloc_queue(GFP_ATOMIC);
1707         if (zv->zv_queue == NULL)
1708                 goto out_kmem;
1709
1710         blk_queue_make_request(zv->zv_queue, zvol_request);
1711         blk_queue_set_write_cache(zv->zv_queue, B_TRUE, B_TRUE);
1712
1713         /* Limit read-ahead to a single page to prevent over-prefetching. */
1714         blk_queue_set_read_ahead(zv->zv_queue, 1);
1715
1716         /* Disable write merging in favor of the ZIO pipeline. */
1717         blk_queue_flag_set(QUEUE_FLAG_NOMERGES, zv->zv_queue);
1718
1719         zv->zv_disk = alloc_disk(ZVOL_MINORS);
1720         if (zv->zv_disk == NULL)
1721                 goto out_queue;
1722
1723         zv->zv_queue->queuedata = zv;
1724         zv->zv_dev = dev;
1725         zv->zv_open_count = 0;
1726         strlcpy(zv->zv_name, name, MAXNAMELEN);
1727
1728         rangelock_init(&zv->zv_rangelock, NULL, NULL);
1729         rw_init(&zv->zv_suspend_lock, NULL, RW_DEFAULT, NULL);
1730
1731         zv->zv_disk->major = zvol_major;
1732 #ifdef HAVE_BLOCK_DEVICE_OPERATIONS_CHECK_EVENTS
1733         zv->zv_disk->events = DISK_EVENT_MEDIA_CHANGE;
1734 #endif
1735
1736         if (volmode == ZFS_VOLMODE_DEV) {
1737                 /*
1738                  * ZFS_VOLMODE_DEV disable partitioning on ZVOL devices: set
1739                  * gendisk->minors = 1 as noted in include/linux/genhd.h.
1740                  * Also disable extended partition numbers (GENHD_FL_EXT_DEVT)
1741                  * and suppresses partition scanning (GENHD_FL_NO_PART_SCAN)
1742                  * setting gendisk->flags accordingly.
1743                  */
1744                 zv->zv_disk->minors = 1;
1745 #if defined(GENHD_FL_EXT_DEVT)
1746                 zv->zv_disk->flags &= ~GENHD_FL_EXT_DEVT;
1747 #endif
1748 #if defined(GENHD_FL_NO_PART_SCAN)
1749                 zv->zv_disk->flags |= GENHD_FL_NO_PART_SCAN;
1750 #endif
1751         }
1752         zv->zv_disk->first_minor = (dev & MINORMASK);
1753         zv->zv_disk->fops = &zvol_ops;
1754         zv->zv_disk->private_data = zv;
1755         zv->zv_disk->queue = zv->zv_queue;
1756         snprintf(zv->zv_disk->disk_name, DISK_NAME_LEN, "%s%d",
1757             ZVOL_DEV_NAME, (dev & MINORMASK));
1758
1759         return (zv);
1760
1761 out_queue:
1762         blk_cleanup_queue(zv->zv_queue);
1763 out_kmem:
1764         kmem_free(zv, sizeof (zvol_state_t));
1765
1766         return (NULL);
1767 }
1768
1769 /*
1770  * Cleanup then free a zvol_state_t which was created by zvol_alloc().
1771  * At this time, the structure is not opened by anyone, is taken off
1772  * the zvol_state_list, and has its private data set to NULL.
1773  * The zvol_state_lock is dropped.
1774  */
1775 static void
1776 zvol_free(void *arg)
1777 {
1778         zvol_state_t *zv = arg;
1779
1780         ASSERT(!RW_LOCK_HELD(&zv->zv_suspend_lock));
1781         ASSERT(!MUTEX_HELD(&zv->zv_state_lock));
1782         ASSERT(zv->zv_open_count == 0);
1783         ASSERT(zv->zv_disk->private_data == NULL);
1784
1785         rw_destroy(&zv->zv_suspend_lock);
1786         rangelock_fini(&zv->zv_rangelock);
1787
1788         del_gendisk(zv->zv_disk);
1789         blk_cleanup_queue(zv->zv_queue);
1790         put_disk(zv->zv_disk);
1791
1792         ida_simple_remove(&zvol_ida, MINOR(zv->zv_dev) >> ZVOL_MINOR_BITS);
1793
1794         mutex_destroy(&zv->zv_state_lock);
1795         dataset_kstats_destroy(&zv->zv_kstat);
1796
1797         kmem_free(zv, sizeof (zvol_state_t));
1798 }
1799
1800 /*
1801  * Create a block device minor node and setup the linkage between it
1802  * and the specified volume.  Once this function returns the block
1803  * device is live and ready for use.
1804  */
1805 static int
1806 zvol_create_minor_impl(const char *name)
1807 {
1808         zvol_state_t *zv;
1809         objset_t *os;
1810         dmu_object_info_t *doi;
1811         uint64_t volsize;
1812         uint64_t len;
1813         unsigned minor = 0;
1814         int error = 0;
1815         int idx;
1816         uint64_t hash = zvol_name_hash(name);
1817
1818         if (zvol_inhibit_dev)
1819                 return (0);
1820
1821         idx = ida_simple_get(&zvol_ida, 0, 0, kmem_flags_convert(KM_SLEEP));
1822         if (idx < 0)
1823                 return (SET_ERROR(-idx));
1824         minor = idx << ZVOL_MINOR_BITS;
1825
1826         zv = zvol_find_by_name_hash(name, hash, RW_NONE);
1827         if (zv) {
1828                 ASSERT(MUTEX_HELD(&zv->zv_state_lock));
1829                 mutex_exit(&zv->zv_state_lock);
1830                 ida_simple_remove(&zvol_ida, idx);
1831                 return (SET_ERROR(EEXIST));
1832         }
1833
1834         doi = kmem_alloc(sizeof (dmu_object_info_t), KM_SLEEP);
1835
1836         error = dmu_objset_own(name, DMU_OST_ZVOL, B_TRUE, B_TRUE, FTAG, &os);
1837         if (error)
1838                 goto out_doi;
1839
1840         error = dmu_object_info(os, ZVOL_OBJ, doi);
1841         if (error)
1842                 goto out_dmu_objset_disown;
1843
1844         error = zap_lookup(os, ZVOL_ZAP_OBJ, "size", 8, 1, &volsize);
1845         if (error)
1846                 goto out_dmu_objset_disown;
1847
1848         zv = zvol_alloc(MKDEV(zvol_major, minor), name);
1849         if (zv == NULL) {
1850                 error = SET_ERROR(EAGAIN);
1851                 goto out_dmu_objset_disown;
1852         }
1853         zv->zv_hash = hash;
1854
1855         if (dmu_objset_is_snapshot(os))
1856                 zv->zv_flags |= ZVOL_RDONLY;
1857
1858         zv->zv_volblocksize = doi->doi_data_block_size;
1859         zv->zv_volsize = volsize;
1860         zv->zv_objset = os;
1861
1862         set_capacity(zv->zv_disk, zv->zv_volsize >> 9);
1863
1864         blk_queue_max_hw_sectors(zv->zv_queue, (DMU_MAX_ACCESS / 4) >> 9);
1865         blk_queue_max_segments(zv->zv_queue, UINT16_MAX);
1866         blk_queue_max_segment_size(zv->zv_queue, UINT_MAX);
1867         blk_queue_physical_block_size(zv->zv_queue, zv->zv_volblocksize);
1868         blk_queue_io_opt(zv->zv_queue, zv->zv_volblocksize);
1869         blk_queue_max_discard_sectors(zv->zv_queue,
1870             (zvol_max_discard_blocks * zv->zv_volblocksize) >> 9);
1871         blk_queue_discard_granularity(zv->zv_queue, zv->zv_volblocksize);
1872         blk_queue_flag_set(QUEUE_FLAG_DISCARD, zv->zv_queue);
1873 #ifdef QUEUE_FLAG_NONROT
1874         blk_queue_flag_set(QUEUE_FLAG_NONROT, zv->zv_queue);
1875 #endif
1876 #ifdef QUEUE_FLAG_ADD_RANDOM
1877         blk_queue_flag_clear(QUEUE_FLAG_ADD_RANDOM, zv->zv_queue);
1878 #endif
1879
1880         if (spa_writeable(dmu_objset_spa(os))) {
1881                 if (zil_replay_disable)
1882                         zil_destroy(dmu_objset_zil(os), B_FALSE);
1883                 else
1884                         zil_replay(os, zv, zvol_replay_vector);
1885         }
1886         ASSERT3P(zv->zv_kstat.dk_kstats, ==, NULL);
1887         dataset_kstats_create(&zv->zv_kstat, zv->zv_objset);
1888
1889         /*
1890          * When udev detects the addition of the device it will immediately
1891          * invoke blkid(8) to determine the type of content on the device.
1892          * Prefetching the blocks commonly scanned by blkid(8) will speed
1893          * up this process.
1894          */
1895         len = MIN(MAX(zvol_prefetch_bytes, 0), SPA_MAXBLOCKSIZE);
1896         if (len > 0) {
1897                 dmu_prefetch(os, ZVOL_OBJ, 0, 0, len, ZIO_PRIORITY_SYNC_READ);
1898                 dmu_prefetch(os, ZVOL_OBJ, 0, volsize - len, len,
1899                     ZIO_PRIORITY_SYNC_READ);
1900         }
1901
1902         zv->zv_objset = NULL;
1903 out_dmu_objset_disown:
1904         dmu_objset_disown(os, B_TRUE, FTAG);
1905 out_doi:
1906         kmem_free(doi, sizeof (dmu_object_info_t));
1907
1908         if (error == 0) {
1909                 rw_enter(&zvol_state_lock, RW_WRITER);
1910                 zvol_insert(zv);
1911                 rw_exit(&zvol_state_lock);
1912                 add_disk(zv->zv_disk);
1913         } else {
1914                 ida_simple_remove(&zvol_ida, idx);
1915         }
1916
1917         return (SET_ERROR(error));
1918 }
1919
1920 /*
1921  * Rename a block device minor mode for the specified volume.
1922  */
1923 static void
1924 zvol_rename_minor(zvol_state_t *zv, const char *newname)
1925 {
1926         int readonly = get_disk_ro(zv->zv_disk);
1927
1928         ASSERT(RW_LOCK_HELD(&zvol_state_lock));
1929         ASSERT(MUTEX_HELD(&zv->zv_state_lock));
1930
1931         strlcpy(zv->zv_name, newname, sizeof (zv->zv_name));
1932
1933         /* move to new hashtable entry  */
1934         zv->zv_hash = zvol_name_hash(zv->zv_name);
1935         hlist_del(&zv->zv_hlink);
1936         hlist_add_head(&zv->zv_hlink, ZVOL_HT_HEAD(zv->zv_hash));
1937
1938         /*
1939          * The block device's read-only state is briefly changed causing
1940          * a KOBJ_CHANGE uevent to be issued.  This ensures udev detects
1941          * the name change and fixes the symlinks.  This does not change
1942          * ZVOL_RDONLY in zv->zv_flags so the actual read-only state never
1943          * changes.  This would normally be done using kobject_uevent() but
1944          * that is a GPL-only symbol which is why we need this workaround.
1945          */
1946         set_disk_ro(zv->zv_disk, !readonly);
1947         set_disk_ro(zv->zv_disk, readonly);
1948 }
1949
1950 typedef struct minors_job {
1951         list_t *list;
1952         list_node_t link;
1953         /* input */
1954         char *name;
1955         /* output */
1956         int error;
1957 } minors_job_t;
1958
1959 /*
1960  * Prefetch zvol dnodes for the minors_job
1961  */
1962 static void
1963 zvol_prefetch_minors_impl(void *arg)
1964 {
1965         minors_job_t *job = arg;
1966         char *dsname = job->name;
1967         objset_t *os = NULL;
1968
1969         job->error = dmu_objset_own(dsname, DMU_OST_ZVOL, B_TRUE, B_TRUE,
1970             FTAG, &os);
1971         if (job->error == 0) {
1972                 dmu_prefetch(os, ZVOL_OBJ, 0, 0, 0, ZIO_PRIORITY_SYNC_READ);
1973                 dmu_objset_disown(os, B_TRUE, FTAG);
1974         }
1975 }
1976
1977 /*
1978  * Mask errors to continue dmu_objset_find() traversal
1979  */
1980 static int
1981 zvol_create_snap_minor_cb(const char *dsname, void *arg)
1982 {
1983         minors_job_t *j = arg;
1984         list_t *minors_list = j->list;
1985         const char *name = j->name;
1986
1987         ASSERT0(MUTEX_HELD(&spa_namespace_lock));
1988
1989         /* skip the designated dataset */
1990         if (name && strcmp(dsname, name) == 0)
1991                 return (0);
1992
1993         /* at this point, the dsname should name a snapshot */
1994         if (strchr(dsname, '@') == 0) {
1995                 dprintf("zvol_create_snap_minor_cb(): "
1996                     "%s is not a shapshot name\n", dsname);
1997         } else {
1998                 minors_job_t *job;
1999                 char *n = strdup(dsname);
2000                 if (n == NULL)
2001                         return (0);
2002
2003                 job = kmem_alloc(sizeof (minors_job_t), KM_SLEEP);
2004                 job->name = n;
2005                 job->list = minors_list;
2006                 job->error = 0;
2007                 list_insert_tail(minors_list, job);
2008                 /* don't care if dispatch fails, because job->error is 0 */
2009                 taskq_dispatch(system_taskq, zvol_prefetch_minors_impl, job,
2010                     TQ_SLEEP);
2011         }
2012
2013         return (0);
2014 }
2015
2016 /*
2017  * Mask errors to continue dmu_objset_find() traversal
2018  */
2019 static int
2020 zvol_create_minors_cb(const char *dsname, void *arg)
2021 {
2022         uint64_t snapdev;
2023         int error;
2024         list_t *minors_list = arg;
2025
2026         ASSERT0(MUTEX_HELD(&spa_namespace_lock));
2027
2028         error = dsl_prop_get_integer(dsname, "snapdev", &snapdev, NULL);
2029         if (error)
2030                 return (0);
2031
2032         /*
2033          * Given the name and the 'snapdev' property, create device minor nodes
2034          * with the linkages to zvols/snapshots as needed.
2035          * If the name represents a zvol, create a minor node for the zvol, then
2036          * check if its snapshots are 'visible', and if so, iterate over the
2037          * snapshots and create device minor nodes for those.
2038          */
2039         if (strchr(dsname, '@') == 0) {
2040                 minors_job_t *job;
2041                 char *n = strdup(dsname);
2042                 if (n == NULL)
2043                         return (0);
2044
2045                 job = kmem_alloc(sizeof (minors_job_t), KM_SLEEP);
2046                 job->name = n;
2047                 job->list = minors_list;
2048                 job->error = 0;
2049                 list_insert_tail(minors_list, job);
2050                 /* don't care if dispatch fails, because job->error is 0 */
2051                 taskq_dispatch(system_taskq, zvol_prefetch_minors_impl, job,
2052                     TQ_SLEEP);
2053
2054                 if (snapdev == ZFS_SNAPDEV_VISIBLE) {
2055                         /*
2056                          * traverse snapshots only, do not traverse children,
2057                          * and skip the 'dsname'
2058                          */
2059                         error = dmu_objset_find((char *)dsname,
2060                             zvol_create_snap_minor_cb, (void *)job,
2061                             DS_FIND_SNAPSHOTS);
2062                 }
2063         } else {
2064                 dprintf("zvol_create_minors_cb(): %s is not a zvol name\n",
2065                     dsname);
2066         }
2067
2068         return (0);
2069 }
2070
2071 /*
2072  * Create minors for the specified dataset, including children and snapshots.
2073  * Pay attention to the 'snapdev' property and iterate over the snapshots
2074  * only if they are 'visible'. This approach allows one to assure that the
2075  * snapshot metadata is read from disk only if it is needed.
2076  *
2077  * The name can represent a dataset to be recursively scanned for zvols and
2078  * their snapshots, or a single zvol snapshot. If the name represents a
2079  * dataset, the scan is performed in two nested stages:
2080  * - scan the dataset for zvols, and
2081  * - for each zvol, create a minor node, then check if the zvol's snapshots
2082  *   are 'visible', and only then iterate over the snapshots if needed
2083  *
2084  * If the name represents a snapshot, a check is performed if the snapshot is
2085  * 'visible' (which also verifies that the parent is a zvol), and if so,
2086  * a minor node for that snapshot is created.
2087  */
2088 static int
2089 zvol_create_minors_impl(const char *name)
2090 {
2091         int error = 0;
2092         fstrans_cookie_t cookie;
2093         char *atp, *parent;
2094         list_t minors_list;
2095         minors_job_t *job;
2096
2097         if (zvol_inhibit_dev)
2098                 return (0);
2099
2100         /*
2101          * This is the list for prefetch jobs. Whenever we found a match
2102          * during dmu_objset_find, we insert a minors_job to the list and do
2103          * taskq_dispatch to parallel prefetch zvol dnodes. Note we don't need
2104          * any lock because all list operation is done on the current thread.
2105          *
2106          * We will use this list to do zvol_create_minor_impl after prefetch
2107          * so we don't have to traverse using dmu_objset_find again.
2108          */
2109         list_create(&minors_list, sizeof (minors_job_t),
2110             offsetof(minors_job_t, link));
2111
2112         parent = kmem_alloc(MAXPATHLEN, KM_SLEEP);
2113         (void) strlcpy(parent, name, MAXPATHLEN);
2114
2115         if ((atp = strrchr(parent, '@')) != NULL) {
2116                 uint64_t snapdev;
2117
2118                 *atp = '\0';
2119                 error = dsl_prop_get_integer(parent, "snapdev",
2120                     &snapdev, NULL);
2121
2122                 if (error == 0 && snapdev == ZFS_SNAPDEV_VISIBLE)
2123                         error = zvol_create_minor_impl(name);
2124         } else {
2125                 cookie = spl_fstrans_mark();
2126                 error = dmu_objset_find(parent, zvol_create_minors_cb,
2127                     &minors_list, DS_FIND_CHILDREN);
2128                 spl_fstrans_unmark(cookie);
2129         }
2130
2131         kmem_free(parent, MAXPATHLEN);
2132         taskq_wait_outstanding(system_taskq, 0);
2133
2134         /*
2135          * Prefetch is completed, we can do zvol_create_minor_impl
2136          * sequentially.
2137          */
2138         while ((job = list_head(&minors_list)) != NULL) {
2139                 list_remove(&minors_list, job);
2140                 if (!job->error)
2141                         zvol_create_minor_impl(job->name);
2142                 strfree(job->name);
2143                 kmem_free(job, sizeof (minors_job_t));
2144         }
2145
2146         list_destroy(&minors_list);
2147
2148         return (SET_ERROR(error));
2149 }
2150
2151 /*
2152  * Remove minors for specified dataset including children and snapshots.
2153  */
2154 static void
2155 zvol_remove_minors_impl(const char *name)
2156 {
2157         zvol_state_t *zv, *zv_next;
2158         int namelen = ((name) ? strlen(name) : 0);
2159         taskqid_t t, tid = TASKQID_INVALID;
2160         list_t free_list;
2161
2162         if (zvol_inhibit_dev)
2163                 return;
2164
2165         list_create(&free_list, sizeof (zvol_state_t),
2166             offsetof(zvol_state_t, zv_next));
2167
2168         rw_enter(&zvol_state_lock, RW_WRITER);
2169
2170         for (zv = list_head(&zvol_state_list); zv != NULL; zv = zv_next) {
2171                 zv_next = list_next(&zvol_state_list, zv);
2172
2173                 mutex_enter(&zv->zv_state_lock);
2174                 if (name == NULL || strcmp(zv->zv_name, name) == 0 ||
2175                     (strncmp(zv->zv_name, name, namelen) == 0 &&
2176                     (zv->zv_name[namelen] == '/' ||
2177                     zv->zv_name[namelen] == '@'))) {
2178                         /*
2179                          * By holding zv_state_lock here, we guarantee that no
2180                          * one is currently using this zv
2181                          */
2182
2183                         /* If in use, leave alone */
2184                         if (zv->zv_open_count > 0 ||
2185                             atomic_read(&zv->zv_suspend_ref)) {
2186                                 mutex_exit(&zv->zv_state_lock);
2187                                 continue;
2188                         }
2189
2190                         zvol_remove(zv);
2191
2192                         /*
2193                          * Cleared while holding zvol_state_lock as a writer
2194                          * which will prevent zvol_open() from opening it.
2195                          */
2196                         zv->zv_disk->private_data = NULL;
2197
2198                         /* Drop zv_state_lock before zvol_free() */
2199                         mutex_exit(&zv->zv_state_lock);
2200
2201                         /* Try parallel zv_free, if failed do it in place */
2202                         t = taskq_dispatch(system_taskq, zvol_free, zv,
2203                             TQ_SLEEP);
2204                         if (t == TASKQID_INVALID)
2205                                 list_insert_head(&free_list, zv);
2206                         else
2207                                 tid = t;
2208                 } else {
2209                         mutex_exit(&zv->zv_state_lock);
2210                 }
2211         }
2212         rw_exit(&zvol_state_lock);
2213
2214         /* Drop zvol_state_lock before calling zvol_free() */
2215         while ((zv = list_head(&free_list)) != NULL) {
2216                 list_remove(&free_list, zv);
2217                 zvol_free(zv);
2218         }
2219
2220         if (tid != TASKQID_INVALID)
2221                 taskq_wait_outstanding(system_taskq, tid);
2222 }
2223
2224 /* Remove minor for this specific volume only */
2225 static void
2226 zvol_remove_minor_impl(const char *name)
2227 {
2228         zvol_state_t *zv = NULL, *zv_next;
2229
2230         if (zvol_inhibit_dev)
2231                 return;
2232
2233         rw_enter(&zvol_state_lock, RW_WRITER);
2234
2235         for (zv = list_head(&zvol_state_list); zv != NULL; zv = zv_next) {
2236                 zv_next = list_next(&zvol_state_list, zv);
2237
2238                 mutex_enter(&zv->zv_state_lock);
2239                 if (strcmp(zv->zv_name, name) == 0) {
2240                         /*
2241                          * By holding zv_state_lock here, we guarantee that no
2242                          * one is currently using this zv
2243                          */
2244
2245                         /* If in use, leave alone */
2246                         if (zv->zv_open_count > 0 ||
2247                             atomic_read(&zv->zv_suspend_ref)) {
2248                                 mutex_exit(&zv->zv_state_lock);
2249                                 continue;
2250                         }
2251                         zvol_remove(zv);
2252
2253                         /*
2254                          * Cleared while holding zvol_state_lock as a writer
2255                          * which will prevent zvol_open() from opening it.
2256                          */
2257                         zv->zv_disk->private_data = NULL;
2258
2259                         mutex_exit(&zv->zv_state_lock);
2260                         break;
2261                 } else {
2262                         mutex_exit(&zv->zv_state_lock);
2263                 }
2264         }
2265
2266         /* Drop zvol_state_lock before calling zvol_free() */
2267         rw_exit(&zvol_state_lock);
2268
2269         if (zv != NULL)
2270                 zvol_free(zv);
2271 }
2272
2273 /*
2274  * Rename minors for specified dataset including children and snapshots.
2275  */
2276 static void
2277 zvol_rename_minors_impl(const char *oldname, const char *newname)
2278 {
2279         zvol_state_t *zv, *zv_next;
2280         int oldnamelen, newnamelen;
2281
2282         if (zvol_inhibit_dev)
2283                 return;
2284
2285         oldnamelen = strlen(oldname);
2286         newnamelen = strlen(newname);
2287
2288         rw_enter(&zvol_state_lock, RW_READER);
2289
2290         for (zv = list_head(&zvol_state_list); zv != NULL; zv = zv_next) {
2291                 zv_next = list_next(&zvol_state_list, zv);
2292
2293                 mutex_enter(&zv->zv_state_lock);
2294
2295                 if (strcmp(zv->zv_name, oldname) == 0) {
2296                         zvol_rename_minor(zv, newname);
2297                 } else if (strncmp(zv->zv_name, oldname, oldnamelen) == 0 &&
2298                     (zv->zv_name[oldnamelen] == '/' ||
2299                     zv->zv_name[oldnamelen] == '@')) {
2300                         char *name = kmem_asprintf("%s%c%s", newname,
2301                             zv->zv_name[oldnamelen],
2302                             zv->zv_name + oldnamelen + 1);
2303                         zvol_rename_minor(zv, name);
2304                         strfree(name);
2305                 }
2306
2307                 mutex_exit(&zv->zv_state_lock);
2308         }
2309
2310         rw_exit(&zvol_state_lock);
2311 }
2312
2313 typedef struct zvol_snapdev_cb_arg {
2314         uint64_t snapdev;
2315 } zvol_snapdev_cb_arg_t;
2316
2317 static int
2318 zvol_set_snapdev_cb(const char *dsname, void *param)
2319 {
2320         zvol_snapdev_cb_arg_t *arg = param;
2321
2322         if (strchr(dsname, '@') == NULL)
2323                 return (0);
2324
2325         switch (arg->snapdev) {
2326                 case ZFS_SNAPDEV_VISIBLE:
2327                         (void) zvol_create_minor_impl(dsname);
2328                         break;
2329                 case ZFS_SNAPDEV_HIDDEN:
2330                         (void) zvol_remove_minor_impl(dsname);
2331                         break;
2332         }
2333
2334         return (0);
2335 }
2336
2337 static void
2338 zvol_set_snapdev_impl(char *name, uint64_t snapdev)
2339 {
2340         zvol_snapdev_cb_arg_t arg = {snapdev};
2341         fstrans_cookie_t cookie = spl_fstrans_mark();
2342         /*
2343          * The zvol_set_snapdev_sync() sets snapdev appropriately
2344          * in the dataset hierarchy. Here, we only scan snapshots.
2345          */
2346         dmu_objset_find(name, zvol_set_snapdev_cb, &arg, DS_FIND_SNAPSHOTS);
2347         spl_fstrans_unmark(cookie);
2348 }
2349
2350 typedef struct zvol_volmode_cb_arg {
2351         uint64_t volmode;
2352 } zvol_volmode_cb_arg_t;
2353
2354 static void
2355 zvol_set_volmode_impl(char *name, uint64_t volmode)
2356 {
2357         fstrans_cookie_t cookie = spl_fstrans_mark();
2358
2359         if (strchr(name, '@') != NULL)
2360                 return;
2361
2362         /*
2363          * It's unfortunate we need to remove minors before we create new ones:
2364          * this is necessary because our backing gendisk (zvol_state->zv_disk)
2365          * coule be different when we set, for instance, volmode from "geom"
2366          * to "dev" (or vice versa).
2367          * A possible optimization is to modify our consumers so we don't get
2368          * called when "volmode" does not change.
2369          */
2370         switch (volmode) {
2371                 case ZFS_VOLMODE_NONE:
2372                         (void) zvol_remove_minor_impl(name);
2373                         break;
2374                 case ZFS_VOLMODE_GEOM:
2375                 case ZFS_VOLMODE_DEV:
2376                         (void) zvol_remove_minor_impl(name);
2377                         (void) zvol_create_minor_impl(name);
2378                         break;
2379                 case ZFS_VOLMODE_DEFAULT:
2380                         (void) zvol_remove_minor_impl(name);
2381                         if (zvol_volmode == ZFS_VOLMODE_NONE)
2382                                 break;
2383                         else /* if zvol_volmode is invalid defaults to "geom" */
2384                                 (void) zvol_create_minor_impl(name);
2385                         break;
2386         }
2387
2388         spl_fstrans_unmark(cookie);
2389 }
2390
2391 static zvol_task_t *
2392 zvol_task_alloc(zvol_async_op_t op, const char *name1, const char *name2,
2393     uint64_t value)
2394 {
2395         zvol_task_t *task;
2396         char *delim;
2397
2398         /* Never allow tasks on hidden names. */
2399         if (name1[0] == '$')
2400                 return (NULL);
2401
2402         task = kmem_zalloc(sizeof (zvol_task_t), KM_SLEEP);
2403         task->op = op;
2404         task->value = value;
2405         delim = strchr(name1, '/');
2406         strlcpy(task->pool, name1, delim ? (delim - name1 + 1) : MAXNAMELEN);
2407
2408         strlcpy(task->name1, name1, MAXNAMELEN);
2409         if (name2 != NULL)
2410                 strlcpy(task->name2, name2, MAXNAMELEN);
2411
2412         return (task);
2413 }
2414
2415 static void
2416 zvol_task_free(zvol_task_t *task)
2417 {
2418         kmem_free(task, sizeof (zvol_task_t));
2419 }
2420
2421 /*
2422  * The worker thread function performed asynchronously.
2423  */
2424 static void
2425 zvol_task_cb(void *param)
2426 {
2427         zvol_task_t *task = (zvol_task_t *)param;
2428
2429         switch (task->op) {
2430         case ZVOL_ASYNC_CREATE_MINORS:
2431                 (void) zvol_create_minors_impl(task->name1);
2432                 break;
2433         case ZVOL_ASYNC_REMOVE_MINORS:
2434                 zvol_remove_minors_impl(task->name1);
2435                 break;
2436         case ZVOL_ASYNC_RENAME_MINORS:
2437                 zvol_rename_minors_impl(task->name1, task->name2);
2438                 break;
2439         case ZVOL_ASYNC_SET_SNAPDEV:
2440                 zvol_set_snapdev_impl(task->name1, task->value);
2441                 break;
2442         case ZVOL_ASYNC_SET_VOLMODE:
2443                 zvol_set_volmode_impl(task->name1, task->value);
2444                 break;
2445         default:
2446                 VERIFY(0);
2447                 break;
2448         }
2449
2450         zvol_task_free(task);
2451 }
2452
2453 typedef struct zvol_set_prop_int_arg {
2454         const char *zsda_name;
2455         uint64_t zsda_value;
2456         zprop_source_t zsda_source;
2457         dmu_tx_t *zsda_tx;
2458 } zvol_set_prop_int_arg_t;
2459
2460 /*
2461  * Sanity check the dataset for safe use by the sync task.  No additional
2462  * conditions are imposed.
2463  */
2464 static int
2465 zvol_set_snapdev_check(void *arg, dmu_tx_t *tx)
2466 {
2467         zvol_set_prop_int_arg_t *zsda = arg;
2468         dsl_pool_t *dp = dmu_tx_pool(tx);
2469         dsl_dir_t *dd;
2470         int error;
2471
2472         error = dsl_dir_hold(dp, zsda->zsda_name, FTAG, &dd, NULL);
2473         if (error != 0)
2474                 return (error);
2475
2476         dsl_dir_rele(dd, FTAG);
2477
2478         return (error);
2479 }
2480
2481 /* ARGSUSED */
2482 static int
2483 zvol_set_snapdev_sync_cb(dsl_pool_t *dp, dsl_dataset_t *ds, void *arg)
2484 {
2485         char dsname[MAXNAMELEN];
2486         zvol_task_t *task;
2487         uint64_t snapdev;
2488
2489         dsl_dataset_name(ds, dsname);
2490         if (dsl_prop_get_int_ds(ds, "snapdev", &snapdev) != 0)
2491                 return (0);
2492         task = zvol_task_alloc(ZVOL_ASYNC_SET_SNAPDEV, dsname, NULL, snapdev);
2493         if (task == NULL)
2494                 return (0);
2495
2496         (void) taskq_dispatch(dp->dp_spa->spa_zvol_taskq, zvol_task_cb,
2497             task, TQ_SLEEP);
2498         return (0);
2499 }
2500
2501 /*
2502  * Traverse all child datasets and apply snapdev appropriately.
2503  * We call dsl_prop_set_sync_impl() here to set the value only on the toplevel
2504  * dataset and read the effective "snapdev" on every child in the callback
2505  * function: this is because the value is not guaranteed to be the same in the
2506  * whole dataset hierarchy.
2507  */
2508 static void
2509 zvol_set_snapdev_sync(void *arg, dmu_tx_t *tx)
2510 {
2511         zvol_set_prop_int_arg_t *zsda = arg;
2512         dsl_pool_t *dp = dmu_tx_pool(tx);
2513         dsl_dir_t *dd;
2514         dsl_dataset_t *ds;
2515         int error;
2516
2517         VERIFY0(dsl_dir_hold(dp, zsda->zsda_name, FTAG, &dd, NULL));
2518         zsda->zsda_tx = tx;
2519
2520         error = dsl_dataset_hold(dp, zsda->zsda_name, FTAG, &ds);
2521         if (error == 0) {
2522                 dsl_prop_set_sync_impl(ds, zfs_prop_to_name(ZFS_PROP_SNAPDEV),
2523                     zsda->zsda_source, sizeof (zsda->zsda_value), 1,
2524                     &zsda->zsda_value, zsda->zsda_tx);
2525                 dsl_dataset_rele(ds, FTAG);
2526         }
2527         dmu_objset_find_dp(dp, dd->dd_object, zvol_set_snapdev_sync_cb,
2528             zsda, DS_FIND_CHILDREN);
2529
2530         dsl_dir_rele(dd, FTAG);
2531 }
2532
2533 int
2534 zvol_set_snapdev(const char *ddname, zprop_source_t source, uint64_t snapdev)
2535 {
2536         zvol_set_prop_int_arg_t zsda;
2537
2538         zsda.zsda_name = ddname;
2539         zsda.zsda_source = source;
2540         zsda.zsda_value = snapdev;
2541
2542         return (dsl_sync_task(ddname, zvol_set_snapdev_check,
2543             zvol_set_snapdev_sync, &zsda, 0, ZFS_SPACE_CHECK_NONE));
2544 }
2545
2546 /*
2547  * Sanity check the dataset for safe use by the sync task.  No additional
2548  * conditions are imposed.
2549  */
2550 static int
2551 zvol_set_volmode_check(void *arg, dmu_tx_t *tx)
2552 {
2553         zvol_set_prop_int_arg_t *zsda = arg;
2554         dsl_pool_t *dp = dmu_tx_pool(tx);
2555         dsl_dir_t *dd;
2556         int error;
2557
2558         error = dsl_dir_hold(dp, zsda->zsda_name, FTAG, &dd, NULL);
2559         if (error != 0)
2560                 return (error);
2561
2562         dsl_dir_rele(dd, FTAG);
2563
2564         return (error);
2565 }
2566
2567 /* ARGSUSED */
2568 static int
2569 zvol_set_volmode_sync_cb(dsl_pool_t *dp, dsl_dataset_t *ds, void *arg)
2570 {
2571         char dsname[MAXNAMELEN];
2572         zvol_task_t *task;
2573         uint64_t volmode;
2574
2575         dsl_dataset_name(ds, dsname);
2576         if (dsl_prop_get_int_ds(ds, "volmode", &volmode) != 0)
2577                 return (0);
2578         task = zvol_task_alloc(ZVOL_ASYNC_SET_VOLMODE, dsname, NULL, volmode);
2579         if (task == NULL)
2580                 return (0);
2581
2582         (void) taskq_dispatch(dp->dp_spa->spa_zvol_taskq, zvol_task_cb,
2583             task, TQ_SLEEP);
2584         return (0);
2585 }
2586
2587 /*
2588  * Traverse all child datasets and apply volmode appropriately.
2589  * We call dsl_prop_set_sync_impl() here to set the value only on the toplevel
2590  * dataset and read the effective "volmode" on every child in the callback
2591  * function: this is because the value is not guaranteed to be the same in the
2592  * whole dataset hierarchy.
2593  */
2594 static void
2595 zvol_set_volmode_sync(void *arg, dmu_tx_t *tx)
2596 {
2597         zvol_set_prop_int_arg_t *zsda = arg;
2598         dsl_pool_t *dp = dmu_tx_pool(tx);
2599         dsl_dir_t *dd;
2600         dsl_dataset_t *ds;
2601         int error;
2602
2603         VERIFY0(dsl_dir_hold(dp, zsda->zsda_name, FTAG, &dd, NULL));
2604         zsda->zsda_tx = tx;
2605
2606         error = dsl_dataset_hold(dp, zsda->zsda_name, FTAG, &ds);
2607         if (error == 0) {
2608                 dsl_prop_set_sync_impl(ds, zfs_prop_to_name(ZFS_PROP_VOLMODE),
2609                     zsda->zsda_source, sizeof (zsda->zsda_value), 1,
2610                     &zsda->zsda_value, zsda->zsda_tx);
2611                 dsl_dataset_rele(ds, FTAG);
2612         }
2613
2614         dmu_objset_find_dp(dp, dd->dd_object, zvol_set_volmode_sync_cb,
2615             zsda, DS_FIND_CHILDREN);
2616
2617         dsl_dir_rele(dd, FTAG);
2618 }
2619
2620 int
2621 zvol_set_volmode(const char *ddname, zprop_source_t source, uint64_t volmode)
2622 {
2623         zvol_set_prop_int_arg_t zsda;
2624
2625         zsda.zsda_name = ddname;
2626         zsda.zsda_source = source;
2627         zsda.zsda_value = volmode;
2628
2629         return (dsl_sync_task(ddname, zvol_set_volmode_check,
2630             zvol_set_volmode_sync, &zsda, 0, ZFS_SPACE_CHECK_NONE));
2631 }
2632
2633 void
2634 zvol_create_minors(spa_t *spa, const char *name, boolean_t async)
2635 {
2636         zvol_task_t *task;
2637         taskqid_t id;
2638
2639         task = zvol_task_alloc(ZVOL_ASYNC_CREATE_MINORS, name, NULL, ~0ULL);
2640         if (task == NULL)
2641                 return;
2642
2643         id = taskq_dispatch(spa->spa_zvol_taskq, zvol_task_cb, task, TQ_SLEEP);
2644         if ((async == B_FALSE) && (id != TASKQID_INVALID))
2645                 taskq_wait_id(spa->spa_zvol_taskq, id);
2646 }
2647
2648 void
2649 zvol_remove_minors(spa_t *spa, const char *name, boolean_t async)
2650 {
2651         zvol_task_t *task;
2652         taskqid_t id;
2653
2654         task = zvol_task_alloc(ZVOL_ASYNC_REMOVE_MINORS, name, NULL, ~0ULL);
2655         if (task == NULL)
2656                 return;
2657
2658         id = taskq_dispatch(spa->spa_zvol_taskq, zvol_task_cb, task, TQ_SLEEP);
2659         if ((async == B_FALSE) && (id != TASKQID_INVALID))
2660                 taskq_wait_id(spa->spa_zvol_taskq, id);
2661 }
2662
2663 void
2664 zvol_rename_minors(spa_t *spa, const char *name1, const char *name2,
2665     boolean_t async)
2666 {
2667         zvol_task_t *task;
2668         taskqid_t id;
2669
2670         task = zvol_task_alloc(ZVOL_ASYNC_RENAME_MINORS, name1, name2, ~0ULL);
2671         if (task == NULL)
2672                 return;
2673
2674         id = taskq_dispatch(spa->spa_zvol_taskq, zvol_task_cb, task, TQ_SLEEP);
2675         if ((async == B_FALSE) && (id != TASKQID_INVALID))
2676                 taskq_wait_id(spa->spa_zvol_taskq, id);
2677 }
2678
2679 int
2680 zvol_init(void)
2681 {
2682         int threads = MIN(MAX(zvol_threads, 1), 1024);
2683         int i, error;
2684
2685         list_create(&zvol_state_list, sizeof (zvol_state_t),
2686             offsetof(zvol_state_t, zv_next));
2687         rw_init(&zvol_state_lock, NULL, RW_DEFAULT, NULL);
2688         ida_init(&zvol_ida);
2689
2690         zvol_taskq = taskq_create(ZVOL_DRIVER, threads, maxclsyspri,
2691             threads * 2, INT_MAX, TASKQ_PREPOPULATE | TASKQ_DYNAMIC);
2692         if (zvol_taskq == NULL) {
2693                 printk(KERN_INFO "ZFS: taskq_create() failed\n");
2694                 error = -ENOMEM;
2695                 goto out;
2696         }
2697
2698         zvol_htable = kmem_alloc(ZVOL_HT_SIZE * sizeof (struct hlist_head),
2699             KM_SLEEP);
2700         if (!zvol_htable) {
2701                 error = -ENOMEM;
2702                 goto out_taskq;
2703         }
2704         for (i = 0; i < ZVOL_HT_SIZE; i++)
2705                 INIT_HLIST_HEAD(&zvol_htable[i]);
2706
2707         error = register_blkdev(zvol_major, ZVOL_DRIVER);
2708         if (error) {
2709                 printk(KERN_INFO "ZFS: register_blkdev() failed %d\n", error);
2710                 goto out_free;
2711         }
2712
2713         blk_register_region(MKDEV(zvol_major, 0), 1UL << MINORBITS,
2714             THIS_MODULE, zvol_probe, NULL, NULL);
2715
2716         return (0);
2717
2718 out_free:
2719         kmem_free(zvol_htable, ZVOL_HT_SIZE * sizeof (struct hlist_head));
2720 out_taskq:
2721         taskq_destroy(zvol_taskq);
2722 out:
2723         ida_destroy(&zvol_ida);
2724         rw_destroy(&zvol_state_lock);
2725         list_destroy(&zvol_state_list);
2726
2727         return (SET_ERROR(error));
2728 }
2729
2730 void
2731 zvol_fini(void)
2732 {
2733         zvol_remove_minors_impl(NULL);
2734
2735         blk_unregister_region(MKDEV(zvol_major, 0), 1UL << MINORBITS);
2736         unregister_blkdev(zvol_major, ZVOL_DRIVER);
2737         kmem_free(zvol_htable, ZVOL_HT_SIZE * sizeof (struct hlist_head));
2738
2739         taskq_destroy(zvol_taskq);
2740         list_destroy(&zvol_state_list);
2741         rw_destroy(&zvol_state_lock);
2742
2743         ida_destroy(&zvol_ida);
2744 }
2745
2746 /* BEGIN CSTYLED */
2747 module_param(zvol_inhibit_dev, uint, 0644);
2748 MODULE_PARM_DESC(zvol_inhibit_dev, "Do not create zvol device nodes");
2749
2750 module_param(zvol_major, uint, 0444);
2751 MODULE_PARM_DESC(zvol_major, "Major number for zvol device");
2752
2753 module_param(zvol_threads, uint, 0444);
2754 MODULE_PARM_DESC(zvol_threads, "Max number of threads to handle I/O requests");
2755
2756 module_param(zvol_request_sync, uint, 0644);
2757 MODULE_PARM_DESC(zvol_request_sync, "Synchronously handle bio requests");
2758
2759 module_param(zvol_max_discard_blocks, ulong, 0444);
2760 MODULE_PARM_DESC(zvol_max_discard_blocks, "Max number of blocks to discard");
2761
2762 module_param(zvol_prefetch_bytes, uint, 0644);
2763 MODULE_PARM_DESC(zvol_prefetch_bytes, "Prefetch N bytes at zvol start+end");
2764
2765 module_param(zvol_volmode, uint, 0644);
2766 MODULE_PARM_DESC(zvol_volmode, "Default volmode property value");
2767 /* END CSTYLED */