2 * Copyright (C) 2001, 2002 Sistina Software (UK) Limited.
3 * Copyright (C) 2004-2008 Red Hat, Inc. All rights reserved.
5 * This file is released under the GPL.
11 #include <linux/init.h>
12 #include <linux/module.h>
13 #include <linux/mutex.h>
14 #include <linux/moduleparam.h>
15 #include <linux/blkpg.h>
16 #include <linux/bio.h>
17 #include <linux/buffer_head.h>
18 #include <linux/smp_lock.h>
19 #include <linux/mempool.h>
20 #include <linux/slab.h>
21 #include <linux/idr.h>
22 #include <linux/hdreg.h>
23 #include <linux/delay.h>
25 #include <trace/events/block.h>
27 #define DM_MSG_PREFIX "core"
30 * Cookies are numeric values sent with CHANGE and REMOVE
31 * uevents while resuming, removing or renaming the device.
33 #define DM_COOKIE_ENV_VAR_NAME "DM_COOKIE"
34 #define DM_COOKIE_LENGTH 24
36 static const char *_name = DM_NAME;
38 static unsigned int major = 0;
39 static unsigned int _major = 0;
41 static DEFINE_SPINLOCK(_minor_lock);
44 * One of these is allocated per bio.
47 struct mapped_device *md;
51 unsigned long start_time;
52 spinlock_t endio_lock;
57 * One of these is allocated per target within a bio. Hopefully
58 * this will be simplified out one day.
67 * For request-based dm.
68 * One of these is allocated per request.
70 struct dm_rq_target_io {
71 struct mapped_device *md;
73 struct request *orig, clone;
79 * For request-based dm.
80 * One of these is allocated per bio.
82 struct dm_rq_clone_bio_info {
84 struct dm_rq_target_io *tio;
87 union map_info *dm_get_mapinfo(struct bio *bio)
89 if (bio && bio->bi_private)
90 return &((struct dm_target_io *)bio->bi_private)->info;
94 union map_info *dm_get_rq_mapinfo(struct request *rq)
96 if (rq && rq->end_io_data)
97 return &((struct dm_rq_target_io *)rq->end_io_data)->info;
100 EXPORT_SYMBOL_GPL(dm_get_rq_mapinfo);
102 #define MINOR_ALLOCED ((void *)-1)
105 * Bits for the md->flags field.
107 #define DMF_BLOCK_IO_FOR_SUSPEND 0
108 #define DMF_SUSPENDED 1
110 #define DMF_FREEING 3
111 #define DMF_DELETING 4
112 #define DMF_NOFLUSH_SUSPENDING 5
113 #define DMF_QUEUE_IO_TO_THREAD 6
116 * Work processed by per-device workqueue.
118 struct mapped_device {
119 struct rw_semaphore io_lock;
120 struct mutex suspend_lock;
127 struct request_queue *queue;
128 struct gendisk *disk;
134 * A list of ios that arrived while we were suspended.
137 wait_queue_head_t wait;
138 struct work_struct work;
139 struct bio_list deferred;
140 spinlock_t deferred_lock;
143 * An error from the barrier request currently being processed.
148 * Protect barrier_error from concurrent endio processing
149 * in request-based dm.
151 spinlock_t barrier_error_lock;
154 * Processing queue (flush/barriers)
156 struct workqueue_struct *wq;
157 struct work_struct barrier_work;
159 /* A pointer to the currently processing pre/post flush request */
160 struct request *flush_request;
163 * The current mapping.
165 struct dm_table *map;
168 * io objects are allocated from here.
179 wait_queue_head_t eventq;
181 struct list_head uevent_list;
182 spinlock_t uevent_lock; /* Protect access to uevent_list */
185 * freeze/thaw support require holding onto a super block
187 struct super_block *frozen_sb;
188 struct block_device *bdev;
190 /* forced geometry settings */
191 struct hd_geometry geometry;
193 /* For saving the address of __make_request for request based dm */
194 make_request_fn *saved_make_request_fn;
199 /* zero-length barrier that will be cloned and submitted to targets */
200 struct bio barrier_bio;
204 * For mempools pre-allocation at the table loading time.
206 struct dm_md_mempools {
213 static struct kmem_cache *_io_cache;
214 static struct kmem_cache *_tio_cache;
215 static struct kmem_cache *_rq_tio_cache;
216 static struct kmem_cache *_rq_bio_info_cache;
218 static int __init local_init(void)
222 /* allocate a slab for the dm_ios */
223 _io_cache = KMEM_CACHE(dm_io, 0);
227 /* allocate a slab for the target ios */
228 _tio_cache = KMEM_CACHE(dm_target_io, 0);
230 goto out_free_io_cache;
232 _rq_tio_cache = KMEM_CACHE(dm_rq_target_io, 0);
234 goto out_free_tio_cache;
236 _rq_bio_info_cache = KMEM_CACHE(dm_rq_clone_bio_info, 0);
237 if (!_rq_bio_info_cache)
238 goto out_free_rq_tio_cache;
240 r = dm_uevent_init();
242 goto out_free_rq_bio_info_cache;
245 r = register_blkdev(_major, _name);
247 goto out_uevent_exit;
256 out_free_rq_bio_info_cache:
257 kmem_cache_destroy(_rq_bio_info_cache);
258 out_free_rq_tio_cache:
259 kmem_cache_destroy(_rq_tio_cache);
261 kmem_cache_destroy(_tio_cache);
263 kmem_cache_destroy(_io_cache);
268 static void local_exit(void)
270 kmem_cache_destroy(_rq_bio_info_cache);
271 kmem_cache_destroy(_rq_tio_cache);
272 kmem_cache_destroy(_tio_cache);
273 kmem_cache_destroy(_io_cache);
274 unregister_blkdev(_major, _name);
279 DMINFO("cleaned up");
282 static int (*_inits[])(void) __initdata = {
292 static void (*_exits[])(void) = {
302 static int __init dm_init(void)
304 const int count = ARRAY_SIZE(_inits);
308 for (i = 0; i < count; i++) {
323 static void __exit dm_exit(void)
325 int i = ARRAY_SIZE(_exits);
332 * Block device functions
334 int dm_deleting_md(struct mapped_device *md)
336 return test_bit(DMF_DELETING, &md->flags);
339 static int dm_blk_open(struct block_device *bdev, fmode_t mode)
341 struct mapped_device *md;
344 spin_lock(&_minor_lock);
346 md = bdev->bd_disk->private_data;
350 if (test_bit(DMF_FREEING, &md->flags) ||
351 dm_deleting_md(md)) {
357 atomic_inc(&md->open_count);
360 spin_unlock(&_minor_lock);
363 return md ? 0 : -ENXIO;
366 static int dm_blk_close(struct gendisk *disk, fmode_t mode)
368 struct mapped_device *md = disk->private_data;
371 atomic_dec(&md->open_count);
378 int dm_open_count(struct mapped_device *md)
380 return atomic_read(&md->open_count);
384 * Guarantees nothing is using the device before it's deleted.
386 int dm_lock_for_deletion(struct mapped_device *md)
390 spin_lock(&_minor_lock);
392 if (dm_open_count(md))
395 set_bit(DMF_DELETING, &md->flags);
397 spin_unlock(&_minor_lock);
402 static int dm_blk_getgeo(struct block_device *bdev, struct hd_geometry *geo)
404 struct mapped_device *md = bdev->bd_disk->private_data;
406 return dm_get_geometry(md, geo);
409 static int dm_blk_ioctl(struct block_device *bdev, fmode_t mode,
410 unsigned int cmd, unsigned long arg)
412 struct mapped_device *md = bdev->bd_disk->private_data;
413 struct dm_table *map = dm_get_live_table(md);
414 struct dm_target *tgt;
417 if (!map || !dm_table_get_size(map))
420 /* We only support devices that have a single target */
421 if (dm_table_get_num_targets(map) != 1)
424 tgt = dm_table_get_target(map, 0);
426 if (dm_suspended_md(md)) {
431 if (tgt->type->ioctl)
432 r = tgt->type->ioctl(tgt, cmd, arg);
440 static struct dm_io *alloc_io(struct mapped_device *md)
442 return mempool_alloc(md->io_pool, GFP_NOIO);
445 static void free_io(struct mapped_device *md, struct dm_io *io)
447 mempool_free(io, md->io_pool);
450 static void free_tio(struct mapped_device *md, struct dm_target_io *tio)
452 mempool_free(tio, md->tio_pool);
455 static struct dm_rq_target_io *alloc_rq_tio(struct mapped_device *md,
458 return mempool_alloc(md->tio_pool, gfp_mask);
461 static void free_rq_tio(struct dm_rq_target_io *tio)
463 mempool_free(tio, tio->md->tio_pool);
466 static struct dm_rq_clone_bio_info *alloc_bio_info(struct mapped_device *md)
468 return mempool_alloc(md->io_pool, GFP_ATOMIC);
471 static void free_bio_info(struct dm_rq_clone_bio_info *info)
473 mempool_free(info, info->tio->md->io_pool);
476 static int md_in_flight(struct mapped_device *md)
478 return atomic_read(&md->pending[READ]) +
479 atomic_read(&md->pending[WRITE]);
482 static void start_io_acct(struct dm_io *io)
484 struct mapped_device *md = io->md;
486 int rw = bio_data_dir(io->bio);
488 io->start_time = jiffies;
490 cpu = part_stat_lock();
491 part_round_stats(cpu, &dm_disk(md)->part0);
493 dm_disk(md)->part0.in_flight[rw] = atomic_inc_return(&md->pending[rw]);
496 static void end_io_acct(struct dm_io *io)
498 struct mapped_device *md = io->md;
499 struct bio *bio = io->bio;
500 unsigned long duration = jiffies - io->start_time;
502 int rw = bio_data_dir(bio);
504 cpu = part_stat_lock();
505 part_round_stats(cpu, &dm_disk(md)->part0);
506 part_stat_add(cpu, &dm_disk(md)->part0, ticks[rw], duration);
510 * After this is decremented the bio must not be touched if it is
513 dm_disk(md)->part0.in_flight[rw] = pending =
514 atomic_dec_return(&md->pending[rw]);
515 pending += atomic_read(&md->pending[rw^0x1]);
517 /* nudge anyone waiting on suspend queue */
523 * Add the bio to the list of deferred io.
525 static void queue_io(struct mapped_device *md, struct bio *bio)
527 down_write(&md->io_lock);
529 spin_lock_irq(&md->deferred_lock);
530 bio_list_add(&md->deferred, bio);
531 spin_unlock_irq(&md->deferred_lock);
533 if (!test_and_set_bit(DMF_QUEUE_IO_TO_THREAD, &md->flags))
534 queue_work(md->wq, &md->work);
536 up_write(&md->io_lock);
540 * Everyone (including functions in this file), should use this
541 * function to access the md->map field, and make sure they call
542 * dm_table_put() when finished.
544 struct dm_table *dm_get_live_table(struct mapped_device *md)
549 read_lock_irqsave(&md->map_lock, flags);
553 read_unlock_irqrestore(&md->map_lock, flags);
559 * Get the geometry associated with a dm device
561 int dm_get_geometry(struct mapped_device *md, struct hd_geometry *geo)
569 * Set the geometry of a device.
571 int dm_set_geometry(struct mapped_device *md, struct hd_geometry *geo)
573 sector_t sz = (sector_t)geo->cylinders * geo->heads * geo->sectors;
575 if (geo->start > sz) {
576 DMWARN("Start sector is beyond the geometry limits.");
585 /*-----------------------------------------------------------------
587 * A more elegant soln is in the works that uses the queue
588 * merge fn, unfortunately there are a couple of changes to
589 * the block layer that I want to make for this. So in the
590 * interests of getting something for people to use I give
591 * you this clearly demarcated crap.
592 *---------------------------------------------------------------*/
594 static int __noflush_suspending(struct mapped_device *md)
596 return test_bit(DMF_NOFLUSH_SUSPENDING, &md->flags);
600 * Decrements the number of outstanding ios that a bio has been
601 * cloned into, completing the original io if necc.
603 static void dec_pending(struct dm_io *io, int error)
608 struct mapped_device *md = io->md;
610 /* Push-back supersedes any I/O errors */
611 if (unlikely(error)) {
612 spin_lock_irqsave(&io->endio_lock, flags);
613 if (!(io->error > 0 && __noflush_suspending(md)))
615 spin_unlock_irqrestore(&io->endio_lock, flags);
618 if (atomic_dec_and_test(&io->io_count)) {
619 if (io->error == DM_ENDIO_REQUEUE) {
621 * Target requested pushing back the I/O.
623 spin_lock_irqsave(&md->deferred_lock, flags);
624 if (__noflush_suspending(md)) {
625 if (!(io->bio->bi_rw & REQ_HARDBARRIER))
626 bio_list_add_head(&md->deferred,
629 /* noflush suspend was interrupted. */
631 spin_unlock_irqrestore(&md->deferred_lock, flags);
634 io_error = io->error;
637 if (bio->bi_rw & REQ_HARDBARRIER) {
639 * There can be just one barrier request so we use
640 * a per-device variable for error reporting.
641 * Note that you can't touch the bio after end_io_acct
643 if (!md->barrier_error && io_error != -EOPNOTSUPP)
644 md->barrier_error = io_error;
651 if (io_error != DM_ENDIO_REQUEUE) {
652 trace_block_bio_complete(md->queue, bio);
654 bio_endio(bio, io_error);
660 static void clone_endio(struct bio *bio, int error)
663 struct dm_target_io *tio = bio->bi_private;
664 struct dm_io *io = tio->io;
665 struct mapped_device *md = tio->io->md;
666 dm_endio_fn endio = tio->ti->type->end_io;
668 if (!bio_flagged(bio, BIO_UPTODATE) && !error)
672 r = endio(tio->ti, bio, error, &tio->info);
673 if (r < 0 || r == DM_ENDIO_REQUEUE)
675 * error and requeue request are handled
679 else if (r == DM_ENDIO_INCOMPLETE)
680 /* The target will handle the io */
683 DMWARN("unimplemented target endio return value: %d", r);
689 * Store md for cleanup instead of tio which is about to get freed.
691 bio->bi_private = md->bs;
695 dec_pending(io, error);
699 * Partial completion handling for request-based dm
701 static void end_clone_bio(struct bio *clone, int error)
703 struct dm_rq_clone_bio_info *info = clone->bi_private;
704 struct dm_rq_target_io *tio = info->tio;
705 struct bio *bio = info->orig;
706 unsigned int nr_bytes = info->orig->bi_size;
712 * An error has already been detected on the request.
713 * Once error occurred, just let clone->end_io() handle
719 * Don't notice the error to the upper layer yet.
720 * The error handling decision is made by the target driver,
721 * when the request is completed.
728 * I/O for the bio successfully completed.
729 * Notice the data completion to the upper layer.
733 * bios are processed from the head of the list.
734 * So the completing bio should always be rq->bio.
735 * If it's not, something wrong is happening.
737 if (tio->orig->bio != bio)
738 DMERR("bio completion is going in the middle of the request");
741 * Update the original request.
742 * Do not use blk_end_request() here, because it may complete
743 * the original request before the clone, and break the ordering.
745 blk_update_request(tio->orig, 0, nr_bytes);
748 static void store_barrier_error(struct mapped_device *md, int error)
752 spin_lock_irqsave(&md->barrier_error_lock, flags);
754 * Basically, the first error is taken, but:
755 * -EOPNOTSUPP supersedes any I/O error.
756 * Requeue request supersedes any I/O error but -EOPNOTSUPP.
758 if (!md->barrier_error || error == -EOPNOTSUPP ||
759 (md->barrier_error != -EOPNOTSUPP &&
760 error == DM_ENDIO_REQUEUE))
761 md->barrier_error = error;
762 spin_unlock_irqrestore(&md->barrier_error_lock, flags);
766 * Don't touch any member of the md after calling this function because
767 * the md may be freed in dm_put() at the end of this function.
768 * Or do dm_get() before calling this function and dm_put() later.
770 static void rq_completed(struct mapped_device *md, int rw, int run_queue)
772 atomic_dec(&md->pending[rw]);
774 /* nudge anyone waiting on suspend queue */
775 if (!md_in_flight(md))
779 blk_run_queue(md->queue);
782 * dm_put() must be at the end of this function. See the comment above
787 static void free_rq_clone(struct request *clone)
789 struct dm_rq_target_io *tio = clone->end_io_data;
791 blk_rq_unprep_clone(clone);
796 * Complete the clone and the original request.
797 * Must be called without queue lock.
799 static void dm_end_request(struct request *clone, int error)
801 int rw = rq_data_dir(clone);
803 bool is_barrier = clone->cmd_flags & REQ_HARDBARRIER;
804 struct dm_rq_target_io *tio = clone->end_io_data;
805 struct mapped_device *md = tio->md;
806 struct request *rq = tio->orig;
808 if (rq->cmd_type == REQ_TYPE_BLOCK_PC && !is_barrier) {
809 rq->errors = clone->errors;
810 rq->resid_len = clone->resid_len;
814 * We are using the sense buffer of the original
816 * So setting the length of the sense data is enough.
818 rq->sense_len = clone->sense_len;
821 free_rq_clone(clone);
823 if (unlikely(is_barrier)) {
825 store_barrier_error(md, error);
828 blk_end_request_all(rq, error);
830 rq_completed(md, rw, run_queue);
833 static void dm_unprep_request(struct request *rq)
835 struct request *clone = rq->special;
838 rq->cmd_flags &= ~REQ_DONTPREP;
840 free_rq_clone(clone);
844 * Requeue the original request of a clone.
846 void dm_requeue_unmapped_request(struct request *clone)
848 int rw = rq_data_dir(clone);
849 struct dm_rq_target_io *tio = clone->end_io_data;
850 struct mapped_device *md = tio->md;
851 struct request *rq = tio->orig;
852 struct request_queue *q = rq->q;
855 if (unlikely(clone->cmd_flags & REQ_HARDBARRIER)) {
857 * Barrier clones share an original request.
858 * Leave it to dm_end_request(), which handles this special
861 dm_end_request(clone, DM_ENDIO_REQUEUE);
865 dm_unprep_request(rq);
867 spin_lock_irqsave(q->queue_lock, flags);
868 if (elv_queue_empty(q))
870 blk_requeue_request(q, rq);
871 spin_unlock_irqrestore(q->queue_lock, flags);
873 rq_completed(md, rw, 0);
875 EXPORT_SYMBOL_GPL(dm_requeue_unmapped_request);
877 static void __stop_queue(struct request_queue *q)
882 static void stop_queue(struct request_queue *q)
886 spin_lock_irqsave(q->queue_lock, flags);
888 spin_unlock_irqrestore(q->queue_lock, flags);
891 static void __start_queue(struct request_queue *q)
893 if (blk_queue_stopped(q))
897 static void start_queue(struct request_queue *q)
901 spin_lock_irqsave(q->queue_lock, flags);
903 spin_unlock_irqrestore(q->queue_lock, flags);
906 static void dm_done(struct request *clone, int error, bool mapped)
909 struct dm_rq_target_io *tio = clone->end_io_data;
910 dm_request_endio_fn rq_end_io = tio->ti->type->rq_end_io;
912 if (mapped && rq_end_io)
913 r = rq_end_io(tio->ti, clone, error, &tio->info);
916 /* The target wants to complete the I/O */
917 dm_end_request(clone, r);
918 else if (r == DM_ENDIO_INCOMPLETE)
919 /* The target will handle the I/O */
921 else if (r == DM_ENDIO_REQUEUE)
922 /* The target wants to requeue the I/O */
923 dm_requeue_unmapped_request(clone);
925 DMWARN("unimplemented target endio return value: %d", r);
931 * Request completion handler for request-based dm
933 static void dm_softirq_done(struct request *rq)
936 struct request *clone = rq->completion_data;
937 struct dm_rq_target_io *tio = clone->end_io_data;
939 if (rq->cmd_flags & REQ_FAILED)
942 dm_done(clone, tio->error, mapped);
946 * Complete the clone and the original request with the error status
947 * through softirq context.
949 static void dm_complete_request(struct request *clone, int error)
951 struct dm_rq_target_io *tio = clone->end_io_data;
952 struct request *rq = tio->orig;
954 if (unlikely(clone->cmd_flags & REQ_HARDBARRIER)) {
956 * Barrier clones share an original request. So can't use
957 * softirq_done with the original.
958 * Pass the clone to dm_done() directly in this special case.
959 * It is safe (even if clone->q->queue_lock is held here)
960 * because there is no I/O dispatching during the completion
963 dm_done(clone, error, true);
968 rq->completion_data = clone;
969 blk_complete_request(rq);
973 * Complete the not-mapped clone and the original request with the error status
974 * through softirq context.
975 * Target's rq_end_io() function isn't called.
976 * This may be used when the target's map_rq() function fails.
978 void dm_kill_unmapped_request(struct request *clone, int error)
980 struct dm_rq_target_io *tio = clone->end_io_data;
981 struct request *rq = tio->orig;
983 if (unlikely(clone->cmd_flags & REQ_HARDBARRIER)) {
985 * Barrier clones share an original request.
986 * Leave it to dm_end_request(), which handles this special
990 dm_end_request(clone, error);
994 rq->cmd_flags |= REQ_FAILED;
995 dm_complete_request(clone, error);
997 EXPORT_SYMBOL_GPL(dm_kill_unmapped_request);
1000 * Called with the queue lock held
1002 static void end_clone_request(struct request *clone, int error)
1005 * For just cleaning up the information of the queue in which
1006 * the clone was dispatched.
1007 * The clone is *NOT* freed actually here because it is alloced from
1008 * dm own mempool and REQ_ALLOCED isn't set in clone->cmd_flags.
1010 __blk_put_request(clone->q, clone);
1013 * Actual request completion is done in a softirq context which doesn't
1014 * hold the queue lock. Otherwise, deadlock could occur because:
1015 * - another request may be submitted by the upper level driver
1016 * of the stacking during the completion
1017 * - the submission which requires queue lock may be done
1018 * against this queue
1020 dm_complete_request(clone, error);
1023 static sector_t max_io_len(struct mapped_device *md,
1024 sector_t sector, struct dm_target *ti)
1026 sector_t offset = sector - ti->begin;
1027 sector_t len = ti->len - offset;
1030 * Does the target need to split even further ?
1034 boundary = ((offset + ti->split_io) & ~(ti->split_io - 1))
1043 static void __map_bio(struct dm_target *ti, struct bio *clone,
1044 struct dm_target_io *tio)
1048 struct mapped_device *md;
1050 clone->bi_end_io = clone_endio;
1051 clone->bi_private = tio;
1054 * Map the clone. If r == 0 we don't need to do
1055 * anything, the target has assumed ownership of
1058 atomic_inc(&tio->io->io_count);
1059 sector = clone->bi_sector;
1060 r = ti->type->map(ti, clone, &tio->info);
1061 if (r == DM_MAPIO_REMAPPED) {
1062 /* the bio has been remapped so dispatch it */
1064 trace_block_remap(bdev_get_queue(clone->bi_bdev), clone,
1065 tio->io->bio->bi_bdev->bd_dev, sector);
1067 generic_make_request(clone);
1068 } else if (r < 0 || r == DM_MAPIO_REQUEUE) {
1069 /* error the io and bail out, or requeue it if needed */
1071 dec_pending(tio->io, r);
1073 * Store bio_set for cleanup.
1075 clone->bi_private = md->bs;
1079 DMWARN("unimplemented target map return value: %d", r);
1085 struct mapped_device *md;
1086 struct dm_table *map;
1090 sector_t sector_count;
1094 static void dm_bio_destructor(struct bio *bio)
1096 struct bio_set *bs = bio->bi_private;
1102 * Creates a little bio that is just does part of a bvec.
1104 static struct bio *split_bvec(struct bio *bio, sector_t sector,
1105 unsigned short idx, unsigned int offset,
1106 unsigned int len, struct bio_set *bs)
1109 struct bio_vec *bv = bio->bi_io_vec + idx;
1111 clone = bio_alloc_bioset(GFP_NOIO, 1, bs);
1112 clone->bi_destructor = dm_bio_destructor;
1113 *clone->bi_io_vec = *bv;
1115 clone->bi_sector = sector;
1116 clone->bi_bdev = bio->bi_bdev;
1117 clone->bi_rw = bio->bi_rw & ~REQ_HARDBARRIER;
1119 clone->bi_size = to_bytes(len);
1120 clone->bi_io_vec->bv_offset = offset;
1121 clone->bi_io_vec->bv_len = clone->bi_size;
1122 clone->bi_flags |= 1 << BIO_CLONED;
1124 if (bio_integrity(bio)) {
1125 bio_integrity_clone(clone, bio, GFP_NOIO, bs);
1126 bio_integrity_trim(clone,
1127 bio_sector_offset(bio, idx, offset), len);
1134 * Creates a bio that consists of range of complete bvecs.
1136 static struct bio *clone_bio(struct bio *bio, sector_t sector,
1137 unsigned short idx, unsigned short bv_count,
1138 unsigned int len, struct bio_set *bs)
1142 clone = bio_alloc_bioset(GFP_NOIO, bio->bi_max_vecs, bs);
1143 __bio_clone(clone, bio);
1144 clone->bi_rw &= ~REQ_HARDBARRIER;
1145 clone->bi_destructor = dm_bio_destructor;
1146 clone->bi_sector = sector;
1147 clone->bi_idx = idx;
1148 clone->bi_vcnt = idx + bv_count;
1149 clone->bi_size = to_bytes(len);
1150 clone->bi_flags &= ~(1 << BIO_SEG_VALID);
1152 if (bio_integrity(bio)) {
1153 bio_integrity_clone(clone, bio, GFP_NOIO, bs);
1155 if (idx != bio->bi_idx || clone->bi_size < bio->bi_size)
1156 bio_integrity_trim(clone,
1157 bio_sector_offset(bio, idx, 0), len);
1163 static struct dm_target_io *alloc_tio(struct clone_info *ci,
1164 struct dm_target *ti)
1166 struct dm_target_io *tio = mempool_alloc(ci->md->tio_pool, GFP_NOIO);
1170 memset(&tio->info, 0, sizeof(tio->info));
1175 static void __flush_target(struct clone_info *ci, struct dm_target *ti,
1178 struct dm_target_io *tio = alloc_tio(ci, ti);
1181 tio->info.flush_request = flush_nr;
1183 clone = bio_alloc_bioset(GFP_NOIO, 0, ci->md->bs);
1184 __bio_clone(clone, ci->bio);
1185 clone->bi_destructor = dm_bio_destructor;
1187 __map_bio(ti, clone, tio);
1190 static int __clone_and_map_empty_barrier(struct clone_info *ci)
1192 unsigned target_nr = 0, flush_nr;
1193 struct dm_target *ti;
1195 while ((ti = dm_table_get_target(ci->map, target_nr++)))
1196 for (flush_nr = 0; flush_nr < ti->num_flush_requests;
1198 __flush_target(ci, ti, flush_nr);
1200 ci->sector_count = 0;
1205 static int __clone_and_map(struct clone_info *ci)
1207 struct bio *clone, *bio = ci->bio;
1208 struct dm_target *ti;
1209 sector_t len = 0, max;
1210 struct dm_target_io *tio;
1212 if (unlikely(bio_empty_barrier(bio)))
1213 return __clone_and_map_empty_barrier(ci);
1215 ti = dm_table_find_target(ci->map, ci->sector);
1216 if (!dm_target_is_valid(ti))
1219 max = max_io_len(ci->md, ci->sector, ti);
1222 * Allocate a target io object.
1224 tio = alloc_tio(ci, ti);
1226 if (ci->sector_count <= max) {
1228 * Optimise for the simple case where we can do all of
1229 * the remaining io with a single clone.
1231 clone = clone_bio(bio, ci->sector, ci->idx,
1232 bio->bi_vcnt - ci->idx, ci->sector_count,
1234 __map_bio(ti, clone, tio);
1235 ci->sector_count = 0;
1237 } else if (to_sector(bio->bi_io_vec[ci->idx].bv_len) <= max) {
1239 * There are some bvecs that don't span targets.
1240 * Do as many of these as possible.
1243 sector_t remaining = max;
1246 for (i = ci->idx; remaining && (i < bio->bi_vcnt); i++) {
1247 bv_len = to_sector(bio->bi_io_vec[i].bv_len);
1249 if (bv_len > remaining)
1252 remaining -= bv_len;
1256 clone = clone_bio(bio, ci->sector, ci->idx, i - ci->idx, len,
1258 __map_bio(ti, clone, tio);
1261 ci->sector_count -= len;
1266 * Handle a bvec that must be split between two or more targets.
1268 struct bio_vec *bv = bio->bi_io_vec + ci->idx;
1269 sector_t remaining = to_sector(bv->bv_len);
1270 unsigned int offset = 0;
1274 ti = dm_table_find_target(ci->map, ci->sector);
1275 if (!dm_target_is_valid(ti))
1278 max = max_io_len(ci->md, ci->sector, ti);
1280 tio = alloc_tio(ci, ti);
1283 len = min(remaining, max);
1285 clone = split_bvec(bio, ci->sector, ci->idx,
1286 bv->bv_offset + offset, len,
1289 __map_bio(ti, clone, tio);
1292 ci->sector_count -= len;
1293 offset += to_bytes(len);
1294 } while (remaining -= len);
1303 * Split the bio into several clones and submit it to targets.
1305 static void __split_and_process_bio(struct mapped_device *md, struct bio *bio)
1307 struct clone_info ci;
1310 ci.map = dm_get_live_table(md);
1311 if (unlikely(!ci.map)) {
1312 if (!(bio->bi_rw & REQ_HARDBARRIER))
1315 if (!md->barrier_error)
1316 md->barrier_error = -EIO;
1322 ci.io = alloc_io(md);
1324 atomic_set(&ci.io->io_count, 1);
1327 spin_lock_init(&ci.io->endio_lock);
1328 ci.sector = bio->bi_sector;
1329 ci.sector_count = bio_sectors(bio);
1330 if (unlikely(bio_empty_barrier(bio)))
1331 ci.sector_count = 1;
1332 ci.idx = bio->bi_idx;
1334 start_io_acct(ci.io);
1335 while (ci.sector_count && !error)
1336 error = __clone_and_map(&ci);
1338 /* drop the extra reference count */
1339 dec_pending(ci.io, error);
1340 dm_table_put(ci.map);
1342 /*-----------------------------------------------------------------
1344 *---------------------------------------------------------------*/
1346 static int dm_merge_bvec(struct request_queue *q,
1347 struct bvec_merge_data *bvm,
1348 struct bio_vec *biovec)
1350 struct mapped_device *md = q->queuedata;
1351 struct dm_table *map = dm_get_live_table(md);
1352 struct dm_target *ti;
1353 sector_t max_sectors;
1359 ti = dm_table_find_target(map, bvm->bi_sector);
1360 if (!dm_target_is_valid(ti))
1364 * Find maximum amount of I/O that won't need splitting
1366 max_sectors = min(max_io_len(md, bvm->bi_sector, ti),
1367 (sector_t) BIO_MAX_SECTORS);
1368 max_size = (max_sectors << SECTOR_SHIFT) - bvm->bi_size;
1373 * merge_bvec_fn() returns number of bytes
1374 * it can accept at this offset
1375 * max is precomputed maximal io size
1377 if (max_size && ti->type->merge)
1378 max_size = ti->type->merge(ti, bvm, biovec, max_size);
1380 * If the target doesn't support merge method and some of the devices
1381 * provided their merge_bvec method (we know this by looking at
1382 * queue_max_hw_sectors), then we can't allow bios with multiple vector
1383 * entries. So always set max_size to 0, and the code below allows
1386 else if (queue_max_hw_sectors(q) <= PAGE_SIZE >> 9)
1395 * Always allow an entire first page
1397 if (max_size <= biovec->bv_len && !(bvm->bi_size >> SECTOR_SHIFT))
1398 max_size = biovec->bv_len;
1404 * The request function that just remaps the bio built up by
1407 static int _dm_request(struct request_queue *q, struct bio *bio)
1409 int rw = bio_data_dir(bio);
1410 struct mapped_device *md = q->queuedata;
1413 down_read(&md->io_lock);
1415 cpu = part_stat_lock();
1416 part_stat_inc(cpu, &dm_disk(md)->part0, ios[rw]);
1417 part_stat_add(cpu, &dm_disk(md)->part0, sectors[rw], bio_sectors(bio));
1421 * If we're suspended or the thread is processing barriers
1422 * we have to queue this io for later.
1424 if (unlikely(test_bit(DMF_QUEUE_IO_TO_THREAD, &md->flags)) ||
1425 unlikely(bio->bi_rw & REQ_HARDBARRIER)) {
1426 up_read(&md->io_lock);
1428 if (unlikely(test_bit(DMF_BLOCK_IO_FOR_SUSPEND, &md->flags)) &&
1429 bio_rw(bio) == READA) {
1439 __split_and_process_bio(md, bio);
1440 up_read(&md->io_lock);
1444 static int dm_make_request(struct request_queue *q, struct bio *bio)
1446 struct mapped_device *md = q->queuedata;
1448 return md->saved_make_request_fn(q, bio); /* call __make_request() */
1451 static int dm_request_based(struct mapped_device *md)
1453 return blk_queue_stackable(md->queue);
1456 static int dm_request(struct request_queue *q, struct bio *bio)
1458 struct mapped_device *md = q->queuedata;
1460 if (dm_request_based(md))
1461 return dm_make_request(q, bio);
1463 return _dm_request(q, bio);
1466 static bool dm_rq_is_flush_request(struct request *rq)
1468 if (rq->cmd_flags & REQ_FLUSH)
1474 void dm_dispatch_request(struct request *rq)
1478 if (blk_queue_io_stat(rq->q))
1479 rq->cmd_flags |= REQ_IO_STAT;
1481 rq->start_time = jiffies;
1482 r = blk_insert_cloned_request(rq->q, rq);
1484 dm_complete_request(rq, r);
1486 EXPORT_SYMBOL_GPL(dm_dispatch_request);
1488 static void dm_rq_bio_destructor(struct bio *bio)
1490 struct dm_rq_clone_bio_info *info = bio->bi_private;
1491 struct mapped_device *md = info->tio->md;
1493 free_bio_info(info);
1494 bio_free(bio, md->bs);
1497 static int dm_rq_bio_constructor(struct bio *bio, struct bio *bio_orig,
1500 struct dm_rq_target_io *tio = data;
1501 struct mapped_device *md = tio->md;
1502 struct dm_rq_clone_bio_info *info = alloc_bio_info(md);
1507 info->orig = bio_orig;
1509 bio->bi_end_io = end_clone_bio;
1510 bio->bi_private = info;
1511 bio->bi_destructor = dm_rq_bio_destructor;
1516 static int setup_clone(struct request *clone, struct request *rq,
1517 struct dm_rq_target_io *tio)
1521 if (dm_rq_is_flush_request(rq)) {
1522 blk_rq_init(NULL, clone);
1523 clone->cmd_type = REQ_TYPE_FS;
1524 clone->cmd_flags |= (REQ_HARDBARRIER | WRITE);
1526 r = blk_rq_prep_clone(clone, rq, tio->md->bs, GFP_ATOMIC,
1527 dm_rq_bio_constructor, tio);
1531 clone->cmd = rq->cmd;
1532 clone->cmd_len = rq->cmd_len;
1533 clone->sense = rq->sense;
1534 clone->buffer = rq->buffer;
1537 clone->end_io = end_clone_request;
1538 clone->end_io_data = tio;
1543 static struct request *clone_rq(struct request *rq, struct mapped_device *md,
1546 struct request *clone;
1547 struct dm_rq_target_io *tio;
1549 tio = alloc_rq_tio(md, gfp_mask);
1557 memset(&tio->info, 0, sizeof(tio->info));
1559 clone = &tio->clone;
1560 if (setup_clone(clone, rq, tio)) {
1570 * Called with the queue lock held.
1572 static int dm_prep_fn(struct request_queue *q, struct request *rq)
1574 struct mapped_device *md = q->queuedata;
1575 struct request *clone;
1577 if (unlikely(dm_rq_is_flush_request(rq)))
1580 if (unlikely(rq->special)) {
1581 DMWARN("Already has something in rq->special.");
1582 return BLKPREP_KILL;
1585 clone = clone_rq(rq, md, GFP_ATOMIC);
1587 return BLKPREP_DEFER;
1589 rq->special = clone;
1590 rq->cmd_flags |= REQ_DONTPREP;
1597 * 0 : the request has been processed (not requeued)
1598 * !0 : the request has been requeued
1600 static int map_request(struct dm_target *ti, struct request *clone,
1601 struct mapped_device *md)
1603 int r, requeued = 0;
1604 struct dm_rq_target_io *tio = clone->end_io_data;
1607 * Hold the md reference here for the in-flight I/O.
1608 * We can't rely on the reference count by device opener,
1609 * because the device may be closed during the request completion
1610 * when all bios are completed.
1611 * See the comment in rq_completed() too.
1616 r = ti->type->map_rq(ti, clone, &tio->info);
1618 case DM_MAPIO_SUBMITTED:
1619 /* The target has taken the I/O to submit by itself later */
1621 case DM_MAPIO_REMAPPED:
1622 /* The target has remapped the I/O so dispatch it */
1623 trace_block_rq_remap(clone->q, clone, disk_devt(dm_disk(md)),
1624 blk_rq_pos(tio->orig));
1625 dm_dispatch_request(clone);
1627 case DM_MAPIO_REQUEUE:
1628 /* The target wants to requeue the I/O */
1629 dm_requeue_unmapped_request(clone);
1634 DMWARN("unimplemented target map return value: %d", r);
1638 /* The target wants to complete the I/O */
1639 dm_kill_unmapped_request(clone, r);
1647 * q->request_fn for request-based dm.
1648 * Called with the queue lock held.
1650 static void dm_request_fn(struct request_queue *q)
1652 struct mapped_device *md = q->queuedata;
1653 struct dm_table *map = dm_get_live_table(md);
1654 struct dm_target *ti;
1655 struct request *rq, *clone;
1658 * For suspend, check blk_queue_stopped() and increment
1659 * ->pending within a single queue_lock not to increment the
1660 * number of in-flight I/Os after the queue is stopped in
1663 while (!blk_queue_plugged(q) && !blk_queue_stopped(q)) {
1664 rq = blk_peek_request(q);
1668 if (unlikely(dm_rq_is_flush_request(rq))) {
1669 BUG_ON(md->flush_request);
1670 md->flush_request = rq;
1671 blk_start_request(rq);
1672 queue_work(md->wq, &md->barrier_work);
1676 ti = dm_table_find_target(map, blk_rq_pos(rq));
1677 if (ti->type->busy && ti->type->busy(ti))
1680 blk_start_request(rq);
1681 clone = rq->special;
1682 atomic_inc(&md->pending[rq_data_dir(clone)]);
1684 spin_unlock(q->queue_lock);
1685 if (map_request(ti, clone, md))
1688 spin_lock_irq(q->queue_lock);
1694 spin_lock_irq(q->queue_lock);
1697 if (!elv_queue_empty(q))
1698 /* Some requests still remain, retry later */
1707 int dm_underlying_device_busy(struct request_queue *q)
1709 return blk_lld_busy(q);
1711 EXPORT_SYMBOL_GPL(dm_underlying_device_busy);
1713 static int dm_lld_busy(struct request_queue *q)
1716 struct mapped_device *md = q->queuedata;
1717 struct dm_table *map = dm_get_live_table(md);
1719 if (!map || test_bit(DMF_BLOCK_IO_FOR_SUSPEND, &md->flags))
1722 r = dm_table_any_busy_target(map);
1729 static void dm_unplug_all(struct request_queue *q)
1731 struct mapped_device *md = q->queuedata;
1732 struct dm_table *map = dm_get_live_table(md);
1735 if (dm_request_based(md))
1736 generic_unplug_device(q);
1738 dm_table_unplug_all(map);
1743 static int dm_any_congested(void *congested_data, int bdi_bits)
1746 struct mapped_device *md = congested_data;
1747 struct dm_table *map;
1749 if (!test_bit(DMF_BLOCK_IO_FOR_SUSPEND, &md->flags)) {
1750 map = dm_get_live_table(md);
1753 * Request-based dm cares about only own queue for
1754 * the query about congestion status of request_queue
1756 if (dm_request_based(md))
1757 r = md->queue->backing_dev_info.state &
1760 r = dm_table_any_congested(map, bdi_bits);
1769 /*-----------------------------------------------------------------
1770 * An IDR is used to keep track of allocated minor numbers.
1771 *---------------------------------------------------------------*/
1772 static DEFINE_IDR(_minor_idr);
1774 static void free_minor(int minor)
1776 spin_lock(&_minor_lock);
1777 idr_remove(&_minor_idr, minor);
1778 spin_unlock(&_minor_lock);
1782 * See if the device with a specific minor # is free.
1784 static int specific_minor(int minor)
1788 if (minor >= (1 << MINORBITS))
1791 r = idr_pre_get(&_minor_idr, GFP_KERNEL);
1795 spin_lock(&_minor_lock);
1797 if (idr_find(&_minor_idr, minor)) {
1802 r = idr_get_new_above(&_minor_idr, MINOR_ALLOCED, minor, &m);
1807 idr_remove(&_minor_idr, m);
1813 spin_unlock(&_minor_lock);
1817 static int next_free_minor(int *minor)
1821 r = idr_pre_get(&_minor_idr, GFP_KERNEL);
1825 spin_lock(&_minor_lock);
1827 r = idr_get_new(&_minor_idr, MINOR_ALLOCED, &m);
1831 if (m >= (1 << MINORBITS)) {
1832 idr_remove(&_minor_idr, m);
1840 spin_unlock(&_minor_lock);
1844 static const struct block_device_operations dm_blk_dops;
1846 static void dm_wq_work(struct work_struct *work);
1847 static void dm_rq_barrier_work(struct work_struct *work);
1850 * Allocate and initialise a blank device with a given minor.
1852 static struct mapped_device *alloc_dev(int minor)
1855 struct mapped_device *md = kzalloc(sizeof(*md), GFP_KERNEL);
1859 DMWARN("unable to allocate device, out of memory.");
1863 if (!try_module_get(THIS_MODULE))
1864 goto bad_module_get;
1866 /* get a minor number for the dev */
1867 if (minor == DM_ANY_MINOR)
1868 r = next_free_minor(&minor);
1870 r = specific_minor(minor);
1874 init_rwsem(&md->io_lock);
1875 mutex_init(&md->suspend_lock);
1876 spin_lock_init(&md->deferred_lock);
1877 spin_lock_init(&md->barrier_error_lock);
1878 rwlock_init(&md->map_lock);
1879 atomic_set(&md->holders, 1);
1880 atomic_set(&md->open_count, 0);
1881 atomic_set(&md->event_nr, 0);
1882 atomic_set(&md->uevent_seq, 0);
1883 INIT_LIST_HEAD(&md->uevent_list);
1884 spin_lock_init(&md->uevent_lock);
1886 md->queue = blk_init_queue(dm_request_fn, NULL);
1891 * Request-based dm devices cannot be stacked on top of bio-based dm
1892 * devices. The type of this dm device has not been decided yet,
1893 * although we initialized the queue using blk_init_queue().
1894 * The type is decided at the first table loading time.
1895 * To prevent problematic device stacking, clear the queue flag
1896 * for request stacking support until then.
1898 * This queue is new, so no concurrency on the queue_flags.
1900 queue_flag_clear_unlocked(QUEUE_FLAG_STACKABLE, md->queue);
1901 md->saved_make_request_fn = md->queue->make_request_fn;
1902 md->queue->queuedata = md;
1903 md->queue->backing_dev_info.congested_fn = dm_any_congested;
1904 md->queue->backing_dev_info.congested_data = md;
1905 blk_queue_make_request(md->queue, dm_request);
1906 blk_queue_bounce_limit(md->queue, BLK_BOUNCE_ANY);
1907 md->queue->unplug_fn = dm_unplug_all;
1908 blk_queue_merge_bvec(md->queue, dm_merge_bvec);
1909 blk_queue_softirq_done(md->queue, dm_softirq_done);
1910 blk_queue_prep_rq(md->queue, dm_prep_fn);
1911 blk_queue_lld_busy(md->queue, dm_lld_busy);
1912 blk_queue_ordered(md->queue, QUEUE_ORDERED_DRAIN_FLUSH);
1914 md->disk = alloc_disk(1);
1918 atomic_set(&md->pending[0], 0);
1919 atomic_set(&md->pending[1], 0);
1920 init_waitqueue_head(&md->wait);
1921 INIT_WORK(&md->work, dm_wq_work);
1922 INIT_WORK(&md->barrier_work, dm_rq_barrier_work);
1923 init_waitqueue_head(&md->eventq);
1925 md->disk->major = _major;
1926 md->disk->first_minor = minor;
1927 md->disk->fops = &dm_blk_dops;
1928 md->disk->queue = md->queue;
1929 md->disk->private_data = md;
1930 sprintf(md->disk->disk_name, "dm-%d", minor);
1932 format_dev_t(md->name, MKDEV(_major, minor));
1934 md->wq = create_singlethread_workqueue("kdmflush");
1938 md->bdev = bdget_disk(md->disk, 0);
1942 /* Populate the mapping, nobody knows we exist yet */
1943 spin_lock(&_minor_lock);
1944 old_md = idr_replace(&_minor_idr, md, minor);
1945 spin_unlock(&_minor_lock);
1947 BUG_ON(old_md != MINOR_ALLOCED);
1952 destroy_workqueue(md->wq);
1954 del_gendisk(md->disk);
1957 blk_cleanup_queue(md->queue);
1961 module_put(THIS_MODULE);
1967 static void unlock_fs(struct mapped_device *md);
1969 static void free_dev(struct mapped_device *md)
1971 int minor = MINOR(disk_devt(md->disk));
1975 destroy_workqueue(md->wq);
1977 mempool_destroy(md->tio_pool);
1979 mempool_destroy(md->io_pool);
1981 bioset_free(md->bs);
1982 blk_integrity_unregister(md->disk);
1983 del_gendisk(md->disk);
1986 spin_lock(&_minor_lock);
1987 md->disk->private_data = NULL;
1988 spin_unlock(&_minor_lock);
1991 blk_cleanup_queue(md->queue);
1992 module_put(THIS_MODULE);
1996 static void __bind_mempools(struct mapped_device *md, struct dm_table *t)
1998 struct dm_md_mempools *p;
2000 if (md->io_pool && md->tio_pool && md->bs)
2001 /* the md already has necessary mempools */
2004 p = dm_table_get_md_mempools(t);
2005 BUG_ON(!p || md->io_pool || md->tio_pool || md->bs);
2007 md->io_pool = p->io_pool;
2009 md->tio_pool = p->tio_pool;
2015 /* mempool bind completed, now no need any mempools in the table */
2016 dm_table_free_md_mempools(t);
2020 * Bind a table to the device.
2022 static void event_callback(void *context)
2024 unsigned long flags;
2026 struct mapped_device *md = (struct mapped_device *) context;
2028 spin_lock_irqsave(&md->uevent_lock, flags);
2029 list_splice_init(&md->uevent_list, &uevents);
2030 spin_unlock_irqrestore(&md->uevent_lock, flags);
2032 dm_send_uevents(&uevents, &disk_to_dev(md->disk)->kobj);
2034 atomic_inc(&md->event_nr);
2035 wake_up(&md->eventq);
2038 static void __set_size(struct mapped_device *md, sector_t size)
2040 set_capacity(md->disk, size);
2042 mutex_lock(&md->bdev->bd_inode->i_mutex);
2043 i_size_write(md->bdev->bd_inode, (loff_t)size << SECTOR_SHIFT);
2044 mutex_unlock(&md->bdev->bd_inode->i_mutex);
2048 * Returns old map, which caller must destroy.
2050 static struct dm_table *__bind(struct mapped_device *md, struct dm_table *t,
2051 struct queue_limits *limits)
2053 struct dm_table *old_map;
2054 struct request_queue *q = md->queue;
2056 unsigned long flags;
2058 size = dm_table_get_size(t);
2061 * Wipe any geometry if the size of the table changed.
2063 if (size != get_capacity(md->disk))
2064 memset(&md->geometry, 0, sizeof(md->geometry));
2066 __set_size(md, size);
2068 dm_table_event_callback(t, event_callback, md);
2071 * The queue hasn't been stopped yet, if the old table type wasn't
2072 * for request-based during suspension. So stop it to prevent
2073 * I/O mapping before resume.
2074 * This must be done before setting the queue restrictions,
2075 * because request-based dm may be run just after the setting.
2077 if (dm_table_request_based(t) && !blk_queue_stopped(q))
2080 __bind_mempools(md, t);
2082 write_lock_irqsave(&md->map_lock, flags);
2085 dm_table_set_restrictions(t, q, limits);
2086 write_unlock_irqrestore(&md->map_lock, flags);
2092 * Returns unbound table for the caller to free.
2094 static struct dm_table *__unbind(struct mapped_device *md)
2096 struct dm_table *map = md->map;
2097 unsigned long flags;
2102 dm_table_event_callback(map, NULL, NULL);
2103 write_lock_irqsave(&md->map_lock, flags);
2105 write_unlock_irqrestore(&md->map_lock, flags);
2111 * Constructor for a new device.
2113 int dm_create(int minor, struct mapped_device **result)
2115 struct mapped_device *md;
2117 md = alloc_dev(minor);
2127 static struct mapped_device *dm_find_md(dev_t dev)
2129 struct mapped_device *md;
2130 unsigned minor = MINOR(dev);
2132 if (MAJOR(dev) != _major || minor >= (1 << MINORBITS))
2135 spin_lock(&_minor_lock);
2137 md = idr_find(&_minor_idr, minor);
2138 if (md && (md == MINOR_ALLOCED ||
2139 (MINOR(disk_devt(dm_disk(md))) != minor) ||
2140 dm_deleting_md(md) ||
2141 test_bit(DMF_FREEING, &md->flags))) {
2147 spin_unlock(&_minor_lock);
2152 struct mapped_device *dm_get_md(dev_t dev)
2154 struct mapped_device *md = dm_find_md(dev);
2162 void *dm_get_mdptr(struct mapped_device *md)
2164 return md->interface_ptr;
2167 void dm_set_mdptr(struct mapped_device *md, void *ptr)
2169 md->interface_ptr = ptr;
2172 void dm_get(struct mapped_device *md)
2174 atomic_inc(&md->holders);
2175 BUG_ON(test_bit(DMF_FREEING, &md->flags));
2178 const char *dm_device_name(struct mapped_device *md)
2182 EXPORT_SYMBOL_GPL(dm_device_name);
2184 static void __dm_destroy(struct mapped_device *md, bool wait)
2186 struct dm_table *map;
2190 spin_lock(&_minor_lock);
2191 map = dm_get_live_table(md);
2192 idr_replace(&_minor_idr, MINOR_ALLOCED, MINOR(disk_devt(dm_disk(md))));
2193 set_bit(DMF_FREEING, &md->flags);
2194 spin_unlock(&_minor_lock);
2196 if (!dm_suspended_md(md)) {
2197 dm_table_presuspend_targets(map);
2198 dm_table_postsuspend_targets(map);
2202 * Rare, but there may be I/O requests still going to complete,
2203 * for example. Wait for all references to disappear.
2204 * No one should increment the reference count of the mapped_device,
2205 * after the mapped_device state becomes DMF_FREEING.
2208 while (atomic_read(&md->holders))
2210 else if (atomic_read(&md->holders))
2211 DMWARN("%s: Forcibly removing mapped_device still in use! (%d users)",
2212 dm_device_name(md), atomic_read(&md->holders));
2216 dm_table_destroy(__unbind(md));
2220 void dm_destroy(struct mapped_device *md)
2222 __dm_destroy(md, true);
2225 void dm_destroy_immediate(struct mapped_device *md)
2227 __dm_destroy(md, false);
2230 void dm_put(struct mapped_device *md)
2232 atomic_dec(&md->holders);
2234 EXPORT_SYMBOL_GPL(dm_put);
2236 static int dm_wait_for_completion(struct mapped_device *md, int interruptible)
2239 DECLARE_WAITQUEUE(wait, current);
2241 dm_unplug_all(md->queue);
2243 add_wait_queue(&md->wait, &wait);
2246 set_current_state(interruptible);
2249 if (!md_in_flight(md))
2252 if (interruptible == TASK_INTERRUPTIBLE &&
2253 signal_pending(current)) {
2260 set_current_state(TASK_RUNNING);
2262 remove_wait_queue(&md->wait, &wait);
2267 static void dm_flush(struct mapped_device *md)
2269 dm_wait_for_completion(md, TASK_UNINTERRUPTIBLE);
2271 bio_init(&md->barrier_bio);
2272 md->barrier_bio.bi_bdev = md->bdev;
2273 md->barrier_bio.bi_rw = WRITE_BARRIER;
2274 __split_and_process_bio(md, &md->barrier_bio);
2276 dm_wait_for_completion(md, TASK_UNINTERRUPTIBLE);
2279 static void process_barrier(struct mapped_device *md, struct bio *bio)
2281 md->barrier_error = 0;
2285 if (!bio_empty_barrier(bio)) {
2286 __split_and_process_bio(md, bio);
2290 if (md->barrier_error != DM_ENDIO_REQUEUE)
2291 bio_endio(bio, md->barrier_error);
2293 spin_lock_irq(&md->deferred_lock);
2294 bio_list_add_head(&md->deferred, bio);
2295 spin_unlock_irq(&md->deferred_lock);
2300 * Process the deferred bios
2302 static void dm_wq_work(struct work_struct *work)
2304 struct mapped_device *md = container_of(work, struct mapped_device,
2308 down_write(&md->io_lock);
2310 while (!test_bit(DMF_BLOCK_IO_FOR_SUSPEND, &md->flags)) {
2311 spin_lock_irq(&md->deferred_lock);
2312 c = bio_list_pop(&md->deferred);
2313 spin_unlock_irq(&md->deferred_lock);
2316 clear_bit(DMF_QUEUE_IO_TO_THREAD, &md->flags);
2320 up_write(&md->io_lock);
2322 if (dm_request_based(md))
2323 generic_make_request(c);
2325 if (c->bi_rw & REQ_HARDBARRIER)
2326 process_barrier(md, c);
2328 __split_and_process_bio(md, c);
2331 down_write(&md->io_lock);
2334 up_write(&md->io_lock);
2337 static void dm_queue_flush(struct mapped_device *md)
2339 clear_bit(DMF_BLOCK_IO_FOR_SUSPEND, &md->flags);
2340 smp_mb__after_clear_bit();
2341 queue_work(md->wq, &md->work);
2344 static void dm_rq_set_flush_nr(struct request *clone, unsigned flush_nr)
2346 struct dm_rq_target_io *tio = clone->end_io_data;
2348 tio->info.flush_request = flush_nr;
2351 /* Issue barrier requests to targets and wait for their completion. */
2352 static int dm_rq_barrier(struct mapped_device *md)
2355 struct dm_table *map = dm_get_live_table(md);
2356 unsigned num_targets = dm_table_get_num_targets(map);
2357 struct dm_target *ti;
2358 struct request *clone;
2360 md->barrier_error = 0;
2362 for (i = 0; i < num_targets; i++) {
2363 ti = dm_table_get_target(map, i);
2364 for (j = 0; j < ti->num_flush_requests; j++) {
2365 clone = clone_rq(md->flush_request, md, GFP_NOIO);
2366 dm_rq_set_flush_nr(clone, j);
2367 atomic_inc(&md->pending[rq_data_dir(clone)]);
2368 map_request(ti, clone, md);
2372 dm_wait_for_completion(md, TASK_UNINTERRUPTIBLE);
2375 return md->barrier_error;
2378 static void dm_rq_barrier_work(struct work_struct *work)
2381 struct mapped_device *md = container_of(work, struct mapped_device,
2383 struct request_queue *q = md->queue;
2385 unsigned long flags;
2388 * Hold the md reference here and leave it at the last part so that
2389 * the md can't be deleted by device opener when the barrier request
2394 error = dm_rq_barrier(md);
2396 rq = md->flush_request;
2397 md->flush_request = NULL;
2399 if (error == DM_ENDIO_REQUEUE) {
2400 spin_lock_irqsave(q->queue_lock, flags);
2401 blk_requeue_request(q, rq);
2402 spin_unlock_irqrestore(q->queue_lock, flags);
2404 blk_end_request_all(rq, error);
2412 * Swap in a new table, returning the old one for the caller to destroy.
2414 struct dm_table *dm_swap_table(struct mapped_device *md, struct dm_table *table)
2416 struct dm_table *map = ERR_PTR(-EINVAL);
2417 struct queue_limits limits;
2420 mutex_lock(&md->suspend_lock);
2422 /* device must be suspended */
2423 if (!dm_suspended_md(md))
2426 r = dm_calculate_queue_limits(table, &limits);
2432 /* cannot change the device type, once a table is bound */
2434 (dm_table_get_type(md->map) != dm_table_get_type(table))) {
2435 DMWARN("can't change the device type after a table is bound");
2439 map = __bind(md, table, &limits);
2442 mutex_unlock(&md->suspend_lock);
2447 * Functions to lock and unlock any filesystem running on the
2450 static int lock_fs(struct mapped_device *md)
2454 WARN_ON(md->frozen_sb);
2456 md->frozen_sb = freeze_bdev(md->bdev);
2457 if (IS_ERR(md->frozen_sb)) {
2458 r = PTR_ERR(md->frozen_sb);
2459 md->frozen_sb = NULL;
2463 set_bit(DMF_FROZEN, &md->flags);
2468 static void unlock_fs(struct mapped_device *md)
2470 if (!test_bit(DMF_FROZEN, &md->flags))
2473 thaw_bdev(md->bdev, md->frozen_sb);
2474 md->frozen_sb = NULL;
2475 clear_bit(DMF_FROZEN, &md->flags);
2479 * We need to be able to change a mapping table under a mounted
2480 * filesystem. For example we might want to move some data in
2481 * the background. Before the table can be swapped with
2482 * dm_bind_table, dm_suspend must be called to flush any in
2483 * flight bios and ensure that any further io gets deferred.
2486 * Suspend mechanism in request-based dm.
2488 * 1. Flush all I/Os by lock_fs() if needed.
2489 * 2. Stop dispatching any I/O by stopping the request_queue.
2490 * 3. Wait for all in-flight I/Os to be completed or requeued.
2492 * To abort suspend, start the request_queue.
2494 int dm_suspend(struct mapped_device *md, unsigned suspend_flags)
2496 struct dm_table *map = NULL;
2498 int do_lockfs = suspend_flags & DM_SUSPEND_LOCKFS_FLAG ? 1 : 0;
2499 int noflush = suspend_flags & DM_SUSPEND_NOFLUSH_FLAG ? 1 : 0;
2501 mutex_lock(&md->suspend_lock);
2503 if (dm_suspended_md(md)) {
2508 map = dm_get_live_table(md);
2511 * DMF_NOFLUSH_SUSPENDING must be set before presuspend.
2512 * This flag is cleared before dm_suspend returns.
2515 set_bit(DMF_NOFLUSH_SUSPENDING, &md->flags);
2517 /* This does not get reverted if there's an error later. */
2518 dm_table_presuspend_targets(map);
2521 * Flush I/O to the device.
2522 * Any I/O submitted after lock_fs() may not be flushed.
2523 * noflush takes precedence over do_lockfs.
2524 * (lock_fs() flushes I/Os and waits for them to complete.)
2526 if (!noflush && do_lockfs) {
2533 * Here we must make sure that no processes are submitting requests
2534 * to target drivers i.e. no one may be executing
2535 * __split_and_process_bio. This is called from dm_request and
2538 * To get all processes out of __split_and_process_bio in dm_request,
2539 * we take the write lock. To prevent any process from reentering
2540 * __split_and_process_bio from dm_request, we set
2541 * DMF_QUEUE_IO_TO_THREAD.
2543 * To quiesce the thread (dm_wq_work), we set DMF_BLOCK_IO_FOR_SUSPEND
2544 * and call flush_workqueue(md->wq). flush_workqueue will wait until
2545 * dm_wq_work exits and DMF_BLOCK_IO_FOR_SUSPEND will prevent any
2546 * further calls to __split_and_process_bio from dm_wq_work.
2548 down_write(&md->io_lock);
2549 set_bit(DMF_BLOCK_IO_FOR_SUSPEND, &md->flags);
2550 set_bit(DMF_QUEUE_IO_TO_THREAD, &md->flags);
2551 up_write(&md->io_lock);
2554 * Request-based dm uses md->wq for barrier (dm_rq_barrier_work) which
2555 * can be kicked until md->queue is stopped. So stop md->queue before
2558 if (dm_request_based(md))
2559 stop_queue(md->queue);
2561 flush_workqueue(md->wq);
2564 * At this point no more requests are entering target request routines.
2565 * We call dm_wait_for_completion to wait for all existing requests
2568 r = dm_wait_for_completion(md, TASK_INTERRUPTIBLE);
2570 down_write(&md->io_lock);
2572 clear_bit(DMF_NOFLUSH_SUSPENDING, &md->flags);
2573 up_write(&md->io_lock);
2575 /* were we interrupted ? */
2579 if (dm_request_based(md))
2580 start_queue(md->queue);
2583 goto out; /* pushback list is already flushed, so skip flush */
2587 * If dm_wait_for_completion returned 0, the device is completely
2588 * quiescent now. There is no request-processing activity. All new
2589 * requests are being added to md->deferred list.
2592 set_bit(DMF_SUSPENDED, &md->flags);
2594 dm_table_postsuspend_targets(map);
2600 mutex_unlock(&md->suspend_lock);
2604 int dm_resume(struct mapped_device *md)
2607 struct dm_table *map = NULL;
2609 mutex_lock(&md->suspend_lock);
2610 if (!dm_suspended_md(md))
2613 map = dm_get_live_table(md);
2614 if (!map || !dm_table_get_size(map))
2617 r = dm_table_resume_targets(map);
2624 * Flushing deferred I/Os must be done after targets are resumed
2625 * so that mapping of targets can work correctly.
2626 * Request-based dm is queueing the deferred I/Os in its request_queue.
2628 if (dm_request_based(md))
2629 start_queue(md->queue);
2633 clear_bit(DMF_SUSPENDED, &md->flags);
2635 dm_table_unplug_all(map);
2639 mutex_unlock(&md->suspend_lock);
2644 /*-----------------------------------------------------------------
2645 * Event notification.
2646 *---------------------------------------------------------------*/
2647 int dm_kobject_uevent(struct mapped_device *md, enum kobject_action action,
2650 char udev_cookie[DM_COOKIE_LENGTH];
2651 char *envp[] = { udev_cookie, NULL };
2654 return kobject_uevent(&disk_to_dev(md->disk)->kobj, action);
2656 snprintf(udev_cookie, DM_COOKIE_LENGTH, "%s=%u",
2657 DM_COOKIE_ENV_VAR_NAME, cookie);
2658 return kobject_uevent_env(&disk_to_dev(md->disk)->kobj,
2663 uint32_t dm_next_uevent_seq(struct mapped_device *md)
2665 return atomic_add_return(1, &md->uevent_seq);
2668 uint32_t dm_get_event_nr(struct mapped_device *md)
2670 return atomic_read(&md->event_nr);
2673 int dm_wait_event(struct mapped_device *md, int event_nr)
2675 return wait_event_interruptible(md->eventq,
2676 (event_nr != atomic_read(&md->event_nr)));
2679 void dm_uevent_add(struct mapped_device *md, struct list_head *elist)
2681 unsigned long flags;
2683 spin_lock_irqsave(&md->uevent_lock, flags);
2684 list_add(elist, &md->uevent_list);
2685 spin_unlock_irqrestore(&md->uevent_lock, flags);
2689 * The gendisk is only valid as long as you have a reference
2692 struct gendisk *dm_disk(struct mapped_device *md)
2697 struct kobject *dm_kobject(struct mapped_device *md)
2703 * struct mapped_device should not be exported outside of dm.c
2704 * so use this check to verify that kobj is part of md structure
2706 struct mapped_device *dm_get_from_kobject(struct kobject *kobj)
2708 struct mapped_device *md;
2710 md = container_of(kobj, struct mapped_device, kobj);
2711 if (&md->kobj != kobj)
2714 if (test_bit(DMF_FREEING, &md->flags) ||
2722 int dm_suspended_md(struct mapped_device *md)
2724 return test_bit(DMF_SUSPENDED, &md->flags);
2727 int dm_suspended(struct dm_target *ti)
2729 return dm_suspended_md(dm_table_get_md(ti->table));
2731 EXPORT_SYMBOL_GPL(dm_suspended);
2733 int dm_noflush_suspending(struct dm_target *ti)
2735 return __noflush_suspending(dm_table_get_md(ti->table));
2737 EXPORT_SYMBOL_GPL(dm_noflush_suspending);
2739 struct dm_md_mempools *dm_alloc_md_mempools(unsigned type)
2741 struct dm_md_mempools *pools = kmalloc(sizeof(*pools), GFP_KERNEL);
2746 pools->io_pool = (type == DM_TYPE_BIO_BASED) ?
2747 mempool_create_slab_pool(MIN_IOS, _io_cache) :
2748 mempool_create_slab_pool(MIN_IOS, _rq_bio_info_cache);
2749 if (!pools->io_pool)
2750 goto free_pools_and_out;
2752 pools->tio_pool = (type == DM_TYPE_BIO_BASED) ?
2753 mempool_create_slab_pool(MIN_IOS, _tio_cache) :
2754 mempool_create_slab_pool(MIN_IOS, _rq_tio_cache);
2755 if (!pools->tio_pool)
2756 goto free_io_pool_and_out;
2758 pools->bs = (type == DM_TYPE_BIO_BASED) ?
2759 bioset_create(16, 0) : bioset_create(MIN_IOS, 0);
2761 goto free_tio_pool_and_out;
2765 free_tio_pool_and_out:
2766 mempool_destroy(pools->tio_pool);
2768 free_io_pool_and_out:
2769 mempool_destroy(pools->io_pool);
2777 void dm_free_md_mempools(struct dm_md_mempools *pools)
2783 mempool_destroy(pools->io_pool);
2785 if (pools->tio_pool)
2786 mempool_destroy(pools->tio_pool);
2789 bioset_free(pools->bs);
2794 static const struct block_device_operations dm_blk_dops = {
2795 .open = dm_blk_open,
2796 .release = dm_blk_close,
2797 .ioctl = dm_blk_ioctl,
2798 .getgeo = dm_blk_getgeo,
2799 .owner = THIS_MODULE
2802 EXPORT_SYMBOL(dm_get_mapinfo);
2807 module_init(dm_init);
2808 module_exit(dm_exit);
2810 module_param(major, uint, 0);
2811 MODULE_PARM_DESC(major, "The major number of the device mapper");
2812 MODULE_DESCRIPTION(DM_NAME " driver");
2813 MODULE_AUTHOR("Joe Thornber <dm-devel@redhat.com>");
2814 MODULE_LICENSE("GPL");