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