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