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