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