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