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