xref: /openbmc/linux/drivers/md/dm.c (revision 1d3aa6f683b1c1a813a63339d7309cff58ba4531)
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 #include <linux/wait.h>
23 #include <linux/kthread.h>
24 #include <linux/ktime.h>
25 #include <linux/elevator.h> /* for rq_end_sector() */
26 #include <linux/blk-mq.h>
27 #include <linux/pr.h>
28 
29 #include <trace/events/block.h>
30 
31 #define DM_MSG_PREFIX "core"
32 
33 #ifdef CONFIG_PRINTK
34 /*
35  * ratelimit state to be used in DMXXX_LIMIT().
36  */
37 DEFINE_RATELIMIT_STATE(dm_ratelimit_state,
38 		       DEFAULT_RATELIMIT_INTERVAL,
39 		       DEFAULT_RATELIMIT_BURST);
40 EXPORT_SYMBOL(dm_ratelimit_state);
41 #endif
42 
43 /*
44  * Cookies are numeric values sent with CHANGE and REMOVE
45  * uevents while resuming, removing or renaming the device.
46  */
47 #define DM_COOKIE_ENV_VAR_NAME "DM_COOKIE"
48 #define DM_COOKIE_LENGTH 24
49 
50 static const char *_name = DM_NAME;
51 
52 static unsigned int major = 0;
53 static unsigned int _major = 0;
54 
55 static DEFINE_IDR(_minor_idr);
56 
57 static DEFINE_SPINLOCK(_minor_lock);
58 
59 static void do_deferred_remove(struct work_struct *w);
60 
61 static DECLARE_WORK(deferred_remove_work, do_deferred_remove);
62 
63 static struct workqueue_struct *deferred_remove_workqueue;
64 
65 /*
66  * For bio-based dm.
67  * One of these is allocated per bio.
68  */
69 struct dm_io {
70 	struct mapped_device *md;
71 	int error;
72 	atomic_t io_count;
73 	struct bio *bio;
74 	unsigned long start_time;
75 	spinlock_t endio_lock;
76 	struct dm_stats_aux stats_aux;
77 };
78 
79 /*
80  * For request-based dm.
81  * One of these is allocated per request.
82  */
83 struct dm_rq_target_io {
84 	struct mapped_device *md;
85 	struct dm_target *ti;
86 	struct request *orig, *clone;
87 	struct kthread_work work;
88 	int error;
89 	union map_info info;
90 	struct dm_stats_aux stats_aux;
91 	unsigned long duration_jiffies;
92 	unsigned n_sectors;
93 };
94 
95 /*
96  * For request-based dm - the bio clones we allocate are embedded in these
97  * structs.
98  *
99  * We allocate these with bio_alloc_bioset, using the front_pad parameter when
100  * the bioset is created - this means the bio has to come at the end of the
101  * struct.
102  */
103 struct dm_rq_clone_bio_info {
104 	struct bio *orig;
105 	struct dm_rq_target_io *tio;
106 	struct bio clone;
107 };
108 
109 #define MINOR_ALLOCED ((void *)-1)
110 
111 /*
112  * Bits for the md->flags field.
113  */
114 #define DMF_BLOCK_IO_FOR_SUSPEND 0
115 #define DMF_SUSPENDED 1
116 #define DMF_FROZEN 2
117 #define DMF_FREEING 3
118 #define DMF_DELETING 4
119 #define DMF_NOFLUSH_SUSPENDING 5
120 #define DMF_DEFERRED_REMOVE 6
121 #define DMF_SUSPENDED_INTERNALLY 7
122 
123 /*
124  * Work processed by per-device workqueue.
125  */
126 struct mapped_device {
127 	struct srcu_struct io_barrier;
128 	struct mutex suspend_lock;
129 	atomic_t holders;
130 	atomic_t open_count;
131 
132 	/*
133 	 * The current mapping (struct dm_table *).
134 	 * Use dm_get_live_table{_fast} or take suspend_lock for
135 	 * dereference.
136 	 */
137 	void __rcu *map;
138 
139 	struct list_head table_devices;
140 	struct mutex table_devices_lock;
141 
142 	unsigned long flags;
143 
144 	struct request_queue *queue;
145 	int numa_node_id;
146 
147 	unsigned type;
148 	/* Protect queue and type against concurrent access. */
149 	struct mutex type_lock;
150 
151 	struct dm_target *immutable_target;
152 	struct target_type *immutable_target_type;
153 
154 	struct gendisk *disk;
155 	char name[16];
156 
157 	void *interface_ptr;
158 
159 	/*
160 	 * A list of ios that arrived while we were suspended.
161 	 */
162 	atomic_t pending[2];
163 	wait_queue_head_t wait;
164 	struct work_struct work;
165 	struct bio_list deferred;
166 	spinlock_t deferred_lock;
167 
168 	/*
169 	 * Processing queue (flush)
170 	 */
171 	struct workqueue_struct *wq;
172 
173 	/*
174 	 * io objects are allocated from here.
175 	 */
176 	mempool_t *io_pool;
177 	mempool_t *rq_pool;
178 
179 	struct bio_set *bs;
180 
181 	/*
182 	 * Event handling.
183 	 */
184 	atomic_t event_nr;
185 	wait_queue_head_t eventq;
186 	atomic_t uevent_seq;
187 	struct list_head uevent_list;
188 	spinlock_t uevent_lock; /* Protect access to uevent_list */
189 
190 	/*
191 	 * freeze/thaw support require holding onto a super block
192 	 */
193 	struct super_block *frozen_sb;
194 	struct block_device *bdev;
195 
196 	/* forced geometry settings */
197 	struct hd_geometry geometry;
198 
199 	/* kobject and completion */
200 	struct dm_kobject_holder kobj_holder;
201 
202 	/* zero-length flush that will be cloned and submitted to targets */
203 	struct bio flush_bio;
204 
205 	/* the number of internal suspends */
206 	unsigned internal_suspend_count;
207 
208 	struct dm_stats stats;
209 
210 	struct kthread_worker kworker;
211 	struct task_struct *kworker_task;
212 
213 	/* for request-based merge heuristic in dm_request_fn() */
214 	unsigned seq_rq_merge_deadline_usecs;
215 	int last_rq_rw;
216 	sector_t last_rq_pos;
217 	ktime_t last_rq_start_time;
218 
219 	/* for blk-mq request-based DM support */
220 	struct blk_mq_tag_set *tag_set;
221 	bool use_blk_mq:1;
222 	bool init_tio_pdu:1;
223 };
224 
225 #ifdef CONFIG_DM_MQ_DEFAULT
226 static bool use_blk_mq = true;
227 #else
228 static bool use_blk_mq = false;
229 #endif
230 
231 #define DM_MQ_NR_HW_QUEUES 1
232 #define DM_MQ_QUEUE_DEPTH 2048
233 #define DM_NUMA_NODE NUMA_NO_NODE
234 
235 static unsigned dm_mq_nr_hw_queues = DM_MQ_NR_HW_QUEUES;
236 static unsigned dm_mq_queue_depth = DM_MQ_QUEUE_DEPTH;
237 static int dm_numa_node = DM_NUMA_NODE;
238 
239 bool dm_use_blk_mq(struct mapped_device *md)
240 {
241 	return md->use_blk_mq;
242 }
243 EXPORT_SYMBOL_GPL(dm_use_blk_mq);
244 
245 /*
246  * For mempools pre-allocation at the table loading time.
247  */
248 struct dm_md_mempools {
249 	mempool_t *io_pool;
250 	mempool_t *rq_pool;
251 	struct bio_set *bs;
252 };
253 
254 struct table_device {
255 	struct list_head list;
256 	atomic_t count;
257 	struct dm_dev dm_dev;
258 };
259 
260 #define RESERVED_BIO_BASED_IOS		16
261 #define RESERVED_REQUEST_BASED_IOS	256
262 #define RESERVED_MAX_IOS		1024
263 static struct kmem_cache *_io_cache;
264 static struct kmem_cache *_rq_tio_cache;
265 static struct kmem_cache *_rq_cache;
266 
267 /*
268  * Bio-based DM's mempools' reserved IOs set by the user.
269  */
270 static unsigned reserved_bio_based_ios = RESERVED_BIO_BASED_IOS;
271 
272 /*
273  * Request-based DM's mempools' reserved IOs set by the user.
274  */
275 static unsigned reserved_rq_based_ios = RESERVED_REQUEST_BASED_IOS;
276 
277 static int __dm_get_module_param_int(int *module_param, int min, int max)
278 {
279 	int param = ACCESS_ONCE(*module_param);
280 	int modified_param = 0;
281 	bool modified = true;
282 
283 	if (param < min)
284 		modified_param = min;
285 	else if (param > max)
286 		modified_param = max;
287 	else
288 		modified = false;
289 
290 	if (modified) {
291 		(void)cmpxchg(module_param, param, modified_param);
292 		param = modified_param;
293 	}
294 
295 	return param;
296 }
297 
298 static unsigned __dm_get_module_param(unsigned *module_param,
299 				      unsigned def, unsigned max)
300 {
301 	unsigned param = ACCESS_ONCE(*module_param);
302 	unsigned modified_param = 0;
303 
304 	if (!param)
305 		modified_param = def;
306 	else if (param > max)
307 		modified_param = max;
308 
309 	if (modified_param) {
310 		(void)cmpxchg(module_param, param, modified_param);
311 		param = modified_param;
312 	}
313 
314 	return param;
315 }
316 
317 unsigned dm_get_reserved_bio_based_ios(void)
318 {
319 	return __dm_get_module_param(&reserved_bio_based_ios,
320 				     RESERVED_BIO_BASED_IOS, RESERVED_MAX_IOS);
321 }
322 EXPORT_SYMBOL_GPL(dm_get_reserved_bio_based_ios);
323 
324 unsigned dm_get_reserved_rq_based_ios(void)
325 {
326 	return __dm_get_module_param(&reserved_rq_based_ios,
327 				     RESERVED_REQUEST_BASED_IOS, RESERVED_MAX_IOS);
328 }
329 EXPORT_SYMBOL_GPL(dm_get_reserved_rq_based_ios);
330 
331 static unsigned dm_get_blk_mq_nr_hw_queues(void)
332 {
333 	return __dm_get_module_param(&dm_mq_nr_hw_queues, 1, 32);
334 }
335 
336 static unsigned dm_get_blk_mq_queue_depth(void)
337 {
338 	return __dm_get_module_param(&dm_mq_queue_depth,
339 				     DM_MQ_QUEUE_DEPTH, BLK_MQ_MAX_DEPTH);
340 }
341 
342 static unsigned dm_get_numa_node(void)
343 {
344 	return __dm_get_module_param_int(&dm_numa_node,
345 					 DM_NUMA_NODE, num_online_nodes() - 1);
346 }
347 
348 static int __init local_init(void)
349 {
350 	int r = -ENOMEM;
351 
352 	/* allocate a slab for the dm_ios */
353 	_io_cache = KMEM_CACHE(dm_io, 0);
354 	if (!_io_cache)
355 		return r;
356 
357 	_rq_tio_cache = KMEM_CACHE(dm_rq_target_io, 0);
358 	if (!_rq_tio_cache)
359 		goto out_free_io_cache;
360 
361 	_rq_cache = kmem_cache_create("dm_old_clone_request", sizeof(struct request),
362 				      __alignof__(struct request), 0, NULL);
363 	if (!_rq_cache)
364 		goto out_free_rq_tio_cache;
365 
366 	r = dm_uevent_init();
367 	if (r)
368 		goto out_free_rq_cache;
369 
370 	deferred_remove_workqueue = alloc_workqueue("kdmremove", WQ_UNBOUND, 1);
371 	if (!deferred_remove_workqueue) {
372 		r = -ENOMEM;
373 		goto out_uevent_exit;
374 	}
375 
376 	_major = major;
377 	r = register_blkdev(_major, _name);
378 	if (r < 0)
379 		goto out_free_workqueue;
380 
381 	if (!_major)
382 		_major = r;
383 
384 	return 0;
385 
386 out_free_workqueue:
387 	destroy_workqueue(deferred_remove_workqueue);
388 out_uevent_exit:
389 	dm_uevent_exit();
390 out_free_rq_cache:
391 	kmem_cache_destroy(_rq_cache);
392 out_free_rq_tio_cache:
393 	kmem_cache_destroy(_rq_tio_cache);
394 out_free_io_cache:
395 	kmem_cache_destroy(_io_cache);
396 
397 	return r;
398 }
399 
400 static void local_exit(void)
401 {
402 	flush_scheduled_work();
403 	destroy_workqueue(deferred_remove_workqueue);
404 
405 	kmem_cache_destroy(_rq_cache);
406 	kmem_cache_destroy(_rq_tio_cache);
407 	kmem_cache_destroy(_io_cache);
408 	unregister_blkdev(_major, _name);
409 	dm_uevent_exit();
410 
411 	_major = 0;
412 
413 	DMINFO("cleaned up");
414 }
415 
416 static int (*_inits[])(void) __initdata = {
417 	local_init,
418 	dm_target_init,
419 	dm_linear_init,
420 	dm_stripe_init,
421 	dm_io_init,
422 	dm_kcopyd_init,
423 	dm_interface_init,
424 	dm_statistics_init,
425 };
426 
427 static void (*_exits[])(void) = {
428 	local_exit,
429 	dm_target_exit,
430 	dm_linear_exit,
431 	dm_stripe_exit,
432 	dm_io_exit,
433 	dm_kcopyd_exit,
434 	dm_interface_exit,
435 	dm_statistics_exit,
436 };
437 
438 static int __init dm_init(void)
439 {
440 	const int count = ARRAY_SIZE(_inits);
441 
442 	int r, i;
443 
444 	for (i = 0; i < count; i++) {
445 		r = _inits[i]();
446 		if (r)
447 			goto bad;
448 	}
449 
450 	return 0;
451 
452       bad:
453 	while (i--)
454 		_exits[i]();
455 
456 	return r;
457 }
458 
459 static void __exit dm_exit(void)
460 {
461 	int i = ARRAY_SIZE(_exits);
462 
463 	while (i--)
464 		_exits[i]();
465 
466 	/*
467 	 * Should be empty by this point.
468 	 */
469 	idr_destroy(&_minor_idr);
470 }
471 
472 /*
473  * Block device functions
474  */
475 int dm_deleting_md(struct mapped_device *md)
476 {
477 	return test_bit(DMF_DELETING, &md->flags);
478 }
479 
480 static int dm_blk_open(struct block_device *bdev, fmode_t mode)
481 {
482 	struct mapped_device *md;
483 
484 	spin_lock(&_minor_lock);
485 
486 	md = bdev->bd_disk->private_data;
487 	if (!md)
488 		goto out;
489 
490 	if (test_bit(DMF_FREEING, &md->flags) ||
491 	    dm_deleting_md(md)) {
492 		md = NULL;
493 		goto out;
494 	}
495 
496 	dm_get(md);
497 	atomic_inc(&md->open_count);
498 out:
499 	spin_unlock(&_minor_lock);
500 
501 	return md ? 0 : -ENXIO;
502 }
503 
504 static void dm_blk_close(struct gendisk *disk, fmode_t mode)
505 {
506 	struct mapped_device *md;
507 
508 	spin_lock(&_minor_lock);
509 
510 	md = disk->private_data;
511 	if (WARN_ON(!md))
512 		goto out;
513 
514 	if (atomic_dec_and_test(&md->open_count) &&
515 	    (test_bit(DMF_DEFERRED_REMOVE, &md->flags)))
516 		queue_work(deferred_remove_workqueue, &deferred_remove_work);
517 
518 	dm_put(md);
519 out:
520 	spin_unlock(&_minor_lock);
521 }
522 
523 int dm_open_count(struct mapped_device *md)
524 {
525 	return atomic_read(&md->open_count);
526 }
527 
528 /*
529  * Guarantees nothing is using the device before it's deleted.
530  */
531 int dm_lock_for_deletion(struct mapped_device *md, bool mark_deferred, bool only_deferred)
532 {
533 	int r = 0;
534 
535 	spin_lock(&_minor_lock);
536 
537 	if (dm_open_count(md)) {
538 		r = -EBUSY;
539 		if (mark_deferred)
540 			set_bit(DMF_DEFERRED_REMOVE, &md->flags);
541 	} else if (only_deferred && !test_bit(DMF_DEFERRED_REMOVE, &md->flags))
542 		r = -EEXIST;
543 	else
544 		set_bit(DMF_DELETING, &md->flags);
545 
546 	spin_unlock(&_minor_lock);
547 
548 	return r;
549 }
550 
551 int dm_cancel_deferred_remove(struct mapped_device *md)
552 {
553 	int r = 0;
554 
555 	spin_lock(&_minor_lock);
556 
557 	if (test_bit(DMF_DELETING, &md->flags))
558 		r = -EBUSY;
559 	else
560 		clear_bit(DMF_DEFERRED_REMOVE, &md->flags);
561 
562 	spin_unlock(&_minor_lock);
563 
564 	return r;
565 }
566 
567 static void do_deferred_remove(struct work_struct *w)
568 {
569 	dm_deferred_remove();
570 }
571 
572 sector_t dm_get_size(struct mapped_device *md)
573 {
574 	return get_capacity(md->disk);
575 }
576 
577 struct request_queue *dm_get_md_queue(struct mapped_device *md)
578 {
579 	return md->queue;
580 }
581 
582 struct dm_stats *dm_get_stats(struct mapped_device *md)
583 {
584 	return &md->stats;
585 }
586 
587 static int dm_blk_getgeo(struct block_device *bdev, struct hd_geometry *geo)
588 {
589 	struct mapped_device *md = bdev->bd_disk->private_data;
590 
591 	return dm_get_geometry(md, geo);
592 }
593 
594 static int dm_grab_bdev_for_ioctl(struct mapped_device *md,
595 				  struct block_device **bdev,
596 				  fmode_t *mode)
597 {
598 	struct dm_target *tgt;
599 	struct dm_table *map;
600 	int srcu_idx, r;
601 
602 retry:
603 	r = -ENOTTY;
604 	map = dm_get_live_table(md, &srcu_idx);
605 	if (!map || !dm_table_get_size(map))
606 		goto out;
607 
608 	/* We only support devices that have a single target */
609 	if (dm_table_get_num_targets(map) != 1)
610 		goto out;
611 
612 	tgt = dm_table_get_target(map, 0);
613 	if (!tgt->type->prepare_ioctl)
614 		goto out;
615 
616 	if (dm_suspended_md(md)) {
617 		r = -EAGAIN;
618 		goto out;
619 	}
620 
621 	r = tgt->type->prepare_ioctl(tgt, bdev, mode);
622 	if (r < 0)
623 		goto out;
624 
625 	bdgrab(*bdev);
626 	dm_put_live_table(md, srcu_idx);
627 	return r;
628 
629 out:
630 	dm_put_live_table(md, srcu_idx);
631 	if (r == -ENOTCONN && !fatal_signal_pending(current)) {
632 		msleep(10);
633 		goto retry;
634 	}
635 	return r;
636 }
637 
638 static int dm_blk_ioctl(struct block_device *bdev, fmode_t mode,
639 			unsigned int cmd, unsigned long arg)
640 {
641 	struct mapped_device *md = bdev->bd_disk->private_data;
642 	int r;
643 
644 	r = dm_grab_bdev_for_ioctl(md, &bdev, &mode);
645 	if (r < 0)
646 		return r;
647 
648 	if (r > 0) {
649 		/*
650 		 * Target determined this ioctl is being issued against
651 		 * a logical partition of the parent bdev; so extra
652 		 * validation is needed.
653 		 */
654 		r = scsi_verify_blk_ioctl(NULL, cmd);
655 		if (r)
656 			goto out;
657 	}
658 
659 	r =  __blkdev_driver_ioctl(bdev, mode, cmd, arg);
660 out:
661 	bdput(bdev);
662 	return r;
663 }
664 
665 static struct dm_io *alloc_io(struct mapped_device *md)
666 {
667 	return mempool_alloc(md->io_pool, GFP_NOIO);
668 }
669 
670 static void free_io(struct mapped_device *md, struct dm_io *io)
671 {
672 	mempool_free(io, md->io_pool);
673 }
674 
675 static void free_tio(struct mapped_device *md, struct dm_target_io *tio)
676 {
677 	bio_put(&tio->clone);
678 }
679 
680 static struct dm_rq_target_io *alloc_old_rq_tio(struct mapped_device *md,
681 						gfp_t gfp_mask)
682 {
683 	return mempool_alloc(md->io_pool, gfp_mask);
684 }
685 
686 static void free_old_rq_tio(struct dm_rq_target_io *tio)
687 {
688 	mempool_free(tio, tio->md->io_pool);
689 }
690 
691 static struct request *alloc_old_clone_request(struct mapped_device *md,
692 					       gfp_t gfp_mask)
693 {
694 	return mempool_alloc(md->rq_pool, gfp_mask);
695 }
696 
697 static void free_old_clone_request(struct mapped_device *md, struct request *rq)
698 {
699 	mempool_free(rq, md->rq_pool);
700 }
701 
702 static int md_in_flight(struct mapped_device *md)
703 {
704 	return atomic_read(&md->pending[READ]) +
705 	       atomic_read(&md->pending[WRITE]);
706 }
707 
708 static void start_io_acct(struct dm_io *io)
709 {
710 	struct mapped_device *md = io->md;
711 	struct bio *bio = io->bio;
712 	int cpu;
713 	int rw = bio_data_dir(bio);
714 
715 	io->start_time = jiffies;
716 
717 	cpu = part_stat_lock();
718 	part_round_stats(cpu, &dm_disk(md)->part0);
719 	part_stat_unlock();
720 	atomic_set(&dm_disk(md)->part0.in_flight[rw],
721 		atomic_inc_return(&md->pending[rw]));
722 
723 	if (unlikely(dm_stats_used(&md->stats)))
724 		dm_stats_account_io(&md->stats, bio->bi_rw, bio->bi_iter.bi_sector,
725 				    bio_sectors(bio), false, 0, &io->stats_aux);
726 }
727 
728 static void end_io_acct(struct dm_io *io)
729 {
730 	struct mapped_device *md = io->md;
731 	struct bio *bio = io->bio;
732 	unsigned long duration = jiffies - io->start_time;
733 	int pending;
734 	int rw = bio_data_dir(bio);
735 
736 	generic_end_io_acct(rw, &dm_disk(md)->part0, io->start_time);
737 
738 	if (unlikely(dm_stats_used(&md->stats)))
739 		dm_stats_account_io(&md->stats, bio->bi_rw, bio->bi_iter.bi_sector,
740 				    bio_sectors(bio), true, duration, &io->stats_aux);
741 
742 	/*
743 	 * After this is decremented the bio must not be touched if it is
744 	 * a flush.
745 	 */
746 	pending = atomic_dec_return(&md->pending[rw]);
747 	atomic_set(&dm_disk(md)->part0.in_flight[rw], pending);
748 	pending += atomic_read(&md->pending[rw^0x1]);
749 
750 	/* nudge anyone waiting on suspend queue */
751 	if (!pending)
752 		wake_up(&md->wait);
753 }
754 
755 /*
756  * Add the bio to the list of deferred io.
757  */
758 static void queue_io(struct mapped_device *md, struct bio *bio)
759 {
760 	unsigned long flags;
761 
762 	spin_lock_irqsave(&md->deferred_lock, flags);
763 	bio_list_add(&md->deferred, bio);
764 	spin_unlock_irqrestore(&md->deferred_lock, flags);
765 	queue_work(md->wq, &md->work);
766 }
767 
768 /*
769  * Everyone (including functions in this file), should use this
770  * function to access the md->map field, and make sure they call
771  * dm_put_live_table() when finished.
772  */
773 struct dm_table *dm_get_live_table(struct mapped_device *md, int *srcu_idx) __acquires(md->io_barrier)
774 {
775 	*srcu_idx = srcu_read_lock(&md->io_barrier);
776 
777 	return srcu_dereference(md->map, &md->io_barrier);
778 }
779 
780 void dm_put_live_table(struct mapped_device *md, int srcu_idx) __releases(md->io_barrier)
781 {
782 	srcu_read_unlock(&md->io_barrier, srcu_idx);
783 }
784 
785 void dm_sync_table(struct mapped_device *md)
786 {
787 	synchronize_srcu(&md->io_barrier);
788 	synchronize_rcu_expedited();
789 }
790 
791 /*
792  * A fast alternative to dm_get_live_table/dm_put_live_table.
793  * The caller must not block between these two functions.
794  */
795 static struct dm_table *dm_get_live_table_fast(struct mapped_device *md) __acquires(RCU)
796 {
797 	rcu_read_lock();
798 	return rcu_dereference(md->map);
799 }
800 
801 static void dm_put_live_table_fast(struct mapped_device *md) __releases(RCU)
802 {
803 	rcu_read_unlock();
804 }
805 
806 /*
807  * Open a table device so we can use it as a map destination.
808  */
809 static int open_table_device(struct table_device *td, dev_t dev,
810 			     struct mapped_device *md)
811 {
812 	static char *_claim_ptr = "I belong to device-mapper";
813 	struct block_device *bdev;
814 
815 	int r;
816 
817 	BUG_ON(td->dm_dev.bdev);
818 
819 	bdev = blkdev_get_by_dev(dev, td->dm_dev.mode | FMODE_EXCL, _claim_ptr);
820 	if (IS_ERR(bdev))
821 		return PTR_ERR(bdev);
822 
823 	r = bd_link_disk_holder(bdev, dm_disk(md));
824 	if (r) {
825 		blkdev_put(bdev, td->dm_dev.mode | FMODE_EXCL);
826 		return r;
827 	}
828 
829 	td->dm_dev.bdev = bdev;
830 	return 0;
831 }
832 
833 /*
834  * Close a table device that we've been using.
835  */
836 static void close_table_device(struct table_device *td, struct mapped_device *md)
837 {
838 	if (!td->dm_dev.bdev)
839 		return;
840 
841 	bd_unlink_disk_holder(td->dm_dev.bdev, dm_disk(md));
842 	blkdev_put(td->dm_dev.bdev, td->dm_dev.mode | FMODE_EXCL);
843 	td->dm_dev.bdev = NULL;
844 }
845 
846 static struct table_device *find_table_device(struct list_head *l, dev_t dev,
847 					      fmode_t mode) {
848 	struct table_device *td;
849 
850 	list_for_each_entry(td, l, list)
851 		if (td->dm_dev.bdev->bd_dev == dev && td->dm_dev.mode == mode)
852 			return td;
853 
854 	return NULL;
855 }
856 
857 int dm_get_table_device(struct mapped_device *md, dev_t dev, fmode_t mode,
858 			struct dm_dev **result) {
859 	int r;
860 	struct table_device *td;
861 
862 	mutex_lock(&md->table_devices_lock);
863 	td = find_table_device(&md->table_devices, dev, mode);
864 	if (!td) {
865 		td = kmalloc_node(sizeof(*td), GFP_KERNEL, md->numa_node_id);
866 		if (!td) {
867 			mutex_unlock(&md->table_devices_lock);
868 			return -ENOMEM;
869 		}
870 
871 		td->dm_dev.mode = mode;
872 		td->dm_dev.bdev = NULL;
873 
874 		if ((r = open_table_device(td, dev, md))) {
875 			mutex_unlock(&md->table_devices_lock);
876 			kfree(td);
877 			return r;
878 		}
879 
880 		format_dev_t(td->dm_dev.name, dev);
881 
882 		atomic_set(&td->count, 0);
883 		list_add(&td->list, &md->table_devices);
884 	}
885 	atomic_inc(&td->count);
886 	mutex_unlock(&md->table_devices_lock);
887 
888 	*result = &td->dm_dev;
889 	return 0;
890 }
891 EXPORT_SYMBOL_GPL(dm_get_table_device);
892 
893 void dm_put_table_device(struct mapped_device *md, struct dm_dev *d)
894 {
895 	struct table_device *td = container_of(d, struct table_device, dm_dev);
896 
897 	mutex_lock(&md->table_devices_lock);
898 	if (atomic_dec_and_test(&td->count)) {
899 		close_table_device(td, md);
900 		list_del(&td->list);
901 		kfree(td);
902 	}
903 	mutex_unlock(&md->table_devices_lock);
904 }
905 EXPORT_SYMBOL(dm_put_table_device);
906 
907 static void free_table_devices(struct list_head *devices)
908 {
909 	struct list_head *tmp, *next;
910 
911 	list_for_each_safe(tmp, next, devices) {
912 		struct table_device *td = list_entry(tmp, struct table_device, list);
913 
914 		DMWARN("dm_destroy: %s still exists with %d references",
915 		       td->dm_dev.name, atomic_read(&td->count));
916 		kfree(td);
917 	}
918 }
919 
920 /*
921  * Get the geometry associated with a dm device
922  */
923 int dm_get_geometry(struct mapped_device *md, struct hd_geometry *geo)
924 {
925 	*geo = md->geometry;
926 
927 	return 0;
928 }
929 
930 /*
931  * Set the geometry of a device.
932  */
933 int dm_set_geometry(struct mapped_device *md, struct hd_geometry *geo)
934 {
935 	sector_t sz = (sector_t)geo->cylinders * geo->heads * geo->sectors;
936 
937 	if (geo->start > sz) {
938 		DMWARN("Start sector is beyond the geometry limits.");
939 		return -EINVAL;
940 	}
941 
942 	md->geometry = *geo;
943 
944 	return 0;
945 }
946 
947 /*-----------------------------------------------------------------
948  * CRUD START:
949  *   A more elegant soln is in the works that uses the queue
950  *   merge fn, unfortunately there are a couple of changes to
951  *   the block layer that I want to make for this.  So in the
952  *   interests of getting something for people to use I give
953  *   you this clearly demarcated crap.
954  *---------------------------------------------------------------*/
955 
956 static int __noflush_suspending(struct mapped_device *md)
957 {
958 	return test_bit(DMF_NOFLUSH_SUSPENDING, &md->flags);
959 }
960 
961 /*
962  * Decrements the number of outstanding ios that a bio has been
963  * cloned into, completing the original io if necc.
964  */
965 static void dec_pending(struct dm_io *io, int error)
966 {
967 	unsigned long flags;
968 	int io_error;
969 	struct bio *bio;
970 	struct mapped_device *md = io->md;
971 
972 	/* Push-back supersedes any I/O errors */
973 	if (unlikely(error)) {
974 		spin_lock_irqsave(&io->endio_lock, flags);
975 		if (!(io->error > 0 && __noflush_suspending(md)))
976 			io->error = error;
977 		spin_unlock_irqrestore(&io->endio_lock, flags);
978 	}
979 
980 	if (atomic_dec_and_test(&io->io_count)) {
981 		if (io->error == DM_ENDIO_REQUEUE) {
982 			/*
983 			 * Target requested pushing back the I/O.
984 			 */
985 			spin_lock_irqsave(&md->deferred_lock, flags);
986 			if (__noflush_suspending(md))
987 				bio_list_add_head(&md->deferred, io->bio);
988 			else
989 				/* noflush suspend was interrupted. */
990 				io->error = -EIO;
991 			spin_unlock_irqrestore(&md->deferred_lock, flags);
992 		}
993 
994 		io_error = io->error;
995 		bio = io->bio;
996 		end_io_acct(io);
997 		free_io(md, io);
998 
999 		if (io_error == DM_ENDIO_REQUEUE)
1000 			return;
1001 
1002 		if ((bio->bi_rw & REQ_FLUSH) && bio->bi_iter.bi_size) {
1003 			/*
1004 			 * Preflush done for flush with data, reissue
1005 			 * without REQ_FLUSH.
1006 			 */
1007 			bio->bi_rw &= ~REQ_FLUSH;
1008 			queue_io(md, bio);
1009 		} else {
1010 			/* done with normal IO or empty flush */
1011 			trace_block_bio_complete(md->queue, bio, io_error);
1012 			bio->bi_error = io_error;
1013 			bio_endio(bio);
1014 		}
1015 	}
1016 }
1017 
1018 static void disable_write_same(struct mapped_device *md)
1019 {
1020 	struct queue_limits *limits = dm_get_queue_limits(md);
1021 
1022 	/* device doesn't really support WRITE SAME, disable it */
1023 	limits->max_write_same_sectors = 0;
1024 }
1025 
1026 static void clone_endio(struct bio *bio)
1027 {
1028 	int error = bio->bi_error;
1029 	int r = error;
1030 	struct dm_target_io *tio = container_of(bio, struct dm_target_io, clone);
1031 	struct dm_io *io = tio->io;
1032 	struct mapped_device *md = tio->io->md;
1033 	dm_endio_fn endio = tio->ti->type->end_io;
1034 
1035 	if (endio) {
1036 		r = endio(tio->ti, bio, error);
1037 		if (r < 0 || r == DM_ENDIO_REQUEUE)
1038 			/*
1039 			 * error and requeue request are handled
1040 			 * in dec_pending().
1041 			 */
1042 			error = r;
1043 		else if (r == DM_ENDIO_INCOMPLETE)
1044 			/* The target will handle the io */
1045 			return;
1046 		else if (r) {
1047 			DMWARN("unimplemented target endio return value: %d", r);
1048 			BUG();
1049 		}
1050 	}
1051 
1052 	if (unlikely(r == -EREMOTEIO && (bio->bi_rw & REQ_WRITE_SAME) &&
1053 		     !bdev_get_queue(bio->bi_bdev)->limits.max_write_same_sectors))
1054 		disable_write_same(md);
1055 
1056 	free_tio(md, tio);
1057 	dec_pending(io, error);
1058 }
1059 
1060 /*
1061  * Partial completion handling for request-based dm
1062  */
1063 static void end_clone_bio(struct bio *clone)
1064 {
1065 	struct dm_rq_clone_bio_info *info =
1066 		container_of(clone, struct dm_rq_clone_bio_info, clone);
1067 	struct dm_rq_target_io *tio = info->tio;
1068 	struct bio *bio = info->orig;
1069 	unsigned int nr_bytes = info->orig->bi_iter.bi_size;
1070 	int error = clone->bi_error;
1071 
1072 	bio_put(clone);
1073 
1074 	if (tio->error)
1075 		/*
1076 		 * An error has already been detected on the request.
1077 		 * Once error occurred, just let clone->end_io() handle
1078 		 * the remainder.
1079 		 */
1080 		return;
1081 	else if (error) {
1082 		/*
1083 		 * Don't notice the error to the upper layer yet.
1084 		 * The error handling decision is made by the target driver,
1085 		 * when the request is completed.
1086 		 */
1087 		tio->error = error;
1088 		return;
1089 	}
1090 
1091 	/*
1092 	 * I/O for the bio successfully completed.
1093 	 * Notice the data completion to the upper layer.
1094 	 */
1095 
1096 	/*
1097 	 * bios are processed from the head of the list.
1098 	 * So the completing bio should always be rq->bio.
1099 	 * If it's not, something wrong is happening.
1100 	 */
1101 	if (tio->orig->bio != bio)
1102 		DMERR("bio completion is going in the middle of the request");
1103 
1104 	/*
1105 	 * Update the original request.
1106 	 * Do not use blk_end_request() here, because it may complete
1107 	 * the original request before the clone, and break the ordering.
1108 	 */
1109 	blk_update_request(tio->orig, 0, nr_bytes);
1110 }
1111 
1112 static struct dm_rq_target_io *tio_from_request(struct request *rq)
1113 {
1114 	return (rq->q->mq_ops ? blk_mq_rq_to_pdu(rq) : rq->special);
1115 }
1116 
1117 static void rq_end_stats(struct mapped_device *md, struct request *orig)
1118 {
1119 	if (unlikely(dm_stats_used(&md->stats))) {
1120 		struct dm_rq_target_io *tio = tio_from_request(orig);
1121 		tio->duration_jiffies = jiffies - tio->duration_jiffies;
1122 		dm_stats_account_io(&md->stats, orig->cmd_flags, blk_rq_pos(orig),
1123 				    tio->n_sectors, true, tio->duration_jiffies,
1124 				    &tio->stats_aux);
1125 	}
1126 }
1127 
1128 /*
1129  * Don't touch any member of the md after calling this function because
1130  * the md may be freed in dm_put() at the end of this function.
1131  * Or do dm_get() before calling this function and dm_put() later.
1132  */
1133 static void rq_completed(struct mapped_device *md, int rw, bool run_queue)
1134 {
1135 	atomic_dec(&md->pending[rw]);
1136 
1137 	/* nudge anyone waiting on suspend queue */
1138 	if (!md_in_flight(md))
1139 		wake_up(&md->wait);
1140 
1141 	/*
1142 	 * Run this off this callpath, as drivers could invoke end_io while
1143 	 * inside their request_fn (and holding the queue lock). Calling
1144 	 * back into ->request_fn() could deadlock attempting to grab the
1145 	 * queue lock again.
1146 	 */
1147 	if (!md->queue->mq_ops && run_queue)
1148 		blk_run_queue_async(md->queue);
1149 
1150 	/*
1151 	 * dm_put() must be at the end of this function. See the comment above
1152 	 */
1153 	dm_put(md);
1154 }
1155 
1156 static void free_rq_clone(struct request *clone)
1157 {
1158 	struct dm_rq_target_io *tio = clone->end_io_data;
1159 	struct mapped_device *md = tio->md;
1160 
1161 	blk_rq_unprep_clone(clone);
1162 
1163 	if (md->type == DM_TYPE_MQ_REQUEST_BASED)
1164 		/* stacked on blk-mq queue(s) */
1165 		tio->ti->type->release_clone_rq(clone);
1166 	else if (!md->queue->mq_ops)
1167 		/* request_fn queue stacked on request_fn queue(s) */
1168 		free_old_clone_request(md, clone);
1169 
1170 	if (!md->queue->mq_ops)
1171 		free_old_rq_tio(tio);
1172 }
1173 
1174 /*
1175  * Complete the clone and the original request.
1176  * Must be called without clone's queue lock held,
1177  * see end_clone_request() for more details.
1178  */
1179 static void dm_end_request(struct request *clone, int error)
1180 {
1181 	int rw = rq_data_dir(clone);
1182 	struct dm_rq_target_io *tio = clone->end_io_data;
1183 	struct mapped_device *md = tio->md;
1184 	struct request *rq = tio->orig;
1185 
1186 	if (rq->cmd_type == REQ_TYPE_BLOCK_PC) {
1187 		rq->errors = clone->errors;
1188 		rq->resid_len = clone->resid_len;
1189 
1190 		if (rq->sense)
1191 			/*
1192 			 * We are using the sense buffer of the original
1193 			 * request.
1194 			 * So setting the length of the sense data is enough.
1195 			 */
1196 			rq->sense_len = clone->sense_len;
1197 	}
1198 
1199 	free_rq_clone(clone);
1200 	rq_end_stats(md, rq);
1201 	if (!rq->q->mq_ops)
1202 		blk_end_request_all(rq, error);
1203 	else
1204 		blk_mq_end_request(rq, error);
1205 	rq_completed(md, rw, true);
1206 }
1207 
1208 static void dm_unprep_request(struct request *rq)
1209 {
1210 	struct dm_rq_target_io *tio = tio_from_request(rq);
1211 	struct request *clone = tio->clone;
1212 
1213 	if (!rq->q->mq_ops) {
1214 		rq->special = NULL;
1215 		rq->cmd_flags &= ~REQ_DONTPREP;
1216 	}
1217 
1218 	if (clone)
1219 		free_rq_clone(clone);
1220 	else if (!tio->md->queue->mq_ops)
1221 		free_old_rq_tio(tio);
1222 }
1223 
1224 /*
1225  * Requeue the original request of a clone.
1226  */
1227 static void dm_old_requeue_request(struct request *rq)
1228 {
1229 	struct request_queue *q = rq->q;
1230 	unsigned long flags;
1231 
1232 	spin_lock_irqsave(q->queue_lock, flags);
1233 	blk_requeue_request(q, rq);
1234 	blk_run_queue_async(q);
1235 	spin_unlock_irqrestore(q->queue_lock, flags);
1236 }
1237 
1238 static void dm_mq_requeue_request(struct request *rq)
1239 {
1240 	struct request_queue *q = rq->q;
1241 	unsigned long flags;
1242 
1243 	blk_mq_requeue_request(rq);
1244 	spin_lock_irqsave(q->queue_lock, flags);
1245 	if (!blk_queue_stopped(q))
1246 		blk_mq_kick_requeue_list(q);
1247 	spin_unlock_irqrestore(q->queue_lock, flags);
1248 }
1249 
1250 static void dm_requeue_original_request(struct mapped_device *md,
1251 					struct request *rq)
1252 {
1253 	int rw = rq_data_dir(rq);
1254 
1255 	dm_unprep_request(rq);
1256 
1257 	rq_end_stats(md, rq);
1258 	if (!rq->q->mq_ops)
1259 		dm_old_requeue_request(rq);
1260 	else
1261 		dm_mq_requeue_request(rq);
1262 
1263 	rq_completed(md, rw, false);
1264 }
1265 
1266 static void dm_old_stop_queue(struct request_queue *q)
1267 {
1268 	unsigned long flags;
1269 
1270 	spin_lock_irqsave(q->queue_lock, flags);
1271 	if (blk_queue_stopped(q)) {
1272 		spin_unlock_irqrestore(q->queue_lock, flags);
1273 		return;
1274 	}
1275 
1276 	blk_stop_queue(q);
1277 	spin_unlock_irqrestore(q->queue_lock, flags);
1278 }
1279 
1280 static void dm_stop_queue(struct request_queue *q)
1281 {
1282 	if (!q->mq_ops)
1283 		dm_old_stop_queue(q);
1284 	else
1285 		blk_mq_stop_hw_queues(q);
1286 }
1287 
1288 static void dm_old_start_queue(struct request_queue *q)
1289 {
1290 	unsigned long flags;
1291 
1292 	spin_lock_irqsave(q->queue_lock, flags);
1293 	if (blk_queue_stopped(q))
1294 		blk_start_queue(q);
1295 	spin_unlock_irqrestore(q->queue_lock, flags);
1296 }
1297 
1298 static void dm_start_queue(struct request_queue *q)
1299 {
1300 	if (!q->mq_ops)
1301 		dm_old_start_queue(q);
1302 	else {
1303 		blk_mq_start_stopped_hw_queues(q, true);
1304 		blk_mq_kick_requeue_list(q);
1305 	}
1306 }
1307 
1308 static void dm_done(struct request *clone, int error, bool mapped)
1309 {
1310 	int r = error;
1311 	struct dm_rq_target_io *tio = clone->end_io_data;
1312 	dm_request_endio_fn rq_end_io = NULL;
1313 
1314 	if (tio->ti) {
1315 		rq_end_io = tio->ti->type->rq_end_io;
1316 
1317 		if (mapped && rq_end_io)
1318 			r = rq_end_io(tio->ti, clone, error, &tio->info);
1319 	}
1320 
1321 	if (unlikely(r == -EREMOTEIO && (clone->cmd_flags & REQ_WRITE_SAME) &&
1322 		     !clone->q->limits.max_write_same_sectors))
1323 		disable_write_same(tio->md);
1324 
1325 	if (r <= 0)
1326 		/* The target wants to complete the I/O */
1327 		dm_end_request(clone, r);
1328 	else if (r == DM_ENDIO_INCOMPLETE)
1329 		/* The target will handle the I/O */
1330 		return;
1331 	else if (r == DM_ENDIO_REQUEUE)
1332 		/* The target wants to requeue the I/O */
1333 		dm_requeue_original_request(tio->md, tio->orig);
1334 	else {
1335 		DMWARN("unimplemented target endio return value: %d", r);
1336 		BUG();
1337 	}
1338 }
1339 
1340 /*
1341  * Request completion handler for request-based dm
1342  */
1343 static void dm_softirq_done(struct request *rq)
1344 {
1345 	bool mapped = true;
1346 	struct dm_rq_target_io *tio = tio_from_request(rq);
1347 	struct request *clone = tio->clone;
1348 	int rw;
1349 
1350 	if (!clone) {
1351 		rq_end_stats(tio->md, rq);
1352 		rw = rq_data_dir(rq);
1353 		if (!rq->q->mq_ops) {
1354 			blk_end_request_all(rq, tio->error);
1355 			rq_completed(tio->md, rw, false);
1356 			free_old_rq_tio(tio);
1357 		} else {
1358 			blk_mq_end_request(rq, tio->error);
1359 			rq_completed(tio->md, rw, false);
1360 		}
1361 		return;
1362 	}
1363 
1364 	if (rq->cmd_flags & REQ_FAILED)
1365 		mapped = false;
1366 
1367 	dm_done(clone, tio->error, mapped);
1368 }
1369 
1370 /*
1371  * Complete the clone and the original request with the error status
1372  * through softirq context.
1373  */
1374 static void dm_complete_request(struct request *rq, int error)
1375 {
1376 	struct dm_rq_target_io *tio = tio_from_request(rq);
1377 
1378 	tio->error = error;
1379 	if (!rq->q->mq_ops)
1380 		blk_complete_request(rq);
1381 	else
1382 		blk_mq_complete_request(rq, error);
1383 }
1384 
1385 /*
1386  * Complete the not-mapped clone and the original request with the error status
1387  * through softirq context.
1388  * Target's rq_end_io() function isn't called.
1389  * This may be used when the target's map_rq() or clone_and_map_rq() functions fail.
1390  */
1391 static void dm_kill_unmapped_request(struct request *rq, int error)
1392 {
1393 	rq->cmd_flags |= REQ_FAILED;
1394 	dm_complete_request(rq, error);
1395 }
1396 
1397 /*
1398  * Called with the clone's queue lock held (in the case of .request_fn)
1399  */
1400 static void end_clone_request(struct request *clone, int error)
1401 {
1402 	struct dm_rq_target_io *tio = clone->end_io_data;
1403 
1404 	if (!clone->q->mq_ops) {
1405 		/*
1406 		 * For just cleaning up the information of the queue in which
1407 		 * the clone was dispatched.
1408 		 * The clone is *NOT* freed actually here because it is alloced
1409 		 * from dm own mempool (REQ_ALLOCED isn't set).
1410 		 */
1411 		__blk_put_request(clone->q, clone);
1412 	}
1413 
1414 	/*
1415 	 * Actual request completion is done in a softirq context which doesn't
1416 	 * hold the clone's queue lock.  Otherwise, deadlock could occur because:
1417 	 *     - another request may be submitted by the upper level driver
1418 	 *       of the stacking during the completion
1419 	 *     - the submission which requires queue lock may be done
1420 	 *       against this clone's queue
1421 	 */
1422 	dm_complete_request(tio->orig, error);
1423 }
1424 
1425 /*
1426  * Return maximum size of I/O possible at the supplied sector up to the current
1427  * target boundary.
1428  */
1429 static sector_t max_io_len_target_boundary(sector_t sector, struct dm_target *ti)
1430 {
1431 	sector_t target_offset = dm_target_offset(ti, sector);
1432 
1433 	return ti->len - target_offset;
1434 }
1435 
1436 static sector_t max_io_len(sector_t sector, struct dm_target *ti)
1437 {
1438 	sector_t len = max_io_len_target_boundary(sector, ti);
1439 	sector_t offset, max_len;
1440 
1441 	/*
1442 	 * Does the target need to split even further?
1443 	 */
1444 	if (ti->max_io_len) {
1445 		offset = dm_target_offset(ti, sector);
1446 		if (unlikely(ti->max_io_len & (ti->max_io_len - 1)))
1447 			max_len = sector_div(offset, ti->max_io_len);
1448 		else
1449 			max_len = offset & (ti->max_io_len - 1);
1450 		max_len = ti->max_io_len - max_len;
1451 
1452 		if (len > max_len)
1453 			len = max_len;
1454 	}
1455 
1456 	return len;
1457 }
1458 
1459 int dm_set_target_max_io_len(struct dm_target *ti, sector_t len)
1460 {
1461 	if (len > UINT_MAX) {
1462 		DMERR("Specified maximum size of target IO (%llu) exceeds limit (%u)",
1463 		      (unsigned long long)len, UINT_MAX);
1464 		ti->error = "Maximum size of target IO is too large";
1465 		return -EINVAL;
1466 	}
1467 
1468 	ti->max_io_len = (uint32_t) len;
1469 
1470 	return 0;
1471 }
1472 EXPORT_SYMBOL_GPL(dm_set_target_max_io_len);
1473 
1474 /*
1475  * A target may call dm_accept_partial_bio only from the map routine.  It is
1476  * allowed for all bio types except REQ_FLUSH.
1477  *
1478  * dm_accept_partial_bio informs the dm that the target only wants to process
1479  * additional n_sectors sectors of the bio and the rest of the data should be
1480  * sent in a next bio.
1481  *
1482  * A diagram that explains the arithmetics:
1483  * +--------------------+---------------+-------+
1484  * |         1          |       2       |   3   |
1485  * +--------------------+---------------+-------+
1486  *
1487  * <-------------- *tio->len_ptr --------------->
1488  *                      <------- bi_size ------->
1489  *                      <-- n_sectors -->
1490  *
1491  * Region 1 was already iterated over with bio_advance or similar function.
1492  *	(it may be empty if the target doesn't use bio_advance)
1493  * Region 2 is the remaining bio size that the target wants to process.
1494  *	(it may be empty if region 1 is non-empty, although there is no reason
1495  *	 to make it empty)
1496  * The target requires that region 3 is to be sent in the next bio.
1497  *
1498  * If the target wants to receive multiple copies of the bio (via num_*bios, etc),
1499  * the partially processed part (the sum of regions 1+2) must be the same for all
1500  * copies of the bio.
1501  */
1502 void dm_accept_partial_bio(struct bio *bio, unsigned n_sectors)
1503 {
1504 	struct dm_target_io *tio = container_of(bio, struct dm_target_io, clone);
1505 	unsigned bi_size = bio->bi_iter.bi_size >> SECTOR_SHIFT;
1506 	BUG_ON(bio->bi_rw & REQ_FLUSH);
1507 	BUG_ON(bi_size > *tio->len_ptr);
1508 	BUG_ON(n_sectors > bi_size);
1509 	*tio->len_ptr -= bi_size - n_sectors;
1510 	bio->bi_iter.bi_size = n_sectors << SECTOR_SHIFT;
1511 }
1512 EXPORT_SYMBOL_GPL(dm_accept_partial_bio);
1513 
1514 static void __map_bio(struct dm_target_io *tio)
1515 {
1516 	int r;
1517 	sector_t sector;
1518 	struct mapped_device *md;
1519 	struct bio *clone = &tio->clone;
1520 	struct dm_target *ti = tio->ti;
1521 
1522 	clone->bi_end_io = clone_endio;
1523 
1524 	/*
1525 	 * Map the clone.  If r == 0 we don't need to do
1526 	 * anything, the target has assumed ownership of
1527 	 * this io.
1528 	 */
1529 	atomic_inc(&tio->io->io_count);
1530 	sector = clone->bi_iter.bi_sector;
1531 	r = ti->type->map(ti, clone);
1532 	if (r == DM_MAPIO_REMAPPED) {
1533 		/* the bio has been remapped so dispatch it */
1534 
1535 		trace_block_bio_remap(bdev_get_queue(clone->bi_bdev), clone,
1536 				      tio->io->bio->bi_bdev->bd_dev, sector);
1537 
1538 		generic_make_request(clone);
1539 	} else if (r < 0 || r == DM_MAPIO_REQUEUE) {
1540 		/* error the io and bail out, or requeue it if needed */
1541 		md = tio->io->md;
1542 		dec_pending(tio->io, r);
1543 		free_tio(md, tio);
1544 	} else if (r != DM_MAPIO_SUBMITTED) {
1545 		DMWARN("unimplemented target map return value: %d", r);
1546 		BUG();
1547 	}
1548 }
1549 
1550 struct clone_info {
1551 	struct mapped_device *md;
1552 	struct dm_table *map;
1553 	struct bio *bio;
1554 	struct dm_io *io;
1555 	sector_t sector;
1556 	unsigned sector_count;
1557 };
1558 
1559 static void bio_setup_sector(struct bio *bio, sector_t sector, unsigned len)
1560 {
1561 	bio->bi_iter.bi_sector = sector;
1562 	bio->bi_iter.bi_size = to_bytes(len);
1563 }
1564 
1565 /*
1566  * Creates a bio that consists of range of complete bvecs.
1567  */
1568 static void clone_bio(struct dm_target_io *tio, struct bio *bio,
1569 		      sector_t sector, unsigned len)
1570 {
1571 	struct bio *clone = &tio->clone;
1572 
1573 	__bio_clone_fast(clone, bio);
1574 
1575 	if (bio_integrity(bio))
1576 		bio_integrity_clone(clone, bio, GFP_NOIO);
1577 
1578 	bio_advance(clone, to_bytes(sector - clone->bi_iter.bi_sector));
1579 	clone->bi_iter.bi_size = to_bytes(len);
1580 
1581 	if (bio_integrity(bio))
1582 		bio_integrity_trim(clone, 0, len);
1583 }
1584 
1585 static struct dm_target_io *alloc_tio(struct clone_info *ci,
1586 				      struct dm_target *ti,
1587 				      unsigned target_bio_nr)
1588 {
1589 	struct dm_target_io *tio;
1590 	struct bio *clone;
1591 
1592 	clone = bio_alloc_bioset(GFP_NOIO, 0, ci->md->bs);
1593 	tio = container_of(clone, struct dm_target_io, clone);
1594 
1595 	tio->io = ci->io;
1596 	tio->ti = ti;
1597 	tio->target_bio_nr = target_bio_nr;
1598 
1599 	return tio;
1600 }
1601 
1602 static void __clone_and_map_simple_bio(struct clone_info *ci,
1603 				       struct dm_target *ti,
1604 				       unsigned target_bio_nr, unsigned *len)
1605 {
1606 	struct dm_target_io *tio = alloc_tio(ci, ti, target_bio_nr);
1607 	struct bio *clone = &tio->clone;
1608 
1609 	tio->len_ptr = len;
1610 
1611 	__bio_clone_fast(clone, ci->bio);
1612 	if (len)
1613 		bio_setup_sector(clone, ci->sector, *len);
1614 
1615 	__map_bio(tio);
1616 }
1617 
1618 static void __send_duplicate_bios(struct clone_info *ci, struct dm_target *ti,
1619 				  unsigned num_bios, unsigned *len)
1620 {
1621 	unsigned target_bio_nr;
1622 
1623 	for (target_bio_nr = 0; target_bio_nr < num_bios; target_bio_nr++)
1624 		__clone_and_map_simple_bio(ci, ti, target_bio_nr, len);
1625 }
1626 
1627 static int __send_empty_flush(struct clone_info *ci)
1628 {
1629 	unsigned target_nr = 0;
1630 	struct dm_target *ti;
1631 
1632 	BUG_ON(bio_has_data(ci->bio));
1633 	while ((ti = dm_table_get_target(ci->map, target_nr++)))
1634 		__send_duplicate_bios(ci, ti, ti->num_flush_bios, NULL);
1635 
1636 	return 0;
1637 }
1638 
1639 static void __clone_and_map_data_bio(struct clone_info *ci, struct dm_target *ti,
1640 				     sector_t sector, unsigned *len)
1641 {
1642 	struct bio *bio = ci->bio;
1643 	struct dm_target_io *tio;
1644 	unsigned target_bio_nr;
1645 	unsigned num_target_bios = 1;
1646 
1647 	/*
1648 	 * Does the target want to receive duplicate copies of the bio?
1649 	 */
1650 	if (bio_data_dir(bio) == WRITE && ti->num_write_bios)
1651 		num_target_bios = ti->num_write_bios(ti, bio);
1652 
1653 	for (target_bio_nr = 0; target_bio_nr < num_target_bios; target_bio_nr++) {
1654 		tio = alloc_tio(ci, ti, target_bio_nr);
1655 		tio->len_ptr = len;
1656 		clone_bio(tio, bio, sector, *len);
1657 		__map_bio(tio);
1658 	}
1659 }
1660 
1661 typedef unsigned (*get_num_bios_fn)(struct dm_target *ti);
1662 
1663 static unsigned get_num_discard_bios(struct dm_target *ti)
1664 {
1665 	return ti->num_discard_bios;
1666 }
1667 
1668 static unsigned get_num_write_same_bios(struct dm_target *ti)
1669 {
1670 	return ti->num_write_same_bios;
1671 }
1672 
1673 typedef bool (*is_split_required_fn)(struct dm_target *ti);
1674 
1675 static bool is_split_required_for_discard(struct dm_target *ti)
1676 {
1677 	return ti->split_discard_bios;
1678 }
1679 
1680 static int __send_changing_extent_only(struct clone_info *ci,
1681 				       get_num_bios_fn get_num_bios,
1682 				       is_split_required_fn is_split_required)
1683 {
1684 	struct dm_target *ti;
1685 	unsigned len;
1686 	unsigned num_bios;
1687 
1688 	do {
1689 		ti = dm_table_find_target(ci->map, ci->sector);
1690 		if (!dm_target_is_valid(ti))
1691 			return -EIO;
1692 
1693 		/*
1694 		 * Even though the device advertised support for this type of
1695 		 * request, that does not mean every target supports it, and
1696 		 * reconfiguration might also have changed that since the
1697 		 * check was performed.
1698 		 */
1699 		num_bios = get_num_bios ? get_num_bios(ti) : 0;
1700 		if (!num_bios)
1701 			return -EOPNOTSUPP;
1702 
1703 		if (is_split_required && !is_split_required(ti))
1704 			len = min((sector_t)ci->sector_count, max_io_len_target_boundary(ci->sector, ti));
1705 		else
1706 			len = min((sector_t)ci->sector_count, max_io_len(ci->sector, ti));
1707 
1708 		__send_duplicate_bios(ci, ti, num_bios, &len);
1709 
1710 		ci->sector += len;
1711 	} while (ci->sector_count -= len);
1712 
1713 	return 0;
1714 }
1715 
1716 static int __send_discard(struct clone_info *ci)
1717 {
1718 	return __send_changing_extent_only(ci, get_num_discard_bios,
1719 					   is_split_required_for_discard);
1720 }
1721 
1722 static int __send_write_same(struct clone_info *ci)
1723 {
1724 	return __send_changing_extent_only(ci, get_num_write_same_bios, NULL);
1725 }
1726 
1727 /*
1728  * Select the correct strategy for processing a non-flush bio.
1729  */
1730 static int __split_and_process_non_flush(struct clone_info *ci)
1731 {
1732 	struct bio *bio = ci->bio;
1733 	struct dm_target *ti;
1734 	unsigned len;
1735 
1736 	if (unlikely(bio->bi_rw & REQ_DISCARD))
1737 		return __send_discard(ci);
1738 	else if (unlikely(bio->bi_rw & REQ_WRITE_SAME))
1739 		return __send_write_same(ci);
1740 
1741 	ti = dm_table_find_target(ci->map, ci->sector);
1742 	if (!dm_target_is_valid(ti))
1743 		return -EIO;
1744 
1745 	len = min_t(sector_t, max_io_len(ci->sector, ti), ci->sector_count);
1746 
1747 	__clone_and_map_data_bio(ci, ti, ci->sector, &len);
1748 
1749 	ci->sector += len;
1750 	ci->sector_count -= len;
1751 
1752 	return 0;
1753 }
1754 
1755 /*
1756  * Entry point to split a bio into clones and submit them to the targets.
1757  */
1758 static void __split_and_process_bio(struct mapped_device *md,
1759 				    struct dm_table *map, struct bio *bio)
1760 {
1761 	struct clone_info ci;
1762 	int error = 0;
1763 
1764 	if (unlikely(!map)) {
1765 		bio_io_error(bio);
1766 		return;
1767 	}
1768 
1769 	ci.map = map;
1770 	ci.md = md;
1771 	ci.io = alloc_io(md);
1772 	ci.io->error = 0;
1773 	atomic_set(&ci.io->io_count, 1);
1774 	ci.io->bio = bio;
1775 	ci.io->md = md;
1776 	spin_lock_init(&ci.io->endio_lock);
1777 	ci.sector = bio->bi_iter.bi_sector;
1778 
1779 	start_io_acct(ci.io);
1780 
1781 	if (bio->bi_rw & REQ_FLUSH) {
1782 		ci.bio = &ci.md->flush_bio;
1783 		ci.sector_count = 0;
1784 		error = __send_empty_flush(&ci);
1785 		/* dec_pending submits any data associated with flush */
1786 	} else {
1787 		ci.bio = bio;
1788 		ci.sector_count = bio_sectors(bio);
1789 		while (ci.sector_count && !error)
1790 			error = __split_and_process_non_flush(&ci);
1791 	}
1792 
1793 	/* drop the extra reference count */
1794 	dec_pending(ci.io, error);
1795 }
1796 /*-----------------------------------------------------------------
1797  * CRUD END
1798  *---------------------------------------------------------------*/
1799 
1800 /*
1801  * The request function that just remaps the bio built up by
1802  * dm_merge_bvec.
1803  */
1804 static blk_qc_t dm_make_request(struct request_queue *q, struct bio *bio)
1805 {
1806 	int rw = bio_data_dir(bio);
1807 	struct mapped_device *md = q->queuedata;
1808 	int srcu_idx;
1809 	struct dm_table *map;
1810 
1811 	map = dm_get_live_table(md, &srcu_idx);
1812 
1813 	generic_start_io_acct(rw, bio_sectors(bio), &dm_disk(md)->part0);
1814 
1815 	/* if we're suspended, we have to queue this io for later */
1816 	if (unlikely(test_bit(DMF_BLOCK_IO_FOR_SUSPEND, &md->flags))) {
1817 		dm_put_live_table(md, srcu_idx);
1818 
1819 		if (bio_rw(bio) != READA)
1820 			queue_io(md, bio);
1821 		else
1822 			bio_io_error(bio);
1823 		return BLK_QC_T_NONE;
1824 	}
1825 
1826 	__split_and_process_bio(md, map, bio);
1827 	dm_put_live_table(md, srcu_idx);
1828 	return BLK_QC_T_NONE;
1829 }
1830 
1831 int dm_request_based(struct mapped_device *md)
1832 {
1833 	return blk_queue_stackable(md->queue);
1834 }
1835 
1836 static void dm_dispatch_clone_request(struct request *clone, struct request *rq)
1837 {
1838 	int r;
1839 
1840 	if (blk_queue_io_stat(clone->q))
1841 		clone->cmd_flags |= REQ_IO_STAT;
1842 
1843 	clone->start_time = jiffies;
1844 	r = blk_insert_cloned_request(clone->q, clone);
1845 	if (r)
1846 		/* must complete clone in terms of original request */
1847 		dm_complete_request(rq, r);
1848 }
1849 
1850 static int dm_rq_bio_constructor(struct bio *bio, struct bio *bio_orig,
1851 				 void *data)
1852 {
1853 	struct dm_rq_target_io *tio = data;
1854 	struct dm_rq_clone_bio_info *info =
1855 		container_of(bio, struct dm_rq_clone_bio_info, clone);
1856 
1857 	info->orig = bio_orig;
1858 	info->tio = tio;
1859 	bio->bi_end_io = end_clone_bio;
1860 
1861 	return 0;
1862 }
1863 
1864 static int setup_clone(struct request *clone, struct request *rq,
1865 		       struct dm_rq_target_io *tio, gfp_t gfp_mask)
1866 {
1867 	int r;
1868 
1869 	r = blk_rq_prep_clone(clone, rq, tio->md->bs, gfp_mask,
1870 			      dm_rq_bio_constructor, tio);
1871 	if (r)
1872 		return r;
1873 
1874 	clone->cmd = rq->cmd;
1875 	clone->cmd_len = rq->cmd_len;
1876 	clone->sense = rq->sense;
1877 	clone->end_io = end_clone_request;
1878 	clone->end_io_data = tio;
1879 
1880 	tio->clone = clone;
1881 
1882 	return 0;
1883 }
1884 
1885 static struct request *clone_old_rq(struct request *rq, struct mapped_device *md,
1886 				    struct dm_rq_target_io *tio, gfp_t gfp_mask)
1887 {
1888 	/*
1889 	 * Create clone for use with .request_fn request_queue
1890 	 */
1891 	struct request *clone;
1892 
1893 	clone = alloc_old_clone_request(md, gfp_mask);
1894 	if (!clone)
1895 		return NULL;
1896 
1897 	blk_rq_init(NULL, clone);
1898 	if (setup_clone(clone, rq, tio, gfp_mask)) {
1899 		/* -ENOMEM */
1900 		free_old_clone_request(md, clone);
1901 		return NULL;
1902 	}
1903 
1904 	return clone;
1905 }
1906 
1907 static void map_tio_request(struct kthread_work *work);
1908 
1909 static void init_tio(struct dm_rq_target_io *tio, struct request *rq,
1910 		     struct mapped_device *md)
1911 {
1912 	tio->md = md;
1913 	tio->ti = NULL;
1914 	tio->clone = NULL;
1915 	tio->orig = rq;
1916 	tio->error = 0;
1917 	/*
1918 	 * Avoid initializing info for blk-mq; it passes
1919 	 * target-specific data through info.ptr
1920 	 * (see: dm_mq_init_request)
1921 	 */
1922 	if (!md->init_tio_pdu)
1923 		memset(&tio->info, 0, sizeof(tio->info));
1924 	if (md->kworker_task)
1925 		init_kthread_work(&tio->work, map_tio_request);
1926 }
1927 
1928 static struct dm_rq_target_io *dm_old_prep_tio(struct request *rq,
1929 					       struct mapped_device *md,
1930 					       gfp_t gfp_mask)
1931 {
1932 	struct dm_rq_target_io *tio;
1933 	int srcu_idx;
1934 	struct dm_table *table;
1935 
1936 	tio = alloc_old_rq_tio(md, gfp_mask);
1937 	if (!tio)
1938 		return NULL;
1939 
1940 	init_tio(tio, rq, md);
1941 
1942 	table = dm_get_live_table(md, &srcu_idx);
1943 	/*
1944 	 * Must clone a request if this .request_fn DM device
1945 	 * is stacked on .request_fn device(s).
1946 	 */
1947 	if (!dm_table_mq_request_based(table)) {
1948 		if (!clone_old_rq(rq, md, tio, gfp_mask)) {
1949 			dm_put_live_table(md, srcu_idx);
1950 			free_old_rq_tio(tio);
1951 			return NULL;
1952 		}
1953 	}
1954 	dm_put_live_table(md, srcu_idx);
1955 
1956 	return tio;
1957 }
1958 
1959 /*
1960  * Called with the queue lock held.
1961  */
1962 static int dm_old_prep_fn(struct request_queue *q, struct request *rq)
1963 {
1964 	struct mapped_device *md = q->queuedata;
1965 	struct dm_rq_target_io *tio;
1966 
1967 	if (unlikely(rq->special)) {
1968 		DMWARN("Already has something in rq->special.");
1969 		return BLKPREP_KILL;
1970 	}
1971 
1972 	tio = dm_old_prep_tio(rq, md, GFP_ATOMIC);
1973 	if (!tio)
1974 		return BLKPREP_DEFER;
1975 
1976 	rq->special = tio;
1977 	rq->cmd_flags |= REQ_DONTPREP;
1978 
1979 	return BLKPREP_OK;
1980 }
1981 
1982 /*
1983  * Returns:
1984  * 0                : the request has been processed
1985  * DM_MAPIO_REQUEUE : the original request needs to be requeued
1986  * < 0              : the request was completed due to failure
1987  */
1988 static int map_request(struct dm_rq_target_io *tio, struct request *rq,
1989 		       struct mapped_device *md)
1990 {
1991 	int r;
1992 	struct dm_target *ti = tio->ti;
1993 	struct request *clone = NULL;
1994 
1995 	if (tio->clone) {
1996 		clone = tio->clone;
1997 		r = ti->type->map_rq(ti, clone, &tio->info);
1998 	} else {
1999 		r = ti->type->clone_and_map_rq(ti, rq, &tio->info, &clone);
2000 		if (r < 0) {
2001 			/* The target wants to complete the I/O */
2002 			dm_kill_unmapped_request(rq, r);
2003 			return r;
2004 		}
2005 		if (r != DM_MAPIO_REMAPPED)
2006 			return r;
2007 		if (setup_clone(clone, rq, tio, GFP_ATOMIC)) {
2008 			/* -ENOMEM */
2009 			ti->type->release_clone_rq(clone);
2010 			return DM_MAPIO_REQUEUE;
2011 		}
2012 	}
2013 
2014 	switch (r) {
2015 	case DM_MAPIO_SUBMITTED:
2016 		/* The target has taken the I/O to submit by itself later */
2017 		break;
2018 	case DM_MAPIO_REMAPPED:
2019 		/* The target has remapped the I/O so dispatch it */
2020 		trace_block_rq_remap(clone->q, clone, disk_devt(dm_disk(md)),
2021 				     blk_rq_pos(rq));
2022 		dm_dispatch_clone_request(clone, rq);
2023 		break;
2024 	case DM_MAPIO_REQUEUE:
2025 		/* The target wants to requeue the I/O */
2026 		dm_requeue_original_request(md, tio->orig);
2027 		break;
2028 	default:
2029 		if (r > 0) {
2030 			DMWARN("unimplemented target map return value: %d", r);
2031 			BUG();
2032 		}
2033 
2034 		/* The target wants to complete the I/O */
2035 		dm_kill_unmapped_request(rq, r);
2036 		return r;
2037 	}
2038 
2039 	return 0;
2040 }
2041 
2042 static void map_tio_request(struct kthread_work *work)
2043 {
2044 	struct dm_rq_target_io *tio = container_of(work, struct dm_rq_target_io, work);
2045 	struct request *rq = tio->orig;
2046 	struct mapped_device *md = tio->md;
2047 
2048 	if (map_request(tio, rq, md) == DM_MAPIO_REQUEUE)
2049 		dm_requeue_original_request(md, rq);
2050 }
2051 
2052 static void dm_start_request(struct mapped_device *md, struct request *orig)
2053 {
2054 	if (!orig->q->mq_ops)
2055 		blk_start_request(orig);
2056 	else
2057 		blk_mq_start_request(orig);
2058 	atomic_inc(&md->pending[rq_data_dir(orig)]);
2059 
2060 	if (md->seq_rq_merge_deadline_usecs) {
2061 		md->last_rq_pos = rq_end_sector(orig);
2062 		md->last_rq_rw = rq_data_dir(orig);
2063 		md->last_rq_start_time = ktime_get();
2064 	}
2065 
2066 	if (unlikely(dm_stats_used(&md->stats))) {
2067 		struct dm_rq_target_io *tio = tio_from_request(orig);
2068 		tio->duration_jiffies = jiffies;
2069 		tio->n_sectors = blk_rq_sectors(orig);
2070 		dm_stats_account_io(&md->stats, orig->cmd_flags, blk_rq_pos(orig),
2071 				    tio->n_sectors, false, 0, &tio->stats_aux);
2072 	}
2073 
2074 	/*
2075 	 * Hold the md reference here for the in-flight I/O.
2076 	 * We can't rely on the reference count by device opener,
2077 	 * because the device may be closed during the request completion
2078 	 * when all bios are completed.
2079 	 * See the comment in rq_completed() too.
2080 	 */
2081 	dm_get(md);
2082 }
2083 
2084 #define MAX_SEQ_RQ_MERGE_DEADLINE_USECS 100000
2085 
2086 ssize_t dm_attr_rq_based_seq_io_merge_deadline_show(struct mapped_device *md, char *buf)
2087 {
2088 	return sprintf(buf, "%u\n", md->seq_rq_merge_deadline_usecs);
2089 }
2090 
2091 ssize_t dm_attr_rq_based_seq_io_merge_deadline_store(struct mapped_device *md,
2092 						     const char *buf, size_t count)
2093 {
2094 	unsigned deadline;
2095 
2096 	if (!dm_request_based(md) || md->use_blk_mq)
2097 		return count;
2098 
2099 	if (kstrtouint(buf, 10, &deadline))
2100 		return -EINVAL;
2101 
2102 	if (deadline > MAX_SEQ_RQ_MERGE_DEADLINE_USECS)
2103 		deadline = MAX_SEQ_RQ_MERGE_DEADLINE_USECS;
2104 
2105 	md->seq_rq_merge_deadline_usecs = deadline;
2106 
2107 	return count;
2108 }
2109 
2110 static bool dm_request_peeked_before_merge_deadline(struct mapped_device *md)
2111 {
2112 	ktime_t kt_deadline;
2113 
2114 	if (!md->seq_rq_merge_deadline_usecs)
2115 		return false;
2116 
2117 	kt_deadline = ns_to_ktime((u64)md->seq_rq_merge_deadline_usecs * NSEC_PER_USEC);
2118 	kt_deadline = ktime_add_safe(md->last_rq_start_time, kt_deadline);
2119 
2120 	return !ktime_after(ktime_get(), kt_deadline);
2121 }
2122 
2123 /*
2124  * q->request_fn for request-based dm.
2125  * Called with the queue lock held.
2126  */
2127 static void dm_request_fn(struct request_queue *q)
2128 {
2129 	struct mapped_device *md = q->queuedata;
2130 	struct dm_target *ti = md->immutable_target;
2131 	struct request *rq;
2132 	struct dm_rq_target_io *tio;
2133 	sector_t pos = 0;
2134 
2135 	if (unlikely(!ti)) {
2136 		int srcu_idx;
2137 		struct dm_table *map = dm_get_live_table(md, &srcu_idx);
2138 
2139 		ti = dm_table_find_target(map, pos);
2140 		dm_put_live_table(md, srcu_idx);
2141 	}
2142 
2143 	/*
2144 	 * For suspend, check blk_queue_stopped() and increment
2145 	 * ->pending within a single queue_lock not to increment the
2146 	 * number of in-flight I/Os after the queue is stopped in
2147 	 * dm_suspend().
2148 	 */
2149 	while (!blk_queue_stopped(q)) {
2150 		rq = blk_peek_request(q);
2151 		if (!rq)
2152 			return;
2153 
2154 		/* always use block 0 to find the target for flushes for now */
2155 		pos = 0;
2156 		if (!(rq->cmd_flags & REQ_FLUSH))
2157 			pos = blk_rq_pos(rq);
2158 
2159 		if ((dm_request_peeked_before_merge_deadline(md) &&
2160 		     md_in_flight(md) && rq->bio && rq->bio->bi_vcnt == 1 &&
2161 		     md->last_rq_pos == pos && md->last_rq_rw == rq_data_dir(rq)) ||
2162 		    (ti->type->busy && ti->type->busy(ti))) {
2163 			blk_delay_queue(q, HZ / 100);
2164 			return;
2165 		}
2166 
2167 		dm_start_request(md, rq);
2168 
2169 		tio = tio_from_request(rq);
2170 		/* Establish tio->ti before queuing work (map_tio_request) */
2171 		tio->ti = ti;
2172 		queue_kthread_work(&md->kworker, &tio->work);
2173 		BUG_ON(!irqs_disabled());
2174 	}
2175 }
2176 
2177 static int dm_any_congested(void *congested_data, int bdi_bits)
2178 {
2179 	int r = bdi_bits;
2180 	struct mapped_device *md = congested_data;
2181 	struct dm_table *map;
2182 
2183 	if (!test_bit(DMF_BLOCK_IO_FOR_SUSPEND, &md->flags)) {
2184 		if (dm_request_based(md)) {
2185 			/*
2186 			 * With request-based DM we only need to check the
2187 			 * top-level queue for congestion.
2188 			 */
2189 			r = md->queue->backing_dev_info.wb.state & bdi_bits;
2190 		} else {
2191 			map = dm_get_live_table_fast(md);
2192 			if (map)
2193 				r = dm_table_any_congested(map, bdi_bits);
2194 			dm_put_live_table_fast(md);
2195 		}
2196 	}
2197 
2198 	return r;
2199 }
2200 
2201 /*-----------------------------------------------------------------
2202  * An IDR is used to keep track of allocated minor numbers.
2203  *---------------------------------------------------------------*/
2204 static void free_minor(int minor)
2205 {
2206 	spin_lock(&_minor_lock);
2207 	idr_remove(&_minor_idr, minor);
2208 	spin_unlock(&_minor_lock);
2209 }
2210 
2211 /*
2212  * See if the device with a specific minor # is free.
2213  */
2214 static int specific_minor(int minor)
2215 {
2216 	int r;
2217 
2218 	if (minor >= (1 << MINORBITS))
2219 		return -EINVAL;
2220 
2221 	idr_preload(GFP_KERNEL);
2222 	spin_lock(&_minor_lock);
2223 
2224 	r = idr_alloc(&_minor_idr, MINOR_ALLOCED, minor, minor + 1, GFP_NOWAIT);
2225 
2226 	spin_unlock(&_minor_lock);
2227 	idr_preload_end();
2228 	if (r < 0)
2229 		return r == -ENOSPC ? -EBUSY : r;
2230 	return 0;
2231 }
2232 
2233 static int next_free_minor(int *minor)
2234 {
2235 	int r;
2236 
2237 	idr_preload(GFP_KERNEL);
2238 	spin_lock(&_minor_lock);
2239 
2240 	r = idr_alloc(&_minor_idr, MINOR_ALLOCED, 0, 1 << MINORBITS, GFP_NOWAIT);
2241 
2242 	spin_unlock(&_minor_lock);
2243 	idr_preload_end();
2244 	if (r < 0)
2245 		return r;
2246 	*minor = r;
2247 	return 0;
2248 }
2249 
2250 static const struct block_device_operations dm_blk_dops;
2251 
2252 static void dm_wq_work(struct work_struct *work);
2253 
2254 static void dm_init_md_queue(struct mapped_device *md)
2255 {
2256 	/*
2257 	 * Request-based dm devices cannot be stacked on top of bio-based dm
2258 	 * devices.  The type of this dm device may not have been decided yet.
2259 	 * The type is decided at the first table loading time.
2260 	 * To prevent problematic device stacking, clear the queue flag
2261 	 * for request stacking support until then.
2262 	 *
2263 	 * This queue is new, so no concurrency on the queue_flags.
2264 	 */
2265 	queue_flag_clear_unlocked(QUEUE_FLAG_STACKABLE, md->queue);
2266 
2267 	/*
2268 	 * Initialize data that will only be used by a non-blk-mq DM queue
2269 	 * - must do so here (in alloc_dev callchain) before queue is used
2270 	 */
2271 	md->queue->queuedata = md;
2272 	md->queue->backing_dev_info.congested_data = md;
2273 }
2274 
2275 static void dm_init_normal_md_queue(struct mapped_device *md)
2276 {
2277 	md->use_blk_mq = false;
2278 	dm_init_md_queue(md);
2279 
2280 	/*
2281 	 * Initialize aspects of queue that aren't relevant for blk-mq
2282 	 */
2283 	md->queue->backing_dev_info.congested_fn = dm_any_congested;
2284 	blk_queue_bounce_limit(md->queue, BLK_BOUNCE_ANY);
2285 }
2286 
2287 static void cleanup_mapped_device(struct mapped_device *md)
2288 {
2289 	if (md->wq)
2290 		destroy_workqueue(md->wq);
2291 	if (md->kworker_task)
2292 		kthread_stop(md->kworker_task);
2293 	mempool_destroy(md->io_pool);
2294 	mempool_destroy(md->rq_pool);
2295 	if (md->bs)
2296 		bioset_free(md->bs);
2297 
2298 	cleanup_srcu_struct(&md->io_barrier);
2299 
2300 	if (md->disk) {
2301 		spin_lock(&_minor_lock);
2302 		md->disk->private_data = NULL;
2303 		spin_unlock(&_minor_lock);
2304 		del_gendisk(md->disk);
2305 		put_disk(md->disk);
2306 	}
2307 
2308 	if (md->queue)
2309 		blk_cleanup_queue(md->queue);
2310 
2311 	if (md->bdev) {
2312 		bdput(md->bdev);
2313 		md->bdev = NULL;
2314 	}
2315 }
2316 
2317 /*
2318  * Allocate and initialise a blank device with a given minor.
2319  */
2320 static struct mapped_device *alloc_dev(int minor)
2321 {
2322 	int r, numa_node_id = dm_get_numa_node();
2323 	struct mapped_device *md;
2324 	void *old_md;
2325 
2326 	md = kzalloc_node(sizeof(*md), GFP_KERNEL, numa_node_id);
2327 	if (!md) {
2328 		DMWARN("unable to allocate device, out of memory.");
2329 		return NULL;
2330 	}
2331 
2332 	if (!try_module_get(THIS_MODULE))
2333 		goto bad_module_get;
2334 
2335 	/* get a minor number for the dev */
2336 	if (minor == DM_ANY_MINOR)
2337 		r = next_free_minor(&minor);
2338 	else
2339 		r = specific_minor(minor);
2340 	if (r < 0)
2341 		goto bad_minor;
2342 
2343 	r = init_srcu_struct(&md->io_barrier);
2344 	if (r < 0)
2345 		goto bad_io_barrier;
2346 
2347 	md->numa_node_id = numa_node_id;
2348 	md->use_blk_mq = use_blk_mq;
2349 	md->init_tio_pdu = false;
2350 	md->type = DM_TYPE_NONE;
2351 	mutex_init(&md->suspend_lock);
2352 	mutex_init(&md->type_lock);
2353 	mutex_init(&md->table_devices_lock);
2354 	spin_lock_init(&md->deferred_lock);
2355 	atomic_set(&md->holders, 1);
2356 	atomic_set(&md->open_count, 0);
2357 	atomic_set(&md->event_nr, 0);
2358 	atomic_set(&md->uevent_seq, 0);
2359 	INIT_LIST_HEAD(&md->uevent_list);
2360 	INIT_LIST_HEAD(&md->table_devices);
2361 	spin_lock_init(&md->uevent_lock);
2362 
2363 	md->queue = blk_alloc_queue_node(GFP_KERNEL, numa_node_id);
2364 	if (!md->queue)
2365 		goto bad;
2366 
2367 	dm_init_md_queue(md);
2368 
2369 	md->disk = alloc_disk_node(1, numa_node_id);
2370 	if (!md->disk)
2371 		goto bad;
2372 
2373 	atomic_set(&md->pending[0], 0);
2374 	atomic_set(&md->pending[1], 0);
2375 	init_waitqueue_head(&md->wait);
2376 	INIT_WORK(&md->work, dm_wq_work);
2377 	init_waitqueue_head(&md->eventq);
2378 	init_completion(&md->kobj_holder.completion);
2379 	md->kworker_task = NULL;
2380 
2381 	md->disk->major = _major;
2382 	md->disk->first_minor = minor;
2383 	md->disk->fops = &dm_blk_dops;
2384 	md->disk->queue = md->queue;
2385 	md->disk->private_data = md;
2386 	sprintf(md->disk->disk_name, "dm-%d", minor);
2387 	add_disk(md->disk);
2388 	format_dev_t(md->name, MKDEV(_major, minor));
2389 
2390 	md->wq = alloc_workqueue("kdmflush", WQ_MEM_RECLAIM, 0);
2391 	if (!md->wq)
2392 		goto bad;
2393 
2394 	md->bdev = bdget_disk(md->disk, 0);
2395 	if (!md->bdev)
2396 		goto bad;
2397 
2398 	bio_init(&md->flush_bio);
2399 	md->flush_bio.bi_bdev = md->bdev;
2400 	md->flush_bio.bi_rw = WRITE_FLUSH;
2401 
2402 	dm_stats_init(&md->stats);
2403 
2404 	/* Populate the mapping, nobody knows we exist yet */
2405 	spin_lock(&_minor_lock);
2406 	old_md = idr_replace(&_minor_idr, md, minor);
2407 	spin_unlock(&_minor_lock);
2408 
2409 	BUG_ON(old_md != MINOR_ALLOCED);
2410 
2411 	return md;
2412 
2413 bad:
2414 	cleanup_mapped_device(md);
2415 bad_io_barrier:
2416 	free_minor(minor);
2417 bad_minor:
2418 	module_put(THIS_MODULE);
2419 bad_module_get:
2420 	kfree(md);
2421 	return NULL;
2422 }
2423 
2424 static void unlock_fs(struct mapped_device *md);
2425 
2426 static void free_dev(struct mapped_device *md)
2427 {
2428 	int minor = MINOR(disk_devt(md->disk));
2429 
2430 	unlock_fs(md);
2431 
2432 	cleanup_mapped_device(md);
2433 	if (md->tag_set) {
2434 		blk_mq_free_tag_set(md->tag_set);
2435 		kfree(md->tag_set);
2436 	}
2437 
2438 	free_table_devices(&md->table_devices);
2439 	dm_stats_cleanup(&md->stats);
2440 	free_minor(minor);
2441 
2442 	module_put(THIS_MODULE);
2443 	kfree(md);
2444 }
2445 
2446 static void __bind_mempools(struct mapped_device *md, struct dm_table *t)
2447 {
2448 	struct dm_md_mempools *p = dm_table_get_md_mempools(t);
2449 
2450 	if (md->bs) {
2451 		/* The md already has necessary mempools. */
2452 		if (dm_table_get_type(t) == DM_TYPE_BIO_BASED) {
2453 			/*
2454 			 * Reload bioset because front_pad may have changed
2455 			 * because a different table was loaded.
2456 			 */
2457 			bioset_free(md->bs);
2458 			md->bs = p->bs;
2459 			p->bs = NULL;
2460 		}
2461 		/*
2462 		 * There's no need to reload with request-based dm
2463 		 * because the size of front_pad doesn't change.
2464 		 * Note for future: If you are to reload bioset,
2465 		 * prep-ed requests in the queue may refer
2466 		 * to bio from the old bioset, so you must walk
2467 		 * through the queue to unprep.
2468 		 */
2469 		goto out;
2470 	}
2471 
2472 	BUG_ON(!p || md->io_pool || md->rq_pool || md->bs);
2473 
2474 	md->io_pool = p->io_pool;
2475 	p->io_pool = NULL;
2476 	md->rq_pool = p->rq_pool;
2477 	p->rq_pool = NULL;
2478 	md->bs = p->bs;
2479 	p->bs = NULL;
2480 
2481 out:
2482 	/* mempool bind completed, no longer need any mempools in the table */
2483 	dm_table_free_md_mempools(t);
2484 }
2485 
2486 /*
2487  * Bind a table to the device.
2488  */
2489 static void event_callback(void *context)
2490 {
2491 	unsigned long flags;
2492 	LIST_HEAD(uevents);
2493 	struct mapped_device *md = (struct mapped_device *) context;
2494 
2495 	spin_lock_irqsave(&md->uevent_lock, flags);
2496 	list_splice_init(&md->uevent_list, &uevents);
2497 	spin_unlock_irqrestore(&md->uevent_lock, flags);
2498 
2499 	dm_send_uevents(&uevents, &disk_to_dev(md->disk)->kobj);
2500 
2501 	atomic_inc(&md->event_nr);
2502 	wake_up(&md->eventq);
2503 }
2504 
2505 /*
2506  * Protected by md->suspend_lock obtained by dm_swap_table().
2507  */
2508 static void __set_size(struct mapped_device *md, sector_t size)
2509 {
2510 	set_capacity(md->disk, size);
2511 
2512 	i_size_write(md->bdev->bd_inode, (loff_t)size << SECTOR_SHIFT);
2513 }
2514 
2515 /*
2516  * Returns old map, which caller must destroy.
2517  */
2518 static struct dm_table *__bind(struct mapped_device *md, struct dm_table *t,
2519 			       struct queue_limits *limits)
2520 {
2521 	struct dm_table *old_map;
2522 	struct request_queue *q = md->queue;
2523 	sector_t size;
2524 
2525 	size = dm_table_get_size(t);
2526 
2527 	/*
2528 	 * Wipe any geometry if the size of the table changed.
2529 	 */
2530 	if (size != dm_get_size(md))
2531 		memset(&md->geometry, 0, sizeof(md->geometry));
2532 
2533 	__set_size(md, size);
2534 
2535 	dm_table_event_callback(t, event_callback, md);
2536 
2537 	/*
2538 	 * The queue hasn't been stopped yet, if the old table type wasn't
2539 	 * for request-based during suspension.  So stop it to prevent
2540 	 * I/O mapping before resume.
2541 	 * This must be done before setting the queue restrictions,
2542 	 * because request-based dm may be run just after the setting.
2543 	 */
2544 	if (dm_table_request_based(t)) {
2545 		dm_stop_queue(q);
2546 		/*
2547 		 * Leverage the fact that request-based DM targets are
2548 		 * immutable singletons and establish md->immutable_target
2549 		 * - used to optimize both dm_request_fn and dm_mq_queue_rq
2550 		 */
2551 		md->immutable_target = dm_table_get_immutable_target(t);
2552 	}
2553 
2554 	__bind_mempools(md, t);
2555 
2556 	old_map = rcu_dereference_protected(md->map, lockdep_is_held(&md->suspend_lock));
2557 	rcu_assign_pointer(md->map, (void *)t);
2558 	md->immutable_target_type = dm_table_get_immutable_target_type(t);
2559 
2560 	dm_table_set_restrictions(t, q, limits);
2561 	if (old_map)
2562 		dm_sync_table(md);
2563 
2564 	return old_map;
2565 }
2566 
2567 /*
2568  * Returns unbound table for the caller to free.
2569  */
2570 static struct dm_table *__unbind(struct mapped_device *md)
2571 {
2572 	struct dm_table *map = rcu_dereference_protected(md->map, 1);
2573 
2574 	if (!map)
2575 		return NULL;
2576 
2577 	dm_table_event_callback(map, NULL, NULL);
2578 	RCU_INIT_POINTER(md->map, NULL);
2579 	dm_sync_table(md);
2580 
2581 	return map;
2582 }
2583 
2584 /*
2585  * Constructor for a new device.
2586  */
2587 int dm_create(int minor, struct mapped_device **result)
2588 {
2589 	struct mapped_device *md;
2590 
2591 	md = alloc_dev(minor);
2592 	if (!md)
2593 		return -ENXIO;
2594 
2595 	dm_sysfs_init(md);
2596 
2597 	*result = md;
2598 	return 0;
2599 }
2600 
2601 /*
2602  * Functions to manage md->type.
2603  * All are required to hold md->type_lock.
2604  */
2605 void dm_lock_md_type(struct mapped_device *md)
2606 {
2607 	mutex_lock(&md->type_lock);
2608 }
2609 
2610 void dm_unlock_md_type(struct mapped_device *md)
2611 {
2612 	mutex_unlock(&md->type_lock);
2613 }
2614 
2615 void dm_set_md_type(struct mapped_device *md, unsigned type)
2616 {
2617 	BUG_ON(!mutex_is_locked(&md->type_lock));
2618 	md->type = type;
2619 }
2620 
2621 unsigned dm_get_md_type(struct mapped_device *md)
2622 {
2623 	return md->type;
2624 }
2625 
2626 struct target_type *dm_get_immutable_target_type(struct mapped_device *md)
2627 {
2628 	return md->immutable_target_type;
2629 }
2630 
2631 /*
2632  * The queue_limits are only valid as long as you have a reference
2633  * count on 'md'.
2634  */
2635 struct queue_limits *dm_get_queue_limits(struct mapped_device *md)
2636 {
2637 	BUG_ON(!atomic_read(&md->holders));
2638 	return &md->queue->limits;
2639 }
2640 EXPORT_SYMBOL_GPL(dm_get_queue_limits);
2641 
2642 static void dm_old_init_rq_based_worker_thread(struct mapped_device *md)
2643 {
2644 	/* Initialize the request-based DM worker thread */
2645 	init_kthread_worker(&md->kworker);
2646 	md->kworker_task = kthread_run(kthread_worker_fn, &md->kworker,
2647 				       "kdmwork-%s", dm_device_name(md));
2648 }
2649 
2650 /*
2651  * Fully initialize a .request_fn request-based queue.
2652  */
2653 static int dm_old_init_request_queue(struct mapped_device *md)
2654 {
2655 	struct request_queue *q = NULL;
2656 
2657 	/* Fully initialize the queue */
2658 	q = blk_init_allocated_queue(md->queue, dm_request_fn, NULL);
2659 	if (!q)
2660 		return -EINVAL;
2661 
2662 	/* disable dm_request_fn's merge heuristic by default */
2663 	md->seq_rq_merge_deadline_usecs = 0;
2664 
2665 	md->queue = q;
2666 	dm_init_normal_md_queue(md);
2667 	blk_queue_softirq_done(md->queue, dm_softirq_done);
2668 	blk_queue_prep_rq(md->queue, dm_old_prep_fn);
2669 
2670 	dm_old_init_rq_based_worker_thread(md);
2671 
2672 	elv_register_queue(md->queue);
2673 
2674 	return 0;
2675 }
2676 
2677 static int dm_mq_init_request(void *data, struct request *rq,
2678 			      unsigned int hctx_idx, unsigned int request_idx,
2679 			      unsigned int numa_node)
2680 {
2681 	struct mapped_device *md = data;
2682 	struct dm_rq_target_io *tio = blk_mq_rq_to_pdu(rq);
2683 
2684 	/*
2685 	 * Must initialize md member of tio, otherwise it won't
2686 	 * be available in dm_mq_queue_rq.
2687 	 */
2688 	tio->md = md;
2689 
2690 	if (md->init_tio_pdu) {
2691 		/* target-specific per-io data is immediately after the tio */
2692 		tio->info.ptr = tio + 1;
2693 	}
2694 
2695 	return 0;
2696 }
2697 
2698 static int dm_mq_queue_rq(struct blk_mq_hw_ctx *hctx,
2699 			  const struct blk_mq_queue_data *bd)
2700 {
2701 	struct request *rq = bd->rq;
2702 	struct dm_rq_target_io *tio = blk_mq_rq_to_pdu(rq);
2703 	struct mapped_device *md = tio->md;
2704 	struct dm_target *ti = md->immutable_target;
2705 
2706 	if (unlikely(!ti)) {
2707 		int srcu_idx;
2708 		struct dm_table *map = dm_get_live_table(md, &srcu_idx);
2709 
2710 		ti = dm_table_find_target(map, 0);
2711 		dm_put_live_table(md, srcu_idx);
2712 	}
2713 
2714 	if (ti->type->busy && ti->type->busy(ti))
2715 		return BLK_MQ_RQ_QUEUE_BUSY;
2716 
2717 	dm_start_request(md, rq);
2718 
2719 	/* Init tio using md established in .init_request */
2720 	init_tio(tio, rq, md);
2721 
2722 	/*
2723 	 * Establish tio->ti before queuing work (map_tio_request)
2724 	 * or making direct call to map_request().
2725 	 */
2726 	tio->ti = ti;
2727 
2728 	/* Direct call is fine since .queue_rq allows allocations */
2729 	if (map_request(tio, rq, md) == DM_MAPIO_REQUEUE) {
2730 		/* Undo dm_start_request() before requeuing */
2731 		rq_end_stats(md, rq);
2732 		rq_completed(md, rq_data_dir(rq), false);
2733 		return BLK_MQ_RQ_QUEUE_BUSY;
2734 	}
2735 
2736 	return BLK_MQ_RQ_QUEUE_OK;
2737 }
2738 
2739 static struct blk_mq_ops dm_mq_ops = {
2740 	.queue_rq = dm_mq_queue_rq,
2741 	.map_queue = blk_mq_map_queue,
2742 	.complete = dm_softirq_done,
2743 	.init_request = dm_mq_init_request,
2744 };
2745 
2746 static int dm_mq_init_request_queue(struct mapped_device *md,
2747 				    struct dm_target *immutable_tgt)
2748 {
2749 	struct request_queue *q;
2750 	int err;
2751 
2752 	if (dm_get_md_type(md) == DM_TYPE_REQUEST_BASED) {
2753 		DMERR("request-based dm-mq may only be stacked on blk-mq device(s)");
2754 		return -EINVAL;
2755 	}
2756 
2757 	md->tag_set = kzalloc_node(sizeof(struct blk_mq_tag_set), GFP_KERNEL, md->numa_node_id);
2758 	if (!md->tag_set)
2759 		return -ENOMEM;
2760 
2761 	md->tag_set->ops = &dm_mq_ops;
2762 	md->tag_set->queue_depth = dm_get_blk_mq_queue_depth();
2763 	md->tag_set->numa_node = md->numa_node_id;
2764 	md->tag_set->flags = BLK_MQ_F_SHOULD_MERGE | BLK_MQ_F_SG_MERGE;
2765 	md->tag_set->nr_hw_queues = dm_get_blk_mq_nr_hw_queues();
2766 	md->tag_set->driver_data = md;
2767 
2768 	md->tag_set->cmd_size = sizeof(struct dm_rq_target_io);
2769 	if (immutable_tgt && immutable_tgt->per_io_data_size) {
2770 		/* any target-specific per-io data is immediately after the tio */
2771 		md->tag_set->cmd_size += immutable_tgt->per_io_data_size;
2772 		md->init_tio_pdu = true;
2773 	}
2774 
2775 	err = blk_mq_alloc_tag_set(md->tag_set);
2776 	if (err)
2777 		goto out_kfree_tag_set;
2778 
2779 	q = blk_mq_init_allocated_queue(md->tag_set, md->queue);
2780 	if (IS_ERR(q)) {
2781 		err = PTR_ERR(q);
2782 		goto out_tag_set;
2783 	}
2784 	md->queue = q;
2785 	dm_init_md_queue(md);
2786 
2787 	/* backfill 'mq' sysfs registration normally done in blk_register_queue */
2788 	blk_mq_register_disk(md->disk);
2789 
2790 	return 0;
2791 
2792 out_tag_set:
2793 	blk_mq_free_tag_set(md->tag_set);
2794 out_kfree_tag_set:
2795 	kfree(md->tag_set);
2796 
2797 	return err;
2798 }
2799 
2800 static unsigned filter_md_type(unsigned type, struct mapped_device *md)
2801 {
2802 	if (type == DM_TYPE_BIO_BASED)
2803 		return type;
2804 
2805 	return !md->use_blk_mq ? DM_TYPE_REQUEST_BASED : DM_TYPE_MQ_REQUEST_BASED;
2806 }
2807 
2808 /*
2809  * Setup the DM device's queue based on md's type
2810  */
2811 int dm_setup_md_queue(struct mapped_device *md, struct dm_table *t)
2812 {
2813 	int r;
2814 	unsigned md_type = filter_md_type(dm_get_md_type(md), md);
2815 
2816 	switch (md_type) {
2817 	case DM_TYPE_REQUEST_BASED:
2818 		r = dm_old_init_request_queue(md);
2819 		if (r) {
2820 			DMERR("Cannot initialize queue for request-based mapped device");
2821 			return r;
2822 		}
2823 		break;
2824 	case DM_TYPE_MQ_REQUEST_BASED:
2825 		r = dm_mq_init_request_queue(md, dm_table_get_immutable_target(t));
2826 		if (r) {
2827 			DMERR("Cannot initialize queue for request-based dm-mq mapped device");
2828 			return r;
2829 		}
2830 		break;
2831 	case DM_TYPE_BIO_BASED:
2832 		dm_init_normal_md_queue(md);
2833 		blk_queue_make_request(md->queue, dm_make_request);
2834 		/*
2835 		 * DM handles splitting bios as needed.  Free the bio_split bioset
2836 		 * since it won't be used (saves 1 process per bio-based DM device).
2837 		 */
2838 		bioset_free(md->queue->bio_split);
2839 		md->queue->bio_split = NULL;
2840 		break;
2841 	}
2842 
2843 	return 0;
2844 }
2845 
2846 struct mapped_device *dm_get_md(dev_t dev)
2847 {
2848 	struct mapped_device *md;
2849 	unsigned minor = MINOR(dev);
2850 
2851 	if (MAJOR(dev) != _major || minor >= (1 << MINORBITS))
2852 		return NULL;
2853 
2854 	spin_lock(&_minor_lock);
2855 
2856 	md = idr_find(&_minor_idr, minor);
2857 	if (md) {
2858 		if ((md == MINOR_ALLOCED ||
2859 		     (MINOR(disk_devt(dm_disk(md))) != minor) ||
2860 		     dm_deleting_md(md) ||
2861 		     test_bit(DMF_FREEING, &md->flags))) {
2862 			md = NULL;
2863 			goto out;
2864 		}
2865 		dm_get(md);
2866 	}
2867 
2868 out:
2869 	spin_unlock(&_minor_lock);
2870 
2871 	return md;
2872 }
2873 EXPORT_SYMBOL_GPL(dm_get_md);
2874 
2875 void *dm_get_mdptr(struct mapped_device *md)
2876 {
2877 	return md->interface_ptr;
2878 }
2879 
2880 void dm_set_mdptr(struct mapped_device *md, void *ptr)
2881 {
2882 	md->interface_ptr = ptr;
2883 }
2884 
2885 void dm_get(struct mapped_device *md)
2886 {
2887 	atomic_inc(&md->holders);
2888 	BUG_ON(test_bit(DMF_FREEING, &md->flags));
2889 }
2890 
2891 int dm_hold(struct mapped_device *md)
2892 {
2893 	spin_lock(&_minor_lock);
2894 	if (test_bit(DMF_FREEING, &md->flags)) {
2895 		spin_unlock(&_minor_lock);
2896 		return -EBUSY;
2897 	}
2898 	dm_get(md);
2899 	spin_unlock(&_minor_lock);
2900 	return 0;
2901 }
2902 EXPORT_SYMBOL_GPL(dm_hold);
2903 
2904 const char *dm_device_name(struct mapped_device *md)
2905 {
2906 	return md->name;
2907 }
2908 EXPORT_SYMBOL_GPL(dm_device_name);
2909 
2910 static void __dm_destroy(struct mapped_device *md, bool wait)
2911 {
2912 	struct dm_table *map;
2913 	int srcu_idx;
2914 
2915 	might_sleep();
2916 
2917 	spin_lock(&_minor_lock);
2918 	idr_replace(&_minor_idr, MINOR_ALLOCED, MINOR(disk_devt(dm_disk(md))));
2919 	set_bit(DMF_FREEING, &md->flags);
2920 	spin_unlock(&_minor_lock);
2921 
2922 	if (dm_request_based(md) && md->kworker_task)
2923 		flush_kthread_worker(&md->kworker);
2924 
2925 	/*
2926 	 * Take suspend_lock so that presuspend and postsuspend methods
2927 	 * do not race with internal suspend.
2928 	 */
2929 	mutex_lock(&md->suspend_lock);
2930 	map = dm_get_live_table(md, &srcu_idx);
2931 	if (!dm_suspended_md(md)) {
2932 		dm_table_presuspend_targets(map);
2933 		dm_table_postsuspend_targets(map);
2934 	}
2935 	/* dm_put_live_table must be before msleep, otherwise deadlock is possible */
2936 	dm_put_live_table(md, srcu_idx);
2937 	mutex_unlock(&md->suspend_lock);
2938 
2939 	/*
2940 	 * Rare, but there may be I/O requests still going to complete,
2941 	 * for example.  Wait for all references to disappear.
2942 	 * No one should increment the reference count of the mapped_device,
2943 	 * after the mapped_device state becomes DMF_FREEING.
2944 	 */
2945 	if (wait)
2946 		while (atomic_read(&md->holders))
2947 			msleep(1);
2948 	else if (atomic_read(&md->holders))
2949 		DMWARN("%s: Forcibly removing mapped_device still in use! (%d users)",
2950 		       dm_device_name(md), atomic_read(&md->holders));
2951 
2952 	dm_sysfs_exit(md);
2953 	dm_table_destroy(__unbind(md));
2954 	free_dev(md);
2955 }
2956 
2957 void dm_destroy(struct mapped_device *md)
2958 {
2959 	__dm_destroy(md, true);
2960 }
2961 
2962 void dm_destroy_immediate(struct mapped_device *md)
2963 {
2964 	__dm_destroy(md, false);
2965 }
2966 
2967 void dm_put(struct mapped_device *md)
2968 {
2969 	atomic_dec(&md->holders);
2970 }
2971 EXPORT_SYMBOL_GPL(dm_put);
2972 
2973 static int dm_wait_for_completion(struct mapped_device *md, int interruptible)
2974 {
2975 	int r = 0;
2976 	DECLARE_WAITQUEUE(wait, current);
2977 
2978 	add_wait_queue(&md->wait, &wait);
2979 
2980 	while (1) {
2981 		set_current_state(interruptible);
2982 
2983 		if (!md_in_flight(md))
2984 			break;
2985 
2986 		if (interruptible == TASK_INTERRUPTIBLE &&
2987 		    signal_pending(current)) {
2988 			r = -EINTR;
2989 			break;
2990 		}
2991 
2992 		io_schedule();
2993 	}
2994 	set_current_state(TASK_RUNNING);
2995 
2996 	remove_wait_queue(&md->wait, &wait);
2997 
2998 	return r;
2999 }
3000 
3001 /*
3002  * Process the deferred bios
3003  */
3004 static void dm_wq_work(struct work_struct *work)
3005 {
3006 	struct mapped_device *md = container_of(work, struct mapped_device,
3007 						work);
3008 	struct bio *c;
3009 	int srcu_idx;
3010 	struct dm_table *map;
3011 
3012 	map = dm_get_live_table(md, &srcu_idx);
3013 
3014 	while (!test_bit(DMF_BLOCK_IO_FOR_SUSPEND, &md->flags)) {
3015 		spin_lock_irq(&md->deferred_lock);
3016 		c = bio_list_pop(&md->deferred);
3017 		spin_unlock_irq(&md->deferred_lock);
3018 
3019 		if (!c)
3020 			break;
3021 
3022 		if (dm_request_based(md))
3023 			generic_make_request(c);
3024 		else
3025 			__split_and_process_bio(md, map, c);
3026 	}
3027 
3028 	dm_put_live_table(md, srcu_idx);
3029 }
3030 
3031 static void dm_queue_flush(struct mapped_device *md)
3032 {
3033 	clear_bit(DMF_BLOCK_IO_FOR_SUSPEND, &md->flags);
3034 	smp_mb__after_atomic();
3035 	queue_work(md->wq, &md->work);
3036 }
3037 
3038 /*
3039  * Swap in a new table, returning the old one for the caller to destroy.
3040  */
3041 struct dm_table *dm_swap_table(struct mapped_device *md, struct dm_table *table)
3042 {
3043 	struct dm_table *live_map = NULL, *map = ERR_PTR(-EINVAL);
3044 	struct queue_limits limits;
3045 	int r;
3046 
3047 	mutex_lock(&md->suspend_lock);
3048 
3049 	/* device must be suspended */
3050 	if (!dm_suspended_md(md))
3051 		goto out;
3052 
3053 	/*
3054 	 * If the new table has no data devices, retain the existing limits.
3055 	 * This helps multipath with queue_if_no_path if all paths disappear,
3056 	 * then new I/O is queued based on these limits, and then some paths
3057 	 * reappear.
3058 	 */
3059 	if (dm_table_has_no_data_devices(table)) {
3060 		live_map = dm_get_live_table_fast(md);
3061 		if (live_map)
3062 			limits = md->queue->limits;
3063 		dm_put_live_table_fast(md);
3064 	}
3065 
3066 	if (!live_map) {
3067 		r = dm_calculate_queue_limits(table, &limits);
3068 		if (r) {
3069 			map = ERR_PTR(r);
3070 			goto out;
3071 		}
3072 	}
3073 
3074 	map = __bind(md, table, &limits);
3075 
3076 out:
3077 	mutex_unlock(&md->suspend_lock);
3078 	return map;
3079 }
3080 
3081 /*
3082  * Functions to lock and unlock any filesystem running on the
3083  * device.
3084  */
3085 static int lock_fs(struct mapped_device *md)
3086 {
3087 	int r;
3088 
3089 	WARN_ON(md->frozen_sb);
3090 
3091 	md->frozen_sb = freeze_bdev(md->bdev);
3092 	if (IS_ERR(md->frozen_sb)) {
3093 		r = PTR_ERR(md->frozen_sb);
3094 		md->frozen_sb = NULL;
3095 		return r;
3096 	}
3097 
3098 	set_bit(DMF_FROZEN, &md->flags);
3099 
3100 	return 0;
3101 }
3102 
3103 static void unlock_fs(struct mapped_device *md)
3104 {
3105 	if (!test_bit(DMF_FROZEN, &md->flags))
3106 		return;
3107 
3108 	thaw_bdev(md->bdev, md->frozen_sb);
3109 	md->frozen_sb = NULL;
3110 	clear_bit(DMF_FROZEN, &md->flags);
3111 }
3112 
3113 /*
3114  * If __dm_suspend returns 0, the device is completely quiescent
3115  * now. There is no request-processing activity. All new requests
3116  * are being added to md->deferred list.
3117  *
3118  * Caller must hold md->suspend_lock
3119  */
3120 static int __dm_suspend(struct mapped_device *md, struct dm_table *map,
3121 			unsigned suspend_flags, int interruptible)
3122 {
3123 	bool do_lockfs = suspend_flags & DM_SUSPEND_LOCKFS_FLAG;
3124 	bool noflush = suspend_flags & DM_SUSPEND_NOFLUSH_FLAG;
3125 	int r;
3126 
3127 	/*
3128 	 * DMF_NOFLUSH_SUSPENDING must be set before presuspend.
3129 	 * This flag is cleared before dm_suspend returns.
3130 	 */
3131 	if (noflush)
3132 		set_bit(DMF_NOFLUSH_SUSPENDING, &md->flags);
3133 
3134 	/*
3135 	 * This gets reverted if there's an error later and the targets
3136 	 * provide the .presuspend_undo hook.
3137 	 */
3138 	dm_table_presuspend_targets(map);
3139 
3140 	/*
3141 	 * Flush I/O to the device.
3142 	 * Any I/O submitted after lock_fs() may not be flushed.
3143 	 * noflush takes precedence over do_lockfs.
3144 	 * (lock_fs() flushes I/Os and waits for them to complete.)
3145 	 */
3146 	if (!noflush && do_lockfs) {
3147 		r = lock_fs(md);
3148 		if (r) {
3149 			dm_table_presuspend_undo_targets(map);
3150 			return r;
3151 		}
3152 	}
3153 
3154 	/*
3155 	 * Here we must make sure that no processes are submitting requests
3156 	 * to target drivers i.e. no one may be executing
3157 	 * __split_and_process_bio. This is called from dm_request and
3158 	 * dm_wq_work.
3159 	 *
3160 	 * To get all processes out of __split_and_process_bio in dm_request,
3161 	 * we take the write lock. To prevent any process from reentering
3162 	 * __split_and_process_bio from dm_request and quiesce the thread
3163 	 * (dm_wq_work), we set BMF_BLOCK_IO_FOR_SUSPEND and call
3164 	 * flush_workqueue(md->wq).
3165 	 */
3166 	set_bit(DMF_BLOCK_IO_FOR_SUSPEND, &md->flags);
3167 	if (map)
3168 		synchronize_srcu(&md->io_barrier);
3169 
3170 	/*
3171 	 * Stop md->queue before flushing md->wq in case request-based
3172 	 * dm defers requests to md->wq from md->queue.
3173 	 */
3174 	if (dm_request_based(md)) {
3175 		dm_stop_queue(md->queue);
3176 		if (md->kworker_task)
3177 			flush_kthread_worker(&md->kworker);
3178 	}
3179 
3180 	flush_workqueue(md->wq);
3181 
3182 	/*
3183 	 * At this point no more requests are entering target request routines.
3184 	 * We call dm_wait_for_completion to wait for all existing requests
3185 	 * to finish.
3186 	 */
3187 	r = dm_wait_for_completion(md, interruptible);
3188 
3189 	if (noflush)
3190 		clear_bit(DMF_NOFLUSH_SUSPENDING, &md->flags);
3191 	if (map)
3192 		synchronize_srcu(&md->io_barrier);
3193 
3194 	/* were we interrupted ? */
3195 	if (r < 0) {
3196 		dm_queue_flush(md);
3197 
3198 		if (dm_request_based(md))
3199 			dm_start_queue(md->queue);
3200 
3201 		unlock_fs(md);
3202 		dm_table_presuspend_undo_targets(map);
3203 		/* pushback list is already flushed, so skip flush */
3204 	}
3205 
3206 	return r;
3207 }
3208 
3209 /*
3210  * We need to be able to change a mapping table under a mounted
3211  * filesystem.  For example we might want to move some data in
3212  * the background.  Before the table can be swapped with
3213  * dm_bind_table, dm_suspend must be called to flush any in
3214  * flight bios and ensure that any further io gets deferred.
3215  */
3216 /*
3217  * Suspend mechanism in request-based dm.
3218  *
3219  * 1. Flush all I/Os by lock_fs() if needed.
3220  * 2. Stop dispatching any I/O by stopping the request_queue.
3221  * 3. Wait for all in-flight I/Os to be completed or requeued.
3222  *
3223  * To abort suspend, start the request_queue.
3224  */
3225 int dm_suspend(struct mapped_device *md, unsigned suspend_flags)
3226 {
3227 	struct dm_table *map = NULL;
3228 	int r = 0;
3229 
3230 retry:
3231 	mutex_lock_nested(&md->suspend_lock, SINGLE_DEPTH_NESTING);
3232 
3233 	if (dm_suspended_md(md)) {
3234 		r = -EINVAL;
3235 		goto out_unlock;
3236 	}
3237 
3238 	if (dm_suspended_internally_md(md)) {
3239 		/* already internally suspended, wait for internal resume */
3240 		mutex_unlock(&md->suspend_lock);
3241 		r = wait_on_bit(&md->flags, DMF_SUSPENDED_INTERNALLY, TASK_INTERRUPTIBLE);
3242 		if (r)
3243 			return r;
3244 		goto retry;
3245 	}
3246 
3247 	map = rcu_dereference_protected(md->map, lockdep_is_held(&md->suspend_lock));
3248 
3249 	r = __dm_suspend(md, map, suspend_flags, TASK_INTERRUPTIBLE);
3250 	if (r)
3251 		goto out_unlock;
3252 
3253 	set_bit(DMF_SUSPENDED, &md->flags);
3254 
3255 	dm_table_postsuspend_targets(map);
3256 
3257 out_unlock:
3258 	mutex_unlock(&md->suspend_lock);
3259 	return r;
3260 }
3261 
3262 static int __dm_resume(struct mapped_device *md, struct dm_table *map)
3263 {
3264 	if (map) {
3265 		int r = dm_table_resume_targets(map);
3266 		if (r)
3267 			return r;
3268 	}
3269 
3270 	dm_queue_flush(md);
3271 
3272 	/*
3273 	 * Flushing deferred I/Os must be done after targets are resumed
3274 	 * so that mapping of targets can work correctly.
3275 	 * Request-based dm is queueing the deferred I/Os in its request_queue.
3276 	 */
3277 	if (dm_request_based(md))
3278 		dm_start_queue(md->queue);
3279 
3280 	unlock_fs(md);
3281 
3282 	return 0;
3283 }
3284 
3285 int dm_resume(struct mapped_device *md)
3286 {
3287 	int r = -EINVAL;
3288 	struct dm_table *map = NULL;
3289 
3290 retry:
3291 	mutex_lock_nested(&md->suspend_lock, SINGLE_DEPTH_NESTING);
3292 
3293 	if (!dm_suspended_md(md))
3294 		goto out;
3295 
3296 	if (dm_suspended_internally_md(md)) {
3297 		/* already internally suspended, wait for internal resume */
3298 		mutex_unlock(&md->suspend_lock);
3299 		r = wait_on_bit(&md->flags, DMF_SUSPENDED_INTERNALLY, TASK_INTERRUPTIBLE);
3300 		if (r)
3301 			return r;
3302 		goto retry;
3303 	}
3304 
3305 	map = rcu_dereference_protected(md->map, lockdep_is_held(&md->suspend_lock));
3306 	if (!map || !dm_table_get_size(map))
3307 		goto out;
3308 
3309 	r = __dm_resume(md, map);
3310 	if (r)
3311 		goto out;
3312 
3313 	clear_bit(DMF_SUSPENDED, &md->flags);
3314 
3315 	r = 0;
3316 out:
3317 	mutex_unlock(&md->suspend_lock);
3318 
3319 	return r;
3320 }
3321 
3322 /*
3323  * Internal suspend/resume works like userspace-driven suspend. It waits
3324  * until all bios finish and prevents issuing new bios to the target drivers.
3325  * It may be used only from the kernel.
3326  */
3327 
3328 static void __dm_internal_suspend(struct mapped_device *md, unsigned suspend_flags)
3329 {
3330 	struct dm_table *map = NULL;
3331 
3332 	if (md->internal_suspend_count++)
3333 		return; /* nested internal suspend */
3334 
3335 	if (dm_suspended_md(md)) {
3336 		set_bit(DMF_SUSPENDED_INTERNALLY, &md->flags);
3337 		return; /* nest suspend */
3338 	}
3339 
3340 	map = rcu_dereference_protected(md->map, lockdep_is_held(&md->suspend_lock));
3341 
3342 	/*
3343 	 * Using TASK_UNINTERRUPTIBLE because only NOFLUSH internal suspend is
3344 	 * supported.  Properly supporting a TASK_INTERRUPTIBLE internal suspend
3345 	 * would require changing .presuspend to return an error -- avoid this
3346 	 * until there is a need for more elaborate variants of internal suspend.
3347 	 */
3348 	(void) __dm_suspend(md, map, suspend_flags, TASK_UNINTERRUPTIBLE);
3349 
3350 	set_bit(DMF_SUSPENDED_INTERNALLY, &md->flags);
3351 
3352 	dm_table_postsuspend_targets(map);
3353 }
3354 
3355 static void __dm_internal_resume(struct mapped_device *md)
3356 {
3357 	BUG_ON(!md->internal_suspend_count);
3358 
3359 	if (--md->internal_suspend_count)
3360 		return; /* resume from nested internal suspend */
3361 
3362 	if (dm_suspended_md(md))
3363 		goto done; /* resume from nested suspend */
3364 
3365 	/*
3366 	 * NOTE: existing callers don't need to call dm_table_resume_targets
3367 	 * (which may fail -- so best to avoid it for now by passing NULL map)
3368 	 */
3369 	(void) __dm_resume(md, NULL);
3370 
3371 done:
3372 	clear_bit(DMF_SUSPENDED_INTERNALLY, &md->flags);
3373 	smp_mb__after_atomic();
3374 	wake_up_bit(&md->flags, DMF_SUSPENDED_INTERNALLY);
3375 }
3376 
3377 void dm_internal_suspend_noflush(struct mapped_device *md)
3378 {
3379 	mutex_lock(&md->suspend_lock);
3380 	__dm_internal_suspend(md, DM_SUSPEND_NOFLUSH_FLAG);
3381 	mutex_unlock(&md->suspend_lock);
3382 }
3383 EXPORT_SYMBOL_GPL(dm_internal_suspend_noflush);
3384 
3385 void dm_internal_resume(struct mapped_device *md)
3386 {
3387 	mutex_lock(&md->suspend_lock);
3388 	__dm_internal_resume(md);
3389 	mutex_unlock(&md->suspend_lock);
3390 }
3391 EXPORT_SYMBOL_GPL(dm_internal_resume);
3392 
3393 /*
3394  * Fast variants of internal suspend/resume hold md->suspend_lock,
3395  * which prevents interaction with userspace-driven suspend.
3396  */
3397 
3398 void dm_internal_suspend_fast(struct mapped_device *md)
3399 {
3400 	mutex_lock(&md->suspend_lock);
3401 	if (dm_suspended_md(md) || dm_suspended_internally_md(md))
3402 		return;
3403 
3404 	set_bit(DMF_BLOCK_IO_FOR_SUSPEND, &md->flags);
3405 	synchronize_srcu(&md->io_barrier);
3406 	flush_workqueue(md->wq);
3407 	dm_wait_for_completion(md, TASK_UNINTERRUPTIBLE);
3408 }
3409 EXPORT_SYMBOL_GPL(dm_internal_suspend_fast);
3410 
3411 void dm_internal_resume_fast(struct mapped_device *md)
3412 {
3413 	if (dm_suspended_md(md) || dm_suspended_internally_md(md))
3414 		goto done;
3415 
3416 	dm_queue_flush(md);
3417 
3418 done:
3419 	mutex_unlock(&md->suspend_lock);
3420 }
3421 EXPORT_SYMBOL_GPL(dm_internal_resume_fast);
3422 
3423 /*-----------------------------------------------------------------
3424  * Event notification.
3425  *---------------------------------------------------------------*/
3426 int dm_kobject_uevent(struct mapped_device *md, enum kobject_action action,
3427 		       unsigned cookie)
3428 {
3429 	char udev_cookie[DM_COOKIE_LENGTH];
3430 	char *envp[] = { udev_cookie, NULL };
3431 
3432 	if (!cookie)
3433 		return kobject_uevent(&disk_to_dev(md->disk)->kobj, action);
3434 	else {
3435 		snprintf(udev_cookie, DM_COOKIE_LENGTH, "%s=%u",
3436 			 DM_COOKIE_ENV_VAR_NAME, cookie);
3437 		return kobject_uevent_env(&disk_to_dev(md->disk)->kobj,
3438 					  action, envp);
3439 	}
3440 }
3441 
3442 uint32_t dm_next_uevent_seq(struct mapped_device *md)
3443 {
3444 	return atomic_add_return(1, &md->uevent_seq);
3445 }
3446 
3447 uint32_t dm_get_event_nr(struct mapped_device *md)
3448 {
3449 	return atomic_read(&md->event_nr);
3450 }
3451 
3452 int dm_wait_event(struct mapped_device *md, int event_nr)
3453 {
3454 	return wait_event_interruptible(md->eventq,
3455 			(event_nr != atomic_read(&md->event_nr)));
3456 }
3457 
3458 void dm_uevent_add(struct mapped_device *md, struct list_head *elist)
3459 {
3460 	unsigned long flags;
3461 
3462 	spin_lock_irqsave(&md->uevent_lock, flags);
3463 	list_add(elist, &md->uevent_list);
3464 	spin_unlock_irqrestore(&md->uevent_lock, flags);
3465 }
3466 
3467 /*
3468  * The gendisk is only valid as long as you have a reference
3469  * count on 'md'.
3470  */
3471 struct gendisk *dm_disk(struct mapped_device *md)
3472 {
3473 	return md->disk;
3474 }
3475 EXPORT_SYMBOL_GPL(dm_disk);
3476 
3477 struct kobject *dm_kobject(struct mapped_device *md)
3478 {
3479 	return &md->kobj_holder.kobj;
3480 }
3481 
3482 struct mapped_device *dm_get_from_kobject(struct kobject *kobj)
3483 {
3484 	struct mapped_device *md;
3485 
3486 	md = container_of(kobj, struct mapped_device, kobj_holder.kobj);
3487 
3488 	if (test_bit(DMF_FREEING, &md->flags) ||
3489 	    dm_deleting_md(md))
3490 		return NULL;
3491 
3492 	dm_get(md);
3493 	return md;
3494 }
3495 
3496 int dm_suspended_md(struct mapped_device *md)
3497 {
3498 	return test_bit(DMF_SUSPENDED, &md->flags);
3499 }
3500 
3501 int dm_suspended_internally_md(struct mapped_device *md)
3502 {
3503 	return test_bit(DMF_SUSPENDED_INTERNALLY, &md->flags);
3504 }
3505 
3506 int dm_test_deferred_remove_flag(struct mapped_device *md)
3507 {
3508 	return test_bit(DMF_DEFERRED_REMOVE, &md->flags);
3509 }
3510 
3511 int dm_suspended(struct dm_target *ti)
3512 {
3513 	return dm_suspended_md(dm_table_get_md(ti->table));
3514 }
3515 EXPORT_SYMBOL_GPL(dm_suspended);
3516 
3517 int dm_noflush_suspending(struct dm_target *ti)
3518 {
3519 	return __noflush_suspending(dm_table_get_md(ti->table));
3520 }
3521 EXPORT_SYMBOL_GPL(dm_noflush_suspending);
3522 
3523 struct dm_md_mempools *dm_alloc_md_mempools(struct mapped_device *md, unsigned type,
3524 					    unsigned integrity, unsigned per_io_data_size)
3525 {
3526 	struct dm_md_mempools *pools = kzalloc_node(sizeof(*pools), GFP_KERNEL, md->numa_node_id);
3527 	struct kmem_cache *cachep = NULL;
3528 	unsigned int pool_size = 0;
3529 	unsigned int front_pad;
3530 
3531 	if (!pools)
3532 		return NULL;
3533 
3534 	type = filter_md_type(type, md);
3535 
3536 	switch (type) {
3537 	case DM_TYPE_BIO_BASED:
3538 		cachep = _io_cache;
3539 		pool_size = dm_get_reserved_bio_based_ios();
3540 		front_pad = roundup(per_io_data_size, __alignof__(struct dm_target_io)) + offsetof(struct dm_target_io, clone);
3541 		break;
3542 	case DM_TYPE_REQUEST_BASED:
3543 		cachep = _rq_tio_cache;
3544 		pool_size = dm_get_reserved_rq_based_ios();
3545 		pools->rq_pool = mempool_create_slab_pool(pool_size, _rq_cache);
3546 		if (!pools->rq_pool)
3547 			goto out;
3548 		/* fall through to setup remaining rq-based pools */
3549 	case DM_TYPE_MQ_REQUEST_BASED:
3550 		if (!pool_size)
3551 			pool_size = dm_get_reserved_rq_based_ios();
3552 		front_pad = offsetof(struct dm_rq_clone_bio_info, clone);
3553 		/* per_io_data_size is used for blk-mq pdu at queue allocation */
3554 		break;
3555 	default:
3556 		BUG();
3557 	}
3558 
3559 	if (cachep) {
3560 		pools->io_pool = mempool_create_slab_pool(pool_size, cachep);
3561 		if (!pools->io_pool)
3562 			goto out;
3563 	}
3564 
3565 	pools->bs = bioset_create_nobvec(pool_size, front_pad);
3566 	if (!pools->bs)
3567 		goto out;
3568 
3569 	if (integrity && bioset_integrity_create(pools->bs, pool_size))
3570 		goto out;
3571 
3572 	return pools;
3573 
3574 out:
3575 	dm_free_md_mempools(pools);
3576 
3577 	return NULL;
3578 }
3579 
3580 void dm_free_md_mempools(struct dm_md_mempools *pools)
3581 {
3582 	if (!pools)
3583 		return;
3584 
3585 	mempool_destroy(pools->io_pool);
3586 	mempool_destroy(pools->rq_pool);
3587 
3588 	if (pools->bs)
3589 		bioset_free(pools->bs);
3590 
3591 	kfree(pools);
3592 }
3593 
3594 static int dm_pr_register(struct block_device *bdev, u64 old_key, u64 new_key,
3595 			  u32 flags)
3596 {
3597 	struct mapped_device *md = bdev->bd_disk->private_data;
3598 	const struct pr_ops *ops;
3599 	fmode_t mode;
3600 	int r;
3601 
3602 	r = dm_grab_bdev_for_ioctl(md, &bdev, &mode);
3603 	if (r < 0)
3604 		return r;
3605 
3606 	ops = bdev->bd_disk->fops->pr_ops;
3607 	if (ops && ops->pr_register)
3608 		r = ops->pr_register(bdev, old_key, new_key, flags);
3609 	else
3610 		r = -EOPNOTSUPP;
3611 
3612 	bdput(bdev);
3613 	return r;
3614 }
3615 
3616 static int dm_pr_reserve(struct block_device *bdev, u64 key, enum pr_type type,
3617 			 u32 flags)
3618 {
3619 	struct mapped_device *md = bdev->bd_disk->private_data;
3620 	const struct pr_ops *ops;
3621 	fmode_t mode;
3622 	int r;
3623 
3624 	r = dm_grab_bdev_for_ioctl(md, &bdev, &mode);
3625 	if (r < 0)
3626 		return r;
3627 
3628 	ops = bdev->bd_disk->fops->pr_ops;
3629 	if (ops && ops->pr_reserve)
3630 		r = ops->pr_reserve(bdev, key, type, flags);
3631 	else
3632 		r = -EOPNOTSUPP;
3633 
3634 	bdput(bdev);
3635 	return r;
3636 }
3637 
3638 static int dm_pr_release(struct block_device *bdev, u64 key, enum pr_type type)
3639 {
3640 	struct mapped_device *md = bdev->bd_disk->private_data;
3641 	const struct pr_ops *ops;
3642 	fmode_t mode;
3643 	int r;
3644 
3645 	r = dm_grab_bdev_for_ioctl(md, &bdev, &mode);
3646 	if (r < 0)
3647 		return r;
3648 
3649 	ops = bdev->bd_disk->fops->pr_ops;
3650 	if (ops && ops->pr_release)
3651 		r = ops->pr_release(bdev, key, type);
3652 	else
3653 		r = -EOPNOTSUPP;
3654 
3655 	bdput(bdev);
3656 	return r;
3657 }
3658 
3659 static int dm_pr_preempt(struct block_device *bdev, u64 old_key, u64 new_key,
3660 			 enum pr_type type, bool abort)
3661 {
3662 	struct mapped_device *md = bdev->bd_disk->private_data;
3663 	const struct pr_ops *ops;
3664 	fmode_t mode;
3665 	int r;
3666 
3667 	r = dm_grab_bdev_for_ioctl(md, &bdev, &mode);
3668 	if (r < 0)
3669 		return r;
3670 
3671 	ops = bdev->bd_disk->fops->pr_ops;
3672 	if (ops && ops->pr_preempt)
3673 		r = ops->pr_preempt(bdev, old_key, new_key, type, abort);
3674 	else
3675 		r = -EOPNOTSUPP;
3676 
3677 	bdput(bdev);
3678 	return r;
3679 }
3680 
3681 static int dm_pr_clear(struct block_device *bdev, u64 key)
3682 {
3683 	struct mapped_device *md = bdev->bd_disk->private_data;
3684 	const struct pr_ops *ops;
3685 	fmode_t mode;
3686 	int r;
3687 
3688 	r = dm_grab_bdev_for_ioctl(md, &bdev, &mode);
3689 	if (r < 0)
3690 		return r;
3691 
3692 	ops = bdev->bd_disk->fops->pr_ops;
3693 	if (ops && ops->pr_clear)
3694 		r = ops->pr_clear(bdev, key);
3695 	else
3696 		r = -EOPNOTSUPP;
3697 
3698 	bdput(bdev);
3699 	return r;
3700 }
3701 
3702 static const struct pr_ops dm_pr_ops = {
3703 	.pr_register	= dm_pr_register,
3704 	.pr_reserve	= dm_pr_reserve,
3705 	.pr_release	= dm_pr_release,
3706 	.pr_preempt	= dm_pr_preempt,
3707 	.pr_clear	= dm_pr_clear,
3708 };
3709 
3710 static const struct block_device_operations dm_blk_dops = {
3711 	.open = dm_blk_open,
3712 	.release = dm_blk_close,
3713 	.ioctl = dm_blk_ioctl,
3714 	.getgeo = dm_blk_getgeo,
3715 	.pr_ops = &dm_pr_ops,
3716 	.owner = THIS_MODULE
3717 };
3718 
3719 /*
3720  * module hooks
3721  */
3722 module_init(dm_init);
3723 module_exit(dm_exit);
3724 
3725 module_param(major, uint, 0);
3726 MODULE_PARM_DESC(major, "The major number of the device mapper");
3727 
3728 module_param(reserved_bio_based_ios, uint, S_IRUGO | S_IWUSR);
3729 MODULE_PARM_DESC(reserved_bio_based_ios, "Reserved IOs in bio-based mempools");
3730 
3731 module_param(reserved_rq_based_ios, uint, S_IRUGO | S_IWUSR);
3732 MODULE_PARM_DESC(reserved_rq_based_ios, "Reserved IOs in request-based mempools");
3733 
3734 module_param(use_blk_mq, bool, S_IRUGO | S_IWUSR);
3735 MODULE_PARM_DESC(use_blk_mq, "Use block multiqueue for request-based DM devices");
3736 
3737 module_param(dm_mq_nr_hw_queues, uint, S_IRUGO | S_IWUSR);
3738 MODULE_PARM_DESC(dm_mq_nr_hw_queues, "Number of hardware queues for request-based dm-mq devices");
3739 
3740 module_param(dm_mq_queue_depth, uint, S_IRUGO | S_IWUSR);
3741 MODULE_PARM_DESC(dm_mq_queue_depth, "Queue depth for request-based dm-mq devices");
3742 
3743 module_param(dm_numa_node, int, S_IRUGO | S_IWUSR);
3744 MODULE_PARM_DESC(dm_numa_node, "NUMA node for DM device memory allocations");
3745 
3746 MODULE_DESCRIPTION(DM_NAME " driver");
3747 MODULE_AUTHOR("Joe Thornber <dm-devel@redhat.com>");
3748 MODULE_LICENSE("GPL");
3749