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