Fix 'zfs set volsize=N pool/dataset'
[zfs.git] / module / zfs / zvol.c
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright (C) 2008-2010 Lawrence Livermore National Security, LLC.
23  * Produced at Lawrence Livermore National Laboratory (cf, DISCLAIMER).
24  * Rewritten for Linux by Brian Behlendorf <behlendorf1@llnl.gov>.
25  * LLNL-CODE-403049.
26  *
27  * ZFS volume emulation driver.
28  *
29  * Makes a DMU object look like a volume of arbitrary size, up to 2^64 bytes.
30  * Volumes are accessed through the symbolic links named:
31  *
32  * /dev/<pool_name>/<dataset_name>
33  *
34  * Volumes are persistent through reboot and module load.  No user command
35  * needs to be run before opening and using a device.
36  */
37
38 #include <sys/dmu_traverse.h>
39 #include <sys/dsl_dataset.h>
40 #include <sys/dsl_prop.h>
41 #include <sys/zap.h>
42 #include <sys/zil_impl.h>
43 #include <sys/zio.h>
44 #include <sys/zfs_rlock.h>
45 #include <sys/zfs_znode.h>
46 #include <sys/zvol.h>
47 #include <linux/blkdev_compat.h>
48
49 unsigned int zvol_major = ZVOL_MAJOR;
50 unsigned int zvol_threads = 0;
51
52 static taskq_t *zvol_taskq;
53 static kmutex_t zvol_state_lock;
54 static list_t zvol_state_list;
55 static char *zvol_tag = "zvol_tag";
56
57 /*
58  * The in-core state of each volume.
59  */
60 typedef struct zvol_state {
61         char                    zv_name[MAXNAMELEN];    /* name */
62         uint64_t                zv_volsize;     /* advertised space */
63         uint64_t                zv_volblocksize;/* volume block size */
64         objset_t                *zv_objset;     /* objset handle */
65         uint32_t                zv_flags;       /* ZVOL_* flags */
66         uint32_t                zv_open_count;  /* open counts */
67         uint32_t                zv_changed;     /* disk changed */
68         zilog_t                 *zv_zilog;      /* ZIL handle */
69         znode_t                 zv_znode;       /* for range locking */
70         dmu_buf_t               *zv_dbuf;       /* bonus handle */
71         dev_t                   zv_dev;         /* device id */
72         struct gendisk          *zv_disk;       /* generic disk */
73         struct request_queue    *zv_queue;      /* request queue */
74         spinlock_t              zv_lock;        /* request queue lock */
75         list_node_t             zv_next;        /* next zvol_state_t linkage */
76 } zvol_state_t;
77
78 #define ZVOL_RDONLY     0x1
79
80 /*
81  * Find the next available range of ZVOL_MINORS minor numbers.  The
82  * zvol_state_list is kept in ascending minor order so we simply need
83  * to scan the list for the first gap in the sequence.  This allows us
84  * to recycle minor number as devices are created and removed.
85  */
86 static int
87 zvol_find_minor(unsigned *minor)
88 {
89         zvol_state_t *zv;
90
91         *minor = 0;
92         ASSERT(MUTEX_HELD(&zvol_state_lock));
93         for (zv = list_head(&zvol_state_list); zv != NULL;
94              zv = list_next(&zvol_state_list, zv), *minor += ZVOL_MINORS) {
95                 if (MINOR(zv->zv_dev) != MINOR(*minor))
96                         break;
97         }
98
99         /* All minors are in use */
100         if (*minor >= (1 << MINORBITS))
101                 return ENXIO;
102
103         return 0;
104 }
105
106 /*
107  * Find a zvol_state_t given the full major+minor dev_t.
108  */
109 static zvol_state_t *
110 zvol_find_by_dev(dev_t dev)
111 {
112         zvol_state_t *zv;
113
114         ASSERT(MUTEX_HELD(&zvol_state_lock));
115         for (zv = list_head(&zvol_state_list); zv != NULL;
116              zv = list_next(&zvol_state_list, zv)) {
117                 if (zv->zv_dev == dev)
118                         return zv;
119         }
120
121         return NULL;
122 }
123
124 /*
125  * Find a zvol_state_t given the name provided at zvol_alloc() time.
126  */
127 static zvol_state_t *
128 zvol_find_by_name(const char *name)
129 {
130         zvol_state_t *zv;
131
132         ASSERT(MUTEX_HELD(&zvol_state_lock));
133         for (zv = list_head(&zvol_state_list); zv != NULL;
134              zv = list_next(&zvol_state_list, zv)) {
135                 if (!strncmp(zv->zv_name, name, MAXNAMELEN))
136                         return zv;
137         }
138
139         return NULL;
140 }
141
142 /*
143  * ZFS_IOC_CREATE callback handles dmu zvol and zap object creation.
144  */
145 void
146 zvol_create_cb(objset_t *os, void *arg, cred_t *cr, dmu_tx_t *tx)
147 {
148         zfs_creat_t *zct = arg;
149         nvlist_t *nvprops = zct->zct_props;
150         int error;
151         uint64_t volblocksize, volsize;
152
153         VERIFY(nvlist_lookup_uint64(nvprops,
154             zfs_prop_to_name(ZFS_PROP_VOLSIZE), &volsize) == 0);
155         if (nvlist_lookup_uint64(nvprops,
156             zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE), &volblocksize) != 0)
157                 volblocksize = zfs_prop_default_numeric(ZFS_PROP_VOLBLOCKSIZE);
158
159         /*
160          * These properties must be removed from the list so the generic
161          * property setting step won't apply to them.
162          */
163         VERIFY(nvlist_remove_all(nvprops,
164             zfs_prop_to_name(ZFS_PROP_VOLSIZE)) == 0);
165         (void) nvlist_remove_all(nvprops,
166             zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE));
167
168         error = dmu_object_claim(os, ZVOL_OBJ, DMU_OT_ZVOL, volblocksize,
169             DMU_OT_NONE, 0, tx);
170         ASSERT(error == 0);
171
172         error = zap_create_claim(os, ZVOL_ZAP_OBJ, DMU_OT_ZVOL_PROP,
173             DMU_OT_NONE, 0, tx);
174         ASSERT(error == 0);
175
176         error = zap_update(os, ZVOL_ZAP_OBJ, "size", 8, 1, &volsize, tx);
177         ASSERT(error == 0);
178 }
179
180 /*
181  * ZFS_IOC_OBJSET_STATS entry point.
182  */
183 int
184 zvol_get_stats(objset_t *os, nvlist_t *nv)
185 {
186         int error;
187         dmu_object_info_t *doi;
188         uint64_t val;
189
190         error = zap_lookup(os, ZVOL_ZAP_OBJ, "size", 8, 1, &val);
191         if (error)
192                 return (error);
193
194         dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_VOLSIZE, val);
195         doi = kmem_alloc(sizeof(dmu_object_info_t), KM_SLEEP);
196         error = dmu_object_info(os, ZVOL_OBJ, doi);
197
198         if (error == 0) {
199                 dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_VOLBLOCKSIZE,
200                     doi->doi_data_block_size);
201         }
202
203         kmem_free(doi, sizeof(dmu_object_info_t));
204
205         return (error);
206 }
207
208 /*
209  * Sanity check volume size.
210  */
211 int
212 zvol_check_volsize(uint64_t volsize, uint64_t blocksize)
213 {
214         if (volsize == 0)
215                 return (EINVAL);
216
217         if (volsize % blocksize != 0)
218                 return (EINVAL);
219
220 #ifdef _ILP32
221         if (volsize - 1 > MAXOFFSET_T)
222                 return (EOVERFLOW);
223 #endif
224         return (0);
225 }
226
227 /*
228  * Ensure the zap is flushed then inform the VFS of the capacity change.
229  */
230 static int
231 zvol_update_volsize(zvol_state_t *zv, uint64_t volsize, objset_t *os)
232 {
233         struct block_device *bdev;
234         dmu_tx_t *tx;
235         int error;
236
237         ASSERT(MUTEX_HELD(&zvol_state_lock));
238
239         tx = dmu_tx_create(os);
240         dmu_tx_hold_zap(tx, ZVOL_ZAP_OBJ, TRUE, NULL);
241         error = dmu_tx_assign(tx, TXG_WAIT);
242         if (error) {
243                 dmu_tx_abort(tx);
244                 return (error);
245         }
246
247         error = zap_update(os, ZVOL_ZAP_OBJ, "size", 8, 1,
248             &volsize, tx);
249         dmu_tx_commit(tx);
250
251         if (error)
252                 return (error);
253
254         error = dmu_free_long_range(os,
255             ZVOL_OBJ, volsize, DMU_OBJECT_END);
256         if (error)
257                 return (error);
258
259         bdev = bdget_disk(zv->zv_disk, 0);
260         if (!bdev)
261                 return (EIO);
262 /*
263  * 2.6.28 API change
264  * Added check_disk_size_change() helper function.
265  */
266 #ifdef HAVE_CHECK_DISK_SIZE_CHANGE
267         set_capacity(zv->zv_disk, volsize >> 9);
268         zv->zv_volsize = volsize;
269         check_disk_size_change(zv->zv_disk, bdev);
270 #else
271         zv->zv_volsize = volsize;
272         zv->zv_changed = 1;
273         (void) check_disk_change(bdev);
274 #endif /* HAVE_CHECK_DISK_SIZE_CHANGE */
275
276         bdput(bdev);
277
278         return (0);
279 }
280
281 /*
282  * Set ZFS_PROP_VOLSIZE set entry point.
283  */
284 int
285 zvol_set_volsize(const char *name, uint64_t volsize)
286 {
287         zvol_state_t *zv;
288         dmu_object_info_t *doi;
289         objset_t *os = NULL;
290         uint64_t readonly;
291         int error;
292
293         mutex_enter(&zvol_state_lock);
294
295         zv = zvol_find_by_name(name);
296         if (zv == NULL) {
297                 error = ENXIO;
298                 goto out;
299         }
300
301         doi = kmem_alloc(sizeof(dmu_object_info_t), KM_SLEEP);
302
303         error = dmu_objset_hold(name, FTAG, &os);
304         if (error)
305                 goto out_doi;
306
307         if ((error = dmu_object_info(os, ZVOL_OBJ, doi)) != 0 ||
308             (error = zvol_check_volsize(volsize,doi->doi_data_block_size)) != 0)
309                 goto out_doi;
310
311         VERIFY(dsl_prop_get_integer(name, "readonly", &readonly, NULL) == 0);
312         if (readonly) {
313                 error = EROFS;
314                 goto out_doi;
315         }
316
317         if (get_disk_ro(zv->zv_disk) || (zv->zv_flags & ZVOL_RDONLY)) {
318                 error = EROFS;
319                 goto out_doi;
320         }
321
322         error = zvol_update_volsize(zv, volsize, os);
323 out_doi:
324         kmem_free(doi, sizeof(dmu_object_info_t));
325 out:
326         if (os)
327                 dmu_objset_rele(os, FTAG);
328
329         mutex_exit(&zvol_state_lock);
330
331         return (error);
332 }
333
334 /*
335  * Sanity check volume block size.
336  */
337 int
338 zvol_check_volblocksize(uint64_t volblocksize)
339 {
340         if (volblocksize < SPA_MINBLOCKSIZE ||
341             volblocksize > SPA_MAXBLOCKSIZE ||
342             !ISP2(volblocksize))
343                 return (EDOM);
344
345         return (0);
346 }
347
348 /*
349  * Set ZFS_PROP_VOLBLOCKSIZE set entry point.
350  */
351 int
352 zvol_set_volblocksize(const char *name, uint64_t volblocksize)
353 {
354         zvol_state_t *zv;
355         dmu_tx_t *tx;
356         int error;
357
358         mutex_enter(&zvol_state_lock);
359
360         zv = zvol_find_by_name(name);
361         if (zv == NULL) {
362                 error = ENXIO;
363                 goto out;
364         }
365
366         if (get_disk_ro(zv->zv_disk) || (zv->zv_flags & ZVOL_RDONLY)) {
367                 error = EROFS;
368                 goto out;
369         }
370
371         tx = dmu_tx_create(zv->zv_objset);
372         dmu_tx_hold_bonus(tx, ZVOL_OBJ);
373         error = dmu_tx_assign(tx, TXG_WAIT);
374         if (error) {
375                 dmu_tx_abort(tx);
376         } else {
377                 error = dmu_object_set_blocksize(zv->zv_objset, ZVOL_OBJ,
378                     volblocksize, 0, tx);
379                 if (error == ENOTSUP)
380                         error = EBUSY;
381                 dmu_tx_commit(tx);
382                 if (error == 0)
383                         zv->zv_volblocksize = volblocksize;
384         }
385 out:
386         mutex_exit(&zvol_state_lock);
387
388         return (error);
389 }
390
391 /*
392  * Replay a TX_WRITE ZIL transaction that didn't get committed
393  * after a system failure
394  */
395 static int
396 zvol_replay_write(zvol_state_t *zv, lr_write_t *lr, boolean_t byteswap)
397 {
398         objset_t *os = zv->zv_objset;
399         char *data = (char *)(lr + 1);  /* data follows lr_write_t */
400         uint64_t off = lr->lr_offset;
401         uint64_t len = lr->lr_length;
402         dmu_tx_t *tx;
403         int error;
404
405         if (byteswap)
406                 byteswap_uint64_array(lr, sizeof (*lr));
407
408         tx = dmu_tx_create(os);
409         dmu_tx_hold_write(tx, ZVOL_OBJ, off, len);
410         error = dmu_tx_assign(tx, TXG_WAIT);
411         if (error) {
412                 dmu_tx_abort(tx);
413         } else {
414                 dmu_write(os, ZVOL_OBJ, off, len, data, tx);
415                 dmu_tx_commit(tx);
416         }
417
418         return (error);
419 }
420
421 static int
422 zvol_replay_err(zvol_state_t *zv, lr_t *lr, boolean_t byteswap)
423 {
424         return (ENOTSUP);
425 }
426
427 /*
428  * Callback vectors for replaying records.
429  * Only TX_WRITE is needed for zvol.
430  */
431 zil_replay_func_t *zvol_replay_vector[TX_MAX_TYPE] = {
432         (zil_replay_func_t *)zvol_replay_err,   /* no such transaction type */
433         (zil_replay_func_t *)zvol_replay_err,   /* TX_CREATE */
434         (zil_replay_func_t *)zvol_replay_err,   /* TX_MKDIR */
435         (zil_replay_func_t *)zvol_replay_err,   /* TX_MKXATTR */
436         (zil_replay_func_t *)zvol_replay_err,   /* TX_SYMLINK */
437         (zil_replay_func_t *)zvol_replay_err,   /* TX_REMOVE */
438         (zil_replay_func_t *)zvol_replay_err,   /* TX_RMDIR */
439         (zil_replay_func_t *)zvol_replay_err,   /* TX_LINK */
440         (zil_replay_func_t *)zvol_replay_err,   /* TX_RENAME */
441         (zil_replay_func_t *)zvol_replay_write, /* TX_WRITE */
442         (zil_replay_func_t *)zvol_replay_err,   /* TX_TRUNCATE */
443         (zil_replay_func_t *)zvol_replay_err,   /* TX_SETATTR */
444         (zil_replay_func_t *)zvol_replay_err,   /* TX_ACL */
445 };
446
447 /*
448  * zvol_log_write() handles synchronous writes using TX_WRITE ZIL transactions.
449  *
450  * We store data in the log buffers if it's small enough.
451  * Otherwise we will later flush the data out via dmu_sync().
452  */
453 ssize_t zvol_immediate_write_sz = 32768;
454
455 static void
456 zvol_log_write(zvol_state_t *zv, dmu_tx_t *tx,
457                uint64_t offset, uint64_t size, int sync)
458 {
459         uint32_t blocksize = zv->zv_volblocksize;
460         zilog_t *zilog = zv->zv_zilog;
461         boolean_t slogging;
462
463         if (zil_replaying(zilog, tx))
464                 return;
465
466         slogging = spa_has_slogs(zilog->zl_spa);
467
468         while (size) {
469                 itx_t *itx;
470                 lr_write_t *lr;
471                 ssize_t len;
472                 itx_wr_state_t write_state;
473
474                 /*
475                  * Unlike zfs_log_write() we can be called with
476                  * up to DMU_MAX_ACCESS/2 (5MB) writes.
477                  */
478                 if (blocksize > zvol_immediate_write_sz && !slogging &&
479                     size >= blocksize && offset % blocksize == 0) {
480                         write_state = WR_INDIRECT; /* uses dmu_sync */
481                         len = blocksize;
482                 } else if (sync) {
483                         write_state = WR_COPIED;
484                         len = MIN(ZIL_MAX_LOG_DATA, size);
485                 } else {
486                         write_state = WR_NEED_COPY;
487                         len = MIN(ZIL_MAX_LOG_DATA, size);
488                 }
489
490                 itx = zil_itx_create(TX_WRITE, sizeof (*lr) +
491                     (write_state == WR_COPIED ? len : 0));
492                 lr = (lr_write_t *)&itx->itx_lr;
493                 if (write_state == WR_COPIED && dmu_read(zv->zv_objset,
494                     ZVOL_OBJ, offset, len, lr+1, DMU_READ_NO_PREFETCH) != 0) {
495                         zil_itx_destroy(itx);
496                         itx = zil_itx_create(TX_WRITE, sizeof (*lr));
497                         lr = (lr_write_t *)&itx->itx_lr;
498                         write_state = WR_NEED_COPY;
499                 }
500
501                 itx->itx_wr_state = write_state;
502                 if (write_state == WR_NEED_COPY)
503                         itx->itx_sod += len;
504                 lr->lr_foid = ZVOL_OBJ;
505                 lr->lr_offset = offset;
506                 lr->lr_length = len;
507                 lr->lr_blkoff = 0;
508                 BP_ZERO(&lr->lr_blkptr);
509
510                 itx->itx_private = zv;
511                 itx->itx_sync = sync;
512
513                 (void) zil_itx_assign(zilog, itx, tx);
514
515                 offset += len;
516                 size -= len;
517         }
518 }
519
520 /*
521  * Common write path running under the zvol taskq context.  This function
522  * is responsible for copying the request structure data in to the DMU and
523  * signaling the request queue with the result of the copy.
524  */
525 static void
526 zvol_write(void *arg)
527 {
528         struct request *req = (struct request *)arg;
529         struct request_queue *q = req->q;
530         zvol_state_t *zv = q->queuedata;
531         uint64_t offset = blk_rq_pos(req) << 9;
532         uint64_t size = blk_rq_bytes(req);
533         int error = 0;
534         dmu_tx_t *tx;
535         rl_t *rl;
536
537         rl = zfs_range_lock(&zv->zv_znode, offset, size, RL_WRITER);
538
539         tx = dmu_tx_create(zv->zv_objset);
540         dmu_tx_hold_write(tx, ZVOL_OBJ, offset, size);
541
542         /* This will only fail for ENOSPC */
543         error = dmu_tx_assign(tx, TXG_WAIT);
544         if (error) {
545                 dmu_tx_abort(tx);
546                 zfs_range_unlock(rl);
547                 blk_end_request(req, -error, size);
548                 return;
549         }
550
551         error = dmu_write_req(zv->zv_objset, ZVOL_OBJ, req, tx);
552         if (error == 0)
553                 zvol_log_write(zv, tx, offset, size, rq_is_sync(req));
554
555         dmu_tx_commit(tx);
556         zfs_range_unlock(rl);
557
558         if (rq_is_sync(req))
559                 zil_commit(zv->zv_zilog, ZVOL_OBJ);
560
561         blk_end_request(req, -error, size);
562 }
563
564 /*
565  * Common read path running under the zvol taskq context.  This function
566  * is responsible for copying the requested data out of the DMU and in to
567  * a linux request structure.  It then must signal the request queue with
568  * an error code describing the result of the copy.
569  */
570 static void
571 zvol_read(void *arg)
572 {
573         struct request *req = (struct request *)arg;
574         struct request_queue *q = req->q;
575         zvol_state_t *zv = q->queuedata;
576         uint64_t offset = blk_rq_pos(req) << 9;
577         uint64_t size = blk_rq_bytes(req);
578         int error;
579         rl_t *rl;
580
581         rl = zfs_range_lock(&zv->zv_znode, offset, size, RL_READER);
582
583         error = dmu_read_req(zv->zv_objset, ZVOL_OBJ, req);
584
585         zfs_range_unlock(rl);
586
587         /* convert checksum errors into IO errors */
588         if (error == ECKSUM)
589                 error = EIO;
590
591         blk_end_request(req, -error, size);
592 }
593
594 /*
595  * Request will be added back to the request queue and retried if
596  * it cannot be immediately dispatched to the taskq for handling
597  */
598 static inline void
599 zvol_dispatch(task_func_t func, struct request *req)
600 {
601         if (!taskq_dispatch(zvol_taskq, func, (void *)req, TQ_NOSLEEP))
602                 blk_requeue_request(req->q, req);
603 }
604
605 /*
606  * Common request path.  Rather than registering a custom make_request()
607  * function we use the generic Linux version.  This is done because it allows
608  * us to easily merge read requests which would otherwise we performed
609  * synchronously by the DMU.  This is less critical in write case where the
610  * DMU will perform the correct merging within a transaction group.  Using
611  * the generic make_request() also let's use leverage the fact that the
612  * elevator with ensure correct ordering in regards to barrior IOs.  On
613  * the downside it means that in the write case we end up doing request
614  * merging twice once in the elevator and once in the DMU.
615  *
616  * The request handler is called under a spin lock so all the real work
617  * is handed off to be done in the context of the zvol taskq.  This function
618  * simply performs basic request sanity checking and hands off the request.
619  */
620 static void
621 zvol_request(struct request_queue *q)
622 {
623         zvol_state_t *zv = q->queuedata;
624         struct request *req;
625         unsigned int size;
626
627         while ((req = blk_fetch_request(q)) != NULL) {
628                 size = blk_rq_bytes(req);
629
630                 if (blk_rq_pos(req) + blk_rq_sectors(req) >
631                     get_capacity(zv->zv_disk)) {
632                         printk(KERN_INFO
633                                "%s: bad access: block=%llu, count=%lu\n",
634                                req->rq_disk->disk_name,
635                                (long long unsigned)blk_rq_pos(req),
636                                (long unsigned)blk_rq_sectors(req));
637                         __blk_end_request(req, -EIO, size);
638                         continue;
639                 }
640
641                 if (!blk_fs_request(req)) {
642                         printk(KERN_INFO "%s: non-fs cmd\n",
643                                req->rq_disk->disk_name);
644                         __blk_end_request(req, -EIO, size);
645                         continue;
646                 }
647
648                 switch (rq_data_dir(req)) {
649                 case READ:
650                         zvol_dispatch(zvol_read, req);
651                         break;
652                 case WRITE:
653                         if (unlikely(get_disk_ro(zv->zv_disk)) ||
654                             unlikely(zv->zv_flags & ZVOL_RDONLY)) {
655                                 __blk_end_request(req, -EROFS, size);
656                                 break;
657                         }
658
659                         zvol_dispatch(zvol_write, req);
660                         break;
661                 default:
662                         printk(KERN_INFO "%s: unknown cmd: %d\n",
663                                req->rq_disk->disk_name, (int)rq_data_dir(req));
664                         __blk_end_request(req, -EIO, size);
665                         break;
666                 }
667         }
668 }
669
670 static void
671 zvol_get_done(zgd_t *zgd, int error)
672 {
673         if (zgd->zgd_db)
674                 dmu_buf_rele(zgd->zgd_db, zgd);
675
676         zfs_range_unlock(zgd->zgd_rl);
677
678         if (error == 0 && zgd->zgd_bp)
679                 zil_add_block(zgd->zgd_zilog, zgd->zgd_bp);
680
681         kmem_free(zgd, sizeof (zgd_t));
682 }
683
684 /*
685  * Get data to generate a TX_WRITE intent log record.
686  */
687 static int
688 zvol_get_data(void *arg, lr_write_t *lr, char *buf, zio_t *zio)
689 {
690         zvol_state_t *zv = arg;
691         objset_t *os = zv->zv_objset;
692         uint64_t offset = lr->lr_offset;
693         uint64_t size = lr->lr_length;
694         dmu_buf_t *db;
695         zgd_t *zgd;
696         int error;
697
698         ASSERT(zio != NULL);
699         ASSERT(size != 0);
700
701         zgd = (zgd_t *)kmem_zalloc(sizeof (zgd_t), KM_SLEEP);
702         zgd->zgd_zilog = zv->zv_zilog;
703         zgd->zgd_rl = zfs_range_lock(&zv->zv_znode, offset, size, RL_READER);
704
705         /*
706          * Write records come in two flavors: immediate and indirect.
707          * For small writes it's cheaper to store the data with the
708          * log record (immediate); for large writes it's cheaper to
709          * sync the data and get a pointer to it (indirect) so that
710          * we don't have to write the data twice.
711          */
712         if (buf != NULL) { /* immediate write */
713                 error = dmu_read(os, ZVOL_OBJ, offset, size, buf,
714                     DMU_READ_NO_PREFETCH);
715         } else {
716                 size = zv->zv_volblocksize;
717                 offset = P2ALIGN_TYPED(offset, size, uint64_t);
718                 error = dmu_buf_hold(os, ZVOL_OBJ, offset, zgd, &db,
719                     DMU_READ_NO_PREFETCH);
720                 if (error == 0) {
721                         zgd->zgd_db = db;
722                         zgd->zgd_bp = &lr->lr_blkptr;
723
724                         ASSERT(db != NULL);
725                         ASSERT(db->db_offset == offset);
726                         ASSERT(db->db_size == size);
727
728                         error = dmu_sync(zio, lr->lr_common.lrc_txg,
729                             zvol_get_done, zgd);
730
731                         if (error == 0)
732                                 return (0);
733                 }
734         }
735
736         zvol_get_done(zgd, error);
737
738         return (error);
739 }
740
741 /*
742  * The zvol_state_t's are inserted in increasing MINOR(dev_t) order.
743  */
744 static void
745 zvol_insert(zvol_state_t *zv_insert)
746 {
747         zvol_state_t *zv = NULL;
748
749         ASSERT(MUTEX_HELD(&zvol_state_lock));
750         ASSERT3U(MINOR(zv_insert->zv_dev) & ZVOL_MINOR_MASK, ==, 0);
751         for (zv = list_head(&zvol_state_list); zv != NULL;
752              zv = list_next(&zvol_state_list, zv)) {
753                 if (MINOR(zv->zv_dev) > MINOR(zv_insert->zv_dev))
754                         break;
755         }
756
757         list_insert_before(&zvol_state_list, zv, zv_insert);
758 }
759
760 /*
761  * Simply remove the zvol from to list of zvols.
762  */
763 static void
764 zvol_remove(zvol_state_t *zv_remove)
765 {
766         ASSERT(MUTEX_HELD(&zvol_state_lock));
767         list_remove(&zvol_state_list, zv_remove);
768 }
769
770 static int
771 zvol_first_open(zvol_state_t *zv)
772 {
773         objset_t *os;
774         uint64_t volsize;
775         int error;
776         uint64_t ro;
777
778         /* lie and say we're read-only */
779         error = dmu_objset_own(zv->zv_name, DMU_OST_ZVOL, 1, zvol_tag, &os);
780         if (error)
781                 return (-error);
782
783         error = zap_lookup(os, ZVOL_ZAP_OBJ, "size", 8, 1, &volsize);
784         if (error) {
785                 dmu_objset_disown(os, zvol_tag);
786                 return (-error);
787         }
788
789         zv->zv_objset = os;
790         error = dmu_bonus_hold(os, ZVOL_OBJ, zvol_tag, &zv->zv_dbuf);
791         if (error) {
792                 dmu_objset_disown(os, zvol_tag);
793                 return (-error);
794         }
795
796         set_capacity(zv->zv_disk, volsize >> 9);
797         zv->zv_volsize = volsize;
798         zv->zv_zilog = zil_open(os, zvol_get_data);
799
800         VERIFY(dsl_prop_get_integer(zv->zv_name, "readonly", &ro, NULL) == 0);
801         if (ro || dmu_objset_is_snapshot(os)) {
802                 set_disk_ro(zv->zv_disk, 1);
803                 zv->zv_flags |= ZVOL_RDONLY;
804         } else {
805                 set_disk_ro(zv->zv_disk, 0);
806                 zv->zv_flags &= ~ZVOL_RDONLY;
807         }
808
809         return (-error);
810 }
811
812 static void
813 zvol_last_close(zvol_state_t *zv)
814 {
815         zil_close(zv->zv_zilog);
816         zv->zv_zilog = NULL;
817         dmu_buf_rele(zv->zv_dbuf, zvol_tag);
818         zv->zv_dbuf = NULL;
819         dmu_objset_disown(zv->zv_objset, zvol_tag);
820         zv->zv_objset = NULL;
821 }
822
823 static int
824 zvol_open(struct block_device *bdev, fmode_t flag)
825 {
826         zvol_state_t *zv = bdev->bd_disk->private_data;
827         int error = 0, drop_mutex = 0;
828
829         /*
830          * If the caller is already holding the mutex do not take it
831          * again, this will happen as part of zvol_create_minor().
832          * Once add_disk() is called the device is live and the kernel
833          * will attempt to open it to read the partition information.
834          */
835         if (!mutex_owned(&zvol_state_lock)) {
836                 mutex_enter(&zvol_state_lock);
837                 drop_mutex = 1;
838         }
839
840         ASSERT3P(zv, !=, NULL);
841
842         if (zv->zv_open_count == 0) {
843                 error = zvol_first_open(zv);
844                 if (error)
845                         goto out_mutex;
846         }
847
848         if ((flag & FMODE_WRITE) &&
849             (get_disk_ro(zv->zv_disk) || (zv->zv_flags & ZVOL_RDONLY))) {
850                 error = -EROFS;
851                 goto out_open_count;
852         }
853
854         zv->zv_open_count++;
855
856 out_open_count:
857         if (zv->zv_open_count == 0)
858                 zvol_last_close(zv);
859
860 out_mutex:
861         if (drop_mutex)
862                 mutex_exit(&zvol_state_lock);
863
864         check_disk_change(bdev);
865
866         return (error);
867 }
868
869 static int
870 zvol_release(struct gendisk *disk, fmode_t mode)
871 {
872         zvol_state_t *zv = disk->private_data;
873         int drop_mutex = 0;
874
875         if (!mutex_owned(&zvol_state_lock)) {
876                 mutex_enter(&zvol_state_lock);
877                 drop_mutex = 1;
878         }
879
880         ASSERT3P(zv, !=, NULL);
881         ASSERT3U(zv->zv_open_count, >, 0);
882         zv->zv_open_count--;
883         if (zv->zv_open_count == 0)
884                 zvol_last_close(zv);
885
886         if (drop_mutex)
887                 mutex_exit(&zvol_state_lock);
888
889         return (0);
890 }
891
892 static int
893 zvol_ioctl(struct block_device *bdev, fmode_t mode,
894            unsigned int cmd, unsigned long arg)
895 {
896         zvol_state_t *zv = bdev->bd_disk->private_data;
897         int error = 0;
898
899         if (zv == NULL)
900                 return (-ENXIO);
901
902         switch (cmd) {
903         case BLKFLSBUF:
904                 zil_commit(zv->zv_zilog, ZVOL_OBJ);
905                 break;
906         case BLKZNAME:
907                 error = copy_to_user((void *)arg, zv->zv_name, MAXNAMELEN);
908                 break;
909
910         default:
911                 error = -ENOTTY;
912                 break;
913
914         }
915
916         return (error);
917 }
918
919 #ifdef CONFIG_COMPAT
920 static int
921 zvol_compat_ioctl(struct block_device *bdev, fmode_t mode,
922                   unsigned cmd, unsigned long arg)
923 {
924         return zvol_ioctl(bdev, mode, cmd, arg);
925 }
926 #else
927 #define zvol_compat_ioctl   NULL
928 #endif
929
930 static int zvol_media_changed(struct gendisk *disk)
931 {
932         zvol_state_t *zv = disk->private_data;
933
934         return zv->zv_changed;
935 }
936
937 static int zvol_revalidate_disk(struct gendisk *disk)
938 {
939         zvol_state_t *zv = disk->private_data;
940
941         zv->zv_changed = 0;
942         set_capacity(zv->zv_disk, zv->zv_volsize >> 9);
943
944         return 0;
945 }
946
947 /*
948  * Provide a simple virtual geometry for legacy compatibility.  For devices
949  * smaller than 1 MiB a small head and sector count is used to allow very
950  * tiny devices.  For devices over 1 Mib a standard head and sector count
951  * is used to keep the cylinders count reasonable.
952  */
953 static int
954 zvol_getgeo(struct block_device *bdev, struct hd_geometry *geo)
955 {
956         zvol_state_t *zv = bdev->bd_disk->private_data;
957         sector_t sectors = get_capacity(zv->zv_disk);
958
959         if (sectors > 2048) {
960                 geo->heads = 16;
961                 geo->sectors = 63;
962         } else {
963                 geo->heads = 2;
964                 geo->sectors = 4;
965         }
966
967         geo->start = 0;
968         geo->cylinders = sectors / (geo->heads * geo->sectors);
969
970         return 0;
971 }
972
973 static struct kobject *
974 zvol_probe(dev_t dev, int *part, void *arg)
975 {
976         zvol_state_t *zv;
977         struct kobject *kobj;
978
979         mutex_enter(&zvol_state_lock);
980         zv = zvol_find_by_dev(dev);
981         kobj = zv ? get_disk(zv->zv_disk) : ERR_PTR(-ENOENT);
982         mutex_exit(&zvol_state_lock);
983
984         return kobj;
985 }
986
987 #ifdef HAVE_BDEV_BLOCK_DEVICE_OPERATIONS
988 static struct block_device_operations zvol_ops = {
989         .open            = zvol_open,
990         .release         = zvol_release,
991         .ioctl           = zvol_ioctl,
992         .compat_ioctl    = zvol_compat_ioctl,
993         .media_changed   = zvol_media_changed,
994         .revalidate_disk = zvol_revalidate_disk,
995         .getgeo          = zvol_getgeo,
996         .owner           = THIS_MODULE,
997 };
998
999 #else /* HAVE_BDEV_BLOCK_DEVICE_OPERATIONS */
1000
1001 static int
1002 zvol_open_by_inode(struct inode *inode, struct file *file)
1003 {
1004         return zvol_open(inode->i_bdev, file->f_mode);
1005 }
1006
1007 static int
1008 zvol_release_by_inode(struct inode *inode, struct file *file)
1009 {
1010         return zvol_release(inode->i_bdev->bd_disk, file->f_mode);
1011 }
1012
1013 static int
1014 zvol_ioctl_by_inode(struct inode *inode, struct file *file,
1015                     unsigned int cmd, unsigned long arg)
1016 {
1017         if (file == NULL || inode == NULL)
1018                 return -EINVAL;
1019         return zvol_ioctl(inode->i_bdev, file->f_mode, cmd, arg);
1020 }
1021
1022 # ifdef CONFIG_COMPAT
1023 static long
1024 zvol_compat_ioctl_by_inode(struct file *file,
1025                            unsigned int cmd, unsigned long arg)
1026 {
1027         if (file == NULL)
1028                 return -EINVAL;
1029         return zvol_compat_ioctl(file->f_dentry->d_inode->i_bdev,
1030                                  file->f_mode, cmd, arg);
1031 }
1032 # else
1033 # define zvol_compat_ioctl_by_inode   NULL
1034 # endif
1035
1036 static struct block_device_operations zvol_ops = {
1037         .open            = zvol_open_by_inode,
1038         .release         = zvol_release_by_inode,
1039         .ioctl           = zvol_ioctl_by_inode,
1040         .compat_ioctl    = zvol_compat_ioctl_by_inode,
1041         .media_changed   = zvol_media_changed,
1042         .revalidate_disk = zvol_revalidate_disk,
1043         .getgeo          = zvol_getgeo,
1044         .owner           = THIS_MODULE,
1045 };
1046 #endif /* HAVE_BDEV_BLOCK_DEVICE_OPERATIONS */
1047
1048 /*
1049  * Allocate memory for a new zvol_state_t and setup the required
1050  * request queue and generic disk structures for the block device.
1051  */
1052 static zvol_state_t *
1053 zvol_alloc(dev_t dev, const char *name)
1054 {
1055         zvol_state_t *zv;
1056
1057         zv = kmem_zalloc(sizeof (zvol_state_t), KM_SLEEP);
1058         if (zv == NULL)
1059                 goto out;
1060
1061         zv->zv_queue = blk_init_queue(zvol_request, &zv->zv_lock);
1062         if (zv->zv_queue == NULL)
1063                 goto out_kmem;
1064
1065         zv->zv_disk = alloc_disk(ZVOL_MINORS);
1066         if (zv->zv_disk == NULL)
1067                 goto out_queue;
1068
1069         zv->zv_queue->queuedata = zv;
1070         zv->zv_dev = dev;
1071         zv->zv_open_count = 0;
1072         strlcpy(zv->zv_name, name, MAXNAMELEN);
1073
1074         mutex_init(&zv->zv_znode.z_range_lock, NULL, MUTEX_DEFAULT, NULL);
1075         avl_create(&zv->zv_znode.z_range_avl, zfs_range_compare,
1076             sizeof (rl_t), offsetof(rl_t, r_node));
1077         zv->zv_znode.z_is_zvol = TRUE;
1078
1079         spin_lock_init(&zv->zv_lock);
1080         list_link_init(&zv->zv_next);
1081
1082         zv->zv_disk->major = zvol_major;
1083         zv->zv_disk->first_minor = (dev & MINORMASK);
1084         zv->zv_disk->fops = &zvol_ops;
1085         zv->zv_disk->private_data = zv;
1086         zv->zv_disk->queue = zv->zv_queue;
1087         snprintf(zv->zv_disk->disk_name, DISK_NAME_LEN, "%s%d",
1088             ZVOL_DEV_NAME, (dev & MINORMASK));
1089
1090         return zv;
1091
1092 out_queue:
1093         blk_cleanup_queue(zv->zv_queue);
1094 out_kmem:
1095         kmem_free(zv, sizeof (zvol_state_t));
1096 out:
1097         return NULL;
1098 }
1099
1100 /*
1101  * Cleanup then free a zvol_state_t which was created by zvol_alloc().
1102  */
1103 static void
1104 zvol_free(zvol_state_t *zv)
1105 {
1106         avl_destroy(&zv->zv_znode.z_range_avl);
1107         mutex_destroy(&zv->zv_znode.z_range_lock);
1108
1109         del_gendisk(zv->zv_disk);
1110         blk_cleanup_queue(zv->zv_queue);
1111         put_disk(zv->zv_disk);
1112
1113         kmem_free(zv, sizeof (zvol_state_t));
1114 }
1115
1116 static int
1117 __zvol_create_minor(const char *name)
1118 {
1119         zvol_state_t *zv;
1120         objset_t *os;
1121         dmu_object_info_t *doi;
1122         uint64_t volsize;
1123         unsigned minor = 0;
1124         int error = 0;
1125
1126         ASSERT(MUTEX_HELD(&zvol_state_lock));
1127
1128         zv = zvol_find_by_name(name);
1129         if (zv) {
1130                 error = EEXIST;
1131                 goto out;
1132         }
1133
1134         doi = kmem_alloc(sizeof(dmu_object_info_t), KM_SLEEP);
1135
1136         error = dmu_objset_own(name, DMU_OST_ZVOL, B_TRUE, zvol_tag, &os);
1137         if (error)
1138                 goto out_doi;
1139
1140         error = dmu_object_info(os, ZVOL_OBJ, doi);
1141         if (error)
1142                 goto out_dmu_objset_disown;
1143
1144         error = zap_lookup(os, ZVOL_ZAP_OBJ, "size", 8, 1, &volsize);
1145         if (error)
1146                 goto out_dmu_objset_disown;
1147
1148         error = zvol_find_minor(&minor);
1149         if (error)
1150                 goto out_dmu_objset_disown;
1151
1152         zv = zvol_alloc(MKDEV(zvol_major, minor), name);
1153         if (zv == NULL) {
1154                 error = EAGAIN;
1155                 goto out_dmu_objset_disown;
1156         }
1157
1158         if (dmu_objset_is_snapshot(os))
1159                 zv->zv_flags |= ZVOL_RDONLY;
1160
1161         zv->zv_volblocksize = doi->doi_data_block_size;
1162         zv->zv_volsize = volsize;
1163         zv->zv_objset = os;
1164
1165         set_capacity(zv->zv_disk, zv->zv_volsize >> 9);
1166
1167         if (zil_replay_disable)
1168                 zil_destroy(dmu_objset_zil(os), B_FALSE);
1169         else
1170                 zil_replay(os, zv, zvol_replay_vector);
1171
1172 out_dmu_objset_disown:
1173         dmu_objset_disown(os, zvol_tag);
1174         zv->zv_objset = NULL;
1175 out_doi:
1176         kmem_free(doi, sizeof(dmu_object_info_t));
1177 out:
1178
1179         if (error == 0) {
1180                 zvol_insert(zv);
1181                 add_disk(zv->zv_disk);
1182         }
1183
1184         return (error);
1185 }
1186
1187 /*
1188  * Create a block device minor node and setup the linkage between it
1189  * and the specified volume.  Once this function returns the block
1190  * device is live and ready for use.
1191  */
1192 int
1193 zvol_create_minor(const char *name)
1194 {
1195         int error;
1196
1197         mutex_enter(&zvol_state_lock);
1198         error = __zvol_create_minor(name);
1199         mutex_exit(&zvol_state_lock);
1200
1201         return (error);
1202 }
1203
1204 static int
1205 __zvol_remove_minor(const char *name)
1206 {
1207         zvol_state_t *zv;
1208
1209         ASSERT(MUTEX_HELD(&zvol_state_lock));
1210
1211         zv = zvol_find_by_name(name);
1212         if (zv == NULL)
1213                 return (ENXIO);
1214
1215         if (zv->zv_open_count > 0)
1216                 return (EBUSY);
1217
1218         zvol_remove(zv);
1219         zvol_free(zv);
1220
1221         return (0);
1222 }
1223
1224 /*
1225  * Remove a block device minor node for the specified volume.
1226  */
1227 int
1228 zvol_remove_minor(const char *name)
1229 {
1230         int error;
1231
1232         mutex_enter(&zvol_state_lock);
1233         error = __zvol_remove_minor(name);
1234         mutex_exit(&zvol_state_lock);
1235
1236         return (error);
1237 }
1238
1239 static int
1240 zvol_create_minors_cb(spa_t *spa, uint64_t dsobj,
1241                       const char *dsname, void *arg)
1242 {
1243         if (strchr(dsname, '/') == NULL)
1244                 return 0;
1245
1246         (void) __zvol_create_minor(dsname);
1247         return (0);
1248 }
1249
1250 /*
1251  * Create minors for specified pool, if pool is NULL create minors
1252  * for all available pools.
1253  */
1254 int
1255 zvol_create_minors(const char *pool)
1256 {
1257         spa_t *spa = NULL;
1258         int error = 0;
1259
1260         mutex_enter(&zvol_state_lock);
1261         if (pool) {
1262                 error = dmu_objset_find_spa(NULL, pool, zvol_create_minors_cb,
1263                     NULL, DS_FIND_CHILDREN | DS_FIND_SNAPSHOTS);
1264         } else {
1265                 mutex_enter(&spa_namespace_lock);
1266                 while ((spa = spa_next(spa)) != NULL) {
1267                         error = dmu_objset_find_spa(NULL,
1268                             spa_name(spa), zvol_create_minors_cb, NULL,
1269                             DS_FIND_CHILDREN | DS_FIND_SNAPSHOTS);
1270                         if (error)
1271                                 break;
1272                 }
1273                 mutex_exit(&spa_namespace_lock);
1274         }
1275         mutex_exit(&zvol_state_lock);
1276
1277         return error;
1278 }
1279
1280 /*
1281  * Remove minors for specified pool, if pool is NULL remove all minors.
1282  */
1283 void
1284 zvol_remove_minors(const char *pool)
1285 {
1286         zvol_state_t *zv, *zv_next;
1287         char *str;
1288
1289         str = kmem_zalloc(MAXNAMELEN, KM_SLEEP);
1290         if (pool) {
1291                 (void) strncpy(str, pool, strlen(pool));
1292                 (void) strcat(str, "/");
1293         }
1294
1295         mutex_enter(&zvol_state_lock);
1296         for (zv = list_head(&zvol_state_list); zv != NULL; zv = zv_next) {
1297                 zv_next = list_next(&zvol_state_list, zv);
1298
1299                 if (pool == NULL || !strncmp(str, zv->zv_name, strlen(str))) {
1300                         zvol_remove(zv);
1301                         zvol_free(zv);
1302                 }
1303         }
1304         mutex_exit(&zvol_state_lock);
1305         kmem_free(str, MAXNAMELEN);
1306 }
1307
1308 int
1309 zvol_init(void)
1310 {
1311         int error;
1312
1313         if (!zvol_threads)
1314                 zvol_threads = num_online_cpus();
1315
1316         zvol_taskq = taskq_create(ZVOL_DRIVER, zvol_threads, maxclsyspri,
1317                                   zvol_threads, INT_MAX, TASKQ_PREPOPULATE);
1318         if (zvol_taskq == NULL) {
1319                 printk(KERN_INFO "ZFS: taskq_create() failed\n");
1320                 return (-ENOMEM);
1321         }
1322
1323         error = register_blkdev(zvol_major, ZVOL_DRIVER);
1324         if (error) {
1325                 printk(KERN_INFO "ZFS: register_blkdev() failed %d\n", error);
1326                 taskq_destroy(zvol_taskq);
1327                 return (error);
1328         }
1329
1330         blk_register_region(MKDEV(zvol_major, 0), 1UL << MINORBITS,
1331                             THIS_MODULE, zvol_probe, NULL, NULL);
1332
1333         mutex_init(&zvol_state_lock, NULL, MUTEX_DEFAULT, NULL);
1334         list_create(&zvol_state_list, sizeof (zvol_state_t),
1335                     offsetof(zvol_state_t, zv_next));
1336
1337         (void) zvol_create_minors(NULL);
1338
1339         return (0);
1340 }
1341
1342 void
1343 zvol_fini(void)
1344 {
1345         zvol_remove_minors(NULL);
1346         blk_unregister_region(MKDEV(zvol_major, 0), 1UL << MINORBITS);
1347         unregister_blkdev(zvol_major, ZVOL_DRIVER);
1348         taskq_destroy(zvol_taskq);
1349         mutex_destroy(&zvol_state_lock);
1350         list_destroy(&zvol_state_list);
1351 }
1352
1353 module_param(zvol_major, uint, 0);
1354 MODULE_PARM_DESC(zvol_major, "Major number for zvol device");
1355
1356 module_param(zvol_threads, uint, 0);
1357 MODULE_PARM_DESC(zvol_threads, "Number of threads for zvol device");