OSDN Git Service

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