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