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