2 * Copyright (C) 2012 Red Hat. All rights reserved.
4 * This file is released under the GPL.
8 #include "dm-bio-prison.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/init.h>
15 #include <linux/mempool.h>
16 #include <linux/module.h>
17 #include <linux/slab.h>
18 #include <linux/vmalloc.h>
20 #define DM_MSG_PREFIX "cache"
22 DECLARE_DM_KCOPYD_THROTTLE_WITH_MODULE_PARM(cache_copy_throttle,
23 "A percentage of time allocated for copying to and/or from cache");
25 /*----------------------------------------------------------------*/
30 * oblock: index of an origin block
31 * cblock: index of a cache block
32 * promotion: movement of a block from origin to cache
33 * demotion: movement of a block from cache to origin
34 * migration: movement of a block between the origin and cache device,
38 /*----------------------------------------------------------------*/
40 static size_t bitset_size_in_bytes(unsigned nr_entries)
42 return sizeof(unsigned long) * dm_div_up(nr_entries, BITS_PER_LONG);
45 static unsigned long *alloc_bitset(unsigned nr_entries)
47 size_t s = bitset_size_in_bytes(nr_entries);
51 static void clear_bitset(void *bitset, unsigned nr_entries)
53 size_t s = bitset_size_in_bytes(nr_entries);
57 static void free_bitset(unsigned long *bits)
62 /*----------------------------------------------------------------*/
65 * There are a couple of places where we let a bio run, but want to do some
66 * work before calling its endio function. We do this by temporarily
67 * changing the endio fn.
70 bio_end_io_t *bi_end_io;
74 static void dm_hook_bio(struct dm_hook_info *h, struct bio *bio,
75 bio_end_io_t *bi_end_io, void *bi_private)
77 h->bi_end_io = bio->bi_end_io;
78 h->bi_private = bio->bi_private;
80 bio->bi_end_io = bi_end_io;
81 bio->bi_private = bi_private;
84 static void dm_unhook_bio(struct dm_hook_info *h, struct bio *bio)
86 bio->bi_end_io = h->bi_end_io;
87 bio->bi_private = h->bi_private;
90 * Must bump bi_remaining to allow bio to complete with
93 atomic_inc(&bio->bi_remaining);
96 /*----------------------------------------------------------------*/
98 #define MIGRATION_POOL_SIZE 128
99 #define COMMIT_PERIOD HZ
100 #define MIGRATION_COUNT_WINDOW 10
103 * The block size of the device holding cache data must be
104 * between 32KB and 1GB.
106 #define DATA_DEV_BLOCK_SIZE_MIN_SECTORS (32 * 1024 >> SECTOR_SHIFT)
107 #define DATA_DEV_BLOCK_SIZE_MAX_SECTORS (1024 * 1024 * 1024 >> SECTOR_SHIFT)
110 * FIXME: the cache is read/write for the time being.
112 enum cache_metadata_mode {
113 CM_WRITE, /* metadata may be changed */
114 CM_READ_ONLY, /* metadata may not be changed */
119 * Data is written to cached blocks only. These blocks are marked
120 * dirty. If you lose the cache device you will lose data.
121 * Potential performance increase for both reads and writes.
126 * Data is written to both cache and origin. Blocks are never
127 * dirty. Potential performance benfit for reads only.
132 * A degraded mode useful for various cache coherency situations
133 * (eg, rolling back snapshots). Reads and writes always go to the
134 * origin. If a write goes to a cached oblock, then the cache
135 * block is invalidated.
140 struct cache_features {
141 enum cache_metadata_mode mode;
142 enum cache_io_mode io_mode;
152 atomic_t copies_avoided;
153 atomic_t cache_cell_clash;
154 atomic_t commit_count;
155 atomic_t discard_count;
159 * Defines a range of cblocks, begin to (end - 1) are in the range. end is
160 * the one-past-the-end value.
162 struct cblock_range {
167 struct invalidation_request {
168 struct list_head list;
169 struct cblock_range *cblocks;
174 wait_queue_head_t result_wait;
178 struct dm_target *ti;
179 struct dm_target_callbacks callbacks;
181 struct dm_cache_metadata *cmd;
184 * Metadata is written to this device.
186 struct dm_dev *metadata_dev;
189 * The slower of the two data devices. Typically a spindle.
191 struct dm_dev *origin_dev;
194 * The faster of the two data devices. Typically an SSD.
196 struct dm_dev *cache_dev;
199 * Size of the origin device in _complete_ blocks and native sectors.
201 dm_oblock_t origin_blocks;
202 sector_t origin_sectors;
205 * Size of the cache device in blocks.
207 dm_cblock_t cache_size;
210 * Fields for converting from sectors to blocks.
212 uint32_t sectors_per_block;
213 int sectors_per_block_shift;
216 struct bio_list deferred_bios;
217 struct bio_list deferred_flush_bios;
218 struct bio_list deferred_writethrough_bios;
219 struct list_head quiesced_migrations;
220 struct list_head completed_migrations;
221 struct list_head need_commit_migrations;
222 sector_t migration_threshold;
223 wait_queue_head_t migration_wait;
224 atomic_t nr_migrations;
226 wait_queue_head_t quiescing_wait;
228 atomic_t quiescing_ack;
231 * cache_size entries, dirty if set
234 unsigned long *dirty_bitset;
237 * origin_blocks entries, discarded if set.
239 dm_dblock_t discard_nr_blocks;
240 unsigned long *discard_bitset;
241 uint32_t discard_block_size; /* a power of 2 times sectors per block */
244 * Rather than reconstructing the table line for the status we just
245 * save it and regurgitate.
247 unsigned nr_ctr_args;
248 const char **ctr_args;
250 struct dm_kcopyd_client *copier;
251 struct workqueue_struct *wq;
252 struct work_struct worker;
254 struct delayed_work waker;
255 unsigned long last_commit_jiffies;
257 struct dm_bio_prison *prison;
258 struct dm_deferred_set *all_io_ds;
260 mempool_t *migration_pool;
261 struct dm_cache_migration *next_migration;
263 struct dm_cache_policy *policy;
264 unsigned policy_nr_args;
266 bool need_tick_bio:1;
269 bool commit_requested:1;
270 bool loaded_mappings:1;
271 bool loaded_discards:1;
274 * Cache features such as write-through.
276 struct cache_features features;
278 struct cache_stats stats;
281 * Invalidation fields.
283 spinlock_t invalidation_lock;
284 struct list_head invalidation_requests;
287 struct per_bio_data {
290 struct dm_deferred_entry *all_io_entry;
291 struct dm_hook_info hook_info;
294 * writethrough fields. These MUST remain at the end of this
295 * structure and the 'cache' member must be the first as it
296 * is used to determine the offset of the writethrough fields.
300 struct dm_bio_details bio_details;
303 struct dm_cache_migration {
304 struct list_head list;
307 unsigned long start_jiffies;
308 dm_oblock_t old_oblock;
309 dm_oblock_t new_oblock;
317 bool requeue_holder:1;
320 struct dm_bio_prison_cell *old_ocell;
321 struct dm_bio_prison_cell *new_ocell;
325 * Processing a bio in the worker thread may require these memory
326 * allocations. We prealloc to avoid deadlocks (the same worker thread
327 * frees them back to the mempool).
330 struct dm_cache_migration *mg;
331 struct dm_bio_prison_cell *cell1;
332 struct dm_bio_prison_cell *cell2;
335 static void wake_worker(struct cache *cache)
337 queue_work(cache->wq, &cache->worker);
340 /*----------------------------------------------------------------*/
342 static struct dm_bio_prison_cell *alloc_prison_cell(struct cache *cache)
344 /* FIXME: change to use a local slab. */
345 return dm_bio_prison_alloc_cell(cache->prison, GFP_NOWAIT);
348 static void free_prison_cell(struct cache *cache, struct dm_bio_prison_cell *cell)
350 dm_bio_prison_free_cell(cache->prison, cell);
353 static int prealloc_data_structs(struct cache *cache, struct prealloc *p)
356 p->mg = mempool_alloc(cache->migration_pool, GFP_NOWAIT);
362 p->cell1 = alloc_prison_cell(cache);
368 p->cell2 = alloc_prison_cell(cache);
376 static void prealloc_free_structs(struct cache *cache, struct prealloc *p)
379 free_prison_cell(cache, p->cell2);
382 free_prison_cell(cache, p->cell1);
385 mempool_free(p->mg, cache->migration_pool);
388 static struct dm_cache_migration *prealloc_get_migration(struct prealloc *p)
390 struct dm_cache_migration *mg = p->mg;
399 * You must have a cell within the prealloc struct to return. If not this
400 * function will BUG() rather than returning NULL.
402 static struct dm_bio_prison_cell *prealloc_get_cell(struct prealloc *p)
404 struct dm_bio_prison_cell *r = NULL;
410 } else if (p->cell2) {
420 * You can't have more than two cells in a prealloc struct. BUG() will be
421 * called if you try and overfill.
423 static void prealloc_put_cell(struct prealloc *p, struct dm_bio_prison_cell *cell)
435 /*----------------------------------------------------------------*/
437 static void build_key(dm_oblock_t begin, dm_oblock_t end, struct dm_cell_key *key)
441 key->block_begin = from_oblock(begin);
442 key->block_end = from_oblock(end);
446 * The caller hands in a preallocated cell, and a free function for it.
447 * The cell will be freed if there's an error, or if it wasn't used because
448 * a cell with that key already exists.
450 typedef void (*cell_free_fn)(void *context, struct dm_bio_prison_cell *cell);
452 static int bio_detain_range(struct cache *cache, dm_oblock_t oblock_begin, dm_oblock_t oblock_end,
453 struct bio *bio, struct dm_bio_prison_cell *cell_prealloc,
454 cell_free_fn free_fn, void *free_context,
455 struct dm_bio_prison_cell **cell_result)
458 struct dm_cell_key key;
460 build_key(oblock_begin, oblock_end, &key);
461 r = dm_bio_detain(cache->prison, &key, bio, cell_prealloc, cell_result);
463 free_fn(free_context, cell_prealloc);
468 static int bio_detain(struct cache *cache, dm_oblock_t oblock,
469 struct bio *bio, struct dm_bio_prison_cell *cell_prealloc,
470 cell_free_fn free_fn, void *free_context,
471 struct dm_bio_prison_cell **cell_result)
473 dm_oblock_t end = to_oblock(from_oblock(oblock) + 1ULL);
474 return bio_detain_range(cache, oblock, end, bio,
475 cell_prealloc, free_fn, free_context, cell_result);
478 static int get_cell(struct cache *cache,
480 struct prealloc *structs,
481 struct dm_bio_prison_cell **cell_result)
484 struct dm_cell_key key;
485 struct dm_bio_prison_cell *cell_prealloc;
487 cell_prealloc = prealloc_get_cell(structs);
489 build_key(oblock, to_oblock(from_oblock(oblock) + 1ULL), &key);
490 r = dm_get_cell(cache->prison, &key, cell_prealloc, cell_result);
492 prealloc_put_cell(structs, cell_prealloc);
497 /*----------------------------------------------------------------*/
499 static bool is_dirty(struct cache *cache, dm_cblock_t b)
501 return test_bit(from_cblock(b), cache->dirty_bitset);
504 static void set_dirty(struct cache *cache, dm_oblock_t oblock, dm_cblock_t cblock)
506 if (!test_and_set_bit(from_cblock(cblock), cache->dirty_bitset)) {
507 atomic_inc(&cache->nr_dirty);
508 policy_set_dirty(cache->policy, oblock);
512 static void clear_dirty(struct cache *cache, dm_oblock_t oblock, dm_cblock_t cblock)
514 if (test_and_clear_bit(from_cblock(cblock), cache->dirty_bitset)) {
515 policy_clear_dirty(cache->policy, oblock);
516 if (atomic_dec_return(&cache->nr_dirty) == 0)
517 dm_table_event(cache->ti->table);
521 /*----------------------------------------------------------------*/
523 static bool block_size_is_power_of_two(struct cache *cache)
525 return cache->sectors_per_block_shift >= 0;
528 /* gcc on ARM generates spurious references to __udivdi3 and __umoddi3 */
529 #if defined(CONFIG_ARM) && __GNUC__ == 4 && __GNUC_MINOR__ <= 6
532 static dm_block_t block_div(dm_block_t b, uint32_t n)
539 static dm_block_t oblocks_per_dblock(struct cache *cache)
541 dm_block_t oblocks = cache->discard_block_size;
543 if (block_size_is_power_of_two(cache))
544 oblocks >>= cache->sectors_per_block_shift;
546 oblocks = block_div(oblocks, cache->sectors_per_block);
551 static dm_dblock_t oblock_to_dblock(struct cache *cache, dm_oblock_t oblock)
553 return to_dblock(block_div(from_oblock(oblock),
554 oblocks_per_dblock(cache)));
557 static dm_oblock_t dblock_to_oblock(struct cache *cache, dm_dblock_t dblock)
559 return to_oblock(from_dblock(dblock) * oblocks_per_dblock(cache));
562 static void set_discard(struct cache *cache, dm_dblock_t b)
566 BUG_ON(from_dblock(b) >= from_dblock(cache->discard_nr_blocks));
567 atomic_inc(&cache->stats.discard_count);
569 spin_lock_irqsave(&cache->lock, flags);
570 set_bit(from_dblock(b), cache->discard_bitset);
571 spin_unlock_irqrestore(&cache->lock, flags);
574 static void clear_discard(struct cache *cache, dm_dblock_t b)
578 spin_lock_irqsave(&cache->lock, flags);
579 clear_bit(from_dblock(b), cache->discard_bitset);
580 spin_unlock_irqrestore(&cache->lock, flags);
583 static bool is_discarded(struct cache *cache, dm_dblock_t b)
588 spin_lock_irqsave(&cache->lock, flags);
589 r = test_bit(from_dblock(b), cache->discard_bitset);
590 spin_unlock_irqrestore(&cache->lock, flags);
595 static bool is_discarded_oblock(struct cache *cache, dm_oblock_t b)
600 spin_lock_irqsave(&cache->lock, flags);
601 r = test_bit(from_dblock(oblock_to_dblock(cache, b)),
602 cache->discard_bitset);
603 spin_unlock_irqrestore(&cache->lock, flags);
608 /*----------------------------------------------------------------*/
610 static void load_stats(struct cache *cache)
612 struct dm_cache_statistics stats;
614 dm_cache_metadata_get_stats(cache->cmd, &stats);
615 atomic_set(&cache->stats.read_hit, stats.read_hits);
616 atomic_set(&cache->stats.read_miss, stats.read_misses);
617 atomic_set(&cache->stats.write_hit, stats.write_hits);
618 atomic_set(&cache->stats.write_miss, stats.write_misses);
621 static void save_stats(struct cache *cache)
623 struct dm_cache_statistics stats;
625 stats.read_hits = atomic_read(&cache->stats.read_hit);
626 stats.read_misses = atomic_read(&cache->stats.read_miss);
627 stats.write_hits = atomic_read(&cache->stats.write_hit);
628 stats.write_misses = atomic_read(&cache->stats.write_miss);
630 dm_cache_metadata_set_stats(cache->cmd, &stats);
633 /*----------------------------------------------------------------
635 *--------------------------------------------------------------*/
638 * If using writeback, leave out struct per_bio_data's writethrough fields.
640 #define PB_DATA_SIZE_WB (offsetof(struct per_bio_data, cache))
641 #define PB_DATA_SIZE_WT (sizeof(struct per_bio_data))
643 static bool writethrough_mode(struct cache_features *f)
645 return f->io_mode == CM_IO_WRITETHROUGH;
648 static bool writeback_mode(struct cache_features *f)
650 return f->io_mode == CM_IO_WRITEBACK;
653 static bool passthrough_mode(struct cache_features *f)
655 return f->io_mode == CM_IO_PASSTHROUGH;
658 static size_t get_per_bio_data_size(struct cache *cache)
660 return writethrough_mode(&cache->features) ? PB_DATA_SIZE_WT : PB_DATA_SIZE_WB;
663 static struct per_bio_data *get_per_bio_data(struct bio *bio, size_t data_size)
665 struct per_bio_data *pb = dm_per_bio_data(bio, data_size);
670 static struct per_bio_data *init_per_bio_data(struct bio *bio, size_t data_size)
672 struct per_bio_data *pb = get_per_bio_data(bio, data_size);
675 pb->req_nr = dm_bio_get_target_bio_nr(bio);
676 pb->all_io_entry = NULL;
681 /*----------------------------------------------------------------
683 *--------------------------------------------------------------*/
684 static void remap_to_origin(struct cache *cache, struct bio *bio)
686 bio->bi_bdev = cache->origin_dev->bdev;
689 static void remap_to_cache(struct cache *cache, struct bio *bio,
692 sector_t bi_sector = bio->bi_iter.bi_sector;
693 sector_t block = from_cblock(cblock);
695 bio->bi_bdev = cache->cache_dev->bdev;
696 if (!block_size_is_power_of_two(cache))
697 bio->bi_iter.bi_sector =
698 (block * cache->sectors_per_block) +
699 sector_div(bi_sector, cache->sectors_per_block);
701 bio->bi_iter.bi_sector =
702 (block << cache->sectors_per_block_shift) |
703 (bi_sector & (cache->sectors_per_block - 1));
706 static void check_if_tick_bio_needed(struct cache *cache, struct bio *bio)
709 size_t pb_data_size = get_per_bio_data_size(cache);
710 struct per_bio_data *pb = get_per_bio_data(bio, pb_data_size);
712 spin_lock_irqsave(&cache->lock, flags);
713 if (cache->need_tick_bio &&
714 !(bio->bi_rw & (REQ_FUA | REQ_FLUSH | REQ_DISCARD))) {
716 cache->need_tick_bio = false;
718 spin_unlock_irqrestore(&cache->lock, flags);
721 static void remap_to_origin_clear_discard(struct cache *cache, struct bio *bio,
724 check_if_tick_bio_needed(cache, bio);
725 remap_to_origin(cache, bio);
726 if (bio_data_dir(bio) == WRITE)
727 clear_discard(cache, oblock_to_dblock(cache, oblock));
730 static void remap_to_cache_dirty(struct cache *cache, struct bio *bio,
731 dm_oblock_t oblock, dm_cblock_t cblock)
733 check_if_tick_bio_needed(cache, bio);
734 remap_to_cache(cache, bio, cblock);
735 if (bio_data_dir(bio) == WRITE) {
736 set_dirty(cache, oblock, cblock);
737 clear_discard(cache, oblock_to_dblock(cache, oblock));
741 static dm_oblock_t get_bio_block(struct cache *cache, struct bio *bio)
743 sector_t block_nr = bio->bi_iter.bi_sector;
745 if (!block_size_is_power_of_two(cache))
746 (void) sector_div(block_nr, cache->sectors_per_block);
748 block_nr >>= cache->sectors_per_block_shift;
750 return to_oblock(block_nr);
753 static int bio_triggers_commit(struct cache *cache, struct bio *bio)
755 return bio->bi_rw & (REQ_FLUSH | REQ_FUA);
759 * You must increment the deferred set whilst the prison cell is held. To
760 * encourage this, we ask for 'cell' to be passed in.
762 static void inc_ds(struct cache *cache, struct bio *bio,
763 struct dm_bio_prison_cell *cell)
765 size_t pb_data_size = get_per_bio_data_size(cache);
766 struct per_bio_data *pb = get_per_bio_data(bio, pb_data_size);
769 BUG_ON(pb->all_io_entry);
771 pb->all_io_entry = dm_deferred_entry_inc(cache->all_io_ds);
774 static void issue(struct cache *cache, struct bio *bio)
778 if (!bio_triggers_commit(cache, bio)) {
779 generic_make_request(bio);
784 * Batch together any bios that trigger commits and then issue a
785 * single commit for them in do_worker().
787 spin_lock_irqsave(&cache->lock, flags);
788 cache->commit_requested = true;
789 bio_list_add(&cache->deferred_flush_bios, bio);
790 spin_unlock_irqrestore(&cache->lock, flags);
793 static void inc_and_issue(struct cache *cache, struct bio *bio, struct dm_bio_prison_cell *cell)
795 inc_ds(cache, bio, cell);
799 static void defer_writethrough_bio(struct cache *cache, struct bio *bio)
803 spin_lock_irqsave(&cache->lock, flags);
804 bio_list_add(&cache->deferred_writethrough_bios, bio);
805 spin_unlock_irqrestore(&cache->lock, flags);
810 static void writethrough_endio(struct bio *bio, int err)
812 struct per_bio_data *pb = get_per_bio_data(bio, PB_DATA_SIZE_WT);
814 dm_unhook_bio(&pb->hook_info, bio);
821 dm_bio_restore(&pb->bio_details, bio);
822 remap_to_cache(pb->cache, bio, pb->cblock);
825 * We can't issue this bio directly, since we're in interrupt
826 * context. So it gets put on a bio list for processing by the
829 defer_writethrough_bio(pb->cache, bio);
833 * When running in writethrough mode we need to send writes to clean blocks
834 * to both the cache and origin devices. In future we'd like to clone the
835 * bio and send them in parallel, but for now we're doing them in
836 * series as this is easier.
838 static void remap_to_origin_then_cache(struct cache *cache, struct bio *bio,
839 dm_oblock_t oblock, dm_cblock_t cblock)
841 struct per_bio_data *pb = get_per_bio_data(bio, PB_DATA_SIZE_WT);
845 dm_hook_bio(&pb->hook_info, bio, writethrough_endio, NULL);
846 dm_bio_record(&pb->bio_details, bio);
848 remap_to_origin_clear_discard(pb->cache, bio, oblock);
851 /*----------------------------------------------------------------
852 * Migration processing
854 * Migration covers moving data from the origin device to the cache, or
856 *--------------------------------------------------------------*/
857 static void free_migration(struct dm_cache_migration *mg)
859 mempool_free(mg, mg->cache->migration_pool);
862 static void inc_nr_migrations(struct cache *cache)
864 atomic_inc(&cache->nr_migrations);
867 static void dec_nr_migrations(struct cache *cache)
869 atomic_dec(&cache->nr_migrations);
872 * Wake the worker in case we're suspending the target.
874 wake_up(&cache->migration_wait);
877 static void __cell_defer(struct cache *cache, struct dm_bio_prison_cell *cell,
880 (holder ? dm_cell_release : dm_cell_release_no_holder)
881 (cache->prison, cell, &cache->deferred_bios);
882 free_prison_cell(cache, cell);
885 static void cell_defer(struct cache *cache, struct dm_bio_prison_cell *cell,
890 spin_lock_irqsave(&cache->lock, flags);
891 __cell_defer(cache, cell, holder);
892 spin_unlock_irqrestore(&cache->lock, flags);
897 static void cleanup_migration(struct dm_cache_migration *mg)
899 struct cache *cache = mg->cache;
901 dec_nr_migrations(cache);
904 static void migration_failure(struct dm_cache_migration *mg)
906 struct cache *cache = mg->cache;
909 DMWARN_LIMIT("writeback failed; couldn't copy block");
910 set_dirty(cache, mg->old_oblock, mg->cblock);
911 cell_defer(cache, mg->old_ocell, false);
913 } else if (mg->demote) {
914 DMWARN_LIMIT("demotion failed; couldn't copy block");
915 policy_force_mapping(cache->policy, mg->new_oblock, mg->old_oblock);
917 cell_defer(cache, mg->old_ocell, mg->promote ? false : true);
919 cell_defer(cache, mg->new_ocell, true);
921 DMWARN_LIMIT("promotion failed; couldn't copy block");
922 policy_remove_mapping(cache->policy, mg->new_oblock);
923 cell_defer(cache, mg->new_ocell, true);
926 cleanup_migration(mg);
929 static void migration_success_pre_commit(struct dm_cache_migration *mg)
932 struct cache *cache = mg->cache;
935 clear_dirty(cache, mg->old_oblock, mg->cblock);
936 cell_defer(cache, mg->old_ocell, false);
937 cleanup_migration(mg);
940 } else if (mg->demote) {
941 if (dm_cache_remove_mapping(cache->cmd, mg->cblock)) {
942 DMWARN_LIMIT("demotion failed; couldn't update on disk metadata");
943 policy_force_mapping(cache->policy, mg->new_oblock,
946 cell_defer(cache, mg->new_ocell, true);
947 cleanup_migration(mg);
951 if (dm_cache_insert_mapping(cache->cmd, mg->cblock, mg->new_oblock)) {
952 DMWARN_LIMIT("promotion failed; couldn't update on disk metadata");
953 policy_remove_mapping(cache->policy, mg->new_oblock);
954 cleanup_migration(mg);
959 spin_lock_irqsave(&cache->lock, flags);
960 list_add_tail(&mg->list, &cache->need_commit_migrations);
961 cache->commit_requested = true;
962 spin_unlock_irqrestore(&cache->lock, flags);
965 static void migration_success_post_commit(struct dm_cache_migration *mg)
968 struct cache *cache = mg->cache;
971 DMWARN("writeback unexpectedly triggered commit");
974 } else if (mg->demote) {
975 cell_defer(cache, mg->old_ocell, mg->promote ? false : true);
980 spin_lock_irqsave(&cache->lock, flags);
981 list_add_tail(&mg->list, &cache->quiesced_migrations);
982 spin_unlock_irqrestore(&cache->lock, flags);
986 policy_remove_mapping(cache->policy, mg->old_oblock);
987 cleanup_migration(mg);
991 if (mg->requeue_holder) {
992 clear_dirty(cache, mg->new_oblock, mg->cblock);
993 cell_defer(cache, mg->new_ocell, true);
996 * The block was promoted via an overwrite, so it's dirty.
998 set_dirty(cache, mg->new_oblock, mg->cblock);
999 bio_endio(mg->new_ocell->holder, 0);
1000 cell_defer(cache, mg->new_ocell, false);
1002 cleanup_migration(mg);
1006 static void copy_complete(int read_err, unsigned long write_err, void *context)
1008 unsigned long flags;
1009 struct dm_cache_migration *mg = (struct dm_cache_migration *) context;
1010 struct cache *cache = mg->cache;
1012 if (read_err || write_err)
1015 spin_lock_irqsave(&cache->lock, flags);
1016 list_add_tail(&mg->list, &cache->completed_migrations);
1017 spin_unlock_irqrestore(&cache->lock, flags);
1022 static void issue_copy(struct dm_cache_migration *mg)
1025 struct dm_io_region o_region, c_region;
1026 struct cache *cache = mg->cache;
1027 sector_t cblock = from_cblock(mg->cblock);
1029 o_region.bdev = cache->origin_dev->bdev;
1030 o_region.count = cache->sectors_per_block;
1032 c_region.bdev = cache->cache_dev->bdev;
1033 c_region.sector = cblock * cache->sectors_per_block;
1034 c_region.count = cache->sectors_per_block;
1036 if (mg->writeback || mg->demote) {
1038 o_region.sector = from_oblock(mg->old_oblock) * cache->sectors_per_block;
1039 r = dm_kcopyd_copy(cache->copier, &c_region, 1, &o_region, 0, copy_complete, mg);
1042 o_region.sector = from_oblock(mg->new_oblock) * cache->sectors_per_block;
1043 r = dm_kcopyd_copy(cache->copier, &o_region, 1, &c_region, 0, copy_complete, mg);
1047 DMERR_LIMIT("issuing migration failed");
1048 migration_failure(mg);
1052 static void overwrite_endio(struct bio *bio, int err)
1054 struct dm_cache_migration *mg = bio->bi_private;
1055 struct cache *cache = mg->cache;
1056 size_t pb_data_size = get_per_bio_data_size(cache);
1057 struct per_bio_data *pb = get_per_bio_data(bio, pb_data_size);
1058 unsigned long flags;
1060 dm_unhook_bio(&pb->hook_info, bio);
1065 mg->requeue_holder = false;
1067 spin_lock_irqsave(&cache->lock, flags);
1068 list_add_tail(&mg->list, &cache->completed_migrations);
1069 spin_unlock_irqrestore(&cache->lock, flags);
1074 static void issue_overwrite(struct dm_cache_migration *mg, struct bio *bio)
1076 size_t pb_data_size = get_per_bio_data_size(mg->cache);
1077 struct per_bio_data *pb = get_per_bio_data(bio, pb_data_size);
1079 dm_hook_bio(&pb->hook_info, bio, overwrite_endio, mg);
1080 remap_to_cache_dirty(mg->cache, bio, mg->new_oblock, mg->cblock);
1083 * No need to inc_ds() here, since the cell will be held for the
1084 * duration of the io.
1086 generic_make_request(bio);
1089 static bool bio_writes_complete_block(struct cache *cache, struct bio *bio)
1091 return (bio_data_dir(bio) == WRITE) &&
1092 (bio->bi_iter.bi_size == (cache->sectors_per_block << SECTOR_SHIFT));
1095 static void avoid_copy(struct dm_cache_migration *mg)
1097 atomic_inc(&mg->cache->stats.copies_avoided);
1098 migration_success_pre_commit(mg);
1101 static void calc_discard_block_range(struct cache *cache, struct bio *bio,
1102 dm_dblock_t *b, dm_dblock_t *e)
1104 sector_t sb = bio->bi_iter.bi_sector;
1105 sector_t se = bio_end_sector(bio);
1107 *b = to_dblock(dm_sector_div_up(sb, cache->discard_block_size));
1109 if (se - sb < cache->discard_block_size)
1112 *e = to_dblock(block_div(se, cache->discard_block_size));
1115 static void issue_discard(struct dm_cache_migration *mg)
1118 struct bio *bio = mg->new_ocell->holder;
1120 calc_discard_block_range(mg->cache, bio, &b, &e);
1122 set_discard(mg->cache, b);
1123 b = to_dblock(from_dblock(b) + 1);
1127 cell_defer(mg->cache, mg->new_ocell, false);
1131 static void issue_copy_or_discard(struct dm_cache_migration *mg)
1134 struct cache *cache = mg->cache;
1141 if (mg->writeback || mg->demote)
1142 avoid = !is_dirty(cache, mg->cblock) ||
1143 is_discarded_oblock(cache, mg->old_oblock);
1145 struct bio *bio = mg->new_ocell->holder;
1147 avoid = is_discarded_oblock(cache, mg->new_oblock);
1149 if (writeback_mode(&cache->features) &&
1150 !avoid && bio_writes_complete_block(cache, bio)) {
1151 issue_overwrite(mg, bio);
1156 avoid ? avoid_copy(mg) : issue_copy(mg);
1159 static void complete_migration(struct dm_cache_migration *mg)
1162 migration_failure(mg);
1164 migration_success_pre_commit(mg);
1167 static void process_migrations(struct cache *cache, struct list_head *head,
1168 void (*fn)(struct dm_cache_migration *))
1170 unsigned long flags;
1171 struct list_head list;
1172 struct dm_cache_migration *mg, *tmp;
1174 INIT_LIST_HEAD(&list);
1175 spin_lock_irqsave(&cache->lock, flags);
1176 list_splice_init(head, &list);
1177 spin_unlock_irqrestore(&cache->lock, flags);
1179 list_for_each_entry_safe(mg, tmp, &list, list)
1183 static void __queue_quiesced_migration(struct dm_cache_migration *mg)
1185 list_add_tail(&mg->list, &mg->cache->quiesced_migrations);
1188 static void queue_quiesced_migration(struct dm_cache_migration *mg)
1190 unsigned long flags;
1191 struct cache *cache = mg->cache;
1193 spin_lock_irqsave(&cache->lock, flags);
1194 __queue_quiesced_migration(mg);
1195 spin_unlock_irqrestore(&cache->lock, flags);
1200 static void queue_quiesced_migrations(struct cache *cache, struct list_head *work)
1202 unsigned long flags;
1203 struct dm_cache_migration *mg, *tmp;
1205 spin_lock_irqsave(&cache->lock, flags);
1206 list_for_each_entry_safe(mg, tmp, work, list)
1207 __queue_quiesced_migration(mg);
1208 spin_unlock_irqrestore(&cache->lock, flags);
1213 static void check_for_quiesced_migrations(struct cache *cache,
1214 struct per_bio_data *pb)
1216 struct list_head work;
1218 if (!pb->all_io_entry)
1221 INIT_LIST_HEAD(&work);
1222 dm_deferred_entry_dec(pb->all_io_entry, &work);
1224 if (!list_empty(&work))
1225 queue_quiesced_migrations(cache, &work);
1228 static void quiesce_migration(struct dm_cache_migration *mg)
1230 if (!dm_deferred_set_add_work(mg->cache->all_io_ds, &mg->list))
1231 queue_quiesced_migration(mg);
1234 static void promote(struct cache *cache, struct prealloc *structs,
1235 dm_oblock_t oblock, dm_cblock_t cblock,
1236 struct dm_bio_prison_cell *cell)
1238 struct dm_cache_migration *mg = prealloc_get_migration(structs);
1241 mg->discard = false;
1242 mg->writeback = false;
1245 mg->requeue_holder = true;
1246 mg->invalidate = false;
1248 mg->new_oblock = oblock;
1249 mg->cblock = cblock;
1250 mg->old_ocell = NULL;
1251 mg->new_ocell = cell;
1252 mg->start_jiffies = jiffies;
1254 inc_nr_migrations(cache);
1255 quiesce_migration(mg);
1258 static void writeback(struct cache *cache, struct prealloc *structs,
1259 dm_oblock_t oblock, dm_cblock_t cblock,
1260 struct dm_bio_prison_cell *cell)
1262 struct dm_cache_migration *mg = prealloc_get_migration(structs);
1265 mg->discard = false;
1266 mg->writeback = true;
1268 mg->promote = false;
1269 mg->requeue_holder = true;
1270 mg->invalidate = false;
1272 mg->old_oblock = oblock;
1273 mg->cblock = cblock;
1274 mg->old_ocell = cell;
1275 mg->new_ocell = NULL;
1276 mg->start_jiffies = jiffies;
1278 inc_nr_migrations(cache);
1279 quiesce_migration(mg);
1282 static void demote_then_promote(struct cache *cache, struct prealloc *structs,
1283 dm_oblock_t old_oblock, dm_oblock_t new_oblock,
1285 struct dm_bio_prison_cell *old_ocell,
1286 struct dm_bio_prison_cell *new_ocell)
1288 struct dm_cache_migration *mg = prealloc_get_migration(structs);
1291 mg->discard = false;
1292 mg->writeback = false;
1295 mg->requeue_holder = true;
1296 mg->invalidate = false;
1298 mg->old_oblock = old_oblock;
1299 mg->new_oblock = new_oblock;
1300 mg->cblock = cblock;
1301 mg->old_ocell = old_ocell;
1302 mg->new_ocell = new_ocell;
1303 mg->start_jiffies = jiffies;
1305 inc_nr_migrations(cache);
1306 quiesce_migration(mg);
1310 * Invalidate a cache entry. No writeback occurs; any changes in the cache
1311 * block are thrown away.
1313 static void invalidate(struct cache *cache, struct prealloc *structs,
1314 dm_oblock_t oblock, dm_cblock_t cblock,
1315 struct dm_bio_prison_cell *cell)
1317 struct dm_cache_migration *mg = prealloc_get_migration(structs);
1320 mg->discard = false;
1321 mg->writeback = false;
1323 mg->promote = false;
1324 mg->requeue_holder = true;
1325 mg->invalidate = true;
1327 mg->old_oblock = oblock;
1328 mg->cblock = cblock;
1329 mg->old_ocell = cell;
1330 mg->new_ocell = NULL;
1331 mg->start_jiffies = jiffies;
1333 inc_nr_migrations(cache);
1334 quiesce_migration(mg);
1337 static void discard(struct cache *cache, struct prealloc *structs,
1338 struct dm_bio_prison_cell *cell)
1340 struct dm_cache_migration *mg = prealloc_get_migration(structs);
1344 mg->writeback = false;
1346 mg->promote = false;
1347 mg->requeue_holder = false;
1348 mg->invalidate = false;
1350 mg->old_ocell = NULL;
1351 mg->new_ocell = cell;
1352 mg->start_jiffies = jiffies;
1354 quiesce_migration(mg);
1357 /*----------------------------------------------------------------
1359 *--------------------------------------------------------------*/
1360 static void defer_bio(struct cache *cache, struct bio *bio)
1362 unsigned long flags;
1364 spin_lock_irqsave(&cache->lock, flags);
1365 bio_list_add(&cache->deferred_bios, bio);
1366 spin_unlock_irqrestore(&cache->lock, flags);
1371 static void process_flush_bio(struct cache *cache, struct bio *bio)
1373 size_t pb_data_size = get_per_bio_data_size(cache);
1374 struct per_bio_data *pb = get_per_bio_data(bio, pb_data_size);
1376 BUG_ON(bio->bi_iter.bi_size);
1378 remap_to_origin(cache, bio);
1380 remap_to_cache(cache, bio, 0);
1383 * REQ_FLUSH is not directed at any particular block so we don't
1384 * need to inc_ds(). REQ_FUA's are split into a write + REQ_FLUSH
1390 static void process_discard_bio(struct cache *cache, struct prealloc *structs,
1395 struct dm_bio_prison_cell *cell_prealloc, *new_ocell;
1397 calc_discard_block_range(cache, bio, &b, &e);
1403 cell_prealloc = prealloc_get_cell(structs);
1404 r = bio_detain_range(cache, dblock_to_oblock(cache, b), dblock_to_oblock(cache, e), bio, cell_prealloc,
1405 (cell_free_fn) prealloc_put_cell,
1406 structs, &new_ocell);
1410 discard(cache, structs, new_ocell);
1413 static bool spare_migration_bandwidth(struct cache *cache)
1415 sector_t current_volume = (atomic_read(&cache->nr_migrations) + 1) *
1416 cache->sectors_per_block;
1417 return current_volume < cache->migration_threshold;
1420 static void inc_hit_counter(struct cache *cache, struct bio *bio)
1422 atomic_inc(bio_data_dir(bio) == READ ?
1423 &cache->stats.read_hit : &cache->stats.write_hit);
1426 static void inc_miss_counter(struct cache *cache, struct bio *bio)
1428 atomic_inc(bio_data_dir(bio) == READ ?
1429 &cache->stats.read_miss : &cache->stats.write_miss);
1432 static void process_bio(struct cache *cache, struct prealloc *structs,
1436 bool release_cell = true;
1437 dm_oblock_t block = get_bio_block(cache, bio);
1438 struct dm_bio_prison_cell *cell_prealloc, *old_ocell, *new_ocell;
1439 struct policy_result lookup_result;
1440 bool passthrough = passthrough_mode(&cache->features);
1441 bool discarded_block, can_migrate;
1444 * Check to see if that block is currently migrating.
1446 cell_prealloc = prealloc_get_cell(structs);
1447 r = bio_detain(cache, block, bio, cell_prealloc,
1448 (cell_free_fn) prealloc_put_cell,
1449 structs, &new_ocell);
1453 discarded_block = is_discarded_oblock(cache, block);
1454 can_migrate = !passthrough && (discarded_block || spare_migration_bandwidth(cache));
1456 r = policy_map(cache->policy, block, true, can_migrate, discarded_block,
1457 bio, &lookup_result);
1459 if (r == -EWOULDBLOCK)
1460 /* migration has been denied */
1461 lookup_result.op = POLICY_MISS;
1463 switch (lookup_result.op) {
1466 inc_miss_counter(cache, bio);
1469 * Passthrough always maps to the origin,
1470 * invalidating any cache blocks that are written
1474 if (bio_data_dir(bio) == WRITE) {
1475 atomic_inc(&cache->stats.demotion);
1476 invalidate(cache, structs, block, lookup_result.cblock, new_ocell);
1477 release_cell = false;
1480 /* FIXME: factor out issue_origin() */
1481 remap_to_origin_clear_discard(cache, bio, block);
1482 inc_and_issue(cache, bio, new_ocell);
1485 inc_hit_counter(cache, bio);
1487 if (bio_data_dir(bio) == WRITE &&
1488 writethrough_mode(&cache->features) &&
1489 !is_dirty(cache, lookup_result.cblock)) {
1490 remap_to_origin_then_cache(cache, bio, block, lookup_result.cblock);
1491 inc_and_issue(cache, bio, new_ocell);
1494 remap_to_cache_dirty(cache, bio, block, lookup_result.cblock);
1495 inc_and_issue(cache, bio, new_ocell);
1502 inc_miss_counter(cache, bio);
1503 remap_to_origin_clear_discard(cache, bio, block);
1504 inc_and_issue(cache, bio, new_ocell);
1508 atomic_inc(&cache->stats.promotion);
1509 promote(cache, structs, block, lookup_result.cblock, new_ocell);
1510 release_cell = false;
1513 case POLICY_REPLACE:
1514 cell_prealloc = prealloc_get_cell(structs);
1515 r = bio_detain(cache, lookup_result.old_oblock, bio, cell_prealloc,
1516 (cell_free_fn) prealloc_put_cell,
1517 structs, &old_ocell);
1520 * We have to be careful to avoid lock inversion of
1521 * the cells. So we back off, and wait for the
1522 * old_ocell to become free.
1524 policy_force_mapping(cache->policy, block,
1525 lookup_result.old_oblock);
1526 atomic_inc(&cache->stats.cache_cell_clash);
1529 atomic_inc(&cache->stats.demotion);
1530 atomic_inc(&cache->stats.promotion);
1532 demote_then_promote(cache, structs, lookup_result.old_oblock,
1533 block, lookup_result.cblock,
1534 old_ocell, new_ocell);
1535 release_cell = false;
1539 DMERR_LIMIT("%s: erroring bio, unknown policy op: %u", __func__,
1540 (unsigned) lookup_result.op);
1545 cell_defer(cache, new_ocell, false);
1548 static int need_commit_due_to_time(struct cache *cache)
1550 return jiffies < cache->last_commit_jiffies ||
1551 jiffies > cache->last_commit_jiffies + COMMIT_PERIOD;
1554 static int commit_if_needed(struct cache *cache)
1558 if ((cache->commit_requested || need_commit_due_to_time(cache)) &&
1559 dm_cache_changed_this_transaction(cache->cmd)) {
1560 atomic_inc(&cache->stats.commit_count);
1561 cache->commit_requested = false;
1562 r = dm_cache_commit(cache->cmd, false);
1563 cache->last_commit_jiffies = jiffies;
1569 static void process_deferred_bios(struct cache *cache)
1571 unsigned long flags;
1572 struct bio_list bios;
1574 struct prealloc structs;
1576 memset(&structs, 0, sizeof(structs));
1577 bio_list_init(&bios);
1579 spin_lock_irqsave(&cache->lock, flags);
1580 bio_list_merge(&bios, &cache->deferred_bios);
1581 bio_list_init(&cache->deferred_bios);
1582 spin_unlock_irqrestore(&cache->lock, flags);
1584 while (!bio_list_empty(&bios)) {
1586 * If we've got no free migration structs, and processing
1587 * this bio might require one, we pause until there are some
1588 * prepared mappings to process.
1590 if (prealloc_data_structs(cache, &structs)) {
1591 spin_lock_irqsave(&cache->lock, flags);
1592 bio_list_merge(&cache->deferred_bios, &bios);
1593 spin_unlock_irqrestore(&cache->lock, flags);
1597 bio = bio_list_pop(&bios);
1599 if (bio->bi_rw & REQ_FLUSH)
1600 process_flush_bio(cache, bio);
1601 else if (bio->bi_rw & REQ_DISCARD)
1602 process_discard_bio(cache, &structs, bio);
1604 process_bio(cache, &structs, bio);
1607 prealloc_free_structs(cache, &structs);
1610 static void process_deferred_flush_bios(struct cache *cache, bool submit_bios)
1612 unsigned long flags;
1613 struct bio_list bios;
1616 bio_list_init(&bios);
1618 spin_lock_irqsave(&cache->lock, flags);
1619 bio_list_merge(&bios, &cache->deferred_flush_bios);
1620 bio_list_init(&cache->deferred_flush_bios);
1621 spin_unlock_irqrestore(&cache->lock, flags);
1624 * These bios have already been through inc_ds()
1626 while ((bio = bio_list_pop(&bios)))
1627 submit_bios ? generic_make_request(bio) : bio_io_error(bio);
1630 static void process_deferred_writethrough_bios(struct cache *cache)
1632 unsigned long flags;
1633 struct bio_list bios;
1636 bio_list_init(&bios);
1638 spin_lock_irqsave(&cache->lock, flags);
1639 bio_list_merge(&bios, &cache->deferred_writethrough_bios);
1640 bio_list_init(&cache->deferred_writethrough_bios);
1641 spin_unlock_irqrestore(&cache->lock, flags);
1644 * These bios have already been through inc_ds()
1646 while ((bio = bio_list_pop(&bios)))
1647 generic_make_request(bio);
1650 static void writeback_some_dirty_blocks(struct cache *cache)
1655 struct prealloc structs;
1656 struct dm_bio_prison_cell *old_ocell;
1658 memset(&structs, 0, sizeof(structs));
1660 while (spare_migration_bandwidth(cache)) {
1661 if (prealloc_data_structs(cache, &structs))
1664 r = policy_writeback_work(cache->policy, &oblock, &cblock);
1668 r = get_cell(cache, oblock, &structs, &old_ocell);
1670 policy_set_dirty(cache->policy, oblock);
1674 writeback(cache, &structs, oblock, cblock, old_ocell);
1677 prealloc_free_structs(cache, &structs);
1680 /*----------------------------------------------------------------
1682 * Dropping something from the cache *without* writing back.
1683 *--------------------------------------------------------------*/
1685 static void process_invalidation_request(struct cache *cache, struct invalidation_request *req)
1688 uint64_t begin = from_cblock(req->cblocks->begin);
1689 uint64_t end = from_cblock(req->cblocks->end);
1691 while (begin != end) {
1692 r = policy_remove_cblock(cache->policy, to_cblock(begin));
1694 r = dm_cache_remove_mapping(cache->cmd, to_cblock(begin));
1698 } else if (r == -ENODATA) {
1699 /* harmless, already unmapped */
1703 DMERR("policy_remove_cblock failed");
1710 cache->commit_requested = true;
1713 atomic_set(&req->complete, 1);
1715 wake_up(&req->result_wait);
1718 static void process_invalidation_requests(struct cache *cache)
1720 struct list_head list;
1721 struct invalidation_request *req, *tmp;
1723 INIT_LIST_HEAD(&list);
1724 spin_lock(&cache->invalidation_lock);
1725 list_splice_init(&cache->invalidation_requests, &list);
1726 spin_unlock(&cache->invalidation_lock);
1728 list_for_each_entry_safe (req, tmp, &list, list)
1729 process_invalidation_request(cache, req);
1732 /*----------------------------------------------------------------
1734 *--------------------------------------------------------------*/
1735 static bool is_quiescing(struct cache *cache)
1737 return atomic_read(&cache->quiescing);
1740 static void ack_quiescing(struct cache *cache)
1742 if (is_quiescing(cache)) {
1743 atomic_inc(&cache->quiescing_ack);
1744 wake_up(&cache->quiescing_wait);
1748 static void wait_for_quiescing_ack(struct cache *cache)
1750 wait_event(cache->quiescing_wait, atomic_read(&cache->quiescing_ack));
1753 static void start_quiescing(struct cache *cache)
1755 atomic_inc(&cache->quiescing);
1756 wait_for_quiescing_ack(cache);
1759 static void stop_quiescing(struct cache *cache)
1761 atomic_set(&cache->quiescing, 0);
1762 atomic_set(&cache->quiescing_ack, 0);
1765 static void wait_for_migrations(struct cache *cache)
1767 wait_event(cache->migration_wait, !atomic_read(&cache->nr_migrations));
1770 static void stop_worker(struct cache *cache)
1772 cancel_delayed_work(&cache->waker);
1773 flush_workqueue(cache->wq);
1776 static void requeue_deferred_io(struct cache *cache)
1779 struct bio_list bios;
1781 bio_list_init(&bios);
1782 bio_list_merge(&bios, &cache->deferred_bios);
1783 bio_list_init(&cache->deferred_bios);
1785 while ((bio = bio_list_pop(&bios)))
1786 bio_endio(bio, DM_ENDIO_REQUEUE);
1789 static int more_work(struct cache *cache)
1791 if (is_quiescing(cache))
1792 return !list_empty(&cache->quiesced_migrations) ||
1793 !list_empty(&cache->completed_migrations) ||
1794 !list_empty(&cache->need_commit_migrations);
1796 return !bio_list_empty(&cache->deferred_bios) ||
1797 !bio_list_empty(&cache->deferred_flush_bios) ||
1798 !bio_list_empty(&cache->deferred_writethrough_bios) ||
1799 !list_empty(&cache->quiesced_migrations) ||
1800 !list_empty(&cache->completed_migrations) ||
1801 !list_empty(&cache->need_commit_migrations) ||
1805 static void do_worker(struct work_struct *ws)
1807 struct cache *cache = container_of(ws, struct cache, worker);
1810 if (!is_quiescing(cache)) {
1811 writeback_some_dirty_blocks(cache);
1812 process_deferred_writethrough_bios(cache);
1813 process_deferred_bios(cache);
1814 process_invalidation_requests(cache);
1817 process_migrations(cache, &cache->quiesced_migrations, issue_copy_or_discard);
1818 process_migrations(cache, &cache->completed_migrations, complete_migration);
1820 if (commit_if_needed(cache)) {
1821 process_deferred_flush_bios(cache, false);
1822 process_migrations(cache, &cache->need_commit_migrations, migration_failure);
1825 * FIXME: rollback metadata or just go into a
1826 * failure mode and error everything
1829 process_deferred_flush_bios(cache, true);
1830 process_migrations(cache, &cache->need_commit_migrations,
1831 migration_success_post_commit);
1834 ack_quiescing(cache);
1836 } while (more_work(cache));
1840 * We want to commit periodically so that not too much
1841 * unwritten metadata builds up.
1843 static void do_waker(struct work_struct *ws)
1845 struct cache *cache = container_of(to_delayed_work(ws), struct cache, waker);
1846 policy_tick(cache->policy);
1848 queue_delayed_work(cache->wq, &cache->waker, COMMIT_PERIOD);
1851 /*----------------------------------------------------------------*/
1853 static int is_congested(struct dm_dev *dev, int bdi_bits)
1855 struct request_queue *q = bdev_get_queue(dev->bdev);
1856 return bdi_congested(&q->backing_dev_info, bdi_bits);
1859 static int cache_is_congested(struct dm_target_callbacks *cb, int bdi_bits)
1861 struct cache *cache = container_of(cb, struct cache, callbacks);
1863 return is_congested(cache->origin_dev, bdi_bits) ||
1864 is_congested(cache->cache_dev, bdi_bits);
1867 /*----------------------------------------------------------------
1869 *--------------------------------------------------------------*/
1872 * This function gets called on the error paths of the constructor, so we
1873 * have to cope with a partially initialised struct.
1875 static void destroy(struct cache *cache)
1879 if (cache->next_migration)
1880 mempool_free(cache->next_migration, cache->migration_pool);
1882 if (cache->migration_pool)
1883 mempool_destroy(cache->migration_pool);
1885 if (cache->all_io_ds)
1886 dm_deferred_set_destroy(cache->all_io_ds);
1889 dm_bio_prison_destroy(cache->prison);
1892 destroy_workqueue(cache->wq);
1894 if (cache->dirty_bitset)
1895 free_bitset(cache->dirty_bitset);
1897 if (cache->discard_bitset)
1898 free_bitset(cache->discard_bitset);
1901 dm_kcopyd_client_destroy(cache->copier);
1904 dm_cache_metadata_close(cache->cmd);
1906 if (cache->metadata_dev)
1907 dm_put_device(cache->ti, cache->metadata_dev);
1909 if (cache->origin_dev)
1910 dm_put_device(cache->ti, cache->origin_dev);
1912 if (cache->cache_dev)
1913 dm_put_device(cache->ti, cache->cache_dev);
1916 dm_cache_policy_destroy(cache->policy);
1918 for (i = 0; i < cache->nr_ctr_args ; i++)
1919 kfree(cache->ctr_args[i]);
1920 kfree(cache->ctr_args);
1925 static void cache_dtr(struct dm_target *ti)
1927 struct cache *cache = ti->private;
1932 static sector_t get_dev_size(struct dm_dev *dev)
1934 return i_size_read(dev->bdev->bd_inode) >> SECTOR_SHIFT;
1937 /*----------------------------------------------------------------*/
1940 * Construct a cache device mapping.
1942 * cache <metadata dev> <cache dev> <origin dev> <block size>
1943 * <#feature args> [<feature arg>]*
1944 * <policy> <#policy args> [<policy arg>]*
1946 * metadata dev : fast device holding the persistent metadata
1947 * cache dev : fast device holding cached data blocks
1948 * origin dev : slow device holding original data blocks
1949 * block size : cache unit size in sectors
1951 * #feature args : number of feature arguments passed
1952 * feature args : writethrough. (The default is writeback.)
1954 * policy : the replacement policy to use
1955 * #policy args : an even number of policy arguments corresponding
1956 * to key/value pairs passed to the policy
1957 * policy args : key/value pairs passed to the policy
1958 * E.g. 'sequential_threshold 1024'
1959 * See cache-policies.txt for details.
1961 * Optional feature arguments are:
1962 * writethrough : write through caching that prohibits cache block
1963 * content from being different from origin block content.
1964 * Without this argument, the default behaviour is to write
1965 * back cache block contents later for performance reasons,
1966 * so they may differ from the corresponding origin blocks.
1969 struct dm_target *ti;
1971 struct dm_dev *metadata_dev;
1973 struct dm_dev *cache_dev;
1974 sector_t cache_sectors;
1976 struct dm_dev *origin_dev;
1977 sector_t origin_sectors;
1979 uint32_t block_size;
1981 const char *policy_name;
1983 const char **policy_argv;
1985 struct cache_features features;
1988 static void destroy_cache_args(struct cache_args *ca)
1990 if (ca->metadata_dev)
1991 dm_put_device(ca->ti, ca->metadata_dev);
1994 dm_put_device(ca->ti, ca->cache_dev);
1997 dm_put_device(ca->ti, ca->origin_dev);
2002 static bool at_least_one_arg(struct dm_arg_set *as, char **error)
2005 *error = "Insufficient args";
2012 static int parse_metadata_dev(struct cache_args *ca, struct dm_arg_set *as,
2016 sector_t metadata_dev_size;
2017 char b[BDEVNAME_SIZE];
2019 if (!at_least_one_arg(as, error))
2022 r = dm_get_device(ca->ti, dm_shift_arg(as), FMODE_READ | FMODE_WRITE,
2025 *error = "Error opening metadata device";
2029 metadata_dev_size = get_dev_size(ca->metadata_dev);
2030 if (metadata_dev_size > DM_CACHE_METADATA_MAX_SECTORS_WARNING)
2031 DMWARN("Metadata device %s is larger than %u sectors: excess space will not be used.",
2032 bdevname(ca->metadata_dev->bdev, b), THIN_METADATA_MAX_SECTORS);
2037 static int parse_cache_dev(struct cache_args *ca, struct dm_arg_set *as,
2042 if (!at_least_one_arg(as, error))
2045 r = dm_get_device(ca->ti, dm_shift_arg(as), FMODE_READ | FMODE_WRITE,
2048 *error = "Error opening cache device";
2051 ca->cache_sectors = get_dev_size(ca->cache_dev);
2056 static int parse_origin_dev(struct cache_args *ca, struct dm_arg_set *as,
2061 if (!at_least_one_arg(as, error))
2064 r = dm_get_device(ca->ti, dm_shift_arg(as), FMODE_READ | FMODE_WRITE,
2067 *error = "Error opening origin device";
2071 ca->origin_sectors = get_dev_size(ca->origin_dev);
2072 if (ca->ti->len > ca->origin_sectors) {
2073 *error = "Device size larger than cached device";
2080 static int parse_block_size(struct cache_args *ca, struct dm_arg_set *as,
2083 unsigned long block_size;
2085 if (!at_least_one_arg(as, error))
2088 if (kstrtoul(dm_shift_arg(as), 10, &block_size) || !block_size ||
2089 block_size < DATA_DEV_BLOCK_SIZE_MIN_SECTORS ||
2090 block_size > DATA_DEV_BLOCK_SIZE_MAX_SECTORS ||
2091 block_size & (DATA_DEV_BLOCK_SIZE_MIN_SECTORS - 1)) {
2092 *error = "Invalid data block size";
2096 if (block_size > ca->cache_sectors) {
2097 *error = "Data block size is larger than the cache device";
2101 ca->block_size = block_size;
2106 static void init_features(struct cache_features *cf)
2108 cf->mode = CM_WRITE;
2109 cf->io_mode = CM_IO_WRITEBACK;
2112 static int parse_features(struct cache_args *ca, struct dm_arg_set *as,
2115 static struct dm_arg _args[] = {
2116 {0, 1, "Invalid number of cache feature arguments"},
2122 struct cache_features *cf = &ca->features;
2126 r = dm_read_arg_group(_args, as, &argc, error);
2131 arg = dm_shift_arg(as);
2133 if (!strcasecmp(arg, "writeback"))
2134 cf->io_mode = CM_IO_WRITEBACK;
2136 else if (!strcasecmp(arg, "writethrough"))
2137 cf->io_mode = CM_IO_WRITETHROUGH;
2139 else if (!strcasecmp(arg, "passthrough"))
2140 cf->io_mode = CM_IO_PASSTHROUGH;
2143 *error = "Unrecognised cache feature requested";
2151 static int parse_policy(struct cache_args *ca, struct dm_arg_set *as,
2154 static struct dm_arg _args[] = {
2155 {0, 1024, "Invalid number of policy arguments"},
2160 if (!at_least_one_arg(as, error))
2163 ca->policy_name = dm_shift_arg(as);
2165 r = dm_read_arg_group(_args, as, &ca->policy_argc, error);
2169 ca->policy_argv = (const char **)as->argv;
2170 dm_consume_args(as, ca->policy_argc);
2175 static int parse_cache_args(struct cache_args *ca, int argc, char **argv,
2179 struct dm_arg_set as;
2184 r = parse_metadata_dev(ca, &as, error);
2188 r = parse_cache_dev(ca, &as, error);
2192 r = parse_origin_dev(ca, &as, error);
2196 r = parse_block_size(ca, &as, error);
2200 r = parse_features(ca, &as, error);
2204 r = parse_policy(ca, &as, error);
2211 /*----------------------------------------------------------------*/
2213 static struct kmem_cache *migration_cache;
2215 #define NOT_CORE_OPTION 1
2217 static int process_config_option(struct cache *cache, const char *key, const char *value)
2221 if (!strcasecmp(key, "migration_threshold")) {
2222 if (kstrtoul(value, 10, &tmp))
2225 cache->migration_threshold = tmp;
2229 return NOT_CORE_OPTION;
2232 static int set_config_value(struct cache *cache, const char *key, const char *value)
2234 int r = process_config_option(cache, key, value);
2236 if (r == NOT_CORE_OPTION)
2237 r = policy_set_config_value(cache->policy, key, value);
2240 DMWARN("bad config value for %s: %s", key, value);
2245 static int set_config_values(struct cache *cache, int argc, const char **argv)
2250 DMWARN("Odd number of policy arguments given but they should be <key> <value> pairs.");
2255 r = set_config_value(cache, argv[0], argv[1]);
2266 static int create_cache_policy(struct cache *cache, struct cache_args *ca,
2269 struct dm_cache_policy *p = dm_cache_policy_create(ca->policy_name,
2271 cache->origin_sectors,
2272 cache->sectors_per_block);
2274 *error = "Error creating cache's policy";
2283 * We want the discard block size to be at least the size of the cache
2284 * block size and have no more than 2^14 discard blocks across the origin.
2286 #define MAX_DISCARD_BLOCKS (1 << 14)
2288 static bool too_many_discard_blocks(sector_t discard_block_size,
2289 sector_t origin_size)
2291 (void) sector_div(origin_size, discard_block_size);
2293 return origin_size > MAX_DISCARD_BLOCKS;
2296 static sector_t calculate_discard_block_size(sector_t cache_block_size,
2297 sector_t origin_size)
2299 sector_t discard_block_size = cache_block_size;
2302 while (too_many_discard_blocks(discard_block_size, origin_size))
2303 discard_block_size *= 2;
2305 return discard_block_size;
2308 static void set_cache_size(struct cache *cache, dm_cblock_t size)
2310 dm_block_t nr_blocks = from_cblock(size);
2312 if (nr_blocks > (1 << 20) && cache->cache_size != size)
2313 DMWARN_LIMIT("You have created a cache device with a lot of individual cache blocks (%llu)\n"
2314 "All these mappings can consume a lot of kernel memory, and take some time to read/write.\n"
2315 "Please consider increasing the cache block size to reduce the overall cache block count.",
2316 (unsigned long long) nr_blocks);
2318 cache->cache_size = size;
2321 #define DEFAULT_MIGRATION_THRESHOLD 2048
2323 static int cache_create(struct cache_args *ca, struct cache **result)
2326 char **error = &ca->ti->error;
2327 struct cache *cache;
2328 struct dm_target *ti = ca->ti;
2329 dm_block_t origin_blocks;
2330 struct dm_cache_metadata *cmd;
2331 bool may_format = ca->features.mode == CM_WRITE;
2333 cache = kzalloc(sizeof(*cache), GFP_KERNEL);
2338 ti->private = cache;
2339 ti->num_flush_bios = 2;
2340 ti->flush_supported = true;
2342 ti->num_discard_bios = 1;
2343 ti->discards_supported = true;
2344 ti->discard_zeroes_data_unsupported = true;
2345 ti->split_discard_bios = false;
2347 cache->features = ca->features;
2348 ti->per_bio_data_size = get_per_bio_data_size(cache);
2350 cache->callbacks.congested_fn = cache_is_congested;
2351 dm_table_add_target_callbacks(ti->table, &cache->callbacks);
2353 cache->metadata_dev = ca->metadata_dev;
2354 cache->origin_dev = ca->origin_dev;
2355 cache->cache_dev = ca->cache_dev;
2357 ca->metadata_dev = ca->origin_dev = ca->cache_dev = NULL;
2359 /* FIXME: factor out this whole section */
2360 origin_blocks = cache->origin_sectors = ca->origin_sectors;
2361 origin_blocks = block_div(origin_blocks, ca->block_size);
2362 cache->origin_blocks = to_oblock(origin_blocks);
2364 cache->sectors_per_block = ca->block_size;
2365 if (dm_set_target_max_io_len(ti, cache->sectors_per_block)) {
2370 if (ca->block_size & (ca->block_size - 1)) {
2371 dm_block_t cache_size = ca->cache_sectors;
2373 cache->sectors_per_block_shift = -1;
2374 cache_size = block_div(cache_size, ca->block_size);
2375 set_cache_size(cache, to_cblock(cache_size));
2377 cache->sectors_per_block_shift = __ffs(ca->block_size);
2378 set_cache_size(cache, to_cblock(ca->cache_sectors >> cache->sectors_per_block_shift));
2381 r = create_cache_policy(cache, ca, error);
2385 cache->policy_nr_args = ca->policy_argc;
2386 cache->migration_threshold = DEFAULT_MIGRATION_THRESHOLD;
2388 r = set_config_values(cache, ca->policy_argc, ca->policy_argv);
2390 *error = "Error setting cache policy's config values";
2394 cmd = dm_cache_metadata_open(cache->metadata_dev->bdev,
2395 ca->block_size, may_format,
2396 dm_cache_policy_get_hint_size(cache->policy));
2398 *error = "Error creating metadata object";
2404 if (passthrough_mode(&cache->features)) {
2407 r = dm_cache_metadata_all_clean(cache->cmd, &all_clean);
2409 *error = "dm_cache_metadata_all_clean() failed";
2414 *error = "Cannot enter passthrough mode unless all blocks are clean";
2420 spin_lock_init(&cache->lock);
2421 bio_list_init(&cache->deferred_bios);
2422 bio_list_init(&cache->deferred_flush_bios);
2423 bio_list_init(&cache->deferred_writethrough_bios);
2424 INIT_LIST_HEAD(&cache->quiesced_migrations);
2425 INIT_LIST_HEAD(&cache->completed_migrations);
2426 INIT_LIST_HEAD(&cache->need_commit_migrations);
2427 atomic_set(&cache->nr_migrations, 0);
2428 init_waitqueue_head(&cache->migration_wait);
2430 init_waitqueue_head(&cache->quiescing_wait);
2431 atomic_set(&cache->quiescing, 0);
2432 atomic_set(&cache->quiescing_ack, 0);
2435 atomic_set(&cache->nr_dirty, 0);
2436 cache->dirty_bitset = alloc_bitset(from_cblock(cache->cache_size));
2437 if (!cache->dirty_bitset) {
2438 *error = "could not allocate dirty bitset";
2441 clear_bitset(cache->dirty_bitset, from_cblock(cache->cache_size));
2443 cache->discard_block_size =
2444 calculate_discard_block_size(cache->sectors_per_block,
2445 cache->origin_sectors);
2446 cache->discard_nr_blocks = to_dblock(dm_sector_div_up(cache->origin_sectors,
2447 cache->discard_block_size));
2448 cache->discard_bitset = alloc_bitset(from_dblock(cache->discard_nr_blocks));
2449 if (!cache->discard_bitset) {
2450 *error = "could not allocate discard bitset";
2453 clear_bitset(cache->discard_bitset, from_dblock(cache->discard_nr_blocks));
2455 cache->copier = dm_kcopyd_client_create(&dm_kcopyd_throttle);
2456 if (IS_ERR(cache->copier)) {
2457 *error = "could not create kcopyd client";
2458 r = PTR_ERR(cache->copier);
2462 cache->wq = alloc_ordered_workqueue("dm-" DM_MSG_PREFIX, WQ_MEM_RECLAIM);
2464 *error = "could not create workqueue for metadata object";
2467 INIT_WORK(&cache->worker, do_worker);
2468 INIT_DELAYED_WORK(&cache->waker, do_waker);
2469 cache->last_commit_jiffies = jiffies;
2471 cache->prison = dm_bio_prison_create();
2472 if (!cache->prison) {
2473 *error = "could not create bio prison";
2477 cache->all_io_ds = dm_deferred_set_create();
2478 if (!cache->all_io_ds) {
2479 *error = "could not create all_io deferred set";
2483 cache->migration_pool = mempool_create_slab_pool(MIGRATION_POOL_SIZE,
2485 if (!cache->migration_pool) {
2486 *error = "Error creating cache's migration mempool";
2490 cache->next_migration = NULL;
2492 cache->need_tick_bio = true;
2493 cache->sized = false;
2494 cache->invalidate = false;
2495 cache->commit_requested = false;
2496 cache->loaded_mappings = false;
2497 cache->loaded_discards = false;
2501 atomic_set(&cache->stats.demotion, 0);
2502 atomic_set(&cache->stats.promotion, 0);
2503 atomic_set(&cache->stats.copies_avoided, 0);
2504 atomic_set(&cache->stats.cache_cell_clash, 0);
2505 atomic_set(&cache->stats.commit_count, 0);
2506 atomic_set(&cache->stats.discard_count, 0);
2508 spin_lock_init(&cache->invalidation_lock);
2509 INIT_LIST_HEAD(&cache->invalidation_requests);
2519 static int copy_ctr_args(struct cache *cache, int argc, const char **argv)
2524 copy = kcalloc(argc, sizeof(*copy), GFP_KERNEL);
2527 for (i = 0; i < argc; i++) {
2528 copy[i] = kstrdup(argv[i], GFP_KERNEL);
2537 cache->nr_ctr_args = argc;
2538 cache->ctr_args = copy;
2543 static int cache_ctr(struct dm_target *ti, unsigned argc, char **argv)
2546 struct cache_args *ca;
2547 struct cache *cache = NULL;
2549 ca = kzalloc(sizeof(*ca), GFP_KERNEL);
2551 ti->error = "Error allocating memory for cache";
2556 r = parse_cache_args(ca, argc, argv, &ti->error);
2560 r = cache_create(ca, &cache);
2564 r = copy_ctr_args(cache, argc - 3, (const char **)argv + 3);
2570 ti->private = cache;
2573 destroy_cache_args(ca);
2577 static int __cache_map(struct cache *cache, struct bio *bio, struct dm_bio_prison_cell **cell)
2580 dm_oblock_t block = get_bio_block(cache, bio);
2581 size_t pb_data_size = get_per_bio_data_size(cache);
2582 bool can_migrate = false;
2583 bool discarded_block;
2584 struct policy_result lookup_result;
2585 struct per_bio_data *pb = init_per_bio_data(bio, pb_data_size);
2587 if (unlikely(from_oblock(block) >= from_oblock(cache->origin_blocks))) {
2589 * This can only occur if the io goes to a partial block at
2590 * the end of the origin device. We don't cache these.
2591 * Just remap to the origin and carry on.
2593 remap_to_origin(cache, bio);
2594 return DM_MAPIO_REMAPPED;
2597 if (bio->bi_rw & (REQ_FLUSH | REQ_FUA | REQ_DISCARD)) {
2598 defer_bio(cache, bio);
2599 return DM_MAPIO_SUBMITTED;
2603 * Check to see if that block is currently migrating.
2605 *cell = alloc_prison_cell(cache);
2607 defer_bio(cache, bio);
2608 return DM_MAPIO_SUBMITTED;
2611 r = bio_detain(cache, block, bio, *cell,
2612 (cell_free_fn) free_prison_cell,
2616 defer_bio(cache, bio);
2618 return DM_MAPIO_SUBMITTED;
2621 discarded_block = is_discarded_oblock(cache, block);
2623 r = policy_map(cache->policy, block, false, can_migrate, discarded_block,
2624 bio, &lookup_result);
2625 if (r == -EWOULDBLOCK) {
2626 cell_defer(cache, *cell, true);
2627 return DM_MAPIO_SUBMITTED;
2630 DMERR_LIMIT("Unexpected return from cache replacement policy: %d", r);
2631 cell_defer(cache, *cell, false);
2633 return DM_MAPIO_SUBMITTED;
2636 r = DM_MAPIO_REMAPPED;
2637 switch (lookup_result.op) {
2639 if (passthrough_mode(&cache->features)) {
2640 if (bio_data_dir(bio) == WRITE) {
2642 * We need to invalidate this block, so
2643 * defer for the worker thread.
2645 cell_defer(cache, *cell, true);
2646 r = DM_MAPIO_SUBMITTED;
2649 inc_miss_counter(cache, bio);
2650 remap_to_origin_clear_discard(cache, bio, block);
2654 inc_hit_counter(cache, bio);
2655 if (bio_data_dir(bio) == WRITE && writethrough_mode(&cache->features) &&
2656 !is_dirty(cache, lookup_result.cblock))
2657 remap_to_origin_then_cache(cache, bio, block, lookup_result.cblock);
2659 remap_to_cache_dirty(cache, bio, block, lookup_result.cblock);
2664 inc_miss_counter(cache, bio);
2665 if (pb->req_nr != 0) {
2667 * This is a duplicate writethrough io that is no
2668 * longer needed because the block has been demoted.
2671 cell_defer(cache, *cell, false);
2672 r = DM_MAPIO_SUBMITTED;
2675 remap_to_origin_clear_discard(cache, bio, block);
2680 DMERR_LIMIT("%s: erroring bio: unknown policy op: %u", __func__,
2681 (unsigned) lookup_result.op);
2682 cell_defer(cache, *cell, false);
2684 r = DM_MAPIO_SUBMITTED;
2690 static int cache_map(struct dm_target *ti, struct bio *bio)
2693 struct dm_bio_prison_cell *cell = NULL;
2694 struct cache *cache = ti->private;
2696 r = __cache_map(cache, bio, &cell);
2697 if (r == DM_MAPIO_REMAPPED && cell) {
2698 inc_ds(cache, bio, cell);
2699 cell_defer(cache, cell, false);
2705 static int cache_end_io(struct dm_target *ti, struct bio *bio, int error)
2707 struct cache *cache = ti->private;
2708 unsigned long flags;
2709 size_t pb_data_size = get_per_bio_data_size(cache);
2710 struct per_bio_data *pb = get_per_bio_data(bio, pb_data_size);
2713 policy_tick(cache->policy);
2715 spin_lock_irqsave(&cache->lock, flags);
2716 cache->need_tick_bio = true;
2717 spin_unlock_irqrestore(&cache->lock, flags);
2720 check_for_quiesced_migrations(cache, pb);
2725 static int write_dirty_bitset(struct cache *cache)
2729 for (i = 0; i < from_cblock(cache->cache_size); i++) {
2730 r = dm_cache_set_dirty(cache->cmd, to_cblock(i),
2731 is_dirty(cache, to_cblock(i)));
2739 static int write_discard_bitset(struct cache *cache)
2743 r = dm_cache_discard_bitset_resize(cache->cmd, cache->discard_block_size,
2744 cache->discard_nr_blocks);
2746 DMERR("could not resize on-disk discard bitset");
2750 for (i = 0; i < from_dblock(cache->discard_nr_blocks); i++) {
2751 r = dm_cache_set_discard(cache->cmd, to_dblock(i),
2752 is_discarded(cache, to_dblock(i)));
2761 * returns true on success
2763 static bool sync_metadata(struct cache *cache)
2767 r1 = write_dirty_bitset(cache);
2769 DMERR("could not write dirty bitset");
2771 r2 = write_discard_bitset(cache);
2773 DMERR("could not write discard bitset");
2777 r3 = dm_cache_write_hints(cache->cmd, cache->policy);
2779 DMERR("could not write hints");
2782 * If writing the above metadata failed, we still commit, but don't
2783 * set the clean shutdown flag. This will effectively force every
2784 * dirty bit to be set on reload.
2786 r4 = dm_cache_commit(cache->cmd, !r1 && !r2 && !r3);
2788 DMERR("could not write cache metadata. Data loss may occur.");
2790 return !r1 && !r2 && !r3 && !r4;
2793 static void cache_postsuspend(struct dm_target *ti)
2795 struct cache *cache = ti->private;
2797 start_quiescing(cache);
2798 wait_for_migrations(cache);
2800 requeue_deferred_io(cache);
2801 stop_quiescing(cache);
2803 (void) sync_metadata(cache);
2806 static int load_mapping(void *context, dm_oblock_t oblock, dm_cblock_t cblock,
2807 bool dirty, uint32_t hint, bool hint_valid)
2810 struct cache *cache = context;
2812 r = policy_load_mapping(cache->policy, oblock, cblock, hint, hint_valid);
2817 set_dirty(cache, oblock, cblock);
2819 clear_dirty(cache, oblock, cblock);
2825 * The discard block size in the on disk metadata is not
2826 * neccessarily the same as we're currently using. So we have to
2827 * be careful to only set the discarded attribute if we know it
2828 * covers a complete block of the new size.
2830 struct discard_load_info {
2831 struct cache *cache;
2834 * These blocks are sized using the on disk dblock size, rather
2835 * than the current one.
2837 dm_block_t block_size;
2838 dm_block_t discard_begin, discard_end;
2841 static void discard_load_info_init(struct cache *cache,
2842 struct discard_load_info *li)
2845 li->discard_begin = li->discard_end = 0;
2848 static void set_discard_range(struct discard_load_info *li)
2852 if (li->discard_begin == li->discard_end)
2856 * Convert to sectors.
2858 b = li->discard_begin * li->block_size;
2859 e = li->discard_end * li->block_size;
2862 * Then convert back to the current dblock size.
2864 b = dm_sector_div_up(b, li->cache->discard_block_size);
2865 sector_div(e, li->cache->discard_block_size);
2868 * The origin may have shrunk, so we need to check we're still in
2871 if (e > from_dblock(li->cache->discard_nr_blocks))
2872 e = from_dblock(li->cache->discard_nr_blocks);
2875 set_discard(li->cache, to_dblock(b));
2878 static int load_discard(void *context, sector_t discard_block_size,
2879 dm_dblock_t dblock, bool discard)
2881 struct discard_load_info *li = context;
2883 li->block_size = discard_block_size;
2886 if (from_dblock(dblock) == li->discard_end)
2888 * We're already in a discard range, just extend it.
2890 li->discard_end = li->discard_end + 1ULL;
2894 * Emit the old range and start a new one.
2896 set_discard_range(li);
2897 li->discard_begin = from_dblock(dblock);
2898 li->discard_end = li->discard_begin + 1ULL;
2901 set_discard_range(li);
2902 li->discard_begin = li->discard_end = 0;
2908 static dm_cblock_t get_cache_dev_size(struct cache *cache)
2910 sector_t size = get_dev_size(cache->cache_dev);
2911 (void) sector_div(size, cache->sectors_per_block);
2912 return to_cblock(size);
2915 static bool can_resize(struct cache *cache, dm_cblock_t new_size)
2917 if (from_cblock(new_size) > from_cblock(cache->cache_size))
2921 * We can't drop a dirty block when shrinking the cache.
2923 while (from_cblock(new_size) < from_cblock(cache->cache_size)) {
2924 new_size = to_cblock(from_cblock(new_size) + 1);
2925 if (is_dirty(cache, new_size)) {
2926 DMERR("unable to shrink cache; cache block %llu is dirty",
2927 (unsigned long long) from_cblock(new_size));
2935 static int resize_cache_dev(struct cache *cache, dm_cblock_t new_size)
2939 r = dm_cache_resize(cache->cmd, new_size);
2941 DMERR("could not resize cache metadata");
2945 set_cache_size(cache, new_size);
2950 static int cache_preresume(struct dm_target *ti)
2953 struct cache *cache = ti->private;
2954 dm_cblock_t csize = get_cache_dev_size(cache);
2957 * Check to see if the cache has resized.
2959 if (!cache->sized) {
2960 r = resize_cache_dev(cache, csize);
2964 cache->sized = true;
2966 } else if (csize != cache->cache_size) {
2967 if (!can_resize(cache, csize))
2970 r = resize_cache_dev(cache, csize);
2975 if (!cache->loaded_mappings) {
2976 r = dm_cache_load_mappings(cache->cmd, cache->policy,
2977 load_mapping, cache);
2979 DMERR("could not load cache mappings");
2983 cache->loaded_mappings = true;
2986 if (!cache->loaded_discards) {
2987 struct discard_load_info li;
2990 * The discard bitset could have been resized, or the
2991 * discard block size changed. To be safe we start by
2992 * setting every dblock to not discarded.
2994 clear_bitset(cache->discard_bitset, from_dblock(cache->discard_nr_blocks));
2996 discard_load_info_init(cache, &li);
2997 r = dm_cache_load_discards(cache->cmd, load_discard, &li);
2999 DMERR("could not load origin discards");
3002 set_discard_range(&li);
3004 cache->loaded_discards = true;
3010 static void cache_resume(struct dm_target *ti)
3012 struct cache *cache = ti->private;
3014 cache->need_tick_bio = true;
3015 do_waker(&cache->waker.work);
3021 * <metadata block size> <#used metadata blocks>/<#total metadata blocks>
3022 * <cache block size> <#used cache blocks>/<#total cache blocks>
3023 * <#read hits> <#read misses> <#write hits> <#write misses>
3024 * <#demotions> <#promotions> <#dirty>
3025 * <#features> <features>*
3026 * <#core args> <core args>
3027 * <policy name> <#policy args> <policy args>*
3029 static void cache_status(struct dm_target *ti, status_type_t type,
3030 unsigned status_flags, char *result, unsigned maxlen)
3035 dm_block_t nr_free_blocks_metadata = 0;
3036 dm_block_t nr_blocks_metadata = 0;
3037 char buf[BDEVNAME_SIZE];
3038 struct cache *cache = ti->private;
3039 dm_cblock_t residency;
3042 case STATUSTYPE_INFO:
3043 /* Commit to ensure statistics aren't out-of-date */
3044 if (!(status_flags & DM_STATUS_NOFLUSH_FLAG) && !dm_suspended(ti)) {
3045 r = dm_cache_commit(cache->cmd, false);
3047 DMERR("could not commit metadata for accurate status");
3050 r = dm_cache_get_free_metadata_block_count(cache->cmd,
3051 &nr_free_blocks_metadata);
3053 DMERR("could not get metadata free block count");
3057 r = dm_cache_get_metadata_dev_size(cache->cmd, &nr_blocks_metadata);
3059 DMERR("could not get metadata device size");
3063 residency = policy_residency(cache->policy);
3065 DMEMIT("%u %llu/%llu %u %llu/%llu %u %u %u %u %u %u %lu ",
3066 (unsigned)DM_CACHE_METADATA_BLOCK_SIZE,
3067 (unsigned long long)(nr_blocks_metadata - nr_free_blocks_metadata),
3068 (unsigned long long)nr_blocks_metadata,
3069 cache->sectors_per_block,
3070 (unsigned long long) from_cblock(residency),
3071 (unsigned long long) from_cblock(cache->cache_size),
3072 (unsigned) atomic_read(&cache->stats.read_hit),
3073 (unsigned) atomic_read(&cache->stats.read_miss),
3074 (unsigned) atomic_read(&cache->stats.write_hit),
3075 (unsigned) atomic_read(&cache->stats.write_miss),
3076 (unsigned) atomic_read(&cache->stats.demotion),
3077 (unsigned) atomic_read(&cache->stats.promotion),
3078 (unsigned long) atomic_read(&cache->nr_dirty));
3080 if (writethrough_mode(&cache->features))
3081 DMEMIT("1 writethrough ");
3083 else if (passthrough_mode(&cache->features))
3084 DMEMIT("1 passthrough ");
3086 else if (writeback_mode(&cache->features))
3087 DMEMIT("1 writeback ");
3090 DMERR("internal error: unknown io mode: %d", (int) cache->features.io_mode);
3094 DMEMIT("2 migration_threshold %llu ", (unsigned long long) cache->migration_threshold);
3096 DMEMIT("%s ", dm_cache_policy_get_name(cache->policy));
3098 r = policy_emit_config_values(cache->policy, result + sz, maxlen - sz);
3100 DMERR("policy_emit_config_values returned %d", r);
3105 case STATUSTYPE_TABLE:
3106 format_dev_t(buf, cache->metadata_dev->bdev->bd_dev);
3108 format_dev_t(buf, cache->cache_dev->bdev->bd_dev);
3110 format_dev_t(buf, cache->origin_dev->bdev->bd_dev);
3113 for (i = 0; i < cache->nr_ctr_args - 1; i++)
3114 DMEMIT(" %s", cache->ctr_args[i]);
3115 if (cache->nr_ctr_args)
3116 DMEMIT(" %s", cache->ctr_args[cache->nr_ctr_args - 1]);
3126 * A cache block range can take two forms:
3128 * i) A single cblock, eg. '3456'
3129 * ii) A begin and end cblock with dots between, eg. 123-234
3131 static int parse_cblock_range(struct cache *cache, const char *str,
3132 struct cblock_range *result)
3139 * Try and parse form (ii) first.
3141 r = sscanf(str, "%llu-%llu%c", &b, &e, &dummy);
3146 result->begin = to_cblock(b);
3147 result->end = to_cblock(e);
3152 * That didn't work, try form (i).
3154 r = sscanf(str, "%llu%c", &b, &dummy);
3159 result->begin = to_cblock(b);
3160 result->end = to_cblock(from_cblock(result->begin) + 1u);
3164 DMERR("invalid cblock range '%s'", str);
3168 static int validate_cblock_range(struct cache *cache, struct cblock_range *range)
3170 uint64_t b = from_cblock(range->begin);
3171 uint64_t e = from_cblock(range->end);
3172 uint64_t n = from_cblock(cache->cache_size);
3175 DMERR("begin cblock out of range: %llu >= %llu", b, n);
3180 DMERR("end cblock out of range: %llu > %llu", e, n);
3185 DMERR("invalid cblock range: %llu >= %llu", b, e);
3192 static int request_invalidation(struct cache *cache, struct cblock_range *range)
3194 struct invalidation_request req;
3196 INIT_LIST_HEAD(&req.list);
3197 req.cblocks = range;
3198 atomic_set(&req.complete, 0);
3200 init_waitqueue_head(&req.result_wait);
3202 spin_lock(&cache->invalidation_lock);
3203 list_add(&req.list, &cache->invalidation_requests);
3204 spin_unlock(&cache->invalidation_lock);
3207 wait_event(req.result_wait, atomic_read(&req.complete));
3211 static int process_invalidate_cblocks_message(struct cache *cache, unsigned count,
3212 const char **cblock_ranges)
3216 struct cblock_range range;
3218 if (!passthrough_mode(&cache->features)) {
3219 DMERR("cache has to be in passthrough mode for invalidation");
3223 for (i = 0; i < count; i++) {
3224 r = parse_cblock_range(cache, cblock_ranges[i], &range);
3228 r = validate_cblock_range(cache, &range);
3233 * Pass begin and end origin blocks to the worker and wake it.
3235 r = request_invalidation(cache, &range);
3247 * "invalidate_cblocks [(<begin>)|(<begin>-<end>)]*
3249 * The key migration_threshold is supported by the cache target core.
3251 static int cache_message(struct dm_target *ti, unsigned argc, char **argv)
3253 struct cache *cache = ti->private;
3258 if (!strcasecmp(argv[0], "invalidate_cblocks"))
3259 return process_invalidate_cblocks_message(cache, argc - 1, (const char **) argv + 1);
3264 return set_config_value(cache, argv[0], argv[1]);
3267 static int cache_iterate_devices(struct dm_target *ti,
3268 iterate_devices_callout_fn fn, void *data)
3271 struct cache *cache = ti->private;
3273 r = fn(ti, cache->cache_dev, 0, get_dev_size(cache->cache_dev), data);
3275 r = fn(ti, cache->origin_dev, 0, ti->len, data);
3281 * We assume I/O is going to the origin (which is the volume
3282 * more likely to have restrictions e.g. by being striped).
3283 * (Looking up the exact location of the data would be expensive
3284 * and could always be out of date by the time the bio is submitted.)
3286 static int cache_bvec_merge(struct dm_target *ti,
3287 struct bvec_merge_data *bvm,
3288 struct bio_vec *biovec, int max_size)
3290 struct cache *cache = ti->private;
3291 struct request_queue *q = bdev_get_queue(cache->origin_dev->bdev);
3293 if (!q->merge_bvec_fn)
3296 bvm->bi_bdev = cache->origin_dev->bdev;
3297 return min(max_size, q->merge_bvec_fn(q, bvm, biovec));
3300 static void set_discard_limits(struct cache *cache, struct queue_limits *limits)
3303 * FIXME: these limits may be incompatible with the cache device
3305 limits->max_discard_sectors = min_t(sector_t, cache->discard_block_size * 1024,
3306 cache->origin_sectors);
3307 limits->discard_granularity = cache->discard_block_size << SECTOR_SHIFT;
3310 static void cache_io_hints(struct dm_target *ti, struct queue_limits *limits)
3312 struct cache *cache = ti->private;
3313 uint64_t io_opt_sectors = limits->io_opt >> SECTOR_SHIFT;
3316 * If the system-determined stacked limits are compatible with the
3317 * cache's blocksize (io_opt is a factor) do not override them.
3319 if (io_opt_sectors < cache->sectors_per_block ||
3320 do_div(io_opt_sectors, cache->sectors_per_block)) {
3321 blk_limits_io_min(limits, cache->sectors_per_block << SECTOR_SHIFT);
3322 blk_limits_io_opt(limits, cache->sectors_per_block << SECTOR_SHIFT);
3324 set_discard_limits(cache, limits);
3327 /*----------------------------------------------------------------*/
3329 static struct target_type cache_target = {
3331 .version = {1, 6, 0},
3332 .module = THIS_MODULE,
3336 .end_io = cache_end_io,
3337 .postsuspend = cache_postsuspend,
3338 .preresume = cache_preresume,
3339 .resume = cache_resume,
3340 .status = cache_status,
3341 .message = cache_message,
3342 .iterate_devices = cache_iterate_devices,
3343 .merge = cache_bvec_merge,
3344 .io_hints = cache_io_hints,
3347 static int __init dm_cache_init(void)
3351 r = dm_register_target(&cache_target);
3353 DMERR("cache target registration failed: %d", r);
3357 migration_cache = KMEM_CACHE(dm_cache_migration, 0);
3358 if (!migration_cache) {
3359 dm_unregister_target(&cache_target);
3366 static void __exit dm_cache_exit(void)
3368 dm_unregister_target(&cache_target);
3369 kmem_cache_destroy(migration_cache);
3372 module_init(dm_cache_init);
3373 module_exit(dm_cache_exit);
3375 MODULE_DESCRIPTION(DM_NAME " cache target");
3376 MODULE_AUTHOR("Joe Thornber <ejt@redhat.com>");
3377 MODULE_LICENSE("GPL");