Use udev to create /dev/zvol/[dataset_name] links
[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)
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(zv->zv_objset);
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(zv->zv_objset, 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(zv->zv_objset,
255             ZVOL_OBJ, volsize, DMU_OBJECT_END);
256         if (error)
257                 return (error);
258
259         zv->zv_volsize = volsize;
260         zv->zv_changed = 1;
261
262         bdev = bdget_disk(zv->zv_disk, 0);
263         if (!bdev)
264                 return EIO;
265
266         error = check_disk_change(bdev);
267         ASSERT3U(error, !=, 0);
268         bdput(bdev);
269
270         return (0);
271 }
272
273 /*
274  * Set ZFS_PROP_VOLSIZE set entry point.
275  */
276 int
277 zvol_set_volsize(const char *name, uint64_t volsize)
278 {
279         zvol_state_t *zv;
280         dmu_object_info_t *doi;
281         objset_t *os = NULL;
282         uint64_t readonly;
283         int error;
284
285         mutex_enter(&zvol_state_lock);
286
287         zv = zvol_find_by_name(name);
288         if (zv == NULL) {
289                 error = ENXIO;
290                 goto out;
291         }
292
293         doi = kmem_alloc(sizeof(dmu_object_info_t), KM_SLEEP);
294
295         error = dmu_objset_hold(name, FTAG, &os);
296         if (error)
297                 goto out_doi;
298
299         if ((error = dmu_object_info(os, ZVOL_OBJ, doi)) != 0 ||
300             (error = zvol_check_volsize(volsize,doi->doi_data_block_size)) != 0)
301                 goto out_doi;
302
303         VERIFY(dsl_prop_get_integer(name, "readonly", &readonly, NULL) == 0);
304         if (readonly) {
305                 error = EROFS;
306                 goto out_doi;
307         }
308
309         if (get_disk_ro(zv->zv_disk) || (zv->zv_flags & ZVOL_RDONLY)) {
310                 error = EROFS;
311                 goto out_doi;
312         }
313
314         error = zvol_update_volsize(zv, volsize);
315 out_doi:
316         kmem_free(doi, sizeof(dmu_object_info_t));
317 out:
318         if (os)
319                 dmu_objset_rele(os, FTAG);
320
321         mutex_exit(&zvol_state_lock);
322
323         return (error);
324 }
325
326 /*
327  * Sanity check volume block size.
328  */
329 int
330 zvol_check_volblocksize(uint64_t volblocksize)
331 {
332         if (volblocksize < SPA_MINBLOCKSIZE ||
333             volblocksize > SPA_MAXBLOCKSIZE ||
334             !ISP2(volblocksize))
335                 return (EDOM);
336
337         return (0);
338 }
339
340 /*
341  * Set ZFS_PROP_VOLBLOCKSIZE set entry point.
342  */
343 int
344 zvol_set_volblocksize(const char *name, uint64_t volblocksize)
345 {
346         zvol_state_t *zv;
347         dmu_tx_t *tx;
348         int error;
349
350         mutex_enter(&zvol_state_lock);
351
352         zv = zvol_find_by_name(name);
353         if (zv == NULL) {
354                 error = ENXIO;
355                 goto out;
356         }
357
358         if (get_disk_ro(zv->zv_disk) || (zv->zv_flags & ZVOL_RDONLY)) {
359                 error = EROFS;
360                 goto out;
361         }
362
363         tx = dmu_tx_create(zv->zv_objset);
364         dmu_tx_hold_bonus(tx, ZVOL_OBJ);
365         error = dmu_tx_assign(tx, TXG_WAIT);
366         if (error) {
367                 dmu_tx_abort(tx);
368         } else {
369                 error = dmu_object_set_blocksize(zv->zv_objset, ZVOL_OBJ,
370                     volblocksize, 0, tx);
371                 if (error == ENOTSUP)
372                         error = EBUSY;
373                 dmu_tx_commit(tx);
374                 if (error == 0)
375                         zv->zv_volblocksize = volblocksize;
376         }
377 out:
378         mutex_exit(&zvol_state_lock);
379
380         return (error);
381 }
382
383 /*
384  * Replay a TX_WRITE ZIL transaction that didn't get committed
385  * after a system failure
386  */
387 static int
388 zvol_replay_write(zvol_state_t *zv, lr_write_t *lr, boolean_t byteswap)
389 {
390         objset_t *os = zv->zv_objset;
391         char *data = (char *)(lr + 1);  /* data follows lr_write_t */
392         uint64_t off = lr->lr_offset;
393         uint64_t len = lr->lr_length;
394         dmu_tx_t *tx;
395         int error;
396
397         if (byteswap)
398                 byteswap_uint64_array(lr, sizeof (*lr));
399
400         tx = dmu_tx_create(os);
401         dmu_tx_hold_write(tx, ZVOL_OBJ, off, len);
402         error = dmu_tx_assign(tx, TXG_WAIT);
403         if (error) {
404                 dmu_tx_abort(tx);
405         } else {
406                 dmu_write(os, ZVOL_OBJ, off, len, data, tx);
407                 dmu_tx_commit(tx);
408         }
409
410         return (error);
411 }
412
413 static int
414 zvol_replay_err(zvol_state_t *zv, lr_t *lr, boolean_t byteswap)
415 {
416         return (ENOTSUP);
417 }
418
419 /*
420  * Callback vectors for replaying records.
421  * Only TX_WRITE is needed for zvol.
422  */
423 zil_replay_func_t *zvol_replay_vector[TX_MAX_TYPE] = {
424         (zil_replay_func_t *)zvol_replay_err,   /* no such transaction type */
425         (zil_replay_func_t *)zvol_replay_err,   /* TX_CREATE */
426         (zil_replay_func_t *)zvol_replay_err,   /* TX_MKDIR */
427         (zil_replay_func_t *)zvol_replay_err,   /* TX_MKXATTR */
428         (zil_replay_func_t *)zvol_replay_err,   /* TX_SYMLINK */
429         (zil_replay_func_t *)zvol_replay_err,   /* TX_REMOVE */
430         (zil_replay_func_t *)zvol_replay_err,   /* TX_RMDIR */
431         (zil_replay_func_t *)zvol_replay_err,   /* TX_LINK */
432         (zil_replay_func_t *)zvol_replay_err,   /* TX_RENAME */
433         (zil_replay_func_t *)zvol_replay_write, /* TX_WRITE */
434         (zil_replay_func_t *)zvol_replay_err,   /* TX_TRUNCATE */
435         (zil_replay_func_t *)zvol_replay_err,   /* TX_SETATTR */
436         (zil_replay_func_t *)zvol_replay_err,   /* TX_ACL */
437 };
438
439 /*
440  * zvol_log_write() handles synchronous writes using TX_WRITE ZIL transactions.
441  *
442  * We store data in the log buffers if it's small enough.
443  * Otherwise we will later flush the data out via dmu_sync().
444  */
445 ssize_t zvol_immediate_write_sz = 32768;
446
447 static void
448 zvol_log_write(zvol_state_t *zv, dmu_tx_t *tx,
449                uint64_t offset, uint64_t size, int sync)
450 {
451         uint32_t blocksize = zv->zv_volblocksize;
452         zilog_t *zilog = zv->zv_zilog;
453         boolean_t slogging;
454
455         if (zil_replaying(zilog, tx))
456                 return;
457
458         slogging = spa_has_slogs(zilog->zl_spa);
459
460         while (size) {
461                 itx_t *itx;
462                 lr_write_t *lr;
463                 ssize_t len;
464                 itx_wr_state_t write_state;
465
466                 /*
467                  * Unlike zfs_log_write() we can be called with
468                  * up to DMU_MAX_ACCESS/2 (5MB) writes.
469                  */
470                 if (blocksize > zvol_immediate_write_sz && !slogging &&
471                     size >= blocksize && offset % blocksize == 0) {
472                         write_state = WR_INDIRECT; /* uses dmu_sync */
473                         len = blocksize;
474                 } else if (sync) {
475                         write_state = WR_COPIED;
476                         len = MIN(ZIL_MAX_LOG_DATA, size);
477                 } else {
478                         write_state = WR_NEED_COPY;
479                         len = MIN(ZIL_MAX_LOG_DATA, size);
480                 }
481
482                 itx = zil_itx_create(TX_WRITE, sizeof (*lr) +
483                     (write_state == WR_COPIED ? len : 0));
484                 lr = (lr_write_t *)&itx->itx_lr;
485                 if (write_state == WR_COPIED && dmu_read(zv->zv_objset,
486                     ZVOL_OBJ, offset, len, lr+1, DMU_READ_NO_PREFETCH) != 0) {
487                         zil_itx_destroy(itx);
488                         itx = zil_itx_create(TX_WRITE, sizeof (*lr));
489                         lr = (lr_write_t *)&itx->itx_lr;
490                         write_state = WR_NEED_COPY;
491                 }
492
493                 itx->itx_wr_state = write_state;
494                 if (write_state == WR_NEED_COPY)
495                         itx->itx_sod += len;
496                 lr->lr_foid = ZVOL_OBJ;
497                 lr->lr_offset = offset;
498                 lr->lr_length = len;
499                 lr->lr_blkoff = 0;
500                 BP_ZERO(&lr->lr_blkptr);
501
502                 itx->itx_private = zv;
503                 itx->itx_sync = sync;
504
505                 (void) zil_itx_assign(zilog, itx, tx);
506
507                 offset += len;
508                 size -= len;
509         }
510 }
511
512 /*
513  * Common write path running under the zvol taskq context.  This function
514  * is responsible for copying the request structure data in to the DMU and
515  * signaling the request queue with the result of the copy.
516  */
517 static void
518 zvol_write(void *arg)
519 {
520         struct request *req = (struct request *)arg;
521         struct request_queue *q = req->q;
522         zvol_state_t *zv = q->queuedata;
523         uint64_t offset = blk_rq_pos(req) << 9;
524         uint64_t size = blk_rq_bytes(req);
525         int error = 0;
526         dmu_tx_t *tx;
527         rl_t *rl;
528
529         rl = zfs_range_lock(&zv->zv_znode, offset, size, RL_WRITER);
530
531         tx = dmu_tx_create(zv->zv_objset);
532         dmu_tx_hold_write(tx, ZVOL_OBJ, offset, size);
533
534         /* This will only fail for ENOSPC */
535         error = dmu_tx_assign(tx, TXG_WAIT);
536         if (error) {
537                 dmu_tx_abort(tx);
538                 zfs_range_unlock(rl);
539                 blk_end_request(req, -error, size);
540                 return;
541         }
542
543         error = dmu_write_req(zv->zv_objset, ZVOL_OBJ, req, tx);
544         if (error == 0)
545                 zvol_log_write(zv, tx, offset, size, rq_is_sync(req));
546
547         dmu_tx_commit(tx);
548         zfs_range_unlock(rl);
549
550         if (rq_is_sync(req))
551                 zil_commit(zv->zv_zilog, ZVOL_OBJ);
552
553         blk_end_request(req, -error, size);
554 }
555
556 /*
557  * Common read path running under the zvol taskq context.  This function
558  * is responsible for copying the requested data out of the DMU and in to
559  * a linux request structure.  It then must signal the request queue with
560  * an error code describing the result of the copy.
561  */
562 static void
563 zvol_read(void *arg)
564 {
565         struct request *req = (struct request *)arg;
566         struct request_queue *q = req->q;
567         zvol_state_t *zv = q->queuedata;
568         uint64_t offset = blk_rq_pos(req) << 9;
569         uint64_t size = blk_rq_bytes(req);
570         int error;
571         rl_t *rl;
572
573         rl = zfs_range_lock(&zv->zv_znode, offset, size, RL_READER);
574
575         error = dmu_read_req(zv->zv_objset, ZVOL_OBJ, req);
576
577         zfs_range_unlock(rl);
578
579         /* convert checksum errors into IO errors */
580         if (error == ECKSUM)
581                 error = EIO;
582
583         blk_end_request(req, -error, size);
584 }
585
586 /*
587  * Request will be added back to the request queue and retried if
588  * it cannot be immediately dispatched to the taskq for handling
589  */
590 static inline void
591 zvol_dispatch(task_func_t func, struct request *req)
592 {
593         if (!taskq_dispatch(zvol_taskq, func, (void *)req, TQ_NOSLEEP))
594                 blk_requeue_request(req->q, req);
595 }
596
597 /*
598  * Common request path.  Rather than registering a custom make_request()
599  * function we use the generic Linux version.  This is done because it allows
600  * us to easily merge read requests which would otherwise we performed
601  * synchronously by the DMU.  This is less critical in write case where the
602  * DMU will perform the correct merging within a transaction group.  Using
603  * the generic make_request() also let's use leverage the fact that the
604  * elevator with ensure correct ordering in regards to barrior IOs.  On
605  * the downside it means that in the write case we end up doing request
606  * merging twice once in the elevator and once in the DMU.
607  *
608  * The request handler is called under a spin lock so all the real work
609  * is handed off to be done in the context of the zvol taskq.  This function
610  * simply performs basic request sanity checking and hands off the request.
611  */
612 static void
613 zvol_request(struct request_queue *q)
614 {
615         zvol_state_t *zv = q->queuedata;
616         struct request *req;
617         unsigned int size;
618
619         while ((req = blk_fetch_request(q)) != NULL) {
620                 size = blk_rq_bytes(req);
621
622                 if (blk_rq_pos(req) + blk_rq_sectors(req) >
623                     get_capacity(zv->zv_disk)) {
624                         printk(KERN_INFO
625                                "%s: bad access: block=%llu, count=%lu\n",
626                                req->rq_disk->disk_name,
627                                (long long unsigned)blk_rq_pos(req),
628                                (long unsigned)blk_rq_sectors(req));
629                         __blk_end_request(req, -EIO, size);
630                         continue;
631                 }
632
633                 if (!blk_fs_request(req)) {
634                         printk(KERN_INFO "%s: non-fs cmd\n",
635                                req->rq_disk->disk_name);
636                         __blk_end_request(req, -EIO, size);
637                         continue;
638                 }
639
640                 switch (rq_data_dir(req)) {
641                 case READ:
642                         zvol_dispatch(zvol_read, req);
643                         break;
644                 case WRITE:
645                         if (unlikely(get_disk_ro(zv->zv_disk)) ||
646                             unlikely(zv->zv_flags & ZVOL_RDONLY)) {
647                                 __blk_end_request(req, -EROFS, size);
648                                 break;
649                         }
650
651                         zvol_dispatch(zvol_write, req);
652                         break;
653                 default:
654                         printk(KERN_INFO "%s: unknown cmd: %d\n",
655                                req->rq_disk->disk_name, (int)rq_data_dir(req));
656                         __blk_end_request(req, -EIO, size);
657                         break;
658                 }
659         }
660 }
661
662 static void
663 zvol_get_done(zgd_t *zgd, int error)
664 {
665         if (zgd->zgd_db)
666                 dmu_buf_rele(zgd->zgd_db, zgd);
667
668         zfs_range_unlock(zgd->zgd_rl);
669
670         if (error == 0 && zgd->zgd_bp)
671                 zil_add_block(zgd->zgd_zilog, zgd->zgd_bp);
672
673         kmem_free(zgd, sizeof (zgd_t));
674 }
675
676 /*
677  * Get data to generate a TX_WRITE intent log record.
678  */
679 static int
680 zvol_get_data(void *arg, lr_write_t *lr, char *buf, zio_t *zio)
681 {
682         zvol_state_t *zv = arg;
683         objset_t *os = zv->zv_objset;
684         uint64_t offset = lr->lr_offset;
685         uint64_t size = lr->lr_length;
686         dmu_buf_t *db;
687         zgd_t *zgd;
688         int error;
689
690         ASSERT(zio != NULL);
691         ASSERT(size != 0);
692
693         zgd = (zgd_t *)kmem_zalloc(sizeof (zgd_t), KM_SLEEP);
694         zgd->zgd_zilog = zv->zv_zilog;
695         zgd->zgd_rl = zfs_range_lock(&zv->zv_znode, offset, size, RL_READER);
696
697         /*
698          * Write records come in two flavors: immediate and indirect.
699          * For small writes it's cheaper to store the data with the
700          * log record (immediate); for large writes it's cheaper to
701          * sync the data and get a pointer to it (indirect) so that
702          * we don't have to write the data twice.
703          */
704         if (buf != NULL) { /* immediate write */
705                 error = dmu_read(os, ZVOL_OBJ, offset, size, buf,
706                     DMU_READ_NO_PREFETCH);
707         } else {
708                 size = zv->zv_volblocksize;
709                 offset = P2ALIGN_TYPED(offset, size, uint64_t);
710                 error = dmu_buf_hold(os, ZVOL_OBJ, offset, zgd, &db,
711                     DMU_READ_NO_PREFETCH);
712                 if (error == 0) {
713                         zgd->zgd_db = db;
714                         zgd->zgd_bp = &lr->lr_blkptr;
715
716                         ASSERT(db != NULL);
717                         ASSERT(db->db_offset == offset);
718                         ASSERT(db->db_size == size);
719
720                         error = dmu_sync(zio, lr->lr_common.lrc_txg,
721                             zvol_get_done, zgd);
722
723                         if (error == 0)
724                                 return (0);
725                 }
726         }
727
728         zvol_get_done(zgd, error);
729
730         return (error);
731 }
732
733 /*
734  * The zvol_state_t's are inserted in increasing MINOR(dev_t) order.
735  */
736 static void
737 zvol_insert(zvol_state_t *zv_insert)
738 {
739         zvol_state_t *zv = NULL;
740
741         ASSERT(MUTEX_HELD(&zvol_state_lock));
742         ASSERT3U(MINOR(zv_insert->zv_dev) & ZVOL_MINOR_MASK, ==, 0);
743         for (zv = list_head(&zvol_state_list); zv != NULL;
744              zv = list_next(&zvol_state_list, zv)) {
745                 if (MINOR(zv->zv_dev) > MINOR(zv_insert->zv_dev))
746                         break;
747         }
748
749         list_insert_before(&zvol_state_list, zv, zv_insert);
750 }
751
752 /*
753  * Simply remove the zvol from to list of zvols.
754  */
755 static void
756 zvol_remove(zvol_state_t *zv_remove)
757 {
758         ASSERT(MUTEX_HELD(&zvol_state_lock));
759         list_remove(&zvol_state_list, zv_remove);
760 }
761
762 static int
763 zvol_first_open(zvol_state_t *zv)
764 {
765         objset_t *os;
766         uint64_t volsize;
767         int error;
768         uint64_t ro;
769
770         /* lie and say we're read-only */
771         error = dmu_objset_own(zv->zv_name, DMU_OST_ZVOL, 1, zvol_tag, &os);
772         if (error)
773                 return (-error);
774
775         error = zap_lookup(os, ZVOL_ZAP_OBJ, "size", 8, 1, &volsize);
776         if (error) {
777                 dmu_objset_disown(os, zvol_tag);
778                 return (-error);
779         }
780
781         zv->zv_objset = os;
782         error = dmu_bonus_hold(os, ZVOL_OBJ, zvol_tag, &zv->zv_dbuf);
783         if (error) {
784                 dmu_objset_disown(os, zvol_tag);
785                 return (-error);
786         }
787
788         set_capacity(zv->zv_disk, volsize >> 9);
789         zv->zv_volsize = volsize;
790         zv->zv_zilog = zil_open(os, zvol_get_data);
791
792         VERIFY(dsl_prop_get_integer(zv->zv_name, "readonly", &ro, NULL) == 0);
793         if (ro || dmu_objset_is_snapshot(os)) {
794                 set_disk_ro(zv->zv_disk, 1);
795                 zv->zv_flags |= ZVOL_RDONLY;
796         } else {
797                 set_disk_ro(zv->zv_disk, 0);
798                 zv->zv_flags &= ~ZVOL_RDONLY;
799         }
800
801         return (-error);
802 }
803
804 static void
805 zvol_last_close(zvol_state_t *zv)
806 {
807         zil_close(zv->zv_zilog);
808         zv->zv_zilog = NULL;
809         dmu_buf_rele(zv->zv_dbuf, zvol_tag);
810         zv->zv_dbuf = NULL;
811         dmu_objset_disown(zv->zv_objset, zvol_tag);
812         zv->zv_objset = NULL;
813 }
814
815 static int
816 zvol_open(struct block_device *bdev, fmode_t flag)
817 {
818         zvol_state_t *zv = bdev->bd_disk->private_data;
819         int error = 0, drop_mutex = 0;
820
821         /*
822          * If the caller is already holding the mutex do not take it
823          * again, this will happen as part of zvol_create_minor().
824          * Once add_disk() is called the device is live and the kernel
825          * will attempt to open it to read the partition information.
826          */
827         if (!mutex_owned(&zvol_state_lock)) {
828                 mutex_enter(&zvol_state_lock);
829                 drop_mutex = 1;
830         }
831
832         ASSERT3P(zv, !=, NULL);
833
834         if (zv->zv_open_count == 0) {
835                 error = zvol_first_open(zv);
836                 if (error)
837                         goto out_mutex;
838         }
839
840         if ((flag & FMODE_WRITE) &&
841             (get_disk_ro(zv->zv_disk) || (zv->zv_flags & ZVOL_RDONLY))) {
842                 error = -EROFS;
843                 goto out_open_count;
844         }
845
846         zv->zv_open_count++;
847
848 out_open_count:
849         if (zv->zv_open_count == 0)
850                 zvol_last_close(zv);
851
852 out_mutex:
853         if (drop_mutex)
854                 mutex_exit(&zvol_state_lock);
855
856         check_disk_change(bdev);
857
858         return (error);
859 }
860
861 static int
862 zvol_release(struct gendisk *disk, fmode_t mode)
863 {
864         zvol_state_t *zv = disk->private_data;
865         int drop_mutex = 0;
866
867         if (!mutex_owned(&zvol_state_lock)) {
868                 mutex_enter(&zvol_state_lock);
869                 drop_mutex = 1;
870         }
871
872         ASSERT3P(zv, !=, NULL);
873         ASSERT3U(zv->zv_open_count, >, 0);
874         zv->zv_open_count--;
875         if (zv->zv_open_count == 0)
876                 zvol_last_close(zv);
877
878         if (drop_mutex)
879                 mutex_exit(&zvol_state_lock);
880
881         return (0);
882 }
883
884 static int
885 zvol_ioctl(struct block_device *bdev, fmode_t mode,
886            unsigned int cmd, unsigned long arg)
887 {
888         zvol_state_t *zv = bdev->bd_disk->private_data;
889         int error = 0;
890
891         if (zv == NULL)
892                 return (-ENXIO);
893
894         switch (cmd) {
895         case BLKFLSBUF:
896                 zil_commit(zv->zv_zilog, ZVOL_OBJ);
897                 break;
898         case BLKZNAME:
899                 error = copy_to_user((void *)arg, zv->zv_name, MAXNAMELEN);
900                 break;
901
902         default:
903                 error = -ENOTTY;
904                 break;
905
906         }
907
908         return (error);
909 }
910
911 #ifdef CONFIG_COMPAT
912 static int
913 zvol_compat_ioctl(struct block_device *bdev, fmode_t mode,
914                   unsigned cmd, unsigned long arg)
915 {
916         return zvol_ioctl(bdev, mode, cmd, arg);
917 }
918 #else
919 #define zvol_compat_ioctl   NULL
920 #endif
921
922 static int zvol_media_changed(struct gendisk *disk)
923 {
924         zvol_state_t *zv = disk->private_data;
925
926         return zv->zv_changed;
927 }
928
929 static int zvol_revalidate_disk(struct gendisk *disk)
930 {
931         zvol_state_t *zv = disk->private_data;
932
933         zv->zv_changed = 0;
934         set_capacity(zv->zv_disk, zv->zv_volsize >> 9);
935
936         return 0;
937 }
938
939 /*
940  * Provide a simple virtual geometry for legacy compatibility.  For devices
941  * smaller than 1 MiB a small head and sector count is used to allow very
942  * tiny devices.  For devices over 1 Mib a standard head and sector count
943  * is used to keep the cylinders count reasonable.
944  */
945 static int
946 zvol_getgeo(struct block_device *bdev, struct hd_geometry *geo)
947 {
948         zvol_state_t *zv = bdev->bd_disk->private_data;
949         sector_t sectors = get_capacity(zv->zv_disk);
950
951         if (sectors > 2048) {
952                 geo->heads = 16;
953                 geo->sectors = 63;
954         } else {
955                 geo->heads = 2;
956                 geo->sectors = 4;
957         }
958
959         geo->start = 0;
960         geo->cylinders = sectors / (geo->heads * geo->sectors);
961
962         return 0;
963 }
964
965 static struct kobject *
966 zvol_probe(dev_t dev, int *part, void *arg)
967 {
968         zvol_state_t *zv;
969         struct kobject *kobj;
970
971         mutex_enter(&zvol_state_lock);
972         zv = zvol_find_by_dev(dev);
973         kobj = zv ? get_disk(zv->zv_disk) : ERR_PTR(-ENOENT);
974         mutex_exit(&zvol_state_lock);
975
976         return kobj;
977 }
978
979 #ifdef HAVE_BDEV_BLOCK_DEVICE_OPERATIONS
980 static struct block_device_operations zvol_ops = {
981         .open            = zvol_open,
982         .release         = zvol_release,
983         .ioctl           = zvol_ioctl,
984         .compat_ioctl    = zvol_compat_ioctl,
985         .media_changed   = zvol_media_changed,
986         .revalidate_disk = zvol_revalidate_disk,
987         .getgeo          = zvol_getgeo,
988         .owner           = THIS_MODULE,
989 };
990
991 #else /* HAVE_BDEV_BLOCK_DEVICE_OPERATIONS */
992
993 static int
994 zvol_open_by_inode(struct inode *inode, struct file *file)
995 {
996         return zvol_open(inode->i_bdev, file->f_mode);
997 }
998
999 static int
1000 zvol_release_by_inode(struct inode *inode, struct file *file)
1001 {
1002         return zvol_release(inode->i_bdev->bd_disk, file->f_mode);
1003 }
1004
1005 static int
1006 zvol_ioctl_by_inode(struct inode *inode, struct file *file,
1007                     unsigned int cmd, unsigned long arg)
1008 {
1009         if (file == NULL || inode == NULL)
1010                 return -EINVAL;
1011         return zvol_ioctl(inode->i_bdev, file->f_mode, cmd, arg);
1012 }
1013
1014 # ifdef CONFIG_COMPAT
1015 static long
1016 zvol_compat_ioctl_by_inode(struct file *file,
1017                            unsigned int cmd, unsigned long arg)
1018 {
1019         if (file == NULL)
1020                 return -EINVAL;
1021         return zvol_compat_ioctl(file->f_dentry->d_inode->i_bdev,
1022                                  file->f_mode, cmd, arg);
1023 }
1024 # else
1025 # define zvol_compat_ioctl_by_inode   NULL
1026 # endif
1027
1028 static struct block_device_operations zvol_ops = {
1029         .open            = zvol_open_by_inode,
1030         .release         = zvol_release_by_inode,
1031         .ioctl           = zvol_ioctl_by_inode,
1032         .compat_ioctl    = zvol_compat_ioctl_by_inode,
1033         .media_changed   = zvol_media_changed,
1034         .revalidate_disk = zvol_revalidate_disk,
1035         .getgeo          = zvol_getgeo,
1036         .owner           = THIS_MODULE,
1037 };
1038 #endif /* HAVE_BDEV_BLOCK_DEVICE_OPERATIONS */
1039
1040 /*
1041  * Allocate memory for a new zvol_state_t and setup the required
1042  * request queue and generic disk structures for the block device.
1043  */
1044 static zvol_state_t *
1045 zvol_alloc(dev_t dev, const char *name)
1046 {
1047         zvol_state_t *zv;
1048
1049         zv = kmem_zalloc(sizeof (zvol_state_t), KM_SLEEP);
1050         if (zv == NULL)
1051                 goto out;
1052
1053         zv->zv_queue = blk_init_queue(zvol_request, &zv->zv_lock);
1054         if (zv->zv_queue == NULL)
1055                 goto out_kmem;
1056
1057         zv->zv_disk = alloc_disk(ZVOL_MINORS);
1058         if (zv->zv_disk == NULL)
1059                 goto out_queue;
1060
1061         zv->zv_queue->queuedata = zv;
1062         zv->zv_dev = dev;
1063         zv->zv_open_count = 0;
1064         strlcpy(zv->zv_name, name, MAXNAMELEN);
1065
1066         mutex_init(&zv->zv_znode.z_range_lock, NULL, MUTEX_DEFAULT, NULL);
1067         avl_create(&zv->zv_znode.z_range_avl, zfs_range_compare,
1068             sizeof (rl_t), offsetof(rl_t, r_node));
1069         zv->zv_znode.z_is_zvol = TRUE;
1070
1071         spin_lock_init(&zv->zv_lock);
1072         list_link_init(&zv->zv_next);
1073
1074         zv->zv_disk->major = zvol_major;
1075         zv->zv_disk->first_minor = (dev & MINORMASK);
1076         zv->zv_disk->fops = &zvol_ops;
1077         zv->zv_disk->private_data = zv;
1078         zv->zv_disk->queue = zv->zv_queue;
1079         snprintf(zv->zv_disk->disk_name, DISK_NAME_LEN, "%s%d",
1080             ZVOL_DEV_NAME, (dev & MINORMASK));
1081
1082         return zv;
1083
1084 out_queue:
1085         blk_cleanup_queue(zv->zv_queue);
1086 out_kmem:
1087         kmem_free(zv, sizeof (zvol_state_t));
1088 out:
1089         return NULL;
1090 }
1091
1092 /*
1093  * Cleanup then free a zvol_state_t which was created by zvol_alloc().
1094  */
1095 static void
1096 zvol_free(zvol_state_t *zv)
1097 {
1098         avl_destroy(&zv->zv_znode.z_range_avl);
1099         mutex_destroy(&zv->zv_znode.z_range_lock);
1100
1101         del_gendisk(zv->zv_disk);
1102         blk_cleanup_queue(zv->zv_queue);
1103         put_disk(zv->zv_disk);
1104
1105         kmem_free(zv, sizeof (zvol_state_t));
1106 }
1107
1108 static int
1109 __zvol_create_minor(const char *name)
1110 {
1111         zvol_state_t *zv;
1112         objset_t *os;
1113         dmu_object_info_t *doi;
1114         uint64_t volsize;
1115         unsigned minor = 0;
1116         int error = 0;
1117
1118         ASSERT(MUTEX_HELD(&zvol_state_lock));
1119
1120         zv = zvol_find_by_name(name);
1121         if (zv) {
1122                 error = EEXIST;
1123                 goto out;
1124         }
1125
1126         doi = kmem_alloc(sizeof(dmu_object_info_t), KM_SLEEP);
1127
1128         error = dmu_objset_own(name, DMU_OST_ZVOL, B_TRUE, zvol_tag, &os);
1129         if (error)
1130                 goto out_doi;
1131
1132         error = dmu_object_info(os, ZVOL_OBJ, doi);
1133         if (error)
1134                 goto out_dmu_objset_disown;
1135
1136         error = zap_lookup(os, ZVOL_ZAP_OBJ, "size", 8, 1, &volsize);
1137         if (error)
1138                 goto out_dmu_objset_disown;
1139
1140         error = zvol_find_minor(&minor);
1141         if (error)
1142                 goto out_dmu_objset_disown;
1143
1144         zv = zvol_alloc(MKDEV(zvol_major, minor), name);
1145         if (zv == NULL) {
1146                 error = EAGAIN;
1147                 goto out_dmu_objset_disown;
1148         }
1149
1150         if (dmu_objset_is_snapshot(os))
1151                 zv->zv_flags |= ZVOL_RDONLY;
1152
1153         zv->zv_volblocksize = doi->doi_data_block_size;
1154         zv->zv_volsize = volsize;
1155         zv->zv_objset = os;
1156
1157         set_capacity(zv->zv_disk, zv->zv_volsize >> 9);
1158
1159         if (zil_replay_disable)
1160                 zil_destroy(dmu_objset_zil(os), B_FALSE);
1161         else
1162                 zil_replay(os, zv, zvol_replay_vector);
1163
1164 out_dmu_objset_disown:
1165         dmu_objset_disown(os, zvol_tag);
1166         zv->zv_objset = NULL;
1167 out_doi:
1168         kmem_free(doi, sizeof(dmu_object_info_t));
1169 out:
1170
1171         if (error == 0) {
1172                 zvol_insert(zv);
1173                 add_disk(zv->zv_disk);
1174         }
1175
1176         return (error);
1177 }
1178
1179 /*
1180  * Create a block device minor node and setup the linkage between it
1181  * and the specified volume.  Once this function returns the block
1182  * device is live and ready for use.
1183  */
1184 int
1185 zvol_create_minor(const char *name)
1186 {
1187         int error;
1188
1189         mutex_enter(&zvol_state_lock);
1190         error = __zvol_create_minor(name);
1191         mutex_exit(&zvol_state_lock);
1192
1193         return (error);
1194 }
1195
1196 static int
1197 __zvol_remove_minor(const char *name)
1198 {
1199         zvol_state_t *zv;
1200
1201         ASSERT(MUTEX_HELD(&zvol_state_lock));
1202
1203         zv = zvol_find_by_name(name);
1204         if (zv == NULL)
1205                 return (ENXIO);
1206
1207         if (zv->zv_open_count > 0)
1208                 return (EBUSY);
1209
1210         zvol_remove(zv);
1211         zvol_free(zv);
1212
1213         return (0);
1214 }
1215
1216 /*
1217  * Remove a block device minor node for the specified volume.
1218  */
1219 int
1220 zvol_remove_minor(const char *name)
1221 {
1222         int error;
1223
1224         mutex_enter(&zvol_state_lock);
1225         error = __zvol_remove_minor(name);
1226         mutex_exit(&zvol_state_lock);
1227
1228         return (error);
1229 }
1230
1231 static int
1232 zvol_create_minors_cb(spa_t *spa, uint64_t dsobj,
1233                       const char *dsname, void *arg)
1234 {
1235         if (strchr(dsname, '/') == NULL)
1236                 return 0;
1237
1238         (void) __zvol_create_minor(dsname);
1239         return (0);
1240 }
1241
1242 /*
1243  * Create minors for specified pool, if pool is NULL create minors
1244  * for all available pools.
1245  */
1246 int
1247 zvol_create_minors(const char *pool)
1248 {
1249         spa_t *spa = NULL;
1250         int error = 0;
1251
1252         mutex_enter(&zvol_state_lock);
1253         if (pool) {
1254                 error = dmu_objset_find_spa(NULL, pool, zvol_create_minors_cb,
1255                     NULL, DS_FIND_CHILDREN | DS_FIND_SNAPSHOTS);
1256         } else {
1257                 mutex_enter(&spa_namespace_lock);
1258                 while ((spa = spa_next(spa)) != NULL) {
1259                         error = dmu_objset_find_spa(NULL,
1260                             spa_name(spa), zvol_create_minors_cb, NULL,
1261                             DS_FIND_CHILDREN | DS_FIND_SNAPSHOTS);
1262                         if (error)
1263                                 break;
1264                 }
1265                 mutex_exit(&spa_namespace_lock);
1266         }
1267         mutex_exit(&zvol_state_lock);
1268
1269         return error;
1270 }
1271
1272 /*
1273  * Remove minors for specified pool, if pool is NULL remove all minors.
1274  */
1275 void
1276 zvol_remove_minors(const char *pool)
1277 {
1278         zvol_state_t *zv, *zv_next;
1279         char *str;
1280
1281         str = kmem_zalloc(MAXNAMELEN, KM_SLEEP);
1282         if (pool) {
1283                 (void) strncpy(str, pool, strlen(pool));
1284                 (void) strcat(str, "/");
1285         }
1286
1287         mutex_enter(&zvol_state_lock);
1288         for (zv = list_head(&zvol_state_list); zv != NULL; zv = zv_next) {
1289                 zv_next = list_next(&zvol_state_list, zv);
1290
1291                 if (pool == NULL || !strncmp(str, zv->zv_name, strlen(str))) {
1292                         zvol_remove(zv);
1293                         zvol_free(zv);
1294                 }
1295         }
1296         mutex_exit(&zvol_state_lock);
1297         kmem_free(str, MAXNAMELEN);
1298 }
1299
1300 int
1301 zvol_init(void)
1302 {
1303         int error;
1304
1305         if (!zvol_threads)
1306                 zvol_threads = num_online_cpus();
1307
1308         zvol_taskq = taskq_create(ZVOL_DRIVER, zvol_threads, maxclsyspri,
1309                                   zvol_threads, INT_MAX, TASKQ_PREPOPULATE);
1310         if (zvol_taskq == NULL) {
1311                 printk(KERN_INFO "ZFS: taskq_create() failed\n");
1312                 return (-ENOMEM);
1313         }
1314
1315         error = register_blkdev(zvol_major, ZVOL_DRIVER);
1316         if (error) {
1317                 printk(KERN_INFO "ZFS: register_blkdev() failed %d\n", error);
1318                 taskq_destroy(zvol_taskq);
1319                 return (error);
1320         }
1321
1322         blk_register_region(MKDEV(zvol_major, 0), 1UL << MINORBITS,
1323                             THIS_MODULE, zvol_probe, NULL, NULL);
1324
1325         mutex_init(&zvol_state_lock, NULL, MUTEX_DEFAULT, NULL);
1326         list_create(&zvol_state_list, sizeof (zvol_state_t),
1327                     offsetof(zvol_state_t, zv_next));
1328
1329         (void) zvol_create_minors(NULL);
1330
1331         return (0);
1332 }
1333
1334 void
1335 zvol_fini(void)
1336 {
1337         zvol_remove_minors(NULL);
1338         blk_unregister_region(MKDEV(zvol_major, 0), 1UL << MINORBITS);
1339         unregister_blkdev(zvol_major, ZVOL_DRIVER);
1340         taskq_destroy(zvol_taskq);
1341         mutex_destroy(&zvol_state_lock);
1342         list_destroy(&zvol_state_list);
1343 }
1344
1345 module_param(zvol_major, uint, 0);
1346 MODULE_PARM_DESC(zvol_major, "Major number for zvol device");
1347
1348 module_param(zvol_threads, uint, 0);
1349 MODULE_PARM_DESC(zvol_threads, "Number of threads for zvol device");