2 * Copyright (C) 2012 Red Hat. All rights reserved.
4 * This file is released under the GPL.
8 #include "dm-bio-prison-v2.h"
9 #include "dm-bio-record.h"
10 #include "dm-cache-metadata.h"
12 #include <linux/dm-io.h>
13 #include <linux/dm-kcopyd.h>
14 #include <linux/jiffies.h>
15 #include <linux/init.h>
16 #include <linux/mempool.h>
17 #include <linux/module.h>
18 #include <linux/rwsem.h>
19 #include <linux/slab.h>
20 #include <linux/vmalloc.h>
22 #define DM_MSG_PREFIX "cache"
24 DECLARE_DM_KCOPYD_THROTTLE_WITH_MODULE_PARM(cache_copy_throttle,
25 "A percentage of time allocated for copying to and/or from cache");
27 /*----------------------------------------------------------------*/
32 * oblock: index of an origin block
33 * cblock: index of a cache block
34 * promotion: movement of a block from origin to cache
35 * demotion: movement of a block from cache to origin
36 * migration: movement of a block between the origin and cache device,
40 /*----------------------------------------------------------------*/
46 * Sectors of in-flight IO.
51 * The time, in jiffies, when this device became idle (if it is
54 unsigned long idle_time;
55 unsigned long last_update_time;
58 static void iot_init(struct io_tracker *iot)
60 spin_lock_init(&iot->lock);
63 iot->last_update_time = jiffies;
66 static bool __iot_idle_for(struct io_tracker *iot, unsigned long jifs)
71 return time_after(jiffies, iot->idle_time + jifs);
74 static bool iot_idle_for(struct io_tracker *iot, unsigned long jifs)
79 spin_lock_irqsave(&iot->lock, flags);
80 r = __iot_idle_for(iot, jifs);
81 spin_unlock_irqrestore(&iot->lock, flags);
86 static void iot_io_begin(struct io_tracker *iot, sector_t len)
90 spin_lock_irqsave(&iot->lock, flags);
91 iot->in_flight += len;
92 spin_unlock_irqrestore(&iot->lock, flags);
95 static void __iot_io_end(struct io_tracker *iot, sector_t len)
100 iot->in_flight -= len;
102 iot->idle_time = jiffies;
105 static void iot_io_end(struct io_tracker *iot, sector_t len)
109 spin_lock_irqsave(&iot->lock, flags);
110 __iot_io_end(iot, len);
111 spin_unlock_irqrestore(&iot->lock, flags);
114 /*----------------------------------------------------------------*/
117 * Represents a chunk of future work. 'input' allows continuations to pass
118 * values between themselves, typically error values.
120 struct continuation {
121 struct work_struct ws;
125 static inline void init_continuation(struct continuation *k,
126 void (*fn)(struct work_struct *))
128 INIT_WORK(&k->ws, fn);
132 static inline void queue_continuation(struct workqueue_struct *wq,
133 struct continuation *k)
135 queue_work(wq, &k->ws);
138 /*----------------------------------------------------------------*/
141 * The batcher collects together pieces of work that need a particular
142 * operation to occur before they can proceed (typically a commit).
146 * The operation that everyone is waiting for.
148 blk_status_t (*commit_op)(void *context);
149 void *commit_context;
152 * This is how bios should be issued once the commit op is complete
153 * (accounted_request).
155 void (*issue_op)(struct bio *bio, void *context);
159 * Queued work gets put on here after commit.
161 struct workqueue_struct *wq;
164 struct list_head work_items;
165 struct bio_list bios;
166 struct work_struct commit_work;
168 bool commit_scheduled;
171 static void __commit(struct work_struct *_ws)
173 struct batcher *b = container_of(_ws, struct batcher, commit_work);
176 struct list_head work_items;
177 struct work_struct *ws, *tmp;
178 struct continuation *k;
180 struct bio_list bios;
182 INIT_LIST_HEAD(&work_items);
183 bio_list_init(&bios);
186 * We have to grab these before the commit_op to avoid a race
189 spin_lock_irqsave(&b->lock, flags);
190 list_splice_init(&b->work_items, &work_items);
191 bio_list_merge(&bios, &b->bios);
192 bio_list_init(&b->bios);
193 b->commit_scheduled = false;
194 spin_unlock_irqrestore(&b->lock, flags);
196 r = b->commit_op(b->commit_context);
198 list_for_each_entry_safe(ws, tmp, &work_items, entry) {
199 k = container_of(ws, struct continuation, ws);
201 INIT_LIST_HEAD(&ws->entry); /* to avoid a WARN_ON */
202 queue_work(b->wq, ws);
205 while ((bio = bio_list_pop(&bios))) {
210 b->issue_op(bio, b->issue_context);
214 static void batcher_init(struct batcher *b,
215 blk_status_t (*commit_op)(void *),
216 void *commit_context,
217 void (*issue_op)(struct bio *bio, void *),
219 struct workqueue_struct *wq)
221 b->commit_op = commit_op;
222 b->commit_context = commit_context;
223 b->issue_op = issue_op;
224 b->issue_context = issue_context;
227 spin_lock_init(&b->lock);
228 INIT_LIST_HEAD(&b->work_items);
229 bio_list_init(&b->bios);
230 INIT_WORK(&b->commit_work, __commit);
231 b->commit_scheduled = false;
234 static void async_commit(struct batcher *b)
236 queue_work(b->wq, &b->commit_work);
239 static void continue_after_commit(struct batcher *b, struct continuation *k)
242 bool commit_scheduled;
244 spin_lock_irqsave(&b->lock, flags);
245 commit_scheduled = b->commit_scheduled;
246 list_add_tail(&k->ws.entry, &b->work_items);
247 spin_unlock_irqrestore(&b->lock, flags);
249 if (commit_scheduled)
254 * Bios are errored if commit failed.
256 static void issue_after_commit(struct batcher *b, struct bio *bio)
259 bool commit_scheduled;
261 spin_lock_irqsave(&b->lock, flags);
262 commit_scheduled = b->commit_scheduled;
263 bio_list_add(&b->bios, bio);
264 spin_unlock_irqrestore(&b->lock, flags);
266 if (commit_scheduled)
271 * Call this if some urgent work is waiting for the commit to complete.
273 static void schedule_commit(struct batcher *b)
278 spin_lock_irqsave(&b->lock, flags);
279 immediate = !list_empty(&b->work_items) || !bio_list_empty(&b->bios);
280 b->commit_scheduled = true;
281 spin_unlock_irqrestore(&b->lock, flags);
288 * There are a couple of places where we let a bio run, but want to do some
289 * work before calling its endio function. We do this by temporarily
290 * changing the endio fn.
292 struct dm_hook_info {
293 bio_end_io_t *bi_end_io;
296 static void dm_hook_bio(struct dm_hook_info *h, struct bio *bio,
297 bio_end_io_t *bi_end_io, void *bi_private)
299 h->bi_end_io = bio->bi_end_io;
301 bio->bi_end_io = bi_end_io;
302 bio->bi_private = bi_private;
305 static void dm_unhook_bio(struct dm_hook_info *h, struct bio *bio)
307 bio->bi_end_io = h->bi_end_io;
310 /*----------------------------------------------------------------*/
312 #define MIGRATION_POOL_SIZE 128
313 #define COMMIT_PERIOD HZ
314 #define MIGRATION_COUNT_WINDOW 10
317 * The block size of the device holding cache data must be
318 * between 32KB and 1GB.
320 #define DATA_DEV_BLOCK_SIZE_MIN_SECTORS (32 * 1024 >> SECTOR_SHIFT)
321 #define DATA_DEV_BLOCK_SIZE_MAX_SECTORS (1024 * 1024 * 1024 >> SECTOR_SHIFT)
323 enum cache_metadata_mode {
324 CM_WRITE, /* metadata may be changed */
325 CM_READ_ONLY, /* metadata may not be changed */
331 * Data is written to cached blocks only. These blocks are marked
332 * dirty. If you lose the cache device you will lose data.
333 * Potential performance increase for both reads and writes.
338 * Data is written to both cache and origin. Blocks are never
339 * dirty. Potential performance benfit for reads only.
344 * A degraded mode useful for various cache coherency situations
345 * (eg, rolling back snapshots). Reads and writes always go to the
346 * origin. If a write goes to a cached oblock, then the cache
347 * block is invalidated.
352 struct cache_features {
353 enum cache_metadata_mode mode;
354 enum cache_io_mode io_mode;
355 unsigned metadata_version;
366 atomic_t copies_avoided;
367 atomic_t cache_cell_clash;
368 atomic_t commit_count;
369 atomic_t discard_count;
373 struct dm_target *ti;
377 * Fields for converting from sectors to blocks.
379 int sectors_per_block_shift;
380 sector_t sectors_per_block;
382 struct dm_cache_metadata *cmd;
385 * Metadata is written to this device.
387 struct dm_dev *metadata_dev;
390 * The slower of the two data devices. Typically a spindle.
392 struct dm_dev *origin_dev;
395 * The faster of the two data devices. Typically an SSD.
397 struct dm_dev *cache_dev;
400 * Size of the origin device in _complete_ blocks and native sectors.
402 dm_oblock_t origin_blocks;
403 sector_t origin_sectors;
406 * Size of the cache device in blocks.
408 dm_cblock_t cache_size;
411 * Invalidation fields.
413 spinlock_t invalidation_lock;
414 struct list_head invalidation_requests;
416 sector_t migration_threshold;
417 wait_queue_head_t migration_wait;
418 atomic_t nr_allocated_migrations;
421 * The number of in flight migrations that are performing
422 * background io. eg, promotion, writeback.
424 atomic_t nr_io_migrations;
426 struct bio_list deferred_bios;
428 struct rw_semaphore quiesce_lock;
430 struct dm_target_callbacks callbacks;
433 * origin_blocks entries, discarded if set.
435 dm_dblock_t discard_nr_blocks;
436 unsigned long *discard_bitset;
437 uint32_t discard_block_size; /* a power of 2 times sectors per block */
440 * Rather than reconstructing the table line for the status we just
441 * save it and regurgitate.
443 unsigned nr_ctr_args;
444 const char **ctr_args;
446 struct dm_kcopyd_client *copier;
447 struct work_struct deferred_bio_worker;
448 struct work_struct migration_worker;
449 struct workqueue_struct *wq;
450 struct delayed_work waker;
451 struct dm_bio_prison_v2 *prison;
454 * cache_size entries, dirty if set
456 unsigned long *dirty_bitset;
459 unsigned policy_nr_args;
460 struct dm_cache_policy *policy;
463 * Cache features such as write-through.
465 struct cache_features features;
467 struct cache_stats stats;
469 bool need_tick_bio:1;
472 bool commit_requested:1;
473 bool loaded_mappings:1;
474 bool loaded_discards:1;
476 struct rw_semaphore background_work_lock;
478 struct batcher committer;
479 struct work_struct commit_ws;
481 struct io_tracker tracker;
483 mempool_t migration_pool;
488 struct per_bio_data {
491 struct dm_bio_prison_cell_v2 *cell;
492 struct dm_hook_info hook_info;
496 struct dm_cache_migration {
497 struct continuation k;
500 struct policy_work *op;
501 struct bio *overwrite_bio;
502 struct dm_bio_prison_cell_v2 *cell;
504 dm_cblock_t invalidate_cblock;
505 dm_oblock_t invalidate_oblock;
508 /*----------------------------------------------------------------*/
510 static bool writethrough_mode(struct cache *cache)
512 return cache->features.io_mode == CM_IO_WRITETHROUGH;
515 static bool writeback_mode(struct cache *cache)
517 return cache->features.io_mode == CM_IO_WRITEBACK;
520 static inline bool passthrough_mode(struct cache *cache)
522 return unlikely(cache->features.io_mode == CM_IO_PASSTHROUGH);
525 /*----------------------------------------------------------------*/
527 static void wake_deferred_bio_worker(struct cache *cache)
529 queue_work(cache->wq, &cache->deferred_bio_worker);
532 static void wake_migration_worker(struct cache *cache)
534 if (passthrough_mode(cache))
537 queue_work(cache->wq, &cache->migration_worker);
540 /*----------------------------------------------------------------*/
542 static struct dm_bio_prison_cell_v2 *alloc_prison_cell(struct cache *cache)
544 return dm_bio_prison_alloc_cell_v2(cache->prison, GFP_NOIO);
547 static void free_prison_cell(struct cache *cache, struct dm_bio_prison_cell_v2 *cell)
549 dm_bio_prison_free_cell_v2(cache->prison, cell);
552 static struct dm_cache_migration *alloc_migration(struct cache *cache)
554 struct dm_cache_migration *mg;
556 mg = mempool_alloc(&cache->migration_pool, GFP_NOIO);
558 memset(mg, 0, sizeof(*mg));
561 atomic_inc(&cache->nr_allocated_migrations);
566 static void free_migration(struct dm_cache_migration *mg)
568 struct cache *cache = mg->cache;
570 if (atomic_dec_and_test(&cache->nr_allocated_migrations))
571 wake_up(&cache->migration_wait);
573 mempool_free(mg, &cache->migration_pool);
576 /*----------------------------------------------------------------*/
578 static inline dm_oblock_t oblock_succ(dm_oblock_t b)
580 return to_oblock(from_oblock(b) + 1ull);
583 static void build_key(dm_oblock_t begin, dm_oblock_t end, struct dm_cell_key_v2 *key)
587 key->block_begin = from_oblock(begin);
588 key->block_end = from_oblock(end);
592 * We have two lock levels. Level 0, which is used to prevent WRITEs, and
593 * level 1 which prevents *both* READs and WRITEs.
595 #define WRITE_LOCK_LEVEL 0
596 #define READ_WRITE_LOCK_LEVEL 1
598 static unsigned lock_level(struct bio *bio)
600 return bio_data_dir(bio) == WRITE ?
602 READ_WRITE_LOCK_LEVEL;
605 /*----------------------------------------------------------------
607 *--------------------------------------------------------------*/
609 static struct per_bio_data *get_per_bio_data(struct bio *bio)
611 struct per_bio_data *pb = dm_per_bio_data(bio, sizeof(struct per_bio_data));
616 static struct per_bio_data *init_per_bio_data(struct bio *bio)
618 struct per_bio_data *pb = get_per_bio_data(bio);
621 pb->req_nr = dm_bio_get_target_bio_nr(bio);
628 /*----------------------------------------------------------------*/
630 static void defer_bio(struct cache *cache, struct bio *bio)
634 spin_lock_irqsave(&cache->lock, flags);
635 bio_list_add(&cache->deferred_bios, bio);
636 spin_unlock_irqrestore(&cache->lock, flags);
638 wake_deferred_bio_worker(cache);
641 static void defer_bios(struct cache *cache, struct bio_list *bios)
645 spin_lock_irqsave(&cache->lock, flags);
646 bio_list_merge(&cache->deferred_bios, bios);
648 spin_unlock_irqrestore(&cache->lock, flags);
650 wake_deferred_bio_worker(cache);
653 /*----------------------------------------------------------------*/
655 static bool bio_detain_shared(struct cache *cache, dm_oblock_t oblock, struct bio *bio)
658 struct per_bio_data *pb;
659 struct dm_cell_key_v2 key;
660 dm_oblock_t end = to_oblock(from_oblock(oblock) + 1ULL);
661 struct dm_bio_prison_cell_v2 *cell_prealloc, *cell;
663 cell_prealloc = alloc_prison_cell(cache); /* FIXME: allow wait if calling from worker */
665 build_key(oblock, end, &key);
666 r = dm_cell_get_v2(cache->prison, &key, lock_level(bio), bio, cell_prealloc, &cell);
669 * Failed to get the lock.
671 free_prison_cell(cache, cell_prealloc);
675 if (cell != cell_prealloc)
676 free_prison_cell(cache, cell_prealloc);
678 pb = get_per_bio_data(bio);
684 /*----------------------------------------------------------------*/
686 static bool is_dirty(struct cache *cache, dm_cblock_t b)
688 return test_bit(from_cblock(b), cache->dirty_bitset);
691 static void set_dirty(struct cache *cache, dm_cblock_t cblock)
693 if (!test_and_set_bit(from_cblock(cblock), cache->dirty_bitset)) {
694 atomic_inc(&cache->nr_dirty);
695 policy_set_dirty(cache->policy, cblock);
700 * These two are called when setting after migrations to force the policy
701 * and dirty bitset to be in sync.
703 static void force_set_dirty(struct cache *cache, dm_cblock_t cblock)
705 if (!test_and_set_bit(from_cblock(cblock), cache->dirty_bitset))
706 atomic_inc(&cache->nr_dirty);
707 policy_set_dirty(cache->policy, cblock);
710 static void force_clear_dirty(struct cache *cache, dm_cblock_t cblock)
712 if (test_and_clear_bit(from_cblock(cblock), cache->dirty_bitset)) {
713 if (atomic_dec_return(&cache->nr_dirty) == 0)
714 dm_table_event(cache->ti->table);
717 policy_clear_dirty(cache->policy, cblock);
720 /*----------------------------------------------------------------*/
722 static bool block_size_is_power_of_two(struct cache *cache)
724 return cache->sectors_per_block_shift >= 0;
727 /* gcc on ARM generates spurious references to __udivdi3 and __umoddi3 */
728 #if defined(CONFIG_ARM) && __GNUC__ == 4 && __GNUC_MINOR__ <= 6
731 static dm_block_t block_div(dm_block_t b, uint32_t n)
738 static dm_block_t oblocks_per_dblock(struct cache *cache)
740 dm_block_t oblocks = cache->discard_block_size;
742 if (block_size_is_power_of_two(cache))
743 oblocks >>= cache->sectors_per_block_shift;
745 oblocks = block_div(oblocks, cache->sectors_per_block);
750 static dm_dblock_t oblock_to_dblock(struct cache *cache, dm_oblock_t oblock)
752 return to_dblock(block_div(from_oblock(oblock),
753 oblocks_per_dblock(cache)));
756 static void set_discard(struct cache *cache, dm_dblock_t b)
760 BUG_ON(from_dblock(b) >= from_dblock(cache->discard_nr_blocks));
761 atomic_inc(&cache->stats.discard_count);
763 spin_lock_irqsave(&cache->lock, flags);
764 set_bit(from_dblock(b), cache->discard_bitset);
765 spin_unlock_irqrestore(&cache->lock, flags);
768 static void clear_discard(struct cache *cache, dm_dblock_t b)
772 spin_lock_irqsave(&cache->lock, flags);
773 clear_bit(from_dblock(b), cache->discard_bitset);
774 spin_unlock_irqrestore(&cache->lock, flags);
777 static bool is_discarded(struct cache *cache, dm_dblock_t b)
782 spin_lock_irqsave(&cache->lock, flags);
783 r = test_bit(from_dblock(b), cache->discard_bitset);
784 spin_unlock_irqrestore(&cache->lock, flags);
789 static bool is_discarded_oblock(struct cache *cache, dm_oblock_t b)
794 spin_lock_irqsave(&cache->lock, flags);
795 r = test_bit(from_dblock(oblock_to_dblock(cache, b)),
796 cache->discard_bitset);
797 spin_unlock_irqrestore(&cache->lock, flags);
802 /*----------------------------------------------------------------
804 *--------------------------------------------------------------*/
805 static void remap_to_origin(struct cache *cache, struct bio *bio)
807 bio_set_dev(bio, cache->origin_dev->bdev);
810 static void remap_to_cache(struct cache *cache, struct bio *bio,
813 sector_t bi_sector = bio->bi_iter.bi_sector;
814 sector_t block = from_cblock(cblock);
816 bio_set_dev(bio, cache->cache_dev->bdev);
817 if (!block_size_is_power_of_two(cache))
818 bio->bi_iter.bi_sector =
819 (block * cache->sectors_per_block) +
820 sector_div(bi_sector, cache->sectors_per_block);
822 bio->bi_iter.bi_sector =
823 (block << cache->sectors_per_block_shift) |
824 (bi_sector & (cache->sectors_per_block - 1));
827 static void check_if_tick_bio_needed(struct cache *cache, struct bio *bio)
830 struct per_bio_data *pb;
832 spin_lock_irqsave(&cache->lock, flags);
833 if (cache->need_tick_bio && !op_is_flush(bio->bi_opf) &&
834 bio_op(bio) != REQ_OP_DISCARD) {
835 pb = get_per_bio_data(bio);
837 cache->need_tick_bio = false;
839 spin_unlock_irqrestore(&cache->lock, flags);
842 static void __remap_to_origin_clear_discard(struct cache *cache, struct bio *bio,
843 dm_oblock_t oblock, bool bio_has_pbd)
846 check_if_tick_bio_needed(cache, bio);
847 remap_to_origin(cache, bio);
848 if (bio_data_dir(bio) == WRITE)
849 clear_discard(cache, oblock_to_dblock(cache, oblock));
852 static void remap_to_origin_clear_discard(struct cache *cache, struct bio *bio,
855 // FIXME: check_if_tick_bio_needed() is called way too much through this interface
856 __remap_to_origin_clear_discard(cache, bio, oblock, true);
859 static void remap_to_cache_dirty(struct cache *cache, struct bio *bio,
860 dm_oblock_t oblock, dm_cblock_t cblock)
862 check_if_tick_bio_needed(cache, bio);
863 remap_to_cache(cache, bio, cblock);
864 if (bio_data_dir(bio) == WRITE) {
865 set_dirty(cache, cblock);
866 clear_discard(cache, oblock_to_dblock(cache, oblock));
870 static dm_oblock_t get_bio_block(struct cache *cache, struct bio *bio)
872 sector_t block_nr = bio->bi_iter.bi_sector;
874 if (!block_size_is_power_of_two(cache))
875 (void) sector_div(block_nr, cache->sectors_per_block);
877 block_nr >>= cache->sectors_per_block_shift;
879 return to_oblock(block_nr);
882 static bool accountable_bio(struct cache *cache, struct bio *bio)
884 return bio_op(bio) != REQ_OP_DISCARD;
887 static void accounted_begin(struct cache *cache, struct bio *bio)
889 struct per_bio_data *pb;
891 if (accountable_bio(cache, bio)) {
892 pb = get_per_bio_data(bio);
893 pb->len = bio_sectors(bio);
894 iot_io_begin(&cache->tracker, pb->len);
898 static void accounted_complete(struct cache *cache, struct bio *bio)
900 struct per_bio_data *pb = get_per_bio_data(bio);
902 iot_io_end(&cache->tracker, pb->len);
905 static void accounted_request(struct cache *cache, struct bio *bio)
907 accounted_begin(cache, bio);
908 generic_make_request(bio);
911 static void issue_op(struct bio *bio, void *context)
913 struct cache *cache = context;
914 accounted_request(cache, bio);
918 * When running in writethrough mode we need to send writes to clean blocks
919 * to both the cache and origin devices. Clone the bio and send them in parallel.
921 static void remap_to_origin_and_cache(struct cache *cache, struct bio *bio,
922 dm_oblock_t oblock, dm_cblock_t cblock)
924 struct bio *origin_bio = bio_clone_fast(bio, GFP_NOIO, &cache->bs);
928 bio_chain(origin_bio, bio);
930 * Passing false to __remap_to_origin_clear_discard() skips
931 * all code that might use per_bio_data (since clone doesn't have it)
933 __remap_to_origin_clear_discard(cache, origin_bio, oblock, false);
934 submit_bio(origin_bio);
936 remap_to_cache(cache, bio, cblock);
939 /*----------------------------------------------------------------
941 *--------------------------------------------------------------*/
942 static enum cache_metadata_mode get_cache_mode(struct cache *cache)
944 return cache->features.mode;
947 static const char *cache_device_name(struct cache *cache)
949 return dm_device_name(dm_table_get_md(cache->ti->table));
952 static void notify_mode_switch(struct cache *cache, enum cache_metadata_mode mode)
954 const char *descs[] = {
960 dm_table_event(cache->ti->table);
961 DMINFO("%s: switching cache to %s mode",
962 cache_device_name(cache), descs[(int)mode]);
965 static void set_cache_mode(struct cache *cache, enum cache_metadata_mode new_mode)
968 enum cache_metadata_mode old_mode = get_cache_mode(cache);
970 if (dm_cache_metadata_needs_check(cache->cmd, &needs_check)) {
971 DMERR("%s: unable to read needs_check flag, setting failure mode.",
972 cache_device_name(cache));
976 if (new_mode == CM_WRITE && needs_check) {
977 DMERR("%s: unable to switch cache to write mode until repaired.",
978 cache_device_name(cache));
979 if (old_mode != new_mode)
982 new_mode = CM_READ_ONLY;
985 /* Never move out of fail mode */
986 if (old_mode == CM_FAIL)
992 dm_cache_metadata_set_read_only(cache->cmd);
996 dm_cache_metadata_set_read_write(cache->cmd);
1000 cache->features.mode = new_mode;
1002 if (new_mode != old_mode)
1003 notify_mode_switch(cache, new_mode);
1006 static void abort_transaction(struct cache *cache)
1008 const char *dev_name = cache_device_name(cache);
1010 if (get_cache_mode(cache) >= CM_READ_ONLY)
1013 DMERR_LIMIT("%s: aborting current metadata transaction", dev_name);
1014 if (dm_cache_metadata_abort(cache->cmd)) {
1015 DMERR("%s: failed to abort metadata transaction", dev_name);
1016 set_cache_mode(cache, CM_FAIL);
1019 if (dm_cache_metadata_set_needs_check(cache->cmd)) {
1020 DMERR("%s: failed to set 'needs_check' flag in metadata", dev_name);
1021 set_cache_mode(cache, CM_FAIL);
1025 static void metadata_operation_failed(struct cache *cache, const char *op, int r)
1027 DMERR_LIMIT("%s: metadata operation '%s' failed: error = %d",
1028 cache_device_name(cache), op, r);
1029 abort_transaction(cache);
1030 set_cache_mode(cache, CM_READ_ONLY);
1033 /*----------------------------------------------------------------*/
1035 static void load_stats(struct cache *cache)
1037 struct dm_cache_statistics stats;
1039 dm_cache_metadata_get_stats(cache->cmd, &stats);
1040 atomic_set(&cache->stats.read_hit, stats.read_hits);
1041 atomic_set(&cache->stats.read_miss, stats.read_misses);
1042 atomic_set(&cache->stats.write_hit, stats.write_hits);
1043 atomic_set(&cache->stats.write_miss, stats.write_misses);
1046 static void save_stats(struct cache *cache)
1048 struct dm_cache_statistics stats;
1050 if (get_cache_mode(cache) >= CM_READ_ONLY)
1053 stats.read_hits = atomic_read(&cache->stats.read_hit);
1054 stats.read_misses = atomic_read(&cache->stats.read_miss);
1055 stats.write_hits = atomic_read(&cache->stats.write_hit);
1056 stats.write_misses = atomic_read(&cache->stats.write_miss);
1058 dm_cache_metadata_set_stats(cache->cmd, &stats);
1061 static void update_stats(struct cache_stats *stats, enum policy_operation op)
1064 case POLICY_PROMOTE:
1065 atomic_inc(&stats->promotion);
1069 atomic_inc(&stats->demotion);
1072 case POLICY_WRITEBACK:
1073 atomic_inc(&stats->writeback);
1078 /*----------------------------------------------------------------
1079 * Migration processing
1081 * Migration covers moving data from the origin device to the cache, or
1083 *--------------------------------------------------------------*/
1085 static void inc_io_migrations(struct cache *cache)
1087 atomic_inc(&cache->nr_io_migrations);
1090 static void dec_io_migrations(struct cache *cache)
1092 atomic_dec(&cache->nr_io_migrations);
1095 static bool discard_or_flush(struct bio *bio)
1097 return bio_op(bio) == REQ_OP_DISCARD || op_is_flush(bio->bi_opf);
1100 static void calc_discard_block_range(struct cache *cache, struct bio *bio,
1101 dm_dblock_t *b, dm_dblock_t *e)
1103 sector_t sb = bio->bi_iter.bi_sector;
1104 sector_t se = bio_end_sector(bio);
1106 *b = to_dblock(dm_sector_div_up(sb, cache->discard_block_size));
1108 if (se - sb < cache->discard_block_size)
1111 *e = to_dblock(block_div(se, cache->discard_block_size));
1114 /*----------------------------------------------------------------*/
1116 static void prevent_background_work(struct cache *cache)
1119 down_write(&cache->background_work_lock);
1123 static void allow_background_work(struct cache *cache)
1126 up_write(&cache->background_work_lock);
1130 static bool background_work_begin(struct cache *cache)
1135 r = down_read_trylock(&cache->background_work_lock);
1141 static void background_work_end(struct cache *cache)
1144 up_read(&cache->background_work_lock);
1148 /*----------------------------------------------------------------*/
1150 static bool bio_writes_complete_block(struct cache *cache, struct bio *bio)
1152 return (bio_data_dir(bio) == WRITE) &&
1153 (bio->bi_iter.bi_size == (cache->sectors_per_block << SECTOR_SHIFT));
1156 static bool optimisable_bio(struct cache *cache, struct bio *bio, dm_oblock_t block)
1158 return writeback_mode(cache) &&
1159 (is_discarded_oblock(cache, block) || bio_writes_complete_block(cache, bio));
1162 static void quiesce(struct dm_cache_migration *mg,
1163 void (*continuation)(struct work_struct *))
1165 init_continuation(&mg->k, continuation);
1166 dm_cell_quiesce_v2(mg->cache->prison, mg->cell, &mg->k.ws);
1169 static struct dm_cache_migration *ws_to_mg(struct work_struct *ws)
1171 struct continuation *k = container_of(ws, struct continuation, ws);
1172 return container_of(k, struct dm_cache_migration, k);
1175 static void copy_complete(int read_err, unsigned long write_err, void *context)
1177 struct dm_cache_migration *mg = container_of(context, struct dm_cache_migration, k);
1179 if (read_err || write_err)
1180 mg->k.input = BLK_STS_IOERR;
1182 queue_continuation(mg->cache->wq, &mg->k);
1185 static void copy(struct dm_cache_migration *mg, bool promote)
1187 struct dm_io_region o_region, c_region;
1188 struct cache *cache = mg->cache;
1190 o_region.bdev = cache->origin_dev->bdev;
1191 o_region.sector = from_oblock(mg->op->oblock) * cache->sectors_per_block;
1192 o_region.count = cache->sectors_per_block;
1194 c_region.bdev = cache->cache_dev->bdev;
1195 c_region.sector = from_cblock(mg->op->cblock) * cache->sectors_per_block;
1196 c_region.count = cache->sectors_per_block;
1199 dm_kcopyd_copy(cache->copier, &o_region, 1, &c_region, 0, copy_complete, &mg->k);
1201 dm_kcopyd_copy(cache->copier, &c_region, 1, &o_region, 0, copy_complete, &mg->k);
1204 static void bio_drop_shared_lock(struct cache *cache, struct bio *bio)
1206 struct per_bio_data *pb = get_per_bio_data(bio);
1208 if (pb->cell && dm_cell_put_v2(cache->prison, pb->cell))
1209 free_prison_cell(cache, pb->cell);
1213 static void overwrite_endio(struct bio *bio)
1215 struct dm_cache_migration *mg = bio->bi_private;
1216 struct cache *cache = mg->cache;
1217 struct per_bio_data *pb = get_per_bio_data(bio);
1219 dm_unhook_bio(&pb->hook_info, bio);
1222 mg->k.input = bio->bi_status;
1224 queue_continuation(cache->wq, &mg->k);
1227 static void overwrite(struct dm_cache_migration *mg,
1228 void (*continuation)(struct work_struct *))
1230 struct bio *bio = mg->overwrite_bio;
1231 struct per_bio_data *pb = get_per_bio_data(bio);
1233 dm_hook_bio(&pb->hook_info, bio, overwrite_endio, mg);
1236 * The overwrite bio is part of the copy operation, as such it does
1237 * not set/clear discard or dirty flags.
1239 if (mg->op->op == POLICY_PROMOTE)
1240 remap_to_cache(mg->cache, bio, mg->op->cblock);
1242 remap_to_origin(mg->cache, bio);
1244 init_continuation(&mg->k, continuation);
1245 accounted_request(mg->cache, bio);
1251 * 1) exclusive lock preventing WRITEs
1253 * 3) copy or issue overwrite bio
1254 * 4) upgrade to exclusive lock preventing READs and WRITEs
1256 * 6) update metadata and commit
1259 static void mg_complete(struct dm_cache_migration *mg, bool success)
1261 struct bio_list bios;
1262 struct cache *cache = mg->cache;
1263 struct policy_work *op = mg->op;
1264 dm_cblock_t cblock = op->cblock;
1267 update_stats(&cache->stats, op->op);
1270 case POLICY_PROMOTE:
1271 clear_discard(cache, oblock_to_dblock(cache, op->oblock));
1272 policy_complete_background_work(cache->policy, op, success);
1274 if (mg->overwrite_bio) {
1276 force_set_dirty(cache, cblock);
1277 else if (mg->k.input)
1278 mg->overwrite_bio->bi_status = mg->k.input;
1280 mg->overwrite_bio->bi_status = BLK_STS_IOERR;
1281 bio_endio(mg->overwrite_bio);
1284 force_clear_dirty(cache, cblock);
1285 dec_io_migrations(cache);
1291 * We clear dirty here to update the nr_dirty counter.
1294 force_clear_dirty(cache, cblock);
1295 policy_complete_background_work(cache->policy, op, success);
1296 dec_io_migrations(cache);
1299 case POLICY_WRITEBACK:
1301 force_clear_dirty(cache, cblock);
1302 policy_complete_background_work(cache->policy, op, success);
1303 dec_io_migrations(cache);
1307 bio_list_init(&bios);
1309 if (dm_cell_unlock_v2(cache->prison, mg->cell, &bios))
1310 free_prison_cell(cache, mg->cell);
1314 defer_bios(cache, &bios);
1315 wake_migration_worker(cache);
1317 background_work_end(cache);
1320 static void mg_success(struct work_struct *ws)
1322 struct dm_cache_migration *mg = ws_to_mg(ws);
1323 mg_complete(mg, mg->k.input == 0);
1326 static void mg_update_metadata(struct work_struct *ws)
1329 struct dm_cache_migration *mg = ws_to_mg(ws);
1330 struct cache *cache = mg->cache;
1331 struct policy_work *op = mg->op;
1334 case POLICY_PROMOTE:
1335 r = dm_cache_insert_mapping(cache->cmd, op->cblock, op->oblock);
1337 DMERR_LIMIT("%s: migration failed; couldn't insert mapping",
1338 cache_device_name(cache));
1339 metadata_operation_failed(cache, "dm_cache_insert_mapping", r);
1341 mg_complete(mg, false);
1344 mg_complete(mg, true);
1348 r = dm_cache_remove_mapping(cache->cmd, op->cblock);
1350 DMERR_LIMIT("%s: migration failed; couldn't update on disk metadata",
1351 cache_device_name(cache));
1352 metadata_operation_failed(cache, "dm_cache_remove_mapping", r);
1354 mg_complete(mg, false);
1359 * It would be nice if we only had to commit when a REQ_FLUSH
1360 * comes through. But there's one scenario that we have to
1363 * - vblock x in a cache block
1365 * - cache block gets reallocated and over written
1368 * When we recover, because there was no commit the cache will
1369 * rollback to having the data for vblock x in the cache block.
1370 * But the cache block has since been overwritten, so it'll end
1371 * up pointing to data that was never in 'x' during the history
1374 * To avoid this issue we require a commit as part of the
1375 * demotion operation.
1377 init_continuation(&mg->k, mg_success);
1378 continue_after_commit(&cache->committer, &mg->k);
1379 schedule_commit(&cache->committer);
1382 case POLICY_WRITEBACK:
1383 mg_complete(mg, true);
1388 static void mg_update_metadata_after_copy(struct work_struct *ws)
1390 struct dm_cache_migration *mg = ws_to_mg(ws);
1393 * Did the copy succeed?
1396 mg_complete(mg, false);
1398 mg_update_metadata(ws);
1401 static void mg_upgrade_lock(struct work_struct *ws)
1404 struct dm_cache_migration *mg = ws_to_mg(ws);
1407 * Did the copy succeed?
1410 mg_complete(mg, false);
1414 * Now we want the lock to prevent both reads and writes.
1416 r = dm_cell_lock_promote_v2(mg->cache->prison, mg->cell,
1417 READ_WRITE_LOCK_LEVEL);
1419 mg_complete(mg, false);
1422 quiesce(mg, mg_update_metadata);
1425 mg_update_metadata(ws);
1429 static void mg_full_copy(struct work_struct *ws)
1431 struct dm_cache_migration *mg = ws_to_mg(ws);
1432 struct cache *cache = mg->cache;
1433 struct policy_work *op = mg->op;
1434 bool is_policy_promote = (op->op == POLICY_PROMOTE);
1436 if ((!is_policy_promote && !is_dirty(cache, op->cblock)) ||
1437 is_discarded_oblock(cache, op->oblock)) {
1438 mg_upgrade_lock(ws);
1442 init_continuation(&mg->k, mg_upgrade_lock);
1443 copy(mg, is_policy_promote);
1446 static void mg_copy(struct work_struct *ws)
1448 struct dm_cache_migration *mg = ws_to_mg(ws);
1450 if (mg->overwrite_bio) {
1452 * No exclusive lock was held when we last checked if the bio
1453 * was optimisable. So we have to check again in case things
1454 * have changed (eg, the block may no longer be discarded).
1456 if (!optimisable_bio(mg->cache, mg->overwrite_bio, mg->op->oblock)) {
1458 * Fallback to a real full copy after doing some tidying up.
1460 bool rb = bio_detain_shared(mg->cache, mg->op->oblock, mg->overwrite_bio);
1461 BUG_ON(rb); /* An exclussive lock must _not_ be held for this block */
1462 mg->overwrite_bio = NULL;
1463 inc_io_migrations(mg->cache);
1469 * It's safe to do this here, even though it's new data
1470 * because all IO has been locked out of the block.
1472 * mg_lock_writes() already took READ_WRITE_LOCK_LEVEL
1473 * so _not_ using mg_upgrade_lock() as continutation.
1475 overwrite(mg, mg_update_metadata_after_copy);
1481 static int mg_lock_writes(struct dm_cache_migration *mg)
1484 struct dm_cell_key_v2 key;
1485 struct cache *cache = mg->cache;
1486 struct dm_bio_prison_cell_v2 *prealloc;
1488 prealloc = alloc_prison_cell(cache);
1491 * Prevent writes to the block, but allow reads to continue.
1492 * Unless we're using an overwrite bio, in which case we lock
1495 build_key(mg->op->oblock, oblock_succ(mg->op->oblock), &key);
1496 r = dm_cell_lock_v2(cache->prison, &key,
1497 mg->overwrite_bio ? READ_WRITE_LOCK_LEVEL : WRITE_LOCK_LEVEL,
1498 prealloc, &mg->cell);
1500 free_prison_cell(cache, prealloc);
1501 mg_complete(mg, false);
1505 if (mg->cell != prealloc)
1506 free_prison_cell(cache, prealloc);
1511 quiesce(mg, mg_copy);
1516 static int mg_start(struct cache *cache, struct policy_work *op, struct bio *bio)
1518 struct dm_cache_migration *mg;
1520 if (!background_work_begin(cache)) {
1521 policy_complete_background_work(cache->policy, op, false);
1525 mg = alloc_migration(cache);
1528 mg->overwrite_bio = bio;
1531 inc_io_migrations(cache);
1533 return mg_lock_writes(mg);
1536 /*----------------------------------------------------------------
1537 * invalidation processing
1538 *--------------------------------------------------------------*/
1540 static void invalidate_complete(struct dm_cache_migration *mg, bool success)
1542 struct bio_list bios;
1543 struct cache *cache = mg->cache;
1545 bio_list_init(&bios);
1546 if (dm_cell_unlock_v2(cache->prison, mg->cell, &bios))
1547 free_prison_cell(cache, mg->cell);
1549 if (!success && mg->overwrite_bio)
1550 bio_io_error(mg->overwrite_bio);
1553 defer_bios(cache, &bios);
1555 background_work_end(cache);
1558 static void invalidate_completed(struct work_struct *ws)
1560 struct dm_cache_migration *mg = ws_to_mg(ws);
1561 invalidate_complete(mg, !mg->k.input);
1564 static int invalidate_cblock(struct cache *cache, dm_cblock_t cblock)
1566 int r = policy_invalidate_mapping(cache->policy, cblock);
1568 r = dm_cache_remove_mapping(cache->cmd, cblock);
1570 DMERR_LIMIT("%s: invalidation failed; couldn't update on disk metadata",
1571 cache_device_name(cache));
1572 metadata_operation_failed(cache, "dm_cache_remove_mapping", r);
1575 } else if (r == -ENODATA) {
1577 * Harmless, already unmapped.
1582 DMERR("%s: policy_invalidate_mapping failed", cache_device_name(cache));
1587 static void invalidate_remove(struct work_struct *ws)
1590 struct dm_cache_migration *mg = ws_to_mg(ws);
1591 struct cache *cache = mg->cache;
1593 r = invalidate_cblock(cache, mg->invalidate_cblock);
1595 invalidate_complete(mg, false);
1599 init_continuation(&mg->k, invalidate_completed);
1600 continue_after_commit(&cache->committer, &mg->k);
1601 remap_to_origin_clear_discard(cache, mg->overwrite_bio, mg->invalidate_oblock);
1602 mg->overwrite_bio = NULL;
1603 schedule_commit(&cache->committer);
1606 static int invalidate_lock(struct dm_cache_migration *mg)
1609 struct dm_cell_key_v2 key;
1610 struct cache *cache = mg->cache;
1611 struct dm_bio_prison_cell_v2 *prealloc;
1613 prealloc = alloc_prison_cell(cache);
1615 build_key(mg->invalidate_oblock, oblock_succ(mg->invalidate_oblock), &key);
1616 r = dm_cell_lock_v2(cache->prison, &key,
1617 READ_WRITE_LOCK_LEVEL, prealloc, &mg->cell);
1619 free_prison_cell(cache, prealloc);
1620 invalidate_complete(mg, false);
1624 if (mg->cell != prealloc)
1625 free_prison_cell(cache, prealloc);
1628 quiesce(mg, invalidate_remove);
1632 * We can't call invalidate_remove() directly here because we
1633 * might still be in request context.
1635 init_continuation(&mg->k, invalidate_remove);
1636 queue_work(cache->wq, &mg->k.ws);
1642 static int invalidate_start(struct cache *cache, dm_cblock_t cblock,
1643 dm_oblock_t oblock, struct bio *bio)
1645 struct dm_cache_migration *mg;
1647 if (!background_work_begin(cache))
1650 mg = alloc_migration(cache);
1652 mg->overwrite_bio = bio;
1653 mg->invalidate_cblock = cblock;
1654 mg->invalidate_oblock = oblock;
1656 return invalidate_lock(mg);
1659 /*----------------------------------------------------------------
1661 *--------------------------------------------------------------*/
1668 static enum busy spare_migration_bandwidth(struct cache *cache)
1670 bool idle = iot_idle_for(&cache->tracker, HZ);
1671 sector_t current_volume = (atomic_read(&cache->nr_io_migrations) + 1) *
1672 cache->sectors_per_block;
1674 if (idle && current_volume <= cache->migration_threshold)
1680 static void inc_hit_counter(struct cache *cache, struct bio *bio)
1682 atomic_inc(bio_data_dir(bio) == READ ?
1683 &cache->stats.read_hit : &cache->stats.write_hit);
1686 static void inc_miss_counter(struct cache *cache, struct bio *bio)
1688 atomic_inc(bio_data_dir(bio) == READ ?
1689 &cache->stats.read_miss : &cache->stats.write_miss);
1692 /*----------------------------------------------------------------*/
1694 static int map_bio(struct cache *cache, struct bio *bio, dm_oblock_t block,
1695 bool *commit_needed)
1698 bool rb, background_queued;
1701 *commit_needed = false;
1703 rb = bio_detain_shared(cache, block, bio);
1706 * An exclusive lock is held for this block, so we have to
1707 * wait. We set the commit_needed flag so the current
1708 * transaction will be committed asap, allowing this lock
1711 *commit_needed = true;
1712 return DM_MAPIO_SUBMITTED;
1715 data_dir = bio_data_dir(bio);
1717 if (optimisable_bio(cache, bio, block)) {
1718 struct policy_work *op = NULL;
1720 r = policy_lookup_with_work(cache->policy, block, &cblock, data_dir, true, &op);
1721 if (unlikely(r && r != -ENOENT)) {
1722 DMERR_LIMIT("%s: policy_lookup_with_work() failed with r = %d",
1723 cache_device_name(cache), r);
1725 return DM_MAPIO_SUBMITTED;
1728 if (r == -ENOENT && op) {
1729 bio_drop_shared_lock(cache, bio);
1730 BUG_ON(op->op != POLICY_PROMOTE);
1731 mg_start(cache, op, bio);
1732 return DM_MAPIO_SUBMITTED;
1735 r = policy_lookup(cache->policy, block, &cblock, data_dir, false, &background_queued);
1736 if (unlikely(r && r != -ENOENT)) {
1737 DMERR_LIMIT("%s: policy_lookup() failed with r = %d",
1738 cache_device_name(cache), r);
1740 return DM_MAPIO_SUBMITTED;
1743 if (background_queued)
1744 wake_migration_worker(cache);
1748 struct per_bio_data *pb = get_per_bio_data(bio);
1753 inc_miss_counter(cache, bio);
1754 if (pb->req_nr == 0) {
1755 accounted_begin(cache, bio);
1756 remap_to_origin_clear_discard(cache, bio, block);
1759 * This is a duplicate writethrough io that is no
1760 * longer needed because the block has been demoted.
1763 return DM_MAPIO_SUBMITTED;
1769 inc_hit_counter(cache, bio);
1772 * Passthrough always maps to the origin, invalidating any
1773 * cache blocks that are written to.
1775 if (passthrough_mode(cache)) {
1776 if (bio_data_dir(bio) == WRITE) {
1777 bio_drop_shared_lock(cache, bio);
1778 atomic_inc(&cache->stats.demotion);
1779 invalidate_start(cache, cblock, block, bio);
1781 remap_to_origin_clear_discard(cache, bio, block);
1783 if (bio_data_dir(bio) == WRITE && writethrough_mode(cache) &&
1784 !is_dirty(cache, cblock)) {
1785 remap_to_origin_and_cache(cache, bio, block, cblock);
1786 accounted_begin(cache, bio);
1788 remap_to_cache_dirty(cache, bio, block, cblock);
1793 * dm core turns FUA requests into a separate payload and FLUSH req.
1795 if (bio->bi_opf & REQ_FUA) {
1797 * issue_after_commit will call accounted_begin a second time. So
1798 * we call accounted_complete() to avoid double accounting.
1800 accounted_complete(cache, bio);
1801 issue_after_commit(&cache->committer, bio);
1802 *commit_needed = true;
1803 return DM_MAPIO_SUBMITTED;
1806 return DM_MAPIO_REMAPPED;
1809 static bool process_bio(struct cache *cache, struct bio *bio)
1813 if (map_bio(cache, bio, get_bio_block(cache, bio), &commit_needed) == DM_MAPIO_REMAPPED)
1814 generic_make_request(bio);
1816 return commit_needed;
1820 * A non-zero return indicates read_only or fail_io mode.
1822 static int commit(struct cache *cache, bool clean_shutdown)
1826 if (get_cache_mode(cache) >= CM_READ_ONLY)
1829 atomic_inc(&cache->stats.commit_count);
1830 r = dm_cache_commit(cache->cmd, clean_shutdown);
1832 metadata_operation_failed(cache, "dm_cache_commit", r);
1838 * Used by the batcher.
1840 static blk_status_t commit_op(void *context)
1842 struct cache *cache = context;
1844 if (dm_cache_changed_this_transaction(cache->cmd))
1845 return errno_to_blk_status(commit(cache, false));
1850 /*----------------------------------------------------------------*/
1852 static bool process_flush_bio(struct cache *cache, struct bio *bio)
1854 struct per_bio_data *pb = get_per_bio_data(bio);
1857 remap_to_origin(cache, bio);
1859 remap_to_cache(cache, bio, 0);
1861 issue_after_commit(&cache->committer, bio);
1865 static bool process_discard_bio(struct cache *cache, struct bio *bio)
1869 // FIXME: do we need to lock the region? Or can we just assume the
1870 // user wont be so foolish as to issue discard concurrently with
1872 calc_discard_block_range(cache, bio, &b, &e);
1874 set_discard(cache, b);
1875 b = to_dblock(from_dblock(b) + 1);
1883 static void process_deferred_bios(struct work_struct *ws)
1885 struct cache *cache = container_of(ws, struct cache, deferred_bio_worker);
1887 unsigned long flags;
1888 bool commit_needed = false;
1889 struct bio_list bios;
1892 bio_list_init(&bios);
1894 spin_lock_irqsave(&cache->lock, flags);
1895 bio_list_merge(&bios, &cache->deferred_bios);
1896 bio_list_init(&cache->deferred_bios);
1897 spin_unlock_irqrestore(&cache->lock, flags);
1899 while ((bio = bio_list_pop(&bios))) {
1900 if (bio->bi_opf & REQ_PREFLUSH)
1901 commit_needed = process_flush_bio(cache, bio) || commit_needed;
1903 else if (bio_op(bio) == REQ_OP_DISCARD)
1904 commit_needed = process_discard_bio(cache, bio) || commit_needed;
1907 commit_needed = process_bio(cache, bio) || commit_needed;
1912 schedule_commit(&cache->committer);
1915 /*----------------------------------------------------------------
1917 *--------------------------------------------------------------*/
1919 static void requeue_deferred_bios(struct cache *cache)
1922 struct bio_list bios;
1924 bio_list_init(&bios);
1925 bio_list_merge(&bios, &cache->deferred_bios);
1926 bio_list_init(&cache->deferred_bios);
1928 while ((bio = bio_list_pop(&bios))) {
1929 bio->bi_status = BLK_STS_DM_REQUEUE;
1936 * We want to commit periodically so that not too much
1937 * unwritten metadata builds up.
1939 static void do_waker(struct work_struct *ws)
1941 struct cache *cache = container_of(to_delayed_work(ws), struct cache, waker);
1943 policy_tick(cache->policy, true);
1944 wake_migration_worker(cache);
1945 schedule_commit(&cache->committer);
1946 queue_delayed_work(cache->wq, &cache->waker, COMMIT_PERIOD);
1949 static void check_migrations(struct work_struct *ws)
1952 struct policy_work *op;
1953 struct cache *cache = container_of(ws, struct cache, migration_worker);
1957 b = spare_migration_bandwidth(cache);
1959 r = policy_get_background_work(cache->policy, b == IDLE, &op);
1964 DMERR_LIMIT("%s: policy_background_work failed",
1965 cache_device_name(cache));
1969 r = mg_start(cache, op, NULL);
1977 /*----------------------------------------------------------------
1979 *--------------------------------------------------------------*/
1982 * This function gets called on the error paths of the constructor, so we
1983 * have to cope with a partially initialised struct.
1985 static void destroy(struct cache *cache)
1989 mempool_exit(&cache->migration_pool);
1992 dm_bio_prison_destroy_v2(cache->prison);
1994 cancel_delayed_work_sync(&cache->waker);
1996 destroy_workqueue(cache->wq);
1998 if (cache->dirty_bitset)
1999 free_bitset(cache->dirty_bitset);
2001 if (cache->discard_bitset)
2002 free_bitset(cache->discard_bitset);
2005 dm_kcopyd_client_destroy(cache->copier);
2008 dm_cache_metadata_close(cache->cmd);
2010 if (cache->metadata_dev)
2011 dm_put_device(cache->ti, cache->metadata_dev);
2013 if (cache->origin_dev)
2014 dm_put_device(cache->ti, cache->origin_dev);
2016 if (cache->cache_dev)
2017 dm_put_device(cache->ti, cache->cache_dev);
2020 dm_cache_policy_destroy(cache->policy);
2022 for (i = 0; i < cache->nr_ctr_args ; i++)
2023 kfree(cache->ctr_args[i]);
2024 kfree(cache->ctr_args);
2026 bioset_exit(&cache->bs);
2031 static void cache_dtr(struct dm_target *ti)
2033 struct cache *cache = ti->private;
2038 static sector_t get_dev_size(struct dm_dev *dev)
2040 return i_size_read(dev->bdev->bd_inode) >> SECTOR_SHIFT;
2043 /*----------------------------------------------------------------*/
2046 * Construct a cache device mapping.
2048 * cache <metadata dev> <cache dev> <origin dev> <block size>
2049 * <#feature args> [<feature arg>]*
2050 * <policy> <#policy args> [<policy arg>]*
2052 * metadata dev : fast device holding the persistent metadata
2053 * cache dev : fast device holding cached data blocks
2054 * origin dev : slow device holding original data blocks
2055 * block size : cache unit size in sectors
2057 * #feature args : number of feature arguments passed
2058 * feature args : writethrough. (The default is writeback.)
2060 * policy : the replacement policy to use
2061 * #policy args : an even number of policy arguments corresponding
2062 * to key/value pairs passed to the policy
2063 * policy args : key/value pairs passed to the policy
2064 * E.g. 'sequential_threshold 1024'
2065 * See cache-policies.txt for details.
2067 * Optional feature arguments are:
2068 * writethrough : write through caching that prohibits cache block
2069 * content from being different from origin block content.
2070 * Without this argument, the default behaviour is to write
2071 * back cache block contents later for performance reasons,
2072 * so they may differ from the corresponding origin blocks.
2075 struct dm_target *ti;
2077 struct dm_dev *metadata_dev;
2079 struct dm_dev *cache_dev;
2080 sector_t cache_sectors;
2082 struct dm_dev *origin_dev;
2083 sector_t origin_sectors;
2085 uint32_t block_size;
2087 const char *policy_name;
2089 const char **policy_argv;
2091 struct cache_features features;
2094 static void destroy_cache_args(struct cache_args *ca)
2096 if (ca->metadata_dev)
2097 dm_put_device(ca->ti, ca->metadata_dev);
2100 dm_put_device(ca->ti, ca->cache_dev);
2103 dm_put_device(ca->ti, ca->origin_dev);
2108 static bool at_least_one_arg(struct dm_arg_set *as, char **error)
2111 *error = "Insufficient args";
2118 static int parse_metadata_dev(struct cache_args *ca, struct dm_arg_set *as,
2122 sector_t metadata_dev_size;
2123 char b[BDEVNAME_SIZE];
2125 if (!at_least_one_arg(as, error))
2128 r = dm_get_device(ca->ti, dm_shift_arg(as), FMODE_READ | FMODE_WRITE,
2131 *error = "Error opening metadata device";
2135 metadata_dev_size = get_dev_size(ca->metadata_dev);
2136 if (metadata_dev_size > DM_CACHE_METADATA_MAX_SECTORS_WARNING)
2137 DMWARN("Metadata device %s is larger than %u sectors: excess space will not be used.",
2138 bdevname(ca->metadata_dev->bdev, b), THIN_METADATA_MAX_SECTORS);
2143 static int parse_cache_dev(struct cache_args *ca, struct dm_arg_set *as,
2148 if (!at_least_one_arg(as, error))
2151 r = dm_get_device(ca->ti, dm_shift_arg(as), FMODE_READ | FMODE_WRITE,
2154 *error = "Error opening cache device";
2157 ca->cache_sectors = get_dev_size(ca->cache_dev);
2162 static int parse_origin_dev(struct cache_args *ca, struct dm_arg_set *as,
2167 if (!at_least_one_arg(as, error))
2170 r = dm_get_device(ca->ti, dm_shift_arg(as), FMODE_READ | FMODE_WRITE,
2173 *error = "Error opening origin device";
2177 ca->origin_sectors = get_dev_size(ca->origin_dev);
2178 if (ca->ti->len > ca->origin_sectors) {
2179 *error = "Device size larger than cached device";
2186 static int parse_block_size(struct cache_args *ca, struct dm_arg_set *as,
2189 unsigned long block_size;
2191 if (!at_least_one_arg(as, error))
2194 if (kstrtoul(dm_shift_arg(as), 10, &block_size) || !block_size ||
2195 block_size < DATA_DEV_BLOCK_SIZE_MIN_SECTORS ||
2196 block_size > DATA_DEV_BLOCK_SIZE_MAX_SECTORS ||
2197 block_size & (DATA_DEV_BLOCK_SIZE_MIN_SECTORS - 1)) {
2198 *error = "Invalid data block size";
2202 if (block_size > ca->cache_sectors) {
2203 *error = "Data block size is larger than the cache device";
2207 ca->block_size = block_size;
2212 static void init_features(struct cache_features *cf)
2214 cf->mode = CM_WRITE;
2215 cf->io_mode = CM_IO_WRITEBACK;
2216 cf->metadata_version = 1;
2219 static int parse_features(struct cache_args *ca, struct dm_arg_set *as,
2222 static const struct dm_arg _args[] = {
2223 {0, 2, "Invalid number of cache feature arguments"},
2226 int r, mode_ctr = 0;
2229 struct cache_features *cf = &ca->features;
2233 r = dm_read_arg_group(_args, as, &argc, error);
2238 arg = dm_shift_arg(as);
2240 if (!strcasecmp(arg, "writeback")) {
2241 cf->io_mode = CM_IO_WRITEBACK;
2245 else if (!strcasecmp(arg, "writethrough")) {
2246 cf->io_mode = CM_IO_WRITETHROUGH;
2250 else if (!strcasecmp(arg, "passthrough")) {
2251 cf->io_mode = CM_IO_PASSTHROUGH;
2255 else if (!strcasecmp(arg, "metadata2"))
2256 cf->metadata_version = 2;
2259 *error = "Unrecognised cache feature requested";
2265 *error = "Duplicate cache io_mode features requested";
2272 static int parse_policy(struct cache_args *ca, struct dm_arg_set *as,
2275 static const struct dm_arg _args[] = {
2276 {0, 1024, "Invalid number of policy arguments"},
2281 if (!at_least_one_arg(as, error))
2284 ca->policy_name = dm_shift_arg(as);
2286 r = dm_read_arg_group(_args, as, &ca->policy_argc, error);
2290 ca->policy_argv = (const char **)as->argv;
2291 dm_consume_args(as, ca->policy_argc);
2296 static int parse_cache_args(struct cache_args *ca, int argc, char **argv,
2300 struct dm_arg_set as;
2305 r = parse_metadata_dev(ca, &as, error);
2309 r = parse_cache_dev(ca, &as, error);
2313 r = parse_origin_dev(ca, &as, error);
2317 r = parse_block_size(ca, &as, error);
2321 r = parse_features(ca, &as, error);
2325 r = parse_policy(ca, &as, error);
2332 /*----------------------------------------------------------------*/
2334 static struct kmem_cache *migration_cache;
2336 #define NOT_CORE_OPTION 1
2338 static int process_config_option(struct cache *cache, const char *key, const char *value)
2342 if (!strcasecmp(key, "migration_threshold")) {
2343 if (kstrtoul(value, 10, &tmp))
2346 cache->migration_threshold = tmp;
2350 return NOT_CORE_OPTION;
2353 static int set_config_value(struct cache *cache, const char *key, const char *value)
2355 int r = process_config_option(cache, key, value);
2357 if (r == NOT_CORE_OPTION)
2358 r = policy_set_config_value(cache->policy, key, value);
2361 DMWARN("bad config value for %s: %s", key, value);
2366 static int set_config_values(struct cache *cache, int argc, const char **argv)
2371 DMWARN("Odd number of policy arguments given but they should be <key> <value> pairs.");
2376 r = set_config_value(cache, argv[0], argv[1]);
2387 static int create_cache_policy(struct cache *cache, struct cache_args *ca,
2390 struct dm_cache_policy *p = dm_cache_policy_create(ca->policy_name,
2392 cache->origin_sectors,
2393 cache->sectors_per_block);
2395 *error = "Error creating cache's policy";
2399 BUG_ON(!cache->policy);
2405 * We want the discard block size to be at least the size of the cache
2406 * block size and have no more than 2^14 discard blocks across the origin.
2408 #define MAX_DISCARD_BLOCKS (1 << 14)
2410 static bool too_many_discard_blocks(sector_t discard_block_size,
2411 sector_t origin_size)
2413 (void) sector_div(origin_size, discard_block_size);
2415 return origin_size > MAX_DISCARD_BLOCKS;
2418 static sector_t calculate_discard_block_size(sector_t cache_block_size,
2419 sector_t origin_size)
2421 sector_t discard_block_size = cache_block_size;
2424 while (too_many_discard_blocks(discard_block_size, origin_size))
2425 discard_block_size *= 2;
2427 return discard_block_size;
2430 static void set_cache_size(struct cache *cache, dm_cblock_t size)
2432 dm_block_t nr_blocks = from_cblock(size);
2434 if (nr_blocks > (1 << 20) && cache->cache_size != size)
2435 DMWARN_LIMIT("You have created a cache device with a lot of individual cache blocks (%llu)\n"
2436 "All these mappings can consume a lot of kernel memory, and take some time to read/write.\n"
2437 "Please consider increasing the cache block size to reduce the overall cache block count.",
2438 (unsigned long long) nr_blocks);
2440 cache->cache_size = size;
2443 static int is_congested(struct dm_dev *dev, int bdi_bits)
2445 struct request_queue *q = bdev_get_queue(dev->bdev);
2446 return bdi_congested(q->backing_dev_info, bdi_bits);
2449 static int cache_is_congested(struct dm_target_callbacks *cb, int bdi_bits)
2451 struct cache *cache = container_of(cb, struct cache, callbacks);
2453 return is_congested(cache->origin_dev, bdi_bits) ||
2454 is_congested(cache->cache_dev, bdi_bits);
2457 #define DEFAULT_MIGRATION_THRESHOLD 2048
2459 static int cache_create(struct cache_args *ca, struct cache **result)
2462 char **error = &ca->ti->error;
2463 struct cache *cache;
2464 struct dm_target *ti = ca->ti;
2465 dm_block_t origin_blocks;
2466 struct dm_cache_metadata *cmd;
2467 bool may_format = ca->features.mode == CM_WRITE;
2469 cache = kzalloc(sizeof(*cache), GFP_KERNEL);
2474 ti->private = cache;
2475 ti->num_flush_bios = 2;
2476 ti->flush_supported = true;
2478 ti->num_discard_bios = 1;
2479 ti->discards_supported = true;
2480 ti->split_discard_bios = false;
2482 ti->per_io_data_size = sizeof(struct per_bio_data);
2484 cache->features = ca->features;
2485 if (writethrough_mode(cache)) {
2486 /* Create bioset for writethrough bios issued to origin */
2487 r = bioset_init(&cache->bs, BIO_POOL_SIZE, 0, 0);
2492 cache->callbacks.congested_fn = cache_is_congested;
2493 dm_table_add_target_callbacks(ti->table, &cache->callbacks);
2495 cache->metadata_dev = ca->metadata_dev;
2496 cache->origin_dev = ca->origin_dev;
2497 cache->cache_dev = ca->cache_dev;
2499 ca->metadata_dev = ca->origin_dev = ca->cache_dev = NULL;
2501 origin_blocks = cache->origin_sectors = ca->origin_sectors;
2502 origin_blocks = block_div(origin_blocks, ca->block_size);
2503 cache->origin_blocks = to_oblock(origin_blocks);
2505 cache->sectors_per_block = ca->block_size;
2506 if (dm_set_target_max_io_len(ti, cache->sectors_per_block)) {
2511 if (ca->block_size & (ca->block_size - 1)) {
2512 dm_block_t cache_size = ca->cache_sectors;
2514 cache->sectors_per_block_shift = -1;
2515 cache_size = block_div(cache_size, ca->block_size);
2516 set_cache_size(cache, to_cblock(cache_size));
2518 cache->sectors_per_block_shift = __ffs(ca->block_size);
2519 set_cache_size(cache, to_cblock(ca->cache_sectors >> cache->sectors_per_block_shift));
2522 r = create_cache_policy(cache, ca, error);
2526 cache->policy_nr_args = ca->policy_argc;
2527 cache->migration_threshold = DEFAULT_MIGRATION_THRESHOLD;
2529 r = set_config_values(cache, ca->policy_argc, ca->policy_argv);
2531 *error = "Error setting cache policy's config values";
2535 cmd = dm_cache_metadata_open(cache->metadata_dev->bdev,
2536 ca->block_size, may_format,
2537 dm_cache_policy_get_hint_size(cache->policy),
2538 ca->features.metadata_version);
2540 *error = "Error creating metadata object";
2545 set_cache_mode(cache, CM_WRITE);
2546 if (get_cache_mode(cache) != CM_WRITE) {
2547 *error = "Unable to get write access to metadata, please check/repair metadata.";
2552 if (passthrough_mode(cache)) {
2555 r = dm_cache_metadata_all_clean(cache->cmd, &all_clean);
2557 *error = "dm_cache_metadata_all_clean() failed";
2562 *error = "Cannot enter passthrough mode unless all blocks are clean";
2567 policy_allow_migrations(cache->policy, false);
2570 spin_lock_init(&cache->lock);
2571 bio_list_init(&cache->deferred_bios);
2572 atomic_set(&cache->nr_allocated_migrations, 0);
2573 atomic_set(&cache->nr_io_migrations, 0);
2574 init_waitqueue_head(&cache->migration_wait);
2577 atomic_set(&cache->nr_dirty, 0);
2578 cache->dirty_bitset = alloc_bitset(from_cblock(cache->cache_size));
2579 if (!cache->dirty_bitset) {
2580 *error = "could not allocate dirty bitset";
2583 clear_bitset(cache->dirty_bitset, from_cblock(cache->cache_size));
2585 cache->discard_block_size =
2586 calculate_discard_block_size(cache->sectors_per_block,
2587 cache->origin_sectors);
2588 cache->discard_nr_blocks = to_dblock(dm_sector_div_up(cache->origin_sectors,
2589 cache->discard_block_size));
2590 cache->discard_bitset = alloc_bitset(from_dblock(cache->discard_nr_blocks));
2591 if (!cache->discard_bitset) {
2592 *error = "could not allocate discard bitset";
2595 clear_bitset(cache->discard_bitset, from_dblock(cache->discard_nr_blocks));
2597 cache->copier = dm_kcopyd_client_create(&dm_kcopyd_throttle);
2598 if (IS_ERR(cache->copier)) {
2599 *error = "could not create kcopyd client";
2600 r = PTR_ERR(cache->copier);
2604 cache->wq = alloc_workqueue("dm-" DM_MSG_PREFIX, WQ_MEM_RECLAIM, 0);
2606 *error = "could not create workqueue for metadata object";
2609 INIT_WORK(&cache->deferred_bio_worker, process_deferred_bios);
2610 INIT_WORK(&cache->migration_worker, check_migrations);
2611 INIT_DELAYED_WORK(&cache->waker, do_waker);
2613 cache->prison = dm_bio_prison_create_v2(cache->wq);
2614 if (!cache->prison) {
2615 *error = "could not create bio prison";
2619 r = mempool_init_slab_pool(&cache->migration_pool, MIGRATION_POOL_SIZE,
2622 *error = "Error creating cache's migration mempool";
2626 cache->need_tick_bio = true;
2627 cache->sized = false;
2628 cache->invalidate = false;
2629 cache->commit_requested = false;
2630 cache->loaded_mappings = false;
2631 cache->loaded_discards = false;
2635 atomic_set(&cache->stats.demotion, 0);
2636 atomic_set(&cache->stats.promotion, 0);
2637 atomic_set(&cache->stats.copies_avoided, 0);
2638 atomic_set(&cache->stats.cache_cell_clash, 0);
2639 atomic_set(&cache->stats.commit_count, 0);
2640 atomic_set(&cache->stats.discard_count, 0);
2642 spin_lock_init(&cache->invalidation_lock);
2643 INIT_LIST_HEAD(&cache->invalidation_requests);
2645 batcher_init(&cache->committer, commit_op, cache,
2646 issue_op, cache, cache->wq);
2647 iot_init(&cache->tracker);
2649 init_rwsem(&cache->background_work_lock);
2650 prevent_background_work(cache);
2659 static int copy_ctr_args(struct cache *cache, int argc, const char **argv)
2664 copy = kcalloc(argc, sizeof(*copy), GFP_KERNEL);
2667 for (i = 0; i < argc; i++) {
2668 copy[i] = kstrdup(argv[i], GFP_KERNEL);
2677 cache->nr_ctr_args = argc;
2678 cache->ctr_args = copy;
2683 static int cache_ctr(struct dm_target *ti, unsigned argc, char **argv)
2686 struct cache_args *ca;
2687 struct cache *cache = NULL;
2689 ca = kzalloc(sizeof(*ca), GFP_KERNEL);
2691 ti->error = "Error allocating memory for cache";
2696 r = parse_cache_args(ca, argc, argv, &ti->error);
2700 r = cache_create(ca, &cache);
2704 r = copy_ctr_args(cache, argc - 3, (const char **)argv + 3);
2710 ti->private = cache;
2712 destroy_cache_args(ca);
2716 /*----------------------------------------------------------------*/
2718 static int cache_map(struct dm_target *ti, struct bio *bio)
2720 struct cache *cache = ti->private;
2724 dm_oblock_t block = get_bio_block(cache, bio);
2726 init_per_bio_data(bio);
2727 if (unlikely(from_oblock(block) >= from_oblock(cache->origin_blocks))) {
2729 * This can only occur if the io goes to a partial block at
2730 * the end of the origin device. We don't cache these.
2731 * Just remap to the origin and carry on.
2733 remap_to_origin(cache, bio);
2734 accounted_begin(cache, bio);
2735 return DM_MAPIO_REMAPPED;
2738 if (discard_or_flush(bio)) {
2739 defer_bio(cache, bio);
2740 return DM_MAPIO_SUBMITTED;
2743 r = map_bio(cache, bio, block, &commit_needed);
2745 schedule_commit(&cache->committer);
2750 static int cache_end_io(struct dm_target *ti, struct bio *bio, blk_status_t *error)
2752 struct cache *cache = ti->private;
2753 unsigned long flags;
2754 struct per_bio_data *pb = get_per_bio_data(bio);
2757 policy_tick(cache->policy, false);
2759 spin_lock_irqsave(&cache->lock, flags);
2760 cache->need_tick_bio = true;
2761 spin_unlock_irqrestore(&cache->lock, flags);
2764 bio_drop_shared_lock(cache, bio);
2765 accounted_complete(cache, bio);
2767 return DM_ENDIO_DONE;
2770 static int write_dirty_bitset(struct cache *cache)
2774 if (get_cache_mode(cache) >= CM_READ_ONLY)
2777 r = dm_cache_set_dirty_bits(cache->cmd, from_cblock(cache->cache_size), cache->dirty_bitset);
2779 metadata_operation_failed(cache, "dm_cache_set_dirty_bits", r);
2784 static int write_discard_bitset(struct cache *cache)
2788 if (get_cache_mode(cache) >= CM_READ_ONLY)
2791 r = dm_cache_discard_bitset_resize(cache->cmd, cache->discard_block_size,
2792 cache->discard_nr_blocks);
2794 DMERR("%s: could not resize on-disk discard bitset", cache_device_name(cache));
2795 metadata_operation_failed(cache, "dm_cache_discard_bitset_resize", r);
2799 for (i = 0; i < from_dblock(cache->discard_nr_blocks); i++) {
2800 r = dm_cache_set_discard(cache->cmd, to_dblock(i),
2801 is_discarded(cache, to_dblock(i)));
2803 metadata_operation_failed(cache, "dm_cache_set_discard", r);
2811 static int write_hints(struct cache *cache)
2815 if (get_cache_mode(cache) >= CM_READ_ONLY)
2818 r = dm_cache_write_hints(cache->cmd, cache->policy);
2820 metadata_operation_failed(cache, "dm_cache_write_hints", r);
2828 * returns true on success
2830 static bool sync_metadata(struct cache *cache)
2834 r1 = write_dirty_bitset(cache);
2836 DMERR("%s: could not write dirty bitset", cache_device_name(cache));
2838 r2 = write_discard_bitset(cache);
2840 DMERR("%s: could not write discard bitset", cache_device_name(cache));
2844 r3 = write_hints(cache);
2846 DMERR("%s: could not write hints", cache_device_name(cache));
2849 * If writing the above metadata failed, we still commit, but don't
2850 * set the clean shutdown flag. This will effectively force every
2851 * dirty bit to be set on reload.
2853 r4 = commit(cache, !r1 && !r2 && !r3);
2855 DMERR("%s: could not write cache metadata", cache_device_name(cache));
2857 return !r1 && !r2 && !r3 && !r4;
2860 static void cache_postsuspend(struct dm_target *ti)
2862 struct cache *cache = ti->private;
2864 prevent_background_work(cache);
2865 BUG_ON(atomic_read(&cache->nr_io_migrations));
2867 cancel_delayed_work_sync(&cache->waker);
2868 drain_workqueue(cache->wq);
2869 WARN_ON(cache->tracker.in_flight);
2872 * If it's a flush suspend there won't be any deferred bios, so this
2875 requeue_deferred_bios(cache);
2877 if (get_cache_mode(cache) == CM_WRITE)
2878 (void) sync_metadata(cache);
2881 static int load_mapping(void *context, dm_oblock_t oblock, dm_cblock_t cblock,
2882 bool dirty, uint32_t hint, bool hint_valid)
2885 struct cache *cache = context;
2888 set_bit(from_cblock(cblock), cache->dirty_bitset);
2889 atomic_inc(&cache->nr_dirty);
2891 clear_bit(from_cblock(cblock), cache->dirty_bitset);
2893 r = policy_load_mapping(cache->policy, oblock, cblock, dirty, hint, hint_valid);
2901 * The discard block size in the on disk metadata is not
2902 * neccessarily the same as we're currently using. So we have to
2903 * be careful to only set the discarded attribute if we know it
2904 * covers a complete block of the new size.
2906 struct discard_load_info {
2907 struct cache *cache;
2910 * These blocks are sized using the on disk dblock size, rather
2911 * than the current one.
2913 dm_block_t block_size;
2914 dm_block_t discard_begin, discard_end;
2917 static void discard_load_info_init(struct cache *cache,
2918 struct discard_load_info *li)
2921 li->discard_begin = li->discard_end = 0;
2924 static void set_discard_range(struct discard_load_info *li)
2928 if (li->discard_begin == li->discard_end)
2932 * Convert to sectors.
2934 b = li->discard_begin * li->block_size;
2935 e = li->discard_end * li->block_size;
2938 * Then convert back to the current dblock size.
2940 b = dm_sector_div_up(b, li->cache->discard_block_size);
2941 sector_div(e, li->cache->discard_block_size);
2944 * The origin may have shrunk, so we need to check we're still in
2947 if (e > from_dblock(li->cache->discard_nr_blocks))
2948 e = from_dblock(li->cache->discard_nr_blocks);
2951 set_discard(li->cache, to_dblock(b));
2954 static int load_discard(void *context, sector_t discard_block_size,
2955 dm_dblock_t dblock, bool discard)
2957 struct discard_load_info *li = context;
2959 li->block_size = discard_block_size;
2962 if (from_dblock(dblock) == li->discard_end)
2964 * We're already in a discard range, just extend it.
2966 li->discard_end = li->discard_end + 1ULL;
2970 * Emit the old range and start a new one.
2972 set_discard_range(li);
2973 li->discard_begin = from_dblock(dblock);
2974 li->discard_end = li->discard_begin + 1ULL;
2977 set_discard_range(li);
2978 li->discard_begin = li->discard_end = 0;
2984 static dm_cblock_t get_cache_dev_size(struct cache *cache)
2986 sector_t size = get_dev_size(cache->cache_dev);
2987 (void) sector_div(size, cache->sectors_per_block);
2988 return to_cblock(size);
2991 static bool can_resize(struct cache *cache, dm_cblock_t new_size)
2993 if (from_cblock(new_size) > from_cblock(cache->cache_size)) {
2995 DMERR("%s: unable to extend cache due to missing cache table reload",
2996 cache_device_name(cache));
3002 * We can't drop a dirty block when shrinking the cache.
3004 while (from_cblock(new_size) < from_cblock(cache->cache_size)) {
3005 new_size = to_cblock(from_cblock(new_size) + 1);
3006 if (is_dirty(cache, new_size)) {
3007 DMERR("%s: unable to shrink cache; cache block %llu is dirty",
3008 cache_device_name(cache),
3009 (unsigned long long) from_cblock(new_size));
3017 static int resize_cache_dev(struct cache *cache, dm_cblock_t new_size)
3021 r = dm_cache_resize(cache->cmd, new_size);
3023 DMERR("%s: could not resize cache metadata", cache_device_name(cache));
3024 metadata_operation_failed(cache, "dm_cache_resize", r);
3028 set_cache_size(cache, new_size);
3033 static int cache_preresume(struct dm_target *ti)
3036 struct cache *cache = ti->private;
3037 dm_cblock_t csize = get_cache_dev_size(cache);
3040 * Check to see if the cache has resized.
3042 if (!cache->sized) {
3043 r = resize_cache_dev(cache, csize);
3047 cache->sized = true;
3049 } else if (csize != cache->cache_size) {
3050 if (!can_resize(cache, csize))
3053 r = resize_cache_dev(cache, csize);
3058 if (!cache->loaded_mappings) {
3059 r = dm_cache_load_mappings(cache->cmd, cache->policy,
3060 load_mapping, cache);
3062 DMERR("%s: could not load cache mappings", cache_device_name(cache));
3063 metadata_operation_failed(cache, "dm_cache_load_mappings", r);
3067 cache->loaded_mappings = true;
3070 if (!cache->loaded_discards) {
3071 struct discard_load_info li;
3074 * The discard bitset could have been resized, or the
3075 * discard block size changed. To be safe we start by
3076 * setting every dblock to not discarded.
3078 clear_bitset(cache->discard_bitset, from_dblock(cache->discard_nr_blocks));
3080 discard_load_info_init(cache, &li);
3081 r = dm_cache_load_discards(cache->cmd, load_discard, &li);
3083 DMERR("%s: could not load origin discards", cache_device_name(cache));
3084 metadata_operation_failed(cache, "dm_cache_load_discards", r);
3087 set_discard_range(&li);
3089 cache->loaded_discards = true;
3095 static void cache_resume(struct dm_target *ti)
3097 struct cache *cache = ti->private;
3099 cache->need_tick_bio = true;
3100 allow_background_work(cache);
3101 do_waker(&cache->waker.work);
3107 * <metadata block size> <#used metadata blocks>/<#total metadata blocks>
3108 * <cache block size> <#used cache blocks>/<#total cache blocks>
3109 * <#read hits> <#read misses> <#write hits> <#write misses>
3110 * <#demotions> <#promotions> <#dirty>
3111 * <#features> <features>*
3112 * <#core args> <core args>
3113 * <policy name> <#policy args> <policy args>* <cache metadata mode> <needs_check>
3115 static void cache_status(struct dm_target *ti, status_type_t type,
3116 unsigned status_flags, char *result, unsigned maxlen)
3121 dm_block_t nr_free_blocks_metadata = 0;
3122 dm_block_t nr_blocks_metadata = 0;
3123 char buf[BDEVNAME_SIZE];
3124 struct cache *cache = ti->private;
3125 dm_cblock_t residency;
3129 case STATUSTYPE_INFO:
3130 if (get_cache_mode(cache) == CM_FAIL) {
3135 /* Commit to ensure statistics aren't out-of-date */
3136 if (!(status_flags & DM_STATUS_NOFLUSH_FLAG) && !dm_suspended(ti))
3137 (void) commit(cache, false);
3139 r = dm_cache_get_free_metadata_block_count(cache->cmd, &nr_free_blocks_metadata);
3141 DMERR("%s: dm_cache_get_free_metadata_block_count returned %d",
3142 cache_device_name(cache), r);
3146 r = dm_cache_get_metadata_dev_size(cache->cmd, &nr_blocks_metadata);
3148 DMERR("%s: dm_cache_get_metadata_dev_size returned %d",
3149 cache_device_name(cache), r);
3153 residency = policy_residency(cache->policy);
3155 DMEMIT("%u %llu/%llu %llu %llu/%llu %u %u %u %u %u %u %lu ",
3156 (unsigned)DM_CACHE_METADATA_BLOCK_SIZE,
3157 (unsigned long long)(nr_blocks_metadata - nr_free_blocks_metadata),
3158 (unsigned long long)nr_blocks_metadata,
3159 (unsigned long long)cache->sectors_per_block,
3160 (unsigned long long) from_cblock(residency),
3161 (unsigned long long) from_cblock(cache->cache_size),
3162 (unsigned) atomic_read(&cache->stats.read_hit),
3163 (unsigned) atomic_read(&cache->stats.read_miss),
3164 (unsigned) atomic_read(&cache->stats.write_hit),
3165 (unsigned) atomic_read(&cache->stats.write_miss),
3166 (unsigned) atomic_read(&cache->stats.demotion),
3167 (unsigned) atomic_read(&cache->stats.promotion),
3168 (unsigned long) atomic_read(&cache->nr_dirty));
3170 if (cache->features.metadata_version == 2)
3171 DMEMIT("2 metadata2 ");
3175 if (writethrough_mode(cache))
3176 DMEMIT("writethrough ");
3178 else if (passthrough_mode(cache))
3179 DMEMIT("passthrough ");
3181 else if (writeback_mode(cache))
3182 DMEMIT("writeback ");
3185 DMERR("%s: internal error: unknown io mode: %d",
3186 cache_device_name(cache), (int) cache->features.io_mode);
3190 DMEMIT("2 migration_threshold %llu ", (unsigned long long) cache->migration_threshold);
3192 DMEMIT("%s ", dm_cache_policy_get_name(cache->policy));
3194 r = policy_emit_config_values(cache->policy, result, maxlen, &sz);
3196 DMERR("%s: policy_emit_config_values returned %d",
3197 cache_device_name(cache), r);
3200 if (get_cache_mode(cache) == CM_READ_ONLY)
3205 r = dm_cache_metadata_needs_check(cache->cmd, &needs_check);
3207 if (r || needs_check)
3208 DMEMIT("needs_check ");
3214 case STATUSTYPE_TABLE:
3215 format_dev_t(buf, cache->metadata_dev->bdev->bd_dev);
3217 format_dev_t(buf, cache->cache_dev->bdev->bd_dev);
3219 format_dev_t(buf, cache->origin_dev->bdev->bd_dev);
3222 for (i = 0; i < cache->nr_ctr_args - 1; i++)
3223 DMEMIT(" %s", cache->ctr_args[i]);
3224 if (cache->nr_ctr_args)
3225 DMEMIT(" %s", cache->ctr_args[cache->nr_ctr_args - 1]);
3235 * Defines a range of cblocks, begin to (end - 1) are in the range. end is
3236 * the one-past-the-end value.
3238 struct cblock_range {
3244 * A cache block range can take two forms:
3246 * i) A single cblock, eg. '3456'
3247 * ii) A begin and end cblock with a dash between, eg. 123-234
3249 static int parse_cblock_range(struct cache *cache, const char *str,
3250 struct cblock_range *result)
3257 * Try and parse form (ii) first.
3259 r = sscanf(str, "%llu-%llu%c", &b, &e, &dummy);
3264 result->begin = to_cblock(b);
3265 result->end = to_cblock(e);
3270 * That didn't work, try form (i).
3272 r = sscanf(str, "%llu%c", &b, &dummy);
3277 result->begin = to_cblock(b);
3278 result->end = to_cblock(from_cblock(result->begin) + 1u);
3282 DMERR("%s: invalid cblock range '%s'", cache_device_name(cache), str);
3286 static int validate_cblock_range(struct cache *cache, struct cblock_range *range)
3288 uint64_t b = from_cblock(range->begin);
3289 uint64_t e = from_cblock(range->end);
3290 uint64_t n = from_cblock(cache->cache_size);
3293 DMERR("%s: begin cblock out of range: %llu >= %llu",
3294 cache_device_name(cache), b, n);
3299 DMERR("%s: end cblock out of range: %llu > %llu",
3300 cache_device_name(cache), e, n);
3305 DMERR("%s: invalid cblock range: %llu >= %llu",
3306 cache_device_name(cache), b, e);
3313 static inline dm_cblock_t cblock_succ(dm_cblock_t b)
3315 return to_cblock(from_cblock(b) + 1);
3318 static int request_invalidation(struct cache *cache, struct cblock_range *range)
3323 * We don't need to do any locking here because we know we're in
3324 * passthrough mode. There's is potential for a race between an
3325 * invalidation triggered by an io and an invalidation message. This
3326 * is harmless, we must not worry if the policy call fails.
3328 while (range->begin != range->end) {
3329 r = invalidate_cblock(cache, range->begin);
3333 range->begin = cblock_succ(range->begin);
3336 cache->commit_requested = true;
3340 static int process_invalidate_cblocks_message(struct cache *cache, unsigned count,
3341 const char **cblock_ranges)
3345 struct cblock_range range;
3347 if (!passthrough_mode(cache)) {
3348 DMERR("%s: cache has to be in passthrough mode for invalidation",
3349 cache_device_name(cache));
3353 for (i = 0; i < count; i++) {
3354 r = parse_cblock_range(cache, cblock_ranges[i], &range);
3358 r = validate_cblock_range(cache, &range);
3363 * Pass begin and end origin blocks to the worker and wake it.
3365 r = request_invalidation(cache, &range);
3377 * "invalidate_cblocks [(<begin>)|(<begin>-<end>)]*
3379 * The key migration_threshold is supported by the cache target core.
3381 static int cache_message(struct dm_target *ti, unsigned argc, char **argv,
3382 char *result, unsigned maxlen)
3384 struct cache *cache = ti->private;
3389 if (get_cache_mode(cache) >= CM_READ_ONLY) {
3390 DMERR("%s: unable to service cache target messages in READ_ONLY or FAIL mode",
3391 cache_device_name(cache));
3395 if (!strcasecmp(argv[0], "invalidate_cblocks"))
3396 return process_invalidate_cblocks_message(cache, argc - 1, (const char **) argv + 1);
3401 return set_config_value(cache, argv[0], argv[1]);
3404 static int cache_iterate_devices(struct dm_target *ti,
3405 iterate_devices_callout_fn fn, void *data)
3408 struct cache *cache = ti->private;
3410 r = fn(ti, cache->cache_dev, 0, get_dev_size(cache->cache_dev), data);
3412 r = fn(ti, cache->origin_dev, 0, ti->len, data);
3417 static void set_discard_limits(struct cache *cache, struct queue_limits *limits)
3420 * FIXME: these limits may be incompatible with the cache device
3422 limits->max_discard_sectors = min_t(sector_t, cache->discard_block_size * 1024,
3423 cache->origin_sectors);
3424 limits->discard_granularity = cache->discard_block_size << SECTOR_SHIFT;
3427 static void cache_io_hints(struct dm_target *ti, struct queue_limits *limits)
3429 struct cache *cache = ti->private;
3430 uint64_t io_opt_sectors = limits->io_opt >> SECTOR_SHIFT;
3433 * If the system-determined stacked limits are compatible with the
3434 * cache's blocksize (io_opt is a factor) do not override them.
3436 if (io_opt_sectors < cache->sectors_per_block ||
3437 do_div(io_opt_sectors, cache->sectors_per_block)) {
3438 blk_limits_io_min(limits, cache->sectors_per_block << SECTOR_SHIFT);
3439 blk_limits_io_opt(limits, cache->sectors_per_block << SECTOR_SHIFT);
3441 set_discard_limits(cache, limits);
3444 /*----------------------------------------------------------------*/
3446 static struct target_type cache_target = {
3448 .version = {2, 0, 0},
3449 .module = THIS_MODULE,
3453 .end_io = cache_end_io,
3454 .postsuspend = cache_postsuspend,
3455 .preresume = cache_preresume,
3456 .resume = cache_resume,
3457 .status = cache_status,
3458 .message = cache_message,
3459 .iterate_devices = cache_iterate_devices,
3460 .io_hints = cache_io_hints,
3463 static int __init dm_cache_init(void)
3467 migration_cache = KMEM_CACHE(dm_cache_migration, 0);
3468 if (!migration_cache)
3471 r = dm_register_target(&cache_target);
3473 DMERR("cache target registration failed: %d", r);
3474 kmem_cache_destroy(migration_cache);
3481 static void __exit dm_cache_exit(void)
3483 dm_unregister_target(&cache_target);
3484 kmem_cache_destroy(migration_cache);
3487 module_init(dm_cache_init);
3488 module_exit(dm_cache_exit);
3490 MODULE_DESCRIPTION(DM_NAME " cache target");
3491 MODULE_AUTHOR("Joe Thornber <ejt@redhat.com>");
3492 MODULE_LICENSE("GPL");