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