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/mempool.h>
18 #include <linux/slab.h>
19 #include <linux/idr.h>
20 #include <linux/hdreg.h>
21 #include <linux/delay.h>
23 #include <trace/events/block.h>
25 #define DM_MSG_PREFIX "core"
29 * ratelimit state to be used in DMXXX_LIMIT().
31 DEFINE_RATELIMIT_STATE(dm_ratelimit_state,
32 DEFAULT_RATELIMIT_INTERVAL,
33 DEFAULT_RATELIMIT_BURST);
34 EXPORT_SYMBOL(dm_ratelimit_state);
38 * Cookies are numeric values sent with CHANGE and REMOVE
39 * uevents while resuming, removing or renaming the device.
41 #define DM_COOKIE_ENV_VAR_NAME "DM_COOKIE"
42 #define DM_COOKIE_LENGTH 24
44 static const char *_name = DM_NAME;
46 static unsigned int major = 0;
47 static unsigned int _major = 0;
49 static DEFINE_IDR(_minor_idr);
51 static DEFINE_SPINLOCK(_minor_lock);
53 static void do_deferred_remove(struct work_struct *w);
55 static DECLARE_WORK(deferred_remove_work, do_deferred_remove);
59 * One of these is allocated per bio.
62 struct mapped_device *md;
66 unsigned long start_time;
67 spinlock_t endio_lock;
68 struct dm_stats_aux stats_aux;
72 * For request-based dm.
73 * One of these is allocated per request.
75 struct dm_rq_target_io {
76 struct mapped_device *md;
78 struct request *orig, clone;
84 * For request-based dm - the bio clones we allocate are embedded in these
87 * We allocate these with bio_alloc_bioset, using the front_pad parameter when
88 * the bioset is created - this means the bio has to come at the end of the
91 struct dm_rq_clone_bio_info {
93 struct dm_rq_target_io *tio;
97 union map_info *dm_get_mapinfo(struct bio *bio)
99 if (bio && bio->bi_private)
100 return &((struct dm_target_io *)bio->bi_private)->info;
104 union map_info *dm_get_rq_mapinfo(struct request *rq)
106 if (rq && rq->end_io_data)
107 return &((struct dm_rq_target_io *)rq->end_io_data)->info;
110 EXPORT_SYMBOL_GPL(dm_get_rq_mapinfo);
112 #define MINOR_ALLOCED ((void *)-1)
115 * Bits for the md->flags field.
117 #define DMF_BLOCK_IO_FOR_SUSPEND 0
118 #define DMF_SUSPENDED 1
120 #define DMF_FREEING 3
121 #define DMF_DELETING 4
122 #define DMF_NOFLUSH_SUSPENDING 5
123 #define DMF_MERGE_IS_OPTIONAL 6
124 #define DMF_DEFERRED_REMOVE 7
127 * A dummy definition to make RCU happy.
128 * struct dm_table should never be dereferenced in this file.
135 * Work processed by per-device workqueue.
137 struct mapped_device {
138 struct srcu_struct io_barrier;
139 struct mutex suspend_lock;
144 * The current mapping.
145 * Use dm_get_live_table{_fast} or take suspend_lock for
148 struct dm_table *map;
152 struct request_queue *queue;
154 /* Protect queue and type against concurrent access. */
155 struct mutex type_lock;
157 struct target_type *immutable_target_type;
159 struct gendisk *disk;
165 * A list of ios that arrived while we were suspended.
168 wait_queue_head_t wait;
169 struct work_struct work;
170 struct bio_list deferred;
171 spinlock_t deferred_lock;
174 * Processing queue (flush)
176 struct workqueue_struct *wq;
179 * io objects are allocated from here.
189 wait_queue_head_t eventq;
191 struct list_head uevent_list;
192 spinlock_t uevent_lock; /* Protect access to uevent_list */
195 * freeze/thaw support require holding onto a super block
197 struct super_block *frozen_sb;
198 struct block_device *bdev;
200 /* forced geometry settings */
201 struct hd_geometry geometry;
206 /* wait until the kobject is released */
207 struct completion kobj_completion;
209 /* zero-length flush that will be cloned and submitted to targets */
210 struct bio flush_bio;
212 struct dm_stats stats;
216 * For mempools pre-allocation at the table loading time.
218 struct dm_md_mempools {
223 #define RESERVED_BIO_BASED_IOS 16
224 #define RESERVED_REQUEST_BASED_IOS 256
225 #define RESERVED_MAX_IOS 1024
226 static struct kmem_cache *_io_cache;
227 static struct kmem_cache *_rq_tio_cache;
230 * Bio-based DM's mempools' reserved IOs set by the user.
232 static unsigned reserved_bio_based_ios = RESERVED_BIO_BASED_IOS;
235 * Request-based DM's mempools' reserved IOs set by the user.
237 static unsigned reserved_rq_based_ios = RESERVED_REQUEST_BASED_IOS;
239 static unsigned __dm_get_reserved_ios(unsigned *reserved_ios,
240 unsigned def, unsigned max)
242 unsigned ios = ACCESS_ONCE(*reserved_ios);
243 unsigned modified_ios = 0;
251 (void)cmpxchg(reserved_ios, ios, modified_ios);
258 unsigned dm_get_reserved_bio_based_ios(void)
260 return __dm_get_reserved_ios(&reserved_bio_based_ios,
261 RESERVED_BIO_BASED_IOS, RESERVED_MAX_IOS);
263 EXPORT_SYMBOL_GPL(dm_get_reserved_bio_based_ios);
265 unsigned dm_get_reserved_rq_based_ios(void)
267 return __dm_get_reserved_ios(&reserved_rq_based_ios,
268 RESERVED_REQUEST_BASED_IOS, RESERVED_MAX_IOS);
270 EXPORT_SYMBOL_GPL(dm_get_reserved_rq_based_ios);
272 static int __init local_init(void)
276 /* allocate a slab for the dm_ios */
277 _io_cache = KMEM_CACHE(dm_io, 0);
281 _rq_tio_cache = KMEM_CACHE(dm_rq_target_io, 0);
283 goto out_free_io_cache;
285 r = dm_uevent_init();
287 goto out_free_rq_tio_cache;
290 r = register_blkdev(_major, _name);
292 goto out_uevent_exit;
301 out_free_rq_tio_cache:
302 kmem_cache_destroy(_rq_tio_cache);
304 kmem_cache_destroy(_io_cache);
309 static void local_exit(void)
311 flush_scheduled_work();
313 kmem_cache_destroy(_rq_tio_cache);
314 kmem_cache_destroy(_io_cache);
315 unregister_blkdev(_major, _name);
320 DMINFO("cleaned up");
323 static int (*_inits[])(void) __initdata = {
334 static void (*_exits[])(void) = {
345 static int __init dm_init(void)
347 const int count = ARRAY_SIZE(_inits);
351 for (i = 0; i < count; i++) {
366 static void __exit dm_exit(void)
368 int i = ARRAY_SIZE(_exits);
374 * Should be empty by this point.
376 idr_destroy(&_minor_idr);
380 * Block device functions
382 int dm_deleting_md(struct mapped_device *md)
384 return test_bit(DMF_DELETING, &md->flags);
387 static int dm_blk_open(struct block_device *bdev, fmode_t mode)
389 struct mapped_device *md;
391 spin_lock(&_minor_lock);
393 md = bdev->bd_disk->private_data;
397 if (test_bit(DMF_FREEING, &md->flags) ||
398 dm_deleting_md(md)) {
404 atomic_inc(&md->open_count);
407 spin_unlock(&_minor_lock);
409 return md ? 0 : -ENXIO;
412 static void dm_blk_close(struct gendisk *disk, fmode_t mode)
414 struct mapped_device *md = disk->private_data;
416 spin_lock(&_minor_lock);
418 if (atomic_dec_and_test(&md->open_count) &&
419 (test_bit(DMF_DEFERRED_REMOVE, &md->flags)))
420 schedule_work(&deferred_remove_work);
424 spin_unlock(&_minor_lock);
427 int dm_open_count(struct mapped_device *md)
429 return atomic_read(&md->open_count);
433 * Guarantees nothing is using the device before it's deleted.
435 int dm_lock_for_deletion(struct mapped_device *md, bool mark_deferred, bool only_deferred)
439 spin_lock(&_minor_lock);
441 if (dm_open_count(md)) {
444 set_bit(DMF_DEFERRED_REMOVE, &md->flags);
445 } else if (only_deferred && !test_bit(DMF_DEFERRED_REMOVE, &md->flags))
448 set_bit(DMF_DELETING, &md->flags);
450 spin_unlock(&_minor_lock);
455 int dm_cancel_deferred_remove(struct mapped_device *md)
459 spin_lock(&_minor_lock);
461 if (test_bit(DMF_DELETING, &md->flags))
464 clear_bit(DMF_DEFERRED_REMOVE, &md->flags);
466 spin_unlock(&_minor_lock);
471 static void do_deferred_remove(struct work_struct *w)
473 dm_deferred_remove();
476 sector_t dm_get_size(struct mapped_device *md)
478 return get_capacity(md->disk);
481 struct dm_stats *dm_get_stats(struct mapped_device *md)
486 static int dm_blk_getgeo(struct block_device *bdev, struct hd_geometry *geo)
488 struct mapped_device *md = bdev->bd_disk->private_data;
490 return dm_get_geometry(md, geo);
493 static int dm_blk_ioctl(struct block_device *bdev, fmode_t mode,
494 unsigned int cmd, unsigned long arg)
496 struct mapped_device *md = bdev->bd_disk->private_data;
498 struct dm_table *map;
499 struct dm_target *tgt;
503 map = dm_get_live_table(md, &srcu_idx);
505 if (!map || !dm_table_get_size(map))
508 /* We only support devices that have a single target */
509 if (dm_table_get_num_targets(map) != 1)
512 tgt = dm_table_get_target(map, 0);
514 if (dm_suspended_md(md)) {
519 if (tgt->type->ioctl)
520 r = tgt->type->ioctl(tgt, cmd, arg);
523 dm_put_live_table(md, srcu_idx);
525 if (r == -ENOTCONN) {
533 static struct dm_io *alloc_io(struct mapped_device *md)
535 return mempool_alloc(md->io_pool, GFP_NOIO);
538 static void free_io(struct mapped_device *md, struct dm_io *io)
540 mempool_free(io, md->io_pool);
543 static void free_tio(struct mapped_device *md, struct dm_target_io *tio)
545 bio_put(&tio->clone);
548 static struct dm_rq_target_io *alloc_rq_tio(struct mapped_device *md,
551 return mempool_alloc(md->io_pool, gfp_mask);
554 static void free_rq_tio(struct dm_rq_target_io *tio)
556 mempool_free(tio, tio->md->io_pool);
559 static int md_in_flight(struct mapped_device *md)
561 return atomic_read(&md->pending[READ]) +
562 atomic_read(&md->pending[WRITE]);
565 static void start_io_acct(struct dm_io *io)
567 struct mapped_device *md = io->md;
568 struct bio *bio = io->bio;
570 int rw = bio_data_dir(bio);
572 io->start_time = jiffies;
574 cpu = part_stat_lock();
575 part_round_stats(cpu, &dm_disk(md)->part0);
577 atomic_set(&dm_disk(md)->part0.in_flight[rw],
578 atomic_inc_return(&md->pending[rw]));
580 if (unlikely(dm_stats_used(&md->stats)))
581 dm_stats_account_io(&md->stats, bio->bi_rw, bio->bi_sector,
582 bio_sectors(bio), false, 0, &io->stats_aux);
585 static void end_io_acct(struct dm_io *io)
587 struct mapped_device *md = io->md;
588 struct bio *bio = io->bio;
589 unsigned long duration = jiffies - io->start_time;
591 int rw = bio_data_dir(bio);
593 cpu = part_stat_lock();
594 part_round_stats(cpu, &dm_disk(md)->part0);
595 part_stat_add(cpu, &dm_disk(md)->part0, ticks[rw], duration);
598 if (unlikely(dm_stats_used(&md->stats)))
599 dm_stats_account_io(&md->stats, bio->bi_rw, bio->bi_sector,
600 bio_sectors(bio), true, duration, &io->stats_aux);
603 * After this is decremented the bio must not be touched if it is
606 pending = atomic_dec_return(&md->pending[rw]);
607 atomic_set(&dm_disk(md)->part0.in_flight[rw], pending);
608 pending += atomic_read(&md->pending[rw^0x1]);
610 /* nudge anyone waiting on suspend queue */
616 * Add the bio to the list of deferred io.
618 static void queue_io(struct mapped_device *md, struct bio *bio)
622 spin_lock_irqsave(&md->deferred_lock, flags);
623 bio_list_add(&md->deferred, bio);
624 spin_unlock_irqrestore(&md->deferred_lock, flags);
625 queue_work(md->wq, &md->work);
629 * Everyone (including functions in this file), should use this
630 * function to access the md->map field, and make sure they call
631 * dm_put_live_table() when finished.
633 struct dm_table *dm_get_live_table(struct mapped_device *md, int *srcu_idx) __acquires(md->io_barrier)
635 *srcu_idx = srcu_read_lock(&md->io_barrier);
637 return srcu_dereference(md->map, &md->io_barrier);
640 void dm_put_live_table(struct mapped_device *md, int srcu_idx) __releases(md->io_barrier)
642 srcu_read_unlock(&md->io_barrier, srcu_idx);
645 void dm_sync_table(struct mapped_device *md)
647 synchronize_srcu(&md->io_barrier);
648 synchronize_rcu_expedited();
652 * A fast alternative to dm_get_live_table/dm_put_live_table.
653 * The caller must not block between these two functions.
655 static struct dm_table *dm_get_live_table_fast(struct mapped_device *md) __acquires(RCU)
658 return rcu_dereference(md->map);
661 static void dm_put_live_table_fast(struct mapped_device *md) __releases(RCU)
667 * Get the geometry associated with a dm device
669 int dm_get_geometry(struct mapped_device *md, struct hd_geometry *geo)
677 * Set the geometry of a device.
679 int dm_set_geometry(struct mapped_device *md, struct hd_geometry *geo)
681 sector_t sz = (sector_t)geo->cylinders * geo->heads * geo->sectors;
683 if (geo->start > sz) {
684 DMWARN("Start sector is beyond the geometry limits.");
693 /*-----------------------------------------------------------------
695 * A more elegant soln is in the works that uses the queue
696 * merge fn, unfortunately there are a couple of changes to
697 * the block layer that I want to make for this. So in the
698 * interests of getting something for people to use I give
699 * you this clearly demarcated crap.
700 *---------------------------------------------------------------*/
702 static int __noflush_suspending(struct mapped_device *md)
704 return test_bit(DMF_NOFLUSH_SUSPENDING, &md->flags);
708 * Decrements the number of outstanding ios that a bio has been
709 * cloned into, completing the original io if necc.
711 static void dec_pending(struct dm_io *io, int error)
716 struct mapped_device *md = io->md;
718 /* Push-back supersedes any I/O errors */
719 if (unlikely(error)) {
720 spin_lock_irqsave(&io->endio_lock, flags);
721 if (!(io->error > 0 && __noflush_suspending(md)))
723 spin_unlock_irqrestore(&io->endio_lock, flags);
726 if (atomic_dec_and_test(&io->io_count)) {
727 if (io->error == DM_ENDIO_REQUEUE) {
729 * Target requested pushing back the I/O.
731 spin_lock_irqsave(&md->deferred_lock, flags);
732 if (__noflush_suspending(md))
733 bio_list_add_head(&md->deferred, io->bio);
735 /* noflush suspend was interrupted. */
737 spin_unlock_irqrestore(&md->deferred_lock, flags);
740 io_error = io->error;
745 if (io_error == DM_ENDIO_REQUEUE)
748 if ((bio->bi_rw & REQ_FLUSH) && bio->bi_size) {
750 * Preflush done for flush with data, reissue
753 bio->bi_rw &= ~REQ_FLUSH;
756 /* done with normal IO or empty flush */
757 trace_block_bio_complete(md->queue, bio, io_error);
758 bio_endio(bio, io_error);
763 static void clone_endio(struct bio *bio, int error)
766 struct dm_target_io *tio = bio->bi_private;
767 struct dm_io *io = tio->io;
768 struct mapped_device *md = tio->io->md;
769 dm_endio_fn endio = tio->ti->type->end_io;
771 if (!bio_flagged(bio, BIO_UPTODATE) && !error)
775 r = endio(tio->ti, bio, error);
776 if (r < 0 || r == DM_ENDIO_REQUEUE)
778 * error and requeue request are handled
782 else if (r == DM_ENDIO_INCOMPLETE)
783 /* The target will handle the io */
786 DMWARN("unimplemented target endio return value: %d", r);
792 dec_pending(io, error);
796 * Partial completion handling for request-based dm
798 static void end_clone_bio(struct bio *clone, int error)
800 struct dm_rq_clone_bio_info *info = clone->bi_private;
801 struct dm_rq_target_io *tio = info->tio;
802 struct bio *bio = info->orig;
803 unsigned int nr_bytes = info->orig->bi_size;
809 * An error has already been detected on the request.
810 * Once error occurred, just let clone->end_io() handle
816 * Don't notice the error to the upper layer yet.
817 * The error handling decision is made by the target driver,
818 * when the request is completed.
825 * I/O for the bio successfully completed.
826 * Notice the data completion to the upper layer.
830 * bios are processed from the head of the list.
831 * So the completing bio should always be rq->bio.
832 * If it's not, something wrong is happening.
834 if (tio->orig->bio != bio)
835 DMERR("bio completion is going in the middle of the request");
838 * Update the original request.
839 * Do not use blk_end_request() here, because it may complete
840 * the original request before the clone, and break the ordering.
842 blk_update_request(tio->orig, 0, nr_bytes);
846 * Don't touch any member of the md after calling this function because
847 * the md may be freed in dm_put() at the end of this function.
848 * Or do dm_get() before calling this function and dm_put() later.
850 static void rq_completed(struct mapped_device *md, int rw, int run_queue)
852 atomic_dec(&md->pending[rw]);
854 /* nudge anyone waiting on suspend queue */
855 if (!md_in_flight(md))
859 * Run this off this callpath, as drivers could invoke end_io while
860 * inside their request_fn (and holding the queue lock). Calling
861 * back into ->request_fn() could deadlock attempting to grab the
865 blk_run_queue_async(md->queue);
868 * dm_put() must be at the end of this function. See the comment above
873 static void free_rq_clone(struct request *clone)
875 struct dm_rq_target_io *tio = clone->end_io_data;
877 blk_rq_unprep_clone(clone);
882 * Complete the clone and the original request.
883 * Must be called without queue lock.
885 static void dm_end_request(struct request *clone, int error)
887 int rw = rq_data_dir(clone);
888 struct dm_rq_target_io *tio = clone->end_io_data;
889 struct mapped_device *md = tio->md;
890 struct request *rq = tio->orig;
892 if (rq->cmd_type == REQ_TYPE_BLOCK_PC) {
893 rq->errors = clone->errors;
894 rq->resid_len = clone->resid_len;
898 * We are using the sense buffer of the original
900 * So setting the length of the sense data is enough.
902 rq->sense_len = clone->sense_len;
905 free_rq_clone(clone);
906 blk_end_request_all(rq, error);
907 rq_completed(md, rw, true);
910 static void dm_unprep_request(struct request *rq)
912 struct request *clone = rq->special;
915 rq->cmd_flags &= ~REQ_DONTPREP;
917 free_rq_clone(clone);
921 * Requeue the original request of a clone.
923 void dm_requeue_unmapped_request(struct request *clone)
925 int rw = rq_data_dir(clone);
926 struct dm_rq_target_io *tio = clone->end_io_data;
927 struct mapped_device *md = tio->md;
928 struct request *rq = tio->orig;
929 struct request_queue *q = rq->q;
932 dm_unprep_request(rq);
934 spin_lock_irqsave(q->queue_lock, flags);
935 blk_requeue_request(q, rq);
936 spin_unlock_irqrestore(q->queue_lock, flags);
938 rq_completed(md, rw, 0);
940 EXPORT_SYMBOL_GPL(dm_requeue_unmapped_request);
942 static void __stop_queue(struct request_queue *q)
947 static void stop_queue(struct request_queue *q)
951 spin_lock_irqsave(q->queue_lock, flags);
953 spin_unlock_irqrestore(q->queue_lock, flags);
956 static void __start_queue(struct request_queue *q)
958 if (blk_queue_stopped(q))
962 static void start_queue(struct request_queue *q)
966 spin_lock_irqsave(q->queue_lock, flags);
968 spin_unlock_irqrestore(q->queue_lock, flags);
971 static void dm_done(struct request *clone, int error, bool mapped)
974 struct dm_rq_target_io *tio = clone->end_io_data;
975 dm_request_endio_fn rq_end_io = NULL;
978 rq_end_io = tio->ti->type->rq_end_io;
980 if (mapped && rq_end_io)
981 r = rq_end_io(tio->ti, clone, error, &tio->info);
985 /* The target wants to complete the I/O */
986 dm_end_request(clone, r);
987 else if (r == DM_ENDIO_INCOMPLETE)
988 /* The target will handle the I/O */
990 else if (r == DM_ENDIO_REQUEUE)
991 /* The target wants to requeue the I/O */
992 dm_requeue_unmapped_request(clone);
994 DMWARN("unimplemented target endio return value: %d", r);
1000 * Request completion handler for request-based dm
1002 static void dm_softirq_done(struct request *rq)
1005 struct request *clone = rq->completion_data;
1006 struct dm_rq_target_io *tio = clone->end_io_data;
1008 if (rq->cmd_flags & REQ_FAILED)
1011 dm_done(clone, tio->error, mapped);
1015 * Complete the clone and the original request with the error status
1016 * through softirq context.
1018 static void dm_complete_request(struct request *clone, int error)
1020 struct dm_rq_target_io *tio = clone->end_io_data;
1021 struct request *rq = tio->orig;
1024 rq->completion_data = clone;
1025 blk_complete_request(rq);
1029 * Complete the not-mapped clone and the original request with the error status
1030 * through softirq context.
1031 * Target's rq_end_io() function isn't called.
1032 * This may be used when the target's map_rq() function fails.
1034 void dm_kill_unmapped_request(struct request *clone, int error)
1036 struct dm_rq_target_io *tio = clone->end_io_data;
1037 struct request *rq = tio->orig;
1039 rq->cmd_flags |= REQ_FAILED;
1040 dm_complete_request(clone, error);
1042 EXPORT_SYMBOL_GPL(dm_kill_unmapped_request);
1045 * Called with the queue lock held
1047 static void end_clone_request(struct request *clone, int error)
1050 * For just cleaning up the information of the queue in which
1051 * the clone was dispatched.
1052 * The clone is *NOT* freed actually here because it is alloced from
1053 * dm own mempool and REQ_ALLOCED isn't set in clone->cmd_flags.
1055 __blk_put_request(clone->q, clone);
1058 * Actual request completion is done in a softirq context which doesn't
1059 * hold the queue lock. Otherwise, deadlock could occur because:
1060 * - another request may be submitted by the upper level driver
1061 * of the stacking during the completion
1062 * - the submission which requires queue lock may be done
1063 * against this queue
1065 dm_complete_request(clone, error);
1069 * Return maximum size of I/O possible at the supplied sector up to the current
1072 static sector_t max_io_len_target_boundary(sector_t sector, struct dm_target *ti)
1074 sector_t target_offset = dm_target_offset(ti, sector);
1076 return ti->len - target_offset;
1079 static sector_t max_io_len(sector_t sector, struct dm_target *ti)
1081 sector_t len = max_io_len_target_boundary(sector, ti);
1082 sector_t offset, max_len;
1085 * Does the target need to split even further?
1087 if (ti->max_io_len) {
1088 offset = dm_target_offset(ti, sector);
1089 if (unlikely(ti->max_io_len & (ti->max_io_len - 1)))
1090 max_len = sector_div(offset, ti->max_io_len);
1092 max_len = offset & (ti->max_io_len - 1);
1093 max_len = ti->max_io_len - max_len;
1102 int dm_set_target_max_io_len(struct dm_target *ti, sector_t len)
1104 if (len > UINT_MAX) {
1105 DMERR("Specified maximum size of target IO (%llu) exceeds limit (%u)",
1106 (unsigned long long)len, UINT_MAX);
1107 ti->error = "Maximum size of target IO is too large";
1111 ti->max_io_len = (uint32_t) len;
1115 EXPORT_SYMBOL_GPL(dm_set_target_max_io_len);
1117 static void __map_bio(struct dm_target_io *tio)
1121 struct mapped_device *md;
1122 struct bio *clone = &tio->clone;
1123 struct dm_target *ti = tio->ti;
1125 clone->bi_end_io = clone_endio;
1126 clone->bi_private = tio;
1129 * Map the clone. If r == 0 we don't need to do
1130 * anything, the target has assumed ownership of
1133 atomic_inc(&tio->io->io_count);
1134 sector = clone->bi_sector;
1135 r = ti->type->map(ti, clone);
1136 if (r == DM_MAPIO_REMAPPED) {
1137 /* the bio has been remapped so dispatch it */
1139 trace_block_bio_remap(bdev_get_queue(clone->bi_bdev), clone,
1140 tio->io->bio->bi_bdev->bd_dev, sector);
1142 generic_make_request(clone);
1143 } else if (r < 0 || r == DM_MAPIO_REQUEUE) {
1144 /* error the io and bail out, or requeue it if needed */
1146 dec_pending(tio->io, r);
1149 DMWARN("unimplemented target map return value: %d", r);
1155 struct mapped_device *md;
1156 struct dm_table *map;
1160 sector_t sector_count;
1164 static void bio_setup_sector(struct bio *bio, sector_t sector, sector_t len)
1166 bio->bi_sector = sector;
1167 bio->bi_size = to_bytes(len);
1170 static void bio_setup_bv(struct bio *bio, unsigned short idx, unsigned short bv_count)
1173 bio->bi_vcnt = idx + bv_count;
1174 bio->bi_flags &= ~(1 << BIO_SEG_VALID);
1177 static void clone_bio_integrity(struct bio *bio, struct bio *clone,
1178 unsigned short idx, unsigned len, unsigned offset,
1181 if (!bio_integrity(bio))
1184 bio_integrity_clone(clone, bio, GFP_NOIO);
1187 bio_integrity_trim(clone, bio_sector_offset(bio, idx, offset), len);
1191 * Creates a little bio that just does part of a bvec.
1193 static void clone_split_bio(struct dm_target_io *tio, struct bio *bio,
1194 sector_t sector, unsigned short idx,
1195 unsigned offset, unsigned len)
1197 struct bio *clone = &tio->clone;
1198 struct bio_vec *bv = bio->bi_io_vec + idx;
1200 *clone->bi_io_vec = *bv;
1202 bio_setup_sector(clone, sector, len);
1204 clone->bi_bdev = bio->bi_bdev;
1205 clone->bi_rw = bio->bi_rw;
1207 clone->bi_io_vec->bv_offset = offset;
1208 clone->bi_io_vec->bv_len = clone->bi_size;
1209 clone->bi_flags |= 1 << BIO_CLONED;
1211 clone_bio_integrity(bio, clone, idx, len, offset, 1);
1215 * Creates a bio that consists of range of complete bvecs.
1217 static void clone_bio(struct dm_target_io *tio, struct bio *bio,
1218 sector_t sector, unsigned short idx,
1219 unsigned short bv_count, unsigned len)
1221 struct bio *clone = &tio->clone;
1224 __bio_clone(clone, bio);
1225 bio_setup_sector(clone, sector, len);
1226 bio_setup_bv(clone, idx, bv_count);
1228 if (idx != bio->bi_idx || clone->bi_size < bio->bi_size)
1230 clone_bio_integrity(bio, clone, idx, len, 0, trim);
1233 static struct dm_target_io *alloc_tio(struct clone_info *ci,
1234 struct dm_target *ti, int nr_iovecs,
1235 unsigned target_bio_nr)
1237 struct dm_target_io *tio;
1240 clone = bio_alloc_bioset(GFP_NOIO, nr_iovecs, ci->md->bs);
1241 tio = container_of(clone, struct dm_target_io, clone);
1245 memset(&tio->info, 0, sizeof(tio->info));
1246 tio->target_bio_nr = target_bio_nr;
1251 static void __clone_and_map_simple_bio(struct clone_info *ci,
1252 struct dm_target *ti,
1253 unsigned target_bio_nr, sector_t len)
1255 struct dm_target_io *tio = alloc_tio(ci, ti, ci->bio->bi_max_vecs, target_bio_nr);
1256 struct bio *clone = &tio->clone;
1259 * Discard requests require the bio's inline iovecs be initialized.
1260 * ci->bio->bi_max_vecs is BIO_INLINE_VECS anyway, for both flush
1261 * and discard, so no need for concern about wasted bvec allocations.
1263 __bio_clone(clone, ci->bio);
1265 bio_setup_sector(clone, ci->sector, len);
1270 static void __send_duplicate_bios(struct clone_info *ci, struct dm_target *ti,
1271 unsigned num_bios, sector_t len)
1273 unsigned target_bio_nr;
1275 for (target_bio_nr = 0; target_bio_nr < num_bios; target_bio_nr++)
1276 __clone_and_map_simple_bio(ci, ti, target_bio_nr, len);
1279 static int __send_empty_flush(struct clone_info *ci)
1281 unsigned target_nr = 0;
1282 struct dm_target *ti;
1284 BUG_ON(bio_has_data(ci->bio));
1285 while ((ti = dm_table_get_target(ci->map, target_nr++)))
1286 __send_duplicate_bios(ci, ti, ti->num_flush_bios, 0);
1291 static void __clone_and_map_data_bio(struct clone_info *ci, struct dm_target *ti,
1292 sector_t sector, int nr_iovecs,
1293 unsigned short idx, unsigned short bv_count,
1294 unsigned offset, unsigned len,
1295 unsigned split_bvec)
1297 struct bio *bio = ci->bio;
1298 struct dm_target_io *tio;
1299 unsigned target_bio_nr;
1300 unsigned num_target_bios = 1;
1303 * Does the target want to receive duplicate copies of the bio?
1305 if (bio_data_dir(bio) == WRITE && ti->num_write_bios)
1306 num_target_bios = ti->num_write_bios(ti, bio);
1308 for (target_bio_nr = 0; target_bio_nr < num_target_bios; target_bio_nr++) {
1309 tio = alloc_tio(ci, ti, nr_iovecs, target_bio_nr);
1311 clone_split_bio(tio, bio, sector, idx, offset, len);
1313 clone_bio(tio, bio, sector, idx, bv_count, len);
1318 typedef unsigned (*get_num_bios_fn)(struct dm_target *ti);
1320 static unsigned get_num_discard_bios(struct dm_target *ti)
1322 return ti->num_discard_bios;
1325 static unsigned get_num_write_same_bios(struct dm_target *ti)
1327 return ti->num_write_same_bios;
1330 typedef bool (*is_split_required_fn)(struct dm_target *ti);
1332 static bool is_split_required_for_discard(struct dm_target *ti)
1334 return ti->split_discard_bios;
1337 static int __send_changing_extent_only(struct clone_info *ci,
1338 get_num_bios_fn get_num_bios,
1339 is_split_required_fn is_split_required)
1341 struct dm_target *ti;
1346 ti = dm_table_find_target(ci->map, ci->sector);
1347 if (!dm_target_is_valid(ti))
1351 * Even though the device advertised support for this type of
1352 * request, that does not mean every target supports it, and
1353 * reconfiguration might also have changed that since the
1354 * check was performed.
1356 num_bios = get_num_bios ? get_num_bios(ti) : 0;
1360 if (is_split_required && !is_split_required(ti))
1361 len = min(ci->sector_count, max_io_len_target_boundary(ci->sector, ti));
1363 len = min(ci->sector_count, max_io_len(ci->sector, ti));
1365 __send_duplicate_bios(ci, ti, num_bios, len);
1368 } while (ci->sector_count -= len);
1373 static int __send_discard(struct clone_info *ci)
1375 return __send_changing_extent_only(ci, get_num_discard_bios,
1376 is_split_required_for_discard);
1379 static int __send_write_same(struct clone_info *ci)
1381 return __send_changing_extent_only(ci, get_num_write_same_bios, NULL);
1385 * Find maximum number of sectors / bvecs we can process with a single bio.
1387 static sector_t __len_within_target(struct clone_info *ci, sector_t max, int *idx)
1389 struct bio *bio = ci->bio;
1390 sector_t bv_len, total_len = 0;
1392 for (*idx = ci->idx; max && (*idx < bio->bi_vcnt); (*idx)++) {
1393 bv_len = to_sector(bio->bi_io_vec[*idx].bv_len);
1399 total_len += bv_len;
1405 static int __split_bvec_across_targets(struct clone_info *ci,
1406 struct dm_target *ti, sector_t max)
1408 struct bio *bio = ci->bio;
1409 struct bio_vec *bv = bio->bi_io_vec + ci->idx;
1410 sector_t remaining = to_sector(bv->bv_len);
1411 unsigned offset = 0;
1416 ti = dm_table_find_target(ci->map, ci->sector);
1417 if (!dm_target_is_valid(ti))
1420 max = max_io_len(ci->sector, ti);
1423 len = min(remaining, max);
1425 __clone_and_map_data_bio(ci, ti, ci->sector, 1, ci->idx, 0,
1426 bv->bv_offset + offset, len, 1);
1429 ci->sector_count -= len;
1430 offset += to_bytes(len);
1431 } while (remaining -= len);
1439 * Select the correct strategy for processing a non-flush bio.
1441 static int __split_and_process_non_flush(struct clone_info *ci)
1443 struct bio *bio = ci->bio;
1444 struct dm_target *ti;
1448 if (unlikely(bio->bi_rw & REQ_DISCARD))
1449 return __send_discard(ci);
1450 else if (unlikely(bio->bi_rw & REQ_WRITE_SAME))
1451 return __send_write_same(ci);
1453 ti = dm_table_find_target(ci->map, ci->sector);
1454 if (!dm_target_is_valid(ti))
1457 max = max_io_len(ci->sector, ti);
1460 * Optimise for the simple case where we can do all of
1461 * the remaining io with a single clone.
1463 if (ci->sector_count <= max) {
1464 __clone_and_map_data_bio(ci, ti, ci->sector, bio->bi_max_vecs,
1465 ci->idx, bio->bi_vcnt - ci->idx, 0,
1466 ci->sector_count, 0);
1467 ci->sector_count = 0;
1472 * There are some bvecs that don't span targets.
1473 * Do as many of these as possible.
1475 if (to_sector(bio->bi_io_vec[ci->idx].bv_len) <= max) {
1476 len = __len_within_target(ci, max, &idx);
1478 __clone_and_map_data_bio(ci, ti, ci->sector, bio->bi_max_vecs,
1479 ci->idx, idx - ci->idx, 0, len, 0);
1482 ci->sector_count -= len;
1489 * Handle a bvec that must be split between two or more targets.
1491 return __split_bvec_across_targets(ci, ti, max);
1495 * Entry point to split a bio into clones and submit them to the targets.
1497 static void __split_and_process_bio(struct mapped_device *md,
1498 struct dm_table *map, struct bio *bio)
1500 struct clone_info ci;
1503 if (unlikely(!map)) {
1510 ci.io = alloc_io(md);
1512 atomic_set(&ci.io->io_count, 1);
1515 spin_lock_init(&ci.io->endio_lock);
1516 ci.sector = bio->bi_sector;
1517 ci.idx = bio->bi_idx;
1519 start_io_acct(ci.io);
1521 if (bio->bi_rw & REQ_FLUSH) {
1522 ci.bio = &ci.md->flush_bio;
1523 ci.sector_count = 0;
1524 error = __send_empty_flush(&ci);
1525 /* dec_pending submits any data associated with flush */
1528 ci.sector_count = bio_sectors(bio);
1529 while (ci.sector_count && !error)
1530 error = __split_and_process_non_flush(&ci);
1533 /* drop the extra reference count */
1534 dec_pending(ci.io, error);
1536 /*-----------------------------------------------------------------
1538 *---------------------------------------------------------------*/
1540 static int dm_merge_bvec(struct request_queue *q,
1541 struct bvec_merge_data *bvm,
1542 struct bio_vec *biovec)
1544 struct mapped_device *md = q->queuedata;
1545 struct dm_table *map = dm_get_live_table_fast(md);
1546 struct dm_target *ti;
1547 sector_t max_sectors;
1553 ti = dm_table_find_target(map, bvm->bi_sector);
1554 if (!dm_target_is_valid(ti))
1558 * Find maximum amount of I/O that won't need splitting
1560 max_sectors = min(max_io_len(bvm->bi_sector, ti),
1561 (sector_t) BIO_MAX_SECTORS);
1562 max_size = (max_sectors << SECTOR_SHIFT) - bvm->bi_size;
1567 * merge_bvec_fn() returns number of bytes
1568 * it can accept at this offset
1569 * max is precomputed maximal io size
1571 if (max_size && ti->type->merge)
1572 max_size = ti->type->merge(ti, bvm, biovec, max_size);
1574 * If the target doesn't support merge method and some of the devices
1575 * provided their merge_bvec method (we know this by looking at
1576 * queue_max_hw_sectors), then we can't allow bios with multiple vector
1577 * entries. So always set max_size to 0, and the code below allows
1580 else if (queue_max_hw_sectors(q) <= PAGE_SIZE >> 9)
1585 dm_put_live_table_fast(md);
1587 * Always allow an entire first page
1589 if (max_size <= biovec->bv_len && !(bvm->bi_size >> SECTOR_SHIFT))
1590 max_size = biovec->bv_len;
1596 * The request function that just remaps the bio built up by
1599 static void _dm_request(struct request_queue *q, struct bio *bio)
1601 int rw = bio_data_dir(bio);
1602 struct mapped_device *md = q->queuedata;
1605 struct dm_table *map;
1607 map = dm_get_live_table(md, &srcu_idx);
1609 cpu = part_stat_lock();
1610 part_stat_inc(cpu, &dm_disk(md)->part0, ios[rw]);
1611 part_stat_add(cpu, &dm_disk(md)->part0, sectors[rw], bio_sectors(bio));
1614 /* if we're suspended, we have to queue this io for later */
1615 if (unlikely(test_bit(DMF_BLOCK_IO_FOR_SUSPEND, &md->flags))) {
1616 dm_put_live_table(md, srcu_idx);
1618 if (bio_rw(bio) != READA)
1625 __split_and_process_bio(md, map, bio);
1626 dm_put_live_table(md, srcu_idx);
1630 int dm_request_based(struct mapped_device *md)
1632 return blk_queue_stackable(md->queue);
1635 static void dm_request(struct request_queue *q, struct bio *bio)
1637 struct mapped_device *md = q->queuedata;
1639 if (dm_request_based(md))
1640 blk_queue_bio(q, bio);
1642 _dm_request(q, bio);
1645 void dm_dispatch_request(struct request *rq)
1649 if (blk_queue_io_stat(rq->q))
1650 rq->cmd_flags |= REQ_IO_STAT;
1652 rq->start_time = jiffies;
1653 r = blk_insert_cloned_request(rq->q, rq);
1655 dm_complete_request(rq, r);
1657 EXPORT_SYMBOL_GPL(dm_dispatch_request);
1659 static int dm_rq_bio_constructor(struct bio *bio, struct bio *bio_orig,
1662 struct dm_rq_target_io *tio = data;
1663 struct dm_rq_clone_bio_info *info =
1664 container_of(bio, struct dm_rq_clone_bio_info, clone);
1666 info->orig = bio_orig;
1668 bio->bi_end_io = end_clone_bio;
1669 bio->bi_private = info;
1674 static int setup_clone(struct request *clone, struct request *rq,
1675 struct dm_rq_target_io *tio)
1679 r = blk_rq_prep_clone(clone, rq, tio->md->bs, GFP_ATOMIC,
1680 dm_rq_bio_constructor, tio);
1684 clone->cmd = rq->cmd;
1685 clone->cmd_len = rq->cmd_len;
1686 clone->sense = rq->sense;
1687 clone->buffer = rq->buffer;
1688 clone->end_io = end_clone_request;
1689 clone->end_io_data = tio;
1694 static struct request *clone_rq(struct request *rq, struct mapped_device *md,
1697 struct request *clone;
1698 struct dm_rq_target_io *tio;
1700 tio = alloc_rq_tio(md, gfp_mask);
1708 memset(&tio->info, 0, sizeof(tio->info));
1710 clone = &tio->clone;
1711 if (setup_clone(clone, rq, tio)) {
1721 * Called with the queue lock held.
1723 static int dm_prep_fn(struct request_queue *q, struct request *rq)
1725 struct mapped_device *md = q->queuedata;
1726 struct request *clone;
1728 if (unlikely(rq->special)) {
1729 DMWARN("Already has something in rq->special.");
1730 return BLKPREP_KILL;
1733 clone = clone_rq(rq, md, GFP_ATOMIC);
1735 return BLKPREP_DEFER;
1737 rq->special = clone;
1738 rq->cmd_flags |= REQ_DONTPREP;
1745 * 0 : the request has been processed (not requeued)
1746 * !0 : the request has been requeued
1748 static int map_request(struct dm_target *ti, struct request *clone,
1749 struct mapped_device *md)
1751 int r, requeued = 0;
1752 struct dm_rq_target_io *tio = clone->end_io_data;
1755 r = ti->type->map_rq(ti, clone, &tio->info);
1757 case DM_MAPIO_SUBMITTED:
1758 /* The target has taken the I/O to submit by itself later */
1760 case DM_MAPIO_REMAPPED:
1761 /* The target has remapped the I/O so dispatch it */
1762 trace_block_rq_remap(clone->q, clone, disk_devt(dm_disk(md)),
1763 blk_rq_pos(tio->orig));
1764 dm_dispatch_request(clone);
1766 case DM_MAPIO_REQUEUE:
1767 /* The target wants to requeue the I/O */
1768 dm_requeue_unmapped_request(clone);
1773 DMWARN("unimplemented target map return value: %d", r);
1777 /* The target wants to complete the I/O */
1778 dm_kill_unmapped_request(clone, r);
1785 static struct request *dm_start_request(struct mapped_device *md, struct request *orig)
1787 struct request *clone;
1789 blk_start_request(orig);
1790 clone = orig->special;
1791 atomic_inc(&md->pending[rq_data_dir(clone)]);
1794 * Hold the md reference here for the in-flight I/O.
1795 * We can't rely on the reference count by device opener,
1796 * because the device may be closed during the request completion
1797 * when all bios are completed.
1798 * See the comment in rq_completed() too.
1806 * q->request_fn for request-based dm.
1807 * Called with the queue lock held.
1809 static void dm_request_fn(struct request_queue *q)
1811 struct mapped_device *md = q->queuedata;
1813 struct dm_table *map = dm_get_live_table(md, &srcu_idx);
1814 struct dm_target *ti;
1815 struct request *rq, *clone;
1819 * For suspend, check blk_queue_stopped() and increment
1820 * ->pending within a single queue_lock not to increment the
1821 * number of in-flight I/Os after the queue is stopped in
1824 while (!blk_queue_stopped(q)) {
1825 rq = blk_peek_request(q);
1829 /* always use block 0 to find the target for flushes for now */
1831 if (!(rq->cmd_flags & REQ_FLUSH))
1832 pos = blk_rq_pos(rq);
1834 ti = dm_table_find_target(map, pos);
1835 if (!dm_target_is_valid(ti)) {
1837 * Must perform setup, that dm_done() requires,
1838 * before calling dm_kill_unmapped_request
1840 DMERR_LIMIT("request attempted access beyond the end of device");
1841 clone = dm_start_request(md, rq);
1842 dm_kill_unmapped_request(clone, -EIO);
1846 if (ti->type->busy && ti->type->busy(ti))
1849 clone = dm_start_request(md, rq);
1851 spin_unlock(q->queue_lock);
1852 if (map_request(ti, clone, md))
1855 BUG_ON(!irqs_disabled());
1856 spin_lock(q->queue_lock);
1862 BUG_ON(!irqs_disabled());
1863 spin_lock(q->queue_lock);
1866 blk_delay_queue(q, HZ / 10);
1868 dm_put_live_table(md, srcu_idx);
1871 int dm_underlying_device_busy(struct request_queue *q)
1873 return blk_lld_busy(q);
1875 EXPORT_SYMBOL_GPL(dm_underlying_device_busy);
1877 static int dm_lld_busy(struct request_queue *q)
1880 struct mapped_device *md = q->queuedata;
1881 struct dm_table *map = dm_get_live_table_fast(md);
1883 if (!map || test_bit(DMF_BLOCK_IO_FOR_SUSPEND, &md->flags))
1886 r = dm_table_any_busy_target(map);
1888 dm_put_live_table_fast(md);
1893 static int dm_any_congested(void *congested_data, int bdi_bits)
1896 struct mapped_device *md = congested_data;
1897 struct dm_table *map;
1899 if (!test_bit(DMF_BLOCK_IO_FOR_SUSPEND, &md->flags)) {
1900 map = dm_get_live_table_fast(md);
1903 * Request-based dm cares about only own queue for
1904 * the query about congestion status of request_queue
1906 if (dm_request_based(md))
1907 r = md->queue->backing_dev_info.state &
1910 r = dm_table_any_congested(map, bdi_bits);
1912 dm_put_live_table_fast(md);
1918 /*-----------------------------------------------------------------
1919 * An IDR is used to keep track of allocated minor numbers.
1920 *---------------------------------------------------------------*/
1921 static void free_minor(int minor)
1923 spin_lock(&_minor_lock);
1924 idr_remove(&_minor_idr, minor);
1925 spin_unlock(&_minor_lock);
1929 * See if the device with a specific minor # is free.
1931 static int specific_minor(int minor)
1935 if (minor >= (1 << MINORBITS))
1938 idr_preload(GFP_KERNEL);
1939 spin_lock(&_minor_lock);
1941 r = idr_alloc(&_minor_idr, MINOR_ALLOCED, minor, minor + 1, GFP_NOWAIT);
1943 spin_unlock(&_minor_lock);
1946 return r == -ENOSPC ? -EBUSY : r;
1950 static int next_free_minor(int *minor)
1954 idr_preload(GFP_KERNEL);
1955 spin_lock(&_minor_lock);
1957 r = idr_alloc(&_minor_idr, MINOR_ALLOCED, 0, 1 << MINORBITS, GFP_NOWAIT);
1959 spin_unlock(&_minor_lock);
1967 static const struct block_device_operations dm_blk_dops;
1969 static void dm_wq_work(struct work_struct *work);
1971 static void dm_init_md_queue(struct mapped_device *md)
1974 * Request-based dm devices cannot be stacked on top of bio-based dm
1975 * devices. The type of this dm device has not been decided yet.
1976 * The type is decided at the first table loading time.
1977 * To prevent problematic device stacking, clear the queue flag
1978 * for request stacking support until then.
1980 * This queue is new, so no concurrency on the queue_flags.
1982 queue_flag_clear_unlocked(QUEUE_FLAG_STACKABLE, md->queue);
1984 md->queue->queuedata = md;
1985 md->queue->backing_dev_info.congested_fn = dm_any_congested;
1986 md->queue->backing_dev_info.congested_data = md;
1987 blk_queue_make_request(md->queue, dm_request);
1988 blk_queue_bounce_limit(md->queue, BLK_BOUNCE_ANY);
1989 blk_queue_merge_bvec(md->queue, dm_merge_bvec);
1993 * Allocate and initialise a blank device with a given minor.
1995 static struct mapped_device *alloc_dev(int minor)
1998 struct mapped_device *md = kzalloc(sizeof(*md), GFP_KERNEL);
2002 DMWARN("unable to allocate device, out of memory.");
2006 if (!try_module_get(THIS_MODULE))
2007 goto bad_module_get;
2009 /* get a minor number for the dev */
2010 if (minor == DM_ANY_MINOR)
2011 r = next_free_minor(&minor);
2013 r = specific_minor(minor);
2017 r = init_srcu_struct(&md->io_barrier);
2019 goto bad_io_barrier;
2021 md->type = DM_TYPE_NONE;
2022 mutex_init(&md->suspend_lock);
2023 mutex_init(&md->type_lock);
2024 spin_lock_init(&md->deferred_lock);
2025 atomic_set(&md->holders, 1);
2026 atomic_set(&md->open_count, 0);
2027 atomic_set(&md->event_nr, 0);
2028 atomic_set(&md->uevent_seq, 0);
2029 INIT_LIST_HEAD(&md->uevent_list);
2030 spin_lock_init(&md->uevent_lock);
2032 md->queue = blk_alloc_queue(GFP_KERNEL);
2036 dm_init_md_queue(md);
2038 md->disk = alloc_disk(1);
2042 atomic_set(&md->pending[0], 0);
2043 atomic_set(&md->pending[1], 0);
2044 init_waitqueue_head(&md->wait);
2045 INIT_WORK(&md->work, dm_wq_work);
2046 init_waitqueue_head(&md->eventq);
2047 init_completion(&md->kobj_completion);
2049 md->disk->major = _major;
2050 md->disk->first_minor = minor;
2051 md->disk->fops = &dm_blk_dops;
2052 md->disk->queue = md->queue;
2053 md->disk->private_data = md;
2054 sprintf(md->disk->disk_name, "dm-%d", minor);
2056 format_dev_t(md->name, MKDEV(_major, minor));
2058 md->wq = alloc_workqueue("kdmflush", WQ_MEM_RECLAIM, 0);
2062 md->bdev = bdget_disk(md->disk, 0);
2066 bio_init(&md->flush_bio);
2067 md->flush_bio.bi_bdev = md->bdev;
2068 md->flush_bio.bi_rw = WRITE_FLUSH;
2070 dm_stats_init(&md->stats);
2072 /* Populate the mapping, nobody knows we exist yet */
2073 spin_lock(&_minor_lock);
2074 old_md = idr_replace(&_minor_idr, md, minor);
2075 spin_unlock(&_minor_lock);
2077 BUG_ON(old_md != MINOR_ALLOCED);
2082 destroy_workqueue(md->wq);
2084 del_gendisk(md->disk);
2087 blk_cleanup_queue(md->queue);
2089 cleanup_srcu_struct(&md->io_barrier);
2093 module_put(THIS_MODULE);
2099 static void unlock_fs(struct mapped_device *md);
2101 static void free_dev(struct mapped_device *md)
2103 int minor = MINOR(disk_devt(md->disk));
2107 destroy_workqueue(md->wq);
2109 mempool_destroy(md->io_pool);
2111 bioset_free(md->bs);
2112 blk_integrity_unregister(md->disk);
2113 del_gendisk(md->disk);
2114 cleanup_srcu_struct(&md->io_barrier);
2117 spin_lock(&_minor_lock);
2118 md->disk->private_data = NULL;
2119 spin_unlock(&_minor_lock);
2122 blk_cleanup_queue(md->queue);
2123 dm_stats_cleanup(&md->stats);
2124 module_put(THIS_MODULE);
2128 static void __bind_mempools(struct mapped_device *md, struct dm_table *t)
2130 struct dm_md_mempools *p = dm_table_get_md_mempools(t);
2132 if (md->io_pool && md->bs) {
2133 /* The md already has necessary mempools. */
2134 if (dm_table_get_type(t) == DM_TYPE_BIO_BASED) {
2136 * Reload bioset because front_pad may have changed
2137 * because a different table was loaded.
2139 bioset_free(md->bs);
2142 } else if (dm_table_get_type(t) == DM_TYPE_REQUEST_BASED) {
2144 * There's no need to reload with request-based dm
2145 * because the size of front_pad doesn't change.
2146 * Note for future: If you are to reload bioset,
2147 * prep-ed requests in the queue may refer
2148 * to bio from the old bioset, so you must walk
2149 * through the queue to unprep.
2155 BUG_ON(!p || md->io_pool || md->bs);
2157 md->io_pool = p->io_pool;
2163 /* mempool bind completed, now no need any mempools in the table */
2164 dm_table_free_md_mempools(t);
2168 * Bind a table to the device.
2170 static void event_callback(void *context)
2172 unsigned long flags;
2174 struct mapped_device *md = (struct mapped_device *) context;
2176 spin_lock_irqsave(&md->uevent_lock, flags);
2177 list_splice_init(&md->uevent_list, &uevents);
2178 spin_unlock_irqrestore(&md->uevent_lock, flags);
2180 dm_send_uevents(&uevents, &disk_to_dev(md->disk)->kobj);
2182 atomic_inc(&md->event_nr);
2183 wake_up(&md->eventq);
2187 * Protected by md->suspend_lock obtained by dm_swap_table().
2189 static void __set_size(struct mapped_device *md, sector_t size)
2191 set_capacity(md->disk, size);
2193 i_size_write(md->bdev->bd_inode, (loff_t)size << SECTOR_SHIFT);
2197 * Return 1 if the queue has a compulsory merge_bvec_fn function.
2199 * If this function returns 0, then the device is either a non-dm
2200 * device without a merge_bvec_fn, or it is a dm device that is
2201 * able to split any bios it receives that are too big.
2203 int dm_queue_merge_is_compulsory(struct request_queue *q)
2205 struct mapped_device *dev_md;
2207 if (!q->merge_bvec_fn)
2210 if (q->make_request_fn == dm_request) {
2211 dev_md = q->queuedata;
2212 if (test_bit(DMF_MERGE_IS_OPTIONAL, &dev_md->flags))
2219 static int dm_device_merge_is_compulsory(struct dm_target *ti,
2220 struct dm_dev *dev, sector_t start,
2221 sector_t len, void *data)
2223 struct block_device *bdev = dev->bdev;
2224 struct request_queue *q = bdev_get_queue(bdev);
2226 return dm_queue_merge_is_compulsory(q);
2230 * Return 1 if it is acceptable to ignore merge_bvec_fn based
2231 * on the properties of the underlying devices.
2233 static int dm_table_merge_is_optional(struct dm_table *table)
2236 struct dm_target *ti;
2238 while (i < dm_table_get_num_targets(table)) {
2239 ti = dm_table_get_target(table, i++);
2241 if (ti->type->iterate_devices &&
2242 ti->type->iterate_devices(ti, dm_device_merge_is_compulsory, NULL))
2250 * Returns old map, which caller must destroy.
2252 static struct dm_table *__bind(struct mapped_device *md, struct dm_table *t,
2253 struct queue_limits *limits)
2255 struct dm_table *old_map;
2256 struct request_queue *q = md->queue;
2258 int merge_is_optional;
2260 size = dm_table_get_size(t);
2263 * Wipe any geometry if the size of the table changed.
2265 if (size != dm_get_size(md))
2266 memset(&md->geometry, 0, sizeof(md->geometry));
2268 __set_size(md, size);
2270 dm_table_event_callback(t, event_callback, md);
2273 * The queue hasn't been stopped yet, if the old table type wasn't
2274 * for request-based during suspension. So stop it to prevent
2275 * I/O mapping before resume.
2276 * This must be done before setting the queue restrictions,
2277 * because request-based dm may be run just after the setting.
2279 if (dm_table_request_based(t) && !blk_queue_stopped(q))
2282 __bind_mempools(md, t);
2284 merge_is_optional = dm_table_merge_is_optional(t);
2287 rcu_assign_pointer(md->map, t);
2288 md->immutable_target_type = dm_table_get_immutable_target_type(t);
2290 dm_table_set_restrictions(t, q, limits);
2291 if (merge_is_optional)
2292 set_bit(DMF_MERGE_IS_OPTIONAL, &md->flags);
2294 clear_bit(DMF_MERGE_IS_OPTIONAL, &md->flags);
2301 * Returns unbound table for the caller to free.
2303 static struct dm_table *__unbind(struct mapped_device *md)
2305 struct dm_table *map = md->map;
2310 dm_table_event_callback(map, NULL, NULL);
2311 rcu_assign_pointer(md->map, NULL);
2318 * Constructor for a new device.
2320 int dm_create(int minor, struct mapped_device **result)
2322 struct mapped_device *md;
2324 md = alloc_dev(minor);
2335 * Functions to manage md->type.
2336 * All are required to hold md->type_lock.
2338 void dm_lock_md_type(struct mapped_device *md)
2340 mutex_lock(&md->type_lock);
2343 void dm_unlock_md_type(struct mapped_device *md)
2345 mutex_unlock(&md->type_lock);
2348 void dm_set_md_type(struct mapped_device *md, unsigned type)
2350 BUG_ON(!mutex_is_locked(&md->type_lock));
2354 unsigned dm_get_md_type(struct mapped_device *md)
2356 BUG_ON(!mutex_is_locked(&md->type_lock));
2360 struct target_type *dm_get_immutable_target_type(struct mapped_device *md)
2362 return md->immutable_target_type;
2366 * The queue_limits are only valid as long as you have a reference
2369 struct queue_limits *dm_get_queue_limits(struct mapped_device *md)
2371 BUG_ON(!atomic_read(&md->holders));
2372 return &md->queue->limits;
2374 EXPORT_SYMBOL_GPL(dm_get_queue_limits);
2377 * Fully initialize a request-based queue (->elevator, ->request_fn, etc).
2379 static int dm_init_request_based_queue(struct mapped_device *md)
2381 struct request_queue *q = NULL;
2383 if (md->queue->elevator)
2386 /* Fully initialize the queue */
2387 q = blk_init_allocated_queue(md->queue, dm_request_fn, NULL);
2392 dm_init_md_queue(md);
2393 blk_queue_softirq_done(md->queue, dm_softirq_done);
2394 blk_queue_prep_rq(md->queue, dm_prep_fn);
2395 blk_queue_lld_busy(md->queue, dm_lld_busy);
2397 elv_register_queue(md->queue);
2403 * Setup the DM device's queue based on md's type
2405 int dm_setup_md_queue(struct mapped_device *md)
2407 if ((dm_get_md_type(md) == DM_TYPE_REQUEST_BASED) &&
2408 !dm_init_request_based_queue(md)) {
2409 DMWARN("Cannot initialize queue for request-based mapped device");
2416 static struct mapped_device *dm_find_md(dev_t dev)
2418 struct mapped_device *md;
2419 unsigned minor = MINOR(dev);
2421 if (MAJOR(dev) != _major || minor >= (1 << MINORBITS))
2424 spin_lock(&_minor_lock);
2426 md = idr_find(&_minor_idr, minor);
2427 if (md && (md == MINOR_ALLOCED ||
2428 (MINOR(disk_devt(dm_disk(md))) != minor) ||
2429 dm_deleting_md(md) ||
2430 test_bit(DMF_FREEING, &md->flags))) {
2436 spin_unlock(&_minor_lock);
2441 struct mapped_device *dm_get_md(dev_t dev)
2443 struct mapped_device *md = dm_find_md(dev);
2450 EXPORT_SYMBOL_GPL(dm_get_md);
2452 void *dm_get_mdptr(struct mapped_device *md)
2454 return md->interface_ptr;
2457 void dm_set_mdptr(struct mapped_device *md, void *ptr)
2459 md->interface_ptr = ptr;
2462 void dm_get(struct mapped_device *md)
2464 atomic_inc(&md->holders);
2465 BUG_ON(test_bit(DMF_FREEING, &md->flags));
2468 const char *dm_device_name(struct mapped_device *md)
2472 EXPORT_SYMBOL_GPL(dm_device_name);
2474 static void __dm_destroy(struct mapped_device *md, bool wait)
2476 struct dm_table *map;
2481 spin_lock(&_minor_lock);
2482 map = dm_get_live_table(md, &srcu_idx);
2483 idr_replace(&_minor_idr, MINOR_ALLOCED, MINOR(disk_devt(dm_disk(md))));
2484 set_bit(DMF_FREEING, &md->flags);
2485 spin_unlock(&_minor_lock);
2487 if (!dm_suspended_md(md)) {
2488 dm_table_presuspend_targets(map);
2489 dm_table_postsuspend_targets(map);
2492 /* dm_put_live_table must be before msleep, otherwise deadlock is possible */
2493 dm_put_live_table(md, srcu_idx);
2496 * Rare, but there may be I/O requests still going to complete,
2497 * for example. Wait for all references to disappear.
2498 * No one should increment the reference count of the mapped_device,
2499 * after the mapped_device state becomes DMF_FREEING.
2502 while (atomic_read(&md->holders))
2504 else if (atomic_read(&md->holders))
2505 DMWARN("%s: Forcibly removing mapped_device still in use! (%d users)",
2506 dm_device_name(md), atomic_read(&md->holders));
2509 dm_table_destroy(__unbind(md));
2513 void dm_destroy(struct mapped_device *md)
2515 __dm_destroy(md, true);
2518 void dm_destroy_immediate(struct mapped_device *md)
2520 __dm_destroy(md, false);
2523 void dm_put(struct mapped_device *md)
2525 atomic_dec(&md->holders);
2527 EXPORT_SYMBOL_GPL(dm_put);
2529 static int dm_wait_for_completion(struct mapped_device *md, int interruptible)
2532 DECLARE_WAITQUEUE(wait, current);
2534 add_wait_queue(&md->wait, &wait);
2537 set_current_state(interruptible);
2539 if (!md_in_flight(md))
2542 if (interruptible == TASK_INTERRUPTIBLE &&
2543 signal_pending(current)) {
2550 set_current_state(TASK_RUNNING);
2552 remove_wait_queue(&md->wait, &wait);
2558 * Process the deferred bios
2560 static void dm_wq_work(struct work_struct *work)
2562 struct mapped_device *md = container_of(work, struct mapped_device,
2566 struct dm_table *map;
2568 map = dm_get_live_table(md, &srcu_idx);
2570 while (!test_bit(DMF_BLOCK_IO_FOR_SUSPEND, &md->flags)) {
2571 spin_lock_irq(&md->deferred_lock);
2572 c = bio_list_pop(&md->deferred);
2573 spin_unlock_irq(&md->deferred_lock);
2578 if (dm_request_based(md))
2579 generic_make_request(c);
2581 __split_and_process_bio(md, map, c);
2584 dm_put_live_table(md, srcu_idx);
2587 static void dm_queue_flush(struct mapped_device *md)
2589 clear_bit(DMF_BLOCK_IO_FOR_SUSPEND, &md->flags);
2590 smp_mb__after_clear_bit();
2591 queue_work(md->wq, &md->work);
2595 * Swap in a new table, returning the old one for the caller to destroy.
2597 struct dm_table *dm_swap_table(struct mapped_device *md, struct dm_table *table)
2599 struct dm_table *live_map = NULL, *map = ERR_PTR(-EINVAL);
2600 struct queue_limits limits;
2603 mutex_lock(&md->suspend_lock);
2605 /* device must be suspended */
2606 if (!dm_suspended_md(md))
2610 * If the new table has no data devices, retain the existing limits.
2611 * This helps multipath with queue_if_no_path if all paths disappear,
2612 * then new I/O is queued based on these limits, and then some paths
2615 if (dm_table_has_no_data_devices(table)) {
2616 live_map = dm_get_live_table_fast(md);
2618 limits = md->queue->limits;
2619 dm_put_live_table_fast(md);
2623 r = dm_calculate_queue_limits(table, &limits);
2630 map = __bind(md, table, &limits);
2633 mutex_unlock(&md->suspend_lock);
2638 * Functions to lock and unlock any filesystem running on the
2641 static int lock_fs(struct mapped_device *md)
2645 WARN_ON(md->frozen_sb);
2647 md->frozen_sb = freeze_bdev(md->bdev);
2648 if (IS_ERR(md->frozen_sb)) {
2649 r = PTR_ERR(md->frozen_sb);
2650 md->frozen_sb = NULL;
2654 set_bit(DMF_FROZEN, &md->flags);
2659 static void unlock_fs(struct mapped_device *md)
2661 if (!test_bit(DMF_FROZEN, &md->flags))
2664 thaw_bdev(md->bdev, md->frozen_sb);
2665 md->frozen_sb = NULL;
2666 clear_bit(DMF_FROZEN, &md->flags);
2670 * We need to be able to change a mapping table under a mounted
2671 * filesystem. For example we might want to move some data in
2672 * the background. Before the table can be swapped with
2673 * dm_bind_table, dm_suspend must be called to flush any in
2674 * flight bios and ensure that any further io gets deferred.
2677 * Suspend mechanism in request-based dm.
2679 * 1. Flush all I/Os by lock_fs() if needed.
2680 * 2. Stop dispatching any I/O by stopping the request_queue.
2681 * 3. Wait for all in-flight I/Os to be completed or requeued.
2683 * To abort suspend, start the request_queue.
2685 int dm_suspend(struct mapped_device *md, unsigned suspend_flags)
2687 struct dm_table *map = NULL;
2689 int do_lockfs = suspend_flags & DM_SUSPEND_LOCKFS_FLAG ? 1 : 0;
2690 int noflush = suspend_flags & DM_SUSPEND_NOFLUSH_FLAG ? 1 : 0;
2692 mutex_lock(&md->suspend_lock);
2694 if (dm_suspended_md(md)) {
2702 * DMF_NOFLUSH_SUSPENDING must be set before presuspend.
2703 * This flag is cleared before dm_suspend returns.
2706 set_bit(DMF_NOFLUSH_SUSPENDING, &md->flags);
2708 /* This does not get reverted if there's an error later. */
2709 dm_table_presuspend_targets(map);
2712 * Flush I/O to the device.
2713 * Any I/O submitted after lock_fs() may not be flushed.
2714 * noflush takes precedence over do_lockfs.
2715 * (lock_fs() flushes I/Os and waits for them to complete.)
2717 if (!noflush && do_lockfs) {
2724 * Here we must make sure that no processes are submitting requests
2725 * to target drivers i.e. no one may be executing
2726 * __split_and_process_bio. This is called from dm_request and
2729 * To get all processes out of __split_and_process_bio in dm_request,
2730 * we take the write lock. To prevent any process from reentering
2731 * __split_and_process_bio from dm_request and quiesce the thread
2732 * (dm_wq_work), we set BMF_BLOCK_IO_FOR_SUSPEND and call
2733 * flush_workqueue(md->wq).
2735 set_bit(DMF_BLOCK_IO_FOR_SUSPEND, &md->flags);
2736 synchronize_srcu(&md->io_barrier);
2739 * Stop md->queue before flushing md->wq in case request-based
2740 * dm defers requests to md->wq from md->queue.
2742 if (dm_request_based(md))
2743 stop_queue(md->queue);
2745 flush_workqueue(md->wq);
2748 * At this point no more requests are entering target request routines.
2749 * We call dm_wait_for_completion to wait for all existing requests
2752 r = dm_wait_for_completion(md, TASK_INTERRUPTIBLE);
2755 clear_bit(DMF_NOFLUSH_SUSPENDING, &md->flags);
2756 synchronize_srcu(&md->io_barrier);
2758 /* were we interrupted ? */
2762 if (dm_request_based(md))
2763 start_queue(md->queue);
2766 goto out_unlock; /* pushback list is already flushed, so skip flush */
2770 * If dm_wait_for_completion returned 0, the device is completely
2771 * quiescent now. There is no request-processing activity. All new
2772 * requests are being added to md->deferred list.
2775 set_bit(DMF_SUSPENDED, &md->flags);
2777 dm_table_postsuspend_targets(map);
2780 mutex_unlock(&md->suspend_lock);
2784 int dm_resume(struct mapped_device *md)
2787 struct dm_table *map = NULL;
2789 mutex_lock(&md->suspend_lock);
2790 if (!dm_suspended_md(md))
2794 if (!map || !dm_table_get_size(map))
2797 r = dm_table_resume_targets(map);
2804 * Flushing deferred I/Os must be done after targets are resumed
2805 * so that mapping of targets can work correctly.
2806 * Request-based dm is queueing the deferred I/Os in its request_queue.
2808 if (dm_request_based(md))
2809 start_queue(md->queue);
2813 clear_bit(DMF_SUSPENDED, &md->flags);
2817 mutex_unlock(&md->suspend_lock);
2823 * Internal suspend/resume works like userspace-driven suspend. It waits
2824 * until all bios finish and prevents issuing new bios to the target drivers.
2825 * It may be used only from the kernel.
2827 * Internal suspend holds md->suspend_lock, which prevents interaction with
2828 * userspace-driven suspend.
2831 void dm_internal_suspend(struct mapped_device *md)
2833 mutex_lock(&md->suspend_lock);
2834 if (dm_suspended_md(md))
2837 set_bit(DMF_BLOCK_IO_FOR_SUSPEND, &md->flags);
2838 synchronize_srcu(&md->io_barrier);
2839 flush_workqueue(md->wq);
2840 dm_wait_for_completion(md, TASK_UNINTERRUPTIBLE);
2843 void dm_internal_resume(struct mapped_device *md)
2845 if (dm_suspended_md(md))
2851 mutex_unlock(&md->suspend_lock);
2854 /*-----------------------------------------------------------------
2855 * Event notification.
2856 *---------------------------------------------------------------*/
2857 int dm_kobject_uevent(struct mapped_device *md, enum kobject_action action,
2860 char udev_cookie[DM_COOKIE_LENGTH];
2861 char *envp[] = { udev_cookie, NULL };
2864 return kobject_uevent(&disk_to_dev(md->disk)->kobj, action);
2866 snprintf(udev_cookie, DM_COOKIE_LENGTH, "%s=%u",
2867 DM_COOKIE_ENV_VAR_NAME, cookie);
2868 return kobject_uevent_env(&disk_to_dev(md->disk)->kobj,
2873 uint32_t dm_next_uevent_seq(struct mapped_device *md)
2875 return atomic_add_return(1, &md->uevent_seq);
2878 uint32_t dm_get_event_nr(struct mapped_device *md)
2880 return atomic_read(&md->event_nr);
2883 int dm_wait_event(struct mapped_device *md, int event_nr)
2885 return wait_event_interruptible(md->eventq,
2886 (event_nr != atomic_read(&md->event_nr)));
2889 void dm_uevent_add(struct mapped_device *md, struct list_head *elist)
2891 unsigned long flags;
2893 spin_lock_irqsave(&md->uevent_lock, flags);
2894 list_add(elist, &md->uevent_list);
2895 spin_unlock_irqrestore(&md->uevent_lock, flags);
2899 * The gendisk is only valid as long as you have a reference
2902 struct gendisk *dm_disk(struct mapped_device *md)
2907 struct kobject *dm_kobject(struct mapped_device *md)
2912 struct mapped_device *dm_get_from_kobject(struct kobject *kobj)
2914 struct mapped_device *md;
2916 md = container_of(kobj, struct mapped_device, kobj);
2918 if (test_bit(DMF_FREEING, &md->flags) ||
2926 struct completion *dm_get_completion_from_kobject(struct kobject *kobj)
2928 struct mapped_device *md = container_of(kobj, struct mapped_device, kobj);
2930 return &md->kobj_completion;
2933 int dm_suspended_md(struct mapped_device *md)
2935 return test_bit(DMF_SUSPENDED, &md->flags);
2938 int dm_test_deferred_remove_flag(struct mapped_device *md)
2940 return test_bit(DMF_DEFERRED_REMOVE, &md->flags);
2943 int dm_suspended(struct dm_target *ti)
2945 return dm_suspended_md(dm_table_get_md(ti->table));
2947 EXPORT_SYMBOL_GPL(dm_suspended);
2949 int dm_noflush_suspending(struct dm_target *ti)
2951 return __noflush_suspending(dm_table_get_md(ti->table));
2953 EXPORT_SYMBOL_GPL(dm_noflush_suspending);
2955 struct dm_md_mempools *dm_alloc_md_mempools(unsigned type, unsigned integrity, unsigned per_bio_data_size)
2957 struct dm_md_mempools *pools = kzalloc(sizeof(*pools), GFP_KERNEL);
2958 struct kmem_cache *cachep;
2959 unsigned int pool_size;
2960 unsigned int front_pad;
2965 if (type == DM_TYPE_BIO_BASED) {
2967 pool_size = dm_get_reserved_bio_based_ios();
2968 front_pad = roundup(per_bio_data_size, __alignof__(struct dm_target_io)) + offsetof(struct dm_target_io, clone);
2969 } else if (type == DM_TYPE_REQUEST_BASED) {
2970 cachep = _rq_tio_cache;
2971 pool_size = dm_get_reserved_rq_based_ios();
2972 front_pad = offsetof(struct dm_rq_clone_bio_info, clone);
2973 /* per_bio_data_size is not used. See __bind_mempools(). */
2974 WARN_ON(per_bio_data_size != 0);
2978 pools->io_pool = mempool_create_slab_pool(pool_size, cachep);
2979 if (!pools->io_pool)
2982 pools->bs = bioset_create(pool_size, front_pad);
2986 if (integrity && bioset_integrity_create(pools->bs, pool_size))
2992 dm_free_md_mempools(pools);
2997 void dm_free_md_mempools(struct dm_md_mempools *pools)
3003 mempool_destroy(pools->io_pool);
3006 bioset_free(pools->bs);
3011 static const struct block_device_operations dm_blk_dops = {
3012 .open = dm_blk_open,
3013 .release = dm_blk_close,
3014 .ioctl = dm_blk_ioctl,
3015 .getgeo = dm_blk_getgeo,
3016 .owner = THIS_MODULE
3019 EXPORT_SYMBOL(dm_get_mapinfo);
3024 module_init(dm_init);
3025 module_exit(dm_exit);
3027 module_param(major, uint, 0);
3028 MODULE_PARM_DESC(major, "The major number of the device mapper");
3030 module_param(reserved_bio_based_ios, uint, S_IRUGO | S_IWUSR);
3031 MODULE_PARM_DESC(reserved_bio_based_ios, "Reserved IOs in bio-based mempools");
3033 module_param(reserved_rq_based_ios, uint, S_IRUGO | S_IWUSR);
3034 MODULE_PARM_DESC(reserved_rq_based_ios, "Reserved IOs in request-based mempools");
3036 MODULE_DESCRIPTION(DM_NAME " driver");
3037 MODULE_AUTHOR("Joe Thornber <dm-devel@redhat.com>");
3038 MODULE_LICENSE("GPL");