xref: /linux/drivers/md/dm-cache-target.c (revision 570f7e331f5febb30f1384817463c7e42b65ca7d)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright (C) 2012 Red Hat. All rights reserved.
4  *
5  * This file is released under the GPL.
6  */
7 
8 #include "dm.h"
9 #include "dm-bio-prison-v2.h"
10 #include "dm-bio-record.h"
11 #include "dm-cache-metadata.h"
12 #include "dm-io-tracker.h"
13 #include "dm-cache-background-tracker.h"
14 
15 #include <linux/dm-io.h>
16 #include <linux/dm-kcopyd.h>
17 #include <linux/jiffies.h>
18 #include <linux/init.h>
19 #include <linux/kstrtox.h>
20 #include <linux/mempool.h>
21 #include <linux/module.h>
22 #include <linux/rwsem.h>
23 #include <linux/slab.h>
24 #include <linux/vmalloc.h>
25 
26 #define DM_MSG_PREFIX "cache"
27 
28 DECLARE_DM_KCOPYD_THROTTLE_WITH_MODULE_PARM(cache_copy_throttle,
29 	"A percentage of time allocated for copying to and/or from cache");
30 
31 /*----------------------------------------------------------------*/
32 
33 /*
34  * Glossary:
35  *
36  * oblock: index of an origin block
37  * cblock: index of a cache block
38  * promotion: movement of a block from origin to cache
39  * demotion: movement of a block from cache to origin
40  * migration: movement of a block between the origin and cache device,
41  *	      either direction
42  */
43 
44 /*----------------------------------------------------------------*/
45 
46 /*
47  * Represents a chunk of future work.  'input' allows continuations to pass
48  * values between themselves, typically error values.
49  */
50 struct continuation {
51 	struct work_struct ws;
52 	blk_status_t input;
53 };
54 
55 static inline void init_continuation(struct continuation *k,
56 				     void (*fn)(struct work_struct *))
57 {
58 	INIT_WORK(&k->ws, fn);
59 	k->input = 0;
60 }
61 
62 static inline void queue_continuation(struct workqueue_struct *wq,
63 				      struct continuation *k)
64 {
65 	queue_work(wq, &k->ws);
66 }
67 
68 /*----------------------------------------------------------------*/
69 
70 /*
71  * The batcher collects together pieces of work that need a particular
72  * operation to occur before they can proceed (typically a commit).
73  */
74 struct batcher {
75 	/*
76 	 * The operation that everyone is waiting for.
77 	 */
78 	blk_status_t (*commit_op)(void *context);
79 	void *commit_context;
80 
81 	/*
82 	 * This is how bios should be issued once the commit op is complete
83 	 * (accounted_request).
84 	 */
85 	void (*issue_op)(struct bio *bio, void *context);
86 	void *issue_context;
87 
88 	/*
89 	 * Queued work gets put on here after commit.
90 	 */
91 	struct workqueue_struct *wq;
92 
93 	spinlock_t lock;
94 	struct list_head work_items;
95 	struct bio_list bios;
96 	struct work_struct commit_work;
97 
98 	bool commit_scheduled;
99 };
100 
101 static void __commit(struct work_struct *_ws)
102 {
103 	struct batcher *b = container_of(_ws, struct batcher, commit_work);
104 	blk_status_t r;
105 	struct list_head work_items;
106 	struct work_struct *ws, *tmp;
107 	struct continuation *k;
108 	struct bio *bio;
109 	struct bio_list bios;
110 
111 	INIT_LIST_HEAD(&work_items);
112 	bio_list_init(&bios);
113 
114 	/*
115 	 * We have to grab these before the commit_op to avoid a race
116 	 * condition.
117 	 */
118 	spin_lock_irq(&b->lock);
119 	list_splice_init(&b->work_items, &work_items);
120 	bio_list_merge_init(&bios, &b->bios);
121 	b->commit_scheduled = false;
122 	spin_unlock_irq(&b->lock);
123 
124 	r = b->commit_op(b->commit_context);
125 
126 	list_for_each_entry_safe(ws, tmp, &work_items, entry) {
127 		k = container_of(ws, struct continuation, ws);
128 		k->input = r;
129 		INIT_LIST_HEAD(&ws->entry); /* to avoid a WARN_ON */
130 		queue_work(b->wq, ws);
131 	}
132 
133 	while ((bio = bio_list_pop(&bios))) {
134 		if (r) {
135 			bio->bi_status = r;
136 			bio_endio(bio);
137 		} else
138 			b->issue_op(bio, b->issue_context);
139 	}
140 }
141 
142 static void batcher_init(struct batcher *b,
143 			 blk_status_t (*commit_op)(void *),
144 			 void *commit_context,
145 			 void (*issue_op)(struct bio *bio, void *),
146 			 void *issue_context,
147 			 struct workqueue_struct *wq)
148 {
149 	b->commit_op = commit_op;
150 	b->commit_context = commit_context;
151 	b->issue_op = issue_op;
152 	b->issue_context = issue_context;
153 	b->wq = wq;
154 
155 	spin_lock_init(&b->lock);
156 	INIT_LIST_HEAD(&b->work_items);
157 	bio_list_init(&b->bios);
158 	INIT_WORK(&b->commit_work, __commit);
159 	b->commit_scheduled = false;
160 }
161 
162 static void async_commit(struct batcher *b)
163 {
164 	queue_work(b->wq, &b->commit_work);
165 }
166 
167 static void continue_after_commit(struct batcher *b, struct continuation *k)
168 {
169 	bool commit_scheduled;
170 
171 	spin_lock_irq(&b->lock);
172 	commit_scheduled = b->commit_scheduled;
173 	list_add_tail(&k->ws.entry, &b->work_items);
174 	spin_unlock_irq(&b->lock);
175 
176 	if (commit_scheduled)
177 		async_commit(b);
178 }
179 
180 /*
181  * Bios are errored if commit failed.
182  */
183 static void issue_after_commit(struct batcher *b, struct bio *bio)
184 {
185 	bool commit_scheduled;
186 
187 	spin_lock_irq(&b->lock);
188 	commit_scheduled = b->commit_scheduled;
189 	bio_list_add(&b->bios, bio);
190 	spin_unlock_irq(&b->lock);
191 
192 	if (commit_scheduled)
193 		async_commit(b);
194 }
195 
196 /*
197  * Call this if some urgent work is waiting for the commit to complete.
198  */
199 static void schedule_commit(struct batcher *b)
200 {
201 	bool immediate;
202 
203 	spin_lock_irq(&b->lock);
204 	immediate = !list_empty(&b->work_items) || !bio_list_empty(&b->bios);
205 	b->commit_scheduled = true;
206 	spin_unlock_irq(&b->lock);
207 
208 	if (immediate)
209 		async_commit(b);
210 }
211 
212 /*
213  * There are a couple of places where we let a bio run, but want to do some
214  * work before calling its endio function.  We do this by temporarily
215  * changing the endio fn.
216  */
217 struct dm_hook_info {
218 	bio_end_io_t *bi_end_io;
219 };
220 
221 static void dm_hook_bio(struct dm_hook_info *h, struct bio *bio,
222 			bio_end_io_t *bi_end_io, void *bi_private)
223 {
224 	h->bi_end_io = bio->bi_end_io;
225 
226 	bio->bi_end_io = bi_end_io;
227 	bio->bi_private = bi_private;
228 }
229 
230 static void dm_unhook_bio(struct dm_hook_info *h, struct bio *bio)
231 {
232 	bio->bi_end_io = h->bi_end_io;
233 }
234 
235 /*----------------------------------------------------------------*/
236 
237 #define MIGRATION_POOL_SIZE 128
238 #define COMMIT_PERIOD HZ
239 #define MIGRATION_COUNT_WINDOW 10
240 
241 /*
242  * The block size of the device holding cache data must be
243  * between 32KB and 1GB.
244  */
245 #define DATA_DEV_BLOCK_SIZE_MIN_SECTORS (32 * 1024 >> SECTOR_SHIFT)
246 #define DATA_DEV_BLOCK_SIZE_MAX_SECTORS (1024 * 1024 * 1024 >> SECTOR_SHIFT)
247 
248 enum cache_metadata_mode {
249 	CM_WRITE,		/* metadata may be changed */
250 	CM_READ_ONLY,		/* metadata may not be changed */
251 	CM_FAIL
252 };
253 
254 enum cache_io_mode {
255 	/*
256 	 * Data is written to cached blocks only.  These blocks are marked
257 	 * dirty.  If you lose the cache device you will lose data.
258 	 * Potential performance increase for both reads and writes.
259 	 */
260 	CM_IO_WRITEBACK,
261 
262 	/*
263 	 * Data is written to both cache and origin.  Blocks are never
264 	 * dirty.  Potential performance benfit for reads only.
265 	 */
266 	CM_IO_WRITETHROUGH,
267 
268 	/*
269 	 * A degraded mode useful for various cache coherency situations
270 	 * (eg, rolling back snapshots).  Reads and writes always go to the
271 	 * origin.  If a write goes to a cached oblock, then the cache
272 	 * block is invalidated.
273 	 */
274 	CM_IO_PASSTHROUGH
275 };
276 
277 struct cache_features {
278 	enum cache_metadata_mode mode;
279 	enum cache_io_mode io_mode;
280 	unsigned int metadata_version;
281 	bool discard_passdown:1;
282 };
283 
284 struct cache_stats {
285 	atomic_t read_hit;
286 	atomic_t read_miss;
287 	atomic_t write_hit;
288 	atomic_t write_miss;
289 	atomic_t demotion;
290 	atomic_t promotion;
291 	atomic_t writeback;
292 	atomic_t copies_avoided;
293 	atomic_t cache_cell_clash;
294 	atomic_t commit_count;
295 	atomic_t discard_count;
296 };
297 
298 struct cache {
299 	struct dm_target *ti;
300 	spinlock_t lock;
301 
302 	/*
303 	 * Fields for converting from sectors to blocks.
304 	 */
305 	int sectors_per_block_shift;
306 	sector_t sectors_per_block;
307 
308 	struct dm_cache_metadata *cmd;
309 
310 	/*
311 	 * Metadata is written to this device.
312 	 */
313 	struct dm_dev *metadata_dev;
314 
315 	/*
316 	 * The slower of the two data devices.  Typically a spindle.
317 	 */
318 	struct dm_dev *origin_dev;
319 
320 	/*
321 	 * The faster of the two data devices.  Typically an SSD.
322 	 */
323 	struct dm_dev *cache_dev;
324 
325 	/*
326 	 * Size of the origin device in _complete_ blocks and native sectors.
327 	 */
328 	dm_oblock_t origin_blocks;
329 	sector_t origin_sectors;
330 
331 	/*
332 	 * Size of the cache device in blocks.
333 	 */
334 	dm_cblock_t cache_size;
335 
336 	/*
337 	 * Invalidation fields.
338 	 */
339 	spinlock_t invalidation_lock;
340 	struct list_head invalidation_requests;
341 
342 	sector_t migration_threshold;
343 	wait_queue_head_t migration_wait;
344 	atomic_t nr_allocated_migrations;
345 
346 	/*
347 	 * The number of in flight migrations that are performing
348 	 * background io. eg, promotion, writeback.
349 	 */
350 	atomic_t nr_io_migrations;
351 
352 	struct bio_list deferred_bios;
353 
354 	struct rw_semaphore quiesce_lock;
355 
356 	/*
357 	 * origin_blocks entries, discarded if set.
358 	 */
359 	dm_dblock_t discard_nr_blocks;
360 	unsigned long *discard_bitset;
361 	uint32_t discard_block_size; /* a power of 2 times sectors per block */
362 
363 	/*
364 	 * Rather than reconstructing the table line for the status we just
365 	 * save it and regurgitate.
366 	 */
367 	unsigned int nr_ctr_args;
368 	const char **ctr_args;
369 
370 	struct dm_kcopyd_client *copier;
371 	struct work_struct deferred_bio_worker;
372 	struct work_struct migration_worker;
373 	struct workqueue_struct *wq;
374 	struct delayed_work waker;
375 	struct dm_bio_prison_v2 *prison;
376 
377 	/*
378 	 * cache_size entries, dirty if set
379 	 */
380 	unsigned long *dirty_bitset;
381 	atomic_t nr_dirty;
382 
383 	unsigned int policy_nr_args;
384 	struct dm_cache_policy *policy;
385 
386 	/*
387 	 * Cache features such as write-through.
388 	 */
389 	struct cache_features features;
390 
391 	struct cache_stats stats;
392 
393 	bool need_tick_bio:1;
394 	bool sized:1;
395 	bool invalidate:1;
396 	bool commit_requested:1;
397 	bool loaded_mappings:1;
398 	bool loaded_discards:1;
399 
400 	struct rw_semaphore background_work_lock;
401 
402 	struct batcher committer;
403 	struct work_struct commit_ws;
404 
405 	struct dm_io_tracker tracker;
406 
407 	mempool_t migration_pool;
408 
409 	struct bio_set bs;
410 
411 	/*
412 	 * Cache_size entries. Set bits indicate blocks mapped beyond the
413 	 * target length, which are marked for invalidation.
414 	 */
415 	unsigned long *invalid_bitset;
416 };
417 
418 struct per_bio_data {
419 	bool tick:1;
420 	unsigned int req_nr:2;
421 	struct dm_bio_prison_cell_v2 *cell;
422 	struct dm_hook_info hook_info;
423 	sector_t len;
424 };
425 
426 struct dm_cache_migration {
427 	struct continuation k;
428 	struct cache *cache;
429 
430 	struct policy_work *op;
431 	struct bio *overwrite_bio;
432 	struct dm_bio_prison_cell_v2 *cell;
433 
434 	dm_cblock_t invalidate_cblock;
435 	dm_oblock_t invalidate_oblock;
436 };
437 
438 /*----------------------------------------------------------------*/
439 
440 static bool writethrough_mode(struct cache *cache)
441 {
442 	return cache->features.io_mode == CM_IO_WRITETHROUGH;
443 }
444 
445 static bool writeback_mode(struct cache *cache)
446 {
447 	return cache->features.io_mode == CM_IO_WRITEBACK;
448 }
449 
450 static inline bool passthrough_mode(struct cache *cache)
451 {
452 	return unlikely(cache->features.io_mode == CM_IO_PASSTHROUGH);
453 }
454 
455 /*----------------------------------------------------------------*/
456 
457 static void wake_deferred_bio_worker(struct cache *cache)
458 {
459 	queue_work(cache->wq, &cache->deferred_bio_worker);
460 }
461 
462 static void wake_migration_worker(struct cache *cache)
463 {
464 	if (passthrough_mode(cache))
465 		return;
466 
467 	queue_work(cache->wq, &cache->migration_worker);
468 }
469 
470 /*----------------------------------------------------------------*/
471 
472 static struct dm_bio_prison_cell_v2 *alloc_prison_cell(struct cache *cache)
473 {
474 	return dm_bio_prison_alloc_cell_v2(cache->prison, GFP_NOIO);
475 }
476 
477 static void free_prison_cell(struct cache *cache, struct dm_bio_prison_cell_v2 *cell)
478 {
479 	dm_bio_prison_free_cell_v2(cache->prison, cell);
480 }
481 
482 static struct dm_cache_migration *alloc_migration(struct cache *cache)
483 {
484 	struct dm_cache_migration *mg;
485 
486 	mg = mempool_alloc(&cache->migration_pool, GFP_NOIO);
487 
488 	memset(mg, 0, sizeof(*mg));
489 
490 	mg->cache = cache;
491 	atomic_inc(&cache->nr_allocated_migrations);
492 
493 	return mg;
494 }
495 
496 static void free_migration(struct dm_cache_migration *mg)
497 {
498 	struct cache *cache = mg->cache;
499 
500 	if (atomic_dec_and_test(&cache->nr_allocated_migrations))
501 		wake_up(&cache->migration_wait);
502 
503 	mempool_free(mg, &cache->migration_pool);
504 }
505 
506 /*----------------------------------------------------------------*/
507 
508 static inline dm_oblock_t oblock_succ(dm_oblock_t b)
509 {
510 	return to_oblock(from_oblock(b) + 1ull);
511 }
512 
513 static void build_key(dm_oblock_t begin, dm_oblock_t end, struct dm_cell_key_v2 *key)
514 {
515 	key->virtual = 0;
516 	key->dev = 0;
517 	key->block_begin = from_oblock(begin);
518 	key->block_end = from_oblock(end);
519 }
520 
521 /*
522  * We have two lock levels.  Level 0, which is used to prevent WRITEs, and
523  * level 1 which prevents *both* READs and WRITEs.
524  */
525 #define WRITE_LOCK_LEVEL 0
526 #define READ_WRITE_LOCK_LEVEL 1
527 
528 static unsigned int lock_level(struct bio *bio)
529 {
530 	return bio_data_dir(bio) == WRITE ?
531 		WRITE_LOCK_LEVEL :
532 		READ_WRITE_LOCK_LEVEL;
533 }
534 
535 /*
536  *--------------------------------------------------------------
537  * Per bio data
538  *--------------------------------------------------------------
539  */
540 
541 static struct per_bio_data *get_per_bio_data(struct bio *bio)
542 {
543 	struct per_bio_data *pb = dm_per_bio_data(bio, sizeof(struct per_bio_data));
544 
545 	BUG_ON(!pb);
546 	return pb;
547 }
548 
549 static struct per_bio_data *init_per_bio_data(struct bio *bio)
550 {
551 	struct per_bio_data *pb = get_per_bio_data(bio);
552 
553 	pb->tick = false;
554 	pb->req_nr = dm_bio_get_target_bio_nr(bio);
555 	pb->cell = NULL;
556 	pb->len = 0;
557 
558 	return pb;
559 }
560 
561 /*----------------------------------------------------------------*/
562 
563 static void defer_bio(struct cache *cache, struct bio *bio)
564 {
565 	spin_lock_irq(&cache->lock);
566 	bio_list_add(&cache->deferred_bios, bio);
567 	spin_unlock_irq(&cache->lock);
568 
569 	wake_deferred_bio_worker(cache);
570 }
571 
572 static void defer_bios(struct cache *cache, struct bio_list *bios)
573 {
574 	spin_lock_irq(&cache->lock);
575 	bio_list_merge_init(&cache->deferred_bios, bios);
576 	spin_unlock_irq(&cache->lock);
577 
578 	wake_deferred_bio_worker(cache);
579 }
580 
581 /*----------------------------------------------------------------*/
582 
583 static bool bio_detain_shared(struct cache *cache, dm_oblock_t oblock, struct bio *bio)
584 {
585 	bool r;
586 	struct per_bio_data *pb;
587 	struct dm_cell_key_v2 key;
588 	dm_oblock_t end = to_oblock(from_oblock(oblock) + 1ULL);
589 	struct dm_bio_prison_cell_v2 *cell_prealloc, *cell;
590 
591 	cell_prealloc = alloc_prison_cell(cache); /* FIXME: allow wait if calling from worker */
592 
593 	build_key(oblock, end, &key);
594 	r = dm_cell_get_v2(cache->prison, &key, lock_level(bio), bio, cell_prealloc, &cell);
595 	if (!r) {
596 		/*
597 		 * Failed to get the lock.
598 		 */
599 		free_prison_cell(cache, cell_prealloc);
600 		return r;
601 	}
602 
603 	if (cell != cell_prealloc)
604 		free_prison_cell(cache, cell_prealloc);
605 
606 	pb = get_per_bio_data(bio);
607 	pb->cell = cell;
608 
609 	return r;
610 }
611 
612 /*----------------------------------------------------------------*/
613 
614 static bool is_dirty(struct cache *cache, dm_cblock_t b)
615 {
616 	return test_bit(from_cblock(b), cache->dirty_bitset);
617 }
618 
619 static void set_dirty(struct cache *cache, dm_cblock_t cblock)
620 {
621 	if (!test_and_set_bit(from_cblock(cblock), cache->dirty_bitset)) {
622 		atomic_inc(&cache->nr_dirty);
623 		policy_set_dirty(cache->policy, cblock);
624 	}
625 }
626 
627 /*
628  * These two are called when setting after migrations to force the policy
629  * and dirty bitset to be in sync.
630  */
631 static void force_set_dirty(struct cache *cache, dm_cblock_t cblock)
632 {
633 	if (!test_and_set_bit(from_cblock(cblock), cache->dirty_bitset))
634 		atomic_inc(&cache->nr_dirty);
635 	policy_set_dirty(cache->policy, cblock);
636 }
637 
638 static void force_clear_dirty(struct cache *cache, dm_cblock_t cblock)
639 {
640 	if (test_and_clear_bit(from_cblock(cblock), cache->dirty_bitset)) {
641 		if (atomic_dec_return(&cache->nr_dirty) == 0)
642 			dm_table_event(cache->ti->table);
643 	}
644 
645 	policy_clear_dirty(cache->policy, cblock);
646 }
647 
648 /*----------------------------------------------------------------*/
649 
650 static bool block_size_is_power_of_two(struct cache *cache)
651 {
652 	return cache->sectors_per_block_shift >= 0;
653 }
654 
655 static dm_block_t block_div(dm_block_t b, uint32_t n)
656 {
657 	do_div(b, n);
658 
659 	return b;
660 }
661 
662 static dm_block_t oblocks_per_dblock(struct cache *cache)
663 {
664 	dm_block_t oblocks = cache->discard_block_size;
665 
666 	if (block_size_is_power_of_two(cache))
667 		oblocks >>= cache->sectors_per_block_shift;
668 	else
669 		oblocks = block_div(oblocks, cache->sectors_per_block);
670 
671 	return oblocks;
672 }
673 
674 static dm_dblock_t oblock_to_dblock(struct cache *cache, dm_oblock_t oblock)
675 {
676 	return to_dblock(block_div(from_oblock(oblock),
677 				   oblocks_per_dblock(cache)));
678 }
679 
680 static void set_discard(struct cache *cache, dm_dblock_t b)
681 {
682 	BUG_ON(from_dblock(b) >= from_dblock(cache->discard_nr_blocks));
683 	atomic_inc(&cache->stats.discard_count);
684 
685 	spin_lock_irq(&cache->lock);
686 	set_bit(from_dblock(b), cache->discard_bitset);
687 	spin_unlock_irq(&cache->lock);
688 }
689 
690 static void clear_discard(struct cache *cache, dm_dblock_t b)
691 {
692 	spin_lock_irq(&cache->lock);
693 	clear_bit(from_dblock(b), cache->discard_bitset);
694 	spin_unlock_irq(&cache->lock);
695 }
696 
697 static bool is_discarded(struct cache *cache, dm_dblock_t b)
698 {
699 	int r;
700 
701 	spin_lock_irq(&cache->lock);
702 	r = test_bit(from_dblock(b), cache->discard_bitset);
703 	spin_unlock_irq(&cache->lock);
704 
705 	return r;
706 }
707 
708 static bool is_discarded_oblock(struct cache *cache, dm_oblock_t b)
709 {
710 	int r;
711 
712 	spin_lock_irq(&cache->lock);
713 	r = test_bit(from_dblock(oblock_to_dblock(cache, b)),
714 		     cache->discard_bitset);
715 	spin_unlock_irq(&cache->lock);
716 
717 	return r;
718 }
719 
720 /*
721  * -------------------------------------------------------------
722  * Remapping
723  *--------------------------------------------------------------
724  */
725 static void remap_to_origin(struct cache *cache, struct bio *bio)
726 {
727 	bio_set_dev(bio, cache->origin_dev->bdev);
728 }
729 
730 static void remap_to_cache(struct cache *cache, struct bio *bio,
731 			   dm_cblock_t cblock)
732 {
733 	sector_t bi_sector = bio->bi_iter.bi_sector;
734 	sector_t block = from_cblock(cblock);
735 
736 	bio_set_dev(bio, cache->cache_dev->bdev);
737 	if (!block_size_is_power_of_two(cache))
738 		bio->bi_iter.bi_sector =
739 			(block * cache->sectors_per_block) +
740 			sector_div(bi_sector, cache->sectors_per_block);
741 	else
742 		bio->bi_iter.bi_sector =
743 			(block << cache->sectors_per_block_shift) |
744 			(bi_sector & (cache->sectors_per_block - 1));
745 }
746 
747 static void check_if_tick_bio_needed(struct cache *cache, struct bio *bio)
748 {
749 	struct per_bio_data *pb;
750 
751 	spin_lock_irq(&cache->lock);
752 	if (cache->need_tick_bio && !op_is_flush(bio->bi_opf) &&
753 	    bio_op(bio) != REQ_OP_DISCARD) {
754 		pb = get_per_bio_data(bio);
755 		pb->tick = true;
756 		cache->need_tick_bio = false;
757 	}
758 	spin_unlock_irq(&cache->lock);
759 }
760 
761 static void remap_to_origin_clear_discard(struct cache *cache, struct bio *bio,
762 					  dm_oblock_t oblock)
763 {
764 	// FIXME: check_if_tick_bio_needed() is called way too much through this interface
765 	check_if_tick_bio_needed(cache, bio);
766 	remap_to_origin(cache, bio);
767 	if (bio_data_dir(bio) == WRITE)
768 		clear_discard(cache, oblock_to_dblock(cache, oblock));
769 }
770 
771 static void remap_to_cache_dirty(struct cache *cache, struct bio *bio,
772 				 dm_oblock_t oblock, dm_cblock_t cblock)
773 {
774 	check_if_tick_bio_needed(cache, bio);
775 	remap_to_cache(cache, bio, cblock);
776 	if (bio_data_dir(bio) == WRITE) {
777 		set_dirty(cache, cblock);
778 		clear_discard(cache, oblock_to_dblock(cache, oblock));
779 	}
780 }
781 
782 static dm_oblock_t get_bio_block(struct cache *cache, struct bio *bio)
783 {
784 	sector_t block_nr = bio->bi_iter.bi_sector;
785 
786 	if (!block_size_is_power_of_two(cache))
787 		(void) sector_div(block_nr, cache->sectors_per_block);
788 	else
789 		block_nr >>= cache->sectors_per_block_shift;
790 
791 	return to_oblock(block_nr);
792 }
793 
794 static bool accountable_bio(struct cache *cache, struct bio *bio)
795 {
796 	return bio_op(bio) != REQ_OP_DISCARD;
797 }
798 
799 static void accounted_begin(struct cache *cache, struct bio *bio)
800 {
801 	struct per_bio_data *pb;
802 
803 	if (accountable_bio(cache, bio)) {
804 		pb = get_per_bio_data(bio);
805 		pb->len = bio_sectors(bio);
806 		dm_iot_io_begin(&cache->tracker, pb->len);
807 	}
808 }
809 
810 static void accounted_complete(struct cache *cache, struct bio *bio)
811 {
812 	struct per_bio_data *pb = get_per_bio_data(bio);
813 
814 	dm_iot_io_end(&cache->tracker, pb->len);
815 }
816 
817 static void accounted_request(struct cache *cache, struct bio *bio)
818 {
819 	accounted_begin(cache, bio);
820 	dm_submit_bio_remap(bio, NULL);
821 }
822 
823 static void issue_op(struct bio *bio, void *context)
824 {
825 	struct cache *cache = context;
826 
827 	accounted_request(cache, bio);
828 }
829 
830 /*
831  * When running in writethrough mode we need to send writes to clean blocks
832  * to both the cache and origin devices.  Clone the bio and send them in parallel.
833  */
834 static void remap_to_origin_and_cache(struct cache *cache, struct bio *bio,
835 				      dm_oblock_t oblock, dm_cblock_t cblock)
836 {
837 	struct bio *origin_bio = bio_alloc_clone(cache->origin_dev->bdev, bio,
838 						 GFP_NOIO, &cache->bs);
839 
840 	BUG_ON(!origin_bio);
841 
842 	bio_chain(origin_bio, bio);
843 
844 	if (bio_data_dir(origin_bio) == WRITE)
845 		clear_discard(cache, oblock_to_dblock(cache, oblock));
846 	submit_bio(origin_bio);
847 
848 	remap_to_cache(cache, bio, cblock);
849 }
850 
851 /*
852  *--------------------------------------------------------------
853  * Failure modes
854  *--------------------------------------------------------------
855  */
856 static enum cache_metadata_mode get_cache_mode(struct cache *cache)
857 {
858 	return cache->features.mode;
859 }
860 
861 static const char *cache_device_name(struct cache *cache)
862 {
863 	return dm_table_device_name(cache->ti->table);
864 }
865 
866 static void notify_mode_switch(struct cache *cache, enum cache_metadata_mode mode)
867 {
868 	static const char *descs[] = {
869 		"write",
870 		"read-only",
871 		"fail"
872 	};
873 
874 	dm_table_event(cache->ti->table);
875 	DMINFO("%s: switching cache to %s mode",
876 	       cache_device_name(cache), descs[(int)mode]);
877 }
878 
879 static void set_cache_mode(struct cache *cache, enum cache_metadata_mode new_mode)
880 {
881 	bool needs_check;
882 	enum cache_metadata_mode old_mode = get_cache_mode(cache);
883 
884 	if (dm_cache_metadata_needs_check(cache->cmd, &needs_check)) {
885 		DMERR("%s: unable to read needs_check flag, setting failure mode.",
886 		      cache_device_name(cache));
887 		new_mode = CM_FAIL;
888 	}
889 
890 	if (new_mode == CM_WRITE && needs_check) {
891 		DMERR("%s: unable to switch cache to write mode until repaired.",
892 		      cache_device_name(cache));
893 		if (old_mode != new_mode)
894 			new_mode = old_mode;
895 		else
896 			new_mode = CM_READ_ONLY;
897 	}
898 
899 	/* Never move out of fail mode */
900 	if (old_mode == CM_FAIL)
901 		new_mode = CM_FAIL;
902 
903 	switch (new_mode) {
904 	case CM_FAIL:
905 	case CM_READ_ONLY:
906 		dm_cache_metadata_set_read_only(cache->cmd);
907 		break;
908 
909 	case CM_WRITE:
910 		dm_cache_metadata_set_read_write(cache->cmd);
911 		break;
912 	}
913 
914 	cache->features.mode = new_mode;
915 
916 	if (new_mode != old_mode)
917 		notify_mode_switch(cache, new_mode);
918 }
919 
920 static void abort_transaction(struct cache *cache)
921 {
922 	const char *dev_name = cache_device_name(cache);
923 
924 	if (get_cache_mode(cache) >= CM_READ_ONLY)
925 		return;
926 
927 	DMERR_LIMIT("%s: aborting current metadata transaction", dev_name);
928 	if (dm_cache_metadata_abort(cache->cmd)) {
929 		DMERR("%s: failed to abort metadata transaction", dev_name);
930 		set_cache_mode(cache, CM_FAIL);
931 	}
932 
933 	if (dm_cache_metadata_set_needs_check(cache->cmd)) {
934 		DMERR("%s: failed to set 'needs_check' flag in metadata", dev_name);
935 		set_cache_mode(cache, CM_FAIL);
936 	}
937 }
938 
939 static void metadata_operation_failed(struct cache *cache, const char *op, int r)
940 {
941 	DMERR_LIMIT("%s: metadata operation '%s' failed: error = %d",
942 		    cache_device_name(cache), op, r);
943 	abort_transaction(cache);
944 	set_cache_mode(cache, CM_READ_ONLY);
945 }
946 
947 /*----------------------------------------------------------------*/
948 
949 static void load_stats(struct cache *cache)
950 {
951 	struct dm_cache_statistics stats;
952 
953 	dm_cache_metadata_get_stats(cache->cmd, &stats);
954 	atomic_set(&cache->stats.read_hit, stats.read_hits);
955 	atomic_set(&cache->stats.read_miss, stats.read_misses);
956 	atomic_set(&cache->stats.write_hit, stats.write_hits);
957 	atomic_set(&cache->stats.write_miss, stats.write_misses);
958 }
959 
960 static void save_stats(struct cache *cache)
961 {
962 	struct dm_cache_statistics stats;
963 
964 	if (get_cache_mode(cache) >= CM_READ_ONLY)
965 		return;
966 
967 	stats.read_hits = atomic_read(&cache->stats.read_hit);
968 	stats.read_misses = atomic_read(&cache->stats.read_miss);
969 	stats.write_hits = atomic_read(&cache->stats.write_hit);
970 	stats.write_misses = atomic_read(&cache->stats.write_miss);
971 
972 	dm_cache_metadata_set_stats(cache->cmd, &stats);
973 }
974 
975 static void update_stats(struct cache_stats *stats, enum policy_operation op)
976 {
977 	switch (op) {
978 	case POLICY_PROMOTE:
979 		atomic_inc(&stats->promotion);
980 		break;
981 
982 	case POLICY_DEMOTE:
983 		atomic_inc(&stats->demotion);
984 		break;
985 
986 	case POLICY_WRITEBACK:
987 		atomic_inc(&stats->writeback);
988 		break;
989 	}
990 }
991 
992 /*
993  *---------------------------------------------------------------------
994  * Migration processing
995  *
996  * Migration covers moving data from the origin device to the cache, or
997  * vice versa.
998  *---------------------------------------------------------------------
999  */
1000 static void inc_io_migrations(struct cache *cache)
1001 {
1002 	atomic_inc(&cache->nr_io_migrations);
1003 }
1004 
1005 static void dec_io_migrations(struct cache *cache)
1006 {
1007 	atomic_dec(&cache->nr_io_migrations);
1008 }
1009 
1010 static bool discard_or_flush(struct bio *bio)
1011 {
1012 	return bio_op(bio) == REQ_OP_DISCARD || op_is_flush(bio->bi_opf);
1013 }
1014 
1015 static void calc_discard_block_range(struct cache *cache, struct bio *bio,
1016 				     dm_dblock_t *b, dm_dblock_t *e)
1017 {
1018 	sector_t sb = bio->bi_iter.bi_sector;
1019 	sector_t se = bio_end_sector(bio);
1020 
1021 	*b = to_dblock(dm_sector_div_up(sb, cache->discard_block_size));
1022 
1023 	if (se - sb < cache->discard_block_size)
1024 		*e = *b;
1025 	else
1026 		*e = to_dblock(block_div(se, cache->discard_block_size));
1027 }
1028 
1029 /*----------------------------------------------------------------*/
1030 
1031 static void prevent_background_work(struct cache *cache)
1032 {
1033 	lockdep_off();
1034 	down_write(&cache->background_work_lock);
1035 	lockdep_on();
1036 }
1037 
1038 static void allow_background_work(struct cache *cache)
1039 {
1040 	lockdep_off();
1041 	up_write(&cache->background_work_lock);
1042 	lockdep_on();
1043 }
1044 
1045 static bool background_work_begin(struct cache *cache)
1046 {
1047 	bool r;
1048 
1049 	lockdep_off();
1050 	r = down_read_trylock(&cache->background_work_lock);
1051 	lockdep_on();
1052 
1053 	return r;
1054 }
1055 
1056 static void background_work_end(struct cache *cache)
1057 {
1058 	lockdep_off();
1059 	up_read(&cache->background_work_lock);
1060 	lockdep_on();
1061 }
1062 
1063 /*----------------------------------------------------------------*/
1064 
1065 static bool bio_writes_complete_block(struct cache *cache, struct bio *bio)
1066 {
1067 	return (bio_data_dir(bio) == WRITE) &&
1068 		(bio->bi_iter.bi_size == (cache->sectors_per_block << SECTOR_SHIFT));
1069 }
1070 
1071 static bool optimisable_bio(struct cache *cache, struct bio *bio, dm_oblock_t block)
1072 {
1073 	return writeback_mode(cache) &&
1074 		(is_discarded_oblock(cache, block) || bio_writes_complete_block(cache, bio));
1075 }
1076 
1077 static void quiesce(struct dm_cache_migration *mg,
1078 		    void (*continuation)(struct work_struct *))
1079 {
1080 	init_continuation(&mg->k, continuation);
1081 	dm_cell_quiesce_v2(mg->cache->prison, mg->cell, &mg->k.ws);
1082 }
1083 
1084 static struct dm_cache_migration *ws_to_mg(struct work_struct *ws)
1085 {
1086 	struct continuation *k = container_of(ws, struct continuation, ws);
1087 
1088 	return container_of(k, struct dm_cache_migration, k);
1089 }
1090 
1091 static void copy_complete(int read_err, unsigned long write_err, void *context)
1092 {
1093 	struct dm_cache_migration *mg = container_of(context, struct dm_cache_migration, k);
1094 
1095 	if (read_err || write_err)
1096 		mg->k.input = BLK_STS_IOERR;
1097 
1098 	queue_continuation(mg->cache->wq, &mg->k);
1099 }
1100 
1101 static void copy(struct dm_cache_migration *mg, bool promote)
1102 {
1103 	struct dm_io_region o_region, c_region;
1104 	struct cache *cache = mg->cache;
1105 
1106 	o_region.bdev = cache->origin_dev->bdev;
1107 	o_region.sector = from_oblock(mg->op->oblock) * cache->sectors_per_block;
1108 	o_region.count = cache->sectors_per_block;
1109 
1110 	c_region.bdev = cache->cache_dev->bdev;
1111 	c_region.sector = from_cblock(mg->op->cblock) * cache->sectors_per_block;
1112 	c_region.count = cache->sectors_per_block;
1113 
1114 	if (promote)
1115 		dm_kcopyd_copy(cache->copier, &o_region, 1, &c_region, 0, copy_complete, &mg->k);
1116 	else
1117 		dm_kcopyd_copy(cache->copier, &c_region, 1, &o_region, 0, copy_complete, &mg->k);
1118 }
1119 
1120 static void bio_drop_shared_lock(struct cache *cache, struct bio *bio)
1121 {
1122 	struct per_bio_data *pb = get_per_bio_data(bio);
1123 
1124 	if (pb->cell && dm_cell_put_v2(cache->prison, pb->cell))
1125 		free_prison_cell(cache, pb->cell);
1126 	pb->cell = NULL;
1127 }
1128 
1129 static void overwrite_endio(struct bio *bio)
1130 {
1131 	struct dm_cache_migration *mg = bio->bi_private;
1132 	struct cache *cache = mg->cache;
1133 	struct per_bio_data *pb = get_per_bio_data(bio);
1134 
1135 	dm_unhook_bio(&pb->hook_info, bio);
1136 
1137 	if (bio->bi_status)
1138 		mg->k.input = bio->bi_status;
1139 
1140 	queue_continuation(cache->wq, &mg->k);
1141 }
1142 
1143 static void overwrite(struct dm_cache_migration *mg,
1144 		      void (*continuation)(struct work_struct *))
1145 {
1146 	struct bio *bio = mg->overwrite_bio;
1147 	struct per_bio_data *pb = get_per_bio_data(bio);
1148 
1149 	dm_hook_bio(&pb->hook_info, bio, overwrite_endio, mg);
1150 
1151 	/*
1152 	 * The overwrite bio is part of the copy operation, as such it does
1153 	 * not set/clear discard or dirty flags.
1154 	 */
1155 	if (mg->op->op == POLICY_PROMOTE)
1156 		remap_to_cache(mg->cache, bio, mg->op->cblock);
1157 	else
1158 		remap_to_origin(mg->cache, bio);
1159 
1160 	init_continuation(&mg->k, continuation);
1161 	accounted_request(mg->cache, bio);
1162 }
1163 
1164 /*
1165  * Migration steps:
1166  *
1167  * 1) exclusive lock preventing WRITEs
1168  * 2) quiesce
1169  * 3) copy or issue overwrite bio
1170  * 4) upgrade to exclusive lock preventing READs and WRITEs
1171  * 5) quiesce
1172  * 6) update metadata and commit
1173  * 7) unlock
1174  */
1175 static void mg_complete(struct dm_cache_migration *mg, bool success)
1176 {
1177 	struct bio_list bios;
1178 	struct cache *cache = mg->cache;
1179 	struct policy_work *op = mg->op;
1180 	dm_cblock_t cblock = op->cblock;
1181 
1182 	if (success)
1183 		update_stats(&cache->stats, op->op);
1184 
1185 	switch (op->op) {
1186 	case POLICY_PROMOTE:
1187 		clear_discard(cache, oblock_to_dblock(cache, op->oblock));
1188 		policy_complete_background_work(cache->policy, op, success);
1189 
1190 		if (mg->overwrite_bio) {
1191 			if (success)
1192 				force_set_dirty(cache, cblock);
1193 			else if (mg->k.input)
1194 				mg->overwrite_bio->bi_status = mg->k.input;
1195 			else
1196 				mg->overwrite_bio->bi_status = BLK_STS_IOERR;
1197 			bio_endio(mg->overwrite_bio);
1198 		} else {
1199 			if (success)
1200 				force_clear_dirty(cache, cblock);
1201 			dec_io_migrations(cache);
1202 		}
1203 		break;
1204 
1205 	case POLICY_DEMOTE:
1206 		/*
1207 		 * We clear dirty here to update the nr_dirty counter.
1208 		 */
1209 		if (success)
1210 			force_clear_dirty(cache, cblock);
1211 		policy_complete_background_work(cache->policy, op, success);
1212 		dec_io_migrations(cache);
1213 		break;
1214 
1215 	case POLICY_WRITEBACK:
1216 		if (success)
1217 			force_clear_dirty(cache, cblock);
1218 		policy_complete_background_work(cache->policy, op, success);
1219 		dec_io_migrations(cache);
1220 		break;
1221 	}
1222 
1223 	bio_list_init(&bios);
1224 	if (mg->cell) {
1225 		if (dm_cell_unlock_v2(cache->prison, mg->cell, &bios))
1226 			free_prison_cell(cache, mg->cell);
1227 	}
1228 
1229 	free_migration(mg);
1230 	defer_bios(cache, &bios);
1231 	wake_migration_worker(cache);
1232 
1233 	background_work_end(cache);
1234 }
1235 
1236 static void mg_success(struct work_struct *ws)
1237 {
1238 	struct dm_cache_migration *mg = ws_to_mg(ws);
1239 
1240 	mg_complete(mg, mg->k.input == 0);
1241 }
1242 
1243 static void mg_update_metadata(struct work_struct *ws)
1244 {
1245 	int r;
1246 	struct dm_cache_migration *mg = ws_to_mg(ws);
1247 	struct cache *cache = mg->cache;
1248 	struct policy_work *op = mg->op;
1249 
1250 	switch (op->op) {
1251 	case POLICY_PROMOTE:
1252 		r = dm_cache_insert_mapping(cache->cmd, op->cblock, op->oblock);
1253 		if (r) {
1254 			DMERR_LIMIT("%s: migration failed; couldn't insert mapping",
1255 				    cache_device_name(cache));
1256 			metadata_operation_failed(cache, "dm_cache_insert_mapping", r);
1257 
1258 			mg_complete(mg, false);
1259 			return;
1260 		}
1261 		mg_complete(mg, true);
1262 		break;
1263 
1264 	case POLICY_DEMOTE:
1265 		r = dm_cache_remove_mapping(cache->cmd, op->cblock);
1266 		if (r) {
1267 			DMERR_LIMIT("%s: migration failed; couldn't update on disk metadata",
1268 				    cache_device_name(cache));
1269 			metadata_operation_failed(cache, "dm_cache_remove_mapping", r);
1270 
1271 			mg_complete(mg, false);
1272 			return;
1273 		}
1274 
1275 		/*
1276 		 * It would be nice if we only had to commit when a REQ_FLUSH
1277 		 * comes through.  But there's one scenario that we have to
1278 		 * look out for:
1279 		 *
1280 		 * - vblock x in a cache block
1281 		 * - domotion occurs
1282 		 * - cache block gets reallocated and over written
1283 		 * - crash
1284 		 *
1285 		 * When we recover, because there was no commit the cache will
1286 		 * rollback to having the data for vblock x in the cache block.
1287 		 * But the cache block has since been overwritten, so it'll end
1288 		 * up pointing to data that was never in 'x' during the history
1289 		 * of the device.
1290 		 *
1291 		 * To avoid this issue we require a commit as part of the
1292 		 * demotion operation.
1293 		 */
1294 		init_continuation(&mg->k, mg_success);
1295 		continue_after_commit(&cache->committer, &mg->k);
1296 		schedule_commit(&cache->committer);
1297 		break;
1298 
1299 	case POLICY_WRITEBACK:
1300 		mg_complete(mg, true);
1301 		break;
1302 	}
1303 }
1304 
1305 static void mg_update_metadata_after_copy(struct work_struct *ws)
1306 {
1307 	struct dm_cache_migration *mg = ws_to_mg(ws);
1308 
1309 	/*
1310 	 * Did the copy succeed?
1311 	 */
1312 	if (mg->k.input)
1313 		mg_complete(mg, false);
1314 	else
1315 		mg_update_metadata(ws);
1316 }
1317 
1318 static void mg_upgrade_lock(struct work_struct *ws)
1319 {
1320 	int r;
1321 	struct dm_cache_migration *mg = ws_to_mg(ws);
1322 
1323 	/*
1324 	 * Did the copy succeed?
1325 	 */
1326 	if (mg->k.input)
1327 		mg_complete(mg, false);
1328 
1329 	else {
1330 		/*
1331 		 * Now we want the lock to prevent both reads and writes.
1332 		 */
1333 		r = dm_cell_lock_promote_v2(mg->cache->prison, mg->cell,
1334 					    READ_WRITE_LOCK_LEVEL);
1335 		if (r < 0)
1336 			mg_complete(mg, false);
1337 
1338 		else if (r)
1339 			quiesce(mg, mg_update_metadata);
1340 
1341 		else
1342 			mg_update_metadata(ws);
1343 	}
1344 }
1345 
1346 static void mg_full_copy(struct work_struct *ws)
1347 {
1348 	struct dm_cache_migration *mg = ws_to_mg(ws);
1349 	struct cache *cache = mg->cache;
1350 	struct policy_work *op = mg->op;
1351 	bool is_policy_promote = (op->op == POLICY_PROMOTE);
1352 
1353 	if ((!is_policy_promote && !is_dirty(cache, op->cblock)) ||
1354 	    is_discarded_oblock(cache, op->oblock)) {
1355 		mg_upgrade_lock(ws);
1356 		return;
1357 	}
1358 
1359 	init_continuation(&mg->k, mg_upgrade_lock);
1360 	copy(mg, is_policy_promote);
1361 }
1362 
1363 static void mg_copy(struct work_struct *ws)
1364 {
1365 	struct dm_cache_migration *mg = ws_to_mg(ws);
1366 
1367 	if (mg->overwrite_bio) {
1368 		/*
1369 		 * No exclusive lock was held when we last checked if the bio
1370 		 * was optimisable.  So we have to check again in case things
1371 		 * have changed (eg, the block may no longer be discarded).
1372 		 */
1373 		if (!optimisable_bio(mg->cache, mg->overwrite_bio, mg->op->oblock)) {
1374 			/*
1375 			 * Fallback to a real full copy after doing some tidying up.
1376 			 */
1377 			bool rb = bio_detain_shared(mg->cache, mg->op->oblock, mg->overwrite_bio);
1378 
1379 			BUG_ON(rb); /* An exclusive lock must _not_ be held for this block */
1380 			mg->overwrite_bio = NULL;
1381 			inc_io_migrations(mg->cache);
1382 			mg_full_copy(ws);
1383 			return;
1384 		}
1385 
1386 		/*
1387 		 * It's safe to do this here, even though it's new data
1388 		 * because all IO has been locked out of the block.
1389 		 *
1390 		 * mg_lock_writes() already took READ_WRITE_LOCK_LEVEL
1391 		 * so _not_ using mg_upgrade_lock() as continutation.
1392 		 */
1393 		overwrite(mg, mg_update_metadata_after_copy);
1394 
1395 	} else
1396 		mg_full_copy(ws);
1397 }
1398 
1399 static int mg_lock_writes(struct dm_cache_migration *mg)
1400 {
1401 	int r;
1402 	struct dm_cell_key_v2 key;
1403 	struct cache *cache = mg->cache;
1404 	struct dm_bio_prison_cell_v2 *prealloc;
1405 
1406 	prealloc = alloc_prison_cell(cache);
1407 
1408 	/*
1409 	 * Prevent writes to the block, but allow reads to continue.
1410 	 * Unless we're using an overwrite bio, in which case we lock
1411 	 * everything.
1412 	 */
1413 	build_key(mg->op->oblock, oblock_succ(mg->op->oblock), &key);
1414 	r = dm_cell_lock_v2(cache->prison, &key,
1415 			    mg->overwrite_bio ?  READ_WRITE_LOCK_LEVEL : WRITE_LOCK_LEVEL,
1416 			    prealloc, &mg->cell);
1417 	if (r < 0) {
1418 		free_prison_cell(cache, prealloc);
1419 		mg_complete(mg, false);
1420 		return r;
1421 	}
1422 
1423 	if (mg->cell != prealloc)
1424 		free_prison_cell(cache, prealloc);
1425 
1426 	if (r == 0)
1427 		mg_copy(&mg->k.ws);
1428 	else
1429 		quiesce(mg, mg_copy);
1430 
1431 	return 0;
1432 }
1433 
1434 static int mg_start(struct cache *cache, struct policy_work *op, struct bio *bio)
1435 {
1436 	struct dm_cache_migration *mg;
1437 
1438 	if (!background_work_begin(cache)) {
1439 		policy_complete_background_work(cache->policy, op, false);
1440 		return -EPERM;
1441 	}
1442 
1443 	mg = alloc_migration(cache);
1444 
1445 	mg->op = op;
1446 	mg->overwrite_bio = bio;
1447 
1448 	if (!bio)
1449 		inc_io_migrations(cache);
1450 
1451 	return mg_lock_writes(mg);
1452 }
1453 
1454 /*
1455  *--------------------------------------------------------------
1456  * invalidation processing
1457  *--------------------------------------------------------------
1458  */
1459 
1460 static void invalidate_complete(struct dm_cache_migration *mg, bool success)
1461 {
1462 	struct bio_list bios;
1463 	struct cache *cache = mg->cache;
1464 
1465 	bio_list_init(&bios);
1466 	if (mg->cell) {
1467 		if (dm_cell_unlock_v2(cache->prison, mg->cell, &bios))
1468 			free_prison_cell(cache, mg->cell);
1469 	}
1470 
1471 	if (mg->overwrite_bio) {
1472 		// Set generic error if the bio hasn't been issued yet,
1473 		// e.g., invalidation or metadata commit failed before bio
1474 		// submission. Otherwise preserve the bio's own error status.
1475 		if (!success && !mg->overwrite_bio->bi_status)
1476 			mg->overwrite_bio->bi_status = BLK_STS_IOERR;
1477 		bio_endio(mg->overwrite_bio);
1478 	}
1479 
1480 	free_migration(mg);
1481 	defer_bios(cache, &bios);
1482 
1483 	background_work_end(cache);
1484 }
1485 
1486 static void invalidate_completed(struct work_struct *ws)
1487 {
1488 	struct dm_cache_migration *mg = ws_to_mg(ws);
1489 
1490 	invalidate_complete(mg, !mg->k.input);
1491 }
1492 
1493 static int invalidate_cblock(struct cache *cache, dm_cblock_t cblock)
1494 {
1495 	int r;
1496 
1497 	r = policy_invalidate_mapping(cache->policy, cblock);
1498 	if (!r) {
1499 		r = dm_cache_remove_mapping(cache->cmd, cblock);
1500 		if (r) {
1501 			DMERR_LIMIT("%s: invalidation failed; couldn't update on disk metadata",
1502 				    cache_device_name(cache));
1503 			metadata_operation_failed(cache, "dm_cache_remove_mapping", r);
1504 		}
1505 
1506 	} else if (r == -ENODATA) {
1507 		/*
1508 		 * Harmless, already unmapped.
1509 		 */
1510 		r = 0;
1511 
1512 	} else
1513 		DMERR("%s: policy_invalidate_mapping failed", cache_device_name(cache));
1514 
1515 	return r;
1516 }
1517 
1518 static void invalidate_committed(struct work_struct *ws)
1519 {
1520 	struct dm_cache_migration *mg = ws_to_mg(ws);
1521 	struct cache *cache = mg->cache;
1522 	struct bio *bio = mg->overwrite_bio;
1523 	struct per_bio_data *pb = get_per_bio_data(bio);
1524 
1525 	if (mg->k.input) {
1526 		invalidate_complete(mg, false);
1527 		return;
1528 	}
1529 
1530 	init_continuation(&mg->k, invalidate_completed);
1531 	remap_to_origin_clear_discard(cache, bio, mg->invalidate_oblock);
1532 	dm_hook_bio(&pb->hook_info, bio, overwrite_endio, mg);
1533 	dm_submit_bio_remap(bio, NULL);
1534 }
1535 
1536 static void invalidate_remove(struct work_struct *ws)
1537 {
1538 	int r;
1539 	struct dm_cache_migration *mg = ws_to_mg(ws);
1540 	struct cache *cache = mg->cache;
1541 
1542 	r = invalidate_cblock(cache, mg->invalidate_cblock);
1543 	if (r) {
1544 		invalidate_complete(mg, false);
1545 		return;
1546 	}
1547 
1548 	init_continuation(&mg->k, invalidate_committed);
1549 	continue_after_commit(&cache->committer, &mg->k);
1550 	schedule_commit(&cache->committer);
1551 }
1552 
1553 static int invalidate_lock(struct dm_cache_migration *mg)
1554 {
1555 	int r;
1556 	struct dm_cell_key_v2 key;
1557 	struct cache *cache = mg->cache;
1558 	struct dm_bio_prison_cell_v2 *prealloc;
1559 
1560 	prealloc = alloc_prison_cell(cache);
1561 
1562 	build_key(mg->invalidate_oblock, oblock_succ(mg->invalidate_oblock), &key);
1563 	r = dm_cell_lock_v2(cache->prison, &key,
1564 			    READ_WRITE_LOCK_LEVEL, prealloc, &mg->cell);
1565 	if (r < 0) {
1566 		free_prison_cell(cache, prealloc);
1567 
1568 		/* Defer the bio for retrying the cell lock */
1569 		if (mg->overwrite_bio) {
1570 			struct bio *bio = mg->overwrite_bio;
1571 
1572 			mg->overwrite_bio = NULL;
1573 			defer_bio(cache, bio);
1574 		}
1575 
1576 		invalidate_complete(mg, false);
1577 		return r;
1578 	}
1579 
1580 	if (mg->cell != prealloc)
1581 		free_prison_cell(cache, prealloc);
1582 
1583 	if (r)
1584 		quiesce(mg, invalidate_remove);
1585 
1586 	else {
1587 		/*
1588 		 * We can't call invalidate_remove() directly here because we
1589 		 * might still be in request context.
1590 		 */
1591 		init_continuation(&mg->k, invalidate_remove);
1592 		queue_work(cache->wq, &mg->k.ws);
1593 	}
1594 
1595 	return 0;
1596 }
1597 
1598 static int invalidate_start(struct cache *cache, dm_cblock_t cblock,
1599 			    dm_oblock_t oblock, struct bio *bio)
1600 {
1601 	struct dm_cache_migration *mg;
1602 
1603 	if (!background_work_begin(cache))
1604 		return -EPERM;
1605 
1606 	mg = alloc_migration(cache);
1607 
1608 	mg->overwrite_bio = bio;
1609 	mg->invalidate_cblock = cblock;
1610 	mg->invalidate_oblock = oblock;
1611 
1612 	return invalidate_lock(mg);
1613 }
1614 
1615 /*
1616  *--------------------------------------------------------------
1617  * bio processing
1618  *--------------------------------------------------------------
1619  */
1620 
1621 enum busy {
1622 	IDLE,
1623 	BUSY
1624 };
1625 
1626 static enum busy spare_migration_bandwidth(struct cache *cache)
1627 {
1628 	bool idle = dm_iot_idle_for(&cache->tracker, HZ);
1629 	sector_t current_volume = (atomic_read(&cache->nr_io_migrations) + 1) *
1630 		cache->sectors_per_block;
1631 
1632 	if (idle && current_volume <= cache->migration_threshold)
1633 		return IDLE;
1634 	else
1635 		return BUSY;
1636 }
1637 
1638 static void inc_hit_counter(struct cache *cache, struct bio *bio)
1639 {
1640 	atomic_inc(bio_data_dir(bio) == READ ?
1641 		   &cache->stats.read_hit : &cache->stats.write_hit);
1642 }
1643 
1644 static void inc_miss_counter(struct cache *cache, struct bio *bio)
1645 {
1646 	atomic_inc(bio_data_dir(bio) == READ ?
1647 		   &cache->stats.read_miss : &cache->stats.write_miss);
1648 }
1649 
1650 /*----------------------------------------------------------------*/
1651 
1652 static int map_bio(struct cache *cache, struct bio *bio, dm_oblock_t block,
1653 		   bool *commit_needed)
1654 {
1655 	int r, data_dir;
1656 	bool rb, background_queued;
1657 	dm_cblock_t cblock;
1658 
1659 	*commit_needed = false;
1660 
1661 	rb = bio_detain_shared(cache, block, bio);
1662 	if (!rb) {
1663 		/*
1664 		 * An exclusive lock is held for this block, so we have to
1665 		 * wait.  We set the commit_needed flag so the current
1666 		 * transaction will be committed asap, allowing this lock
1667 		 * to be dropped.
1668 		 */
1669 		*commit_needed = true;
1670 		return DM_MAPIO_SUBMITTED;
1671 	}
1672 
1673 	data_dir = bio_data_dir(bio);
1674 
1675 	if (optimisable_bio(cache, bio, block)) {
1676 		struct policy_work *op = NULL;
1677 
1678 		r = policy_lookup_with_work(cache->policy, block, &cblock, data_dir, true, &op);
1679 		if (unlikely(r && r != -ENOENT)) {
1680 			DMERR_LIMIT("%s: policy_lookup_with_work() failed with r = %d",
1681 				    cache_device_name(cache), r);
1682 			bio_io_error(bio);
1683 			return DM_MAPIO_SUBMITTED;
1684 		}
1685 
1686 		if (r == -ENOENT && op) {
1687 			bio_drop_shared_lock(cache, bio);
1688 			BUG_ON(op->op != POLICY_PROMOTE);
1689 			mg_start(cache, op, bio);
1690 			return DM_MAPIO_SUBMITTED;
1691 		}
1692 	} else {
1693 		r = policy_lookup(cache->policy, block, &cblock, data_dir, false, &background_queued);
1694 		if (unlikely(r && r != -ENOENT)) {
1695 			DMERR_LIMIT("%s: policy_lookup() failed with r = %d",
1696 				    cache_device_name(cache), r);
1697 			bio_io_error(bio);
1698 			return DM_MAPIO_SUBMITTED;
1699 		}
1700 
1701 		if (background_queued)
1702 			wake_migration_worker(cache);
1703 	}
1704 
1705 	if (r == -ENOENT) {
1706 		struct per_bio_data *pb = get_per_bio_data(bio);
1707 
1708 		/*
1709 		 * Miss.
1710 		 */
1711 		inc_miss_counter(cache, bio);
1712 		if (pb->req_nr == 0) {
1713 			accounted_begin(cache, bio);
1714 			remap_to_origin_clear_discard(cache, bio, block);
1715 		} else {
1716 			/*
1717 			 * This is a duplicate writethrough io that is no
1718 			 * longer needed because the block has been demoted.
1719 			 */
1720 			bio_endio(bio);
1721 			return DM_MAPIO_SUBMITTED;
1722 		}
1723 	} else {
1724 		/*
1725 		 * Hit.
1726 		 */
1727 		inc_hit_counter(cache, bio);
1728 
1729 		/*
1730 		 * Passthrough always maps to the origin, invalidating any
1731 		 * cache blocks that are written to.
1732 		 */
1733 		if (passthrough_mode(cache)) {
1734 			if (bio_data_dir(bio) == WRITE) {
1735 				bio_drop_shared_lock(cache, bio);
1736 				atomic_inc(&cache->stats.demotion);
1737 				invalidate_start(cache, cblock, block, bio);
1738 				return DM_MAPIO_SUBMITTED;
1739 			} else
1740 				remap_to_origin_clear_discard(cache, bio, block);
1741 		} else {
1742 			if (bio_data_dir(bio) == WRITE && writethrough_mode(cache) &&
1743 			    !is_dirty(cache, cblock)) {
1744 				remap_to_origin_and_cache(cache, bio, block, cblock);
1745 				accounted_begin(cache, bio);
1746 			} else
1747 				remap_to_cache_dirty(cache, bio, block, cblock);
1748 		}
1749 	}
1750 
1751 	/*
1752 	 * dm core turns FUA requests into a separate payload and FLUSH req.
1753 	 */
1754 	if (bio->bi_opf & REQ_FUA) {
1755 		/*
1756 		 * issue_after_commit will call accounted_begin a second time.  So
1757 		 * we call accounted_complete() to avoid double accounting.
1758 		 */
1759 		accounted_complete(cache, bio);
1760 		issue_after_commit(&cache->committer, bio);
1761 		*commit_needed = true;
1762 		return DM_MAPIO_SUBMITTED;
1763 	}
1764 
1765 	return DM_MAPIO_REMAPPED;
1766 }
1767 
1768 static bool process_bio(struct cache *cache, struct bio *bio)
1769 {
1770 	bool commit_needed;
1771 
1772 	if (map_bio(cache, bio, get_bio_block(cache, bio), &commit_needed) == DM_MAPIO_REMAPPED)
1773 		dm_submit_bio_remap(bio, NULL);
1774 
1775 	return commit_needed;
1776 }
1777 
1778 /*
1779  * A non-zero return indicates read_only or fail_io mode.
1780  */
1781 static int commit(struct cache *cache, bool clean_shutdown)
1782 {
1783 	int r;
1784 
1785 	if (get_cache_mode(cache) >= CM_READ_ONLY)
1786 		return -EINVAL;
1787 
1788 	atomic_inc(&cache->stats.commit_count);
1789 	r = dm_cache_commit(cache->cmd, clean_shutdown);
1790 	if (r)
1791 		metadata_operation_failed(cache, "dm_cache_commit", r);
1792 
1793 	return r;
1794 }
1795 
1796 /*
1797  * Used by the batcher.
1798  */
1799 static blk_status_t commit_op(void *context)
1800 {
1801 	struct cache *cache = context;
1802 
1803 	if (dm_cache_changed_this_transaction(cache->cmd))
1804 		return errno_to_blk_status(commit(cache, false));
1805 
1806 	return 0;
1807 }
1808 
1809 /*----------------------------------------------------------------*/
1810 
1811 static bool process_flush_bio(struct cache *cache, struct bio *bio)
1812 {
1813 	struct per_bio_data *pb = get_per_bio_data(bio);
1814 
1815 	if (!pb->req_nr)
1816 		remap_to_origin(cache, bio);
1817 	else
1818 		remap_to_cache(cache, bio, 0);
1819 
1820 	issue_after_commit(&cache->committer, bio);
1821 	return true;
1822 }
1823 
1824 static bool process_discard_bio(struct cache *cache, struct bio *bio)
1825 {
1826 	dm_dblock_t b, e;
1827 
1828 	/*
1829 	 * FIXME: do we need to lock the region?  Or can we just assume the
1830 	 * user wont be so foolish as to issue discard concurrently with
1831 	 * other IO?
1832 	 */
1833 	calc_discard_block_range(cache, bio, &b, &e);
1834 	while (b != e) {
1835 		set_discard(cache, b);
1836 		b = to_dblock(from_dblock(b) + 1);
1837 	}
1838 
1839 	if (cache->features.discard_passdown) {
1840 		remap_to_origin(cache, bio);
1841 		dm_submit_bio_remap(bio, NULL);
1842 	} else
1843 		bio_endio(bio);
1844 
1845 	return false;
1846 }
1847 
1848 static void process_deferred_bios(struct work_struct *ws)
1849 {
1850 	struct cache *cache = container_of(ws, struct cache, deferred_bio_worker);
1851 
1852 	bool commit_needed = false;
1853 	struct bio_list bios;
1854 	struct bio *bio;
1855 
1856 	bio_list_init(&bios);
1857 
1858 	spin_lock_irq(&cache->lock);
1859 	bio_list_merge_init(&bios, &cache->deferred_bios);
1860 	spin_unlock_irq(&cache->lock);
1861 
1862 	while ((bio = bio_list_pop(&bios))) {
1863 		if (bio->bi_opf & REQ_PREFLUSH)
1864 			commit_needed = process_flush_bio(cache, bio) || commit_needed;
1865 
1866 		else if (bio_op(bio) == REQ_OP_DISCARD)
1867 			commit_needed = process_discard_bio(cache, bio) || commit_needed;
1868 
1869 		else
1870 			commit_needed = process_bio(cache, bio) || commit_needed;
1871 		cond_resched();
1872 	}
1873 
1874 	if (commit_needed)
1875 		schedule_commit(&cache->committer);
1876 }
1877 
1878 /*
1879  *--------------------------------------------------------------
1880  * Main worker loop
1881  *--------------------------------------------------------------
1882  */
1883 static void requeue_deferred_bios(struct cache *cache)
1884 {
1885 	struct bio *bio;
1886 	struct bio_list bios;
1887 
1888 	bio_list_init(&bios);
1889 	bio_list_merge_init(&bios, &cache->deferred_bios);
1890 
1891 	while ((bio = bio_list_pop(&bios))) {
1892 		bio->bi_status = BLK_STS_DM_REQUEUE;
1893 		bio_endio(bio);
1894 		cond_resched();
1895 	}
1896 }
1897 
1898 /*
1899  * We want to commit periodically so that not too much
1900  * unwritten metadata builds up.
1901  */
1902 static void do_waker(struct work_struct *ws)
1903 {
1904 	struct cache *cache = container_of(to_delayed_work(ws), struct cache, waker);
1905 
1906 	policy_tick(cache->policy, true);
1907 	wake_migration_worker(cache);
1908 	schedule_commit(&cache->committer);
1909 	queue_delayed_work(cache->wq, &cache->waker, COMMIT_PERIOD);
1910 }
1911 
1912 static void check_migrations(struct work_struct *ws)
1913 {
1914 	int r;
1915 	struct policy_work *op;
1916 	struct cache *cache = container_of(ws, struct cache, migration_worker);
1917 	enum busy b;
1918 
1919 	for (;;) {
1920 		b = spare_migration_bandwidth(cache);
1921 
1922 		r = policy_get_background_work(cache->policy, b == IDLE, &op);
1923 		if (r == -ENODATA)
1924 			break;
1925 
1926 		if (r) {
1927 			DMERR_LIMIT("%s: policy_background_work failed",
1928 				    cache_device_name(cache));
1929 			break;
1930 		}
1931 
1932 		r = mg_start(cache, op, NULL);
1933 		if (r)
1934 			break;
1935 
1936 		cond_resched();
1937 	}
1938 }
1939 
1940 /*
1941  *--------------------------------------------------------------
1942  * Target methods
1943  *--------------------------------------------------------------
1944  */
1945 
1946 /*
1947  * This function gets called on the error paths of the constructor, so we
1948  * have to cope with a partially initialised struct.
1949  */
1950 static void __destroy(struct cache *cache)
1951 {
1952 	mempool_exit(&cache->migration_pool);
1953 
1954 	if (cache->prison)
1955 		dm_bio_prison_destroy_v2(cache->prison);
1956 
1957 	if (cache->wq)
1958 		destroy_workqueue(cache->wq);
1959 
1960 	if (cache->dirty_bitset)
1961 		free_bitset(cache->dirty_bitset);
1962 
1963 	if (cache->discard_bitset)
1964 		free_bitset(cache->discard_bitset);
1965 
1966 	if (cache->invalid_bitset)
1967 		free_bitset(cache->invalid_bitset);
1968 
1969 	if (cache->copier)
1970 		dm_kcopyd_client_destroy(cache->copier);
1971 
1972 	if (cache->cmd)
1973 		dm_cache_metadata_close(cache->cmd);
1974 
1975 	if (cache->metadata_dev)
1976 		dm_put_device(cache->ti, cache->metadata_dev);
1977 
1978 	if (cache->origin_dev)
1979 		dm_put_device(cache->ti, cache->origin_dev);
1980 
1981 	if (cache->cache_dev)
1982 		dm_put_device(cache->ti, cache->cache_dev);
1983 
1984 	if (cache->policy)
1985 		dm_cache_policy_destroy(cache->policy);
1986 
1987 	bioset_exit(&cache->bs);
1988 
1989 	kfree(cache);
1990 }
1991 
1992 static void destroy(struct cache *cache)
1993 {
1994 	unsigned int i;
1995 
1996 	cancel_delayed_work_sync(&cache->waker);
1997 
1998 	for (i = 0; i < cache->nr_ctr_args ; i++)
1999 		kfree(cache->ctr_args[i]);
2000 	kfree(cache->ctr_args);
2001 
2002 	__destroy(cache);
2003 }
2004 
2005 static void cache_dtr(struct dm_target *ti)
2006 {
2007 	struct cache *cache = ti->private;
2008 
2009 	destroy(cache);
2010 }
2011 
2012 static sector_t get_dev_size(struct dm_dev *dev)
2013 {
2014 	return bdev_nr_sectors(dev->bdev);
2015 }
2016 
2017 /*----------------------------------------------------------------*/
2018 
2019 /*
2020  * Construct a cache device mapping.
2021  *
2022  * cache <metadata dev> <cache dev> <origin dev> <block size>
2023  *       <#feature args> [<feature arg>]*
2024  *       <policy> <#policy args> [<policy arg>]*
2025  *
2026  * metadata dev    : fast device holding the persistent metadata
2027  * cache dev	   : fast device holding cached data blocks
2028  * origin dev	   : slow device holding original data blocks
2029  * block size	   : cache unit size in sectors
2030  *
2031  * #feature args   : number of feature arguments passed
2032  * feature args    : writethrough.  (The default is writeback.)
2033  *
2034  * policy	   : the replacement policy to use
2035  * #policy args    : an even number of policy arguments corresponding
2036  *		     to key/value pairs passed to the policy
2037  * policy args	   : key/value pairs passed to the policy
2038  *		     E.g. 'sequential_threshold 1024'
2039  *		     See cache-policies.txt for details.
2040  *
2041  * Optional feature arguments are:
2042  *   writethrough  : write through caching that prohibits cache block
2043  *		     content from being different from origin block content.
2044  *		     Without this argument, the default behaviour is to write
2045  *		     back cache block contents later for performance reasons,
2046  *		     so they may differ from the corresponding origin blocks.
2047  */
2048 struct cache_args {
2049 	struct dm_target *ti;
2050 
2051 	struct dm_dev *metadata_dev;
2052 
2053 	struct dm_dev *cache_dev;
2054 	sector_t cache_sectors;
2055 
2056 	struct dm_dev *origin_dev;
2057 
2058 	uint32_t block_size;
2059 
2060 	const char *policy_name;
2061 	int policy_argc;
2062 	const char **policy_argv;
2063 
2064 	struct cache_features features;
2065 };
2066 
2067 static void destroy_cache_args(struct cache_args *ca)
2068 {
2069 	if (ca->metadata_dev)
2070 		dm_put_device(ca->ti, ca->metadata_dev);
2071 
2072 	if (ca->cache_dev)
2073 		dm_put_device(ca->ti, ca->cache_dev);
2074 
2075 	if (ca->origin_dev)
2076 		dm_put_device(ca->ti, ca->origin_dev);
2077 
2078 	kfree(ca);
2079 }
2080 
2081 static bool at_least_one_arg(struct dm_arg_set *as, char **error)
2082 {
2083 	if (!as->argc) {
2084 		*error = "Insufficient args";
2085 		return false;
2086 	}
2087 
2088 	return true;
2089 }
2090 
2091 static int parse_metadata_dev(struct cache_args *ca, struct dm_arg_set *as,
2092 			      char **error)
2093 {
2094 	int r;
2095 	sector_t metadata_dev_size;
2096 
2097 	if (!at_least_one_arg(as, error))
2098 		return -EINVAL;
2099 
2100 	r = dm_get_device(ca->ti, dm_shift_arg(as),
2101 			  BLK_OPEN_READ | BLK_OPEN_WRITE, &ca->metadata_dev);
2102 	if (r) {
2103 		*error = "Error opening metadata device";
2104 		return r;
2105 	}
2106 
2107 	metadata_dev_size = get_dev_size(ca->metadata_dev);
2108 	if (metadata_dev_size > DM_CACHE_METADATA_MAX_SECTORS_WARNING)
2109 		DMWARN("Metadata device %pg is larger than %u sectors: excess space will not be used.",
2110 		       ca->metadata_dev->bdev, THIN_METADATA_MAX_SECTORS);
2111 
2112 	return 0;
2113 }
2114 
2115 static int parse_cache_dev(struct cache_args *ca, struct dm_arg_set *as,
2116 			   char **error)
2117 {
2118 	int r;
2119 
2120 	if (!at_least_one_arg(as, error))
2121 		return -EINVAL;
2122 
2123 	r = dm_get_device(ca->ti, dm_shift_arg(as),
2124 			  BLK_OPEN_READ | BLK_OPEN_WRITE, &ca->cache_dev);
2125 	if (r) {
2126 		*error = "Error opening cache device";
2127 		return r;
2128 	}
2129 	ca->cache_sectors = get_dev_size(ca->cache_dev);
2130 
2131 	return 0;
2132 }
2133 
2134 static int parse_origin_dev(struct cache_args *ca, struct dm_arg_set *as,
2135 			    char **error)
2136 {
2137 	int r;
2138 
2139 	if (!at_least_one_arg(as, error))
2140 		return -EINVAL;
2141 
2142 	r = dm_get_device(ca->ti, dm_shift_arg(as),
2143 			  BLK_OPEN_READ | BLK_OPEN_WRITE, &ca->origin_dev);
2144 	if (r) {
2145 		*error = "Error opening origin device";
2146 		return r;
2147 	}
2148 
2149 	return 0;
2150 }
2151 
2152 static int parse_block_size(struct cache_args *ca, struct dm_arg_set *as,
2153 			    char **error)
2154 {
2155 	unsigned long block_size;
2156 
2157 	if (!at_least_one_arg(as, error))
2158 		return -EINVAL;
2159 
2160 	if (kstrtoul(dm_shift_arg(as), 10, &block_size) || !block_size ||
2161 	    block_size < DATA_DEV_BLOCK_SIZE_MIN_SECTORS ||
2162 	    block_size > DATA_DEV_BLOCK_SIZE_MAX_SECTORS ||
2163 	    block_size & (DATA_DEV_BLOCK_SIZE_MIN_SECTORS - 1)) {
2164 		*error = "Invalid data block size";
2165 		return -EINVAL;
2166 	}
2167 
2168 	if (block_size > ca->cache_sectors) {
2169 		*error = "Data block size is larger than the cache device";
2170 		return -EINVAL;
2171 	}
2172 
2173 	ca->block_size = block_size;
2174 
2175 	return 0;
2176 }
2177 
2178 static void init_features(struct cache_features *cf)
2179 {
2180 	cf->mode = CM_WRITE;
2181 	cf->io_mode = CM_IO_WRITEBACK;
2182 	cf->metadata_version = 1;
2183 	cf->discard_passdown = true;
2184 }
2185 
2186 static int parse_features(struct cache_args *ca, struct dm_arg_set *as,
2187 			  char **error)
2188 {
2189 	static const struct dm_arg _args[] = {
2190 		{0, 3, "Invalid number of cache feature arguments"},
2191 	};
2192 
2193 	int r, mode_ctr = 0;
2194 	unsigned int argc;
2195 	const char *arg;
2196 	struct cache_features *cf = &ca->features;
2197 
2198 	init_features(cf);
2199 
2200 	r = dm_read_arg_group(_args, as, &argc, error);
2201 	if (r)
2202 		return -EINVAL;
2203 
2204 	while (argc--) {
2205 		arg = dm_shift_arg(as);
2206 
2207 		if (!strcasecmp(arg, "writeback")) {
2208 			cf->io_mode = CM_IO_WRITEBACK;
2209 			mode_ctr++;
2210 		}
2211 
2212 		else if (!strcasecmp(arg, "writethrough")) {
2213 			cf->io_mode = CM_IO_WRITETHROUGH;
2214 			mode_ctr++;
2215 		}
2216 
2217 		else if (!strcasecmp(arg, "passthrough")) {
2218 			cf->io_mode = CM_IO_PASSTHROUGH;
2219 			mode_ctr++;
2220 		}
2221 
2222 		else if (!strcasecmp(arg, "metadata2"))
2223 			cf->metadata_version = 2;
2224 
2225 		else if (!strcasecmp(arg, "no_discard_passdown"))
2226 			cf->discard_passdown = false;
2227 
2228 		else {
2229 			*error = "Unrecognised cache feature requested";
2230 			return -EINVAL;
2231 		}
2232 	}
2233 
2234 	if (mode_ctr > 1) {
2235 		*error = "Duplicate cache io_mode features requested";
2236 		return -EINVAL;
2237 	}
2238 
2239 	return 0;
2240 }
2241 
2242 static int parse_policy(struct cache_args *ca, struct dm_arg_set *as,
2243 			char **error)
2244 {
2245 	static const struct dm_arg _args[] = {
2246 		{0, 1024, "Invalid number of policy arguments"},
2247 	};
2248 
2249 	int r;
2250 
2251 	if (!at_least_one_arg(as, error))
2252 		return -EINVAL;
2253 
2254 	ca->policy_name = dm_shift_arg(as);
2255 
2256 	r = dm_read_arg_group(_args, as, &ca->policy_argc, error);
2257 	if (r)
2258 		return -EINVAL;
2259 
2260 	ca->policy_argv = (const char **)as->argv;
2261 	dm_consume_args(as, ca->policy_argc);
2262 
2263 	return 0;
2264 }
2265 
2266 static int parse_cache_args(struct cache_args *ca, int argc, char **argv,
2267 			    char **error)
2268 {
2269 	int r;
2270 	struct dm_arg_set as;
2271 
2272 	as.argc = argc;
2273 	as.argv = argv;
2274 
2275 	r = parse_metadata_dev(ca, &as, error);
2276 	if (r)
2277 		return r;
2278 
2279 	r = parse_cache_dev(ca, &as, error);
2280 	if (r)
2281 		return r;
2282 
2283 	r = parse_origin_dev(ca, &as, error);
2284 	if (r)
2285 		return r;
2286 
2287 	r = parse_block_size(ca, &as, error);
2288 	if (r)
2289 		return r;
2290 
2291 	r = parse_features(ca, &as, error);
2292 	if (r)
2293 		return r;
2294 
2295 	r = parse_policy(ca, &as, error);
2296 	if (r)
2297 		return r;
2298 
2299 	return 0;
2300 }
2301 
2302 /*----------------------------------------------------------------*/
2303 
2304 static struct kmem_cache *migration_cache = NULL;
2305 
2306 #define NOT_CORE_OPTION 1
2307 
2308 static int process_config_option(struct cache *cache, const char *key, const char *value)
2309 {
2310 	unsigned long tmp;
2311 
2312 	if (!strcasecmp(key, "migration_threshold")) {
2313 		if (kstrtoul(value, 10, &tmp))
2314 			return -EINVAL;
2315 
2316 		cache->migration_threshold = tmp;
2317 		return 0;
2318 	}
2319 
2320 	return NOT_CORE_OPTION;
2321 }
2322 
2323 static int set_config_value(struct cache *cache, const char *key, const char *value)
2324 {
2325 	int r = process_config_option(cache, key, value);
2326 
2327 	if (r == NOT_CORE_OPTION)
2328 		r = policy_set_config_value(cache->policy, key, value);
2329 
2330 	if (r)
2331 		DMWARN("bad config value for %s: %s", key, value);
2332 
2333 	return r;
2334 }
2335 
2336 static int set_config_values(struct cache *cache, int argc, const char **argv)
2337 {
2338 	int r = 0;
2339 
2340 	if (argc & 1) {
2341 		DMWARN("Odd number of policy arguments given but they should be <key> <value> pairs.");
2342 		return -EINVAL;
2343 	}
2344 
2345 	while (argc) {
2346 		r = set_config_value(cache, argv[0], argv[1]);
2347 		if (r)
2348 			break;
2349 
2350 		argc -= 2;
2351 		argv += 2;
2352 	}
2353 
2354 	return r;
2355 }
2356 
2357 static int create_cache_policy(struct cache *cache, struct cache_args *ca,
2358 			       char **error)
2359 {
2360 	struct dm_cache_policy *p = dm_cache_policy_create(ca->policy_name,
2361 							   cache->cache_size,
2362 							   cache->origin_sectors,
2363 							   cache->sectors_per_block);
2364 	if (IS_ERR(p)) {
2365 		*error = "Error creating cache's policy";
2366 		return PTR_ERR(p);
2367 	}
2368 	cache->policy = p;
2369 	BUG_ON(!cache->policy);
2370 
2371 	return 0;
2372 }
2373 
2374 /*
2375  * We want the discard block size to be at least the size of the cache
2376  * block size and have no more than 2^14 discard blocks across the origin.
2377  */
2378 #define MAX_DISCARD_BLOCKS (1 << 14)
2379 
2380 static bool too_many_discard_blocks(sector_t discard_block_size,
2381 				    sector_t origin_size)
2382 {
2383 	(void) sector_div(origin_size, discard_block_size);
2384 
2385 	return origin_size > MAX_DISCARD_BLOCKS;
2386 }
2387 
2388 static sector_t calculate_discard_block_size(sector_t cache_block_size,
2389 					     sector_t origin_size)
2390 {
2391 	sector_t discard_block_size = cache_block_size;
2392 
2393 	if (origin_size)
2394 		while (too_many_discard_blocks(discard_block_size, origin_size))
2395 			discard_block_size *= 2;
2396 
2397 	return discard_block_size;
2398 }
2399 
2400 static void set_cache_size(struct cache *cache, dm_cblock_t size)
2401 {
2402 	dm_block_t nr_blocks = from_cblock(size);
2403 
2404 	if (nr_blocks > (1 << 20) && cache->cache_size != size)
2405 		DMWARN_LIMIT("You have created a cache device with a lot of individual cache blocks (%llu)\n"
2406 			     "All these mappings can consume a lot of kernel memory, and take some time to read/write.\n"
2407 			     "Please consider increasing the cache block size to reduce the overall cache block count.",
2408 			     (unsigned long long) nr_blocks);
2409 
2410 	cache->cache_size = size;
2411 }
2412 
2413 #define DEFAULT_MIGRATION_THRESHOLD 2048
2414 
2415 static int cache_create(struct cache_args *ca, struct cache **result)
2416 {
2417 	int r = 0;
2418 	char **error = &ca->ti->error;
2419 	struct cache *cache;
2420 	struct dm_target *ti = ca->ti;
2421 	dm_block_t origin_blocks;
2422 	struct dm_cache_metadata *cmd;
2423 	bool may_format = ca->features.mode == CM_WRITE;
2424 
2425 	cache = kzalloc_obj(*cache);
2426 	if (!cache)
2427 		return -ENOMEM;
2428 
2429 	cache->ti = ca->ti;
2430 	ti->private = cache;
2431 	ti->accounts_remapped_io = true;
2432 	ti->num_flush_bios = 2;
2433 	ti->flush_supported = true;
2434 
2435 	ti->num_discard_bios = 1;
2436 	ti->discards_supported = true;
2437 
2438 	ti->per_io_data_size = sizeof(struct per_bio_data);
2439 
2440 	cache->features = ca->features;
2441 	if (writethrough_mode(cache)) {
2442 		/* Create bioset for writethrough bios issued to origin */
2443 		r = bioset_init(&cache->bs, BIO_POOL_SIZE, 0, 0);
2444 		if (r)
2445 			goto bad;
2446 	}
2447 
2448 	cache->metadata_dev = ca->metadata_dev;
2449 	cache->origin_dev = ca->origin_dev;
2450 	cache->cache_dev = ca->cache_dev;
2451 
2452 	ca->metadata_dev = ca->origin_dev = ca->cache_dev = NULL;
2453 
2454 	origin_blocks = cache->origin_sectors = ti->len;
2455 	origin_blocks = block_div(origin_blocks, ca->block_size);
2456 	cache->origin_blocks = to_oblock(origin_blocks);
2457 
2458 	cache->sectors_per_block = ca->block_size;
2459 	if (dm_set_target_max_io_len(ti, cache->sectors_per_block)) {
2460 		r = -EINVAL;
2461 		goto bad;
2462 	}
2463 
2464 	if (ca->block_size & (ca->block_size - 1)) {
2465 		dm_block_t cache_size = ca->cache_sectors;
2466 
2467 		cache->sectors_per_block_shift = -1;
2468 		cache_size = block_div(cache_size, ca->block_size);
2469 		set_cache_size(cache, to_cblock(cache_size));
2470 	} else {
2471 		cache->sectors_per_block_shift = __ffs(ca->block_size);
2472 		set_cache_size(cache, to_cblock(ca->cache_sectors >> cache->sectors_per_block_shift));
2473 	}
2474 
2475 	r = create_cache_policy(cache, ca, error);
2476 	if (r)
2477 		goto bad;
2478 
2479 	cache->policy_nr_args = ca->policy_argc;
2480 	cache->migration_threshold = DEFAULT_MIGRATION_THRESHOLD;
2481 
2482 	r = set_config_values(cache, ca->policy_argc, ca->policy_argv);
2483 	if (r) {
2484 		*error = "Error setting cache policy's config values";
2485 		goto bad;
2486 	}
2487 
2488 	cmd = dm_cache_metadata_open(cache->metadata_dev->bdev,
2489 				     ca->block_size, may_format,
2490 				     dm_cache_policy_get_hint_size(cache->policy),
2491 				     ca->features.metadata_version);
2492 	if (IS_ERR(cmd)) {
2493 		*error = "Error creating metadata object";
2494 		r = PTR_ERR(cmd);
2495 		goto bad;
2496 	}
2497 	cache->cmd = cmd;
2498 	set_cache_mode(cache, CM_WRITE);
2499 	if (get_cache_mode(cache) != CM_WRITE) {
2500 		*error = "Unable to get write access to metadata, please check/repair metadata.";
2501 		r = -EINVAL;
2502 		goto bad;
2503 	}
2504 
2505 	if (passthrough_mode(cache))
2506 		policy_allow_migrations(cache->policy, false);
2507 
2508 	spin_lock_init(&cache->lock);
2509 	bio_list_init(&cache->deferred_bios);
2510 	atomic_set(&cache->nr_allocated_migrations, 0);
2511 	atomic_set(&cache->nr_io_migrations, 0);
2512 	init_waitqueue_head(&cache->migration_wait);
2513 
2514 	r = -ENOMEM;
2515 	atomic_set(&cache->nr_dirty, 0);
2516 	cache->dirty_bitset = alloc_bitset(from_cblock(cache->cache_size));
2517 	if (!cache->dirty_bitset) {
2518 		*error = "could not allocate dirty bitset";
2519 		goto bad;
2520 	}
2521 	clear_bitset(cache->dirty_bitset, from_cblock(cache->cache_size));
2522 
2523 	cache->discard_block_size =
2524 		calculate_discard_block_size(cache->sectors_per_block,
2525 					     cache->origin_sectors);
2526 	cache->discard_nr_blocks = to_dblock(dm_sector_div_up(cache->origin_sectors,
2527 							      cache->discard_block_size));
2528 	cache->discard_bitset = alloc_bitset(from_dblock(cache->discard_nr_blocks));
2529 	if (!cache->discard_bitset) {
2530 		*error = "could not allocate discard bitset";
2531 		goto bad;
2532 	}
2533 	clear_bitset(cache->discard_bitset, from_dblock(cache->discard_nr_blocks));
2534 
2535 	cache->invalid_bitset = alloc_bitset(from_cblock(cache->cache_size));
2536 	if (!cache->invalid_bitset) {
2537 		*error = "could not allocate bitset for invalid blocks";
2538 		goto bad;
2539 	}
2540 	clear_bitset(cache->invalid_bitset, from_cblock(cache->cache_size));
2541 
2542 	cache->copier = dm_kcopyd_client_create(&dm_kcopyd_throttle);
2543 	if (IS_ERR(cache->copier)) {
2544 		*error = "could not create kcopyd client";
2545 		r = PTR_ERR(cache->copier);
2546 		goto bad;
2547 	}
2548 
2549 	cache->wq = alloc_workqueue("dm-" DM_MSG_PREFIX,
2550 				    WQ_MEM_RECLAIM | WQ_PERCPU, 0);
2551 	if (!cache->wq) {
2552 		*error = "could not create workqueue for metadata object";
2553 		goto bad;
2554 	}
2555 	INIT_WORK(&cache->deferred_bio_worker, process_deferred_bios);
2556 	INIT_WORK(&cache->migration_worker, check_migrations);
2557 	INIT_DELAYED_WORK(&cache->waker, do_waker);
2558 
2559 	cache->prison = dm_bio_prison_create_v2(cache->wq);
2560 	if (!cache->prison) {
2561 		*error = "could not create bio prison";
2562 		goto bad;
2563 	}
2564 
2565 	r = mempool_init_slab_pool(&cache->migration_pool, MIGRATION_POOL_SIZE,
2566 				   migration_cache);
2567 	if (r) {
2568 		*error = "Error creating cache's migration mempool";
2569 		goto bad;
2570 	}
2571 
2572 	cache->need_tick_bio = true;
2573 	cache->sized = false;
2574 	cache->invalidate = false;
2575 	cache->commit_requested = false;
2576 	cache->loaded_mappings = false;
2577 	cache->loaded_discards = false;
2578 
2579 	load_stats(cache);
2580 
2581 	atomic_set(&cache->stats.demotion, 0);
2582 	atomic_set(&cache->stats.promotion, 0);
2583 	atomic_set(&cache->stats.copies_avoided, 0);
2584 	atomic_set(&cache->stats.cache_cell_clash, 0);
2585 	atomic_set(&cache->stats.commit_count, 0);
2586 	atomic_set(&cache->stats.discard_count, 0);
2587 
2588 	spin_lock_init(&cache->invalidation_lock);
2589 	INIT_LIST_HEAD(&cache->invalidation_requests);
2590 
2591 	batcher_init(&cache->committer, commit_op, cache,
2592 		     issue_op, cache, cache->wq);
2593 	dm_iot_init(&cache->tracker);
2594 
2595 	init_rwsem(&cache->background_work_lock);
2596 	prevent_background_work(cache);
2597 
2598 	*result = cache;
2599 	return 0;
2600 bad:
2601 	__destroy(cache);
2602 	return r;
2603 }
2604 
2605 static int copy_ctr_args(struct cache *cache, int argc, const char **argv)
2606 {
2607 	unsigned int i;
2608 	const char **copy;
2609 
2610 	copy = kcalloc(argc, sizeof(*copy), GFP_KERNEL);
2611 	if (!copy)
2612 		return -ENOMEM;
2613 	for (i = 0; i < argc; i++) {
2614 		copy[i] = kstrdup(argv[i], GFP_KERNEL);
2615 		if (!copy[i]) {
2616 			while (i--)
2617 				kfree(copy[i]);
2618 			kfree(copy);
2619 			return -ENOMEM;
2620 		}
2621 	}
2622 
2623 	cache->nr_ctr_args = argc;
2624 	cache->ctr_args = copy;
2625 
2626 	return 0;
2627 }
2628 
2629 static int cache_ctr(struct dm_target *ti, unsigned int argc, char **argv)
2630 {
2631 	int r = -EINVAL;
2632 	struct cache_args *ca;
2633 	struct cache *cache = NULL;
2634 
2635 	ca = kzalloc_obj(*ca);
2636 	if (!ca) {
2637 		ti->error = "Error allocating memory for cache";
2638 		return -ENOMEM;
2639 	}
2640 	ca->ti = ti;
2641 
2642 	r = parse_cache_args(ca, argc, argv, &ti->error);
2643 	if (r)
2644 		goto out;
2645 
2646 	r = cache_create(ca, &cache);
2647 	if (r)
2648 		goto out;
2649 
2650 	r = copy_ctr_args(cache, argc - 3, (const char **)argv + 3);
2651 	if (r) {
2652 		__destroy(cache);
2653 		goto out;
2654 	}
2655 
2656 	ti->private = cache;
2657 out:
2658 	destroy_cache_args(ca);
2659 	return r;
2660 }
2661 
2662 /*----------------------------------------------------------------*/
2663 
2664 static int cache_map(struct dm_target *ti, struct bio *bio)
2665 {
2666 	struct cache *cache = ti->private;
2667 
2668 	int r;
2669 	bool commit_needed;
2670 	dm_oblock_t block = get_bio_block(cache, bio);
2671 
2672 	init_per_bio_data(bio);
2673 	if (unlikely(from_oblock(block) >= from_oblock(cache->origin_blocks))) {
2674 		/*
2675 		 * This can only occur if the io goes to a partial block at
2676 		 * the end of the origin device.  We don't cache these.
2677 		 * Just remap to the origin and carry on.
2678 		 */
2679 		remap_to_origin(cache, bio);
2680 		accounted_begin(cache, bio);
2681 		return DM_MAPIO_REMAPPED;
2682 	}
2683 
2684 	if (discard_or_flush(bio)) {
2685 		defer_bio(cache, bio);
2686 		return DM_MAPIO_SUBMITTED;
2687 	}
2688 
2689 	r = map_bio(cache, bio, block, &commit_needed);
2690 	if (commit_needed)
2691 		schedule_commit(&cache->committer);
2692 
2693 	return r;
2694 }
2695 
2696 static int cache_end_io(struct dm_target *ti, struct bio *bio, blk_status_t *error)
2697 {
2698 	struct cache *cache = ti->private;
2699 	unsigned long flags;
2700 	struct per_bio_data *pb = get_per_bio_data(bio);
2701 
2702 	if (pb->tick) {
2703 		policy_tick(cache->policy, false);
2704 
2705 		spin_lock_irqsave(&cache->lock, flags);
2706 		cache->need_tick_bio = true;
2707 		spin_unlock_irqrestore(&cache->lock, flags);
2708 	}
2709 
2710 	bio_drop_shared_lock(cache, bio);
2711 	accounted_complete(cache, bio);
2712 
2713 	return DM_ENDIO_DONE;
2714 }
2715 
2716 static int write_dirty_bitset(struct cache *cache)
2717 {
2718 	int r;
2719 
2720 	if (get_cache_mode(cache) >= CM_READ_ONLY)
2721 		return -EINVAL;
2722 
2723 	r = dm_cache_set_dirty_bits(cache->cmd, from_cblock(cache->cache_size), cache->dirty_bitset);
2724 	if (r)
2725 		metadata_operation_failed(cache, "dm_cache_set_dirty_bits", r);
2726 
2727 	return r;
2728 }
2729 
2730 static int write_discard_bitset(struct cache *cache)
2731 {
2732 	unsigned int i, r;
2733 
2734 	if (get_cache_mode(cache) >= CM_READ_ONLY)
2735 		return -EINVAL;
2736 
2737 	r = dm_cache_discard_bitset_resize(cache->cmd, cache->discard_block_size,
2738 					   cache->discard_nr_blocks);
2739 	if (r) {
2740 		DMERR("%s: could not resize on-disk discard bitset", cache_device_name(cache));
2741 		metadata_operation_failed(cache, "dm_cache_discard_bitset_resize", r);
2742 		return r;
2743 	}
2744 
2745 	for (i = 0; i < from_dblock(cache->discard_nr_blocks); i++) {
2746 		r = dm_cache_set_discard(cache->cmd, to_dblock(i),
2747 					 is_discarded(cache, to_dblock(i)));
2748 		if (r) {
2749 			metadata_operation_failed(cache, "dm_cache_set_discard", r);
2750 			return r;
2751 		}
2752 	}
2753 
2754 	return 0;
2755 }
2756 
2757 static int write_hints(struct cache *cache)
2758 {
2759 	int r;
2760 
2761 	if (get_cache_mode(cache) >= CM_READ_ONLY)
2762 		return -EINVAL;
2763 
2764 	r = dm_cache_write_hints(cache->cmd, cache->policy);
2765 	if (r) {
2766 		metadata_operation_failed(cache, "dm_cache_write_hints", r);
2767 		return r;
2768 	}
2769 
2770 	return 0;
2771 }
2772 
2773 /*
2774  * returns true on success
2775  */
2776 static bool sync_metadata(struct cache *cache)
2777 {
2778 	int r1, r2, r3, r4;
2779 
2780 	r1 = write_dirty_bitset(cache);
2781 	if (r1)
2782 		DMERR("%s: could not write dirty bitset", cache_device_name(cache));
2783 
2784 	r2 = write_discard_bitset(cache);
2785 	if (r2)
2786 		DMERR("%s: could not write discard bitset", cache_device_name(cache));
2787 
2788 	save_stats(cache);
2789 
2790 	r3 = write_hints(cache);
2791 	if (r3)
2792 		DMERR("%s: could not write hints", cache_device_name(cache));
2793 
2794 	/*
2795 	 * If writing the above metadata failed, we still commit, but don't
2796 	 * set the clean shutdown flag.  This will effectively force every
2797 	 * dirty bit to be set on reload.
2798 	 */
2799 	r4 = commit(cache, !r1 && !r2 && !r3);
2800 	if (r4)
2801 		DMERR("%s: could not write cache metadata", cache_device_name(cache));
2802 
2803 	return !r1 && !r2 && !r3 && !r4;
2804 }
2805 
2806 static void cache_postsuspend(struct dm_target *ti)
2807 {
2808 	struct cache *cache = ti->private;
2809 
2810 	prevent_background_work(cache);
2811 	BUG_ON(atomic_read(&cache->nr_io_migrations));
2812 
2813 	cancel_delayed_work_sync(&cache->waker);
2814 	drain_workqueue(cache->wq);
2815 	WARN_ON(cache->tracker.in_flight);
2816 
2817 	/*
2818 	 * If it's a flush suspend there won't be any deferred bios, so this
2819 	 * call is harmless.
2820 	 */
2821 	requeue_deferred_bios(cache);
2822 
2823 	if (get_cache_mode(cache) == CM_WRITE)
2824 		(void) sync_metadata(cache);
2825 }
2826 
2827 static int load_mapping(void *context, dm_oblock_t oblock, dm_cblock_t cblock,
2828 			bool dirty, uint32_t hint, bool hint_valid)
2829 {
2830 	struct cache *cache = context;
2831 
2832 	if (dirty) {
2833 		if (passthrough_mode(cache)) {
2834 			DMERR("%s: cannot enter passthrough mode unless all blocks are clean",
2835 			      cache_device_name(cache));
2836 			return -EBUSY;
2837 		}
2838 
2839 		set_bit(from_cblock(cblock), cache->dirty_bitset);
2840 		atomic_inc(&cache->nr_dirty);
2841 	} else
2842 		clear_bit(from_cblock(cblock), cache->dirty_bitset);
2843 
2844 	return policy_load_mapping(cache->policy, oblock, cblock, dirty, hint, hint_valid);
2845 }
2846 
2847 static int load_filtered_mapping(void *context, dm_oblock_t oblock, dm_cblock_t cblock,
2848 				 bool dirty, uint32_t hint, bool hint_valid)
2849 {
2850 	struct cache *cache = context;
2851 
2852 	if (from_oblock(oblock) >= from_oblock(cache->origin_blocks)) {
2853 		if (dirty) {
2854 			DMERR("%s: unable to shrink origin; cache block %u is dirty",
2855 			      cache_device_name(cache), from_cblock(cblock));
2856 			return -EFBIG;
2857 		}
2858 		set_bit(from_cblock(cblock), cache->invalid_bitset);
2859 		return 0;
2860 	}
2861 
2862 	return load_mapping(context, oblock, cblock, dirty, hint, hint_valid);
2863 }
2864 
2865 /*
2866  * The discard block size in the on disk metadata is not
2867  * necessarily the same as we're currently using.  So we have to
2868  * be careful to only set the discarded attribute if we know it
2869  * covers a complete block of the new size.
2870  */
2871 struct discard_load_info {
2872 	struct cache *cache;
2873 
2874 	/*
2875 	 * These blocks are sized using the on disk dblock size, rather
2876 	 * than the current one.
2877 	 */
2878 	dm_block_t block_size;
2879 	dm_block_t discard_begin, discard_end;
2880 };
2881 
2882 static void discard_load_info_init(struct cache *cache,
2883 				   struct discard_load_info *li)
2884 {
2885 	li->cache = cache;
2886 	li->discard_begin = li->discard_end = 0;
2887 }
2888 
2889 static void set_discard_range(struct discard_load_info *li)
2890 {
2891 	sector_t b, e;
2892 
2893 	if (li->discard_begin == li->discard_end)
2894 		return;
2895 
2896 	/*
2897 	 * Convert to sectors.
2898 	 */
2899 	b = li->discard_begin * li->block_size;
2900 	e = li->discard_end * li->block_size;
2901 
2902 	/*
2903 	 * Then convert back to the current dblock size.
2904 	 */
2905 	b = dm_sector_div_up(b, li->cache->discard_block_size);
2906 	sector_div(e, li->cache->discard_block_size);
2907 
2908 	/*
2909 	 * The origin may have shrunk, so we need to check we're still in
2910 	 * bounds.
2911 	 */
2912 	if (e > from_dblock(li->cache->discard_nr_blocks))
2913 		e = from_dblock(li->cache->discard_nr_blocks);
2914 
2915 	for (; b < e; b++)
2916 		set_discard(li->cache, to_dblock(b));
2917 }
2918 
2919 static int load_discard(void *context, sector_t discard_block_size,
2920 			dm_dblock_t dblock, bool discard)
2921 {
2922 	struct discard_load_info *li = context;
2923 
2924 	li->block_size = discard_block_size;
2925 
2926 	if (discard) {
2927 		if (from_dblock(dblock) == li->discard_end)
2928 			/*
2929 			 * We're already in a discard range, just extend it.
2930 			 */
2931 			li->discard_end = li->discard_end + 1ULL;
2932 
2933 		else {
2934 			/*
2935 			 * Emit the old range and start a new one.
2936 			 */
2937 			set_discard_range(li);
2938 			li->discard_begin = from_dblock(dblock);
2939 			li->discard_end = li->discard_begin + 1ULL;
2940 		}
2941 	} else {
2942 		set_discard_range(li);
2943 		li->discard_begin = li->discard_end = 0;
2944 	}
2945 
2946 	return 0;
2947 }
2948 
2949 static dm_cblock_t get_cache_dev_size(struct cache *cache)
2950 {
2951 	sector_t size = get_dev_size(cache->cache_dev);
2952 	(void) sector_div(size, cache->sectors_per_block);
2953 	return to_cblock(size);
2954 }
2955 
2956 static bool can_resume(struct cache *cache)
2957 {
2958 	bool clean_when_opened;
2959 	int r;
2960 
2961 	/*
2962 	 * Disallow retrying the resume operation for devices that failed the
2963 	 * first resume attempt, as the failure leaves the policy object partially
2964 	 * initialized. Retrying could trigger BUG_ON when loading cache mappings
2965 	 * into the incomplete policy object.
2966 	 */
2967 	if (cache->sized && !cache->loaded_mappings) {
2968 		if (get_cache_mode(cache) != CM_WRITE)
2969 			DMERR("%s: unable to resume a failed-loaded cache, please check metadata.",
2970 			      cache_device_name(cache));
2971 		else
2972 			DMERR("%s: unable to resume cache due to missing proper cache table reload",
2973 			      cache_device_name(cache));
2974 		return false;
2975 	}
2976 
2977 	if (passthrough_mode(cache)) {
2978 		r = dm_cache_metadata_clean_when_opened(cache->cmd, &clean_when_opened);
2979 		if (r) {
2980 			DMERR("%s: failed to query metadata flags", cache_device_name(cache));
2981 			return false;
2982 		}
2983 
2984 		if (!clean_when_opened) {
2985 			DMERR("%s: unable to resume into passthrough mode after unclean shutdown",
2986 			      cache_device_name(cache));
2987 			return false;
2988 		}
2989 	}
2990 
2991 	return true;
2992 }
2993 
2994 static bool can_resize(struct cache *cache, dm_cblock_t new_size)
2995 {
2996 	if (from_cblock(new_size) > from_cblock(cache->cache_size)) {
2997 		DMERR("%s: unable to extend cache due to missing cache table reload",
2998 		      cache_device_name(cache));
2999 		return false;
3000 	}
3001 
3002 	/*
3003 	 * We can't drop a dirty block when shrinking the cache.
3004 	 */
3005 	if (cache->loaded_mappings) {
3006 		new_size = to_cblock(find_next_bit(cache->dirty_bitset,
3007 						   from_cblock(cache->cache_size),
3008 						   from_cblock(new_size)));
3009 		if (new_size != cache->cache_size) {
3010 			DMERR("%s: unable to shrink cache; cache block %llu is dirty",
3011 			      cache_device_name(cache),
3012 			      (unsigned long long) from_cblock(new_size));
3013 			return false;
3014 		}
3015 	}
3016 
3017 	return true;
3018 }
3019 
3020 static int resize_cache_dev(struct cache *cache, dm_cblock_t new_size)
3021 {
3022 	int r;
3023 
3024 	r = dm_cache_resize(cache->cmd, new_size);
3025 	if (r) {
3026 		DMERR("%s: could not resize cache metadata", cache_device_name(cache));
3027 		metadata_operation_failed(cache, "dm_cache_resize", r);
3028 		return r;
3029 	}
3030 
3031 	set_cache_size(cache, new_size);
3032 
3033 	return 0;
3034 }
3035 
3036 static int truncate_oblocks(struct cache *cache)
3037 {
3038 	uint32_t nr_blocks = from_cblock(cache->cache_size);
3039 	uint32_t i;
3040 	int r;
3041 
3042 	for_each_set_bit(i, cache->invalid_bitset, nr_blocks) {
3043 		r = dm_cache_remove_mapping(cache->cmd, to_cblock(i));
3044 		if (r) {
3045 			DMERR_LIMIT("%s: invalidation failed; couldn't update on disk metadata",
3046 				    cache_device_name(cache));
3047 			return r;
3048 		}
3049 	}
3050 
3051 	return 0;
3052 }
3053 
3054 static int cache_preresume(struct dm_target *ti)
3055 {
3056 	int r = 0;
3057 	struct cache *cache = ti->private;
3058 	dm_cblock_t csize = get_cache_dev_size(cache);
3059 
3060 	if (!can_resume(cache))
3061 		return -EINVAL;
3062 
3063 	/*
3064 	 * Check to see if the cache has resized.
3065 	 */
3066 	if (!cache->sized || csize != cache->cache_size) {
3067 		if (!can_resize(cache, csize))
3068 			return -EINVAL;
3069 
3070 		r = resize_cache_dev(cache, csize);
3071 		if (r)
3072 			return r;
3073 
3074 		cache->sized = true;
3075 	}
3076 
3077 	if (!cache->loaded_mappings) {
3078 		/*
3079 		 * The fast device could have been resized since the last
3080 		 * failed preresume attempt.  To be safe we start by a blank
3081 		 * bitset for cache blocks.
3082 		 */
3083 		clear_bitset(cache->invalid_bitset, from_cblock(cache->cache_size));
3084 
3085 		r = dm_cache_load_mappings(cache->cmd, cache->policy,
3086 					   load_filtered_mapping, cache);
3087 		if (r) {
3088 			DMERR("%s: could not load cache mappings", cache_device_name(cache));
3089 			if (r != -EFBIG && r != -EBUSY)
3090 				metadata_operation_failed(cache, "dm_cache_load_mappings", r);
3091 			return r;
3092 		}
3093 
3094 		r = truncate_oblocks(cache);
3095 		if (r) {
3096 			metadata_operation_failed(cache, "dm_cache_remove_mapping", r);
3097 			return r;
3098 		}
3099 
3100 		cache->loaded_mappings = true;
3101 	}
3102 
3103 	if (!cache->loaded_discards) {
3104 		struct discard_load_info li;
3105 
3106 		/*
3107 		 * The discard bitset could have been resized, or the
3108 		 * discard block size changed.  To be safe we start by
3109 		 * setting every dblock to not discarded.
3110 		 */
3111 		clear_bitset(cache->discard_bitset, from_dblock(cache->discard_nr_blocks));
3112 
3113 		discard_load_info_init(cache, &li);
3114 		r = dm_cache_load_discards(cache->cmd, load_discard, &li);
3115 		if (r) {
3116 			DMERR("%s: could not load origin discards", cache_device_name(cache));
3117 			metadata_operation_failed(cache, "dm_cache_load_discards", r);
3118 			return r;
3119 		}
3120 		set_discard_range(&li);
3121 
3122 		cache->loaded_discards = true;
3123 	}
3124 
3125 	return r;
3126 }
3127 
3128 static void cache_resume(struct dm_target *ti)
3129 {
3130 	struct cache *cache = ti->private;
3131 
3132 	cache->need_tick_bio = true;
3133 	allow_background_work(cache);
3134 	do_waker(&cache->waker.work);
3135 }
3136 
3137 static void emit_flags(struct cache *cache, char *result,
3138 		       unsigned int maxlen, ssize_t *sz_ptr)
3139 {
3140 	ssize_t sz = *sz_ptr;
3141 	struct cache_features *cf = &cache->features;
3142 	unsigned int count = (cf->metadata_version == 2) + !cf->discard_passdown + 1;
3143 
3144 	DMEMIT("%u ", count);
3145 
3146 	if (cf->metadata_version == 2)
3147 		DMEMIT("metadata2 ");
3148 
3149 	if (writethrough_mode(cache))
3150 		DMEMIT("writethrough ");
3151 
3152 	else if (passthrough_mode(cache))
3153 		DMEMIT("passthrough ");
3154 
3155 	else if (writeback_mode(cache))
3156 		DMEMIT("writeback ");
3157 
3158 	else {
3159 		DMEMIT("unknown ");
3160 		DMERR("%s: internal error: unknown io mode: %d",
3161 		      cache_device_name(cache), (int) cf->io_mode);
3162 	}
3163 
3164 	if (!cf->discard_passdown)
3165 		DMEMIT("no_discard_passdown ");
3166 
3167 	*sz_ptr = sz;
3168 }
3169 
3170 /*
3171  * Status format:
3172  *
3173  * <metadata block size> <#used metadata blocks>/<#total metadata blocks>
3174  * <cache block size> <#used cache blocks>/<#total cache blocks>
3175  * <#read hits> <#read misses> <#write hits> <#write misses>
3176  * <#demotions> <#promotions> <#dirty>
3177  * <#features> <features>*
3178  * <#core args> <core args>
3179  * <policy name> <#policy args> <policy args>* <cache metadata mode> <needs_check>
3180  */
3181 static void cache_status(struct dm_target *ti, status_type_t type,
3182 			 unsigned int status_flags, char *result, unsigned int maxlen)
3183 {
3184 	int r = 0;
3185 	unsigned int i;
3186 	ssize_t sz = 0;
3187 	dm_block_t nr_free_blocks_metadata = 0;
3188 	dm_block_t nr_blocks_metadata = 0;
3189 	char buf[BDEVNAME_SIZE];
3190 	struct cache *cache = ti->private;
3191 	dm_cblock_t residency;
3192 	bool needs_check;
3193 
3194 	switch (type) {
3195 	case STATUSTYPE_INFO:
3196 		if (get_cache_mode(cache) == CM_FAIL) {
3197 			DMEMIT("Fail");
3198 			break;
3199 		}
3200 
3201 		/* Commit to ensure statistics aren't out-of-date */
3202 		if (!(status_flags & DM_STATUS_NOFLUSH_FLAG) && !dm_suspended(ti))
3203 			(void) commit(cache, false);
3204 
3205 		r = dm_cache_get_free_metadata_block_count(cache->cmd, &nr_free_blocks_metadata);
3206 		if (r) {
3207 			DMERR("%s: dm_cache_get_free_metadata_block_count returned %d",
3208 			      cache_device_name(cache), r);
3209 			goto err;
3210 		}
3211 
3212 		r = dm_cache_get_metadata_dev_size(cache->cmd, &nr_blocks_metadata);
3213 		if (r) {
3214 			DMERR("%s: dm_cache_get_metadata_dev_size returned %d",
3215 			      cache_device_name(cache), r);
3216 			goto err;
3217 		}
3218 
3219 		residency = policy_residency(cache->policy);
3220 
3221 		DMEMIT("%u %llu/%llu %llu %llu/%llu %u %u %u %u %u %u %lu ",
3222 		       (unsigned int)DM_CACHE_METADATA_BLOCK_SIZE,
3223 		       (unsigned long long)(nr_blocks_metadata - nr_free_blocks_metadata),
3224 		       (unsigned long long)nr_blocks_metadata,
3225 		       (unsigned long long)cache->sectors_per_block,
3226 		       (unsigned long long) from_cblock(residency),
3227 		       (unsigned long long) from_cblock(cache->cache_size),
3228 		       (unsigned int) atomic_read(&cache->stats.read_hit),
3229 		       (unsigned int) atomic_read(&cache->stats.read_miss),
3230 		       (unsigned int) atomic_read(&cache->stats.write_hit),
3231 		       (unsigned int) atomic_read(&cache->stats.write_miss),
3232 		       (unsigned int) atomic_read(&cache->stats.demotion),
3233 		       (unsigned int) atomic_read(&cache->stats.promotion),
3234 		       (unsigned long) atomic_read(&cache->nr_dirty));
3235 
3236 		emit_flags(cache, result, maxlen, &sz);
3237 
3238 		DMEMIT("2 migration_threshold %llu ", (unsigned long long) cache->migration_threshold);
3239 
3240 		DMEMIT("%s ", dm_cache_policy_get_name(cache->policy));
3241 		if (sz < maxlen) {
3242 			r = policy_emit_config_values(cache->policy, result, maxlen, &sz);
3243 			if (r)
3244 				DMERR("%s: policy_emit_config_values returned %d",
3245 				      cache_device_name(cache), r);
3246 		}
3247 
3248 		if (get_cache_mode(cache) == CM_READ_ONLY)
3249 			DMEMIT("ro ");
3250 		else
3251 			DMEMIT("rw ");
3252 
3253 		r = dm_cache_metadata_needs_check(cache->cmd, &needs_check);
3254 
3255 		if (r || needs_check)
3256 			DMEMIT("needs_check ");
3257 		else
3258 			DMEMIT("- ");
3259 
3260 		break;
3261 
3262 	case STATUSTYPE_TABLE:
3263 		format_dev_t(buf, cache->metadata_dev->bdev->bd_dev);
3264 		DMEMIT("%s ", buf);
3265 		format_dev_t(buf, cache->cache_dev->bdev->bd_dev);
3266 		DMEMIT("%s ", buf);
3267 		format_dev_t(buf, cache->origin_dev->bdev->bd_dev);
3268 		DMEMIT("%s", buf);
3269 
3270 		for (i = 0; i < cache->nr_ctr_args - 1; i++)
3271 			DMEMIT(" %s", cache->ctr_args[i]);
3272 		if (cache->nr_ctr_args)
3273 			DMEMIT(" %s", cache->ctr_args[cache->nr_ctr_args - 1]);
3274 		break;
3275 
3276 	case STATUSTYPE_IMA:
3277 		DMEMIT_TARGET_NAME_VERSION(ti->type);
3278 		if (get_cache_mode(cache) == CM_FAIL)
3279 			DMEMIT(",metadata_mode=fail");
3280 		else if (get_cache_mode(cache) == CM_READ_ONLY)
3281 			DMEMIT(",metadata_mode=ro");
3282 		else
3283 			DMEMIT(",metadata_mode=rw");
3284 
3285 		format_dev_t(buf, cache->metadata_dev->bdev->bd_dev);
3286 		DMEMIT(",cache_metadata_device=%s", buf);
3287 		format_dev_t(buf, cache->cache_dev->bdev->bd_dev);
3288 		DMEMIT(",cache_device=%s", buf);
3289 		format_dev_t(buf, cache->origin_dev->bdev->bd_dev);
3290 		DMEMIT(",cache_origin_device=%s", buf);
3291 		DMEMIT(",writethrough=%c", writethrough_mode(cache) ? 'y' : 'n');
3292 		DMEMIT(",writeback=%c", writeback_mode(cache) ? 'y' : 'n');
3293 		DMEMIT(",passthrough=%c", passthrough_mode(cache) ? 'y' : 'n');
3294 		DMEMIT(",metadata2=%c", cache->features.metadata_version == 2 ? 'y' : 'n');
3295 		DMEMIT(",no_discard_passdown=%c", cache->features.discard_passdown ? 'n' : 'y');
3296 		DMEMIT(";");
3297 		break;
3298 	}
3299 
3300 	return;
3301 
3302 err:
3303 	DMEMIT("Error");
3304 }
3305 
3306 /*
3307  * Defines a range of cblocks, begin to (end - 1) are in the range.  end is
3308  * the one-past-the-end value.
3309  */
3310 struct cblock_range {
3311 	dm_cblock_t begin;
3312 	dm_cblock_t end;
3313 };
3314 
3315 static inline dm_cblock_t cblock_succ(dm_cblock_t b)
3316 {
3317 	return to_cblock(from_cblock(b) + 1);
3318 }
3319 
3320 /*
3321  * A cache block range can take two forms:
3322  *
3323  * i) A single cblock, eg. '3456'
3324  * ii) A begin and end cblock with a dash between, eg. 123-234
3325  */
3326 static int parse_cblock_range(struct cache *cache, char *str,
3327 			      struct cblock_range *result)
3328 {
3329 	char *blocknr = strsep(&str, "-");
3330 	unsigned int b, e;
3331 	int r;
3332 
3333 	r = kstrtouint(blocknr, 10, &b);
3334 	if (r)
3335 		goto bad;
3336 
3337 	result->begin = to_cblock(b);
3338 
3339 	if (str) {
3340 		blocknr = str;
3341 
3342 		r = kstrtouint(blocknr, 10, &e);
3343 		if (r)
3344 			goto bad;
3345 
3346 		result->end = to_cblock(e);
3347 	} else {
3348 		result->end = cblock_succ(result->begin);
3349 	}
3350 
3351 	return 0;
3352 
3353 bad:
3354 	DMERR("%s: invalid cblock range '%s'", cache_device_name(cache), blocknr);
3355 	return -EINVAL;
3356 }
3357 
3358 static int validate_cblock_range(struct cache *cache, struct cblock_range *range)
3359 {
3360 	uint64_t b = from_cblock(range->begin);
3361 	uint64_t e = from_cblock(range->end);
3362 	uint64_t n = from_cblock(cache->cache_size);
3363 
3364 	if (b >= n) {
3365 		DMERR("%s: begin cblock out of range: %llu >= %llu",
3366 		      cache_device_name(cache), b, n);
3367 		return -EINVAL;
3368 	}
3369 
3370 	if (e > n) {
3371 		DMERR("%s: end cblock out of range: %llu > %llu",
3372 		      cache_device_name(cache), e, n);
3373 		return -EINVAL;
3374 	}
3375 
3376 	if (b >= e) {
3377 		DMERR("%s: invalid cblock range: %llu >= %llu",
3378 		      cache_device_name(cache), b, e);
3379 		return -EINVAL;
3380 	}
3381 
3382 	return 0;
3383 }
3384 
3385 static int request_invalidation(struct cache *cache, struct cblock_range *range)
3386 {
3387 	int r = 0;
3388 
3389 	/*
3390 	 * We don't need to do any locking here because we know we're in
3391 	 * passthrough mode.  There's is potential for a race between an
3392 	 * invalidation triggered by an io and an invalidation message.  This
3393 	 * is harmless, we must not worry if the policy call fails.
3394 	 */
3395 	while (range->begin != range->end) {
3396 		r = invalidate_cblock(cache, range->begin);
3397 		if (r)
3398 			return r;
3399 
3400 		range->begin = cblock_succ(range->begin);
3401 	}
3402 
3403 	cache->commit_requested = true;
3404 	return r;
3405 }
3406 
3407 static int process_invalidate_cblocks_message(struct cache *cache, unsigned int count,
3408 					      char **cblock_ranges)
3409 {
3410 	int r = 0;
3411 	unsigned int i;
3412 	struct cblock_range range;
3413 
3414 	if (!passthrough_mode(cache)) {
3415 		DMERR("%s: cache has to be in passthrough mode for invalidation",
3416 		      cache_device_name(cache));
3417 		return -EPERM;
3418 	}
3419 
3420 	for (i = 0; i < count; i++) {
3421 		r = parse_cblock_range(cache, cblock_ranges[i], &range);
3422 		if (r)
3423 			break;
3424 
3425 		r = validate_cblock_range(cache, &range);
3426 		if (r)
3427 			break;
3428 
3429 		/*
3430 		 * Pass begin and end origin blocks to the worker and wake it.
3431 		 */
3432 		r = request_invalidation(cache, &range);
3433 		if (r)
3434 			break;
3435 	}
3436 
3437 	return r;
3438 }
3439 
3440 /*
3441  * Supports
3442  *	"<key> <value>"
3443  * and
3444  *     "invalidate_cblocks [(<begin>)|(<begin>-<end>)]*
3445  *
3446  * The key migration_threshold is supported by the cache target core.
3447  */
3448 static int cache_message(struct dm_target *ti, unsigned int argc, char **argv,
3449 			 char *result, unsigned int maxlen)
3450 {
3451 	struct cache *cache = ti->private;
3452 
3453 	if (!argc)
3454 		return -EINVAL;
3455 
3456 	if (get_cache_mode(cache) >= CM_READ_ONLY) {
3457 		DMERR("%s: unable to service cache target messages in READ_ONLY or FAIL mode",
3458 		      cache_device_name(cache));
3459 		return -EOPNOTSUPP;
3460 	}
3461 
3462 	if (!strcasecmp(argv[0], "invalidate_cblocks"))
3463 		return process_invalidate_cblocks_message(cache, argc - 1, argv + 1);
3464 
3465 	if (argc != 2)
3466 		return -EINVAL;
3467 
3468 	return set_config_value(cache, argv[0], argv[1]);
3469 }
3470 
3471 static int cache_iterate_devices(struct dm_target *ti,
3472 				 iterate_devices_callout_fn fn, void *data)
3473 {
3474 	int r = 0;
3475 	struct cache *cache = ti->private;
3476 
3477 	r = fn(ti, cache->cache_dev, 0, get_dev_size(cache->cache_dev), data);
3478 	if (!r)
3479 		r = fn(ti, cache->origin_dev, 0, ti->len, data);
3480 
3481 	return r;
3482 }
3483 
3484 /*
3485  * If discard_passdown was enabled verify that the origin device
3486  * supports discards.  Disable discard_passdown if not.
3487  */
3488 static void disable_passdown_if_not_supported(struct cache *cache)
3489 {
3490 	struct block_device *origin_bdev = cache->origin_dev->bdev;
3491 	struct queue_limits *origin_limits = bdev_limits(origin_bdev);
3492 	const char *reason = NULL;
3493 
3494 	if (!cache->features.discard_passdown)
3495 		return;
3496 
3497 	if (!bdev_max_discard_sectors(origin_bdev))
3498 		reason = "discard unsupported";
3499 
3500 	else if (origin_limits->max_discard_sectors < cache->sectors_per_block)
3501 		reason = "max discard sectors smaller than a block";
3502 
3503 	if (reason) {
3504 		DMWARN("Origin device (%pg) %s: Disabling discard passdown.",
3505 		       origin_bdev, reason);
3506 		cache->features.discard_passdown = false;
3507 	}
3508 }
3509 
3510 static void set_discard_limits(struct cache *cache, struct queue_limits *limits)
3511 {
3512 	struct block_device *origin_bdev = cache->origin_dev->bdev;
3513 	struct queue_limits *origin_limits = bdev_limits(origin_bdev);
3514 
3515 	if (!cache->features.discard_passdown) {
3516 		/* No passdown is done so setting own virtual limits */
3517 		limits->max_hw_discard_sectors = min_t(sector_t, cache->discard_block_size * 1024,
3518 						       cache->origin_sectors);
3519 		limits->discard_granularity = cache->discard_block_size << SECTOR_SHIFT;
3520 		return;
3521 	}
3522 
3523 	/*
3524 	 * cache_iterate_devices() is stacking both origin and fast device limits
3525 	 * but discards aren't passed to fast device, so inherit origin's limits.
3526 	 */
3527 	limits->max_hw_discard_sectors = origin_limits->max_hw_discard_sectors;
3528 	limits->discard_granularity = origin_limits->discard_granularity;
3529 	limits->discard_alignment = origin_limits->discard_alignment;
3530 }
3531 
3532 static void cache_io_hints(struct dm_target *ti, struct queue_limits *limits)
3533 {
3534 	struct cache *cache = ti->private;
3535 	uint64_t io_opt_sectors = limits->io_opt >> SECTOR_SHIFT;
3536 
3537 	/*
3538 	 * If the system-determined stacked limits are compatible with the
3539 	 * cache's blocksize (io_opt is a factor) do not override them.
3540 	 */
3541 	if (io_opt_sectors < cache->sectors_per_block ||
3542 	    do_div(io_opt_sectors, cache->sectors_per_block)) {
3543 		limits->io_min = cache->sectors_per_block << SECTOR_SHIFT;
3544 		limits->io_opt = cache->sectors_per_block << SECTOR_SHIFT;
3545 	}
3546 
3547 	disable_passdown_if_not_supported(cache);
3548 	set_discard_limits(cache, limits);
3549 }
3550 
3551 /*----------------------------------------------------------------*/
3552 
3553 static struct target_type cache_target = {
3554 	.name = "cache",
3555 	.version = {2, 4, 0},
3556 	.module = THIS_MODULE,
3557 	.ctr = cache_ctr,
3558 	.dtr = cache_dtr,
3559 	.map = cache_map,
3560 	.end_io = cache_end_io,
3561 	.postsuspend = cache_postsuspend,
3562 	.preresume = cache_preresume,
3563 	.resume = cache_resume,
3564 	.status = cache_status,
3565 	.message = cache_message,
3566 	.iterate_devices = cache_iterate_devices,
3567 	.io_hints = cache_io_hints,
3568 };
3569 
3570 static int __init dm_cache_init(void)
3571 {
3572 	int r;
3573 
3574 	migration_cache = KMEM_CACHE(dm_cache_migration, 0);
3575 	if (!migration_cache) {
3576 		r = -ENOMEM;
3577 		goto err;
3578 	}
3579 
3580 	btracker_work_cache = kmem_cache_create("dm_cache_bt_work",
3581 		sizeof(struct bt_work), __alignof__(struct bt_work), 0, NULL);
3582 	if (!btracker_work_cache) {
3583 		r = -ENOMEM;
3584 		goto err;
3585 	}
3586 
3587 	r = dm_register_target(&cache_target);
3588 	if (r) {
3589 		goto err;
3590 	}
3591 
3592 	return 0;
3593 
3594 err:
3595 	kmem_cache_destroy(migration_cache);
3596 	kmem_cache_destroy(btracker_work_cache);
3597 	return r;
3598 }
3599 
3600 static void __exit dm_cache_exit(void)
3601 {
3602 	dm_unregister_target(&cache_target);
3603 	kmem_cache_destroy(migration_cache);
3604 	kmem_cache_destroy(btracker_work_cache);
3605 }
3606 
3607 module_init(dm_cache_init);
3608 module_exit(dm_cache_exit);
3609 
3610 MODULE_DESCRIPTION(DM_NAME " cache target");
3611 MODULE_AUTHOR("Joe Thornber <ejt@redhat.com>");
3612 MODULE_LICENSE("GPL");
3613