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/jiffies.h>
15 #include <linux/init.h>
16 #include <linux/mempool.h>
17 #include <linux/module.h>
18 #include <linux/slab.h>
19 #include <linux/vmalloc.h>
21 #define DM_MSG_PREFIX "cache"
23 DECLARE_DM_KCOPYD_THROTTLE_WITH_MODULE_PARM(cache_copy_throttle,
24 "A percentage of time allocated for copying to and/or from cache");
26 /*----------------------------------------------------------------*/
31 * oblock: index of an origin block
32 * cblock: index of a cache block
33 * promotion: movement of a block from origin to cache
34 * demotion: movement of a block from cache to origin
35 * migration: movement of a block between the origin and cache device,
39 /*----------------------------------------------------------------*/
41 static size_t bitset_size_in_bytes(unsigned nr_entries)
43 return sizeof(unsigned long) * dm_div_up(nr_entries, BITS_PER_LONG);
46 static unsigned long *alloc_bitset(unsigned nr_entries)
48 size_t s = bitset_size_in_bytes(nr_entries);
52 static void clear_bitset(void *bitset, unsigned nr_entries)
54 size_t s = bitset_size_in_bytes(nr_entries);
58 static void free_bitset(unsigned long *bits)
63 /*----------------------------------------------------------------*/
66 * There are a couple of places where we let a bio run, but want to do some
67 * work before calling its endio function. We do this by temporarily
68 * changing the endio fn.
71 bio_end_io_t *bi_end_io;
75 static void dm_hook_bio(struct dm_hook_info *h, struct bio *bio,
76 bio_end_io_t *bi_end_io, void *bi_private)
78 h->bi_end_io = bio->bi_end_io;
79 h->bi_private = bio->bi_private;
81 bio->bi_end_io = bi_end_io;
82 bio->bi_private = bi_private;
85 static void dm_unhook_bio(struct dm_hook_info *h, struct bio *bio)
87 bio->bi_end_io = h->bi_end_io;
88 bio->bi_private = h->bi_private;
91 /*----------------------------------------------------------------*/
93 #define MIGRATION_POOL_SIZE 128
94 #define COMMIT_PERIOD HZ
95 #define MIGRATION_COUNT_WINDOW 10
98 * The block size of the device holding cache data must be
99 * between 32KB and 1GB.
101 #define DATA_DEV_BLOCK_SIZE_MIN_SECTORS (32 * 1024 >> SECTOR_SHIFT)
102 #define DATA_DEV_BLOCK_SIZE_MAX_SECTORS (1024 * 1024 * 1024 >> SECTOR_SHIFT)
105 * FIXME: the cache is read/write for the time being.
107 enum cache_metadata_mode {
108 CM_WRITE, /* metadata may be changed */
109 CM_READ_ONLY, /* metadata may not be changed */
114 * Data is written to cached blocks only. These blocks are marked
115 * dirty. If you lose the cache device you will lose data.
116 * Potential performance increase for both reads and writes.
121 * Data is written to both cache and origin. Blocks are never
122 * dirty. Potential performance benfit for reads only.
127 * A degraded mode useful for various cache coherency situations
128 * (eg, rolling back snapshots). Reads and writes always go to the
129 * origin. If a write goes to a cached oblock, then the cache
130 * block is invalidated.
135 struct cache_features {
136 enum cache_metadata_mode mode;
137 enum cache_io_mode io_mode;
147 atomic_t copies_avoided;
148 atomic_t cache_cell_clash;
149 atomic_t commit_count;
150 atomic_t discard_count;
154 * Defines a range of cblocks, begin to (end - 1) are in the range. end is
155 * the one-past-the-end value.
157 struct cblock_range {
162 struct invalidation_request {
163 struct list_head list;
164 struct cblock_range *cblocks;
169 wait_queue_head_t result_wait;
173 struct dm_target *ti;
174 struct dm_target_callbacks callbacks;
176 struct dm_cache_metadata *cmd;
179 * Metadata is written to this device.
181 struct dm_dev *metadata_dev;
184 * The slower of the two data devices. Typically a spindle.
186 struct dm_dev *origin_dev;
189 * The faster of the two data devices. Typically an SSD.
191 struct dm_dev *cache_dev;
194 * Size of the origin device in _complete_ blocks and native sectors.
196 dm_oblock_t origin_blocks;
197 sector_t origin_sectors;
200 * Size of the cache device in blocks.
202 dm_cblock_t cache_size;
205 * Fields for converting from sectors to blocks.
207 uint32_t sectors_per_block;
208 int sectors_per_block_shift;
211 struct bio_list deferred_bios;
212 struct bio_list deferred_flush_bios;
213 struct bio_list deferred_writethrough_bios;
214 struct list_head quiesced_migrations;
215 struct list_head completed_migrations;
216 struct list_head need_commit_migrations;
217 sector_t migration_threshold;
218 wait_queue_head_t migration_wait;
219 atomic_t nr_allocated_migrations;
222 * The number of in flight migrations that are performing
223 * background io. eg, promotion, writeback.
225 atomic_t nr_io_migrations;
227 wait_queue_head_t quiescing_wait;
229 atomic_t quiescing_ack;
232 * cache_size entries, dirty if set
235 unsigned long *dirty_bitset;
238 * origin_blocks entries, discarded if set.
240 dm_dblock_t discard_nr_blocks;
241 unsigned long *discard_bitset;
242 uint32_t discard_block_size; /* a power of 2 times sectors per block */
245 * Rather than reconstructing the table line for the status we just
246 * save it and regurgitate.
248 unsigned nr_ctr_args;
249 const char **ctr_args;
251 struct dm_kcopyd_client *copier;
252 struct workqueue_struct *wq;
253 struct work_struct worker;
255 struct delayed_work waker;
256 unsigned long last_commit_jiffies;
258 struct dm_bio_prison *prison;
259 struct dm_deferred_set *all_io_ds;
261 mempool_t *migration_pool;
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 struct dm_cache_migration *alloc_migration(struct cache *cache)
355 struct dm_cache_migration *mg;
357 mg = mempool_alloc(cache->migration_pool, GFP_NOWAIT);
360 atomic_inc(&mg->cache->nr_allocated_migrations);
366 static void free_migration(struct dm_cache_migration *mg)
368 if (atomic_dec_and_test(&mg->cache->nr_allocated_migrations))
369 wake_up(&mg->cache->migration_wait);
371 mempool_free(mg, mg->cache->migration_pool);
374 static int prealloc_data_structs(struct cache *cache, struct prealloc *p)
377 p->mg = alloc_migration(cache);
383 p->cell1 = alloc_prison_cell(cache);
389 p->cell2 = alloc_prison_cell(cache);
397 static void prealloc_free_structs(struct cache *cache, struct prealloc *p)
400 free_prison_cell(cache, p->cell2);
403 free_prison_cell(cache, p->cell1);
406 free_migration(p->mg);
409 static struct dm_cache_migration *prealloc_get_migration(struct prealloc *p)
411 struct dm_cache_migration *mg = p->mg;
420 * You must have a cell within the prealloc struct to return. If not this
421 * function will BUG() rather than returning NULL.
423 static struct dm_bio_prison_cell *prealloc_get_cell(struct prealloc *p)
425 struct dm_bio_prison_cell *r = NULL;
431 } else if (p->cell2) {
441 * You can't have more than two cells in a prealloc struct. BUG() will be
442 * called if you try and overfill.
444 static void prealloc_put_cell(struct prealloc *p, struct dm_bio_prison_cell *cell)
456 /*----------------------------------------------------------------*/
458 static void build_key(dm_oblock_t begin, dm_oblock_t end, struct dm_cell_key *key)
462 key->block_begin = from_oblock(begin);
463 key->block_end = from_oblock(end);
467 * The caller hands in a preallocated cell, and a free function for it.
468 * The cell will be freed if there's an error, or if it wasn't used because
469 * a cell with that key already exists.
471 typedef void (*cell_free_fn)(void *context, struct dm_bio_prison_cell *cell);
473 static int bio_detain_range(struct cache *cache, dm_oblock_t oblock_begin, dm_oblock_t oblock_end,
474 struct bio *bio, struct dm_bio_prison_cell *cell_prealloc,
475 cell_free_fn free_fn, void *free_context,
476 struct dm_bio_prison_cell **cell_result)
479 struct dm_cell_key key;
481 build_key(oblock_begin, oblock_end, &key);
482 r = dm_bio_detain(cache->prison, &key, bio, cell_prealloc, cell_result);
484 free_fn(free_context, cell_prealloc);
489 static int bio_detain(struct cache *cache, dm_oblock_t oblock,
490 struct bio *bio, struct dm_bio_prison_cell *cell_prealloc,
491 cell_free_fn free_fn, void *free_context,
492 struct dm_bio_prison_cell **cell_result)
494 dm_oblock_t end = to_oblock(from_oblock(oblock) + 1ULL);
495 return bio_detain_range(cache, oblock, end, bio,
496 cell_prealloc, free_fn, free_context, cell_result);
499 static int get_cell(struct cache *cache,
501 struct prealloc *structs,
502 struct dm_bio_prison_cell **cell_result)
505 struct dm_cell_key key;
506 struct dm_bio_prison_cell *cell_prealloc;
508 cell_prealloc = prealloc_get_cell(structs);
510 build_key(oblock, to_oblock(from_oblock(oblock) + 1ULL), &key);
511 r = dm_get_cell(cache->prison, &key, cell_prealloc, cell_result);
513 prealloc_put_cell(structs, cell_prealloc);
518 /*----------------------------------------------------------------*/
520 static bool is_dirty(struct cache *cache, dm_cblock_t b)
522 return test_bit(from_cblock(b), cache->dirty_bitset);
525 static void set_dirty(struct cache *cache, dm_oblock_t oblock, dm_cblock_t cblock)
527 if (!test_and_set_bit(from_cblock(cblock), cache->dirty_bitset)) {
528 atomic_inc(&cache->nr_dirty);
529 policy_set_dirty(cache->policy, oblock);
533 static void clear_dirty(struct cache *cache, dm_oblock_t oblock, dm_cblock_t cblock)
535 if (test_and_clear_bit(from_cblock(cblock), cache->dirty_bitset)) {
536 policy_clear_dirty(cache->policy, oblock);
537 if (atomic_dec_return(&cache->nr_dirty) == 0)
538 dm_table_event(cache->ti->table);
542 /*----------------------------------------------------------------*/
544 static bool block_size_is_power_of_two(struct cache *cache)
546 return cache->sectors_per_block_shift >= 0;
549 /* gcc on ARM generates spurious references to __udivdi3 and __umoddi3 */
550 #if defined(CONFIG_ARM) && __GNUC__ == 4 && __GNUC_MINOR__ <= 6
553 static dm_block_t block_div(dm_block_t b, uint32_t n)
560 static dm_block_t oblocks_per_dblock(struct cache *cache)
562 dm_block_t oblocks = cache->discard_block_size;
564 if (block_size_is_power_of_two(cache))
565 oblocks >>= cache->sectors_per_block_shift;
567 oblocks = block_div(oblocks, cache->sectors_per_block);
572 static dm_dblock_t oblock_to_dblock(struct cache *cache, dm_oblock_t oblock)
574 return to_dblock(block_div(from_oblock(oblock),
575 oblocks_per_dblock(cache)));
578 static dm_oblock_t dblock_to_oblock(struct cache *cache, dm_dblock_t dblock)
580 return to_oblock(from_dblock(dblock) * oblocks_per_dblock(cache));
583 static void set_discard(struct cache *cache, dm_dblock_t b)
587 BUG_ON(from_dblock(b) >= from_dblock(cache->discard_nr_blocks));
588 atomic_inc(&cache->stats.discard_count);
590 spin_lock_irqsave(&cache->lock, flags);
591 set_bit(from_dblock(b), cache->discard_bitset);
592 spin_unlock_irqrestore(&cache->lock, flags);
595 static void clear_discard(struct cache *cache, dm_dblock_t b)
599 spin_lock_irqsave(&cache->lock, flags);
600 clear_bit(from_dblock(b), cache->discard_bitset);
601 spin_unlock_irqrestore(&cache->lock, flags);
604 static bool is_discarded(struct cache *cache, dm_dblock_t b)
609 spin_lock_irqsave(&cache->lock, flags);
610 r = test_bit(from_dblock(b), cache->discard_bitset);
611 spin_unlock_irqrestore(&cache->lock, flags);
616 static bool is_discarded_oblock(struct cache *cache, dm_oblock_t b)
621 spin_lock_irqsave(&cache->lock, flags);
622 r = test_bit(from_dblock(oblock_to_dblock(cache, b)),
623 cache->discard_bitset);
624 spin_unlock_irqrestore(&cache->lock, flags);
629 /*----------------------------------------------------------------*/
631 static void load_stats(struct cache *cache)
633 struct dm_cache_statistics stats;
635 dm_cache_metadata_get_stats(cache->cmd, &stats);
636 atomic_set(&cache->stats.read_hit, stats.read_hits);
637 atomic_set(&cache->stats.read_miss, stats.read_misses);
638 atomic_set(&cache->stats.write_hit, stats.write_hits);
639 atomic_set(&cache->stats.write_miss, stats.write_misses);
642 static void save_stats(struct cache *cache)
644 struct dm_cache_statistics stats;
646 stats.read_hits = atomic_read(&cache->stats.read_hit);
647 stats.read_misses = atomic_read(&cache->stats.read_miss);
648 stats.write_hits = atomic_read(&cache->stats.write_hit);
649 stats.write_misses = atomic_read(&cache->stats.write_miss);
651 dm_cache_metadata_set_stats(cache->cmd, &stats);
654 /*----------------------------------------------------------------
656 *--------------------------------------------------------------*/
659 * If using writeback, leave out struct per_bio_data's writethrough fields.
661 #define PB_DATA_SIZE_WB (offsetof(struct per_bio_data, cache))
662 #define PB_DATA_SIZE_WT (sizeof(struct per_bio_data))
664 static bool writethrough_mode(struct cache_features *f)
666 return f->io_mode == CM_IO_WRITETHROUGH;
669 static bool writeback_mode(struct cache_features *f)
671 return f->io_mode == CM_IO_WRITEBACK;
674 static bool passthrough_mode(struct cache_features *f)
676 return f->io_mode == CM_IO_PASSTHROUGH;
679 static size_t get_per_bio_data_size(struct cache *cache)
681 return writethrough_mode(&cache->features) ? PB_DATA_SIZE_WT : PB_DATA_SIZE_WB;
684 static struct per_bio_data *get_per_bio_data(struct bio *bio, size_t data_size)
686 struct per_bio_data *pb = dm_per_bio_data(bio, data_size);
691 static struct per_bio_data *init_per_bio_data(struct bio *bio, size_t data_size)
693 struct per_bio_data *pb = get_per_bio_data(bio, data_size);
696 pb->req_nr = dm_bio_get_target_bio_nr(bio);
697 pb->all_io_entry = NULL;
702 /*----------------------------------------------------------------
704 *--------------------------------------------------------------*/
705 static void remap_to_origin(struct cache *cache, struct bio *bio)
707 bio->bi_bdev = cache->origin_dev->bdev;
710 static void remap_to_cache(struct cache *cache, struct bio *bio,
713 sector_t bi_sector = bio->bi_iter.bi_sector;
714 sector_t block = from_cblock(cblock);
716 bio->bi_bdev = cache->cache_dev->bdev;
717 if (!block_size_is_power_of_two(cache))
718 bio->bi_iter.bi_sector =
719 (block * cache->sectors_per_block) +
720 sector_div(bi_sector, cache->sectors_per_block);
722 bio->bi_iter.bi_sector =
723 (block << cache->sectors_per_block_shift) |
724 (bi_sector & (cache->sectors_per_block - 1));
727 static void check_if_tick_bio_needed(struct cache *cache, struct bio *bio)
730 size_t pb_data_size = get_per_bio_data_size(cache);
731 struct per_bio_data *pb = get_per_bio_data(bio, pb_data_size);
733 spin_lock_irqsave(&cache->lock, flags);
734 if (cache->need_tick_bio &&
735 !(bio->bi_rw & (REQ_FUA | REQ_FLUSH | REQ_DISCARD))) {
737 cache->need_tick_bio = false;
739 spin_unlock_irqrestore(&cache->lock, flags);
742 static void remap_to_origin_clear_discard(struct cache *cache, struct bio *bio,
745 check_if_tick_bio_needed(cache, bio);
746 remap_to_origin(cache, bio);
747 if (bio_data_dir(bio) == WRITE)
748 clear_discard(cache, oblock_to_dblock(cache, oblock));
751 static void remap_to_cache_dirty(struct cache *cache, struct bio *bio,
752 dm_oblock_t oblock, dm_cblock_t cblock)
754 check_if_tick_bio_needed(cache, bio);
755 remap_to_cache(cache, bio, cblock);
756 if (bio_data_dir(bio) == WRITE) {
757 set_dirty(cache, oblock, cblock);
758 clear_discard(cache, oblock_to_dblock(cache, oblock));
762 static dm_oblock_t get_bio_block(struct cache *cache, struct bio *bio)
764 sector_t block_nr = bio->bi_iter.bi_sector;
766 if (!block_size_is_power_of_two(cache))
767 (void) sector_div(block_nr, cache->sectors_per_block);
769 block_nr >>= cache->sectors_per_block_shift;
771 return to_oblock(block_nr);
774 static int bio_triggers_commit(struct cache *cache, struct bio *bio)
776 return bio->bi_rw & (REQ_FLUSH | REQ_FUA);
780 * You must increment the deferred set whilst the prison cell is held. To
781 * encourage this, we ask for 'cell' to be passed in.
783 static void inc_ds(struct cache *cache, struct bio *bio,
784 struct dm_bio_prison_cell *cell)
786 size_t pb_data_size = get_per_bio_data_size(cache);
787 struct per_bio_data *pb = get_per_bio_data(bio, pb_data_size);
790 BUG_ON(pb->all_io_entry);
792 pb->all_io_entry = dm_deferred_entry_inc(cache->all_io_ds);
795 static void issue(struct cache *cache, struct bio *bio)
799 if (!bio_triggers_commit(cache, bio)) {
800 generic_make_request(bio);
805 * Batch together any bios that trigger commits and then issue a
806 * single commit for them in do_worker().
808 spin_lock_irqsave(&cache->lock, flags);
809 cache->commit_requested = true;
810 bio_list_add(&cache->deferred_flush_bios, bio);
811 spin_unlock_irqrestore(&cache->lock, flags);
814 static void inc_and_issue(struct cache *cache, struct bio *bio, struct dm_bio_prison_cell *cell)
816 inc_ds(cache, bio, cell);
820 static void defer_writethrough_bio(struct cache *cache, struct bio *bio)
824 spin_lock_irqsave(&cache->lock, flags);
825 bio_list_add(&cache->deferred_writethrough_bios, bio);
826 spin_unlock_irqrestore(&cache->lock, flags);
831 static void writethrough_endio(struct bio *bio, int err)
833 struct per_bio_data *pb = get_per_bio_data(bio, PB_DATA_SIZE_WT);
835 dm_unhook_bio(&pb->hook_info, bio);
842 dm_bio_restore(&pb->bio_details, bio);
843 remap_to_cache(pb->cache, bio, pb->cblock);
846 * We can't issue this bio directly, since we're in interrupt
847 * context. So it gets put on a bio list for processing by the
850 defer_writethrough_bio(pb->cache, bio);
854 * When running in writethrough mode we need to send writes to clean blocks
855 * to both the cache and origin devices. In future we'd like to clone the
856 * bio and send them in parallel, but for now we're doing them in
857 * series as this is easier.
859 static void remap_to_origin_then_cache(struct cache *cache, struct bio *bio,
860 dm_oblock_t oblock, dm_cblock_t cblock)
862 struct per_bio_data *pb = get_per_bio_data(bio, PB_DATA_SIZE_WT);
866 dm_hook_bio(&pb->hook_info, bio, writethrough_endio, NULL);
867 dm_bio_record(&pb->bio_details, bio);
869 remap_to_origin_clear_discard(pb->cache, bio, oblock);
872 /*----------------------------------------------------------------
873 * Migration processing
875 * Migration covers moving data from the origin device to the cache, or
877 *--------------------------------------------------------------*/
878 static void inc_io_migrations(struct cache *cache)
880 atomic_inc(&cache->nr_io_migrations);
883 static void dec_io_migrations(struct cache *cache)
885 atomic_dec(&cache->nr_io_migrations);
888 static void __cell_defer(struct cache *cache, struct dm_bio_prison_cell *cell,
891 (holder ? dm_cell_release : dm_cell_release_no_holder)
892 (cache->prison, cell, &cache->deferred_bios);
893 free_prison_cell(cache, cell);
896 static void cell_defer(struct cache *cache, struct dm_bio_prison_cell *cell,
901 spin_lock_irqsave(&cache->lock, flags);
902 __cell_defer(cache, cell, holder);
903 spin_unlock_irqrestore(&cache->lock, flags);
908 static void free_io_migration(struct dm_cache_migration *mg)
910 dec_io_migrations(mg->cache);
914 static void migration_failure(struct dm_cache_migration *mg)
916 struct cache *cache = mg->cache;
919 DMWARN_LIMIT("writeback failed; couldn't copy block");
920 set_dirty(cache, mg->old_oblock, mg->cblock);
921 cell_defer(cache, mg->old_ocell, false);
923 } else if (mg->demote) {
924 DMWARN_LIMIT("demotion failed; couldn't copy block");
925 policy_force_mapping(cache->policy, mg->new_oblock, mg->old_oblock);
927 cell_defer(cache, mg->old_ocell, mg->promote ? false : true);
929 cell_defer(cache, mg->new_ocell, true);
931 DMWARN_LIMIT("promotion failed; couldn't copy block");
932 policy_remove_mapping(cache->policy, mg->new_oblock);
933 cell_defer(cache, mg->new_ocell, true);
936 free_io_migration(mg);
939 static void migration_success_pre_commit(struct dm_cache_migration *mg)
942 struct cache *cache = mg->cache;
945 clear_dirty(cache, mg->old_oblock, mg->cblock);
946 cell_defer(cache, mg->old_ocell, false);
947 free_io_migration(mg);
950 } else if (mg->demote) {
951 if (dm_cache_remove_mapping(cache->cmd, mg->cblock)) {
952 DMWARN_LIMIT("demotion failed; couldn't update on disk metadata");
953 policy_force_mapping(cache->policy, mg->new_oblock,
956 cell_defer(cache, mg->new_ocell, true);
957 free_io_migration(mg);
961 if (dm_cache_insert_mapping(cache->cmd, mg->cblock, mg->new_oblock)) {
962 DMWARN_LIMIT("promotion failed; couldn't update on disk metadata");
963 policy_remove_mapping(cache->policy, mg->new_oblock);
964 free_io_migration(mg);
969 spin_lock_irqsave(&cache->lock, flags);
970 list_add_tail(&mg->list, &cache->need_commit_migrations);
971 cache->commit_requested = true;
972 spin_unlock_irqrestore(&cache->lock, flags);
975 static void migration_success_post_commit(struct dm_cache_migration *mg)
978 struct cache *cache = mg->cache;
981 DMWARN("writeback unexpectedly triggered commit");
984 } else if (mg->demote) {
985 cell_defer(cache, mg->old_ocell, mg->promote ? false : true);
990 spin_lock_irqsave(&cache->lock, flags);
991 list_add_tail(&mg->list, &cache->quiesced_migrations);
992 spin_unlock_irqrestore(&cache->lock, flags);
996 policy_remove_mapping(cache->policy, mg->old_oblock);
997 free_io_migration(mg);
1001 if (mg->requeue_holder) {
1002 clear_dirty(cache, mg->new_oblock, mg->cblock);
1003 cell_defer(cache, mg->new_ocell, true);
1006 * The block was promoted via an overwrite, so it's dirty.
1008 set_dirty(cache, mg->new_oblock, mg->cblock);
1009 bio_endio(mg->new_ocell->holder, 0);
1010 cell_defer(cache, mg->new_ocell, false);
1012 free_io_migration(mg);
1016 static void copy_complete(int read_err, unsigned long write_err, void *context)
1018 unsigned long flags;
1019 struct dm_cache_migration *mg = (struct dm_cache_migration *) context;
1020 struct cache *cache = mg->cache;
1022 if (read_err || write_err)
1025 spin_lock_irqsave(&cache->lock, flags);
1026 list_add_tail(&mg->list, &cache->completed_migrations);
1027 spin_unlock_irqrestore(&cache->lock, flags);
1032 static void issue_copy(struct dm_cache_migration *mg)
1035 struct dm_io_region o_region, c_region;
1036 struct cache *cache = mg->cache;
1037 sector_t cblock = from_cblock(mg->cblock);
1039 o_region.bdev = cache->origin_dev->bdev;
1040 o_region.count = cache->sectors_per_block;
1042 c_region.bdev = cache->cache_dev->bdev;
1043 c_region.sector = cblock * cache->sectors_per_block;
1044 c_region.count = cache->sectors_per_block;
1046 if (mg->writeback || mg->demote) {
1048 o_region.sector = from_oblock(mg->old_oblock) * cache->sectors_per_block;
1049 r = dm_kcopyd_copy(cache->copier, &c_region, 1, &o_region, 0, copy_complete, mg);
1052 o_region.sector = from_oblock(mg->new_oblock) * cache->sectors_per_block;
1053 r = dm_kcopyd_copy(cache->copier, &o_region, 1, &c_region, 0, copy_complete, mg);
1057 DMERR_LIMIT("issuing migration failed");
1058 migration_failure(mg);
1062 static void overwrite_endio(struct bio *bio, int err)
1064 struct dm_cache_migration *mg = bio->bi_private;
1065 struct cache *cache = mg->cache;
1066 size_t pb_data_size = get_per_bio_data_size(cache);
1067 struct per_bio_data *pb = get_per_bio_data(bio, pb_data_size);
1068 unsigned long flags;
1070 dm_unhook_bio(&pb->hook_info, bio);
1075 mg->requeue_holder = false;
1077 spin_lock_irqsave(&cache->lock, flags);
1078 list_add_tail(&mg->list, &cache->completed_migrations);
1079 spin_unlock_irqrestore(&cache->lock, flags);
1084 static void issue_overwrite(struct dm_cache_migration *mg, struct bio *bio)
1086 size_t pb_data_size = get_per_bio_data_size(mg->cache);
1087 struct per_bio_data *pb = get_per_bio_data(bio, pb_data_size);
1089 dm_hook_bio(&pb->hook_info, bio, overwrite_endio, mg);
1090 remap_to_cache_dirty(mg->cache, bio, mg->new_oblock, mg->cblock);
1093 * No need to inc_ds() here, since the cell will be held for the
1094 * duration of the io.
1096 generic_make_request(bio);
1099 static bool bio_writes_complete_block(struct cache *cache, struct bio *bio)
1101 return (bio_data_dir(bio) == WRITE) &&
1102 (bio->bi_iter.bi_size == (cache->sectors_per_block << SECTOR_SHIFT));
1105 static void avoid_copy(struct dm_cache_migration *mg)
1107 atomic_inc(&mg->cache->stats.copies_avoided);
1108 migration_success_pre_commit(mg);
1111 static void calc_discard_block_range(struct cache *cache, struct bio *bio,
1112 dm_dblock_t *b, dm_dblock_t *e)
1114 sector_t sb = bio->bi_iter.bi_sector;
1115 sector_t se = bio_end_sector(bio);
1117 *b = to_dblock(dm_sector_div_up(sb, cache->discard_block_size));
1119 if (se - sb < cache->discard_block_size)
1122 *e = to_dblock(block_div(se, cache->discard_block_size));
1125 static void issue_discard(struct dm_cache_migration *mg)
1128 struct bio *bio = mg->new_ocell->holder;
1130 calc_discard_block_range(mg->cache, bio, &b, &e);
1132 set_discard(mg->cache, b);
1133 b = to_dblock(from_dblock(b) + 1);
1137 cell_defer(mg->cache, mg->new_ocell, false);
1141 static void issue_copy_or_discard(struct dm_cache_migration *mg)
1144 struct cache *cache = mg->cache;
1151 if (mg->writeback || mg->demote)
1152 avoid = !is_dirty(cache, mg->cblock) ||
1153 is_discarded_oblock(cache, mg->old_oblock);
1155 struct bio *bio = mg->new_ocell->holder;
1157 avoid = is_discarded_oblock(cache, mg->new_oblock);
1159 if (writeback_mode(&cache->features) &&
1160 !avoid && bio_writes_complete_block(cache, bio)) {
1161 issue_overwrite(mg, bio);
1166 avoid ? avoid_copy(mg) : issue_copy(mg);
1169 static void complete_migration(struct dm_cache_migration *mg)
1172 migration_failure(mg);
1174 migration_success_pre_commit(mg);
1177 static void process_migrations(struct cache *cache, struct list_head *head,
1178 void (*fn)(struct dm_cache_migration *))
1180 unsigned long flags;
1181 struct list_head list;
1182 struct dm_cache_migration *mg, *tmp;
1184 INIT_LIST_HEAD(&list);
1185 spin_lock_irqsave(&cache->lock, flags);
1186 list_splice_init(head, &list);
1187 spin_unlock_irqrestore(&cache->lock, flags);
1189 list_for_each_entry_safe(mg, tmp, &list, list)
1193 static void __queue_quiesced_migration(struct dm_cache_migration *mg)
1195 list_add_tail(&mg->list, &mg->cache->quiesced_migrations);
1198 static void queue_quiesced_migration(struct dm_cache_migration *mg)
1200 unsigned long flags;
1201 struct cache *cache = mg->cache;
1203 spin_lock_irqsave(&cache->lock, flags);
1204 __queue_quiesced_migration(mg);
1205 spin_unlock_irqrestore(&cache->lock, flags);
1210 static void queue_quiesced_migrations(struct cache *cache, struct list_head *work)
1212 unsigned long flags;
1213 struct dm_cache_migration *mg, *tmp;
1215 spin_lock_irqsave(&cache->lock, flags);
1216 list_for_each_entry_safe(mg, tmp, work, list)
1217 __queue_quiesced_migration(mg);
1218 spin_unlock_irqrestore(&cache->lock, flags);
1223 static void check_for_quiesced_migrations(struct cache *cache,
1224 struct per_bio_data *pb)
1226 struct list_head work;
1228 if (!pb->all_io_entry)
1231 INIT_LIST_HEAD(&work);
1232 dm_deferred_entry_dec(pb->all_io_entry, &work);
1234 if (!list_empty(&work))
1235 queue_quiesced_migrations(cache, &work);
1238 static void quiesce_migration(struct dm_cache_migration *mg)
1240 if (!dm_deferred_set_add_work(mg->cache->all_io_ds, &mg->list))
1241 queue_quiesced_migration(mg);
1244 static void promote(struct cache *cache, struct prealloc *structs,
1245 dm_oblock_t oblock, dm_cblock_t cblock,
1246 struct dm_bio_prison_cell *cell)
1248 struct dm_cache_migration *mg = prealloc_get_migration(structs);
1251 mg->discard = false;
1252 mg->writeback = false;
1255 mg->requeue_holder = true;
1256 mg->invalidate = false;
1258 mg->new_oblock = oblock;
1259 mg->cblock = cblock;
1260 mg->old_ocell = NULL;
1261 mg->new_ocell = cell;
1262 mg->start_jiffies = jiffies;
1264 inc_io_migrations(cache);
1265 quiesce_migration(mg);
1268 static void writeback(struct cache *cache, struct prealloc *structs,
1269 dm_oblock_t oblock, dm_cblock_t cblock,
1270 struct dm_bio_prison_cell *cell)
1272 struct dm_cache_migration *mg = prealloc_get_migration(structs);
1275 mg->discard = false;
1276 mg->writeback = true;
1278 mg->promote = false;
1279 mg->requeue_holder = true;
1280 mg->invalidate = false;
1282 mg->old_oblock = oblock;
1283 mg->cblock = cblock;
1284 mg->old_ocell = cell;
1285 mg->new_ocell = NULL;
1286 mg->start_jiffies = jiffies;
1288 inc_io_migrations(cache);
1289 quiesce_migration(mg);
1292 static void demote_then_promote(struct cache *cache, struct prealloc *structs,
1293 dm_oblock_t old_oblock, dm_oblock_t new_oblock,
1295 struct dm_bio_prison_cell *old_ocell,
1296 struct dm_bio_prison_cell *new_ocell)
1298 struct dm_cache_migration *mg = prealloc_get_migration(structs);
1301 mg->discard = false;
1302 mg->writeback = false;
1305 mg->requeue_holder = true;
1306 mg->invalidate = false;
1308 mg->old_oblock = old_oblock;
1309 mg->new_oblock = new_oblock;
1310 mg->cblock = cblock;
1311 mg->old_ocell = old_ocell;
1312 mg->new_ocell = new_ocell;
1313 mg->start_jiffies = jiffies;
1315 inc_io_migrations(cache);
1316 quiesce_migration(mg);
1320 * Invalidate a cache entry. No writeback occurs; any changes in the cache
1321 * block are thrown away.
1323 static void invalidate(struct cache *cache, struct prealloc *structs,
1324 dm_oblock_t oblock, dm_cblock_t cblock,
1325 struct dm_bio_prison_cell *cell)
1327 struct dm_cache_migration *mg = prealloc_get_migration(structs);
1330 mg->discard = false;
1331 mg->writeback = false;
1333 mg->promote = false;
1334 mg->requeue_holder = true;
1335 mg->invalidate = true;
1337 mg->old_oblock = oblock;
1338 mg->cblock = cblock;
1339 mg->old_ocell = cell;
1340 mg->new_ocell = NULL;
1341 mg->start_jiffies = jiffies;
1343 inc_io_migrations(cache);
1344 quiesce_migration(mg);
1347 static void discard(struct cache *cache, struct prealloc *structs,
1348 struct dm_bio_prison_cell *cell)
1350 struct dm_cache_migration *mg = prealloc_get_migration(structs);
1354 mg->writeback = false;
1356 mg->promote = false;
1357 mg->requeue_holder = false;
1358 mg->invalidate = false;
1360 mg->old_ocell = NULL;
1361 mg->new_ocell = cell;
1362 mg->start_jiffies = jiffies;
1364 quiesce_migration(mg);
1367 /*----------------------------------------------------------------
1369 *--------------------------------------------------------------*/
1370 static void defer_bio(struct cache *cache, struct bio *bio)
1372 unsigned long flags;
1374 spin_lock_irqsave(&cache->lock, flags);
1375 bio_list_add(&cache->deferred_bios, bio);
1376 spin_unlock_irqrestore(&cache->lock, flags);
1381 static void process_flush_bio(struct cache *cache, struct bio *bio)
1383 size_t pb_data_size = get_per_bio_data_size(cache);
1384 struct per_bio_data *pb = get_per_bio_data(bio, pb_data_size);
1386 BUG_ON(bio->bi_iter.bi_size);
1388 remap_to_origin(cache, bio);
1390 remap_to_cache(cache, bio, 0);
1393 * REQ_FLUSH is not directed at any particular block so we don't
1394 * need to inc_ds(). REQ_FUA's are split into a write + REQ_FLUSH
1400 static void process_discard_bio(struct cache *cache, struct prealloc *structs,
1405 struct dm_bio_prison_cell *cell_prealloc, *new_ocell;
1407 calc_discard_block_range(cache, bio, &b, &e);
1413 cell_prealloc = prealloc_get_cell(structs);
1414 r = bio_detain_range(cache, dblock_to_oblock(cache, b), dblock_to_oblock(cache, e), bio, cell_prealloc,
1415 (cell_free_fn) prealloc_put_cell,
1416 structs, &new_ocell);
1420 discard(cache, structs, new_ocell);
1423 static bool spare_migration_bandwidth(struct cache *cache)
1425 sector_t current_volume = (atomic_read(&cache->nr_io_migrations) + 1) *
1426 cache->sectors_per_block;
1427 return current_volume < cache->migration_threshold;
1430 static void inc_hit_counter(struct cache *cache, struct bio *bio)
1432 atomic_inc(bio_data_dir(bio) == READ ?
1433 &cache->stats.read_hit : &cache->stats.write_hit);
1436 static void inc_miss_counter(struct cache *cache, struct bio *bio)
1438 atomic_inc(bio_data_dir(bio) == READ ?
1439 &cache->stats.read_miss : &cache->stats.write_miss);
1442 /*----------------------------------------------------------------*/
1444 struct old_oblock_lock {
1445 struct policy_locker locker;
1446 struct cache *cache;
1447 struct prealloc *structs;
1448 struct dm_bio_prison_cell *cell;
1451 static int null_locker(struct policy_locker *locker, dm_oblock_t b)
1453 /* This should never be called */
1458 static int cell_locker(struct policy_locker *locker, dm_oblock_t b)
1460 struct old_oblock_lock *l = container_of(locker, struct old_oblock_lock, locker);
1461 struct dm_bio_prison_cell *cell_prealloc = prealloc_get_cell(l->structs);
1463 return bio_detain(l->cache, b, NULL, cell_prealloc,
1464 (cell_free_fn) prealloc_put_cell,
1465 l->structs, &l->cell);
1468 static void process_bio(struct cache *cache, struct prealloc *structs,
1472 bool release_cell = true;
1473 dm_oblock_t block = get_bio_block(cache, bio);
1474 struct dm_bio_prison_cell *cell_prealloc, *new_ocell;
1475 struct policy_result lookup_result;
1476 bool passthrough = passthrough_mode(&cache->features);
1477 bool discarded_block, can_migrate;
1478 struct old_oblock_lock ool;
1481 * Check to see if that block is currently migrating.
1483 cell_prealloc = prealloc_get_cell(structs);
1484 r = bio_detain(cache, block, bio, cell_prealloc,
1485 (cell_free_fn) prealloc_put_cell,
1486 structs, &new_ocell);
1490 discarded_block = is_discarded_oblock(cache, block);
1491 can_migrate = !passthrough && (discarded_block || spare_migration_bandwidth(cache));
1493 ool.locker.fn = cell_locker;
1495 ool.structs = structs;
1497 r = policy_map(cache->policy, block, true, can_migrate, discarded_block,
1498 bio, &ool.locker, &lookup_result);
1500 if (r == -EWOULDBLOCK)
1501 /* migration has been denied */
1502 lookup_result.op = POLICY_MISS;
1504 switch (lookup_result.op) {
1507 inc_miss_counter(cache, bio);
1510 * Passthrough always maps to the origin,
1511 * invalidating any cache blocks that are written
1515 if (bio_data_dir(bio) == WRITE) {
1516 atomic_inc(&cache->stats.demotion);
1517 invalidate(cache, structs, block, lookup_result.cblock, new_ocell);
1518 release_cell = false;
1521 /* FIXME: factor out issue_origin() */
1522 remap_to_origin_clear_discard(cache, bio, block);
1523 inc_and_issue(cache, bio, new_ocell);
1526 inc_hit_counter(cache, bio);
1528 if (bio_data_dir(bio) == WRITE &&
1529 writethrough_mode(&cache->features) &&
1530 !is_dirty(cache, lookup_result.cblock)) {
1531 remap_to_origin_then_cache(cache, bio, block, lookup_result.cblock);
1532 inc_and_issue(cache, bio, new_ocell);
1535 remap_to_cache_dirty(cache, bio, block, lookup_result.cblock);
1536 inc_and_issue(cache, bio, new_ocell);
1543 inc_miss_counter(cache, bio);
1544 remap_to_origin_clear_discard(cache, bio, block);
1545 inc_and_issue(cache, bio, new_ocell);
1549 atomic_inc(&cache->stats.promotion);
1550 promote(cache, structs, block, lookup_result.cblock, new_ocell);
1551 release_cell = false;
1554 case POLICY_REPLACE:
1555 atomic_inc(&cache->stats.demotion);
1556 atomic_inc(&cache->stats.promotion);
1557 demote_then_promote(cache, structs, lookup_result.old_oblock,
1558 block, lookup_result.cblock,
1559 ool.cell, new_ocell);
1560 release_cell = false;
1564 DMERR_LIMIT("%s: erroring bio, unknown policy op: %u", __func__,
1565 (unsigned) lookup_result.op);
1570 cell_defer(cache, new_ocell, false);
1573 static int need_commit_due_to_time(struct cache *cache)
1575 return !time_in_range(jiffies, cache->last_commit_jiffies,
1576 cache->last_commit_jiffies + COMMIT_PERIOD);
1579 static int commit_if_needed(struct cache *cache)
1583 if ((cache->commit_requested || need_commit_due_to_time(cache)) &&
1584 dm_cache_changed_this_transaction(cache->cmd)) {
1585 atomic_inc(&cache->stats.commit_count);
1586 cache->commit_requested = false;
1587 r = dm_cache_commit(cache->cmd, false);
1588 cache->last_commit_jiffies = jiffies;
1594 static void process_deferred_bios(struct cache *cache)
1596 unsigned long flags;
1597 struct bio_list bios;
1599 struct prealloc structs;
1601 memset(&structs, 0, sizeof(structs));
1602 bio_list_init(&bios);
1604 spin_lock_irqsave(&cache->lock, flags);
1605 bio_list_merge(&bios, &cache->deferred_bios);
1606 bio_list_init(&cache->deferred_bios);
1607 spin_unlock_irqrestore(&cache->lock, flags);
1609 while (!bio_list_empty(&bios)) {
1611 * If we've got no free migration structs, and processing
1612 * this bio might require one, we pause until there are some
1613 * prepared mappings to process.
1615 if (prealloc_data_structs(cache, &structs)) {
1616 spin_lock_irqsave(&cache->lock, flags);
1617 bio_list_merge(&cache->deferred_bios, &bios);
1618 spin_unlock_irqrestore(&cache->lock, flags);
1622 bio = bio_list_pop(&bios);
1624 if (bio->bi_rw & REQ_FLUSH)
1625 process_flush_bio(cache, bio);
1626 else if (bio->bi_rw & REQ_DISCARD)
1627 process_discard_bio(cache, &structs, bio);
1629 process_bio(cache, &structs, bio);
1632 prealloc_free_structs(cache, &structs);
1635 static void process_deferred_flush_bios(struct cache *cache, bool submit_bios)
1637 unsigned long flags;
1638 struct bio_list bios;
1641 bio_list_init(&bios);
1643 spin_lock_irqsave(&cache->lock, flags);
1644 bio_list_merge(&bios, &cache->deferred_flush_bios);
1645 bio_list_init(&cache->deferred_flush_bios);
1646 spin_unlock_irqrestore(&cache->lock, flags);
1649 * These bios have already been through inc_ds()
1651 while ((bio = bio_list_pop(&bios)))
1652 submit_bios ? generic_make_request(bio) : bio_io_error(bio);
1655 static void process_deferred_writethrough_bios(struct cache *cache)
1657 unsigned long flags;
1658 struct bio_list bios;
1661 bio_list_init(&bios);
1663 spin_lock_irqsave(&cache->lock, flags);
1664 bio_list_merge(&bios, &cache->deferred_writethrough_bios);
1665 bio_list_init(&cache->deferred_writethrough_bios);
1666 spin_unlock_irqrestore(&cache->lock, flags);
1669 * These bios have already been through inc_ds()
1671 while ((bio = bio_list_pop(&bios)))
1672 generic_make_request(bio);
1675 static void writeback_some_dirty_blocks(struct cache *cache)
1680 struct prealloc structs;
1681 struct dm_bio_prison_cell *old_ocell;
1683 memset(&structs, 0, sizeof(structs));
1685 while (spare_migration_bandwidth(cache)) {
1686 if (prealloc_data_structs(cache, &structs))
1689 r = policy_writeback_work(cache->policy, &oblock, &cblock);
1693 r = get_cell(cache, oblock, &structs, &old_ocell);
1695 policy_set_dirty(cache->policy, oblock);
1699 writeback(cache, &structs, oblock, cblock, old_ocell);
1702 prealloc_free_structs(cache, &structs);
1705 /*----------------------------------------------------------------
1707 * Dropping something from the cache *without* writing back.
1708 *--------------------------------------------------------------*/
1710 static void process_invalidation_request(struct cache *cache, struct invalidation_request *req)
1713 uint64_t begin = from_cblock(req->cblocks->begin);
1714 uint64_t end = from_cblock(req->cblocks->end);
1716 while (begin != end) {
1717 r = policy_remove_cblock(cache->policy, to_cblock(begin));
1719 r = dm_cache_remove_mapping(cache->cmd, to_cblock(begin));
1723 } else if (r == -ENODATA) {
1724 /* harmless, already unmapped */
1728 DMERR("policy_remove_cblock failed");
1735 cache->commit_requested = true;
1738 atomic_set(&req->complete, 1);
1740 wake_up(&req->result_wait);
1743 static void process_invalidation_requests(struct cache *cache)
1745 struct list_head list;
1746 struct invalidation_request *req, *tmp;
1748 INIT_LIST_HEAD(&list);
1749 spin_lock(&cache->invalidation_lock);
1750 list_splice_init(&cache->invalidation_requests, &list);
1751 spin_unlock(&cache->invalidation_lock);
1753 list_for_each_entry_safe (req, tmp, &list, list)
1754 process_invalidation_request(cache, req);
1757 /*----------------------------------------------------------------
1759 *--------------------------------------------------------------*/
1760 static bool is_quiescing(struct cache *cache)
1762 return atomic_read(&cache->quiescing);
1765 static void ack_quiescing(struct cache *cache)
1767 if (is_quiescing(cache)) {
1768 atomic_inc(&cache->quiescing_ack);
1769 wake_up(&cache->quiescing_wait);
1773 static void wait_for_quiescing_ack(struct cache *cache)
1775 wait_event(cache->quiescing_wait, atomic_read(&cache->quiescing_ack));
1778 static void start_quiescing(struct cache *cache)
1780 atomic_inc(&cache->quiescing);
1781 wait_for_quiescing_ack(cache);
1784 static void stop_quiescing(struct cache *cache)
1786 atomic_set(&cache->quiescing, 0);
1787 atomic_set(&cache->quiescing_ack, 0);
1790 static void wait_for_migrations(struct cache *cache)
1792 wait_event(cache->migration_wait, !atomic_read(&cache->nr_allocated_migrations));
1795 static void stop_worker(struct cache *cache)
1797 cancel_delayed_work(&cache->waker);
1798 flush_workqueue(cache->wq);
1801 static void requeue_deferred_io(struct cache *cache)
1804 struct bio_list bios;
1806 bio_list_init(&bios);
1807 bio_list_merge(&bios, &cache->deferred_bios);
1808 bio_list_init(&cache->deferred_bios);
1810 while ((bio = bio_list_pop(&bios)))
1811 bio_endio(bio, DM_ENDIO_REQUEUE);
1814 static int more_work(struct cache *cache)
1816 if (is_quiescing(cache))
1817 return !list_empty(&cache->quiesced_migrations) ||
1818 !list_empty(&cache->completed_migrations) ||
1819 !list_empty(&cache->need_commit_migrations);
1821 return !bio_list_empty(&cache->deferred_bios) ||
1822 !bio_list_empty(&cache->deferred_flush_bios) ||
1823 !bio_list_empty(&cache->deferred_writethrough_bios) ||
1824 !list_empty(&cache->quiesced_migrations) ||
1825 !list_empty(&cache->completed_migrations) ||
1826 !list_empty(&cache->need_commit_migrations) ||
1830 static void do_worker(struct work_struct *ws)
1832 struct cache *cache = container_of(ws, struct cache, worker);
1835 if (!is_quiescing(cache)) {
1836 writeback_some_dirty_blocks(cache);
1837 process_deferred_writethrough_bios(cache);
1838 process_deferred_bios(cache);
1839 process_invalidation_requests(cache);
1842 process_migrations(cache, &cache->quiesced_migrations, issue_copy_or_discard);
1843 process_migrations(cache, &cache->completed_migrations, complete_migration);
1845 if (commit_if_needed(cache)) {
1846 process_deferred_flush_bios(cache, false);
1847 process_migrations(cache, &cache->need_commit_migrations, migration_failure);
1850 * FIXME: rollback metadata or just go into a
1851 * failure mode and error everything
1854 process_deferred_flush_bios(cache, true);
1855 process_migrations(cache, &cache->need_commit_migrations,
1856 migration_success_post_commit);
1859 ack_quiescing(cache);
1861 } while (more_work(cache));
1865 * We want to commit periodically so that not too much
1866 * unwritten metadata builds up.
1868 static void do_waker(struct work_struct *ws)
1870 struct cache *cache = container_of(to_delayed_work(ws), struct cache, waker);
1871 policy_tick(cache->policy);
1873 queue_delayed_work(cache->wq, &cache->waker, COMMIT_PERIOD);
1876 /*----------------------------------------------------------------*/
1878 static int is_congested(struct dm_dev *dev, int bdi_bits)
1880 struct request_queue *q = bdev_get_queue(dev->bdev);
1881 return bdi_congested(&q->backing_dev_info, bdi_bits);
1884 static int cache_is_congested(struct dm_target_callbacks *cb, int bdi_bits)
1886 struct cache *cache = container_of(cb, struct cache, callbacks);
1888 return is_congested(cache->origin_dev, bdi_bits) ||
1889 is_congested(cache->cache_dev, bdi_bits);
1892 /*----------------------------------------------------------------
1894 *--------------------------------------------------------------*/
1897 * This function gets called on the error paths of the constructor, so we
1898 * have to cope with a partially initialised struct.
1900 static void destroy(struct cache *cache)
1904 if (cache->migration_pool)
1905 mempool_destroy(cache->migration_pool);
1907 if (cache->all_io_ds)
1908 dm_deferred_set_destroy(cache->all_io_ds);
1911 dm_bio_prison_destroy(cache->prison);
1914 destroy_workqueue(cache->wq);
1916 if (cache->dirty_bitset)
1917 free_bitset(cache->dirty_bitset);
1919 if (cache->discard_bitset)
1920 free_bitset(cache->discard_bitset);
1923 dm_kcopyd_client_destroy(cache->copier);
1926 dm_cache_metadata_close(cache->cmd);
1928 if (cache->metadata_dev)
1929 dm_put_device(cache->ti, cache->metadata_dev);
1931 if (cache->origin_dev)
1932 dm_put_device(cache->ti, cache->origin_dev);
1934 if (cache->cache_dev)
1935 dm_put_device(cache->ti, cache->cache_dev);
1938 dm_cache_policy_destroy(cache->policy);
1940 for (i = 0; i < cache->nr_ctr_args ; i++)
1941 kfree(cache->ctr_args[i]);
1942 kfree(cache->ctr_args);
1947 static void cache_dtr(struct dm_target *ti)
1949 struct cache *cache = ti->private;
1954 static sector_t get_dev_size(struct dm_dev *dev)
1956 return i_size_read(dev->bdev->bd_inode) >> SECTOR_SHIFT;
1959 /*----------------------------------------------------------------*/
1962 * Construct a cache device mapping.
1964 * cache <metadata dev> <cache dev> <origin dev> <block size>
1965 * <#feature args> [<feature arg>]*
1966 * <policy> <#policy args> [<policy arg>]*
1968 * metadata dev : fast device holding the persistent metadata
1969 * cache dev : fast device holding cached data blocks
1970 * origin dev : slow device holding original data blocks
1971 * block size : cache unit size in sectors
1973 * #feature args : number of feature arguments passed
1974 * feature args : writethrough. (The default is writeback.)
1976 * policy : the replacement policy to use
1977 * #policy args : an even number of policy arguments corresponding
1978 * to key/value pairs passed to the policy
1979 * policy args : key/value pairs passed to the policy
1980 * E.g. 'sequential_threshold 1024'
1981 * See cache-policies.txt for details.
1983 * Optional feature arguments are:
1984 * writethrough : write through caching that prohibits cache block
1985 * content from being different from origin block content.
1986 * Without this argument, the default behaviour is to write
1987 * back cache block contents later for performance reasons,
1988 * so they may differ from the corresponding origin blocks.
1991 struct dm_target *ti;
1993 struct dm_dev *metadata_dev;
1995 struct dm_dev *cache_dev;
1996 sector_t cache_sectors;
1998 struct dm_dev *origin_dev;
1999 sector_t origin_sectors;
2001 uint32_t block_size;
2003 const char *policy_name;
2005 const char **policy_argv;
2007 struct cache_features features;
2010 static void destroy_cache_args(struct cache_args *ca)
2012 if (ca->metadata_dev)
2013 dm_put_device(ca->ti, ca->metadata_dev);
2016 dm_put_device(ca->ti, ca->cache_dev);
2019 dm_put_device(ca->ti, ca->origin_dev);
2024 static bool at_least_one_arg(struct dm_arg_set *as, char **error)
2027 *error = "Insufficient args";
2034 static int parse_metadata_dev(struct cache_args *ca, struct dm_arg_set *as,
2038 sector_t metadata_dev_size;
2039 char b[BDEVNAME_SIZE];
2041 if (!at_least_one_arg(as, error))
2044 r = dm_get_device(ca->ti, dm_shift_arg(as), FMODE_READ | FMODE_WRITE,
2047 *error = "Error opening metadata device";
2051 metadata_dev_size = get_dev_size(ca->metadata_dev);
2052 if (metadata_dev_size > DM_CACHE_METADATA_MAX_SECTORS_WARNING)
2053 DMWARN("Metadata device %s is larger than %u sectors: excess space will not be used.",
2054 bdevname(ca->metadata_dev->bdev, b), THIN_METADATA_MAX_SECTORS);
2059 static int parse_cache_dev(struct cache_args *ca, struct dm_arg_set *as,
2064 if (!at_least_one_arg(as, error))
2067 r = dm_get_device(ca->ti, dm_shift_arg(as), FMODE_READ | FMODE_WRITE,
2070 *error = "Error opening cache device";
2073 ca->cache_sectors = get_dev_size(ca->cache_dev);
2078 static int parse_origin_dev(struct cache_args *ca, struct dm_arg_set *as,
2083 if (!at_least_one_arg(as, error))
2086 r = dm_get_device(ca->ti, dm_shift_arg(as), FMODE_READ | FMODE_WRITE,
2089 *error = "Error opening origin device";
2093 ca->origin_sectors = get_dev_size(ca->origin_dev);
2094 if (ca->ti->len > ca->origin_sectors) {
2095 *error = "Device size larger than cached device";
2102 static int parse_block_size(struct cache_args *ca, struct dm_arg_set *as,
2105 unsigned long block_size;
2107 if (!at_least_one_arg(as, error))
2110 if (kstrtoul(dm_shift_arg(as), 10, &block_size) || !block_size ||
2111 block_size < DATA_DEV_BLOCK_SIZE_MIN_SECTORS ||
2112 block_size > DATA_DEV_BLOCK_SIZE_MAX_SECTORS ||
2113 block_size & (DATA_DEV_BLOCK_SIZE_MIN_SECTORS - 1)) {
2114 *error = "Invalid data block size";
2118 if (block_size > ca->cache_sectors) {
2119 *error = "Data block size is larger than the cache device";
2123 ca->block_size = block_size;
2128 static void init_features(struct cache_features *cf)
2130 cf->mode = CM_WRITE;
2131 cf->io_mode = CM_IO_WRITEBACK;
2134 static int parse_features(struct cache_args *ca, struct dm_arg_set *as,
2137 static struct dm_arg _args[] = {
2138 {0, 1, "Invalid number of cache feature arguments"},
2144 struct cache_features *cf = &ca->features;
2148 r = dm_read_arg_group(_args, as, &argc, error);
2153 arg = dm_shift_arg(as);
2155 if (!strcasecmp(arg, "writeback"))
2156 cf->io_mode = CM_IO_WRITEBACK;
2158 else if (!strcasecmp(arg, "writethrough"))
2159 cf->io_mode = CM_IO_WRITETHROUGH;
2161 else if (!strcasecmp(arg, "passthrough"))
2162 cf->io_mode = CM_IO_PASSTHROUGH;
2165 *error = "Unrecognised cache feature requested";
2173 static int parse_policy(struct cache_args *ca, struct dm_arg_set *as,
2176 static struct dm_arg _args[] = {
2177 {0, 1024, "Invalid number of policy arguments"},
2182 if (!at_least_one_arg(as, error))
2185 ca->policy_name = dm_shift_arg(as);
2187 r = dm_read_arg_group(_args, as, &ca->policy_argc, error);
2191 ca->policy_argv = (const char **)as->argv;
2192 dm_consume_args(as, ca->policy_argc);
2197 static int parse_cache_args(struct cache_args *ca, int argc, char **argv,
2201 struct dm_arg_set as;
2206 r = parse_metadata_dev(ca, &as, error);
2210 r = parse_cache_dev(ca, &as, error);
2214 r = parse_origin_dev(ca, &as, error);
2218 r = parse_block_size(ca, &as, error);
2222 r = parse_features(ca, &as, error);
2226 r = parse_policy(ca, &as, error);
2233 /*----------------------------------------------------------------*/
2235 static struct kmem_cache *migration_cache;
2237 #define NOT_CORE_OPTION 1
2239 static int process_config_option(struct cache *cache, const char *key, const char *value)
2243 if (!strcasecmp(key, "migration_threshold")) {
2244 if (kstrtoul(value, 10, &tmp))
2247 cache->migration_threshold = tmp;
2251 return NOT_CORE_OPTION;
2254 static int set_config_value(struct cache *cache, const char *key, const char *value)
2256 int r = process_config_option(cache, key, value);
2258 if (r == NOT_CORE_OPTION)
2259 r = policy_set_config_value(cache->policy, key, value);
2262 DMWARN("bad config value for %s: %s", key, value);
2267 static int set_config_values(struct cache *cache, int argc, const char **argv)
2272 DMWARN("Odd number of policy arguments given but they should be <key> <value> pairs.");
2277 r = set_config_value(cache, argv[0], argv[1]);
2288 static int create_cache_policy(struct cache *cache, struct cache_args *ca,
2291 struct dm_cache_policy *p = dm_cache_policy_create(ca->policy_name,
2293 cache->origin_sectors,
2294 cache->sectors_per_block);
2296 *error = "Error creating cache's policy";
2305 * We want the discard block size to be at least the size of the cache
2306 * block size and have no more than 2^14 discard blocks across the origin.
2308 #define MAX_DISCARD_BLOCKS (1 << 14)
2310 static bool too_many_discard_blocks(sector_t discard_block_size,
2311 sector_t origin_size)
2313 (void) sector_div(origin_size, discard_block_size);
2315 return origin_size > MAX_DISCARD_BLOCKS;
2318 static sector_t calculate_discard_block_size(sector_t cache_block_size,
2319 sector_t origin_size)
2321 sector_t discard_block_size = cache_block_size;
2324 while (too_many_discard_blocks(discard_block_size, origin_size))
2325 discard_block_size *= 2;
2327 return discard_block_size;
2330 static void set_cache_size(struct cache *cache, dm_cblock_t size)
2332 dm_block_t nr_blocks = from_cblock(size);
2334 if (nr_blocks > (1 << 20) && cache->cache_size != size)
2335 DMWARN_LIMIT("You have created a cache device with a lot of individual cache blocks (%llu)\n"
2336 "All these mappings can consume a lot of kernel memory, and take some time to read/write.\n"
2337 "Please consider increasing the cache block size to reduce the overall cache block count.",
2338 (unsigned long long) nr_blocks);
2340 cache->cache_size = size;
2343 #define DEFAULT_MIGRATION_THRESHOLD 2048
2345 static int cache_create(struct cache_args *ca, struct cache **result)
2348 char **error = &ca->ti->error;
2349 struct cache *cache;
2350 struct dm_target *ti = ca->ti;
2351 dm_block_t origin_blocks;
2352 struct dm_cache_metadata *cmd;
2353 bool may_format = ca->features.mode == CM_WRITE;
2355 cache = kzalloc(sizeof(*cache), GFP_KERNEL);
2360 ti->private = cache;
2361 ti->num_flush_bios = 2;
2362 ti->flush_supported = true;
2364 ti->num_discard_bios = 1;
2365 ti->discards_supported = true;
2366 ti->discard_zeroes_data_unsupported = true;
2367 ti->split_discard_bios = false;
2369 cache->features = ca->features;
2370 ti->per_bio_data_size = get_per_bio_data_size(cache);
2372 cache->callbacks.congested_fn = cache_is_congested;
2373 dm_table_add_target_callbacks(ti->table, &cache->callbacks);
2375 cache->metadata_dev = ca->metadata_dev;
2376 cache->origin_dev = ca->origin_dev;
2377 cache->cache_dev = ca->cache_dev;
2379 ca->metadata_dev = ca->origin_dev = ca->cache_dev = NULL;
2381 /* FIXME: factor out this whole section */
2382 origin_blocks = cache->origin_sectors = ca->origin_sectors;
2383 origin_blocks = block_div(origin_blocks, ca->block_size);
2384 cache->origin_blocks = to_oblock(origin_blocks);
2386 cache->sectors_per_block = ca->block_size;
2387 if (dm_set_target_max_io_len(ti, cache->sectors_per_block)) {
2392 if (ca->block_size & (ca->block_size - 1)) {
2393 dm_block_t cache_size = ca->cache_sectors;
2395 cache->sectors_per_block_shift = -1;
2396 cache_size = block_div(cache_size, ca->block_size);
2397 set_cache_size(cache, to_cblock(cache_size));
2399 cache->sectors_per_block_shift = __ffs(ca->block_size);
2400 set_cache_size(cache, to_cblock(ca->cache_sectors >> cache->sectors_per_block_shift));
2403 r = create_cache_policy(cache, ca, error);
2407 cache->policy_nr_args = ca->policy_argc;
2408 cache->migration_threshold = DEFAULT_MIGRATION_THRESHOLD;
2410 r = set_config_values(cache, ca->policy_argc, ca->policy_argv);
2412 *error = "Error setting cache policy's config values";
2416 cmd = dm_cache_metadata_open(cache->metadata_dev->bdev,
2417 ca->block_size, may_format,
2418 dm_cache_policy_get_hint_size(cache->policy));
2420 *error = "Error creating metadata object";
2426 if (passthrough_mode(&cache->features)) {
2429 r = dm_cache_metadata_all_clean(cache->cmd, &all_clean);
2431 *error = "dm_cache_metadata_all_clean() failed";
2436 *error = "Cannot enter passthrough mode unless all blocks are clean";
2442 spin_lock_init(&cache->lock);
2443 bio_list_init(&cache->deferred_bios);
2444 bio_list_init(&cache->deferred_flush_bios);
2445 bio_list_init(&cache->deferred_writethrough_bios);
2446 INIT_LIST_HEAD(&cache->quiesced_migrations);
2447 INIT_LIST_HEAD(&cache->completed_migrations);
2448 INIT_LIST_HEAD(&cache->need_commit_migrations);
2449 atomic_set(&cache->nr_allocated_migrations, 0);
2450 atomic_set(&cache->nr_io_migrations, 0);
2451 init_waitqueue_head(&cache->migration_wait);
2453 init_waitqueue_head(&cache->quiescing_wait);
2454 atomic_set(&cache->quiescing, 0);
2455 atomic_set(&cache->quiescing_ack, 0);
2458 atomic_set(&cache->nr_dirty, 0);
2459 cache->dirty_bitset = alloc_bitset(from_cblock(cache->cache_size));
2460 if (!cache->dirty_bitset) {
2461 *error = "could not allocate dirty bitset";
2464 clear_bitset(cache->dirty_bitset, from_cblock(cache->cache_size));
2466 cache->discard_block_size =
2467 calculate_discard_block_size(cache->sectors_per_block,
2468 cache->origin_sectors);
2469 cache->discard_nr_blocks = to_dblock(dm_sector_div_up(cache->origin_sectors,
2470 cache->discard_block_size));
2471 cache->discard_bitset = alloc_bitset(from_dblock(cache->discard_nr_blocks));
2472 if (!cache->discard_bitset) {
2473 *error = "could not allocate discard bitset";
2476 clear_bitset(cache->discard_bitset, from_dblock(cache->discard_nr_blocks));
2478 cache->copier = dm_kcopyd_client_create(&dm_kcopyd_throttle);
2479 if (IS_ERR(cache->copier)) {
2480 *error = "could not create kcopyd client";
2481 r = PTR_ERR(cache->copier);
2485 cache->wq = alloc_ordered_workqueue("dm-" DM_MSG_PREFIX, WQ_MEM_RECLAIM);
2487 *error = "could not create workqueue for metadata object";
2490 INIT_WORK(&cache->worker, do_worker);
2491 INIT_DELAYED_WORK(&cache->waker, do_waker);
2492 cache->last_commit_jiffies = jiffies;
2494 cache->prison = dm_bio_prison_create();
2495 if (!cache->prison) {
2496 *error = "could not create bio prison";
2500 cache->all_io_ds = dm_deferred_set_create();
2501 if (!cache->all_io_ds) {
2502 *error = "could not create all_io deferred set";
2506 cache->migration_pool = mempool_create_slab_pool(MIGRATION_POOL_SIZE,
2508 if (!cache->migration_pool) {
2509 *error = "Error creating cache's migration mempool";
2513 cache->need_tick_bio = true;
2514 cache->sized = false;
2515 cache->invalidate = false;
2516 cache->commit_requested = false;
2517 cache->loaded_mappings = false;
2518 cache->loaded_discards = false;
2522 atomic_set(&cache->stats.demotion, 0);
2523 atomic_set(&cache->stats.promotion, 0);
2524 atomic_set(&cache->stats.copies_avoided, 0);
2525 atomic_set(&cache->stats.cache_cell_clash, 0);
2526 atomic_set(&cache->stats.commit_count, 0);
2527 atomic_set(&cache->stats.discard_count, 0);
2529 spin_lock_init(&cache->invalidation_lock);
2530 INIT_LIST_HEAD(&cache->invalidation_requests);
2540 static int copy_ctr_args(struct cache *cache, int argc, const char **argv)
2545 copy = kcalloc(argc, sizeof(*copy), GFP_KERNEL);
2548 for (i = 0; i < argc; i++) {
2549 copy[i] = kstrdup(argv[i], GFP_KERNEL);
2558 cache->nr_ctr_args = argc;
2559 cache->ctr_args = copy;
2564 static int cache_ctr(struct dm_target *ti, unsigned argc, char **argv)
2567 struct cache_args *ca;
2568 struct cache *cache = NULL;
2570 ca = kzalloc(sizeof(*ca), GFP_KERNEL);
2572 ti->error = "Error allocating memory for cache";
2577 r = parse_cache_args(ca, argc, argv, &ti->error);
2581 r = cache_create(ca, &cache);
2585 r = copy_ctr_args(cache, argc - 3, (const char **)argv + 3);
2591 ti->private = cache;
2594 destroy_cache_args(ca);
2598 static int __cache_map(struct cache *cache, struct bio *bio, struct dm_bio_prison_cell **cell)
2601 dm_oblock_t block = get_bio_block(cache, bio);
2602 size_t pb_data_size = get_per_bio_data_size(cache);
2603 bool can_migrate = false;
2604 bool discarded_block;
2605 struct policy_result lookup_result;
2606 struct per_bio_data *pb = init_per_bio_data(bio, pb_data_size);
2607 struct old_oblock_lock ool;
2609 ool.locker.fn = null_locker;
2611 if (unlikely(from_oblock(block) >= from_oblock(cache->origin_blocks))) {
2613 * This can only occur if the io goes to a partial block at
2614 * the end of the origin device. We don't cache these.
2615 * Just remap to the origin and carry on.
2617 remap_to_origin(cache, bio);
2618 return DM_MAPIO_REMAPPED;
2621 if (bio->bi_rw & (REQ_FLUSH | REQ_FUA | REQ_DISCARD)) {
2622 defer_bio(cache, bio);
2623 return DM_MAPIO_SUBMITTED;
2627 * Check to see if that block is currently migrating.
2629 *cell = alloc_prison_cell(cache);
2631 defer_bio(cache, bio);
2632 return DM_MAPIO_SUBMITTED;
2635 r = bio_detain(cache, block, bio, *cell,
2636 (cell_free_fn) free_prison_cell,
2640 defer_bio(cache, bio);
2642 return DM_MAPIO_SUBMITTED;
2645 discarded_block = is_discarded_oblock(cache, block);
2647 r = policy_map(cache->policy, block, false, can_migrate, discarded_block,
2648 bio, &ool.locker, &lookup_result);
2649 if (r == -EWOULDBLOCK) {
2650 cell_defer(cache, *cell, true);
2651 return DM_MAPIO_SUBMITTED;
2654 DMERR_LIMIT("Unexpected return from cache replacement policy: %d", r);
2655 cell_defer(cache, *cell, false);
2657 return DM_MAPIO_SUBMITTED;
2660 r = DM_MAPIO_REMAPPED;
2661 switch (lookup_result.op) {
2663 if (passthrough_mode(&cache->features)) {
2664 if (bio_data_dir(bio) == WRITE) {
2666 * We need to invalidate this block, so
2667 * defer for the worker thread.
2669 cell_defer(cache, *cell, true);
2670 r = DM_MAPIO_SUBMITTED;
2673 inc_miss_counter(cache, bio);
2674 remap_to_origin_clear_discard(cache, bio, block);
2678 inc_hit_counter(cache, bio);
2679 if (bio_data_dir(bio) == WRITE && writethrough_mode(&cache->features) &&
2680 !is_dirty(cache, lookup_result.cblock))
2681 remap_to_origin_then_cache(cache, bio, block, lookup_result.cblock);
2683 remap_to_cache_dirty(cache, bio, block, lookup_result.cblock);
2688 inc_miss_counter(cache, bio);
2689 if (pb->req_nr != 0) {
2691 * This is a duplicate writethrough io that is no
2692 * longer needed because the block has been demoted.
2695 cell_defer(cache, *cell, false);
2696 r = DM_MAPIO_SUBMITTED;
2699 remap_to_origin_clear_discard(cache, bio, block);
2704 DMERR_LIMIT("%s: erroring bio: unknown policy op: %u", __func__,
2705 (unsigned) lookup_result.op);
2706 cell_defer(cache, *cell, false);
2708 r = DM_MAPIO_SUBMITTED;
2714 static int cache_map(struct dm_target *ti, struct bio *bio)
2717 struct dm_bio_prison_cell *cell = NULL;
2718 struct cache *cache = ti->private;
2720 r = __cache_map(cache, bio, &cell);
2721 if (r == DM_MAPIO_REMAPPED && cell) {
2722 inc_ds(cache, bio, cell);
2723 cell_defer(cache, cell, false);
2729 static int cache_end_io(struct dm_target *ti, struct bio *bio, int error)
2731 struct cache *cache = ti->private;
2732 unsigned long flags;
2733 size_t pb_data_size = get_per_bio_data_size(cache);
2734 struct per_bio_data *pb = get_per_bio_data(bio, pb_data_size);
2737 policy_tick(cache->policy);
2739 spin_lock_irqsave(&cache->lock, flags);
2740 cache->need_tick_bio = true;
2741 spin_unlock_irqrestore(&cache->lock, flags);
2744 check_for_quiesced_migrations(cache, pb);
2749 static int write_dirty_bitset(struct cache *cache)
2753 for (i = 0; i < from_cblock(cache->cache_size); i++) {
2754 r = dm_cache_set_dirty(cache->cmd, to_cblock(i),
2755 is_dirty(cache, to_cblock(i)));
2763 static int write_discard_bitset(struct cache *cache)
2767 r = dm_cache_discard_bitset_resize(cache->cmd, cache->discard_block_size,
2768 cache->discard_nr_blocks);
2770 DMERR("could not resize on-disk discard bitset");
2774 for (i = 0; i < from_dblock(cache->discard_nr_blocks); i++) {
2775 r = dm_cache_set_discard(cache->cmd, to_dblock(i),
2776 is_discarded(cache, to_dblock(i)));
2785 * returns true on success
2787 static bool sync_metadata(struct cache *cache)
2791 r1 = write_dirty_bitset(cache);
2793 DMERR("could not write dirty bitset");
2795 r2 = write_discard_bitset(cache);
2797 DMERR("could not write discard bitset");
2801 r3 = dm_cache_write_hints(cache->cmd, cache->policy);
2803 DMERR("could not write hints");
2806 * If writing the above metadata failed, we still commit, but don't
2807 * set the clean shutdown flag. This will effectively force every
2808 * dirty bit to be set on reload.
2810 r4 = dm_cache_commit(cache->cmd, !r1 && !r2 && !r3);
2812 DMERR("could not write cache metadata. Data loss may occur.");
2814 return !r1 && !r2 && !r3 && !r4;
2817 static void cache_postsuspend(struct dm_target *ti)
2819 struct cache *cache = ti->private;
2821 start_quiescing(cache);
2822 wait_for_migrations(cache);
2824 requeue_deferred_io(cache);
2825 stop_quiescing(cache);
2827 (void) sync_metadata(cache);
2830 static int load_mapping(void *context, dm_oblock_t oblock, dm_cblock_t cblock,
2831 bool dirty, uint32_t hint, bool hint_valid)
2834 struct cache *cache = context;
2836 r = policy_load_mapping(cache->policy, oblock, cblock, hint, hint_valid);
2841 set_dirty(cache, oblock, cblock);
2843 clear_dirty(cache, oblock, cblock);
2849 * The discard block size in the on disk metadata is not
2850 * neccessarily the same as we're currently using. So we have to
2851 * be careful to only set the discarded attribute if we know it
2852 * covers a complete block of the new size.
2854 struct discard_load_info {
2855 struct cache *cache;
2858 * These blocks are sized using the on disk dblock size, rather
2859 * than the current one.
2861 dm_block_t block_size;
2862 dm_block_t discard_begin, discard_end;
2865 static void discard_load_info_init(struct cache *cache,
2866 struct discard_load_info *li)
2869 li->discard_begin = li->discard_end = 0;
2872 static void set_discard_range(struct discard_load_info *li)
2876 if (li->discard_begin == li->discard_end)
2880 * Convert to sectors.
2882 b = li->discard_begin * li->block_size;
2883 e = li->discard_end * li->block_size;
2886 * Then convert back to the current dblock size.
2888 b = dm_sector_div_up(b, li->cache->discard_block_size);
2889 sector_div(e, li->cache->discard_block_size);
2892 * The origin may have shrunk, so we need to check we're still in
2895 if (e > from_dblock(li->cache->discard_nr_blocks))
2896 e = from_dblock(li->cache->discard_nr_blocks);
2899 set_discard(li->cache, to_dblock(b));
2902 static int load_discard(void *context, sector_t discard_block_size,
2903 dm_dblock_t dblock, bool discard)
2905 struct discard_load_info *li = context;
2907 li->block_size = discard_block_size;
2910 if (from_dblock(dblock) == li->discard_end)
2912 * We're already in a discard range, just extend it.
2914 li->discard_end = li->discard_end + 1ULL;
2918 * Emit the old range and start a new one.
2920 set_discard_range(li);
2921 li->discard_begin = from_dblock(dblock);
2922 li->discard_end = li->discard_begin + 1ULL;
2925 set_discard_range(li);
2926 li->discard_begin = li->discard_end = 0;
2932 static dm_cblock_t get_cache_dev_size(struct cache *cache)
2934 sector_t size = get_dev_size(cache->cache_dev);
2935 (void) sector_div(size, cache->sectors_per_block);
2936 return to_cblock(size);
2939 static bool can_resize(struct cache *cache, dm_cblock_t new_size)
2941 if (from_cblock(new_size) > from_cblock(cache->cache_size))
2945 * We can't drop a dirty block when shrinking the cache.
2947 while (from_cblock(new_size) < from_cblock(cache->cache_size)) {
2948 new_size = to_cblock(from_cblock(new_size) + 1);
2949 if (is_dirty(cache, new_size)) {
2950 DMERR("unable to shrink cache; cache block %llu is dirty",
2951 (unsigned long long) from_cblock(new_size));
2959 static int resize_cache_dev(struct cache *cache, dm_cblock_t new_size)
2963 r = dm_cache_resize(cache->cmd, new_size);
2965 DMERR("could not resize cache metadata");
2969 set_cache_size(cache, new_size);
2974 static int cache_preresume(struct dm_target *ti)
2977 struct cache *cache = ti->private;
2978 dm_cblock_t csize = get_cache_dev_size(cache);
2981 * Check to see if the cache has resized.
2983 if (!cache->sized) {
2984 r = resize_cache_dev(cache, csize);
2988 cache->sized = true;
2990 } else if (csize != cache->cache_size) {
2991 if (!can_resize(cache, csize))
2994 r = resize_cache_dev(cache, csize);
2999 if (!cache->loaded_mappings) {
3000 r = dm_cache_load_mappings(cache->cmd, cache->policy,
3001 load_mapping, cache);
3003 DMERR("could not load cache mappings");
3007 cache->loaded_mappings = true;
3010 if (!cache->loaded_discards) {
3011 struct discard_load_info li;
3014 * The discard bitset could have been resized, or the
3015 * discard block size changed. To be safe we start by
3016 * setting every dblock to not discarded.
3018 clear_bitset(cache->discard_bitset, from_dblock(cache->discard_nr_blocks));
3020 discard_load_info_init(cache, &li);
3021 r = dm_cache_load_discards(cache->cmd, load_discard, &li);
3023 DMERR("could not load origin discards");
3026 set_discard_range(&li);
3028 cache->loaded_discards = true;
3034 static void cache_resume(struct dm_target *ti)
3036 struct cache *cache = ti->private;
3038 cache->need_tick_bio = true;
3039 do_waker(&cache->waker.work);
3045 * <metadata block size> <#used metadata blocks>/<#total metadata blocks>
3046 * <cache block size> <#used cache blocks>/<#total cache blocks>
3047 * <#read hits> <#read misses> <#write hits> <#write misses>
3048 * <#demotions> <#promotions> <#dirty>
3049 * <#features> <features>*
3050 * <#core args> <core args>
3051 * <policy name> <#policy args> <policy args>*
3053 static void cache_status(struct dm_target *ti, status_type_t type,
3054 unsigned status_flags, char *result, unsigned maxlen)
3059 dm_block_t nr_free_blocks_metadata = 0;
3060 dm_block_t nr_blocks_metadata = 0;
3061 char buf[BDEVNAME_SIZE];
3062 struct cache *cache = ti->private;
3063 dm_cblock_t residency;
3066 case STATUSTYPE_INFO:
3067 /* Commit to ensure statistics aren't out-of-date */
3068 if (!(status_flags & DM_STATUS_NOFLUSH_FLAG) && !dm_suspended(ti)) {
3069 r = dm_cache_commit(cache->cmd, false);
3071 DMERR("could not commit metadata for accurate status");
3074 r = dm_cache_get_free_metadata_block_count(cache->cmd,
3075 &nr_free_blocks_metadata);
3077 DMERR("could not get metadata free block count");
3081 r = dm_cache_get_metadata_dev_size(cache->cmd, &nr_blocks_metadata);
3083 DMERR("could not get metadata device size");
3087 residency = policy_residency(cache->policy);
3089 DMEMIT("%u %llu/%llu %u %llu/%llu %u %u %u %u %u %u %lu ",
3090 (unsigned)DM_CACHE_METADATA_BLOCK_SIZE,
3091 (unsigned long long)(nr_blocks_metadata - nr_free_blocks_metadata),
3092 (unsigned long long)nr_blocks_metadata,
3093 cache->sectors_per_block,
3094 (unsigned long long) from_cblock(residency),
3095 (unsigned long long) from_cblock(cache->cache_size),
3096 (unsigned) atomic_read(&cache->stats.read_hit),
3097 (unsigned) atomic_read(&cache->stats.read_miss),
3098 (unsigned) atomic_read(&cache->stats.write_hit),
3099 (unsigned) atomic_read(&cache->stats.write_miss),
3100 (unsigned) atomic_read(&cache->stats.demotion),
3101 (unsigned) atomic_read(&cache->stats.promotion),
3102 (unsigned long) atomic_read(&cache->nr_dirty));
3104 if (writethrough_mode(&cache->features))
3105 DMEMIT("1 writethrough ");
3107 else if (passthrough_mode(&cache->features))
3108 DMEMIT("1 passthrough ");
3110 else if (writeback_mode(&cache->features))
3111 DMEMIT("1 writeback ");
3114 DMERR("internal error: unknown io mode: %d", (int) cache->features.io_mode);
3118 DMEMIT("2 migration_threshold %llu ", (unsigned long long) cache->migration_threshold);
3120 DMEMIT("%s ", dm_cache_policy_get_name(cache->policy));
3122 r = policy_emit_config_values(cache->policy, result + sz, maxlen - sz);
3124 DMERR("policy_emit_config_values returned %d", r);
3129 case STATUSTYPE_TABLE:
3130 format_dev_t(buf, cache->metadata_dev->bdev->bd_dev);
3132 format_dev_t(buf, cache->cache_dev->bdev->bd_dev);
3134 format_dev_t(buf, cache->origin_dev->bdev->bd_dev);
3137 for (i = 0; i < cache->nr_ctr_args - 1; i++)
3138 DMEMIT(" %s", cache->ctr_args[i]);
3139 if (cache->nr_ctr_args)
3140 DMEMIT(" %s", cache->ctr_args[cache->nr_ctr_args - 1]);
3150 * A cache block range can take two forms:
3152 * i) A single cblock, eg. '3456'
3153 * ii) A begin and end cblock with dots between, eg. 123-234
3155 static int parse_cblock_range(struct cache *cache, const char *str,
3156 struct cblock_range *result)
3163 * Try and parse form (ii) first.
3165 r = sscanf(str, "%llu-%llu%c", &b, &e, &dummy);
3170 result->begin = to_cblock(b);
3171 result->end = to_cblock(e);
3176 * That didn't work, try form (i).
3178 r = sscanf(str, "%llu%c", &b, &dummy);
3183 result->begin = to_cblock(b);
3184 result->end = to_cblock(from_cblock(result->begin) + 1u);
3188 DMERR("invalid cblock range '%s'", str);
3192 static int validate_cblock_range(struct cache *cache, struct cblock_range *range)
3194 uint64_t b = from_cblock(range->begin);
3195 uint64_t e = from_cblock(range->end);
3196 uint64_t n = from_cblock(cache->cache_size);
3199 DMERR("begin cblock out of range: %llu >= %llu", b, n);
3204 DMERR("end cblock out of range: %llu > %llu", e, n);
3209 DMERR("invalid cblock range: %llu >= %llu", b, e);
3216 static int request_invalidation(struct cache *cache, struct cblock_range *range)
3218 struct invalidation_request req;
3220 INIT_LIST_HEAD(&req.list);
3221 req.cblocks = range;
3222 atomic_set(&req.complete, 0);
3224 init_waitqueue_head(&req.result_wait);
3226 spin_lock(&cache->invalidation_lock);
3227 list_add(&req.list, &cache->invalidation_requests);
3228 spin_unlock(&cache->invalidation_lock);
3231 wait_event(req.result_wait, atomic_read(&req.complete));
3235 static int process_invalidate_cblocks_message(struct cache *cache, unsigned count,
3236 const char **cblock_ranges)
3240 struct cblock_range range;
3242 if (!passthrough_mode(&cache->features)) {
3243 DMERR("cache has to be in passthrough mode for invalidation");
3247 for (i = 0; i < count; i++) {
3248 r = parse_cblock_range(cache, cblock_ranges[i], &range);
3252 r = validate_cblock_range(cache, &range);
3257 * Pass begin and end origin blocks to the worker and wake it.
3259 r = request_invalidation(cache, &range);
3271 * "invalidate_cblocks [(<begin>)|(<begin>-<end>)]*
3273 * The key migration_threshold is supported by the cache target core.
3275 static int cache_message(struct dm_target *ti, unsigned argc, char **argv)
3277 struct cache *cache = ti->private;
3282 if (!strcasecmp(argv[0], "invalidate_cblocks"))
3283 return process_invalidate_cblocks_message(cache, argc - 1, (const char **) argv + 1);
3288 return set_config_value(cache, argv[0], argv[1]);
3291 static int cache_iterate_devices(struct dm_target *ti,
3292 iterate_devices_callout_fn fn, void *data)
3295 struct cache *cache = ti->private;
3297 r = fn(ti, cache->cache_dev, 0, get_dev_size(cache->cache_dev), data);
3299 r = fn(ti, cache->origin_dev, 0, ti->len, data);
3305 * We assume I/O is going to the origin (which is the volume
3306 * more likely to have restrictions e.g. by being striped).
3307 * (Looking up the exact location of the data would be expensive
3308 * and could always be out of date by the time the bio is submitted.)
3310 static int cache_bvec_merge(struct dm_target *ti,
3311 struct bvec_merge_data *bvm,
3312 struct bio_vec *biovec, int max_size)
3314 struct cache *cache = ti->private;
3315 struct request_queue *q = bdev_get_queue(cache->origin_dev->bdev);
3317 if (!q->merge_bvec_fn)
3320 bvm->bi_bdev = cache->origin_dev->bdev;
3321 return min(max_size, q->merge_bvec_fn(q, bvm, biovec));
3324 static void set_discard_limits(struct cache *cache, struct queue_limits *limits)
3327 * FIXME: these limits may be incompatible with the cache device
3329 limits->max_discard_sectors = min_t(sector_t, cache->discard_block_size * 1024,
3330 cache->origin_sectors);
3331 limits->discard_granularity = cache->discard_block_size << SECTOR_SHIFT;
3334 static void cache_io_hints(struct dm_target *ti, struct queue_limits *limits)
3336 struct cache *cache = ti->private;
3337 uint64_t io_opt_sectors = limits->io_opt >> SECTOR_SHIFT;
3340 * If the system-determined stacked limits are compatible with the
3341 * cache's blocksize (io_opt is a factor) do not override them.
3343 if (io_opt_sectors < cache->sectors_per_block ||
3344 do_div(io_opt_sectors, cache->sectors_per_block)) {
3345 blk_limits_io_min(limits, cache->sectors_per_block << SECTOR_SHIFT);
3346 blk_limits_io_opt(limits, cache->sectors_per_block << SECTOR_SHIFT);
3348 set_discard_limits(cache, limits);
3351 /*----------------------------------------------------------------*/
3353 static struct target_type cache_target = {
3355 .version = {1, 6, 0},
3356 .module = THIS_MODULE,
3360 .end_io = cache_end_io,
3361 .postsuspend = cache_postsuspend,
3362 .preresume = cache_preresume,
3363 .resume = cache_resume,
3364 .status = cache_status,
3365 .message = cache_message,
3366 .iterate_devices = cache_iterate_devices,
3367 .merge = cache_bvec_merge,
3368 .io_hints = cache_io_hints,
3371 static int __init dm_cache_init(void)
3375 r = dm_register_target(&cache_target);
3377 DMERR("cache target registration failed: %d", r);
3381 migration_cache = KMEM_CACHE(dm_cache_migration, 0);
3382 if (!migration_cache) {
3383 dm_unregister_target(&cache_target);
3390 static void __exit dm_cache_exit(void)
3392 dm_unregister_target(&cache_target);
3393 kmem_cache_destroy(migration_cache);
3396 module_init(dm_cache_init);
3397 module_exit(dm_cache_exit);
3399 MODULE_DESCRIPTION(DM_NAME " cache target");
3400 MODULE_AUTHOR("Joe Thornber <ejt@redhat.com>");
3401 MODULE_LICENSE("GPL");