]> git.karo-electronics.de Git - karo-tx-linux.git/blob - drivers/md/dm.c
block: prep work for batch completion
[karo-tx-linux.git] / drivers / md / dm.c
1 /*
2  * Copyright (C) 2001, 2002 Sistina Software (UK) Limited.
3  * Copyright (C) 2004-2008 Red Hat, Inc. All rights reserved.
4  *
5  * This file is released under the GPL.
6  */
7
8 #include "dm.h"
9 #include "dm-uevent.h"
10
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>
22
23 #include <trace/events/block.h>
24
25 #define DM_MSG_PREFIX "core"
26
27 #ifdef CONFIG_PRINTK
28 /*
29  * ratelimit state to be used in DMXXX_LIMIT().
30  */
31 DEFINE_RATELIMIT_STATE(dm_ratelimit_state,
32                        DEFAULT_RATELIMIT_INTERVAL,
33                        DEFAULT_RATELIMIT_BURST);
34 EXPORT_SYMBOL(dm_ratelimit_state);
35 #endif
36
37 /*
38  * Cookies are numeric values sent with CHANGE and REMOVE
39  * uevents while resuming, removing or renaming the device.
40  */
41 #define DM_COOKIE_ENV_VAR_NAME "DM_COOKIE"
42 #define DM_COOKIE_LENGTH 24
43
44 static const char *_name = DM_NAME;
45
46 static unsigned int major = 0;
47 static unsigned int _major = 0;
48
49 static DEFINE_IDR(_minor_idr);
50
51 static DEFINE_SPINLOCK(_minor_lock);
52 /*
53  * For bio-based dm.
54  * One of these is allocated per bio.
55  */
56 struct dm_io {
57         struct mapped_device *md;
58         int error;
59         atomic_t io_count;
60         struct bio *bio;
61         unsigned long start_time;
62         spinlock_t endio_lock;
63 };
64
65 /*
66  * For request-based dm.
67  * One of these is allocated per request.
68  */
69 struct dm_rq_target_io {
70         struct mapped_device *md;
71         struct dm_target *ti;
72         struct request *orig, clone;
73         int error;
74         union map_info info;
75 };
76
77 /*
78  * For request-based dm - the bio clones we allocate are embedded in these
79  * structs.
80  *
81  * We allocate these with bio_alloc_bioset, using the front_pad parameter when
82  * the bioset is created - this means the bio has to come at the end of the
83  * struct.
84  */
85 struct dm_rq_clone_bio_info {
86         struct bio *orig;
87         struct dm_rq_target_io *tio;
88         struct bio clone;
89 };
90
91 union map_info *dm_get_mapinfo(struct bio *bio)
92 {
93         if (bio && bio->bi_private)
94                 return &((struct dm_target_io *)bio->bi_private)->info;
95         return NULL;
96 }
97
98 union map_info *dm_get_rq_mapinfo(struct request *rq)
99 {
100         if (rq && rq->end_io_data)
101                 return &((struct dm_rq_target_io *)rq->end_io_data)->info;
102         return NULL;
103 }
104 EXPORT_SYMBOL_GPL(dm_get_rq_mapinfo);
105
106 #define MINOR_ALLOCED ((void *)-1)
107
108 /*
109  * Bits for the md->flags field.
110  */
111 #define DMF_BLOCK_IO_FOR_SUSPEND 0
112 #define DMF_SUSPENDED 1
113 #define DMF_FROZEN 2
114 #define DMF_FREEING 3
115 #define DMF_DELETING 4
116 #define DMF_NOFLUSH_SUSPENDING 5
117 #define DMF_MERGE_IS_OPTIONAL 6
118
119 /*
120  * Work processed by per-device workqueue.
121  */
122 struct mapped_device {
123         struct rw_semaphore io_lock;
124         struct mutex suspend_lock;
125         rwlock_t map_lock;
126         atomic_t holders;
127         atomic_t open_count;
128
129         unsigned long flags;
130
131         struct request_queue *queue;
132         unsigned type;
133         /* Protect queue and type against concurrent access. */
134         struct mutex type_lock;
135
136         struct target_type *immutable_target_type;
137
138         struct gendisk *disk;
139         char name[16];
140
141         void *interface_ptr;
142
143         /*
144          * A list of ios that arrived while we were suspended.
145          */
146         atomic_t pending[2];
147         wait_queue_head_t wait;
148         struct work_struct work;
149         struct bio_list deferred;
150         spinlock_t deferred_lock;
151
152         /*
153          * Processing queue (flush)
154          */
155         struct workqueue_struct *wq;
156
157         /*
158          * The current mapping.
159          */
160         struct dm_table *map;
161
162         /*
163          * io objects are allocated from here.
164          */
165         mempool_t *io_pool;
166
167         struct bio_set *bs;
168
169         /*
170          * Event handling.
171          */
172         atomic_t event_nr;
173         wait_queue_head_t eventq;
174         atomic_t uevent_seq;
175         struct list_head uevent_list;
176         spinlock_t uevent_lock; /* Protect access to uevent_list */
177
178         /*
179          * freeze/thaw support require holding onto a super block
180          */
181         struct super_block *frozen_sb;
182         struct block_device *bdev;
183
184         /* forced geometry settings */
185         struct hd_geometry geometry;
186
187         /* sysfs handle */
188         struct kobject kobj;
189
190         /* zero-length flush that will be cloned and submitted to targets */
191         struct bio flush_bio;
192 };
193
194 /*
195  * For mempools pre-allocation at the table loading time.
196  */
197 struct dm_md_mempools {
198         mempool_t *io_pool;
199         struct bio_set *bs;
200 };
201
202 #define MIN_IOS 256
203 static struct kmem_cache *_io_cache;
204 static struct kmem_cache *_rq_tio_cache;
205
206 static int __init local_init(void)
207 {
208         int r = -ENOMEM;
209
210         /* allocate a slab for the dm_ios */
211         _io_cache = KMEM_CACHE(dm_io, 0);
212         if (!_io_cache)
213                 return r;
214
215         _rq_tio_cache = KMEM_CACHE(dm_rq_target_io, 0);
216         if (!_rq_tio_cache)
217                 goto out_free_io_cache;
218
219         r = dm_uevent_init();
220         if (r)
221                 goto out_free_rq_tio_cache;
222
223         _major = major;
224         r = register_blkdev(_major, _name);
225         if (r < 0)
226                 goto out_uevent_exit;
227
228         if (!_major)
229                 _major = r;
230
231         return 0;
232
233 out_uevent_exit:
234         dm_uevent_exit();
235 out_free_rq_tio_cache:
236         kmem_cache_destroy(_rq_tio_cache);
237 out_free_io_cache:
238         kmem_cache_destroy(_io_cache);
239
240         return r;
241 }
242
243 static void local_exit(void)
244 {
245         kmem_cache_destroy(_rq_tio_cache);
246         kmem_cache_destroy(_io_cache);
247         unregister_blkdev(_major, _name);
248         dm_uevent_exit();
249
250         _major = 0;
251
252         DMINFO("cleaned up");
253 }
254
255 static int (*_inits[])(void) __initdata = {
256         local_init,
257         dm_target_init,
258         dm_linear_init,
259         dm_stripe_init,
260         dm_io_init,
261         dm_kcopyd_init,
262         dm_interface_init,
263 };
264
265 static void (*_exits[])(void) = {
266         local_exit,
267         dm_target_exit,
268         dm_linear_exit,
269         dm_stripe_exit,
270         dm_io_exit,
271         dm_kcopyd_exit,
272         dm_interface_exit,
273 };
274
275 static int __init dm_init(void)
276 {
277         const int count = ARRAY_SIZE(_inits);
278
279         int r, i;
280
281         for (i = 0; i < count; i++) {
282                 r = _inits[i]();
283                 if (r)
284                         goto bad;
285         }
286
287         return 0;
288
289       bad:
290         while (i--)
291                 _exits[i]();
292
293         return r;
294 }
295
296 static void __exit dm_exit(void)
297 {
298         int i = ARRAY_SIZE(_exits);
299
300         while (i--)
301                 _exits[i]();
302
303         /*
304          * Should be empty by this point.
305          */
306         idr_destroy(&_minor_idr);
307 }
308
309 /*
310  * Block device functions
311  */
312 int dm_deleting_md(struct mapped_device *md)
313 {
314         return test_bit(DMF_DELETING, &md->flags);
315 }
316
317 static int dm_blk_open(struct block_device *bdev, fmode_t mode)
318 {
319         struct mapped_device *md;
320
321         spin_lock(&_minor_lock);
322
323         md = bdev->bd_disk->private_data;
324         if (!md)
325                 goto out;
326
327         if (test_bit(DMF_FREEING, &md->flags) ||
328             dm_deleting_md(md)) {
329                 md = NULL;
330                 goto out;
331         }
332
333         dm_get(md);
334         atomic_inc(&md->open_count);
335
336 out:
337         spin_unlock(&_minor_lock);
338
339         return md ? 0 : -ENXIO;
340 }
341
342 static int dm_blk_close(struct gendisk *disk, fmode_t mode)
343 {
344         struct mapped_device *md = disk->private_data;
345
346         spin_lock(&_minor_lock);
347
348         atomic_dec(&md->open_count);
349         dm_put(md);
350
351         spin_unlock(&_minor_lock);
352
353         return 0;
354 }
355
356 int dm_open_count(struct mapped_device *md)
357 {
358         return atomic_read(&md->open_count);
359 }
360
361 /*
362  * Guarantees nothing is using the device before it's deleted.
363  */
364 int dm_lock_for_deletion(struct mapped_device *md)
365 {
366         int r = 0;
367
368         spin_lock(&_minor_lock);
369
370         if (dm_open_count(md))
371                 r = -EBUSY;
372         else
373                 set_bit(DMF_DELETING, &md->flags);
374
375         spin_unlock(&_minor_lock);
376
377         return r;
378 }
379
380 static int dm_blk_getgeo(struct block_device *bdev, struct hd_geometry *geo)
381 {
382         struct mapped_device *md = bdev->bd_disk->private_data;
383
384         return dm_get_geometry(md, geo);
385 }
386
387 static int dm_blk_ioctl(struct block_device *bdev, fmode_t mode,
388                         unsigned int cmd, unsigned long arg)
389 {
390         struct mapped_device *md = bdev->bd_disk->private_data;
391         struct dm_table *map = dm_get_live_table(md);
392         struct dm_target *tgt;
393         int r = -ENOTTY;
394
395         if (!map || !dm_table_get_size(map))
396                 goto out;
397
398         /* We only support devices that have a single target */
399         if (dm_table_get_num_targets(map) != 1)
400                 goto out;
401
402         tgt = dm_table_get_target(map, 0);
403
404         if (dm_suspended_md(md)) {
405                 r = -EAGAIN;
406                 goto out;
407         }
408
409         if (tgt->type->ioctl)
410                 r = tgt->type->ioctl(tgt, cmd, arg);
411
412 out:
413         dm_table_put(map);
414
415         return r;
416 }
417
418 static struct dm_io *alloc_io(struct mapped_device *md)
419 {
420         return mempool_alloc(md->io_pool, GFP_NOIO);
421 }
422
423 static void free_io(struct mapped_device *md, struct dm_io *io)
424 {
425         mempool_free(io, md->io_pool);
426 }
427
428 static void free_tio(struct mapped_device *md, struct dm_target_io *tio)
429 {
430         bio_put(&tio->clone);
431 }
432
433 static struct dm_rq_target_io *alloc_rq_tio(struct mapped_device *md,
434                                             gfp_t gfp_mask)
435 {
436         return mempool_alloc(md->io_pool, gfp_mask);
437 }
438
439 static void free_rq_tio(struct dm_rq_target_io *tio)
440 {
441         mempool_free(tio, tio->md->io_pool);
442 }
443
444 static int md_in_flight(struct mapped_device *md)
445 {
446         return atomic_read(&md->pending[READ]) +
447                atomic_read(&md->pending[WRITE]);
448 }
449
450 static void start_io_acct(struct dm_io *io)
451 {
452         struct mapped_device *md = io->md;
453         int cpu;
454         int rw = bio_data_dir(io->bio);
455
456         io->start_time = jiffies;
457
458         cpu = part_stat_lock();
459         part_round_stats(cpu, &dm_disk(md)->part0);
460         part_stat_unlock();
461         atomic_set(&dm_disk(md)->part0.in_flight[rw],
462                 atomic_inc_return(&md->pending[rw]));
463 }
464
465 static void end_io_acct(struct dm_io *io)
466 {
467         struct mapped_device *md = io->md;
468         struct bio *bio = io->bio;
469         unsigned long duration = jiffies - io->start_time;
470         int pending, cpu;
471         int rw = bio_data_dir(bio);
472
473         cpu = part_stat_lock();
474         part_round_stats(cpu, &dm_disk(md)->part0);
475         part_stat_add(cpu, &dm_disk(md)->part0, ticks[rw], duration);
476         part_stat_unlock();
477
478         /*
479          * After this is decremented the bio must not be touched if it is
480          * a flush.
481          */
482         pending = atomic_dec_return(&md->pending[rw]);
483         atomic_set(&dm_disk(md)->part0.in_flight[rw], pending);
484         pending += atomic_read(&md->pending[rw^0x1]);
485
486         /* nudge anyone waiting on suspend queue */
487         if (!pending)
488                 wake_up(&md->wait);
489 }
490
491 /*
492  * Add the bio to the list of deferred io.
493  */
494 static void queue_io(struct mapped_device *md, struct bio *bio)
495 {
496         unsigned long flags;
497
498         spin_lock_irqsave(&md->deferred_lock, flags);
499         bio_list_add(&md->deferred, bio);
500         spin_unlock_irqrestore(&md->deferred_lock, flags);
501         queue_work(md->wq, &md->work);
502 }
503
504 /*
505  * Everyone (including functions in this file), should use this
506  * function to access the md->map field, and make sure they call
507  * dm_table_put() when finished.
508  */
509 struct dm_table *dm_get_live_table(struct mapped_device *md)
510 {
511         struct dm_table *t;
512         unsigned long flags;
513
514         read_lock_irqsave(&md->map_lock, flags);
515         t = md->map;
516         if (t)
517                 dm_table_get(t);
518         read_unlock_irqrestore(&md->map_lock, flags);
519
520         return t;
521 }
522
523 /*
524  * Get the geometry associated with a dm device
525  */
526 int dm_get_geometry(struct mapped_device *md, struct hd_geometry *geo)
527 {
528         *geo = md->geometry;
529
530         return 0;
531 }
532
533 /*
534  * Set the geometry of a device.
535  */
536 int dm_set_geometry(struct mapped_device *md, struct hd_geometry *geo)
537 {
538         sector_t sz = (sector_t)geo->cylinders * geo->heads * geo->sectors;
539
540         if (geo->start > sz) {
541                 DMWARN("Start sector is beyond the geometry limits.");
542                 return -EINVAL;
543         }
544
545         md->geometry = *geo;
546
547         return 0;
548 }
549
550 /*-----------------------------------------------------------------
551  * CRUD START:
552  *   A more elegant soln is in the works that uses the queue
553  *   merge fn, unfortunately there are a couple of changes to
554  *   the block layer that I want to make for this.  So in the
555  *   interests of getting something for people to use I give
556  *   you this clearly demarcated crap.
557  *---------------------------------------------------------------*/
558
559 static int __noflush_suspending(struct mapped_device *md)
560 {
561         return test_bit(DMF_NOFLUSH_SUSPENDING, &md->flags);
562 }
563
564 /*
565  * Decrements the number of outstanding ios that a bio has been
566  * cloned into, completing the original io if necc.
567  */
568 static void dec_pending(struct dm_io *io, int error)
569 {
570         unsigned long flags;
571         int io_error;
572         struct bio *bio;
573         struct mapped_device *md = io->md;
574
575         /* Push-back supersedes any I/O errors */
576         if (unlikely(error)) {
577                 spin_lock_irqsave(&io->endio_lock, flags);
578                 if (!(io->error > 0 && __noflush_suspending(md)))
579                         io->error = error;
580                 spin_unlock_irqrestore(&io->endio_lock, flags);
581         }
582
583         if (atomic_dec_and_test(&io->io_count)) {
584                 if (io->error == DM_ENDIO_REQUEUE) {
585                         /*
586                          * Target requested pushing back the I/O.
587                          */
588                         spin_lock_irqsave(&md->deferred_lock, flags);
589                         if (__noflush_suspending(md))
590                                 bio_list_add_head(&md->deferred, io->bio);
591                         else
592                                 /* noflush suspend was interrupted. */
593                                 io->error = -EIO;
594                         spin_unlock_irqrestore(&md->deferred_lock, flags);
595                 }
596
597                 io_error = io->error;
598                 bio = io->bio;
599                 end_io_acct(io);
600                 free_io(md, io);
601
602                 if (io_error == DM_ENDIO_REQUEUE)
603                         return;
604
605                 if ((bio->bi_rw & REQ_FLUSH) && bio->bi_size) {
606                         /*
607                          * Preflush done for flush with data, reissue
608                          * without REQ_FLUSH.
609                          */
610                         bio->bi_rw &= ~REQ_FLUSH;
611                         queue_io(md, bio);
612                 } else {
613                         /* done with normal IO or empty flush */
614                         bio_endio(bio, io_error);
615                 }
616         }
617 }
618
619 static void clone_endio(struct bio *bio, int error,
620                         struct batch_complete *batch)
621 {
622         int r = 0;
623         struct dm_target_io *tio = bio->bi_private;
624         struct dm_io *io = tio->io;
625         struct mapped_device *md = tio->io->md;
626         dm_endio_fn endio = tio->ti->type->end_io;
627
628         if (!bio_flagged(bio, BIO_UPTODATE) && !error)
629                 error = -EIO;
630
631         if (endio) {
632                 r = endio(tio->ti, bio, error);
633                 if (r < 0 || r == DM_ENDIO_REQUEUE)
634                         /*
635                          * error and requeue request are handled
636                          * in dec_pending().
637                          */
638                         error = r;
639                 else if (r == DM_ENDIO_INCOMPLETE)
640                         /* The target will handle the io */
641                         return;
642                 else if (r) {
643                         DMWARN("unimplemented target endio return value: %d", r);
644                         BUG();
645                 }
646         }
647
648         free_tio(md, tio);
649         dec_pending(io, error);
650 }
651
652 /*
653  * Partial completion handling for request-based dm
654  */
655 static void end_clone_bio(struct bio *clone, int error,
656                           struct batch_complete *batch)
657 {
658         struct dm_rq_clone_bio_info *info = clone->bi_private;
659         struct dm_rq_target_io *tio = info->tio;
660         struct bio *bio = info->orig;
661         unsigned int nr_bytes = info->orig->bi_size;
662
663         bio_put(clone);
664
665         if (tio->error)
666                 /*
667                  * An error has already been detected on the request.
668                  * Once error occurred, just let clone->end_io() handle
669                  * the remainder.
670                  */
671                 return;
672         else if (error) {
673                 /*
674                  * Don't notice the error to the upper layer yet.
675                  * The error handling decision is made by the target driver,
676                  * when the request is completed.
677                  */
678                 tio->error = error;
679                 return;
680         }
681
682         /*
683          * I/O for the bio successfully completed.
684          * Notice the data completion to the upper layer.
685          */
686
687         /*
688          * bios are processed from the head of the list.
689          * So the completing bio should always be rq->bio.
690          * If it's not, something wrong is happening.
691          */
692         if (tio->orig->bio != bio)
693                 DMERR("bio completion is going in the middle of the request");
694
695         /*
696          * Update the original request.
697          * Do not use blk_end_request() here, because it may complete
698          * the original request before the clone, and break the ordering.
699          */
700         blk_update_request(tio->orig, 0, nr_bytes);
701 }
702
703 /*
704  * Don't touch any member of the md after calling this function because
705  * the md may be freed in dm_put() at the end of this function.
706  * Or do dm_get() before calling this function and dm_put() later.
707  */
708 static void rq_completed(struct mapped_device *md, int rw, int run_queue)
709 {
710         atomic_dec(&md->pending[rw]);
711
712         /* nudge anyone waiting on suspend queue */
713         if (!md_in_flight(md))
714                 wake_up(&md->wait);
715
716         /*
717          * Run this off this callpath, as drivers could invoke end_io while
718          * inside their request_fn (and holding the queue lock). Calling
719          * back into ->request_fn() could deadlock attempting to grab the
720          * queue lock again.
721          */
722         if (run_queue)
723                 blk_run_queue_async(md->queue);
724
725         /*
726          * dm_put() must be at the end of this function. See the comment above
727          */
728         dm_put(md);
729 }
730
731 static void free_rq_clone(struct request *clone)
732 {
733         struct dm_rq_target_io *tio = clone->end_io_data;
734
735         blk_rq_unprep_clone(clone);
736         free_rq_tio(tio);
737 }
738
739 /*
740  * Complete the clone and the original request.
741  * Must be called without queue lock.
742  */
743 static void dm_end_request(struct request *clone, int error)
744 {
745         int rw = rq_data_dir(clone);
746         struct dm_rq_target_io *tio = clone->end_io_data;
747         struct mapped_device *md = tio->md;
748         struct request *rq = tio->orig;
749
750         if (rq->cmd_type == REQ_TYPE_BLOCK_PC) {
751                 rq->errors = clone->errors;
752                 rq->resid_len = clone->resid_len;
753
754                 if (rq->sense)
755                         /*
756                          * We are using the sense buffer of the original
757                          * request.
758                          * So setting the length of the sense data is enough.
759                          */
760                         rq->sense_len = clone->sense_len;
761         }
762
763         free_rq_clone(clone);
764         blk_end_request_all(rq, error);
765         rq_completed(md, rw, true);
766 }
767
768 static void dm_unprep_request(struct request *rq)
769 {
770         struct request *clone = rq->special;
771
772         rq->special = NULL;
773         rq->cmd_flags &= ~REQ_DONTPREP;
774
775         free_rq_clone(clone);
776 }
777
778 /*
779  * Requeue the original request of a clone.
780  */
781 void dm_requeue_unmapped_request(struct request *clone)
782 {
783         int rw = rq_data_dir(clone);
784         struct dm_rq_target_io *tio = clone->end_io_data;
785         struct mapped_device *md = tio->md;
786         struct request *rq = tio->orig;
787         struct request_queue *q = rq->q;
788         unsigned long flags;
789
790         dm_unprep_request(rq);
791
792         spin_lock_irqsave(q->queue_lock, flags);
793         blk_requeue_request(q, rq);
794         spin_unlock_irqrestore(q->queue_lock, flags);
795
796         rq_completed(md, rw, 0);
797 }
798 EXPORT_SYMBOL_GPL(dm_requeue_unmapped_request);
799
800 static void __stop_queue(struct request_queue *q)
801 {
802         blk_stop_queue(q);
803 }
804
805 static void stop_queue(struct request_queue *q)
806 {
807         unsigned long flags;
808
809         spin_lock_irqsave(q->queue_lock, flags);
810         __stop_queue(q);
811         spin_unlock_irqrestore(q->queue_lock, flags);
812 }
813
814 static void __start_queue(struct request_queue *q)
815 {
816         if (blk_queue_stopped(q))
817                 blk_start_queue(q);
818 }
819
820 static void start_queue(struct request_queue *q)
821 {
822         unsigned long flags;
823
824         spin_lock_irqsave(q->queue_lock, flags);
825         __start_queue(q);
826         spin_unlock_irqrestore(q->queue_lock, flags);
827 }
828
829 static void dm_done(struct request *clone, int error, bool mapped)
830 {
831         int r = error;
832         struct dm_rq_target_io *tio = clone->end_io_data;
833         dm_request_endio_fn rq_end_io = NULL;
834
835         if (tio->ti) {
836                 rq_end_io = tio->ti->type->rq_end_io;
837
838                 if (mapped && rq_end_io)
839                         r = rq_end_io(tio->ti, clone, error, &tio->info);
840         }
841
842         if (r <= 0)
843                 /* The target wants to complete the I/O */
844                 dm_end_request(clone, r);
845         else if (r == DM_ENDIO_INCOMPLETE)
846                 /* The target will handle the I/O */
847                 return;
848         else if (r == DM_ENDIO_REQUEUE)
849                 /* The target wants to requeue the I/O */
850                 dm_requeue_unmapped_request(clone);
851         else {
852                 DMWARN("unimplemented target endio return value: %d", r);
853                 BUG();
854         }
855 }
856
857 /*
858  * Request completion handler for request-based dm
859  */
860 static void dm_softirq_done(struct request *rq)
861 {
862         bool mapped = true;
863         struct request *clone = rq->completion_data;
864         struct dm_rq_target_io *tio = clone->end_io_data;
865
866         if (rq->cmd_flags & REQ_FAILED)
867                 mapped = false;
868
869         dm_done(clone, tio->error, mapped);
870 }
871
872 /*
873  * Complete the clone and the original request with the error status
874  * through softirq context.
875  */
876 static void dm_complete_request(struct request *clone, int error)
877 {
878         struct dm_rq_target_io *tio = clone->end_io_data;
879         struct request *rq = tio->orig;
880
881         tio->error = error;
882         rq->completion_data = clone;
883         blk_complete_request(rq);
884 }
885
886 /*
887  * Complete the not-mapped clone and the original request with the error status
888  * through softirq context.
889  * Target's rq_end_io() function isn't called.
890  * This may be used when the target's map_rq() function fails.
891  */
892 void dm_kill_unmapped_request(struct request *clone, int error)
893 {
894         struct dm_rq_target_io *tio = clone->end_io_data;
895         struct request *rq = tio->orig;
896
897         rq->cmd_flags |= REQ_FAILED;
898         dm_complete_request(clone, error);
899 }
900 EXPORT_SYMBOL_GPL(dm_kill_unmapped_request);
901
902 /*
903  * Called with the queue lock held
904  */
905 static void end_clone_request(struct request *clone, int error)
906 {
907         /*
908          * For just cleaning up the information of the queue in which
909          * the clone was dispatched.
910          * The clone is *NOT* freed actually here because it is alloced from
911          * dm own mempool and REQ_ALLOCED isn't set in clone->cmd_flags.
912          */
913         __blk_put_request(clone->q, clone);
914
915         /*
916          * Actual request completion is done in a softirq context which doesn't
917          * hold the queue lock.  Otherwise, deadlock could occur because:
918          *     - another request may be submitted by the upper level driver
919          *       of the stacking during the completion
920          *     - the submission which requires queue lock may be done
921          *       against this queue
922          */
923         dm_complete_request(clone, error);
924 }
925
926 /*
927  * Return maximum size of I/O possible at the supplied sector up to the current
928  * target boundary.
929  */
930 static sector_t max_io_len_target_boundary(sector_t sector, struct dm_target *ti)
931 {
932         sector_t target_offset = dm_target_offset(ti, sector);
933
934         return ti->len - target_offset;
935 }
936
937 static sector_t max_io_len(sector_t sector, struct dm_target *ti)
938 {
939         sector_t len = max_io_len_target_boundary(sector, ti);
940         sector_t offset, max_len;
941
942         /*
943          * Does the target need to split even further?
944          */
945         if (ti->max_io_len) {
946                 offset = dm_target_offset(ti, sector);
947                 if (unlikely(ti->max_io_len & (ti->max_io_len - 1)))
948                         max_len = sector_div(offset, ti->max_io_len);
949                 else
950                         max_len = offset & (ti->max_io_len - 1);
951                 max_len = ti->max_io_len - max_len;
952
953                 if (len > max_len)
954                         len = max_len;
955         }
956
957         return len;
958 }
959
960 int dm_set_target_max_io_len(struct dm_target *ti, sector_t len)
961 {
962         if (len > UINT_MAX) {
963                 DMERR("Specified maximum size of target IO (%llu) exceeds limit (%u)",
964                       (unsigned long long)len, UINT_MAX);
965                 ti->error = "Maximum size of target IO is too large";
966                 return -EINVAL;
967         }
968
969         ti->max_io_len = (uint32_t) len;
970
971         return 0;
972 }
973 EXPORT_SYMBOL_GPL(dm_set_target_max_io_len);
974
975 static void __map_bio(struct dm_target_io *tio)
976 {
977         int r;
978         sector_t sector;
979         struct mapped_device *md;
980         struct bio *clone = &tio->clone;
981         struct dm_target *ti = tio->ti;
982
983         clone->bi_end_io = clone_endio;
984         clone->bi_private = tio;
985
986         /*
987          * Map the clone.  If r == 0 we don't need to do
988          * anything, the target has assumed ownership of
989          * this io.
990          */
991         atomic_inc(&tio->io->io_count);
992         sector = clone->bi_sector;
993         r = ti->type->map(ti, clone);
994         if (r == DM_MAPIO_REMAPPED) {
995                 /* the bio has been remapped so dispatch it */
996
997                 trace_block_bio_remap(bdev_get_queue(clone->bi_bdev), clone,
998                                       tio->io->bio->bi_bdev->bd_dev, sector);
999
1000                 generic_make_request(clone);
1001         } else if (r < 0 || r == DM_MAPIO_REQUEUE) {
1002                 /* error the io and bail out, or requeue it if needed */
1003                 md = tio->io->md;
1004                 dec_pending(tio->io, r);
1005                 free_tio(md, tio);
1006         } else if (r) {
1007                 DMWARN("unimplemented target map return value: %d", r);
1008                 BUG();
1009         }
1010 }
1011
1012 struct clone_info {
1013         struct mapped_device *md;
1014         struct dm_table *map;
1015         struct bio *bio;
1016         struct dm_io *io;
1017         sector_t sector;
1018         sector_t sector_count;
1019         unsigned short idx;
1020 };
1021
1022 static void bio_setup_sector(struct bio *bio, sector_t sector, sector_t len)
1023 {
1024         bio->bi_sector = sector;
1025         bio->bi_size = to_bytes(len);
1026 }
1027
1028 static void bio_setup_bv(struct bio *bio, unsigned short idx, unsigned short bv_count)
1029 {
1030         bio->bi_idx = idx;
1031         bio->bi_vcnt = idx + bv_count;
1032         bio->bi_flags &= ~(1 << BIO_SEG_VALID);
1033 }
1034
1035 static void clone_bio_integrity(struct bio *bio, struct bio *clone,
1036                                 unsigned short idx, unsigned len, unsigned offset,
1037                                 unsigned trim)
1038 {
1039         if (!bio_integrity(bio))
1040                 return;
1041
1042         bio_integrity_clone(clone, bio, GFP_NOIO);
1043
1044         if (trim)
1045                 bio_integrity_trim(clone, bio_sector_offset(bio, idx, offset), len);
1046 }
1047
1048 /*
1049  * Creates a little bio that just does part of a bvec.
1050  */
1051 static void clone_split_bio(struct dm_target_io *tio, struct bio *bio,
1052                             sector_t sector, unsigned short idx,
1053                             unsigned offset, unsigned len)
1054 {
1055         struct bio *clone = &tio->clone;
1056         struct bio_vec *bv = bio->bi_io_vec + idx;
1057
1058         *clone->bi_io_vec = *bv;
1059
1060         bio_setup_sector(clone, sector, len);
1061
1062         clone->bi_bdev = bio->bi_bdev;
1063         clone->bi_rw = bio->bi_rw;
1064         clone->bi_vcnt = 1;
1065         clone->bi_io_vec->bv_offset = offset;
1066         clone->bi_io_vec->bv_len = clone->bi_size;
1067         clone->bi_flags |= 1 << BIO_CLONED;
1068
1069         clone_bio_integrity(bio, clone, idx, len, offset, 1);
1070 }
1071
1072 /*
1073  * Creates a bio that consists of range of complete bvecs.
1074  */
1075 static void clone_bio(struct dm_target_io *tio, struct bio *bio,
1076                       sector_t sector, unsigned short idx,
1077                       unsigned short bv_count, unsigned len)
1078 {
1079         struct bio *clone = &tio->clone;
1080         unsigned trim = 0;
1081
1082         __bio_clone(clone, bio);
1083         bio_setup_sector(clone, sector, len);
1084         bio_setup_bv(clone, idx, bv_count);
1085
1086         if (idx != bio->bi_idx || clone->bi_size < bio->bi_size)
1087                 trim = 1;
1088         clone_bio_integrity(bio, clone, idx, len, 0, trim);
1089 }
1090
1091 static struct dm_target_io *alloc_tio(struct clone_info *ci,
1092                                       struct dm_target *ti, int nr_iovecs,
1093                                       unsigned target_bio_nr)
1094 {
1095         struct dm_target_io *tio;
1096         struct bio *clone;
1097
1098         clone = bio_alloc_bioset(GFP_NOIO, nr_iovecs, ci->md->bs);
1099         tio = container_of(clone, struct dm_target_io, clone);
1100
1101         tio->io = ci->io;
1102         tio->ti = ti;
1103         memset(&tio->info, 0, sizeof(tio->info));
1104         tio->target_bio_nr = target_bio_nr;
1105
1106         return tio;
1107 }
1108
1109 static void __clone_and_map_simple_bio(struct clone_info *ci,
1110                                        struct dm_target *ti,
1111                                        unsigned target_bio_nr, sector_t len)
1112 {
1113         struct dm_target_io *tio = alloc_tio(ci, ti, ci->bio->bi_max_vecs, target_bio_nr);
1114         struct bio *clone = &tio->clone;
1115
1116         /*
1117          * Discard requests require the bio's inline iovecs be initialized.
1118          * ci->bio->bi_max_vecs is BIO_INLINE_VECS anyway, for both flush
1119          * and discard, so no need for concern about wasted bvec allocations.
1120          */
1121          __bio_clone(clone, ci->bio);
1122         if (len)
1123                 bio_setup_sector(clone, ci->sector, len);
1124
1125         __map_bio(tio);
1126 }
1127
1128 static void __send_duplicate_bios(struct clone_info *ci, struct dm_target *ti,
1129                                   unsigned num_bios, sector_t len)
1130 {
1131         unsigned target_bio_nr;
1132
1133         for (target_bio_nr = 0; target_bio_nr < num_bios; target_bio_nr++)
1134                 __clone_and_map_simple_bio(ci, ti, target_bio_nr, len);
1135 }
1136
1137 static int __send_empty_flush(struct clone_info *ci)
1138 {
1139         unsigned target_nr = 0;
1140         struct dm_target *ti;
1141
1142         BUG_ON(bio_has_data(ci->bio));
1143         while ((ti = dm_table_get_target(ci->map, target_nr++)))
1144                 __send_duplicate_bios(ci, ti, ti->num_flush_bios, 0);
1145
1146         return 0;
1147 }
1148
1149 static void __clone_and_map_data_bio(struct clone_info *ci, struct dm_target *ti,
1150                                      sector_t sector, int nr_iovecs,
1151                                      unsigned short idx, unsigned short bv_count,
1152                                      unsigned offset, unsigned len,
1153                                      unsigned split_bvec)
1154 {
1155         struct bio *bio = ci->bio;
1156         struct dm_target_io *tio;
1157         unsigned target_bio_nr;
1158         unsigned num_target_bios = 1;
1159
1160         /*
1161          * Does the target want to receive duplicate copies of the bio?
1162          */
1163         if (bio_data_dir(bio) == WRITE && ti->num_write_bios)
1164                 num_target_bios = ti->num_write_bios(ti, bio);
1165
1166         for (target_bio_nr = 0; target_bio_nr < num_target_bios; target_bio_nr++) {
1167                 tio = alloc_tio(ci, ti, nr_iovecs, target_bio_nr);
1168                 if (split_bvec)
1169                         clone_split_bio(tio, bio, sector, idx, offset, len);
1170                 else
1171                         clone_bio(tio, bio, sector, idx, bv_count, len);
1172                 __map_bio(tio);
1173         }
1174 }
1175
1176 typedef unsigned (*get_num_bios_fn)(struct dm_target *ti);
1177
1178 static unsigned get_num_discard_bios(struct dm_target *ti)
1179 {
1180         return ti->num_discard_bios;
1181 }
1182
1183 static unsigned get_num_write_same_bios(struct dm_target *ti)
1184 {
1185         return ti->num_write_same_bios;
1186 }
1187
1188 typedef bool (*is_split_required_fn)(struct dm_target *ti);
1189
1190 static bool is_split_required_for_discard(struct dm_target *ti)
1191 {
1192         return ti->split_discard_bios;
1193 }
1194
1195 static int __send_changing_extent_only(struct clone_info *ci,
1196                                        get_num_bios_fn get_num_bios,
1197                                        is_split_required_fn is_split_required)
1198 {
1199         struct dm_target *ti;
1200         sector_t len;
1201         unsigned num_bios;
1202
1203         do {
1204                 ti = dm_table_find_target(ci->map, ci->sector);
1205                 if (!dm_target_is_valid(ti))
1206                         return -EIO;
1207
1208                 /*
1209                  * Even though the device advertised support for this type of
1210                  * request, that does not mean every target supports it, and
1211                  * reconfiguration might also have changed that since the
1212                  * check was performed.
1213                  */
1214                 num_bios = get_num_bios ? get_num_bios(ti) : 0;
1215                 if (!num_bios)
1216                         return -EOPNOTSUPP;
1217
1218                 if (is_split_required && !is_split_required(ti))
1219                         len = min(ci->sector_count, max_io_len_target_boundary(ci->sector, ti));
1220                 else
1221                         len = min(ci->sector_count, max_io_len(ci->sector, ti));
1222
1223                 __send_duplicate_bios(ci, ti, num_bios, len);
1224
1225                 ci->sector += len;
1226         } while (ci->sector_count -= len);
1227
1228         return 0;
1229 }
1230
1231 static int __send_discard(struct clone_info *ci)
1232 {
1233         return __send_changing_extent_only(ci, get_num_discard_bios,
1234                                            is_split_required_for_discard);
1235 }
1236
1237 static int __send_write_same(struct clone_info *ci)
1238 {
1239         return __send_changing_extent_only(ci, get_num_write_same_bios, NULL);
1240 }
1241
1242 /*
1243  * Find maximum number of sectors / bvecs we can process with a single bio.
1244  */
1245 static sector_t __len_within_target(struct clone_info *ci, sector_t max, int *idx)
1246 {
1247         struct bio *bio = ci->bio;
1248         sector_t bv_len, total_len = 0;
1249
1250         for (*idx = ci->idx; max && (*idx < bio->bi_vcnt); (*idx)++) {
1251                 bv_len = to_sector(bio->bi_io_vec[*idx].bv_len);
1252
1253                 if (bv_len > max)
1254                         break;
1255
1256                 max -= bv_len;
1257                 total_len += bv_len;
1258         }
1259
1260         return total_len;
1261 }
1262
1263 static int __split_bvec_across_targets(struct clone_info *ci,
1264                                        struct dm_target *ti, sector_t max)
1265 {
1266         struct bio *bio = ci->bio;
1267         struct bio_vec *bv = bio->bi_io_vec + ci->idx;
1268         sector_t remaining = to_sector(bv->bv_len);
1269         unsigned offset = 0;
1270         sector_t len;
1271
1272         do {
1273                 if (offset) {
1274                         ti = dm_table_find_target(ci->map, ci->sector);
1275                         if (!dm_target_is_valid(ti))
1276                                 return -EIO;
1277
1278                         max = max_io_len(ci->sector, ti);
1279                 }
1280
1281                 len = min(remaining, max);
1282
1283                 __clone_and_map_data_bio(ci, ti, ci->sector, 1, ci->idx, 0,
1284                                          bv->bv_offset + offset, len, 1);
1285
1286                 ci->sector += len;
1287                 ci->sector_count -= len;
1288                 offset += to_bytes(len);
1289         } while (remaining -= len);
1290
1291         ci->idx++;
1292
1293         return 0;
1294 }
1295
1296 /*
1297  * Select the correct strategy for processing a non-flush bio.
1298  */
1299 static int __split_and_process_non_flush(struct clone_info *ci)
1300 {
1301         struct bio *bio = ci->bio;
1302         struct dm_target *ti;
1303         sector_t len, max;
1304         int idx;
1305
1306         if (unlikely(bio->bi_rw & REQ_DISCARD))
1307                 return __send_discard(ci);
1308         else if (unlikely(bio->bi_rw & REQ_WRITE_SAME))
1309                 return __send_write_same(ci);
1310
1311         ti = dm_table_find_target(ci->map, ci->sector);
1312         if (!dm_target_is_valid(ti))
1313                 return -EIO;
1314
1315         max = max_io_len(ci->sector, ti);
1316
1317         /*
1318          * Optimise for the simple case where we can do all of
1319          * the remaining io with a single clone.
1320          */
1321         if (ci->sector_count <= max) {
1322                 __clone_and_map_data_bio(ci, ti, ci->sector, bio->bi_max_vecs,
1323                                          ci->idx, bio->bi_vcnt - ci->idx, 0,
1324                                          ci->sector_count, 0);
1325                 ci->sector_count = 0;
1326                 return 0;
1327         }
1328
1329         /*
1330          * There are some bvecs that don't span targets.
1331          * Do as many of these as possible.
1332          */
1333         if (to_sector(bio->bi_io_vec[ci->idx].bv_len) <= max) {
1334                 len = __len_within_target(ci, max, &idx);
1335
1336                 __clone_and_map_data_bio(ci, ti, ci->sector, bio->bi_max_vecs,
1337                                          ci->idx, idx - ci->idx, 0, len, 0);
1338
1339                 ci->sector += len;
1340                 ci->sector_count -= len;
1341                 ci->idx = idx;
1342
1343                 return 0;
1344         }
1345
1346         /*
1347          * Handle a bvec that must be split between two or more targets.
1348          */
1349         return __split_bvec_across_targets(ci, ti, max);
1350 }
1351
1352 /*
1353  * Entry point to split a bio into clones and submit them to the targets.
1354  */
1355 static void __split_and_process_bio(struct mapped_device *md, struct bio *bio)
1356 {
1357         struct clone_info ci;
1358         int error = 0;
1359
1360         ci.map = dm_get_live_table(md);
1361         if (unlikely(!ci.map)) {
1362                 bio_io_error(bio);
1363                 return;
1364         }
1365
1366         ci.md = md;
1367         ci.io = alloc_io(md);
1368         ci.io->error = 0;
1369         atomic_set(&ci.io->io_count, 1);
1370         ci.io->bio = bio;
1371         ci.io->md = md;
1372         spin_lock_init(&ci.io->endio_lock);
1373         ci.sector = bio->bi_sector;
1374         ci.idx = bio->bi_idx;
1375
1376         start_io_acct(ci.io);
1377
1378         if (bio->bi_rw & REQ_FLUSH) {
1379                 ci.bio = &ci.md->flush_bio;
1380                 ci.sector_count = 0;
1381                 error = __send_empty_flush(&ci);
1382                 /* dec_pending submits any data associated with flush */
1383         } else {
1384                 ci.bio = bio;
1385                 ci.sector_count = bio_sectors(bio);
1386                 while (ci.sector_count && !error)
1387                         error = __split_and_process_non_flush(&ci);
1388         }
1389
1390         /* drop the extra reference count */
1391         dec_pending(ci.io, error);
1392         dm_table_put(ci.map);
1393 }
1394 /*-----------------------------------------------------------------
1395  * CRUD END
1396  *---------------------------------------------------------------*/
1397
1398 static int dm_merge_bvec(struct request_queue *q,
1399                          struct bvec_merge_data *bvm,
1400                          struct bio_vec *biovec)
1401 {
1402         struct mapped_device *md = q->queuedata;
1403         struct dm_table *map = dm_get_live_table(md);
1404         struct dm_target *ti;
1405         sector_t max_sectors;
1406         int max_size = 0;
1407
1408         if (unlikely(!map))
1409                 goto out;
1410
1411         ti = dm_table_find_target(map, bvm->bi_sector);
1412         if (!dm_target_is_valid(ti))
1413                 goto out_table;
1414
1415         /*
1416          * Find maximum amount of I/O that won't need splitting
1417          */
1418         max_sectors = min(max_io_len(bvm->bi_sector, ti),
1419                           (sector_t) BIO_MAX_SECTORS);
1420         max_size = (max_sectors << SECTOR_SHIFT) - bvm->bi_size;
1421         if (max_size < 0)
1422                 max_size = 0;
1423
1424         /*
1425          * merge_bvec_fn() returns number of bytes
1426          * it can accept at this offset
1427          * max is precomputed maximal io size
1428          */
1429         if (max_size && ti->type->merge)
1430                 max_size = ti->type->merge(ti, bvm, biovec, max_size);
1431         /*
1432          * If the target doesn't support merge method and some of the devices
1433          * provided their merge_bvec method (we know this by looking at
1434          * queue_max_hw_sectors), then we can't allow bios with multiple vector
1435          * entries.  So always set max_size to 0, and the code below allows
1436          * just one page.
1437          */
1438         else if (queue_max_hw_sectors(q) <= PAGE_SIZE >> 9)
1439
1440                 max_size = 0;
1441
1442 out_table:
1443         dm_table_put(map);
1444
1445 out:
1446         /*
1447          * Always allow an entire first page
1448          */
1449         if (max_size <= biovec->bv_len && !(bvm->bi_size >> SECTOR_SHIFT))
1450                 max_size = biovec->bv_len;
1451
1452         return max_size;
1453 }
1454
1455 /*
1456  * The request function that just remaps the bio built up by
1457  * dm_merge_bvec.
1458  */
1459 static void _dm_request(struct request_queue *q, struct bio *bio)
1460 {
1461         int rw = bio_data_dir(bio);
1462         struct mapped_device *md = q->queuedata;
1463         int cpu;
1464
1465         down_read(&md->io_lock);
1466
1467         cpu = part_stat_lock();
1468         part_stat_inc(cpu, &dm_disk(md)->part0, ios[rw]);
1469         part_stat_add(cpu, &dm_disk(md)->part0, sectors[rw], bio_sectors(bio));
1470         part_stat_unlock();
1471
1472         /* if we're suspended, we have to queue this io for later */
1473         if (unlikely(test_bit(DMF_BLOCK_IO_FOR_SUSPEND, &md->flags))) {
1474                 up_read(&md->io_lock);
1475
1476                 if (bio_rw(bio) != READA)
1477                         queue_io(md, bio);
1478                 else
1479                         bio_io_error(bio);
1480                 return;
1481         }
1482
1483         __split_and_process_bio(md, bio);
1484         up_read(&md->io_lock);
1485         return;
1486 }
1487
1488 static int dm_request_based(struct mapped_device *md)
1489 {
1490         return blk_queue_stackable(md->queue);
1491 }
1492
1493 static void dm_request(struct request_queue *q, struct bio *bio)
1494 {
1495         struct mapped_device *md = q->queuedata;
1496
1497         if (dm_request_based(md))
1498                 blk_queue_bio(q, bio);
1499         else
1500                 _dm_request(q, bio);
1501 }
1502
1503 void dm_dispatch_request(struct request *rq)
1504 {
1505         int r;
1506
1507         if (blk_queue_io_stat(rq->q))
1508                 rq->cmd_flags |= REQ_IO_STAT;
1509
1510         rq->start_time = jiffies;
1511         r = blk_insert_cloned_request(rq->q, rq);
1512         if (r)
1513                 dm_complete_request(rq, r);
1514 }
1515 EXPORT_SYMBOL_GPL(dm_dispatch_request);
1516
1517 static int dm_rq_bio_constructor(struct bio *bio, struct bio *bio_orig,
1518                                  void *data)
1519 {
1520         struct dm_rq_target_io *tio = data;
1521         struct dm_rq_clone_bio_info *info =
1522                 container_of(bio, struct dm_rq_clone_bio_info, clone);
1523
1524         info->orig = bio_orig;
1525         info->tio = tio;
1526         bio->bi_end_io = end_clone_bio;
1527         bio->bi_private = info;
1528
1529         return 0;
1530 }
1531
1532 static int setup_clone(struct request *clone, struct request *rq,
1533                        struct dm_rq_target_io *tio)
1534 {
1535         int r;
1536
1537         r = blk_rq_prep_clone(clone, rq, tio->md->bs, GFP_ATOMIC,
1538                               dm_rq_bio_constructor, tio);
1539         if (r)
1540                 return r;
1541
1542         clone->cmd = rq->cmd;
1543         clone->cmd_len = rq->cmd_len;
1544         clone->sense = rq->sense;
1545         clone->buffer = rq->buffer;
1546         clone->end_io = end_clone_request;
1547         clone->end_io_data = tio;
1548
1549         return 0;
1550 }
1551
1552 static struct request *clone_rq(struct request *rq, struct mapped_device *md,
1553                                 gfp_t gfp_mask)
1554 {
1555         struct request *clone;
1556         struct dm_rq_target_io *tio;
1557
1558         tio = alloc_rq_tio(md, gfp_mask);
1559         if (!tio)
1560                 return NULL;
1561
1562         tio->md = md;
1563         tio->ti = NULL;
1564         tio->orig = rq;
1565         tio->error = 0;
1566         memset(&tio->info, 0, sizeof(tio->info));
1567
1568         clone = &tio->clone;
1569         if (setup_clone(clone, rq, tio)) {
1570                 /* -ENOMEM */
1571                 free_rq_tio(tio);
1572                 return NULL;
1573         }
1574
1575         return clone;
1576 }
1577
1578 /*
1579  * Called with the queue lock held.
1580  */
1581 static int dm_prep_fn(struct request_queue *q, struct request *rq)
1582 {
1583         struct mapped_device *md = q->queuedata;
1584         struct request *clone;
1585
1586         if (unlikely(rq->special)) {
1587                 DMWARN("Already has something in rq->special.");
1588                 return BLKPREP_KILL;
1589         }
1590
1591         clone = clone_rq(rq, md, GFP_ATOMIC);
1592         if (!clone)
1593                 return BLKPREP_DEFER;
1594
1595         rq->special = clone;
1596         rq->cmd_flags |= REQ_DONTPREP;
1597
1598         return BLKPREP_OK;
1599 }
1600
1601 /*
1602  * Returns:
1603  * 0  : the request has been processed (not requeued)
1604  * !0 : the request has been requeued
1605  */
1606 static int map_request(struct dm_target *ti, struct request *clone,
1607                        struct mapped_device *md)
1608 {
1609         int r, requeued = 0;
1610         struct dm_rq_target_io *tio = clone->end_io_data;
1611
1612         tio->ti = ti;
1613         r = ti->type->map_rq(ti, clone, &tio->info);
1614         switch (r) {
1615         case DM_MAPIO_SUBMITTED:
1616                 /* The target has taken the I/O to submit by itself later */
1617                 break;
1618         case DM_MAPIO_REMAPPED:
1619                 /* The target has remapped the I/O so dispatch it */
1620                 trace_block_rq_remap(clone->q, clone, disk_devt(dm_disk(md)),
1621                                      blk_rq_pos(tio->orig));
1622                 dm_dispatch_request(clone);
1623                 break;
1624         case DM_MAPIO_REQUEUE:
1625                 /* The target wants to requeue the I/O */
1626                 dm_requeue_unmapped_request(clone);
1627                 requeued = 1;
1628                 break;
1629         default:
1630                 if (r > 0) {
1631                         DMWARN("unimplemented target map return value: %d", r);
1632                         BUG();
1633                 }
1634
1635                 /* The target wants to complete the I/O */
1636                 dm_kill_unmapped_request(clone, r);
1637                 break;
1638         }
1639
1640         return requeued;
1641 }
1642
1643 static struct request *dm_start_request(struct mapped_device *md, struct request *orig)
1644 {
1645         struct request *clone;
1646
1647         blk_start_request(orig);
1648         clone = orig->special;
1649         atomic_inc(&md->pending[rq_data_dir(clone)]);
1650
1651         /*
1652          * Hold the md reference here for the in-flight I/O.
1653          * We can't rely on the reference count by device opener,
1654          * because the device may be closed during the request completion
1655          * when all bios are completed.
1656          * See the comment in rq_completed() too.
1657          */
1658         dm_get(md);
1659
1660         return clone;
1661 }
1662
1663 /*
1664  * q->request_fn for request-based dm.
1665  * Called with the queue lock held.
1666  */
1667 static void dm_request_fn(struct request_queue *q)
1668 {
1669         struct mapped_device *md = q->queuedata;
1670         struct dm_table *map = dm_get_live_table(md);
1671         struct dm_target *ti;
1672         struct request *rq, *clone;
1673         sector_t pos;
1674
1675         /*
1676          * For suspend, check blk_queue_stopped() and increment
1677          * ->pending within a single queue_lock not to increment the
1678          * number of in-flight I/Os after the queue is stopped in
1679          * dm_suspend().
1680          */
1681         while (!blk_queue_stopped(q)) {
1682                 rq = blk_peek_request(q);
1683                 if (!rq)
1684                         goto delay_and_out;
1685
1686                 /* always use block 0 to find the target for flushes for now */
1687                 pos = 0;
1688                 if (!(rq->cmd_flags & REQ_FLUSH))
1689                         pos = blk_rq_pos(rq);
1690
1691                 ti = dm_table_find_target(map, pos);
1692                 if (!dm_target_is_valid(ti)) {
1693                         /*
1694                          * Must perform setup, that dm_done() requires,
1695                          * before calling dm_kill_unmapped_request
1696                          */
1697                         DMERR_LIMIT("request attempted access beyond the end of device");
1698                         clone = dm_start_request(md, rq);
1699                         dm_kill_unmapped_request(clone, -EIO);
1700                         continue;
1701                 }
1702
1703                 if (ti->type->busy && ti->type->busy(ti))
1704                         goto delay_and_out;
1705
1706                 clone = dm_start_request(md, rq);
1707
1708                 spin_unlock(q->queue_lock);
1709                 if (map_request(ti, clone, md))
1710                         goto requeued;
1711
1712                 BUG_ON(!irqs_disabled());
1713                 spin_lock(q->queue_lock);
1714         }
1715
1716         goto out;
1717
1718 requeued:
1719         BUG_ON(!irqs_disabled());
1720         spin_lock(q->queue_lock);
1721
1722 delay_and_out:
1723         blk_delay_queue(q, HZ / 10);
1724 out:
1725         dm_table_put(map);
1726 }
1727
1728 int dm_underlying_device_busy(struct request_queue *q)
1729 {
1730         return blk_lld_busy(q);
1731 }
1732 EXPORT_SYMBOL_GPL(dm_underlying_device_busy);
1733
1734 static int dm_lld_busy(struct request_queue *q)
1735 {
1736         int r;
1737         struct mapped_device *md = q->queuedata;
1738         struct dm_table *map = dm_get_live_table(md);
1739
1740         if (!map || test_bit(DMF_BLOCK_IO_FOR_SUSPEND, &md->flags))
1741                 r = 1;
1742         else
1743                 r = dm_table_any_busy_target(map);
1744
1745         dm_table_put(map);
1746
1747         return r;
1748 }
1749
1750 static int dm_any_congested(void *congested_data, int bdi_bits)
1751 {
1752         int r = bdi_bits;
1753         struct mapped_device *md = congested_data;
1754         struct dm_table *map;
1755
1756         if (!test_bit(DMF_BLOCK_IO_FOR_SUSPEND, &md->flags)) {
1757                 map = dm_get_live_table(md);
1758                 if (map) {
1759                         /*
1760                          * Request-based dm cares about only own queue for
1761                          * the query about congestion status of request_queue
1762                          */
1763                         if (dm_request_based(md))
1764                                 r = md->queue->backing_dev_info.state &
1765                                     bdi_bits;
1766                         else
1767                                 r = dm_table_any_congested(map, bdi_bits);
1768
1769                         dm_table_put(map);
1770                 }
1771         }
1772
1773         return r;
1774 }
1775
1776 /*-----------------------------------------------------------------
1777  * An IDR is used to keep track of allocated minor numbers.
1778  *---------------------------------------------------------------*/
1779 static void free_minor(int minor)
1780 {
1781         spin_lock(&_minor_lock);
1782         idr_remove(&_minor_idr, minor);
1783         spin_unlock(&_minor_lock);
1784 }
1785
1786 /*
1787  * See if the device with a specific minor # is free.
1788  */
1789 static int specific_minor(int minor)
1790 {
1791         int r;
1792
1793         if (minor >= (1 << MINORBITS))
1794                 return -EINVAL;
1795
1796         idr_preload(GFP_KERNEL);
1797         spin_lock(&_minor_lock);
1798
1799         r = idr_alloc(&_minor_idr, MINOR_ALLOCED, minor, minor + 1, GFP_NOWAIT);
1800
1801         spin_unlock(&_minor_lock);
1802         idr_preload_end();
1803         if (r < 0)
1804                 return r == -ENOSPC ? -EBUSY : r;
1805         return 0;
1806 }
1807
1808 static int next_free_minor(int *minor)
1809 {
1810         int r;
1811
1812         idr_preload(GFP_KERNEL);
1813         spin_lock(&_minor_lock);
1814
1815         r = idr_alloc(&_minor_idr, MINOR_ALLOCED, 0, 1 << MINORBITS, GFP_NOWAIT);
1816
1817         spin_unlock(&_minor_lock);
1818         idr_preload_end();
1819         if (r < 0)
1820                 return r;
1821         *minor = r;
1822         return 0;
1823 }
1824
1825 static const struct block_device_operations dm_blk_dops;
1826
1827 static void dm_wq_work(struct work_struct *work);
1828
1829 static void dm_init_md_queue(struct mapped_device *md)
1830 {
1831         /*
1832          * Request-based dm devices cannot be stacked on top of bio-based dm
1833          * devices.  The type of this dm device has not been decided yet.
1834          * The type is decided at the first table loading time.
1835          * To prevent problematic device stacking, clear the queue flag
1836          * for request stacking support until then.
1837          *
1838          * This queue is new, so no concurrency on the queue_flags.
1839          */
1840         queue_flag_clear_unlocked(QUEUE_FLAG_STACKABLE, md->queue);
1841
1842         md->queue->queuedata = md;
1843         md->queue->backing_dev_info.congested_fn = dm_any_congested;
1844         md->queue->backing_dev_info.congested_data = md;
1845         blk_queue_make_request(md->queue, dm_request);
1846         blk_queue_bounce_limit(md->queue, BLK_BOUNCE_ANY);
1847         blk_queue_merge_bvec(md->queue, dm_merge_bvec);
1848 }
1849
1850 /*
1851  * Allocate and initialise a blank device with a given minor.
1852  */
1853 static struct mapped_device *alloc_dev(int minor)
1854 {
1855         int r;
1856         struct mapped_device *md = kzalloc(sizeof(*md), GFP_KERNEL);
1857         void *old_md;
1858
1859         if (!md) {
1860                 DMWARN("unable to allocate device, out of memory.");
1861                 return NULL;
1862         }
1863
1864         if (!try_module_get(THIS_MODULE))
1865                 goto bad_module_get;
1866
1867         /* get a minor number for the dev */
1868         if (minor == DM_ANY_MINOR)
1869                 r = next_free_minor(&minor);
1870         else
1871                 r = specific_minor(minor);
1872         if (r < 0)
1873                 goto bad_minor;
1874
1875         md->type = DM_TYPE_NONE;
1876         init_rwsem(&md->io_lock);
1877         mutex_init(&md->suspend_lock);
1878         mutex_init(&md->type_lock);
1879         spin_lock_init(&md->deferred_lock);
1880         rwlock_init(&md->map_lock);
1881         atomic_set(&md->holders, 1);
1882         atomic_set(&md->open_count, 0);
1883         atomic_set(&md->event_nr, 0);
1884         atomic_set(&md->uevent_seq, 0);
1885         INIT_LIST_HEAD(&md->uevent_list);
1886         spin_lock_init(&md->uevent_lock);
1887
1888         md->queue = blk_alloc_queue(GFP_KERNEL);
1889         if (!md->queue)
1890                 goto bad_queue;
1891
1892         dm_init_md_queue(md);
1893
1894         md->disk = alloc_disk(1);
1895         if (!md->disk)
1896                 goto bad_disk;
1897
1898         atomic_set(&md->pending[0], 0);
1899         atomic_set(&md->pending[1], 0);
1900         init_waitqueue_head(&md->wait);
1901         INIT_WORK(&md->work, dm_wq_work);
1902         init_waitqueue_head(&md->eventq);
1903
1904         md->disk->major = _major;
1905         md->disk->first_minor = minor;
1906         md->disk->fops = &dm_blk_dops;
1907         md->disk->queue = md->queue;
1908         md->disk->private_data = md;
1909         sprintf(md->disk->disk_name, "dm-%d", minor);
1910         add_disk(md->disk);
1911         format_dev_t(md->name, MKDEV(_major, minor));
1912
1913         md->wq = alloc_workqueue("kdmflush",
1914                                  WQ_NON_REENTRANT | WQ_MEM_RECLAIM, 0);
1915         if (!md->wq)
1916                 goto bad_thread;
1917
1918         md->bdev = bdget_disk(md->disk, 0);
1919         if (!md->bdev)
1920                 goto bad_bdev;
1921
1922         bio_init(&md->flush_bio);
1923         md->flush_bio.bi_bdev = md->bdev;
1924         md->flush_bio.bi_rw = WRITE_FLUSH;
1925
1926         /* Populate the mapping, nobody knows we exist yet */
1927         spin_lock(&_minor_lock);
1928         old_md = idr_replace(&_minor_idr, md, minor);
1929         spin_unlock(&_minor_lock);
1930
1931         BUG_ON(old_md != MINOR_ALLOCED);
1932
1933         return md;
1934
1935 bad_bdev:
1936         destroy_workqueue(md->wq);
1937 bad_thread:
1938         del_gendisk(md->disk);
1939         put_disk(md->disk);
1940 bad_disk:
1941         blk_cleanup_queue(md->queue);
1942 bad_queue:
1943         free_minor(minor);
1944 bad_minor:
1945         module_put(THIS_MODULE);
1946 bad_module_get:
1947         kfree(md);
1948         return NULL;
1949 }
1950
1951 static void unlock_fs(struct mapped_device *md);
1952
1953 static void free_dev(struct mapped_device *md)
1954 {
1955         int minor = MINOR(disk_devt(md->disk));
1956
1957         unlock_fs(md);
1958         bdput(md->bdev);
1959         destroy_workqueue(md->wq);
1960         if (md->io_pool)
1961                 mempool_destroy(md->io_pool);
1962         if (md->bs)
1963                 bioset_free(md->bs);
1964         blk_integrity_unregister(md->disk);
1965         del_gendisk(md->disk);
1966         free_minor(minor);
1967
1968         spin_lock(&_minor_lock);
1969         md->disk->private_data = NULL;
1970         spin_unlock(&_minor_lock);
1971
1972         put_disk(md->disk);
1973         blk_cleanup_queue(md->queue);
1974         module_put(THIS_MODULE);
1975         kfree(md);
1976 }
1977
1978 static void __bind_mempools(struct mapped_device *md, struct dm_table *t)
1979 {
1980         struct dm_md_mempools *p = dm_table_get_md_mempools(t);
1981
1982         if (md->io_pool && md->bs) {
1983                 /* The md already has necessary mempools. */
1984                 if (dm_table_get_type(t) == DM_TYPE_BIO_BASED) {
1985                         /*
1986                          * Reload bioset because front_pad may have changed
1987                          * because a different table was loaded.
1988                          */
1989                         bioset_free(md->bs);
1990                         md->bs = p->bs;
1991                         p->bs = NULL;
1992                 } else if (dm_table_get_type(t) == DM_TYPE_REQUEST_BASED) {
1993                         /*
1994                          * There's no need to reload with request-based dm
1995                          * because the size of front_pad doesn't change.
1996                          * Note for future: If you are to reload bioset,
1997                          * prep-ed requests in the queue may refer
1998                          * to bio from the old bioset, so you must walk
1999                          * through the queue to unprep.
2000                          */
2001                 }
2002                 goto out;
2003         }
2004
2005         BUG_ON(!p || md->io_pool || md->bs);
2006
2007         md->io_pool = p->io_pool;
2008         p->io_pool = NULL;
2009         md->bs = p->bs;
2010         p->bs = NULL;
2011
2012 out:
2013         /* mempool bind completed, now no need any mempools in the table */
2014         dm_table_free_md_mempools(t);
2015 }
2016
2017 /*
2018  * Bind a table to the device.
2019  */
2020 static void event_callback(void *context)
2021 {
2022         unsigned long flags;
2023         LIST_HEAD(uevents);
2024         struct mapped_device *md = (struct mapped_device *) context;
2025
2026         spin_lock_irqsave(&md->uevent_lock, flags);
2027         list_splice_init(&md->uevent_list, &uevents);
2028         spin_unlock_irqrestore(&md->uevent_lock, flags);
2029
2030         dm_send_uevents(&uevents, &disk_to_dev(md->disk)->kobj);
2031
2032         atomic_inc(&md->event_nr);
2033         wake_up(&md->eventq);
2034 }
2035
2036 /*
2037  * Protected by md->suspend_lock obtained by dm_swap_table().
2038  */
2039 static void __set_size(struct mapped_device *md, sector_t size)
2040 {
2041         set_capacity(md->disk, size);
2042
2043         i_size_write(md->bdev->bd_inode, (loff_t)size << SECTOR_SHIFT);
2044 }
2045
2046 /*
2047  * Return 1 if the queue has a compulsory merge_bvec_fn function.
2048  *
2049  * If this function returns 0, then the device is either a non-dm
2050  * device without a merge_bvec_fn, or it is a dm device that is
2051  * able to split any bios it receives that are too big.
2052  */
2053 int dm_queue_merge_is_compulsory(struct request_queue *q)
2054 {
2055         struct mapped_device *dev_md;
2056
2057         if (!q->merge_bvec_fn)
2058                 return 0;
2059
2060         if (q->make_request_fn == dm_request) {
2061                 dev_md = q->queuedata;
2062                 if (test_bit(DMF_MERGE_IS_OPTIONAL, &dev_md->flags))
2063                         return 0;
2064         }
2065
2066         return 1;
2067 }
2068
2069 static int dm_device_merge_is_compulsory(struct dm_target *ti,
2070                                          struct dm_dev *dev, sector_t start,
2071                                          sector_t len, void *data)
2072 {
2073         struct block_device *bdev = dev->bdev;
2074         struct request_queue *q = bdev_get_queue(bdev);
2075
2076         return dm_queue_merge_is_compulsory(q);
2077 }
2078
2079 /*
2080  * Return 1 if it is acceptable to ignore merge_bvec_fn based
2081  * on the properties of the underlying devices.
2082  */
2083 static int dm_table_merge_is_optional(struct dm_table *table)
2084 {
2085         unsigned i = 0;
2086         struct dm_target *ti;
2087
2088         while (i < dm_table_get_num_targets(table)) {
2089                 ti = dm_table_get_target(table, i++);
2090
2091                 if (ti->type->iterate_devices &&
2092                     ti->type->iterate_devices(ti, dm_device_merge_is_compulsory, NULL))
2093                         return 0;
2094         }
2095
2096         return 1;
2097 }
2098
2099 /*
2100  * Returns old map, which caller must destroy.
2101  */
2102 static struct dm_table *__bind(struct mapped_device *md, struct dm_table *t,
2103                                struct queue_limits *limits)
2104 {
2105         struct dm_table *old_map;
2106         struct request_queue *q = md->queue;
2107         sector_t size;
2108         unsigned long flags;
2109         int merge_is_optional;
2110
2111         size = dm_table_get_size(t);
2112
2113         /*
2114          * Wipe any geometry if the size of the table changed.
2115          */
2116         if (size != get_capacity(md->disk))
2117                 memset(&md->geometry, 0, sizeof(md->geometry));
2118
2119         __set_size(md, size);
2120
2121         dm_table_event_callback(t, event_callback, md);
2122
2123         /*
2124          * The queue hasn't been stopped yet, if the old table type wasn't
2125          * for request-based during suspension.  So stop it to prevent
2126          * I/O mapping before resume.
2127          * This must be done before setting the queue restrictions,
2128          * because request-based dm may be run just after the setting.
2129          */
2130         if (dm_table_request_based(t) && !blk_queue_stopped(q))
2131                 stop_queue(q);
2132
2133         __bind_mempools(md, t);
2134
2135         merge_is_optional = dm_table_merge_is_optional(t);
2136
2137         write_lock_irqsave(&md->map_lock, flags);
2138         old_map = md->map;
2139         md->map = t;
2140         md->immutable_target_type = dm_table_get_immutable_target_type(t);
2141
2142         dm_table_set_restrictions(t, q, limits);
2143         if (merge_is_optional)
2144                 set_bit(DMF_MERGE_IS_OPTIONAL, &md->flags);
2145         else
2146                 clear_bit(DMF_MERGE_IS_OPTIONAL, &md->flags);
2147         write_unlock_irqrestore(&md->map_lock, flags);
2148
2149         return old_map;
2150 }
2151
2152 /*
2153  * Returns unbound table for the caller to free.
2154  */
2155 static struct dm_table *__unbind(struct mapped_device *md)
2156 {
2157         struct dm_table *map = md->map;
2158         unsigned long flags;
2159
2160         if (!map)
2161                 return NULL;
2162
2163         dm_table_event_callback(map, NULL, NULL);
2164         write_lock_irqsave(&md->map_lock, flags);
2165         md->map = NULL;
2166         write_unlock_irqrestore(&md->map_lock, flags);
2167
2168         return map;
2169 }
2170
2171 /*
2172  * Constructor for a new device.
2173  */
2174 int dm_create(int minor, struct mapped_device **result)
2175 {
2176         struct mapped_device *md;
2177
2178         md = alloc_dev(minor);
2179         if (!md)
2180                 return -ENXIO;
2181
2182         dm_sysfs_init(md);
2183
2184         *result = md;
2185         return 0;
2186 }
2187
2188 /*
2189  * Functions to manage md->type.
2190  * All are required to hold md->type_lock.
2191  */
2192 void dm_lock_md_type(struct mapped_device *md)
2193 {
2194         mutex_lock(&md->type_lock);
2195 }
2196
2197 void dm_unlock_md_type(struct mapped_device *md)
2198 {
2199         mutex_unlock(&md->type_lock);
2200 }
2201
2202 void dm_set_md_type(struct mapped_device *md, unsigned type)
2203 {
2204         md->type = type;
2205 }
2206
2207 unsigned dm_get_md_type(struct mapped_device *md)
2208 {
2209         return md->type;
2210 }
2211
2212 struct target_type *dm_get_immutable_target_type(struct mapped_device *md)
2213 {
2214         return md->immutable_target_type;
2215 }
2216
2217 /*
2218  * Fully initialize a request-based queue (->elevator, ->request_fn, etc).
2219  */
2220 static int dm_init_request_based_queue(struct mapped_device *md)
2221 {
2222         struct request_queue *q = NULL;
2223
2224         if (md->queue->elevator)
2225                 return 1;
2226
2227         /* Fully initialize the queue */
2228         q = blk_init_allocated_queue(md->queue, dm_request_fn, NULL);
2229         if (!q)
2230                 return 0;
2231
2232         md->queue = q;
2233         dm_init_md_queue(md);
2234         blk_queue_softirq_done(md->queue, dm_softirq_done);
2235         blk_queue_prep_rq(md->queue, dm_prep_fn);
2236         blk_queue_lld_busy(md->queue, dm_lld_busy);
2237
2238         elv_register_queue(md->queue);
2239
2240         return 1;
2241 }
2242
2243 /*
2244  * Setup the DM device's queue based on md's type
2245  */
2246 int dm_setup_md_queue(struct mapped_device *md)
2247 {
2248         if ((dm_get_md_type(md) == DM_TYPE_REQUEST_BASED) &&
2249             !dm_init_request_based_queue(md)) {
2250                 DMWARN("Cannot initialize queue for request-based mapped device");
2251                 return -EINVAL;
2252         }
2253
2254         return 0;
2255 }
2256
2257 static struct mapped_device *dm_find_md(dev_t dev)
2258 {
2259         struct mapped_device *md;
2260         unsigned minor = MINOR(dev);
2261
2262         if (MAJOR(dev) != _major || minor >= (1 << MINORBITS))
2263                 return NULL;
2264
2265         spin_lock(&_minor_lock);
2266
2267         md = idr_find(&_minor_idr, minor);
2268         if (md && (md == MINOR_ALLOCED ||
2269                    (MINOR(disk_devt(dm_disk(md))) != minor) ||
2270                    dm_deleting_md(md) ||
2271                    test_bit(DMF_FREEING, &md->flags))) {
2272                 md = NULL;
2273                 goto out;
2274         }
2275
2276 out:
2277         spin_unlock(&_minor_lock);
2278
2279         return md;
2280 }
2281
2282 struct mapped_device *dm_get_md(dev_t dev)
2283 {
2284         struct mapped_device *md = dm_find_md(dev);
2285
2286         if (md)
2287                 dm_get(md);
2288
2289         return md;
2290 }
2291 EXPORT_SYMBOL_GPL(dm_get_md);
2292
2293 void *dm_get_mdptr(struct mapped_device *md)
2294 {
2295         return md->interface_ptr;
2296 }
2297
2298 void dm_set_mdptr(struct mapped_device *md, void *ptr)
2299 {
2300         md->interface_ptr = ptr;
2301 }
2302
2303 void dm_get(struct mapped_device *md)
2304 {
2305         atomic_inc(&md->holders);
2306         BUG_ON(test_bit(DMF_FREEING, &md->flags));
2307 }
2308
2309 const char *dm_device_name(struct mapped_device *md)
2310 {
2311         return md->name;
2312 }
2313 EXPORT_SYMBOL_GPL(dm_device_name);
2314
2315 static void __dm_destroy(struct mapped_device *md, bool wait)
2316 {
2317         struct dm_table *map;
2318
2319         might_sleep();
2320
2321         spin_lock(&_minor_lock);
2322         map = dm_get_live_table(md);
2323         idr_replace(&_minor_idr, MINOR_ALLOCED, MINOR(disk_devt(dm_disk(md))));
2324         set_bit(DMF_FREEING, &md->flags);
2325         spin_unlock(&_minor_lock);
2326
2327         if (!dm_suspended_md(md)) {
2328                 dm_table_presuspend_targets(map);
2329                 dm_table_postsuspend_targets(map);
2330         }
2331
2332         /*
2333          * Rare, but there may be I/O requests still going to complete,
2334          * for example.  Wait for all references to disappear.
2335          * No one should increment the reference count of the mapped_device,
2336          * after the mapped_device state becomes DMF_FREEING.
2337          */
2338         if (wait)
2339                 while (atomic_read(&md->holders))
2340                         msleep(1);
2341         else if (atomic_read(&md->holders))
2342                 DMWARN("%s: Forcibly removing mapped_device still in use! (%d users)",
2343                        dm_device_name(md), atomic_read(&md->holders));
2344
2345         dm_sysfs_exit(md);
2346         dm_table_put(map);
2347         dm_table_destroy(__unbind(md));
2348         free_dev(md);
2349 }
2350
2351 void dm_destroy(struct mapped_device *md)
2352 {
2353         __dm_destroy(md, true);
2354 }
2355
2356 void dm_destroy_immediate(struct mapped_device *md)
2357 {
2358         __dm_destroy(md, false);
2359 }
2360
2361 void dm_put(struct mapped_device *md)
2362 {
2363         atomic_dec(&md->holders);
2364 }
2365 EXPORT_SYMBOL_GPL(dm_put);
2366
2367 static int dm_wait_for_completion(struct mapped_device *md, int interruptible)
2368 {
2369         int r = 0;
2370         DECLARE_WAITQUEUE(wait, current);
2371
2372         add_wait_queue(&md->wait, &wait);
2373
2374         while (1) {
2375                 set_current_state(interruptible);
2376
2377                 if (!md_in_flight(md))
2378                         break;
2379
2380                 if (interruptible == TASK_INTERRUPTIBLE &&
2381                     signal_pending(current)) {
2382                         r = -EINTR;
2383                         break;
2384                 }
2385
2386                 io_schedule();
2387         }
2388         set_current_state(TASK_RUNNING);
2389
2390         remove_wait_queue(&md->wait, &wait);
2391
2392         return r;
2393 }
2394
2395 /*
2396  * Process the deferred bios
2397  */
2398 static void dm_wq_work(struct work_struct *work)
2399 {
2400         struct mapped_device *md = container_of(work, struct mapped_device,
2401                                                 work);
2402         struct bio *c;
2403
2404         down_read(&md->io_lock);
2405
2406         while (!test_bit(DMF_BLOCK_IO_FOR_SUSPEND, &md->flags)) {
2407                 spin_lock_irq(&md->deferred_lock);
2408                 c = bio_list_pop(&md->deferred);
2409                 spin_unlock_irq(&md->deferred_lock);
2410
2411                 if (!c)
2412                         break;
2413
2414                 up_read(&md->io_lock);
2415
2416                 if (dm_request_based(md))
2417                         generic_make_request(c);
2418                 else
2419                         __split_and_process_bio(md, c);
2420
2421                 down_read(&md->io_lock);
2422         }
2423
2424         up_read(&md->io_lock);
2425 }
2426
2427 static void dm_queue_flush(struct mapped_device *md)
2428 {
2429         clear_bit(DMF_BLOCK_IO_FOR_SUSPEND, &md->flags);
2430         smp_mb__after_clear_bit();
2431         queue_work(md->wq, &md->work);
2432 }
2433
2434 /*
2435  * Swap in a new table, returning the old one for the caller to destroy.
2436  */
2437 struct dm_table *dm_swap_table(struct mapped_device *md, struct dm_table *table)
2438 {
2439         struct dm_table *live_map = NULL, *map = ERR_PTR(-EINVAL);
2440         struct queue_limits limits;
2441         int r;
2442
2443         mutex_lock(&md->suspend_lock);
2444
2445         /* device must be suspended */
2446         if (!dm_suspended_md(md))
2447                 goto out;
2448
2449         /*
2450          * If the new table has no data devices, retain the existing limits.
2451          * This helps multipath with queue_if_no_path if all paths disappear,
2452          * then new I/O is queued based on these limits, and then some paths
2453          * reappear.
2454          */
2455         if (dm_table_has_no_data_devices(table)) {
2456                 live_map = dm_get_live_table(md);
2457                 if (live_map)
2458                         limits = md->queue->limits;
2459                 dm_table_put(live_map);
2460         }
2461
2462         if (!live_map) {
2463                 r = dm_calculate_queue_limits(table, &limits);
2464                 if (r) {
2465                         map = ERR_PTR(r);
2466                         goto out;
2467                 }
2468         }
2469
2470         map = __bind(md, table, &limits);
2471
2472 out:
2473         mutex_unlock(&md->suspend_lock);
2474         return map;
2475 }
2476
2477 /*
2478  * Functions to lock and unlock any filesystem running on the
2479  * device.
2480  */
2481 static int lock_fs(struct mapped_device *md)
2482 {
2483         int r;
2484
2485         WARN_ON(md->frozen_sb);
2486
2487         md->frozen_sb = freeze_bdev(md->bdev);
2488         if (IS_ERR(md->frozen_sb)) {
2489                 r = PTR_ERR(md->frozen_sb);
2490                 md->frozen_sb = NULL;
2491                 return r;
2492         }
2493
2494         set_bit(DMF_FROZEN, &md->flags);
2495
2496         return 0;
2497 }
2498
2499 static void unlock_fs(struct mapped_device *md)
2500 {
2501         if (!test_bit(DMF_FROZEN, &md->flags))
2502                 return;
2503
2504         thaw_bdev(md->bdev, md->frozen_sb);
2505         md->frozen_sb = NULL;
2506         clear_bit(DMF_FROZEN, &md->flags);
2507 }
2508
2509 /*
2510  * We need to be able to change a mapping table under a mounted
2511  * filesystem.  For example we might want to move some data in
2512  * the background.  Before the table can be swapped with
2513  * dm_bind_table, dm_suspend must be called to flush any in
2514  * flight bios and ensure that any further io gets deferred.
2515  */
2516 /*
2517  * Suspend mechanism in request-based dm.
2518  *
2519  * 1. Flush all I/Os by lock_fs() if needed.
2520  * 2. Stop dispatching any I/O by stopping the request_queue.
2521  * 3. Wait for all in-flight I/Os to be completed or requeued.
2522  *
2523  * To abort suspend, start the request_queue.
2524  */
2525 int dm_suspend(struct mapped_device *md, unsigned suspend_flags)
2526 {
2527         struct dm_table *map = NULL;
2528         int r = 0;
2529         int do_lockfs = suspend_flags & DM_SUSPEND_LOCKFS_FLAG ? 1 : 0;
2530         int noflush = suspend_flags & DM_SUSPEND_NOFLUSH_FLAG ? 1 : 0;
2531
2532         mutex_lock(&md->suspend_lock);
2533
2534         if (dm_suspended_md(md)) {
2535                 r = -EINVAL;
2536                 goto out_unlock;
2537         }
2538
2539         map = dm_get_live_table(md);
2540
2541         /*
2542          * DMF_NOFLUSH_SUSPENDING must be set before presuspend.
2543          * This flag is cleared before dm_suspend returns.
2544          */
2545         if (noflush)
2546                 set_bit(DMF_NOFLUSH_SUSPENDING, &md->flags);
2547
2548         /* This does not get reverted if there's an error later. */
2549         dm_table_presuspend_targets(map);
2550
2551         /*
2552          * Flush I/O to the device.
2553          * Any I/O submitted after lock_fs() may not be flushed.
2554          * noflush takes precedence over do_lockfs.
2555          * (lock_fs() flushes I/Os and waits for them to complete.)
2556          */
2557         if (!noflush && do_lockfs) {
2558                 r = lock_fs(md);
2559                 if (r)
2560                         goto out;
2561         }
2562
2563         /*
2564          * Here we must make sure that no processes are submitting requests
2565          * to target drivers i.e. no one may be executing
2566          * __split_and_process_bio. This is called from dm_request and
2567          * dm_wq_work.
2568          *
2569          * To get all processes out of __split_and_process_bio in dm_request,
2570          * we take the write lock. To prevent any process from reentering
2571          * __split_and_process_bio from dm_request and quiesce the thread
2572          * (dm_wq_work), we set BMF_BLOCK_IO_FOR_SUSPEND and call
2573          * flush_workqueue(md->wq).
2574          */
2575         down_write(&md->io_lock);
2576         set_bit(DMF_BLOCK_IO_FOR_SUSPEND, &md->flags);
2577         up_write(&md->io_lock);
2578
2579         /*
2580          * Stop md->queue before flushing md->wq in case request-based
2581          * dm defers requests to md->wq from md->queue.
2582          */
2583         if (dm_request_based(md))
2584                 stop_queue(md->queue);
2585
2586         flush_workqueue(md->wq);
2587
2588         /*
2589          * At this point no more requests are entering target request routines.
2590          * We call dm_wait_for_completion to wait for all existing requests
2591          * to finish.
2592          */
2593         r = dm_wait_for_completion(md, TASK_INTERRUPTIBLE);
2594
2595         down_write(&md->io_lock);
2596         if (noflush)
2597                 clear_bit(DMF_NOFLUSH_SUSPENDING, &md->flags);
2598         up_write(&md->io_lock);
2599
2600         /* were we interrupted ? */
2601         if (r < 0) {
2602                 dm_queue_flush(md);
2603
2604                 if (dm_request_based(md))
2605                         start_queue(md->queue);
2606
2607                 unlock_fs(md);
2608                 goto out; /* pushback list is already flushed, so skip flush */
2609         }
2610
2611         /*
2612          * If dm_wait_for_completion returned 0, the device is completely
2613          * quiescent now. There is no request-processing activity. All new
2614          * requests are being added to md->deferred list.
2615          */
2616
2617         set_bit(DMF_SUSPENDED, &md->flags);
2618
2619         dm_table_postsuspend_targets(map);
2620
2621 out:
2622         dm_table_put(map);
2623
2624 out_unlock:
2625         mutex_unlock(&md->suspend_lock);
2626         return r;
2627 }
2628
2629 int dm_resume(struct mapped_device *md)
2630 {
2631         int r = -EINVAL;
2632         struct dm_table *map = NULL;
2633
2634         mutex_lock(&md->suspend_lock);
2635         if (!dm_suspended_md(md))
2636                 goto out;
2637
2638         map = dm_get_live_table(md);
2639         if (!map || !dm_table_get_size(map))
2640                 goto out;
2641
2642         r = dm_table_resume_targets(map);
2643         if (r)
2644                 goto out;
2645
2646         dm_queue_flush(md);
2647
2648         /*
2649          * Flushing deferred I/Os must be done after targets are resumed
2650          * so that mapping of targets can work correctly.
2651          * Request-based dm is queueing the deferred I/Os in its request_queue.
2652          */
2653         if (dm_request_based(md))
2654                 start_queue(md->queue);
2655
2656         unlock_fs(md);
2657
2658         clear_bit(DMF_SUSPENDED, &md->flags);
2659
2660         r = 0;
2661 out:
2662         dm_table_put(map);
2663         mutex_unlock(&md->suspend_lock);
2664
2665         return r;
2666 }
2667
2668 /*-----------------------------------------------------------------
2669  * Event notification.
2670  *---------------------------------------------------------------*/
2671 int dm_kobject_uevent(struct mapped_device *md, enum kobject_action action,
2672                        unsigned cookie)
2673 {
2674         char udev_cookie[DM_COOKIE_LENGTH];
2675         char *envp[] = { udev_cookie, NULL };
2676
2677         if (!cookie)
2678                 return kobject_uevent(&disk_to_dev(md->disk)->kobj, action);
2679         else {
2680                 snprintf(udev_cookie, DM_COOKIE_LENGTH, "%s=%u",
2681                          DM_COOKIE_ENV_VAR_NAME, cookie);
2682                 return kobject_uevent_env(&disk_to_dev(md->disk)->kobj,
2683                                           action, envp);
2684         }
2685 }
2686
2687 uint32_t dm_next_uevent_seq(struct mapped_device *md)
2688 {
2689         return atomic_add_return(1, &md->uevent_seq);
2690 }
2691
2692 uint32_t dm_get_event_nr(struct mapped_device *md)
2693 {
2694         return atomic_read(&md->event_nr);
2695 }
2696
2697 int dm_wait_event(struct mapped_device *md, int event_nr)
2698 {
2699         return wait_event_interruptible(md->eventq,
2700                         (event_nr != atomic_read(&md->event_nr)));
2701 }
2702
2703 void dm_uevent_add(struct mapped_device *md, struct list_head *elist)
2704 {
2705         unsigned long flags;
2706
2707         spin_lock_irqsave(&md->uevent_lock, flags);
2708         list_add(elist, &md->uevent_list);
2709         spin_unlock_irqrestore(&md->uevent_lock, flags);
2710 }
2711
2712 /*
2713  * The gendisk is only valid as long as you have a reference
2714  * count on 'md'.
2715  */
2716 struct gendisk *dm_disk(struct mapped_device *md)
2717 {
2718         return md->disk;
2719 }
2720
2721 struct kobject *dm_kobject(struct mapped_device *md)
2722 {
2723         return &md->kobj;
2724 }
2725
2726 /*
2727  * struct mapped_device should not be exported outside of dm.c
2728  * so use this check to verify that kobj is part of md structure
2729  */
2730 struct mapped_device *dm_get_from_kobject(struct kobject *kobj)
2731 {
2732         struct mapped_device *md;
2733
2734         md = container_of(kobj, struct mapped_device, kobj);
2735         if (&md->kobj != kobj)
2736                 return NULL;
2737
2738         if (test_bit(DMF_FREEING, &md->flags) ||
2739             dm_deleting_md(md))
2740                 return NULL;
2741
2742         dm_get(md);
2743         return md;
2744 }
2745
2746 int dm_suspended_md(struct mapped_device *md)
2747 {
2748         return test_bit(DMF_SUSPENDED, &md->flags);
2749 }
2750
2751 int dm_suspended(struct dm_target *ti)
2752 {
2753         return dm_suspended_md(dm_table_get_md(ti->table));
2754 }
2755 EXPORT_SYMBOL_GPL(dm_suspended);
2756
2757 int dm_noflush_suspending(struct dm_target *ti)
2758 {
2759         return __noflush_suspending(dm_table_get_md(ti->table));
2760 }
2761 EXPORT_SYMBOL_GPL(dm_noflush_suspending);
2762
2763 struct dm_md_mempools *dm_alloc_md_mempools(unsigned type, unsigned integrity, unsigned per_bio_data_size)
2764 {
2765         struct dm_md_mempools *pools = kzalloc(sizeof(*pools), GFP_KERNEL);
2766         struct kmem_cache *cachep;
2767         unsigned int pool_size;
2768         unsigned int front_pad;
2769
2770         if (!pools)
2771                 return NULL;
2772
2773         if (type == DM_TYPE_BIO_BASED) {
2774                 cachep = _io_cache;
2775                 pool_size = 16;
2776                 front_pad = roundup(per_bio_data_size, __alignof__(struct dm_target_io)) + offsetof(struct dm_target_io, clone);
2777         } else if (type == DM_TYPE_REQUEST_BASED) {
2778                 cachep = _rq_tio_cache;
2779                 pool_size = MIN_IOS;
2780                 front_pad = offsetof(struct dm_rq_clone_bio_info, clone);
2781                 /* per_bio_data_size is not used. See __bind_mempools(). */
2782                 WARN_ON(per_bio_data_size != 0);
2783         } else
2784                 goto out;
2785
2786         pools->io_pool = mempool_create_slab_pool(MIN_IOS, cachep);
2787         if (!pools->io_pool)
2788                 goto out;
2789
2790         pools->bs = bioset_create(pool_size, front_pad);
2791         if (!pools->bs)
2792                 goto out;
2793
2794         if (integrity && bioset_integrity_create(pools->bs, pool_size))
2795                 goto out;
2796
2797         return pools;
2798
2799 out:
2800         dm_free_md_mempools(pools);
2801
2802         return NULL;
2803 }
2804
2805 void dm_free_md_mempools(struct dm_md_mempools *pools)
2806 {
2807         if (!pools)
2808                 return;
2809
2810         if (pools->io_pool)
2811                 mempool_destroy(pools->io_pool);
2812
2813         if (pools->bs)
2814                 bioset_free(pools->bs);
2815
2816         kfree(pools);
2817 }
2818
2819 static const struct block_device_operations dm_blk_dops = {
2820         .open = dm_blk_open,
2821         .release = dm_blk_close,
2822         .ioctl = dm_blk_ioctl,
2823         .getgeo = dm_blk_getgeo,
2824         .owner = THIS_MODULE
2825 };
2826
2827 EXPORT_SYMBOL(dm_get_mapinfo);
2828
2829 /*
2830  * module hooks
2831  */
2832 module_init(dm_init);
2833 module_exit(dm_exit);
2834
2835 module_param(major, uint, 0);
2836 MODULE_PARM_DESC(major, "The major number of the device mapper");
2837 MODULE_DESCRIPTION(DM_NAME " driver");
2838 MODULE_AUTHOR("Joe Thornber <dm-devel@redhat.com>");
2839 MODULE_LICENSE("GPL");