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);
54 * One of these is allocated per bio.
57 struct mapped_device *md;
61 unsigned long start_time;
62 spinlock_t endio_lock;
63 struct dm_stats_aux stats_aux;
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 - the bio clones we allocate are embedded in these
82 * We allocate these with bio_alloc_bioset, using the front_pad parameter when
83 * the bioset is created - this means the bio has to come at the end of the
86 struct dm_rq_clone_bio_info {
88 struct dm_rq_target_io *tio;
92 union map_info *dm_get_mapinfo(struct bio *bio)
94 if (bio && bio->bi_private)
95 return &((struct dm_target_io *)bio->bi_private)->info;
99 union map_info *dm_get_rq_mapinfo(struct request *rq)
101 if (rq && rq->end_io_data)
102 return &((struct dm_rq_target_io *)rq->end_io_data)->info;
105 EXPORT_SYMBOL_GPL(dm_get_rq_mapinfo);
107 #define MINOR_ALLOCED ((void *)-1)
110 * Bits for the md->flags field.
112 #define DMF_BLOCK_IO_FOR_SUSPEND 0
113 #define DMF_SUSPENDED 1
115 #define DMF_FREEING 3
116 #define DMF_DELETING 4
117 #define DMF_NOFLUSH_SUSPENDING 5
118 #define DMF_MERGE_IS_OPTIONAL 6
121 * A dummy definition to make RCU happy.
122 * struct dm_table should never be dereferenced in this file.
129 * Work processed by per-device workqueue.
131 struct mapped_device {
132 struct srcu_struct io_barrier;
133 struct mutex suspend_lock;
138 * The current mapping.
139 * Use dm_get_live_table{_fast} or take suspend_lock for
142 struct dm_table *map;
146 struct request_queue *queue;
148 /* Protect queue and type against concurrent access. */
149 struct mutex type_lock;
151 struct target_type *immutable_target_type;
153 struct gendisk *disk;
159 * A list of ios that arrived while we were suspended.
162 wait_queue_head_t wait;
163 struct work_struct work;
164 struct bio_list deferred;
165 spinlock_t deferred_lock;
168 * Processing queue (flush)
170 struct workqueue_struct *wq;
173 * io objects are allocated from here.
183 wait_queue_head_t eventq;
185 struct list_head uevent_list;
186 spinlock_t uevent_lock; /* Protect access to uevent_list */
189 * freeze/thaw support require holding onto a super block
191 struct super_block *frozen_sb;
192 struct block_device *bdev;
194 /* forced geometry settings */
195 struct hd_geometry geometry;
200 /* zero-length flush that will be cloned and submitted to targets */
201 struct bio flush_bio;
203 struct dm_stats stats;
207 * For mempools pre-allocation at the table loading time.
209 struct dm_md_mempools {
214 #define RESERVED_BIO_BASED_IOS 16
215 #define RESERVED_REQUEST_BASED_IOS 256
216 #define RESERVED_MAX_IOS 1024
217 static struct kmem_cache *_io_cache;
218 static struct kmem_cache *_rq_tio_cache;
221 * Bio-based DM's mempools' reserved IOs set by the user.
223 static unsigned reserved_bio_based_ios = RESERVED_BIO_BASED_IOS;
226 * Request-based DM's mempools' reserved IOs set by the user.
228 static unsigned reserved_rq_based_ios = RESERVED_REQUEST_BASED_IOS;
230 static unsigned __dm_get_reserved_ios(unsigned *reserved_ios,
231 unsigned def, unsigned max)
233 unsigned ios = ACCESS_ONCE(*reserved_ios);
234 unsigned modified_ios = 0;
242 (void)cmpxchg(reserved_ios, ios, modified_ios);
249 unsigned dm_get_reserved_bio_based_ios(void)
251 return __dm_get_reserved_ios(&reserved_bio_based_ios,
252 RESERVED_BIO_BASED_IOS, RESERVED_MAX_IOS);
254 EXPORT_SYMBOL_GPL(dm_get_reserved_bio_based_ios);
256 unsigned dm_get_reserved_rq_based_ios(void)
258 return __dm_get_reserved_ios(&reserved_rq_based_ios,
259 RESERVED_REQUEST_BASED_IOS, RESERVED_MAX_IOS);
261 EXPORT_SYMBOL_GPL(dm_get_reserved_rq_based_ios);
263 static int __init local_init(void)
267 /* allocate a slab for the dm_ios */
268 _io_cache = KMEM_CACHE(dm_io, 0);
272 _rq_tio_cache = KMEM_CACHE(dm_rq_target_io, 0);
274 goto out_free_io_cache;
276 r = dm_uevent_init();
278 goto out_free_rq_tio_cache;
281 r = register_blkdev(_major, _name);
283 goto out_uevent_exit;
292 out_free_rq_tio_cache:
293 kmem_cache_destroy(_rq_tio_cache);
295 kmem_cache_destroy(_io_cache);
300 static void local_exit(void)
302 kmem_cache_destroy(_rq_tio_cache);
303 kmem_cache_destroy(_io_cache);
304 unregister_blkdev(_major, _name);
309 DMINFO("cleaned up");
312 static int (*_inits[])(void) __initdata = {
323 static void (*_exits[])(void) = {
334 static int __init dm_init(void)
336 const int count = ARRAY_SIZE(_inits);
340 for (i = 0; i < count; i++) {
355 static void __exit dm_exit(void)
357 int i = ARRAY_SIZE(_exits);
363 * Should be empty by this point.
365 idr_destroy(&_minor_idr);
369 * Block device functions
371 int dm_deleting_md(struct mapped_device *md)
373 return test_bit(DMF_DELETING, &md->flags);
376 static int dm_blk_open(struct block_device *bdev, fmode_t mode)
378 struct mapped_device *md;
380 spin_lock(&_minor_lock);
382 md = bdev->bd_disk->private_data;
386 if (test_bit(DMF_FREEING, &md->flags) ||
387 dm_deleting_md(md)) {
393 atomic_inc(&md->open_count);
396 spin_unlock(&_minor_lock);
398 return md ? 0 : -ENXIO;
401 static void dm_blk_close(struct gendisk *disk, fmode_t mode)
403 struct mapped_device *md = disk->private_data;
405 spin_lock(&_minor_lock);
407 atomic_dec(&md->open_count);
410 spin_unlock(&_minor_lock);
413 int dm_open_count(struct mapped_device *md)
415 return atomic_read(&md->open_count);
419 * Guarantees nothing is using the device before it's deleted.
421 int dm_lock_for_deletion(struct mapped_device *md)
425 spin_lock(&_minor_lock);
427 if (dm_open_count(md))
430 set_bit(DMF_DELETING, &md->flags);
432 spin_unlock(&_minor_lock);
437 sector_t dm_get_size(struct mapped_device *md)
439 return get_capacity(md->disk);
442 struct dm_stats *dm_get_stats(struct mapped_device *md)
447 static int dm_blk_getgeo(struct block_device *bdev, struct hd_geometry *geo)
449 struct mapped_device *md = bdev->bd_disk->private_data;
451 return dm_get_geometry(md, geo);
454 static int dm_blk_ioctl(struct block_device *bdev, fmode_t mode,
455 unsigned int cmd, unsigned long arg)
457 struct mapped_device *md = bdev->bd_disk->private_data;
459 struct dm_table *map;
460 struct dm_target *tgt;
464 map = dm_get_live_table(md, &srcu_idx);
466 if (!map || !dm_table_get_size(map))
469 /* We only support devices that have a single target */
470 if (dm_table_get_num_targets(map) != 1)
473 tgt = dm_table_get_target(map, 0);
475 if (dm_suspended_md(md)) {
480 if (tgt->type->ioctl)
481 r = tgt->type->ioctl(tgt, cmd, arg);
484 dm_put_live_table(md, srcu_idx);
486 if (r == -ENOTCONN) {
494 static struct dm_io *alloc_io(struct mapped_device *md)
496 return mempool_alloc(md->io_pool, GFP_NOIO);
499 static void free_io(struct mapped_device *md, struct dm_io *io)
501 mempool_free(io, md->io_pool);
504 static void free_tio(struct mapped_device *md, struct dm_target_io *tio)
506 bio_put(&tio->clone);
509 static struct dm_rq_target_io *alloc_rq_tio(struct mapped_device *md,
512 return mempool_alloc(md->io_pool, gfp_mask);
515 static void free_rq_tio(struct dm_rq_target_io *tio)
517 mempool_free(tio, tio->md->io_pool);
520 static int md_in_flight(struct mapped_device *md)
522 return atomic_read(&md->pending[READ]) +
523 atomic_read(&md->pending[WRITE]);
526 static void start_io_acct(struct dm_io *io)
528 struct mapped_device *md = io->md;
529 struct bio *bio = io->bio;
531 int rw = bio_data_dir(bio);
533 io->start_time = jiffies;
535 cpu = part_stat_lock();
536 part_round_stats(cpu, &dm_disk(md)->part0);
538 atomic_set(&dm_disk(md)->part0.in_flight[rw],
539 atomic_inc_return(&md->pending[rw]));
541 if (unlikely(dm_stats_used(&md->stats)))
542 dm_stats_account_io(&md->stats, bio->bi_rw, bio->bi_sector,
543 bio_sectors(bio), false, 0, &io->stats_aux);
546 static void end_io_acct(struct dm_io *io)
548 struct mapped_device *md = io->md;
549 struct bio *bio = io->bio;
550 unsigned long duration = jiffies - io->start_time;
552 int rw = bio_data_dir(bio);
554 cpu = part_stat_lock();
555 part_round_stats(cpu, &dm_disk(md)->part0);
556 part_stat_add(cpu, &dm_disk(md)->part0, ticks[rw], duration);
559 if (unlikely(dm_stats_used(&md->stats)))
560 dm_stats_account_io(&md->stats, bio->bi_rw, bio->bi_sector,
561 bio_sectors(bio), true, duration, &io->stats_aux);
564 * After this is decremented the bio must not be touched if it is
567 pending = atomic_dec_return(&md->pending[rw]);
568 atomic_set(&dm_disk(md)->part0.in_flight[rw], pending);
569 pending += atomic_read(&md->pending[rw^0x1]);
571 /* nudge anyone waiting on suspend queue */
577 * Add the bio to the list of deferred io.
579 static void queue_io(struct mapped_device *md, struct bio *bio)
583 spin_lock_irqsave(&md->deferred_lock, flags);
584 bio_list_add(&md->deferred, bio);
585 spin_unlock_irqrestore(&md->deferred_lock, flags);
586 queue_work(md->wq, &md->work);
590 * Everyone (including functions in this file), should use this
591 * function to access the md->map field, and make sure they call
592 * dm_put_live_table() when finished.
594 struct dm_table *dm_get_live_table(struct mapped_device *md, int *srcu_idx) __acquires(md->io_barrier)
596 *srcu_idx = srcu_read_lock(&md->io_barrier);
598 return srcu_dereference(md->map, &md->io_barrier);
601 void dm_put_live_table(struct mapped_device *md, int srcu_idx) __releases(md->io_barrier)
603 srcu_read_unlock(&md->io_barrier, srcu_idx);
606 void dm_sync_table(struct mapped_device *md)
608 synchronize_srcu(&md->io_barrier);
609 synchronize_rcu_expedited();
613 * A fast alternative to dm_get_live_table/dm_put_live_table.
614 * The caller must not block between these two functions.
616 static struct dm_table *dm_get_live_table_fast(struct mapped_device *md) __acquires(RCU)
619 return rcu_dereference(md->map);
622 static void dm_put_live_table_fast(struct mapped_device *md) __releases(RCU)
628 * Get the geometry associated with a dm device
630 int dm_get_geometry(struct mapped_device *md, struct hd_geometry *geo)
638 * Set the geometry of a device.
640 int dm_set_geometry(struct mapped_device *md, struct hd_geometry *geo)
642 sector_t sz = (sector_t)geo->cylinders * geo->heads * geo->sectors;
644 if (geo->start > sz) {
645 DMWARN("Start sector is beyond the geometry limits.");
654 /*-----------------------------------------------------------------
656 * A more elegant soln is in the works that uses the queue
657 * merge fn, unfortunately there are a couple of changes to
658 * the block layer that I want to make for this. So in the
659 * interests of getting something for people to use I give
660 * you this clearly demarcated crap.
661 *---------------------------------------------------------------*/
663 static int __noflush_suspending(struct mapped_device *md)
665 return test_bit(DMF_NOFLUSH_SUSPENDING, &md->flags);
669 * Decrements the number of outstanding ios that a bio has been
670 * cloned into, completing the original io if necc.
672 static void dec_pending(struct dm_io *io, int error)
677 struct mapped_device *md = io->md;
679 /* Push-back supersedes any I/O errors */
680 if (unlikely(error)) {
681 spin_lock_irqsave(&io->endio_lock, flags);
682 if (!(io->error > 0 && __noflush_suspending(md)))
684 spin_unlock_irqrestore(&io->endio_lock, flags);
687 if (atomic_dec_and_test(&io->io_count)) {
688 if (io->error == DM_ENDIO_REQUEUE) {
690 * Target requested pushing back the I/O.
692 spin_lock_irqsave(&md->deferred_lock, flags);
693 if (__noflush_suspending(md))
694 bio_list_add_head(&md->deferred, io->bio);
696 /* noflush suspend was interrupted. */
698 spin_unlock_irqrestore(&md->deferred_lock, flags);
701 io_error = io->error;
706 if (io_error == DM_ENDIO_REQUEUE)
709 if ((bio->bi_rw & REQ_FLUSH) && bio->bi_size) {
711 * Preflush done for flush with data, reissue
714 bio->bi_rw &= ~REQ_FLUSH;
717 /* done with normal IO or empty flush */
718 trace_block_bio_complete(md->queue, bio, io_error);
719 bio_endio(bio, io_error);
724 static void clone_endio(struct bio *bio, int error)
727 struct dm_target_io *tio = bio->bi_private;
728 struct dm_io *io = tio->io;
729 struct mapped_device *md = tio->io->md;
730 dm_endio_fn endio = tio->ti->type->end_io;
732 if (!bio_flagged(bio, BIO_UPTODATE) && !error)
736 r = endio(tio->ti, bio, error);
737 if (r < 0 || r == DM_ENDIO_REQUEUE)
739 * error and requeue request are handled
743 else if (r == DM_ENDIO_INCOMPLETE)
744 /* The target will handle the io */
747 DMWARN("unimplemented target endio return value: %d", r);
753 dec_pending(io, error);
757 * Partial completion handling for request-based dm
759 static void end_clone_bio(struct bio *clone, int error)
761 struct dm_rq_clone_bio_info *info = clone->bi_private;
762 struct dm_rq_target_io *tio = info->tio;
763 struct bio *bio = info->orig;
764 unsigned int nr_bytes = info->orig->bi_size;
770 * An error has already been detected on the request.
771 * Once error occurred, just let clone->end_io() handle
777 * Don't notice the error to the upper layer yet.
778 * The error handling decision is made by the target driver,
779 * when the request is completed.
786 * I/O for the bio successfully completed.
787 * Notice the data completion to the upper layer.
791 * bios are processed from the head of the list.
792 * So the completing bio should always be rq->bio.
793 * If it's not, something wrong is happening.
795 if (tio->orig->bio != bio)
796 DMERR("bio completion is going in the middle of the request");
799 * Update the original request.
800 * Do not use blk_end_request() here, because it may complete
801 * the original request before the clone, and break the ordering.
803 blk_update_request(tio->orig, 0, nr_bytes);
807 * Don't touch any member of the md after calling this function because
808 * the md may be freed in dm_put() at the end of this function.
809 * Or do dm_get() before calling this function and dm_put() later.
811 static void rq_completed(struct mapped_device *md, int rw, int run_queue)
813 atomic_dec(&md->pending[rw]);
815 /* nudge anyone waiting on suspend queue */
816 if (!md_in_flight(md))
820 * Run this off this callpath, as drivers could invoke end_io while
821 * inside their request_fn (and holding the queue lock). Calling
822 * back into ->request_fn() could deadlock attempting to grab the
826 blk_run_queue_async(md->queue);
829 * dm_put() must be at the end of this function. See the comment above
834 static void free_rq_clone(struct request *clone)
836 struct dm_rq_target_io *tio = clone->end_io_data;
838 blk_rq_unprep_clone(clone);
843 * Complete the clone and the original request.
844 * Must be called without queue lock.
846 static void dm_end_request(struct request *clone, int error)
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;
853 if (rq->cmd_type == REQ_TYPE_BLOCK_PC) {
854 rq->errors = clone->errors;
855 rq->resid_len = clone->resid_len;
859 * We are using the sense buffer of the original
861 * So setting the length of the sense data is enough.
863 rq->sense_len = clone->sense_len;
866 free_rq_clone(clone);
867 blk_end_request_all(rq, error);
868 rq_completed(md, rw, true);
871 static void dm_unprep_request(struct request *rq)
873 struct request *clone = rq->special;
876 rq->cmd_flags &= ~REQ_DONTPREP;
878 free_rq_clone(clone);
882 * Requeue the original request of a clone.
884 void dm_requeue_unmapped_request(struct request *clone)
886 int rw = rq_data_dir(clone);
887 struct dm_rq_target_io *tio = clone->end_io_data;
888 struct mapped_device *md = tio->md;
889 struct request *rq = tio->orig;
890 struct request_queue *q = rq->q;
893 dm_unprep_request(rq);
895 spin_lock_irqsave(q->queue_lock, flags);
896 blk_requeue_request(q, rq);
897 spin_unlock_irqrestore(q->queue_lock, flags);
899 rq_completed(md, rw, 0);
901 EXPORT_SYMBOL_GPL(dm_requeue_unmapped_request);
903 static void __stop_queue(struct request_queue *q)
908 static void stop_queue(struct request_queue *q)
912 spin_lock_irqsave(q->queue_lock, flags);
914 spin_unlock_irqrestore(q->queue_lock, flags);
917 static void __start_queue(struct request_queue *q)
919 if (blk_queue_stopped(q))
923 static void start_queue(struct request_queue *q)
927 spin_lock_irqsave(q->queue_lock, flags);
929 spin_unlock_irqrestore(q->queue_lock, flags);
932 static void dm_done(struct request *clone, int error, bool mapped)
935 struct dm_rq_target_io *tio = clone->end_io_data;
936 dm_request_endio_fn rq_end_io = NULL;
939 rq_end_io = tio->ti->type->rq_end_io;
941 if (mapped && rq_end_io)
942 r = rq_end_io(tio->ti, clone, error, &tio->info);
946 /* The target wants to complete the I/O */
947 dm_end_request(clone, r);
948 else if (r == DM_ENDIO_INCOMPLETE)
949 /* The target will handle the I/O */
951 else if (r == DM_ENDIO_REQUEUE)
952 /* The target wants to requeue the I/O */
953 dm_requeue_unmapped_request(clone);
955 DMWARN("unimplemented target endio return value: %d", r);
961 * Request completion handler for request-based dm
963 static void dm_softirq_done(struct request *rq)
966 struct request *clone = rq->completion_data;
967 struct dm_rq_target_io *tio = clone->end_io_data;
969 if (rq->cmd_flags & REQ_FAILED)
972 dm_done(clone, tio->error, mapped);
976 * Complete the clone and the original request with the error status
977 * through softirq context.
979 static void dm_complete_request(struct request *clone, int error)
981 struct dm_rq_target_io *tio = clone->end_io_data;
982 struct request *rq = tio->orig;
985 rq->completion_data = clone;
986 blk_complete_request(rq);
990 * Complete the not-mapped clone and the original request with the error status
991 * through softirq context.
992 * Target's rq_end_io() function isn't called.
993 * This may be used when the target's map_rq() function fails.
995 void dm_kill_unmapped_request(struct request *clone, int error)
997 struct dm_rq_target_io *tio = clone->end_io_data;
998 struct request *rq = tio->orig;
1000 rq->cmd_flags |= REQ_FAILED;
1001 dm_complete_request(clone, error);
1003 EXPORT_SYMBOL_GPL(dm_kill_unmapped_request);
1006 * Called with the queue lock held
1008 static void end_clone_request(struct request *clone, int error)
1011 * For just cleaning up the information of the queue in which
1012 * the clone was dispatched.
1013 * The clone is *NOT* freed actually here because it is alloced from
1014 * dm own mempool and REQ_ALLOCED isn't set in clone->cmd_flags.
1016 __blk_put_request(clone->q, clone);
1019 * Actual request completion is done in a softirq context which doesn't
1020 * hold the queue lock. Otherwise, deadlock could occur because:
1021 * - another request may be submitted by the upper level driver
1022 * of the stacking during the completion
1023 * - the submission which requires queue lock may be done
1024 * against this queue
1026 dm_complete_request(clone, error);
1030 * Return maximum size of I/O possible at the supplied sector up to the current
1033 static sector_t max_io_len_target_boundary(sector_t sector, struct dm_target *ti)
1035 sector_t target_offset = dm_target_offset(ti, sector);
1037 return ti->len - target_offset;
1040 static sector_t max_io_len(sector_t sector, struct dm_target *ti)
1042 sector_t len = max_io_len_target_boundary(sector, ti);
1043 sector_t offset, max_len;
1046 * Does the target need to split even further?
1048 if (ti->max_io_len) {
1049 offset = dm_target_offset(ti, sector);
1050 if (unlikely(ti->max_io_len & (ti->max_io_len - 1)))
1051 max_len = sector_div(offset, ti->max_io_len);
1053 max_len = offset & (ti->max_io_len - 1);
1054 max_len = ti->max_io_len - max_len;
1063 int dm_set_target_max_io_len(struct dm_target *ti, sector_t len)
1065 if (len > UINT_MAX) {
1066 DMERR("Specified maximum size of target IO (%llu) exceeds limit (%u)",
1067 (unsigned long long)len, UINT_MAX);
1068 ti->error = "Maximum size of target IO is too large";
1072 ti->max_io_len = (uint32_t) len;
1076 EXPORT_SYMBOL_GPL(dm_set_target_max_io_len);
1078 static void __map_bio(struct dm_target_io *tio)
1082 struct mapped_device *md;
1083 struct bio *clone = &tio->clone;
1084 struct dm_target *ti = tio->ti;
1086 clone->bi_end_io = clone_endio;
1087 clone->bi_private = tio;
1090 * Map the clone. If r == 0 we don't need to do
1091 * anything, the target has assumed ownership of
1094 atomic_inc(&tio->io->io_count);
1095 sector = clone->bi_sector;
1096 r = ti->type->map(ti, clone);
1097 if (r == DM_MAPIO_REMAPPED) {
1098 /* the bio has been remapped so dispatch it */
1100 trace_block_bio_remap(bdev_get_queue(clone->bi_bdev), clone,
1101 tio->io->bio->bi_bdev->bd_dev, sector);
1103 generic_make_request(clone);
1104 } else if (r < 0 || r == DM_MAPIO_REQUEUE) {
1105 /* error the io and bail out, or requeue it if needed */
1107 dec_pending(tio->io, r);
1110 DMWARN("unimplemented target map return value: %d", r);
1116 struct mapped_device *md;
1117 struct dm_table *map;
1121 sector_t sector_count;
1125 static void bio_setup_sector(struct bio *bio, sector_t sector, sector_t len)
1127 bio->bi_sector = sector;
1128 bio->bi_size = to_bytes(len);
1131 static void bio_setup_bv(struct bio *bio, unsigned short idx, unsigned short bv_count)
1134 bio->bi_vcnt = idx + bv_count;
1135 bio->bi_flags &= ~(1 << BIO_SEG_VALID);
1138 static void clone_bio_integrity(struct bio *bio, struct bio *clone,
1139 unsigned short idx, unsigned len, unsigned offset,
1142 if (!bio_integrity(bio))
1145 bio_integrity_clone(clone, bio, GFP_NOIO);
1148 bio_integrity_trim(clone, bio_sector_offset(bio, idx, offset), len);
1152 * Creates a little bio that just does part of a bvec.
1154 static void clone_split_bio(struct dm_target_io *tio, struct bio *bio,
1155 sector_t sector, unsigned short idx,
1156 unsigned offset, unsigned len)
1158 struct bio *clone = &tio->clone;
1159 struct bio_vec *bv = bio->bi_io_vec + idx;
1161 *clone->bi_io_vec = *bv;
1163 bio_setup_sector(clone, sector, len);
1165 clone->bi_bdev = bio->bi_bdev;
1166 clone->bi_rw = bio->bi_rw;
1168 clone->bi_io_vec->bv_offset = offset;
1169 clone->bi_io_vec->bv_len = clone->bi_size;
1170 clone->bi_flags |= 1 << BIO_CLONED;
1172 clone_bio_integrity(bio, clone, idx, len, offset, 1);
1176 * Creates a bio that consists of range of complete bvecs.
1178 static void clone_bio(struct dm_target_io *tio, struct bio *bio,
1179 sector_t sector, unsigned short idx,
1180 unsigned short bv_count, unsigned len)
1182 struct bio *clone = &tio->clone;
1185 __bio_clone(clone, bio);
1186 bio_setup_sector(clone, sector, len);
1187 bio_setup_bv(clone, idx, bv_count);
1189 if (idx != bio->bi_idx || clone->bi_size < bio->bi_size)
1191 clone_bio_integrity(bio, clone, idx, len, 0, trim);
1194 static struct dm_target_io *alloc_tio(struct clone_info *ci,
1195 struct dm_target *ti, int nr_iovecs,
1196 unsigned target_bio_nr)
1198 struct dm_target_io *tio;
1201 clone = bio_alloc_bioset(GFP_NOIO, nr_iovecs, ci->md->bs);
1202 tio = container_of(clone, struct dm_target_io, clone);
1206 memset(&tio->info, 0, sizeof(tio->info));
1207 tio->target_bio_nr = target_bio_nr;
1212 static void __clone_and_map_simple_bio(struct clone_info *ci,
1213 struct dm_target *ti,
1214 unsigned target_bio_nr, sector_t len)
1216 struct dm_target_io *tio = alloc_tio(ci, ti, ci->bio->bi_max_vecs, target_bio_nr);
1217 struct bio *clone = &tio->clone;
1220 * Discard requests require the bio's inline iovecs be initialized.
1221 * ci->bio->bi_max_vecs is BIO_INLINE_VECS anyway, for both flush
1222 * and discard, so no need for concern about wasted bvec allocations.
1224 __bio_clone(clone, ci->bio);
1226 bio_setup_sector(clone, ci->sector, len);
1231 static void __send_duplicate_bios(struct clone_info *ci, struct dm_target *ti,
1232 unsigned num_bios, sector_t len)
1234 unsigned target_bio_nr;
1236 for (target_bio_nr = 0; target_bio_nr < num_bios; target_bio_nr++)
1237 __clone_and_map_simple_bio(ci, ti, target_bio_nr, len);
1240 static int __send_empty_flush(struct clone_info *ci)
1242 unsigned target_nr = 0;
1243 struct dm_target *ti;
1245 BUG_ON(bio_has_data(ci->bio));
1246 while ((ti = dm_table_get_target(ci->map, target_nr++)))
1247 __send_duplicate_bios(ci, ti, ti->num_flush_bios, 0);
1252 static void __clone_and_map_data_bio(struct clone_info *ci, struct dm_target *ti,
1253 sector_t sector, int nr_iovecs,
1254 unsigned short idx, unsigned short bv_count,
1255 unsigned offset, unsigned len,
1256 unsigned split_bvec)
1258 struct bio *bio = ci->bio;
1259 struct dm_target_io *tio;
1260 unsigned target_bio_nr;
1261 unsigned num_target_bios = 1;
1264 * Does the target want to receive duplicate copies of the bio?
1266 if (bio_data_dir(bio) == WRITE && ti->num_write_bios)
1267 num_target_bios = ti->num_write_bios(ti, bio);
1269 for (target_bio_nr = 0; target_bio_nr < num_target_bios; target_bio_nr++) {
1270 tio = alloc_tio(ci, ti, nr_iovecs, target_bio_nr);
1272 clone_split_bio(tio, bio, sector, idx, offset, len);
1274 clone_bio(tio, bio, sector, idx, bv_count, len);
1279 typedef unsigned (*get_num_bios_fn)(struct dm_target *ti);
1281 static unsigned get_num_discard_bios(struct dm_target *ti)
1283 return ti->num_discard_bios;
1286 static unsigned get_num_write_same_bios(struct dm_target *ti)
1288 return ti->num_write_same_bios;
1291 typedef bool (*is_split_required_fn)(struct dm_target *ti);
1293 static bool is_split_required_for_discard(struct dm_target *ti)
1295 return ti->split_discard_bios;
1298 static int __send_changing_extent_only(struct clone_info *ci,
1299 get_num_bios_fn get_num_bios,
1300 is_split_required_fn is_split_required)
1302 struct dm_target *ti;
1307 ti = dm_table_find_target(ci->map, ci->sector);
1308 if (!dm_target_is_valid(ti))
1312 * Even though the device advertised support for this type of
1313 * request, that does not mean every target supports it, and
1314 * reconfiguration might also have changed that since the
1315 * check was performed.
1317 num_bios = get_num_bios ? get_num_bios(ti) : 0;
1321 if (is_split_required && !is_split_required(ti))
1322 len = min(ci->sector_count, max_io_len_target_boundary(ci->sector, ti));
1324 len = min(ci->sector_count, max_io_len(ci->sector, ti));
1326 __send_duplicate_bios(ci, ti, num_bios, len);
1329 } while (ci->sector_count -= len);
1334 static int __send_discard(struct clone_info *ci)
1336 return __send_changing_extent_only(ci, get_num_discard_bios,
1337 is_split_required_for_discard);
1340 static int __send_write_same(struct clone_info *ci)
1342 return __send_changing_extent_only(ci, get_num_write_same_bios, NULL);
1346 * Find maximum number of sectors / bvecs we can process with a single bio.
1348 static sector_t __len_within_target(struct clone_info *ci, sector_t max, int *idx)
1350 struct bio *bio = ci->bio;
1351 sector_t bv_len, total_len = 0;
1353 for (*idx = ci->idx; max && (*idx < bio->bi_vcnt); (*idx)++) {
1354 bv_len = to_sector(bio->bi_io_vec[*idx].bv_len);
1360 total_len += bv_len;
1366 static int __split_bvec_across_targets(struct clone_info *ci,
1367 struct dm_target *ti, sector_t max)
1369 struct bio *bio = ci->bio;
1370 struct bio_vec *bv = bio->bi_io_vec + ci->idx;
1371 sector_t remaining = to_sector(bv->bv_len);
1372 unsigned offset = 0;
1377 ti = dm_table_find_target(ci->map, ci->sector);
1378 if (!dm_target_is_valid(ti))
1381 max = max_io_len(ci->sector, ti);
1384 len = min(remaining, max);
1386 __clone_and_map_data_bio(ci, ti, ci->sector, 1, ci->idx, 0,
1387 bv->bv_offset + offset, len, 1);
1390 ci->sector_count -= len;
1391 offset += to_bytes(len);
1392 } while (remaining -= len);
1400 * Select the correct strategy for processing a non-flush bio.
1402 static int __split_and_process_non_flush(struct clone_info *ci)
1404 struct bio *bio = ci->bio;
1405 struct dm_target *ti;
1409 if (unlikely(bio->bi_rw & REQ_DISCARD))
1410 return __send_discard(ci);
1411 else if (unlikely(bio->bi_rw & REQ_WRITE_SAME))
1412 return __send_write_same(ci);
1414 ti = dm_table_find_target(ci->map, ci->sector);
1415 if (!dm_target_is_valid(ti))
1418 max = max_io_len(ci->sector, ti);
1421 * Optimise for the simple case where we can do all of
1422 * the remaining io with a single clone.
1424 if (ci->sector_count <= max) {
1425 __clone_and_map_data_bio(ci, ti, ci->sector, bio->bi_max_vecs,
1426 ci->idx, bio->bi_vcnt - ci->idx, 0,
1427 ci->sector_count, 0);
1428 ci->sector_count = 0;
1433 * There are some bvecs that don't span targets.
1434 * Do as many of these as possible.
1436 if (to_sector(bio->bi_io_vec[ci->idx].bv_len) <= max) {
1437 len = __len_within_target(ci, max, &idx);
1439 __clone_and_map_data_bio(ci, ti, ci->sector, bio->bi_max_vecs,
1440 ci->idx, idx - ci->idx, 0, len, 0);
1443 ci->sector_count -= len;
1450 * Handle a bvec that must be split between two or more targets.
1452 return __split_bvec_across_targets(ci, ti, max);
1456 * Entry point to split a bio into clones and submit them to the targets.
1458 static void __split_and_process_bio(struct mapped_device *md,
1459 struct dm_table *map, struct bio *bio)
1461 struct clone_info ci;
1464 if (unlikely(!map)) {
1471 ci.io = alloc_io(md);
1473 atomic_set(&ci.io->io_count, 1);
1476 spin_lock_init(&ci.io->endio_lock);
1477 ci.sector = bio->bi_sector;
1478 ci.idx = bio->bi_idx;
1480 start_io_acct(ci.io);
1482 if (bio->bi_rw & REQ_FLUSH) {
1483 ci.bio = &ci.md->flush_bio;
1484 ci.sector_count = 0;
1485 error = __send_empty_flush(&ci);
1486 /* dec_pending submits any data associated with flush */
1489 ci.sector_count = bio_sectors(bio);
1490 while (ci.sector_count && !error)
1491 error = __split_and_process_non_flush(&ci);
1494 /* drop the extra reference count */
1495 dec_pending(ci.io, error);
1497 /*-----------------------------------------------------------------
1499 *---------------------------------------------------------------*/
1501 static int dm_merge_bvec(struct request_queue *q,
1502 struct bvec_merge_data *bvm,
1503 struct bio_vec *biovec)
1505 struct mapped_device *md = q->queuedata;
1506 struct dm_table *map = dm_get_live_table_fast(md);
1507 struct dm_target *ti;
1508 sector_t max_sectors;
1514 ti = dm_table_find_target(map, bvm->bi_sector);
1515 if (!dm_target_is_valid(ti))
1519 * Find maximum amount of I/O that won't need splitting
1521 max_sectors = min(max_io_len(bvm->bi_sector, ti),
1522 (sector_t) BIO_MAX_SECTORS);
1523 max_size = (max_sectors << SECTOR_SHIFT) - bvm->bi_size;
1528 * merge_bvec_fn() returns number of bytes
1529 * it can accept at this offset
1530 * max is precomputed maximal io size
1532 if (max_size && ti->type->merge)
1533 max_size = ti->type->merge(ti, bvm, biovec, max_size);
1535 * If the target doesn't support merge method and some of the devices
1536 * provided their merge_bvec method (we know this by looking at
1537 * queue_max_hw_sectors), then we can't allow bios with multiple vector
1538 * entries. So always set max_size to 0, and the code below allows
1541 else if (queue_max_hw_sectors(q) <= PAGE_SIZE >> 9)
1546 dm_put_live_table_fast(md);
1548 * Always allow an entire first page
1550 if (max_size <= biovec->bv_len && !(bvm->bi_size >> SECTOR_SHIFT))
1551 max_size = biovec->bv_len;
1557 * The request function that just remaps the bio built up by
1560 static void _dm_request(struct request_queue *q, struct bio *bio)
1562 int rw = bio_data_dir(bio);
1563 struct mapped_device *md = q->queuedata;
1566 struct dm_table *map;
1568 map = dm_get_live_table(md, &srcu_idx);
1570 cpu = part_stat_lock();
1571 part_stat_inc(cpu, &dm_disk(md)->part0, ios[rw]);
1572 part_stat_add(cpu, &dm_disk(md)->part0, sectors[rw], bio_sectors(bio));
1575 /* if we're suspended, we have to queue this io for later */
1576 if (unlikely(test_bit(DMF_BLOCK_IO_FOR_SUSPEND, &md->flags))) {
1577 dm_put_live_table(md, srcu_idx);
1579 if (bio_rw(bio) != READA)
1586 __split_and_process_bio(md, map, bio);
1587 dm_put_live_table(md, srcu_idx);
1591 int dm_request_based(struct mapped_device *md)
1593 return blk_queue_stackable(md->queue);
1596 static void dm_request(struct request_queue *q, struct bio *bio)
1598 struct mapped_device *md = q->queuedata;
1600 if (dm_request_based(md))
1601 blk_queue_bio(q, bio);
1603 _dm_request(q, bio);
1606 void dm_dispatch_request(struct request *rq)
1610 if (blk_queue_io_stat(rq->q))
1611 rq->cmd_flags |= REQ_IO_STAT;
1613 rq->start_time = jiffies;
1614 r = blk_insert_cloned_request(rq->q, rq);
1616 dm_complete_request(rq, r);
1618 EXPORT_SYMBOL_GPL(dm_dispatch_request);
1620 static int dm_rq_bio_constructor(struct bio *bio, struct bio *bio_orig,
1623 struct dm_rq_target_io *tio = data;
1624 struct dm_rq_clone_bio_info *info =
1625 container_of(bio, struct dm_rq_clone_bio_info, clone);
1627 info->orig = bio_orig;
1629 bio->bi_end_io = end_clone_bio;
1630 bio->bi_private = info;
1635 static int setup_clone(struct request *clone, struct request *rq,
1636 struct dm_rq_target_io *tio)
1640 r = blk_rq_prep_clone(clone, rq, tio->md->bs, GFP_ATOMIC,
1641 dm_rq_bio_constructor, tio);
1645 clone->cmd = rq->cmd;
1646 clone->cmd_len = rq->cmd_len;
1647 clone->sense = rq->sense;
1648 clone->buffer = rq->buffer;
1649 clone->end_io = end_clone_request;
1650 clone->end_io_data = tio;
1655 static struct request *clone_rq(struct request *rq, struct mapped_device *md,
1658 struct request *clone;
1659 struct dm_rq_target_io *tio;
1661 tio = alloc_rq_tio(md, gfp_mask);
1669 memset(&tio->info, 0, sizeof(tio->info));
1671 clone = &tio->clone;
1672 if (setup_clone(clone, rq, tio)) {
1682 * Called with the queue lock held.
1684 static int dm_prep_fn(struct request_queue *q, struct request *rq)
1686 struct mapped_device *md = q->queuedata;
1687 struct request *clone;
1689 if (unlikely(rq->special)) {
1690 DMWARN("Already has something in rq->special.");
1691 return BLKPREP_KILL;
1694 clone = clone_rq(rq, md, GFP_ATOMIC);
1696 return BLKPREP_DEFER;
1698 rq->special = clone;
1699 rq->cmd_flags |= REQ_DONTPREP;
1706 * 0 : the request has been processed (not requeued)
1707 * !0 : the request has been requeued
1709 static int map_request(struct dm_target *ti, struct request *clone,
1710 struct mapped_device *md)
1712 int r, requeued = 0;
1713 struct dm_rq_target_io *tio = clone->end_io_data;
1716 r = ti->type->map_rq(ti, clone, &tio->info);
1718 case DM_MAPIO_SUBMITTED:
1719 /* The target has taken the I/O to submit by itself later */
1721 case DM_MAPIO_REMAPPED:
1722 /* The target has remapped the I/O so dispatch it */
1723 trace_block_rq_remap(clone->q, clone, disk_devt(dm_disk(md)),
1724 blk_rq_pos(tio->orig));
1725 dm_dispatch_request(clone);
1727 case DM_MAPIO_REQUEUE:
1728 /* The target wants to requeue the I/O */
1729 dm_requeue_unmapped_request(clone);
1734 DMWARN("unimplemented target map return value: %d", r);
1738 /* The target wants to complete the I/O */
1739 dm_kill_unmapped_request(clone, r);
1746 static struct request *dm_start_request(struct mapped_device *md, struct request *orig)
1748 struct request *clone;
1750 blk_start_request(orig);
1751 clone = orig->special;
1752 atomic_inc(&md->pending[rq_data_dir(clone)]);
1755 * Hold the md reference here for the in-flight I/O.
1756 * We can't rely on the reference count by device opener,
1757 * because the device may be closed during the request completion
1758 * when all bios are completed.
1759 * See the comment in rq_completed() too.
1767 * q->request_fn for request-based dm.
1768 * Called with the queue lock held.
1770 static void dm_request_fn(struct request_queue *q)
1772 struct mapped_device *md = q->queuedata;
1774 struct dm_table *map = dm_get_live_table(md, &srcu_idx);
1775 struct dm_target *ti;
1776 struct request *rq, *clone;
1780 * For suspend, check blk_queue_stopped() and increment
1781 * ->pending within a single queue_lock not to increment the
1782 * number of in-flight I/Os after the queue is stopped in
1785 while (!blk_queue_stopped(q)) {
1786 rq = blk_peek_request(q);
1790 /* always use block 0 to find the target for flushes for now */
1792 if (!(rq->cmd_flags & REQ_FLUSH))
1793 pos = blk_rq_pos(rq);
1795 ti = dm_table_find_target(map, pos);
1796 if (!dm_target_is_valid(ti)) {
1798 * Must perform setup, that dm_done() requires,
1799 * before calling dm_kill_unmapped_request
1801 DMERR_LIMIT("request attempted access beyond the end of device");
1802 clone = dm_start_request(md, rq);
1803 dm_kill_unmapped_request(clone, -EIO);
1807 if (ti->type->busy && ti->type->busy(ti))
1810 clone = dm_start_request(md, rq);
1812 spin_unlock(q->queue_lock);
1813 if (map_request(ti, clone, md))
1816 BUG_ON(!irqs_disabled());
1817 spin_lock(q->queue_lock);
1823 BUG_ON(!irqs_disabled());
1824 spin_lock(q->queue_lock);
1827 blk_delay_queue(q, HZ / 10);
1829 dm_put_live_table(md, srcu_idx);
1832 int dm_underlying_device_busy(struct request_queue *q)
1834 return blk_lld_busy(q);
1836 EXPORT_SYMBOL_GPL(dm_underlying_device_busy);
1838 static int dm_lld_busy(struct request_queue *q)
1841 struct mapped_device *md = q->queuedata;
1842 struct dm_table *map = dm_get_live_table_fast(md);
1844 if (!map || test_bit(DMF_BLOCK_IO_FOR_SUSPEND, &md->flags))
1847 r = dm_table_any_busy_target(map);
1849 dm_put_live_table_fast(md);
1854 static int dm_any_congested(void *congested_data, int bdi_bits)
1857 struct mapped_device *md = congested_data;
1858 struct dm_table *map;
1860 if (!test_bit(DMF_BLOCK_IO_FOR_SUSPEND, &md->flags)) {
1861 map = dm_get_live_table_fast(md);
1864 * Request-based dm cares about only own queue for
1865 * the query about congestion status of request_queue
1867 if (dm_request_based(md))
1868 r = md->queue->backing_dev_info.state &
1871 r = dm_table_any_congested(map, bdi_bits);
1873 dm_put_live_table_fast(md);
1879 /*-----------------------------------------------------------------
1880 * An IDR is used to keep track of allocated minor numbers.
1881 *---------------------------------------------------------------*/
1882 static void free_minor(int minor)
1884 spin_lock(&_minor_lock);
1885 idr_remove(&_minor_idr, minor);
1886 spin_unlock(&_minor_lock);
1890 * See if the device with a specific minor # is free.
1892 static int specific_minor(int minor)
1896 if (minor >= (1 << MINORBITS))
1899 idr_preload(GFP_KERNEL);
1900 spin_lock(&_minor_lock);
1902 r = idr_alloc(&_minor_idr, MINOR_ALLOCED, minor, minor + 1, GFP_NOWAIT);
1904 spin_unlock(&_minor_lock);
1907 return r == -ENOSPC ? -EBUSY : r;
1911 static int next_free_minor(int *minor)
1915 idr_preload(GFP_KERNEL);
1916 spin_lock(&_minor_lock);
1918 r = idr_alloc(&_minor_idr, MINOR_ALLOCED, 0, 1 << MINORBITS, GFP_NOWAIT);
1920 spin_unlock(&_minor_lock);
1928 static const struct block_device_operations dm_blk_dops;
1930 static void dm_wq_work(struct work_struct *work);
1932 static void dm_init_md_queue(struct mapped_device *md)
1935 * Request-based dm devices cannot be stacked on top of bio-based dm
1936 * devices. The type of this dm device has not been decided yet.
1937 * The type is decided at the first table loading time.
1938 * To prevent problematic device stacking, clear the queue flag
1939 * for request stacking support until then.
1941 * This queue is new, so no concurrency on the queue_flags.
1943 queue_flag_clear_unlocked(QUEUE_FLAG_STACKABLE, md->queue);
1945 md->queue->queuedata = md;
1946 md->queue->backing_dev_info.congested_fn = dm_any_congested;
1947 md->queue->backing_dev_info.congested_data = md;
1948 blk_queue_make_request(md->queue, dm_request);
1949 blk_queue_bounce_limit(md->queue, BLK_BOUNCE_ANY);
1950 blk_queue_merge_bvec(md->queue, dm_merge_bvec);
1954 * Allocate and initialise a blank device with a given minor.
1956 static struct mapped_device *alloc_dev(int minor)
1959 struct mapped_device *md = kzalloc(sizeof(*md), GFP_KERNEL);
1963 DMWARN("unable to allocate device, out of memory.");
1967 if (!try_module_get(THIS_MODULE))
1968 goto bad_module_get;
1970 /* get a minor number for the dev */
1971 if (minor == DM_ANY_MINOR)
1972 r = next_free_minor(&minor);
1974 r = specific_minor(minor);
1978 r = init_srcu_struct(&md->io_barrier);
1980 goto bad_io_barrier;
1982 md->type = DM_TYPE_NONE;
1983 mutex_init(&md->suspend_lock);
1984 mutex_init(&md->type_lock);
1985 spin_lock_init(&md->deferred_lock);
1986 atomic_set(&md->holders, 1);
1987 atomic_set(&md->open_count, 0);
1988 atomic_set(&md->event_nr, 0);
1989 atomic_set(&md->uevent_seq, 0);
1990 INIT_LIST_HEAD(&md->uevent_list);
1991 spin_lock_init(&md->uevent_lock);
1993 md->queue = blk_alloc_queue(GFP_KERNEL);
1997 dm_init_md_queue(md);
1999 md->disk = alloc_disk(1);
2003 atomic_set(&md->pending[0], 0);
2004 atomic_set(&md->pending[1], 0);
2005 init_waitqueue_head(&md->wait);
2006 INIT_WORK(&md->work, dm_wq_work);
2007 init_waitqueue_head(&md->eventq);
2009 md->disk->major = _major;
2010 md->disk->first_minor = minor;
2011 md->disk->fops = &dm_blk_dops;
2012 md->disk->queue = md->queue;
2013 md->disk->private_data = md;
2014 sprintf(md->disk->disk_name, "dm-%d", minor);
2016 format_dev_t(md->name, MKDEV(_major, minor));
2018 md->wq = alloc_workqueue("kdmflush", WQ_MEM_RECLAIM, 0);
2022 md->bdev = bdget_disk(md->disk, 0);
2026 bio_init(&md->flush_bio);
2027 md->flush_bio.bi_bdev = md->bdev;
2028 md->flush_bio.bi_rw = WRITE_FLUSH;
2030 dm_stats_init(&md->stats);
2032 /* Populate the mapping, nobody knows we exist yet */
2033 spin_lock(&_minor_lock);
2034 old_md = idr_replace(&_minor_idr, md, minor);
2035 spin_unlock(&_minor_lock);
2037 BUG_ON(old_md != MINOR_ALLOCED);
2042 destroy_workqueue(md->wq);
2044 del_gendisk(md->disk);
2047 blk_cleanup_queue(md->queue);
2049 cleanup_srcu_struct(&md->io_barrier);
2053 module_put(THIS_MODULE);
2059 static void unlock_fs(struct mapped_device *md);
2061 static void free_dev(struct mapped_device *md)
2063 int minor = MINOR(disk_devt(md->disk));
2067 destroy_workqueue(md->wq);
2069 mempool_destroy(md->io_pool);
2071 bioset_free(md->bs);
2072 blk_integrity_unregister(md->disk);
2073 del_gendisk(md->disk);
2074 cleanup_srcu_struct(&md->io_barrier);
2077 spin_lock(&_minor_lock);
2078 md->disk->private_data = NULL;
2079 spin_unlock(&_minor_lock);
2082 blk_cleanup_queue(md->queue);
2083 dm_stats_cleanup(&md->stats);
2084 module_put(THIS_MODULE);
2088 static void __bind_mempools(struct mapped_device *md, struct dm_table *t)
2090 struct dm_md_mempools *p = dm_table_get_md_mempools(t);
2092 if (md->io_pool && md->bs) {
2093 /* The md already has necessary mempools. */
2094 if (dm_table_get_type(t) == DM_TYPE_BIO_BASED) {
2096 * Reload bioset because front_pad may have changed
2097 * because a different table was loaded.
2099 bioset_free(md->bs);
2102 } else if (dm_table_get_type(t) == DM_TYPE_REQUEST_BASED) {
2104 * There's no need to reload with request-based dm
2105 * because the size of front_pad doesn't change.
2106 * Note for future: If you are to reload bioset,
2107 * prep-ed requests in the queue may refer
2108 * to bio from the old bioset, so you must walk
2109 * through the queue to unprep.
2115 BUG_ON(!p || md->io_pool || md->bs);
2117 md->io_pool = p->io_pool;
2123 /* mempool bind completed, now no need any mempools in the table */
2124 dm_table_free_md_mempools(t);
2128 * Bind a table to the device.
2130 static void event_callback(void *context)
2132 unsigned long flags;
2134 struct mapped_device *md = (struct mapped_device *) context;
2136 spin_lock_irqsave(&md->uevent_lock, flags);
2137 list_splice_init(&md->uevent_list, &uevents);
2138 spin_unlock_irqrestore(&md->uevent_lock, flags);
2140 dm_send_uevents(&uevents, &disk_to_dev(md->disk)->kobj);
2142 atomic_inc(&md->event_nr);
2143 wake_up(&md->eventq);
2147 * Protected by md->suspend_lock obtained by dm_swap_table().
2149 static void __set_size(struct mapped_device *md, sector_t size)
2151 set_capacity(md->disk, size);
2153 i_size_write(md->bdev->bd_inode, (loff_t)size << SECTOR_SHIFT);
2157 * Return 1 if the queue has a compulsory merge_bvec_fn function.
2159 * If this function returns 0, then the device is either a non-dm
2160 * device without a merge_bvec_fn, or it is a dm device that is
2161 * able to split any bios it receives that are too big.
2163 int dm_queue_merge_is_compulsory(struct request_queue *q)
2165 struct mapped_device *dev_md;
2167 if (!q->merge_bvec_fn)
2170 if (q->make_request_fn == dm_request) {
2171 dev_md = q->queuedata;
2172 if (test_bit(DMF_MERGE_IS_OPTIONAL, &dev_md->flags))
2179 static int dm_device_merge_is_compulsory(struct dm_target *ti,
2180 struct dm_dev *dev, sector_t start,
2181 sector_t len, void *data)
2183 struct block_device *bdev = dev->bdev;
2184 struct request_queue *q = bdev_get_queue(bdev);
2186 return dm_queue_merge_is_compulsory(q);
2190 * Return 1 if it is acceptable to ignore merge_bvec_fn based
2191 * on the properties of the underlying devices.
2193 static int dm_table_merge_is_optional(struct dm_table *table)
2196 struct dm_target *ti;
2198 while (i < dm_table_get_num_targets(table)) {
2199 ti = dm_table_get_target(table, i++);
2201 if (ti->type->iterate_devices &&
2202 ti->type->iterate_devices(ti, dm_device_merge_is_compulsory, NULL))
2210 * Returns old map, which caller must destroy.
2212 static struct dm_table *__bind(struct mapped_device *md, struct dm_table *t,
2213 struct queue_limits *limits)
2215 struct dm_table *old_map;
2216 struct request_queue *q = md->queue;
2218 int merge_is_optional;
2220 size = dm_table_get_size(t);
2223 * Wipe any geometry if the size of the table changed.
2225 if (size != dm_get_size(md))
2226 memset(&md->geometry, 0, sizeof(md->geometry));
2228 __set_size(md, size);
2230 dm_table_event_callback(t, event_callback, md);
2233 * The queue hasn't been stopped yet, if the old table type wasn't
2234 * for request-based during suspension. So stop it to prevent
2235 * I/O mapping before resume.
2236 * This must be done before setting the queue restrictions,
2237 * because request-based dm may be run just after the setting.
2239 if (dm_table_request_based(t) && !blk_queue_stopped(q))
2242 __bind_mempools(md, t);
2244 merge_is_optional = dm_table_merge_is_optional(t);
2247 rcu_assign_pointer(md->map, t);
2248 md->immutable_target_type = dm_table_get_immutable_target_type(t);
2250 dm_table_set_restrictions(t, q, limits);
2251 if (merge_is_optional)
2252 set_bit(DMF_MERGE_IS_OPTIONAL, &md->flags);
2254 clear_bit(DMF_MERGE_IS_OPTIONAL, &md->flags);
2261 * Returns unbound table for the caller to free.
2263 static struct dm_table *__unbind(struct mapped_device *md)
2265 struct dm_table *map = md->map;
2270 dm_table_event_callback(map, NULL, NULL);
2271 rcu_assign_pointer(md->map, NULL);
2278 * Constructor for a new device.
2280 int dm_create(int minor, struct mapped_device **result)
2282 struct mapped_device *md;
2284 md = alloc_dev(minor);
2295 * Functions to manage md->type.
2296 * All are required to hold md->type_lock.
2298 void dm_lock_md_type(struct mapped_device *md)
2300 mutex_lock(&md->type_lock);
2303 void dm_unlock_md_type(struct mapped_device *md)
2305 mutex_unlock(&md->type_lock);
2308 void dm_set_md_type(struct mapped_device *md, unsigned type)
2310 BUG_ON(!mutex_is_locked(&md->type_lock));
2314 unsigned dm_get_md_type(struct mapped_device *md)
2316 BUG_ON(!mutex_is_locked(&md->type_lock));
2320 struct target_type *dm_get_immutable_target_type(struct mapped_device *md)
2322 return md->immutable_target_type;
2326 * The queue_limits are only valid as long as you have a reference
2329 struct queue_limits *dm_get_queue_limits(struct mapped_device *md)
2331 BUG_ON(!atomic_read(&md->holders));
2332 return &md->queue->limits;
2334 EXPORT_SYMBOL_GPL(dm_get_queue_limits);
2337 * Fully initialize a request-based queue (->elevator, ->request_fn, etc).
2339 static int dm_init_request_based_queue(struct mapped_device *md)
2341 struct request_queue *q = NULL;
2343 if (md->queue->elevator)
2346 /* Fully initialize the queue */
2347 q = blk_init_allocated_queue(md->queue, dm_request_fn, NULL);
2352 dm_init_md_queue(md);
2353 blk_queue_softirq_done(md->queue, dm_softirq_done);
2354 blk_queue_prep_rq(md->queue, dm_prep_fn);
2355 blk_queue_lld_busy(md->queue, dm_lld_busy);
2357 elv_register_queue(md->queue);
2363 * Setup the DM device's queue based on md's type
2365 int dm_setup_md_queue(struct mapped_device *md)
2367 if ((dm_get_md_type(md) == DM_TYPE_REQUEST_BASED) &&
2368 !dm_init_request_based_queue(md)) {
2369 DMWARN("Cannot initialize queue for request-based mapped device");
2376 static struct mapped_device *dm_find_md(dev_t dev)
2378 struct mapped_device *md;
2379 unsigned minor = MINOR(dev);
2381 if (MAJOR(dev) != _major || minor >= (1 << MINORBITS))
2384 spin_lock(&_minor_lock);
2386 md = idr_find(&_minor_idr, minor);
2387 if (md && (md == MINOR_ALLOCED ||
2388 (MINOR(disk_devt(dm_disk(md))) != minor) ||
2389 dm_deleting_md(md) ||
2390 test_bit(DMF_FREEING, &md->flags))) {
2396 spin_unlock(&_minor_lock);
2401 struct mapped_device *dm_get_md(dev_t dev)
2403 struct mapped_device *md = dm_find_md(dev);
2410 EXPORT_SYMBOL_GPL(dm_get_md);
2412 void *dm_get_mdptr(struct mapped_device *md)
2414 return md->interface_ptr;
2417 void dm_set_mdptr(struct mapped_device *md, void *ptr)
2419 md->interface_ptr = ptr;
2422 void dm_get(struct mapped_device *md)
2424 atomic_inc(&md->holders);
2425 BUG_ON(test_bit(DMF_FREEING, &md->flags));
2428 const char *dm_device_name(struct mapped_device *md)
2432 EXPORT_SYMBOL_GPL(dm_device_name);
2434 static void __dm_destroy(struct mapped_device *md, bool wait)
2436 struct dm_table *map;
2441 spin_lock(&_minor_lock);
2442 map = dm_get_live_table(md, &srcu_idx);
2443 idr_replace(&_minor_idr, MINOR_ALLOCED, MINOR(disk_devt(dm_disk(md))));
2444 set_bit(DMF_FREEING, &md->flags);
2445 spin_unlock(&_minor_lock);
2447 if (!dm_suspended_md(md)) {
2448 dm_table_presuspend_targets(map);
2449 dm_table_postsuspend_targets(map);
2452 /* dm_put_live_table must be before msleep, otherwise deadlock is possible */
2453 dm_put_live_table(md, srcu_idx);
2456 * Rare, but there may be I/O requests still going to complete,
2457 * for example. Wait for all references to disappear.
2458 * No one should increment the reference count of the mapped_device,
2459 * after the mapped_device state becomes DMF_FREEING.
2462 while (atomic_read(&md->holders))
2464 else if (atomic_read(&md->holders))
2465 DMWARN("%s: Forcibly removing mapped_device still in use! (%d users)",
2466 dm_device_name(md), atomic_read(&md->holders));
2469 dm_table_destroy(__unbind(md));
2473 void dm_destroy(struct mapped_device *md)
2475 __dm_destroy(md, true);
2478 void dm_destroy_immediate(struct mapped_device *md)
2480 __dm_destroy(md, false);
2483 void dm_put(struct mapped_device *md)
2485 atomic_dec(&md->holders);
2487 EXPORT_SYMBOL_GPL(dm_put);
2489 static int dm_wait_for_completion(struct mapped_device *md, int interruptible)
2492 DECLARE_WAITQUEUE(wait, current);
2494 add_wait_queue(&md->wait, &wait);
2497 set_current_state(interruptible);
2499 if (!md_in_flight(md))
2502 if (interruptible == TASK_INTERRUPTIBLE &&
2503 signal_pending(current)) {
2510 set_current_state(TASK_RUNNING);
2512 remove_wait_queue(&md->wait, &wait);
2518 * Process the deferred bios
2520 static void dm_wq_work(struct work_struct *work)
2522 struct mapped_device *md = container_of(work, struct mapped_device,
2526 struct dm_table *map;
2528 map = dm_get_live_table(md, &srcu_idx);
2530 while (!test_bit(DMF_BLOCK_IO_FOR_SUSPEND, &md->flags)) {
2531 spin_lock_irq(&md->deferred_lock);
2532 c = bio_list_pop(&md->deferred);
2533 spin_unlock_irq(&md->deferred_lock);
2538 if (dm_request_based(md))
2539 generic_make_request(c);
2541 __split_and_process_bio(md, map, c);
2544 dm_put_live_table(md, srcu_idx);
2547 static void dm_queue_flush(struct mapped_device *md)
2549 clear_bit(DMF_BLOCK_IO_FOR_SUSPEND, &md->flags);
2550 smp_mb__after_clear_bit();
2551 queue_work(md->wq, &md->work);
2555 * Swap in a new table, returning the old one for the caller to destroy.
2557 struct dm_table *dm_swap_table(struct mapped_device *md, struct dm_table *table)
2559 struct dm_table *live_map = NULL, *map = ERR_PTR(-EINVAL);
2560 struct queue_limits limits;
2563 mutex_lock(&md->suspend_lock);
2565 /* device must be suspended */
2566 if (!dm_suspended_md(md))
2570 * If the new table has no data devices, retain the existing limits.
2571 * This helps multipath with queue_if_no_path if all paths disappear,
2572 * then new I/O is queued based on these limits, and then some paths
2575 if (dm_table_has_no_data_devices(table)) {
2576 live_map = dm_get_live_table_fast(md);
2578 limits = md->queue->limits;
2579 dm_put_live_table_fast(md);
2583 r = dm_calculate_queue_limits(table, &limits);
2590 map = __bind(md, table, &limits);
2593 mutex_unlock(&md->suspend_lock);
2598 * Functions to lock and unlock any filesystem running on the
2601 static int lock_fs(struct mapped_device *md)
2605 WARN_ON(md->frozen_sb);
2607 md->frozen_sb = freeze_bdev(md->bdev);
2608 if (IS_ERR(md->frozen_sb)) {
2609 r = PTR_ERR(md->frozen_sb);
2610 md->frozen_sb = NULL;
2614 set_bit(DMF_FROZEN, &md->flags);
2619 static void unlock_fs(struct mapped_device *md)
2621 if (!test_bit(DMF_FROZEN, &md->flags))
2624 thaw_bdev(md->bdev, md->frozen_sb);
2625 md->frozen_sb = NULL;
2626 clear_bit(DMF_FROZEN, &md->flags);
2630 * We need to be able to change a mapping table under a mounted
2631 * filesystem. For example we might want to move some data in
2632 * the background. Before the table can be swapped with
2633 * dm_bind_table, dm_suspend must be called to flush any in
2634 * flight bios and ensure that any further io gets deferred.
2637 * Suspend mechanism in request-based dm.
2639 * 1. Flush all I/Os by lock_fs() if needed.
2640 * 2. Stop dispatching any I/O by stopping the request_queue.
2641 * 3. Wait for all in-flight I/Os to be completed or requeued.
2643 * To abort suspend, start the request_queue.
2645 int dm_suspend(struct mapped_device *md, unsigned suspend_flags)
2647 struct dm_table *map = NULL;
2649 int do_lockfs = suspend_flags & DM_SUSPEND_LOCKFS_FLAG ? 1 : 0;
2650 int noflush = suspend_flags & DM_SUSPEND_NOFLUSH_FLAG ? 1 : 0;
2652 mutex_lock(&md->suspend_lock);
2654 if (dm_suspended_md(md)) {
2662 * DMF_NOFLUSH_SUSPENDING must be set before presuspend.
2663 * This flag is cleared before dm_suspend returns.
2666 set_bit(DMF_NOFLUSH_SUSPENDING, &md->flags);
2668 /* This does not get reverted if there's an error later. */
2669 dm_table_presuspend_targets(map);
2672 * Flush I/O to the device.
2673 * Any I/O submitted after lock_fs() may not be flushed.
2674 * noflush takes precedence over do_lockfs.
2675 * (lock_fs() flushes I/Os and waits for them to complete.)
2677 if (!noflush && do_lockfs) {
2684 * Here we must make sure that no processes are submitting requests
2685 * to target drivers i.e. no one may be executing
2686 * __split_and_process_bio. This is called from dm_request and
2689 * To get all processes out of __split_and_process_bio in dm_request,
2690 * we take the write lock. To prevent any process from reentering
2691 * __split_and_process_bio from dm_request and quiesce the thread
2692 * (dm_wq_work), we set BMF_BLOCK_IO_FOR_SUSPEND and call
2693 * flush_workqueue(md->wq).
2695 set_bit(DMF_BLOCK_IO_FOR_SUSPEND, &md->flags);
2696 synchronize_srcu(&md->io_barrier);
2699 * Stop md->queue before flushing md->wq in case request-based
2700 * dm defers requests to md->wq from md->queue.
2702 if (dm_request_based(md))
2703 stop_queue(md->queue);
2705 flush_workqueue(md->wq);
2708 * At this point no more requests are entering target request routines.
2709 * We call dm_wait_for_completion to wait for all existing requests
2712 r = dm_wait_for_completion(md, TASK_INTERRUPTIBLE);
2715 clear_bit(DMF_NOFLUSH_SUSPENDING, &md->flags);
2716 synchronize_srcu(&md->io_barrier);
2718 /* were we interrupted ? */
2722 if (dm_request_based(md))
2723 start_queue(md->queue);
2726 goto out_unlock; /* pushback list is already flushed, so skip flush */
2730 * If dm_wait_for_completion returned 0, the device is completely
2731 * quiescent now. There is no request-processing activity. All new
2732 * requests are being added to md->deferred list.
2735 set_bit(DMF_SUSPENDED, &md->flags);
2737 dm_table_postsuspend_targets(map);
2740 mutex_unlock(&md->suspend_lock);
2744 int dm_resume(struct mapped_device *md)
2747 struct dm_table *map = NULL;
2749 mutex_lock(&md->suspend_lock);
2750 if (!dm_suspended_md(md))
2754 if (!map || !dm_table_get_size(map))
2757 r = dm_table_resume_targets(map);
2764 * Flushing deferred I/Os must be done after targets are resumed
2765 * so that mapping of targets can work correctly.
2766 * Request-based dm is queueing the deferred I/Os in its request_queue.
2768 if (dm_request_based(md))
2769 start_queue(md->queue);
2773 clear_bit(DMF_SUSPENDED, &md->flags);
2777 mutex_unlock(&md->suspend_lock);
2783 * Internal suspend/resume works like userspace-driven suspend. It waits
2784 * until all bios finish and prevents issuing new bios to the target drivers.
2785 * It may be used only from the kernel.
2787 * Internal suspend holds md->suspend_lock, which prevents interaction with
2788 * userspace-driven suspend.
2791 void dm_internal_suspend(struct mapped_device *md)
2793 mutex_lock(&md->suspend_lock);
2794 if (dm_suspended_md(md))
2797 set_bit(DMF_BLOCK_IO_FOR_SUSPEND, &md->flags);
2798 synchronize_srcu(&md->io_barrier);
2799 flush_workqueue(md->wq);
2800 dm_wait_for_completion(md, TASK_UNINTERRUPTIBLE);
2803 void dm_internal_resume(struct mapped_device *md)
2805 if (dm_suspended_md(md))
2811 mutex_unlock(&md->suspend_lock);
2814 /*-----------------------------------------------------------------
2815 * Event notification.
2816 *---------------------------------------------------------------*/
2817 int dm_kobject_uevent(struct mapped_device *md, enum kobject_action action,
2820 char udev_cookie[DM_COOKIE_LENGTH];
2821 char *envp[] = { udev_cookie, NULL };
2824 return kobject_uevent(&disk_to_dev(md->disk)->kobj, action);
2826 snprintf(udev_cookie, DM_COOKIE_LENGTH, "%s=%u",
2827 DM_COOKIE_ENV_VAR_NAME, cookie);
2828 return kobject_uevent_env(&disk_to_dev(md->disk)->kobj,
2833 uint32_t dm_next_uevent_seq(struct mapped_device *md)
2835 return atomic_add_return(1, &md->uevent_seq);
2838 uint32_t dm_get_event_nr(struct mapped_device *md)
2840 return atomic_read(&md->event_nr);
2843 int dm_wait_event(struct mapped_device *md, int event_nr)
2845 return wait_event_interruptible(md->eventq,
2846 (event_nr != atomic_read(&md->event_nr)));
2849 void dm_uevent_add(struct mapped_device *md, struct list_head *elist)
2851 unsigned long flags;
2853 spin_lock_irqsave(&md->uevent_lock, flags);
2854 list_add(elist, &md->uevent_list);
2855 spin_unlock_irqrestore(&md->uevent_lock, flags);
2859 * The gendisk is only valid as long as you have a reference
2862 struct gendisk *dm_disk(struct mapped_device *md)
2867 struct kobject *dm_kobject(struct mapped_device *md)
2873 * struct mapped_device should not be exported outside of dm.c
2874 * so use this check to verify that kobj is part of md structure
2876 struct mapped_device *dm_get_from_kobject(struct kobject *kobj)
2878 struct mapped_device *md;
2880 md = container_of(kobj, struct mapped_device, kobj);
2881 if (&md->kobj != kobj)
2884 if (test_bit(DMF_FREEING, &md->flags) ||
2892 int dm_suspended_md(struct mapped_device *md)
2894 return test_bit(DMF_SUSPENDED, &md->flags);
2897 int dm_suspended(struct dm_target *ti)
2899 return dm_suspended_md(dm_table_get_md(ti->table));
2901 EXPORT_SYMBOL_GPL(dm_suspended);
2903 int dm_noflush_suspending(struct dm_target *ti)
2905 return __noflush_suspending(dm_table_get_md(ti->table));
2907 EXPORT_SYMBOL_GPL(dm_noflush_suspending);
2909 struct dm_md_mempools *dm_alloc_md_mempools(unsigned type, unsigned integrity, unsigned per_bio_data_size)
2911 struct dm_md_mempools *pools = kzalloc(sizeof(*pools), GFP_KERNEL);
2912 struct kmem_cache *cachep;
2913 unsigned int pool_size;
2914 unsigned int front_pad;
2919 if (type == DM_TYPE_BIO_BASED) {
2921 pool_size = dm_get_reserved_bio_based_ios();
2922 front_pad = roundup(per_bio_data_size, __alignof__(struct dm_target_io)) + offsetof(struct dm_target_io, clone);
2923 } else if (type == DM_TYPE_REQUEST_BASED) {
2924 cachep = _rq_tio_cache;
2925 pool_size = dm_get_reserved_rq_based_ios();
2926 front_pad = offsetof(struct dm_rq_clone_bio_info, clone);
2927 /* per_bio_data_size is not used. See __bind_mempools(). */
2928 WARN_ON(per_bio_data_size != 0);
2932 pools->io_pool = mempool_create_slab_pool(pool_size, cachep);
2933 if (!pools->io_pool)
2936 pools->bs = bioset_create(pool_size, front_pad);
2940 if (integrity && bioset_integrity_create(pools->bs, pool_size))
2946 dm_free_md_mempools(pools);
2951 void dm_free_md_mempools(struct dm_md_mempools *pools)
2957 mempool_destroy(pools->io_pool);
2960 bioset_free(pools->bs);
2965 static const struct block_device_operations dm_blk_dops = {
2966 .open = dm_blk_open,
2967 .release = dm_blk_close,
2968 .ioctl = dm_blk_ioctl,
2969 .getgeo = dm_blk_getgeo,
2970 .owner = THIS_MODULE
2973 EXPORT_SYMBOL(dm_get_mapinfo);
2978 module_init(dm_init);
2979 module_exit(dm_exit);
2981 module_param(major, uint, 0);
2982 MODULE_PARM_DESC(major, "The major number of the device mapper");
2984 module_param(reserved_bio_based_ios, uint, S_IRUGO | S_IWUSR);
2985 MODULE_PARM_DESC(reserved_bio_based_ios, "Reserved IOs in bio-based mempools");
2987 module_param(reserved_rq_based_ios, uint, S_IRUGO | S_IWUSR);
2988 MODULE_PARM_DESC(reserved_rq_based_ios, "Reserved IOs in request-based mempools");
2990 MODULE_DESCRIPTION(DM_NAME " driver");
2991 MODULE_AUTHOR("Joe Thornber <dm-devel@redhat.com>");
2992 MODULE_LICENSE("GPL");