dm thin: fix deadlock in __requeue_bio_list
[platform/adaptation/renesas_rcar/renesas_kernel.git] / drivers / md / dm-thin.c
1 /*
2  * Copyright (C) 2011-2012 Red Hat UK.
3  *
4  * This file is released under the GPL.
5  */
6
7 #include "dm-thin-metadata.h"
8 #include "dm-bio-prison.h"
9 #include "dm.h"
10
11 #include <linux/device-mapper.h>
12 #include <linux/dm-io.h>
13 #include <linux/dm-kcopyd.h>
14 #include <linux/list.h>
15 #include <linux/init.h>
16 #include <linux/module.h>
17 #include <linux/slab.h>
18
19 #define DM_MSG_PREFIX   "thin"
20
21 /*
22  * Tunable constants
23  */
24 #define ENDIO_HOOK_POOL_SIZE 1024
25 #define MAPPING_POOL_SIZE 1024
26 #define PRISON_CELLS 1024
27 #define COMMIT_PERIOD HZ
28
29 DECLARE_DM_KCOPYD_THROTTLE_WITH_MODULE_PARM(snapshot_copy_throttle,
30                 "A percentage of time allocated for copy on write");
31
32 /*
33  * The block size of the device holding pool data must be
34  * between 64KB and 1GB.
35  */
36 #define DATA_DEV_BLOCK_SIZE_MIN_SECTORS (64 * 1024 >> SECTOR_SHIFT)
37 #define DATA_DEV_BLOCK_SIZE_MAX_SECTORS (1024 * 1024 * 1024 >> SECTOR_SHIFT)
38
39 /*
40  * Device id is restricted to 24 bits.
41  */
42 #define MAX_DEV_ID ((1 << 24) - 1)
43
44 /*
45  * How do we handle breaking sharing of data blocks?
46  * =================================================
47  *
48  * We use a standard copy-on-write btree to store the mappings for the
49  * devices (note I'm talking about copy-on-write of the metadata here, not
50  * the data).  When you take an internal snapshot you clone the root node
51  * of the origin btree.  After this there is no concept of an origin or a
52  * snapshot.  They are just two device trees that happen to point to the
53  * same data blocks.
54  *
55  * When we get a write in we decide if it's to a shared data block using
56  * some timestamp magic.  If it is, we have to break sharing.
57  *
58  * Let's say we write to a shared block in what was the origin.  The
59  * steps are:
60  *
61  * i) plug io further to this physical block. (see bio_prison code).
62  *
63  * ii) quiesce any read io to that shared data block.  Obviously
64  * including all devices that share this block.  (see dm_deferred_set code)
65  *
66  * iii) copy the data block to a newly allocate block.  This step can be
67  * missed out if the io covers the block. (schedule_copy).
68  *
69  * iv) insert the new mapping into the origin's btree
70  * (process_prepared_mapping).  This act of inserting breaks some
71  * sharing of btree nodes between the two devices.  Breaking sharing only
72  * effects the btree of that specific device.  Btrees for the other
73  * devices that share the block never change.  The btree for the origin
74  * device as it was after the last commit is untouched, ie. we're using
75  * persistent data structures in the functional programming sense.
76  *
77  * v) unplug io to this physical block, including the io that triggered
78  * the breaking of sharing.
79  *
80  * Steps (ii) and (iii) occur in parallel.
81  *
82  * The metadata _doesn't_ need to be committed before the io continues.  We
83  * get away with this because the io is always written to a _new_ block.
84  * If there's a crash, then:
85  *
86  * - The origin mapping will point to the old origin block (the shared
87  * one).  This will contain the data as it was before the io that triggered
88  * the breaking of sharing came in.
89  *
90  * - The snap mapping still points to the old block.  As it would after
91  * the commit.
92  *
93  * The downside of this scheme is the timestamp magic isn't perfect, and
94  * will continue to think that data block in the snapshot device is shared
95  * even after the write to the origin has broken sharing.  I suspect data
96  * blocks will typically be shared by many different devices, so we're
97  * breaking sharing n + 1 times, rather than n, where n is the number of
98  * devices that reference this data block.  At the moment I think the
99  * benefits far, far outweigh the disadvantages.
100  */
101
102 /*----------------------------------------------------------------*/
103
104 /*
105  * Key building.
106  */
107 static void build_data_key(struct dm_thin_device *td,
108                            dm_block_t b, struct dm_cell_key *key)
109 {
110         key->virtual = 0;
111         key->dev = dm_thin_dev_id(td);
112         key->block = b;
113 }
114
115 static void build_virtual_key(struct dm_thin_device *td, dm_block_t b,
116                               struct dm_cell_key *key)
117 {
118         key->virtual = 1;
119         key->dev = dm_thin_dev_id(td);
120         key->block = b;
121 }
122
123 /*----------------------------------------------------------------*/
124
125 /*
126  * A pool device ties together a metadata device and a data device.  It
127  * also provides the interface for creating and destroying internal
128  * devices.
129  */
130 struct dm_thin_new_mapping;
131
132 /*
133  * The pool runs in 4 modes.  Ordered in degraded order for comparisons.
134  */
135 enum pool_mode {
136         PM_WRITE,               /* metadata may be changed */
137         PM_OUT_OF_DATA_SPACE,   /* metadata may be changed, though data may not be allocated */
138         PM_READ_ONLY,           /* metadata may not be changed */
139         PM_FAIL,                /* all I/O fails */
140 };
141
142 struct pool_features {
143         enum pool_mode mode;
144
145         bool zero_new_blocks:1;
146         bool discard_enabled:1;
147         bool discard_passdown:1;
148         bool error_if_no_space:1;
149 };
150
151 struct thin_c;
152 typedef void (*process_bio_fn)(struct thin_c *tc, struct bio *bio);
153 typedef void (*process_mapping_fn)(struct dm_thin_new_mapping *m);
154
155 struct pool {
156         struct list_head list;
157         struct dm_target *ti;   /* Only set if a pool target is bound */
158
159         struct mapped_device *pool_md;
160         struct block_device *md_dev;
161         struct dm_pool_metadata *pmd;
162
163         dm_block_t low_water_blocks;
164         uint32_t sectors_per_block;
165         int sectors_per_block_shift;
166
167         struct pool_features pf;
168         bool low_water_triggered:1;     /* A dm event has been sent */
169
170         struct dm_bio_prison *prison;
171         struct dm_kcopyd_client *copier;
172
173         struct workqueue_struct *wq;
174         struct work_struct worker;
175         struct delayed_work waker;
176
177         unsigned long last_commit_jiffies;
178         unsigned ref_count;
179
180         spinlock_t lock;
181         struct bio_list deferred_bios;
182         struct bio_list deferred_flush_bios;
183         struct list_head prepared_mappings;
184         struct list_head prepared_discards;
185
186         struct bio_list retry_on_resume_list;
187
188         struct dm_deferred_set *shared_read_ds;
189         struct dm_deferred_set *all_io_ds;
190
191         struct dm_thin_new_mapping *next_mapping;
192         mempool_t *mapping_pool;
193
194         process_bio_fn process_bio;
195         process_bio_fn process_discard;
196
197         process_mapping_fn process_prepared_mapping;
198         process_mapping_fn process_prepared_discard;
199 };
200
201 static enum pool_mode get_pool_mode(struct pool *pool);
202 static void metadata_operation_failed(struct pool *pool, const char *op, int r);
203
204 /*
205  * Target context for a pool.
206  */
207 struct pool_c {
208         struct dm_target *ti;
209         struct pool *pool;
210         struct dm_dev *data_dev;
211         struct dm_dev *metadata_dev;
212         struct dm_target_callbacks callbacks;
213
214         dm_block_t low_water_blocks;
215         struct pool_features requested_pf; /* Features requested during table load */
216         struct pool_features adjusted_pf;  /* Features used after adjusting for constituent devices */
217 };
218
219 /*
220  * Target context for a thin.
221  */
222 struct thin_c {
223         struct dm_dev *pool_dev;
224         struct dm_dev *origin_dev;
225         dm_thin_id dev_id;
226
227         struct pool *pool;
228         struct dm_thin_device *td;
229 };
230
231 /*----------------------------------------------------------------*/
232
233 /*
234  * wake_worker() is used when new work is queued and when pool_resume is
235  * ready to continue deferred IO processing.
236  */
237 static void wake_worker(struct pool *pool)
238 {
239         queue_work(pool->wq, &pool->worker);
240 }
241
242 /*----------------------------------------------------------------*/
243
244 static int bio_detain(struct pool *pool, struct dm_cell_key *key, struct bio *bio,
245                       struct dm_bio_prison_cell **cell_result)
246 {
247         int r;
248         struct dm_bio_prison_cell *cell_prealloc;
249
250         /*
251          * Allocate a cell from the prison's mempool.
252          * This might block but it can't fail.
253          */
254         cell_prealloc = dm_bio_prison_alloc_cell(pool->prison, GFP_NOIO);
255
256         r = dm_bio_detain(pool->prison, key, bio, cell_prealloc, cell_result);
257         if (r)
258                 /*
259                  * We reused an old cell; we can get rid of
260                  * the new one.
261                  */
262                 dm_bio_prison_free_cell(pool->prison, cell_prealloc);
263
264         return r;
265 }
266
267 static void cell_release(struct pool *pool,
268                          struct dm_bio_prison_cell *cell,
269                          struct bio_list *bios)
270 {
271         dm_cell_release(pool->prison, cell, bios);
272         dm_bio_prison_free_cell(pool->prison, cell);
273 }
274
275 static void cell_release_no_holder(struct pool *pool,
276                                    struct dm_bio_prison_cell *cell,
277                                    struct bio_list *bios)
278 {
279         dm_cell_release_no_holder(pool->prison, cell, bios);
280         dm_bio_prison_free_cell(pool->prison, cell);
281 }
282
283 static void cell_defer_no_holder_no_free(struct thin_c *tc,
284                                          struct dm_bio_prison_cell *cell)
285 {
286         struct pool *pool = tc->pool;
287         unsigned long flags;
288
289         spin_lock_irqsave(&pool->lock, flags);
290         dm_cell_release_no_holder(pool->prison, cell, &pool->deferred_bios);
291         spin_unlock_irqrestore(&pool->lock, flags);
292
293         wake_worker(pool);
294 }
295
296 static void cell_error(struct pool *pool,
297                        struct dm_bio_prison_cell *cell)
298 {
299         dm_cell_error(pool->prison, cell);
300         dm_bio_prison_free_cell(pool->prison, cell);
301 }
302
303 /*----------------------------------------------------------------*/
304
305 /*
306  * A global list of pools that uses a struct mapped_device as a key.
307  */
308 static struct dm_thin_pool_table {
309         struct mutex mutex;
310         struct list_head pools;
311 } dm_thin_pool_table;
312
313 static void pool_table_init(void)
314 {
315         mutex_init(&dm_thin_pool_table.mutex);
316         INIT_LIST_HEAD(&dm_thin_pool_table.pools);
317 }
318
319 static void __pool_table_insert(struct pool *pool)
320 {
321         BUG_ON(!mutex_is_locked(&dm_thin_pool_table.mutex));
322         list_add(&pool->list, &dm_thin_pool_table.pools);
323 }
324
325 static void __pool_table_remove(struct pool *pool)
326 {
327         BUG_ON(!mutex_is_locked(&dm_thin_pool_table.mutex));
328         list_del(&pool->list);
329 }
330
331 static struct pool *__pool_table_lookup(struct mapped_device *md)
332 {
333         struct pool *pool = NULL, *tmp;
334
335         BUG_ON(!mutex_is_locked(&dm_thin_pool_table.mutex));
336
337         list_for_each_entry(tmp, &dm_thin_pool_table.pools, list) {
338                 if (tmp->pool_md == md) {
339                         pool = tmp;
340                         break;
341                 }
342         }
343
344         return pool;
345 }
346
347 static struct pool *__pool_table_lookup_metadata_dev(struct block_device *md_dev)
348 {
349         struct pool *pool = NULL, *tmp;
350
351         BUG_ON(!mutex_is_locked(&dm_thin_pool_table.mutex));
352
353         list_for_each_entry(tmp, &dm_thin_pool_table.pools, list) {
354                 if (tmp->md_dev == md_dev) {
355                         pool = tmp;
356                         break;
357                 }
358         }
359
360         return pool;
361 }
362
363 /*----------------------------------------------------------------*/
364
365 struct dm_thin_endio_hook {
366         struct thin_c *tc;
367         struct dm_deferred_entry *shared_read_entry;
368         struct dm_deferred_entry *all_io_entry;
369         struct dm_thin_new_mapping *overwrite_mapping;
370 };
371
372 static void requeue_bio_list(struct thin_c *tc, struct bio_list *master)
373 {
374         struct bio *bio;
375         struct bio_list bios;
376         unsigned long flags;
377
378         bio_list_init(&bios);
379
380         spin_lock_irqsave(&tc->pool->lock, flags);
381         bio_list_merge(&bios, master);
382         bio_list_init(master);
383         spin_unlock_irqrestore(&tc->pool->lock, flags);
384
385         while ((bio = bio_list_pop(&bios))) {
386                 struct dm_thin_endio_hook *h = dm_per_bio_data(bio, sizeof(struct dm_thin_endio_hook));
387
388                 if (h->tc == tc)
389                         bio_endio(bio, DM_ENDIO_REQUEUE);
390                 else
391                         bio_list_add(master, bio);
392         }
393 }
394
395 static void requeue_io(struct thin_c *tc)
396 {
397         struct pool *pool = tc->pool;
398
399         requeue_bio_list(tc, &pool->deferred_bios);
400         requeue_bio_list(tc, &pool->retry_on_resume_list);
401 }
402
403 static void error_retry_list(struct pool *pool)
404 {
405         struct bio *bio;
406         unsigned long flags;
407         struct bio_list bios;
408
409         bio_list_init(&bios);
410
411         spin_lock_irqsave(&pool->lock, flags);
412         bio_list_merge(&bios, &pool->retry_on_resume_list);
413         bio_list_init(&pool->retry_on_resume_list);
414         spin_unlock_irqrestore(&pool->lock, flags);
415
416         while ((bio = bio_list_pop(&bios)))
417                 bio_io_error(bio);
418 }
419
420 /*
421  * This section of code contains the logic for processing a thin device's IO.
422  * Much of the code depends on pool object resources (lists, workqueues, etc)
423  * but most is exclusively called from the thin target rather than the thin-pool
424  * target.
425  */
426
427 static bool block_size_is_power_of_two(struct pool *pool)
428 {
429         return pool->sectors_per_block_shift >= 0;
430 }
431
432 static dm_block_t get_bio_block(struct thin_c *tc, struct bio *bio)
433 {
434         struct pool *pool = tc->pool;
435         sector_t block_nr = bio->bi_iter.bi_sector;
436
437         if (block_size_is_power_of_two(pool))
438                 block_nr >>= pool->sectors_per_block_shift;
439         else
440                 (void) sector_div(block_nr, pool->sectors_per_block);
441
442         return block_nr;
443 }
444
445 static void remap(struct thin_c *tc, struct bio *bio, dm_block_t block)
446 {
447         struct pool *pool = tc->pool;
448         sector_t bi_sector = bio->bi_iter.bi_sector;
449
450         bio->bi_bdev = tc->pool_dev->bdev;
451         if (block_size_is_power_of_two(pool))
452                 bio->bi_iter.bi_sector =
453                         (block << pool->sectors_per_block_shift) |
454                         (bi_sector & (pool->sectors_per_block - 1));
455         else
456                 bio->bi_iter.bi_sector = (block * pool->sectors_per_block) +
457                                  sector_div(bi_sector, pool->sectors_per_block);
458 }
459
460 static void remap_to_origin(struct thin_c *tc, struct bio *bio)
461 {
462         bio->bi_bdev = tc->origin_dev->bdev;
463 }
464
465 static int bio_triggers_commit(struct thin_c *tc, struct bio *bio)
466 {
467         return (bio->bi_rw & (REQ_FLUSH | REQ_FUA)) &&
468                 dm_thin_changed_this_transaction(tc->td);
469 }
470
471 static void inc_all_io_entry(struct pool *pool, struct bio *bio)
472 {
473         struct dm_thin_endio_hook *h;
474
475         if (bio->bi_rw & REQ_DISCARD)
476                 return;
477
478         h = dm_per_bio_data(bio, sizeof(struct dm_thin_endio_hook));
479         h->all_io_entry = dm_deferred_entry_inc(pool->all_io_ds);
480 }
481
482 static void issue(struct thin_c *tc, struct bio *bio)
483 {
484         struct pool *pool = tc->pool;
485         unsigned long flags;
486
487         if (!bio_triggers_commit(tc, bio)) {
488                 generic_make_request(bio);
489                 return;
490         }
491
492         /*
493          * Complete bio with an error if earlier I/O caused changes to
494          * the metadata that can't be committed e.g, due to I/O errors
495          * on the metadata device.
496          */
497         if (dm_thin_aborted_changes(tc->td)) {
498                 bio_io_error(bio);
499                 return;
500         }
501
502         /*
503          * Batch together any bios that trigger commits and then issue a
504          * single commit for them in process_deferred_bios().
505          */
506         spin_lock_irqsave(&pool->lock, flags);
507         bio_list_add(&pool->deferred_flush_bios, bio);
508         spin_unlock_irqrestore(&pool->lock, flags);
509 }
510
511 static void remap_to_origin_and_issue(struct thin_c *tc, struct bio *bio)
512 {
513         remap_to_origin(tc, bio);
514         issue(tc, bio);
515 }
516
517 static void remap_and_issue(struct thin_c *tc, struct bio *bio,
518                             dm_block_t block)
519 {
520         remap(tc, bio, block);
521         issue(tc, bio);
522 }
523
524 /*----------------------------------------------------------------*/
525
526 /*
527  * Bio endio functions.
528  */
529 struct dm_thin_new_mapping {
530         struct list_head list;
531
532         bool quiesced:1;
533         bool prepared:1;
534         bool pass_discard:1;
535         bool definitely_not_shared:1;
536
537         int err;
538         struct thin_c *tc;
539         dm_block_t virt_block;
540         dm_block_t data_block;
541         struct dm_bio_prison_cell *cell, *cell2;
542
543         /*
544          * If the bio covers the whole area of a block then we can avoid
545          * zeroing or copying.  Instead this bio is hooked.  The bio will
546          * still be in the cell, so care has to be taken to avoid issuing
547          * the bio twice.
548          */
549         struct bio *bio;
550         bio_end_io_t *saved_bi_end_io;
551 };
552
553 static void __maybe_add_mapping(struct dm_thin_new_mapping *m)
554 {
555         struct pool *pool = m->tc->pool;
556
557         if (m->quiesced && m->prepared) {
558                 list_add_tail(&m->list, &pool->prepared_mappings);
559                 wake_worker(pool);
560         }
561 }
562
563 static void copy_complete(int read_err, unsigned long write_err, void *context)
564 {
565         unsigned long flags;
566         struct dm_thin_new_mapping *m = context;
567         struct pool *pool = m->tc->pool;
568
569         m->err = read_err || write_err ? -EIO : 0;
570
571         spin_lock_irqsave(&pool->lock, flags);
572         m->prepared = true;
573         __maybe_add_mapping(m);
574         spin_unlock_irqrestore(&pool->lock, flags);
575 }
576
577 static void overwrite_endio(struct bio *bio, int err)
578 {
579         unsigned long flags;
580         struct dm_thin_endio_hook *h = dm_per_bio_data(bio, sizeof(struct dm_thin_endio_hook));
581         struct dm_thin_new_mapping *m = h->overwrite_mapping;
582         struct pool *pool = m->tc->pool;
583
584         m->err = err;
585
586         spin_lock_irqsave(&pool->lock, flags);
587         m->prepared = true;
588         __maybe_add_mapping(m);
589         spin_unlock_irqrestore(&pool->lock, flags);
590 }
591
592 /*----------------------------------------------------------------*/
593
594 /*
595  * Workqueue.
596  */
597
598 /*
599  * Prepared mapping jobs.
600  */
601
602 /*
603  * This sends the bios in the cell back to the deferred_bios list.
604  */
605 static void cell_defer(struct thin_c *tc, struct dm_bio_prison_cell *cell)
606 {
607         struct pool *pool = tc->pool;
608         unsigned long flags;
609
610         spin_lock_irqsave(&pool->lock, flags);
611         cell_release(pool, cell, &pool->deferred_bios);
612         spin_unlock_irqrestore(&tc->pool->lock, flags);
613
614         wake_worker(pool);
615 }
616
617 /*
618  * Same as cell_defer above, except it omits the original holder of the cell.
619  */
620 static void cell_defer_no_holder(struct thin_c *tc, struct dm_bio_prison_cell *cell)
621 {
622         struct pool *pool = tc->pool;
623         unsigned long flags;
624
625         spin_lock_irqsave(&pool->lock, flags);
626         cell_release_no_holder(pool, cell, &pool->deferred_bios);
627         spin_unlock_irqrestore(&pool->lock, flags);
628
629         wake_worker(pool);
630 }
631
632 static void process_prepared_mapping_fail(struct dm_thin_new_mapping *m)
633 {
634         if (m->bio) {
635                 m->bio->bi_end_io = m->saved_bi_end_io;
636                 atomic_inc(&m->bio->bi_remaining);
637         }
638         cell_error(m->tc->pool, m->cell);
639         list_del(&m->list);
640         mempool_free(m, m->tc->pool->mapping_pool);
641 }
642
643 static void process_prepared_mapping(struct dm_thin_new_mapping *m)
644 {
645         struct thin_c *tc = m->tc;
646         struct pool *pool = tc->pool;
647         struct bio *bio;
648         int r;
649
650         bio = m->bio;
651         if (bio) {
652                 bio->bi_end_io = m->saved_bi_end_io;
653                 atomic_inc(&bio->bi_remaining);
654         }
655
656         if (m->err) {
657                 cell_error(pool, m->cell);
658                 goto out;
659         }
660
661         /*
662          * Commit the prepared block into the mapping btree.
663          * Any I/O for this block arriving after this point will get
664          * remapped to it directly.
665          */
666         r = dm_thin_insert_block(tc->td, m->virt_block, m->data_block);
667         if (r) {
668                 metadata_operation_failed(pool, "dm_thin_insert_block", r);
669                 cell_error(pool, m->cell);
670                 goto out;
671         }
672
673         /*
674          * Release any bios held while the block was being provisioned.
675          * If we are processing a write bio that completely covers the block,
676          * we already processed it so can ignore it now when processing
677          * the bios in the cell.
678          */
679         if (bio) {
680                 cell_defer_no_holder(tc, m->cell);
681                 bio_endio(bio, 0);
682         } else
683                 cell_defer(tc, m->cell);
684
685 out:
686         list_del(&m->list);
687         mempool_free(m, pool->mapping_pool);
688 }
689
690 static void process_prepared_discard_fail(struct dm_thin_new_mapping *m)
691 {
692         struct thin_c *tc = m->tc;
693
694         bio_io_error(m->bio);
695         cell_defer_no_holder(tc, m->cell);
696         cell_defer_no_holder(tc, m->cell2);
697         mempool_free(m, tc->pool->mapping_pool);
698 }
699
700 static void process_prepared_discard_passdown(struct dm_thin_new_mapping *m)
701 {
702         struct thin_c *tc = m->tc;
703
704         inc_all_io_entry(tc->pool, m->bio);
705         cell_defer_no_holder(tc, m->cell);
706         cell_defer_no_holder(tc, m->cell2);
707
708         if (m->pass_discard)
709                 if (m->definitely_not_shared)
710                         remap_and_issue(tc, m->bio, m->data_block);
711                 else {
712                         bool used = false;
713                         if (dm_pool_block_is_used(tc->pool->pmd, m->data_block, &used) || used)
714                                 bio_endio(m->bio, 0);
715                         else
716                                 remap_and_issue(tc, m->bio, m->data_block);
717                 }
718         else
719                 bio_endio(m->bio, 0);
720
721         mempool_free(m, tc->pool->mapping_pool);
722 }
723
724 static void process_prepared_discard(struct dm_thin_new_mapping *m)
725 {
726         int r;
727         struct thin_c *tc = m->tc;
728
729         r = dm_thin_remove_block(tc->td, m->virt_block);
730         if (r)
731                 DMERR_LIMIT("dm_thin_remove_block() failed");
732
733         process_prepared_discard_passdown(m);
734 }
735
736 static void process_prepared(struct pool *pool, struct list_head *head,
737                              process_mapping_fn *fn)
738 {
739         unsigned long flags;
740         struct list_head maps;
741         struct dm_thin_new_mapping *m, *tmp;
742
743         INIT_LIST_HEAD(&maps);
744         spin_lock_irqsave(&pool->lock, flags);
745         list_splice_init(head, &maps);
746         spin_unlock_irqrestore(&pool->lock, flags);
747
748         list_for_each_entry_safe(m, tmp, &maps, list)
749                 (*fn)(m);
750 }
751
752 /*
753  * Deferred bio jobs.
754  */
755 static int io_overlaps_block(struct pool *pool, struct bio *bio)
756 {
757         return bio->bi_iter.bi_size ==
758                 (pool->sectors_per_block << SECTOR_SHIFT);
759 }
760
761 static int io_overwrites_block(struct pool *pool, struct bio *bio)
762 {
763         return (bio_data_dir(bio) == WRITE) &&
764                 io_overlaps_block(pool, bio);
765 }
766
767 static void save_and_set_endio(struct bio *bio, bio_end_io_t **save,
768                                bio_end_io_t *fn)
769 {
770         *save = bio->bi_end_io;
771         bio->bi_end_io = fn;
772 }
773
774 static int ensure_next_mapping(struct pool *pool)
775 {
776         if (pool->next_mapping)
777                 return 0;
778
779         pool->next_mapping = mempool_alloc(pool->mapping_pool, GFP_ATOMIC);
780
781         return pool->next_mapping ? 0 : -ENOMEM;
782 }
783
784 static struct dm_thin_new_mapping *get_next_mapping(struct pool *pool)
785 {
786         struct dm_thin_new_mapping *m = pool->next_mapping;
787
788         BUG_ON(!pool->next_mapping);
789
790         memset(m, 0, sizeof(struct dm_thin_new_mapping));
791         INIT_LIST_HEAD(&m->list);
792         m->bio = NULL;
793
794         pool->next_mapping = NULL;
795
796         return m;
797 }
798
799 static void schedule_copy(struct thin_c *tc, dm_block_t virt_block,
800                           struct dm_dev *origin, dm_block_t data_origin,
801                           dm_block_t data_dest,
802                           struct dm_bio_prison_cell *cell, struct bio *bio)
803 {
804         int r;
805         struct pool *pool = tc->pool;
806         struct dm_thin_new_mapping *m = get_next_mapping(pool);
807
808         m->tc = tc;
809         m->virt_block = virt_block;
810         m->data_block = data_dest;
811         m->cell = cell;
812
813         if (!dm_deferred_set_add_work(pool->shared_read_ds, &m->list))
814                 m->quiesced = true;
815
816         /*
817          * IO to pool_dev remaps to the pool target's data_dev.
818          *
819          * If the whole block of data is being overwritten, we can issue the
820          * bio immediately. Otherwise we use kcopyd to clone the data first.
821          */
822         if (io_overwrites_block(pool, bio)) {
823                 struct dm_thin_endio_hook *h = dm_per_bio_data(bio, sizeof(struct dm_thin_endio_hook));
824
825                 h->overwrite_mapping = m;
826                 m->bio = bio;
827                 save_and_set_endio(bio, &m->saved_bi_end_io, overwrite_endio);
828                 inc_all_io_entry(pool, bio);
829                 remap_and_issue(tc, bio, data_dest);
830         } else {
831                 struct dm_io_region from, to;
832
833                 from.bdev = origin->bdev;
834                 from.sector = data_origin * pool->sectors_per_block;
835                 from.count = pool->sectors_per_block;
836
837                 to.bdev = tc->pool_dev->bdev;
838                 to.sector = data_dest * pool->sectors_per_block;
839                 to.count = pool->sectors_per_block;
840
841                 r = dm_kcopyd_copy(pool->copier, &from, 1, &to,
842                                    0, copy_complete, m);
843                 if (r < 0) {
844                         mempool_free(m, pool->mapping_pool);
845                         DMERR_LIMIT("dm_kcopyd_copy() failed");
846                         cell_error(pool, cell);
847                 }
848         }
849 }
850
851 static void schedule_internal_copy(struct thin_c *tc, dm_block_t virt_block,
852                                    dm_block_t data_origin, dm_block_t data_dest,
853                                    struct dm_bio_prison_cell *cell, struct bio *bio)
854 {
855         schedule_copy(tc, virt_block, tc->pool_dev,
856                       data_origin, data_dest, cell, bio);
857 }
858
859 static void schedule_external_copy(struct thin_c *tc, dm_block_t virt_block,
860                                    dm_block_t data_dest,
861                                    struct dm_bio_prison_cell *cell, struct bio *bio)
862 {
863         schedule_copy(tc, virt_block, tc->origin_dev,
864                       virt_block, data_dest, cell, bio);
865 }
866
867 static void schedule_zero(struct thin_c *tc, dm_block_t virt_block,
868                           dm_block_t data_block, struct dm_bio_prison_cell *cell,
869                           struct bio *bio)
870 {
871         struct pool *pool = tc->pool;
872         struct dm_thin_new_mapping *m = get_next_mapping(pool);
873
874         m->quiesced = true;
875         m->prepared = false;
876         m->tc = tc;
877         m->virt_block = virt_block;
878         m->data_block = data_block;
879         m->cell = cell;
880
881         /*
882          * If the whole block of data is being overwritten or we are not
883          * zeroing pre-existing data, we can issue the bio immediately.
884          * Otherwise we use kcopyd to zero the data first.
885          */
886         if (!pool->pf.zero_new_blocks)
887                 process_prepared_mapping(m);
888
889         else if (io_overwrites_block(pool, bio)) {
890                 struct dm_thin_endio_hook *h = dm_per_bio_data(bio, sizeof(struct dm_thin_endio_hook));
891
892                 h->overwrite_mapping = m;
893                 m->bio = bio;
894                 save_and_set_endio(bio, &m->saved_bi_end_io, overwrite_endio);
895                 inc_all_io_entry(pool, bio);
896                 remap_and_issue(tc, bio, data_block);
897         } else {
898                 int r;
899                 struct dm_io_region to;
900
901                 to.bdev = tc->pool_dev->bdev;
902                 to.sector = data_block * pool->sectors_per_block;
903                 to.count = pool->sectors_per_block;
904
905                 r = dm_kcopyd_zero(pool->copier, 1, &to, 0, copy_complete, m);
906                 if (r < 0) {
907                         mempool_free(m, pool->mapping_pool);
908                         DMERR_LIMIT("dm_kcopyd_zero() failed");
909                         cell_error(pool, cell);
910                 }
911         }
912 }
913
914 /*
915  * A non-zero return indicates read_only or fail_io mode.
916  * Many callers don't care about the return value.
917  */
918 static int commit(struct pool *pool)
919 {
920         int r;
921
922         if (get_pool_mode(pool) != PM_WRITE)
923                 return -EINVAL;
924
925         r = dm_pool_commit_metadata(pool->pmd);
926         if (r)
927                 metadata_operation_failed(pool, "dm_pool_commit_metadata", r);
928
929         return r;
930 }
931
932 static void check_low_water_mark(struct pool *pool, dm_block_t free_blocks)
933 {
934         unsigned long flags;
935
936         if (free_blocks <= pool->low_water_blocks && !pool->low_water_triggered) {
937                 DMWARN("%s: reached low water mark for data device: sending event.",
938                        dm_device_name(pool->pool_md));
939                 spin_lock_irqsave(&pool->lock, flags);
940                 pool->low_water_triggered = true;
941                 spin_unlock_irqrestore(&pool->lock, flags);
942                 dm_table_event(pool->ti->table);
943         }
944 }
945
946 static void set_pool_mode(struct pool *pool, enum pool_mode new_mode);
947
948 static int alloc_data_block(struct thin_c *tc, dm_block_t *result)
949 {
950         int r;
951         dm_block_t free_blocks;
952         struct pool *pool = tc->pool;
953
954         if (WARN_ON(get_pool_mode(pool) != PM_WRITE))
955                 return -EINVAL;
956
957         r = dm_pool_get_free_block_count(pool->pmd, &free_blocks);
958         if (r) {
959                 metadata_operation_failed(pool, "dm_pool_get_free_block_count", r);
960                 return r;
961         }
962
963         check_low_water_mark(pool, free_blocks);
964
965         if (!free_blocks) {
966                 /*
967                  * Try to commit to see if that will free up some
968                  * more space.
969                  */
970                 r = commit(pool);
971                 if (r)
972                         return r;
973
974                 r = dm_pool_get_free_block_count(pool->pmd, &free_blocks);
975                 if (r) {
976                         metadata_operation_failed(pool, "dm_pool_get_free_block_count", r);
977                         return r;
978                 }
979
980                 if (!free_blocks) {
981                         set_pool_mode(pool, PM_OUT_OF_DATA_SPACE);
982                         return -ENOSPC;
983                 }
984         }
985
986         r = dm_pool_alloc_data_block(pool->pmd, result);
987         if (r) {
988                 metadata_operation_failed(pool, "dm_pool_alloc_data_block", r);
989                 return r;
990         }
991
992         return 0;
993 }
994
995 /*
996  * If we have run out of space, queue bios until the device is
997  * resumed, presumably after having been reloaded with more space.
998  */
999 static void retry_on_resume(struct bio *bio)
1000 {
1001         struct dm_thin_endio_hook *h = dm_per_bio_data(bio, sizeof(struct dm_thin_endio_hook));
1002         struct thin_c *tc = h->tc;
1003         struct pool *pool = tc->pool;
1004         unsigned long flags;
1005
1006         spin_lock_irqsave(&pool->lock, flags);
1007         bio_list_add(&pool->retry_on_resume_list, bio);
1008         spin_unlock_irqrestore(&pool->lock, flags);
1009 }
1010
1011 static bool should_error_unserviceable_bio(struct pool *pool)
1012 {
1013         enum pool_mode m = get_pool_mode(pool);
1014
1015         switch (m) {
1016         case PM_WRITE:
1017                 /* Shouldn't get here */
1018                 DMERR_LIMIT("bio unserviceable, yet pool is in PM_WRITE mode");
1019                 return true;
1020
1021         case PM_OUT_OF_DATA_SPACE:
1022                 return pool->pf.error_if_no_space;
1023
1024         case PM_READ_ONLY:
1025         case PM_FAIL:
1026                 return true;
1027         default:
1028                 /* Shouldn't get here */
1029                 DMERR_LIMIT("bio unserviceable, yet pool has an unknown mode");
1030                 return true;
1031         }
1032 }
1033
1034 static void handle_unserviceable_bio(struct pool *pool, struct bio *bio)
1035 {
1036         if (should_error_unserviceable_bio(pool))
1037                 bio_io_error(bio);
1038         else
1039                 retry_on_resume(bio);
1040 }
1041
1042 static void retry_bios_on_resume(struct pool *pool, struct dm_bio_prison_cell *cell)
1043 {
1044         struct bio *bio;
1045         struct bio_list bios;
1046
1047         if (should_error_unserviceable_bio(pool)) {
1048                 cell_error(pool, cell);
1049                 return;
1050         }
1051
1052         bio_list_init(&bios);
1053         cell_release(pool, cell, &bios);
1054
1055         if (should_error_unserviceable_bio(pool))
1056                 while ((bio = bio_list_pop(&bios)))
1057                         bio_io_error(bio);
1058         else
1059                 while ((bio = bio_list_pop(&bios)))
1060                         retry_on_resume(bio);
1061 }
1062
1063 static void process_discard(struct thin_c *tc, struct bio *bio)
1064 {
1065         int r;
1066         unsigned long flags;
1067         struct pool *pool = tc->pool;
1068         struct dm_bio_prison_cell *cell, *cell2;
1069         struct dm_cell_key key, key2;
1070         dm_block_t block = get_bio_block(tc, bio);
1071         struct dm_thin_lookup_result lookup_result;
1072         struct dm_thin_new_mapping *m;
1073
1074         build_virtual_key(tc->td, block, &key);
1075         if (bio_detain(tc->pool, &key, bio, &cell))
1076                 return;
1077
1078         r = dm_thin_find_block(tc->td, block, 1, &lookup_result);
1079         switch (r) {
1080         case 0:
1081                 /*
1082                  * Check nobody is fiddling with this pool block.  This can
1083                  * happen if someone's in the process of breaking sharing
1084                  * on this block.
1085                  */
1086                 build_data_key(tc->td, lookup_result.block, &key2);
1087                 if (bio_detain(tc->pool, &key2, bio, &cell2)) {
1088                         cell_defer_no_holder(tc, cell);
1089                         break;
1090                 }
1091
1092                 if (io_overlaps_block(pool, bio)) {
1093                         /*
1094                          * IO may still be going to the destination block.  We must
1095                          * quiesce before we can do the removal.
1096                          */
1097                         m = get_next_mapping(pool);
1098                         m->tc = tc;
1099                         m->pass_discard = pool->pf.discard_passdown;
1100                         m->definitely_not_shared = !lookup_result.shared;
1101                         m->virt_block = block;
1102                         m->data_block = lookup_result.block;
1103                         m->cell = cell;
1104                         m->cell2 = cell2;
1105                         m->bio = bio;
1106
1107                         if (!dm_deferred_set_add_work(pool->all_io_ds, &m->list)) {
1108                                 spin_lock_irqsave(&pool->lock, flags);
1109                                 list_add_tail(&m->list, &pool->prepared_discards);
1110                                 spin_unlock_irqrestore(&pool->lock, flags);
1111                                 wake_worker(pool);
1112                         }
1113                 } else {
1114                         inc_all_io_entry(pool, bio);
1115                         cell_defer_no_holder(tc, cell);
1116                         cell_defer_no_holder(tc, cell2);
1117
1118                         /*
1119                          * The DM core makes sure that the discard doesn't span
1120                          * a block boundary.  So we submit the discard of a
1121                          * partial block appropriately.
1122                          */
1123                         if ((!lookup_result.shared) && pool->pf.discard_passdown)
1124                                 remap_and_issue(tc, bio, lookup_result.block);
1125                         else
1126                                 bio_endio(bio, 0);
1127                 }
1128                 break;
1129
1130         case -ENODATA:
1131                 /*
1132                  * It isn't provisioned, just forget it.
1133                  */
1134                 cell_defer_no_holder(tc, cell);
1135                 bio_endio(bio, 0);
1136                 break;
1137
1138         default:
1139                 DMERR_LIMIT("%s: dm_thin_find_block() failed: error = %d",
1140                             __func__, r);
1141                 cell_defer_no_holder(tc, cell);
1142                 bio_io_error(bio);
1143                 break;
1144         }
1145 }
1146
1147 static void break_sharing(struct thin_c *tc, struct bio *bio, dm_block_t block,
1148                           struct dm_cell_key *key,
1149                           struct dm_thin_lookup_result *lookup_result,
1150                           struct dm_bio_prison_cell *cell)
1151 {
1152         int r;
1153         dm_block_t data_block;
1154         struct pool *pool = tc->pool;
1155
1156         r = alloc_data_block(tc, &data_block);
1157         switch (r) {
1158         case 0:
1159                 schedule_internal_copy(tc, block, lookup_result->block,
1160                                        data_block, cell, bio);
1161                 break;
1162
1163         case -ENOSPC:
1164                 retry_bios_on_resume(pool, cell);
1165                 break;
1166
1167         default:
1168                 DMERR_LIMIT("%s: alloc_data_block() failed: error = %d",
1169                             __func__, r);
1170                 cell_error(pool, cell);
1171                 break;
1172         }
1173 }
1174
1175 static void process_shared_bio(struct thin_c *tc, struct bio *bio,
1176                                dm_block_t block,
1177                                struct dm_thin_lookup_result *lookup_result)
1178 {
1179         struct dm_bio_prison_cell *cell;
1180         struct pool *pool = tc->pool;
1181         struct dm_cell_key key;
1182
1183         /*
1184          * If cell is already occupied, then sharing is already in the process
1185          * of being broken so we have nothing further to do here.
1186          */
1187         build_data_key(tc->td, lookup_result->block, &key);
1188         if (bio_detain(pool, &key, bio, &cell))
1189                 return;
1190
1191         if (bio_data_dir(bio) == WRITE && bio->bi_iter.bi_size)
1192                 break_sharing(tc, bio, block, &key, lookup_result, cell);
1193         else {
1194                 struct dm_thin_endio_hook *h = dm_per_bio_data(bio, sizeof(struct dm_thin_endio_hook));
1195
1196                 h->shared_read_entry = dm_deferred_entry_inc(pool->shared_read_ds);
1197                 inc_all_io_entry(pool, bio);
1198                 cell_defer_no_holder(tc, cell);
1199
1200                 remap_and_issue(tc, bio, lookup_result->block);
1201         }
1202 }
1203
1204 static void provision_block(struct thin_c *tc, struct bio *bio, dm_block_t block,
1205                             struct dm_bio_prison_cell *cell)
1206 {
1207         int r;
1208         dm_block_t data_block;
1209         struct pool *pool = tc->pool;
1210
1211         /*
1212          * Remap empty bios (flushes) immediately, without provisioning.
1213          */
1214         if (!bio->bi_iter.bi_size) {
1215                 inc_all_io_entry(pool, bio);
1216                 cell_defer_no_holder(tc, cell);
1217
1218                 remap_and_issue(tc, bio, 0);
1219                 return;
1220         }
1221
1222         /*
1223          * Fill read bios with zeroes and complete them immediately.
1224          */
1225         if (bio_data_dir(bio) == READ) {
1226                 zero_fill_bio(bio);
1227                 cell_defer_no_holder(tc, cell);
1228                 bio_endio(bio, 0);
1229                 return;
1230         }
1231
1232         r = alloc_data_block(tc, &data_block);
1233         switch (r) {
1234         case 0:
1235                 if (tc->origin_dev)
1236                         schedule_external_copy(tc, block, data_block, cell, bio);
1237                 else
1238                         schedule_zero(tc, block, data_block, cell, bio);
1239                 break;
1240
1241         case -ENOSPC:
1242                 retry_bios_on_resume(pool, cell);
1243                 break;
1244
1245         default:
1246                 DMERR_LIMIT("%s: alloc_data_block() failed: error = %d",
1247                             __func__, r);
1248                 cell_error(pool, cell);
1249                 break;
1250         }
1251 }
1252
1253 static void process_bio(struct thin_c *tc, struct bio *bio)
1254 {
1255         int r;
1256         struct pool *pool = tc->pool;
1257         dm_block_t block = get_bio_block(tc, bio);
1258         struct dm_bio_prison_cell *cell;
1259         struct dm_cell_key key;
1260         struct dm_thin_lookup_result lookup_result;
1261
1262         /*
1263          * If cell is already occupied, then the block is already
1264          * being provisioned so we have nothing further to do here.
1265          */
1266         build_virtual_key(tc->td, block, &key);
1267         if (bio_detain(pool, &key, bio, &cell))
1268                 return;
1269
1270         r = dm_thin_find_block(tc->td, block, 1, &lookup_result);
1271         switch (r) {
1272         case 0:
1273                 if (lookup_result.shared) {
1274                         process_shared_bio(tc, bio, block, &lookup_result);
1275                         cell_defer_no_holder(tc, cell); /* FIXME: pass this cell into process_shared? */
1276                 } else {
1277                         inc_all_io_entry(pool, bio);
1278                         cell_defer_no_holder(tc, cell);
1279
1280                         remap_and_issue(tc, bio, lookup_result.block);
1281                 }
1282                 break;
1283
1284         case -ENODATA:
1285                 if (bio_data_dir(bio) == READ && tc->origin_dev) {
1286                         inc_all_io_entry(pool, bio);
1287                         cell_defer_no_holder(tc, cell);
1288
1289                         remap_to_origin_and_issue(tc, bio);
1290                 } else
1291                         provision_block(tc, bio, block, cell);
1292                 break;
1293
1294         default:
1295                 DMERR_LIMIT("%s: dm_thin_find_block() failed: error = %d",
1296                             __func__, r);
1297                 cell_defer_no_holder(tc, cell);
1298                 bio_io_error(bio);
1299                 break;
1300         }
1301 }
1302
1303 static void process_bio_read_only(struct thin_c *tc, struct bio *bio)
1304 {
1305         int r;
1306         int rw = bio_data_dir(bio);
1307         dm_block_t block = get_bio_block(tc, bio);
1308         struct dm_thin_lookup_result lookup_result;
1309
1310         r = dm_thin_find_block(tc->td, block, 1, &lookup_result);
1311         switch (r) {
1312         case 0:
1313                 if (lookup_result.shared && (rw == WRITE) && bio->bi_iter.bi_size)
1314                         handle_unserviceable_bio(tc->pool, bio);
1315                 else {
1316                         inc_all_io_entry(tc->pool, bio);
1317                         remap_and_issue(tc, bio, lookup_result.block);
1318                 }
1319                 break;
1320
1321         case -ENODATA:
1322                 if (rw != READ) {
1323                         handle_unserviceable_bio(tc->pool, bio);
1324                         break;
1325                 }
1326
1327                 if (tc->origin_dev) {
1328                         inc_all_io_entry(tc->pool, bio);
1329                         remap_to_origin_and_issue(tc, bio);
1330                         break;
1331                 }
1332
1333                 zero_fill_bio(bio);
1334                 bio_endio(bio, 0);
1335                 break;
1336
1337         default:
1338                 DMERR_LIMIT("%s: dm_thin_find_block() failed: error = %d",
1339                             __func__, r);
1340                 bio_io_error(bio);
1341                 break;
1342         }
1343 }
1344
1345 static void process_bio_success(struct thin_c *tc, struct bio *bio)
1346 {
1347         bio_endio(bio, 0);
1348 }
1349
1350 static void process_bio_fail(struct thin_c *tc, struct bio *bio)
1351 {
1352         bio_io_error(bio);
1353 }
1354
1355 /*
1356  * FIXME: should we also commit due to size of transaction, measured in
1357  * metadata blocks?
1358  */
1359 static int need_commit_due_to_time(struct pool *pool)
1360 {
1361         return jiffies < pool->last_commit_jiffies ||
1362                jiffies > pool->last_commit_jiffies + COMMIT_PERIOD;
1363 }
1364
1365 static void process_deferred_bios(struct pool *pool)
1366 {
1367         unsigned long flags;
1368         struct bio *bio;
1369         struct bio_list bios;
1370
1371         bio_list_init(&bios);
1372
1373         spin_lock_irqsave(&pool->lock, flags);
1374         bio_list_merge(&bios, &pool->deferred_bios);
1375         bio_list_init(&pool->deferred_bios);
1376         spin_unlock_irqrestore(&pool->lock, flags);
1377
1378         while ((bio = bio_list_pop(&bios))) {
1379                 struct dm_thin_endio_hook *h = dm_per_bio_data(bio, sizeof(struct dm_thin_endio_hook));
1380                 struct thin_c *tc = h->tc;
1381
1382                 /*
1383                  * If we've got no free new_mapping structs, and processing
1384                  * this bio might require one, we pause until there are some
1385                  * prepared mappings to process.
1386                  */
1387                 if (ensure_next_mapping(pool)) {
1388                         spin_lock_irqsave(&pool->lock, flags);
1389                         bio_list_merge(&pool->deferred_bios, &bios);
1390                         spin_unlock_irqrestore(&pool->lock, flags);
1391
1392                         break;
1393                 }
1394
1395                 if (bio->bi_rw & REQ_DISCARD)
1396                         pool->process_discard(tc, bio);
1397                 else
1398                         pool->process_bio(tc, bio);
1399         }
1400
1401         /*
1402          * If there are any deferred flush bios, we must commit
1403          * the metadata before issuing them.
1404          */
1405         bio_list_init(&bios);
1406         spin_lock_irqsave(&pool->lock, flags);
1407         bio_list_merge(&bios, &pool->deferred_flush_bios);
1408         bio_list_init(&pool->deferred_flush_bios);
1409         spin_unlock_irqrestore(&pool->lock, flags);
1410
1411         if (bio_list_empty(&bios) &&
1412             !(dm_pool_changed_this_transaction(pool->pmd) && need_commit_due_to_time(pool)))
1413                 return;
1414
1415         if (commit(pool)) {
1416                 while ((bio = bio_list_pop(&bios)))
1417                         bio_io_error(bio);
1418                 return;
1419         }
1420         pool->last_commit_jiffies = jiffies;
1421
1422         while ((bio = bio_list_pop(&bios)))
1423                 generic_make_request(bio);
1424 }
1425
1426 static void do_worker(struct work_struct *ws)
1427 {
1428         struct pool *pool = container_of(ws, struct pool, worker);
1429
1430         process_prepared(pool, &pool->prepared_mappings, &pool->process_prepared_mapping);
1431         process_prepared(pool, &pool->prepared_discards, &pool->process_prepared_discard);
1432         process_deferred_bios(pool);
1433 }
1434
1435 /*
1436  * We want to commit periodically so that not too much
1437  * unwritten data builds up.
1438  */
1439 static void do_waker(struct work_struct *ws)
1440 {
1441         struct pool *pool = container_of(to_delayed_work(ws), struct pool, waker);
1442         wake_worker(pool);
1443         queue_delayed_work(pool->wq, &pool->waker, COMMIT_PERIOD);
1444 }
1445
1446 /*----------------------------------------------------------------*/
1447
1448 static enum pool_mode get_pool_mode(struct pool *pool)
1449 {
1450         return pool->pf.mode;
1451 }
1452
1453 static void notify_of_pool_mode_change(struct pool *pool, const char *new_mode)
1454 {
1455         dm_table_event(pool->ti->table);
1456         DMINFO("%s: switching pool to %s mode",
1457                dm_device_name(pool->pool_md), new_mode);
1458 }
1459
1460 static void set_pool_mode(struct pool *pool, enum pool_mode new_mode)
1461 {
1462         struct pool_c *pt = pool->ti->private;
1463         bool needs_check = dm_pool_metadata_needs_check(pool->pmd);
1464         enum pool_mode old_mode = get_pool_mode(pool);
1465
1466         /*
1467          * Never allow the pool to transition to PM_WRITE mode if user
1468          * intervention is required to verify metadata and data consistency.
1469          */
1470         if (new_mode == PM_WRITE && needs_check) {
1471                 DMERR("%s: unable to switch pool to write mode until repaired.",
1472                       dm_device_name(pool->pool_md));
1473                 if (old_mode != new_mode)
1474                         new_mode = old_mode;
1475                 else
1476                         new_mode = PM_READ_ONLY;
1477         }
1478         /*
1479          * If we were in PM_FAIL mode, rollback of metadata failed.  We're
1480          * not going to recover without a thin_repair.  So we never let the
1481          * pool move out of the old mode.
1482          */
1483         if (old_mode == PM_FAIL)
1484                 new_mode = old_mode;
1485
1486         switch (new_mode) {
1487         case PM_FAIL:
1488                 if (old_mode != new_mode)
1489                         notify_of_pool_mode_change(pool, "failure");
1490                 dm_pool_metadata_read_only(pool->pmd);
1491                 pool->process_bio = process_bio_fail;
1492                 pool->process_discard = process_bio_fail;
1493                 pool->process_prepared_mapping = process_prepared_mapping_fail;
1494                 pool->process_prepared_discard = process_prepared_discard_fail;
1495
1496                 error_retry_list(pool);
1497                 break;
1498
1499         case PM_READ_ONLY:
1500                 if (old_mode != new_mode)
1501                         notify_of_pool_mode_change(pool, "read-only");
1502                 dm_pool_metadata_read_only(pool->pmd);
1503                 pool->process_bio = process_bio_read_only;
1504                 pool->process_discard = process_bio_success;
1505                 pool->process_prepared_mapping = process_prepared_mapping_fail;
1506                 pool->process_prepared_discard = process_prepared_discard_passdown;
1507
1508                 error_retry_list(pool);
1509                 break;
1510
1511         case PM_OUT_OF_DATA_SPACE:
1512                 /*
1513                  * Ideally we'd never hit this state; the low water mark
1514                  * would trigger userland to extend the pool before we
1515                  * completely run out of data space.  However, many small
1516                  * IOs to unprovisioned space can consume data space at an
1517                  * alarming rate.  Adjust your low water mark if you're
1518                  * frequently seeing this mode.
1519                  */
1520                 if (old_mode != new_mode)
1521                         notify_of_pool_mode_change(pool, "out-of-data-space");
1522                 pool->process_bio = process_bio_read_only;
1523                 pool->process_discard = process_discard;
1524                 pool->process_prepared_mapping = process_prepared_mapping;
1525                 pool->process_prepared_discard = process_prepared_discard_passdown;
1526                 break;
1527
1528         case PM_WRITE:
1529                 if (old_mode != new_mode)
1530                         notify_of_pool_mode_change(pool, "write");
1531                 dm_pool_metadata_read_write(pool->pmd);
1532                 pool->process_bio = process_bio;
1533                 pool->process_discard = process_discard;
1534                 pool->process_prepared_mapping = process_prepared_mapping;
1535                 pool->process_prepared_discard = process_prepared_discard;
1536                 break;
1537         }
1538
1539         pool->pf.mode = new_mode;
1540         /*
1541          * The pool mode may have changed, sync it so bind_control_target()
1542          * doesn't cause an unexpected mode transition on resume.
1543          */
1544         pt->adjusted_pf.mode = new_mode;
1545 }
1546
1547 static void abort_transaction(struct pool *pool)
1548 {
1549         const char *dev_name = dm_device_name(pool->pool_md);
1550
1551         DMERR_LIMIT("%s: aborting current metadata transaction", dev_name);
1552         if (dm_pool_abort_metadata(pool->pmd)) {
1553                 DMERR("%s: failed to abort metadata transaction", dev_name);
1554                 set_pool_mode(pool, PM_FAIL);
1555         }
1556
1557         if (dm_pool_metadata_set_needs_check(pool->pmd)) {
1558                 DMERR("%s: failed to set 'needs_check' flag in metadata", dev_name);
1559                 set_pool_mode(pool, PM_FAIL);
1560         }
1561 }
1562
1563 static void metadata_operation_failed(struct pool *pool, const char *op, int r)
1564 {
1565         DMERR_LIMIT("%s: metadata operation '%s' failed: error = %d",
1566                     dm_device_name(pool->pool_md), op, r);
1567
1568         abort_transaction(pool);
1569         set_pool_mode(pool, PM_READ_ONLY);
1570 }
1571
1572 /*----------------------------------------------------------------*/
1573
1574 /*
1575  * Mapping functions.
1576  */
1577
1578 /*
1579  * Called only while mapping a thin bio to hand it over to the workqueue.
1580  */
1581 static void thin_defer_bio(struct thin_c *tc, struct bio *bio)
1582 {
1583         unsigned long flags;
1584         struct pool *pool = tc->pool;
1585
1586         spin_lock_irqsave(&pool->lock, flags);
1587         bio_list_add(&pool->deferred_bios, bio);
1588         spin_unlock_irqrestore(&pool->lock, flags);
1589
1590         wake_worker(pool);
1591 }
1592
1593 static void thin_hook_bio(struct thin_c *tc, struct bio *bio)
1594 {
1595         struct dm_thin_endio_hook *h = dm_per_bio_data(bio, sizeof(struct dm_thin_endio_hook));
1596
1597         h->tc = tc;
1598         h->shared_read_entry = NULL;
1599         h->all_io_entry = NULL;
1600         h->overwrite_mapping = NULL;
1601 }
1602
1603 /*
1604  * Non-blocking function called from the thin target's map function.
1605  */
1606 static int thin_bio_map(struct dm_target *ti, struct bio *bio)
1607 {
1608         int r;
1609         struct thin_c *tc = ti->private;
1610         dm_block_t block = get_bio_block(tc, bio);
1611         struct dm_thin_device *td = tc->td;
1612         struct dm_thin_lookup_result result;
1613         struct dm_bio_prison_cell cell1, cell2;
1614         struct dm_bio_prison_cell *cell_result;
1615         struct dm_cell_key key;
1616
1617         thin_hook_bio(tc, bio);
1618
1619         if (get_pool_mode(tc->pool) == PM_FAIL) {
1620                 bio_io_error(bio);
1621                 return DM_MAPIO_SUBMITTED;
1622         }
1623
1624         if (bio->bi_rw & (REQ_DISCARD | REQ_FLUSH | REQ_FUA)) {
1625                 thin_defer_bio(tc, bio);
1626                 return DM_MAPIO_SUBMITTED;
1627         }
1628
1629         r = dm_thin_find_block(td, block, 0, &result);
1630
1631         /*
1632          * Note that we defer readahead too.
1633          */
1634         switch (r) {
1635         case 0:
1636                 if (unlikely(result.shared)) {
1637                         /*
1638                          * We have a race condition here between the
1639                          * result.shared value returned by the lookup and
1640                          * snapshot creation, which may cause new
1641                          * sharing.
1642                          *
1643                          * To avoid this always quiesce the origin before
1644                          * taking the snap.  You want to do this anyway to
1645                          * ensure a consistent application view
1646                          * (i.e. lockfs).
1647                          *
1648                          * More distant ancestors are irrelevant. The
1649                          * shared flag will be set in their case.
1650                          */
1651                         thin_defer_bio(tc, bio);
1652                         return DM_MAPIO_SUBMITTED;
1653                 }
1654
1655                 build_virtual_key(tc->td, block, &key);
1656                 if (dm_bio_detain(tc->pool->prison, &key, bio, &cell1, &cell_result))
1657                         return DM_MAPIO_SUBMITTED;
1658
1659                 build_data_key(tc->td, result.block, &key);
1660                 if (dm_bio_detain(tc->pool->prison, &key, bio, &cell2, &cell_result)) {
1661                         cell_defer_no_holder_no_free(tc, &cell1);
1662                         return DM_MAPIO_SUBMITTED;
1663                 }
1664
1665                 inc_all_io_entry(tc->pool, bio);
1666                 cell_defer_no_holder_no_free(tc, &cell2);
1667                 cell_defer_no_holder_no_free(tc, &cell1);
1668
1669                 remap(tc, bio, result.block);
1670                 return DM_MAPIO_REMAPPED;
1671
1672         case -ENODATA:
1673                 if (get_pool_mode(tc->pool) == PM_READ_ONLY) {
1674                         /*
1675                          * This block isn't provisioned, and we have no way
1676                          * of doing so.
1677                          */
1678                         handle_unserviceable_bio(tc->pool, bio);
1679                         return DM_MAPIO_SUBMITTED;
1680                 }
1681                 /* fall through */
1682
1683         case -EWOULDBLOCK:
1684                 /*
1685                  * In future, the failed dm_thin_find_block above could
1686                  * provide the hint to load the metadata into cache.
1687                  */
1688                 thin_defer_bio(tc, bio);
1689                 return DM_MAPIO_SUBMITTED;
1690
1691         default:
1692                 /*
1693                  * Must always call bio_io_error on failure.
1694                  * dm_thin_find_block can fail with -EINVAL if the
1695                  * pool is switched to fail-io mode.
1696                  */
1697                 bio_io_error(bio);
1698                 return DM_MAPIO_SUBMITTED;
1699         }
1700 }
1701
1702 static int pool_is_congested(struct dm_target_callbacks *cb, int bdi_bits)
1703 {
1704         int r;
1705         unsigned long flags;
1706         struct pool_c *pt = container_of(cb, struct pool_c, callbacks);
1707
1708         spin_lock_irqsave(&pt->pool->lock, flags);
1709         r = !bio_list_empty(&pt->pool->retry_on_resume_list);
1710         spin_unlock_irqrestore(&pt->pool->lock, flags);
1711
1712         if (!r) {
1713                 struct request_queue *q = bdev_get_queue(pt->data_dev->bdev);
1714                 r = bdi_congested(&q->backing_dev_info, bdi_bits);
1715         }
1716
1717         return r;
1718 }
1719
1720 static void __requeue_bios(struct pool *pool)
1721 {
1722         bio_list_merge(&pool->deferred_bios, &pool->retry_on_resume_list);
1723         bio_list_init(&pool->retry_on_resume_list);
1724 }
1725
1726 /*----------------------------------------------------------------
1727  * Binding of control targets to a pool object
1728  *--------------------------------------------------------------*/
1729 static bool data_dev_supports_discard(struct pool_c *pt)
1730 {
1731         struct request_queue *q = bdev_get_queue(pt->data_dev->bdev);
1732
1733         return q && blk_queue_discard(q);
1734 }
1735
1736 static bool is_factor(sector_t block_size, uint32_t n)
1737 {
1738         return !sector_div(block_size, n);
1739 }
1740
1741 /*
1742  * If discard_passdown was enabled verify that the data device
1743  * supports discards.  Disable discard_passdown if not.
1744  */
1745 static void disable_passdown_if_not_supported(struct pool_c *pt)
1746 {
1747         struct pool *pool = pt->pool;
1748         struct block_device *data_bdev = pt->data_dev->bdev;
1749         struct queue_limits *data_limits = &bdev_get_queue(data_bdev)->limits;
1750         sector_t block_size = pool->sectors_per_block << SECTOR_SHIFT;
1751         const char *reason = NULL;
1752         char buf[BDEVNAME_SIZE];
1753
1754         if (!pt->adjusted_pf.discard_passdown)
1755                 return;
1756
1757         if (!data_dev_supports_discard(pt))
1758                 reason = "discard unsupported";
1759
1760         else if (data_limits->max_discard_sectors < pool->sectors_per_block)
1761                 reason = "max discard sectors smaller than a block";
1762
1763         else if (data_limits->discard_granularity > block_size)
1764                 reason = "discard granularity larger than a block";
1765
1766         else if (!is_factor(block_size, data_limits->discard_granularity))
1767                 reason = "discard granularity not a factor of block size";
1768
1769         if (reason) {
1770                 DMWARN("Data device (%s) %s: Disabling discard passdown.", bdevname(data_bdev, buf), reason);
1771                 pt->adjusted_pf.discard_passdown = false;
1772         }
1773 }
1774
1775 static int bind_control_target(struct pool *pool, struct dm_target *ti)
1776 {
1777         struct pool_c *pt = ti->private;
1778
1779         /*
1780          * We want to make sure that a pool in PM_FAIL mode is never upgraded.
1781          */
1782         enum pool_mode old_mode = get_pool_mode(pool);
1783         enum pool_mode new_mode = pt->adjusted_pf.mode;
1784
1785         /*
1786          * Don't change the pool's mode until set_pool_mode() below.
1787          * Otherwise the pool's process_* function pointers may
1788          * not match the desired pool mode.
1789          */
1790         pt->adjusted_pf.mode = old_mode;
1791
1792         pool->ti = ti;
1793         pool->pf = pt->adjusted_pf;
1794         pool->low_water_blocks = pt->low_water_blocks;
1795
1796         set_pool_mode(pool, new_mode);
1797
1798         return 0;
1799 }
1800
1801 static void unbind_control_target(struct pool *pool, struct dm_target *ti)
1802 {
1803         if (pool->ti == ti)
1804                 pool->ti = NULL;
1805 }
1806
1807 /*----------------------------------------------------------------
1808  * Pool creation
1809  *--------------------------------------------------------------*/
1810 /* Initialize pool features. */
1811 static void pool_features_init(struct pool_features *pf)
1812 {
1813         pf->mode = PM_WRITE;
1814         pf->zero_new_blocks = true;
1815         pf->discard_enabled = true;
1816         pf->discard_passdown = true;
1817         pf->error_if_no_space = false;
1818 }
1819
1820 static void __pool_destroy(struct pool *pool)
1821 {
1822         __pool_table_remove(pool);
1823
1824         if (dm_pool_metadata_close(pool->pmd) < 0)
1825                 DMWARN("%s: dm_pool_metadata_close() failed.", __func__);
1826
1827         dm_bio_prison_destroy(pool->prison);
1828         dm_kcopyd_client_destroy(pool->copier);
1829
1830         if (pool->wq)
1831                 destroy_workqueue(pool->wq);
1832
1833         if (pool->next_mapping)
1834                 mempool_free(pool->next_mapping, pool->mapping_pool);
1835         mempool_destroy(pool->mapping_pool);
1836         dm_deferred_set_destroy(pool->shared_read_ds);
1837         dm_deferred_set_destroy(pool->all_io_ds);
1838         kfree(pool);
1839 }
1840
1841 static struct kmem_cache *_new_mapping_cache;
1842
1843 static struct pool *pool_create(struct mapped_device *pool_md,
1844                                 struct block_device *metadata_dev,
1845                                 unsigned long block_size,
1846                                 int read_only, char **error)
1847 {
1848         int r;
1849         void *err_p;
1850         struct pool *pool;
1851         struct dm_pool_metadata *pmd;
1852         bool format_device = read_only ? false : true;
1853
1854         pmd = dm_pool_metadata_open(metadata_dev, block_size, format_device);
1855         if (IS_ERR(pmd)) {
1856                 *error = "Error creating metadata object";
1857                 return (struct pool *)pmd;
1858         }
1859
1860         pool = kmalloc(sizeof(*pool), GFP_KERNEL);
1861         if (!pool) {
1862                 *error = "Error allocating memory for pool";
1863                 err_p = ERR_PTR(-ENOMEM);
1864                 goto bad_pool;
1865         }
1866
1867         pool->pmd = pmd;
1868         pool->sectors_per_block = block_size;
1869         if (block_size & (block_size - 1))
1870                 pool->sectors_per_block_shift = -1;
1871         else
1872                 pool->sectors_per_block_shift = __ffs(block_size);
1873         pool->low_water_blocks = 0;
1874         pool_features_init(&pool->pf);
1875         pool->prison = dm_bio_prison_create(PRISON_CELLS);
1876         if (!pool->prison) {
1877                 *error = "Error creating pool's bio prison";
1878                 err_p = ERR_PTR(-ENOMEM);
1879                 goto bad_prison;
1880         }
1881
1882         pool->copier = dm_kcopyd_client_create(&dm_kcopyd_throttle);
1883         if (IS_ERR(pool->copier)) {
1884                 r = PTR_ERR(pool->copier);
1885                 *error = "Error creating pool's kcopyd client";
1886                 err_p = ERR_PTR(r);
1887                 goto bad_kcopyd_client;
1888         }
1889
1890         /*
1891          * Create singlethreaded workqueue that will service all devices
1892          * that use this metadata.
1893          */
1894         pool->wq = alloc_ordered_workqueue("dm-" DM_MSG_PREFIX, WQ_MEM_RECLAIM);
1895         if (!pool->wq) {
1896                 *error = "Error creating pool's workqueue";
1897                 err_p = ERR_PTR(-ENOMEM);
1898                 goto bad_wq;
1899         }
1900
1901         INIT_WORK(&pool->worker, do_worker);
1902         INIT_DELAYED_WORK(&pool->waker, do_waker);
1903         spin_lock_init(&pool->lock);
1904         bio_list_init(&pool->deferred_bios);
1905         bio_list_init(&pool->deferred_flush_bios);
1906         INIT_LIST_HEAD(&pool->prepared_mappings);
1907         INIT_LIST_HEAD(&pool->prepared_discards);
1908         pool->low_water_triggered = false;
1909         bio_list_init(&pool->retry_on_resume_list);
1910
1911         pool->shared_read_ds = dm_deferred_set_create();
1912         if (!pool->shared_read_ds) {
1913                 *error = "Error creating pool's shared read deferred set";
1914                 err_p = ERR_PTR(-ENOMEM);
1915                 goto bad_shared_read_ds;
1916         }
1917
1918         pool->all_io_ds = dm_deferred_set_create();
1919         if (!pool->all_io_ds) {
1920                 *error = "Error creating pool's all io deferred set";
1921                 err_p = ERR_PTR(-ENOMEM);
1922                 goto bad_all_io_ds;
1923         }
1924
1925         pool->next_mapping = NULL;
1926         pool->mapping_pool = mempool_create_slab_pool(MAPPING_POOL_SIZE,
1927                                                       _new_mapping_cache);
1928         if (!pool->mapping_pool) {
1929                 *error = "Error creating pool's mapping mempool";
1930                 err_p = ERR_PTR(-ENOMEM);
1931                 goto bad_mapping_pool;
1932         }
1933
1934         pool->ref_count = 1;
1935         pool->last_commit_jiffies = jiffies;
1936         pool->pool_md = pool_md;
1937         pool->md_dev = metadata_dev;
1938         __pool_table_insert(pool);
1939
1940         return pool;
1941
1942 bad_mapping_pool:
1943         dm_deferred_set_destroy(pool->all_io_ds);
1944 bad_all_io_ds:
1945         dm_deferred_set_destroy(pool->shared_read_ds);
1946 bad_shared_read_ds:
1947         destroy_workqueue(pool->wq);
1948 bad_wq:
1949         dm_kcopyd_client_destroy(pool->copier);
1950 bad_kcopyd_client:
1951         dm_bio_prison_destroy(pool->prison);
1952 bad_prison:
1953         kfree(pool);
1954 bad_pool:
1955         if (dm_pool_metadata_close(pmd))
1956                 DMWARN("%s: dm_pool_metadata_close() failed.", __func__);
1957
1958         return err_p;
1959 }
1960
1961 static void __pool_inc(struct pool *pool)
1962 {
1963         BUG_ON(!mutex_is_locked(&dm_thin_pool_table.mutex));
1964         pool->ref_count++;
1965 }
1966
1967 static void __pool_dec(struct pool *pool)
1968 {
1969         BUG_ON(!mutex_is_locked(&dm_thin_pool_table.mutex));
1970         BUG_ON(!pool->ref_count);
1971         if (!--pool->ref_count)
1972                 __pool_destroy(pool);
1973 }
1974
1975 static struct pool *__pool_find(struct mapped_device *pool_md,
1976                                 struct block_device *metadata_dev,
1977                                 unsigned long block_size, int read_only,
1978                                 char **error, int *created)
1979 {
1980         struct pool *pool = __pool_table_lookup_metadata_dev(metadata_dev);
1981
1982         if (pool) {
1983                 if (pool->pool_md != pool_md) {
1984                         *error = "metadata device already in use by a pool";
1985                         return ERR_PTR(-EBUSY);
1986                 }
1987                 __pool_inc(pool);
1988
1989         } else {
1990                 pool = __pool_table_lookup(pool_md);
1991                 if (pool) {
1992                         if (pool->md_dev != metadata_dev) {
1993                                 *error = "different pool cannot replace a pool";
1994                                 return ERR_PTR(-EINVAL);
1995                         }
1996                         __pool_inc(pool);
1997
1998                 } else {
1999                         pool = pool_create(pool_md, metadata_dev, block_size, read_only, error);
2000                         *created = 1;
2001                 }
2002         }
2003
2004         return pool;
2005 }
2006
2007 /*----------------------------------------------------------------
2008  * Pool target methods
2009  *--------------------------------------------------------------*/
2010 static void pool_dtr(struct dm_target *ti)
2011 {
2012         struct pool_c *pt = ti->private;
2013
2014         mutex_lock(&dm_thin_pool_table.mutex);
2015
2016         unbind_control_target(pt->pool, ti);
2017         __pool_dec(pt->pool);
2018         dm_put_device(ti, pt->metadata_dev);
2019         dm_put_device(ti, pt->data_dev);
2020         kfree(pt);
2021
2022         mutex_unlock(&dm_thin_pool_table.mutex);
2023 }
2024
2025 static int parse_pool_features(struct dm_arg_set *as, struct pool_features *pf,
2026                                struct dm_target *ti)
2027 {
2028         int r;
2029         unsigned argc;
2030         const char *arg_name;
2031
2032         static struct dm_arg _args[] = {
2033                 {0, 4, "Invalid number of pool feature arguments"},
2034         };
2035
2036         /*
2037          * No feature arguments supplied.
2038          */
2039         if (!as->argc)
2040                 return 0;
2041
2042         r = dm_read_arg_group(_args, as, &argc, &ti->error);
2043         if (r)
2044                 return -EINVAL;
2045
2046         while (argc && !r) {
2047                 arg_name = dm_shift_arg(as);
2048                 argc--;
2049
2050                 if (!strcasecmp(arg_name, "skip_block_zeroing"))
2051                         pf->zero_new_blocks = false;
2052
2053                 else if (!strcasecmp(arg_name, "ignore_discard"))
2054                         pf->discard_enabled = false;
2055
2056                 else if (!strcasecmp(arg_name, "no_discard_passdown"))
2057                         pf->discard_passdown = false;
2058
2059                 else if (!strcasecmp(arg_name, "read_only"))
2060                         pf->mode = PM_READ_ONLY;
2061
2062                 else if (!strcasecmp(arg_name, "error_if_no_space"))
2063                         pf->error_if_no_space = true;
2064
2065                 else {
2066                         ti->error = "Unrecognised pool feature requested";
2067                         r = -EINVAL;
2068                         break;
2069                 }
2070         }
2071
2072         return r;
2073 }
2074
2075 static void metadata_low_callback(void *context)
2076 {
2077         struct pool *pool = context;
2078
2079         DMWARN("%s: reached low water mark for metadata device: sending event.",
2080                dm_device_name(pool->pool_md));
2081
2082         dm_table_event(pool->ti->table);
2083 }
2084
2085 static sector_t get_dev_size(struct block_device *bdev)
2086 {
2087         return i_size_read(bdev->bd_inode) >> SECTOR_SHIFT;
2088 }
2089
2090 static void warn_if_metadata_device_too_big(struct block_device *bdev)
2091 {
2092         sector_t metadata_dev_size = get_dev_size(bdev);
2093         char buffer[BDEVNAME_SIZE];
2094
2095         if (metadata_dev_size > THIN_METADATA_MAX_SECTORS_WARNING)
2096                 DMWARN("Metadata device %s is larger than %u sectors: excess space will not be used.",
2097                        bdevname(bdev, buffer), THIN_METADATA_MAX_SECTORS);
2098 }
2099
2100 static sector_t get_metadata_dev_size(struct block_device *bdev)
2101 {
2102         sector_t metadata_dev_size = get_dev_size(bdev);
2103
2104         if (metadata_dev_size > THIN_METADATA_MAX_SECTORS)
2105                 metadata_dev_size = THIN_METADATA_MAX_SECTORS;
2106
2107         return metadata_dev_size;
2108 }
2109
2110 static dm_block_t get_metadata_dev_size_in_blocks(struct block_device *bdev)
2111 {
2112         sector_t metadata_dev_size = get_metadata_dev_size(bdev);
2113
2114         sector_div(metadata_dev_size, THIN_METADATA_BLOCK_SIZE);
2115
2116         return metadata_dev_size;
2117 }
2118
2119 /*
2120  * When a metadata threshold is crossed a dm event is triggered, and
2121  * userland should respond by growing the metadata device.  We could let
2122  * userland set the threshold, like we do with the data threshold, but I'm
2123  * not sure they know enough to do this well.
2124  */
2125 static dm_block_t calc_metadata_threshold(struct pool_c *pt)
2126 {
2127         /*
2128          * 4M is ample for all ops with the possible exception of thin
2129          * device deletion which is harmless if it fails (just retry the
2130          * delete after you've grown the device).
2131          */
2132         dm_block_t quarter = get_metadata_dev_size_in_blocks(pt->metadata_dev->bdev) / 4;
2133         return min((dm_block_t)1024ULL /* 4M */, quarter);
2134 }
2135
2136 /*
2137  * thin-pool <metadata dev> <data dev>
2138  *           <data block size (sectors)>
2139  *           <low water mark (blocks)>
2140  *           [<#feature args> [<arg>]*]
2141  *
2142  * Optional feature arguments are:
2143  *           skip_block_zeroing: skips the zeroing of newly-provisioned blocks.
2144  *           ignore_discard: disable discard
2145  *           no_discard_passdown: don't pass discards down to the data device
2146  *           read_only: Don't allow any changes to be made to the pool metadata.
2147  *           error_if_no_space: error IOs, instead of queueing, if no space.
2148  */
2149 static int pool_ctr(struct dm_target *ti, unsigned argc, char **argv)
2150 {
2151         int r, pool_created = 0;
2152         struct pool_c *pt;
2153         struct pool *pool;
2154         struct pool_features pf;
2155         struct dm_arg_set as;
2156         struct dm_dev *data_dev;
2157         unsigned long block_size;
2158         dm_block_t low_water_blocks;
2159         struct dm_dev *metadata_dev;
2160         fmode_t metadata_mode;
2161
2162         /*
2163          * FIXME Remove validation from scope of lock.
2164          */
2165         mutex_lock(&dm_thin_pool_table.mutex);
2166
2167         if (argc < 4) {
2168                 ti->error = "Invalid argument count";
2169                 r = -EINVAL;
2170                 goto out_unlock;
2171         }
2172
2173         as.argc = argc;
2174         as.argv = argv;
2175
2176         /*
2177          * Set default pool features.
2178          */
2179         pool_features_init(&pf);
2180
2181         dm_consume_args(&as, 4);
2182         r = parse_pool_features(&as, &pf, ti);
2183         if (r)
2184                 goto out_unlock;
2185
2186         metadata_mode = FMODE_READ | ((pf.mode == PM_READ_ONLY) ? 0 : FMODE_WRITE);
2187         r = dm_get_device(ti, argv[0], metadata_mode, &metadata_dev);
2188         if (r) {
2189                 ti->error = "Error opening metadata block device";
2190                 goto out_unlock;
2191         }
2192         warn_if_metadata_device_too_big(metadata_dev->bdev);
2193
2194         r = dm_get_device(ti, argv[1], FMODE_READ | FMODE_WRITE, &data_dev);
2195         if (r) {
2196                 ti->error = "Error getting data device";
2197                 goto out_metadata;
2198         }
2199
2200         if (kstrtoul(argv[2], 10, &block_size) || !block_size ||
2201             block_size < DATA_DEV_BLOCK_SIZE_MIN_SECTORS ||
2202             block_size > DATA_DEV_BLOCK_SIZE_MAX_SECTORS ||
2203             block_size & (DATA_DEV_BLOCK_SIZE_MIN_SECTORS - 1)) {
2204                 ti->error = "Invalid block size";
2205                 r = -EINVAL;
2206                 goto out;
2207         }
2208
2209         if (kstrtoull(argv[3], 10, (unsigned long long *)&low_water_blocks)) {
2210                 ti->error = "Invalid low water mark";
2211                 r = -EINVAL;
2212                 goto out;
2213         }
2214
2215         pt = kzalloc(sizeof(*pt), GFP_KERNEL);
2216         if (!pt) {
2217                 r = -ENOMEM;
2218                 goto out;
2219         }
2220
2221         pool = __pool_find(dm_table_get_md(ti->table), metadata_dev->bdev,
2222                            block_size, pf.mode == PM_READ_ONLY, &ti->error, &pool_created);
2223         if (IS_ERR(pool)) {
2224                 r = PTR_ERR(pool);
2225                 goto out_free_pt;
2226         }
2227
2228         /*
2229          * 'pool_created' reflects whether this is the first table load.
2230          * Top level discard support is not allowed to be changed after
2231          * initial load.  This would require a pool reload to trigger thin
2232          * device changes.
2233          */
2234         if (!pool_created && pf.discard_enabled != pool->pf.discard_enabled) {
2235                 ti->error = "Discard support cannot be disabled once enabled";
2236                 r = -EINVAL;
2237                 goto out_flags_changed;
2238         }
2239
2240         pt->pool = pool;
2241         pt->ti = ti;
2242         pt->metadata_dev = metadata_dev;
2243         pt->data_dev = data_dev;
2244         pt->low_water_blocks = low_water_blocks;
2245         pt->adjusted_pf = pt->requested_pf = pf;
2246         ti->num_flush_bios = 1;
2247
2248         /*
2249          * Only need to enable discards if the pool should pass
2250          * them down to the data device.  The thin device's discard
2251          * processing will cause mappings to be removed from the btree.
2252          */
2253         ti->discard_zeroes_data_unsupported = true;
2254         if (pf.discard_enabled && pf.discard_passdown) {
2255                 ti->num_discard_bios = 1;
2256
2257                 /*
2258                  * Setting 'discards_supported' circumvents the normal
2259                  * stacking of discard limits (this keeps the pool and
2260                  * thin devices' discard limits consistent).
2261                  */
2262                 ti->discards_supported = true;
2263         }
2264         ti->private = pt;
2265
2266         r = dm_pool_register_metadata_threshold(pt->pool->pmd,
2267                                                 calc_metadata_threshold(pt),
2268                                                 metadata_low_callback,
2269                                                 pool);
2270         if (r)
2271                 goto out_free_pt;
2272
2273         pt->callbacks.congested_fn = pool_is_congested;
2274         dm_table_add_target_callbacks(ti->table, &pt->callbacks);
2275
2276         mutex_unlock(&dm_thin_pool_table.mutex);
2277
2278         return 0;
2279
2280 out_flags_changed:
2281         __pool_dec(pool);
2282 out_free_pt:
2283         kfree(pt);
2284 out:
2285         dm_put_device(ti, data_dev);
2286 out_metadata:
2287         dm_put_device(ti, metadata_dev);
2288 out_unlock:
2289         mutex_unlock(&dm_thin_pool_table.mutex);
2290
2291         return r;
2292 }
2293
2294 static int pool_map(struct dm_target *ti, struct bio *bio)
2295 {
2296         int r;
2297         struct pool_c *pt = ti->private;
2298         struct pool *pool = pt->pool;
2299         unsigned long flags;
2300
2301         /*
2302          * As this is a singleton target, ti->begin is always zero.
2303          */
2304         spin_lock_irqsave(&pool->lock, flags);
2305         bio->bi_bdev = pt->data_dev->bdev;
2306         r = DM_MAPIO_REMAPPED;
2307         spin_unlock_irqrestore(&pool->lock, flags);
2308
2309         return r;
2310 }
2311
2312 static int maybe_resize_data_dev(struct dm_target *ti, bool *need_commit)
2313 {
2314         int r;
2315         struct pool_c *pt = ti->private;
2316         struct pool *pool = pt->pool;
2317         sector_t data_size = ti->len;
2318         dm_block_t sb_data_size;
2319
2320         *need_commit = false;
2321
2322         (void) sector_div(data_size, pool->sectors_per_block);
2323
2324         r = dm_pool_get_data_dev_size(pool->pmd, &sb_data_size);
2325         if (r) {
2326                 DMERR("%s: failed to retrieve data device size",
2327                       dm_device_name(pool->pool_md));
2328                 return r;
2329         }
2330
2331         if (data_size < sb_data_size) {
2332                 DMERR("%s: pool target (%llu blocks) too small: expected %llu",
2333                       dm_device_name(pool->pool_md),
2334                       (unsigned long long)data_size, sb_data_size);
2335                 return -EINVAL;
2336
2337         } else if (data_size > sb_data_size) {
2338                 if (dm_pool_metadata_needs_check(pool->pmd)) {
2339                         DMERR("%s: unable to grow the data device until repaired.",
2340                               dm_device_name(pool->pool_md));
2341                         return 0;
2342                 }
2343
2344                 if (sb_data_size)
2345                         DMINFO("%s: growing the data device from %llu to %llu blocks",
2346                                dm_device_name(pool->pool_md),
2347                                sb_data_size, (unsigned long long)data_size);
2348                 r = dm_pool_resize_data_dev(pool->pmd, data_size);
2349                 if (r) {
2350                         metadata_operation_failed(pool, "dm_pool_resize_data_dev", r);
2351                         return r;
2352                 }
2353
2354                 *need_commit = true;
2355         }
2356
2357         return 0;
2358 }
2359
2360 static int maybe_resize_metadata_dev(struct dm_target *ti, bool *need_commit)
2361 {
2362         int r;
2363         struct pool_c *pt = ti->private;
2364         struct pool *pool = pt->pool;
2365         dm_block_t metadata_dev_size, sb_metadata_dev_size;
2366
2367         *need_commit = false;
2368
2369         metadata_dev_size = get_metadata_dev_size_in_blocks(pool->md_dev);
2370
2371         r = dm_pool_get_metadata_dev_size(pool->pmd, &sb_metadata_dev_size);
2372         if (r) {
2373                 DMERR("%s: failed to retrieve metadata device size",
2374                       dm_device_name(pool->pool_md));
2375                 return r;
2376         }
2377
2378         if (metadata_dev_size < sb_metadata_dev_size) {
2379                 DMERR("%s: metadata device (%llu blocks) too small: expected %llu",
2380                       dm_device_name(pool->pool_md),
2381                       metadata_dev_size, sb_metadata_dev_size);
2382                 return -EINVAL;
2383
2384         } else if (metadata_dev_size > sb_metadata_dev_size) {
2385                 if (dm_pool_metadata_needs_check(pool->pmd)) {
2386                         DMERR("%s: unable to grow the metadata device until repaired.",
2387                               dm_device_name(pool->pool_md));
2388                         return 0;
2389                 }
2390
2391                 warn_if_metadata_device_too_big(pool->md_dev);
2392                 DMINFO("%s: growing the metadata device from %llu to %llu blocks",
2393                        dm_device_name(pool->pool_md),
2394                        sb_metadata_dev_size, metadata_dev_size);
2395                 r = dm_pool_resize_metadata_dev(pool->pmd, metadata_dev_size);
2396                 if (r) {
2397                         metadata_operation_failed(pool, "dm_pool_resize_metadata_dev", r);
2398                         return r;
2399                 }
2400
2401                 *need_commit = true;
2402         }
2403
2404         return 0;
2405 }
2406
2407 /*
2408  * Retrieves the number of blocks of the data device from
2409  * the superblock and compares it to the actual device size,
2410  * thus resizing the data device in case it has grown.
2411  *
2412  * This both copes with opening preallocated data devices in the ctr
2413  * being followed by a resume
2414  * -and-
2415  * calling the resume method individually after userspace has
2416  * grown the data device in reaction to a table event.
2417  */
2418 static int pool_preresume(struct dm_target *ti)
2419 {
2420         int r;
2421         bool need_commit1, need_commit2;
2422         struct pool_c *pt = ti->private;
2423         struct pool *pool = pt->pool;
2424
2425         /*
2426          * Take control of the pool object.
2427          */
2428         r = bind_control_target(pool, ti);
2429         if (r)
2430                 return r;
2431
2432         r = maybe_resize_data_dev(ti, &need_commit1);
2433         if (r)
2434                 return r;
2435
2436         r = maybe_resize_metadata_dev(ti, &need_commit2);
2437         if (r)
2438                 return r;
2439
2440         if (need_commit1 || need_commit2)
2441                 (void) commit(pool);
2442
2443         return 0;
2444 }
2445
2446 static void pool_resume(struct dm_target *ti)
2447 {
2448         struct pool_c *pt = ti->private;
2449         struct pool *pool = pt->pool;
2450         unsigned long flags;
2451
2452         spin_lock_irqsave(&pool->lock, flags);
2453         pool->low_water_triggered = false;
2454         __requeue_bios(pool);
2455         spin_unlock_irqrestore(&pool->lock, flags);
2456
2457         do_waker(&pool->waker.work);
2458 }
2459
2460 static void pool_postsuspend(struct dm_target *ti)
2461 {
2462         struct pool_c *pt = ti->private;
2463         struct pool *pool = pt->pool;
2464
2465         cancel_delayed_work(&pool->waker);
2466         flush_workqueue(pool->wq);
2467         (void) commit(pool);
2468 }
2469
2470 static int check_arg_count(unsigned argc, unsigned args_required)
2471 {
2472         if (argc != args_required) {
2473                 DMWARN("Message received with %u arguments instead of %u.",
2474                        argc, args_required);
2475                 return -EINVAL;
2476         }
2477
2478         return 0;
2479 }
2480
2481 static int read_dev_id(char *arg, dm_thin_id *dev_id, int warning)
2482 {
2483         if (!kstrtoull(arg, 10, (unsigned long long *)dev_id) &&
2484             *dev_id <= MAX_DEV_ID)
2485                 return 0;
2486
2487         if (warning)
2488                 DMWARN("Message received with invalid device id: %s", arg);
2489
2490         return -EINVAL;
2491 }
2492
2493 static int process_create_thin_mesg(unsigned argc, char **argv, struct pool *pool)
2494 {
2495         dm_thin_id dev_id;
2496         int r;
2497
2498         r = check_arg_count(argc, 2);
2499         if (r)
2500                 return r;
2501
2502         r = read_dev_id(argv[1], &dev_id, 1);
2503         if (r)
2504                 return r;
2505
2506         r = dm_pool_create_thin(pool->pmd, dev_id);
2507         if (r) {
2508                 DMWARN("Creation of new thinly-provisioned device with id %s failed.",
2509                        argv[1]);
2510                 return r;
2511         }
2512
2513         return 0;
2514 }
2515
2516 static int process_create_snap_mesg(unsigned argc, char **argv, struct pool *pool)
2517 {
2518         dm_thin_id dev_id;
2519         dm_thin_id origin_dev_id;
2520         int r;
2521
2522         r = check_arg_count(argc, 3);
2523         if (r)
2524                 return r;
2525
2526         r = read_dev_id(argv[1], &dev_id, 1);
2527         if (r)
2528                 return r;
2529
2530         r = read_dev_id(argv[2], &origin_dev_id, 1);
2531         if (r)
2532                 return r;
2533
2534         r = dm_pool_create_snap(pool->pmd, dev_id, origin_dev_id);
2535         if (r) {
2536                 DMWARN("Creation of new snapshot %s of device %s failed.",
2537                        argv[1], argv[2]);
2538                 return r;
2539         }
2540
2541         return 0;
2542 }
2543
2544 static int process_delete_mesg(unsigned argc, char **argv, struct pool *pool)
2545 {
2546         dm_thin_id dev_id;
2547         int r;
2548
2549         r = check_arg_count(argc, 2);
2550         if (r)
2551                 return r;
2552
2553         r = read_dev_id(argv[1], &dev_id, 1);
2554         if (r)
2555                 return r;
2556
2557         r = dm_pool_delete_thin_device(pool->pmd, dev_id);
2558         if (r)
2559                 DMWARN("Deletion of thin device %s failed.", argv[1]);
2560
2561         return r;
2562 }
2563
2564 static int process_set_transaction_id_mesg(unsigned argc, char **argv, struct pool *pool)
2565 {
2566         dm_thin_id old_id, new_id;
2567         int r;
2568
2569         r = check_arg_count(argc, 3);
2570         if (r)
2571                 return r;
2572
2573         if (kstrtoull(argv[1], 10, (unsigned long long *)&old_id)) {
2574                 DMWARN("set_transaction_id message: Unrecognised id %s.", argv[1]);
2575                 return -EINVAL;
2576         }
2577
2578         if (kstrtoull(argv[2], 10, (unsigned long long *)&new_id)) {
2579                 DMWARN("set_transaction_id message: Unrecognised new id %s.", argv[2]);
2580                 return -EINVAL;
2581         }
2582
2583         r = dm_pool_set_metadata_transaction_id(pool->pmd, old_id, new_id);
2584         if (r) {
2585                 DMWARN("Failed to change transaction id from %s to %s.",
2586                        argv[1], argv[2]);
2587                 return r;
2588         }
2589
2590         return 0;
2591 }
2592
2593 static int process_reserve_metadata_snap_mesg(unsigned argc, char **argv, struct pool *pool)
2594 {
2595         int r;
2596
2597         r = check_arg_count(argc, 1);
2598         if (r)
2599                 return r;
2600
2601         (void) commit(pool);
2602
2603         r = dm_pool_reserve_metadata_snap(pool->pmd);
2604         if (r)
2605                 DMWARN("reserve_metadata_snap message failed.");
2606
2607         return r;
2608 }
2609
2610 static int process_release_metadata_snap_mesg(unsigned argc, char **argv, struct pool *pool)
2611 {
2612         int r;
2613
2614         r = check_arg_count(argc, 1);
2615         if (r)
2616                 return r;
2617
2618         r = dm_pool_release_metadata_snap(pool->pmd);
2619         if (r)
2620                 DMWARN("release_metadata_snap message failed.");
2621
2622         return r;
2623 }
2624
2625 /*
2626  * Messages supported:
2627  *   create_thin        <dev_id>
2628  *   create_snap        <dev_id> <origin_id>
2629  *   delete             <dev_id>
2630  *   trim               <dev_id> <new_size_in_sectors>
2631  *   set_transaction_id <current_trans_id> <new_trans_id>
2632  *   reserve_metadata_snap
2633  *   release_metadata_snap
2634  */
2635 static int pool_message(struct dm_target *ti, unsigned argc, char **argv)
2636 {
2637         int r = -EINVAL;
2638         struct pool_c *pt = ti->private;
2639         struct pool *pool = pt->pool;
2640
2641         if (!strcasecmp(argv[0], "create_thin"))
2642                 r = process_create_thin_mesg(argc, argv, pool);
2643
2644         else if (!strcasecmp(argv[0], "create_snap"))
2645                 r = process_create_snap_mesg(argc, argv, pool);
2646
2647         else if (!strcasecmp(argv[0], "delete"))
2648                 r = process_delete_mesg(argc, argv, pool);
2649
2650         else if (!strcasecmp(argv[0], "set_transaction_id"))
2651                 r = process_set_transaction_id_mesg(argc, argv, pool);
2652
2653         else if (!strcasecmp(argv[0], "reserve_metadata_snap"))
2654                 r = process_reserve_metadata_snap_mesg(argc, argv, pool);
2655
2656         else if (!strcasecmp(argv[0], "release_metadata_snap"))
2657                 r = process_release_metadata_snap_mesg(argc, argv, pool);
2658
2659         else
2660                 DMWARN("Unrecognised thin pool target message received: %s", argv[0]);
2661
2662         if (!r)
2663                 (void) commit(pool);
2664
2665         return r;
2666 }
2667
2668 static void emit_flags(struct pool_features *pf, char *result,
2669                        unsigned sz, unsigned maxlen)
2670 {
2671         unsigned count = !pf->zero_new_blocks + !pf->discard_enabled +
2672                 !pf->discard_passdown + (pf->mode == PM_READ_ONLY) +
2673                 pf->error_if_no_space;
2674         DMEMIT("%u ", count);
2675
2676         if (!pf->zero_new_blocks)
2677                 DMEMIT("skip_block_zeroing ");
2678
2679         if (!pf->discard_enabled)
2680                 DMEMIT("ignore_discard ");
2681
2682         if (!pf->discard_passdown)
2683                 DMEMIT("no_discard_passdown ");
2684
2685         if (pf->mode == PM_READ_ONLY)
2686                 DMEMIT("read_only ");
2687
2688         if (pf->error_if_no_space)
2689                 DMEMIT("error_if_no_space ");
2690 }
2691
2692 /*
2693  * Status line is:
2694  *    <transaction id> <used metadata sectors>/<total metadata sectors>
2695  *    <used data sectors>/<total data sectors> <held metadata root>
2696  */
2697 static void pool_status(struct dm_target *ti, status_type_t type,
2698                         unsigned status_flags, char *result, unsigned maxlen)
2699 {
2700         int r;
2701         unsigned sz = 0;
2702         uint64_t transaction_id;
2703         dm_block_t nr_free_blocks_data;
2704         dm_block_t nr_free_blocks_metadata;
2705         dm_block_t nr_blocks_data;
2706         dm_block_t nr_blocks_metadata;
2707         dm_block_t held_root;
2708         char buf[BDEVNAME_SIZE];
2709         char buf2[BDEVNAME_SIZE];
2710         struct pool_c *pt = ti->private;
2711         struct pool *pool = pt->pool;
2712
2713         switch (type) {
2714         case STATUSTYPE_INFO:
2715                 if (get_pool_mode(pool) == PM_FAIL) {
2716                         DMEMIT("Fail");
2717                         break;
2718                 }
2719
2720                 /* Commit to ensure statistics aren't out-of-date */
2721                 if (!(status_flags & DM_STATUS_NOFLUSH_FLAG) && !dm_suspended(ti))
2722                         (void) commit(pool);
2723
2724                 r = dm_pool_get_metadata_transaction_id(pool->pmd, &transaction_id);
2725                 if (r) {
2726                         DMERR("%s: dm_pool_get_metadata_transaction_id returned %d",
2727                               dm_device_name(pool->pool_md), r);
2728                         goto err;
2729                 }
2730
2731                 r = dm_pool_get_free_metadata_block_count(pool->pmd, &nr_free_blocks_metadata);
2732                 if (r) {
2733                         DMERR("%s: dm_pool_get_free_metadata_block_count returned %d",
2734                               dm_device_name(pool->pool_md), r);
2735                         goto err;
2736                 }
2737
2738                 r = dm_pool_get_metadata_dev_size(pool->pmd, &nr_blocks_metadata);
2739                 if (r) {
2740                         DMERR("%s: dm_pool_get_metadata_dev_size returned %d",
2741                               dm_device_name(pool->pool_md), r);
2742                         goto err;
2743                 }
2744
2745                 r = dm_pool_get_free_block_count(pool->pmd, &nr_free_blocks_data);
2746                 if (r) {
2747                         DMERR("%s: dm_pool_get_free_block_count returned %d",
2748                               dm_device_name(pool->pool_md), r);
2749                         goto err;
2750                 }
2751
2752                 r = dm_pool_get_data_dev_size(pool->pmd, &nr_blocks_data);
2753                 if (r) {
2754                         DMERR("%s: dm_pool_get_data_dev_size returned %d",
2755                               dm_device_name(pool->pool_md), r);
2756                         goto err;
2757                 }
2758
2759                 r = dm_pool_get_metadata_snap(pool->pmd, &held_root);
2760                 if (r) {
2761                         DMERR("%s: dm_pool_get_metadata_snap returned %d",
2762                               dm_device_name(pool->pool_md), r);
2763                         goto err;
2764                 }
2765
2766                 DMEMIT("%llu %llu/%llu %llu/%llu ",
2767                        (unsigned long long)transaction_id,
2768                        (unsigned long long)(nr_blocks_metadata - nr_free_blocks_metadata),
2769                        (unsigned long long)nr_blocks_metadata,
2770                        (unsigned long long)(nr_blocks_data - nr_free_blocks_data),
2771                        (unsigned long long)nr_blocks_data);
2772
2773                 if (held_root)
2774                         DMEMIT("%llu ", held_root);
2775                 else
2776                         DMEMIT("- ");
2777
2778                 if (pool->pf.mode == PM_OUT_OF_DATA_SPACE)
2779                         DMEMIT("out_of_data_space ");
2780                 else if (pool->pf.mode == PM_READ_ONLY)
2781                         DMEMIT("ro ");
2782                 else
2783                         DMEMIT("rw ");
2784
2785                 if (!pool->pf.discard_enabled)
2786                         DMEMIT("ignore_discard ");
2787                 else if (pool->pf.discard_passdown)
2788                         DMEMIT("discard_passdown ");
2789                 else
2790                         DMEMIT("no_discard_passdown ");
2791
2792                 if (pool->pf.error_if_no_space)
2793                         DMEMIT("error_if_no_space ");
2794                 else
2795                         DMEMIT("queue_if_no_space ");
2796
2797                 break;
2798
2799         case STATUSTYPE_TABLE:
2800                 DMEMIT("%s %s %lu %llu ",
2801                        format_dev_t(buf, pt->metadata_dev->bdev->bd_dev),
2802                        format_dev_t(buf2, pt->data_dev->bdev->bd_dev),
2803                        (unsigned long)pool->sectors_per_block,
2804                        (unsigned long long)pt->low_water_blocks);
2805                 emit_flags(&pt->requested_pf, result, sz, maxlen);
2806                 break;
2807         }
2808         return;
2809
2810 err:
2811         DMEMIT("Error");
2812 }
2813
2814 static int pool_iterate_devices(struct dm_target *ti,
2815                                 iterate_devices_callout_fn fn, void *data)
2816 {
2817         struct pool_c *pt = ti->private;
2818
2819         return fn(ti, pt->data_dev, 0, ti->len, data);
2820 }
2821
2822 static int pool_merge(struct dm_target *ti, struct bvec_merge_data *bvm,
2823                       struct bio_vec *biovec, int max_size)
2824 {
2825         struct pool_c *pt = ti->private;
2826         struct request_queue *q = bdev_get_queue(pt->data_dev->bdev);
2827
2828         if (!q->merge_bvec_fn)
2829                 return max_size;
2830
2831         bvm->bi_bdev = pt->data_dev->bdev;
2832
2833         return min(max_size, q->merge_bvec_fn(q, bvm, biovec));
2834 }
2835
2836 static void set_discard_limits(struct pool_c *pt, struct queue_limits *limits)
2837 {
2838         struct pool *pool = pt->pool;
2839         struct queue_limits *data_limits;
2840
2841         limits->max_discard_sectors = pool->sectors_per_block;
2842
2843         /*
2844          * discard_granularity is just a hint, and not enforced.
2845          */
2846         if (pt->adjusted_pf.discard_passdown) {
2847                 data_limits = &bdev_get_queue(pt->data_dev->bdev)->limits;
2848                 limits->discard_granularity = data_limits->discard_granularity;
2849         } else
2850                 limits->discard_granularity = pool->sectors_per_block << SECTOR_SHIFT;
2851 }
2852
2853 static void pool_io_hints(struct dm_target *ti, struct queue_limits *limits)
2854 {
2855         struct pool_c *pt = ti->private;
2856         struct pool *pool = pt->pool;
2857         uint64_t io_opt_sectors = limits->io_opt >> SECTOR_SHIFT;
2858
2859         /*
2860          * If the system-determined stacked limits are compatible with the
2861          * pool's blocksize (io_opt is a factor) do not override them.
2862          */
2863         if (io_opt_sectors < pool->sectors_per_block ||
2864             do_div(io_opt_sectors, pool->sectors_per_block)) {
2865                 blk_limits_io_min(limits, 0);
2866                 blk_limits_io_opt(limits, pool->sectors_per_block << SECTOR_SHIFT);
2867         }
2868
2869         /*
2870          * pt->adjusted_pf is a staging area for the actual features to use.
2871          * They get transferred to the live pool in bind_control_target()
2872          * called from pool_preresume().
2873          */
2874         if (!pt->adjusted_pf.discard_enabled) {
2875                 /*
2876                  * Must explicitly disallow stacking discard limits otherwise the
2877                  * block layer will stack them if pool's data device has support.
2878                  * QUEUE_FLAG_DISCARD wouldn't be set but there is no way for the
2879                  * user to see that, so make sure to set all discard limits to 0.
2880                  */
2881                 limits->discard_granularity = 0;
2882                 return;
2883         }
2884
2885         disable_passdown_if_not_supported(pt);
2886
2887         set_discard_limits(pt, limits);
2888 }
2889
2890 static struct target_type pool_target = {
2891         .name = "thin-pool",
2892         .features = DM_TARGET_SINGLETON | DM_TARGET_ALWAYS_WRITEABLE |
2893                     DM_TARGET_IMMUTABLE,
2894         .version = {1, 11, 0},
2895         .module = THIS_MODULE,
2896         .ctr = pool_ctr,
2897         .dtr = pool_dtr,
2898         .map = pool_map,
2899         .postsuspend = pool_postsuspend,
2900         .preresume = pool_preresume,
2901         .resume = pool_resume,
2902         .message = pool_message,
2903         .status = pool_status,
2904         .merge = pool_merge,
2905         .iterate_devices = pool_iterate_devices,
2906         .io_hints = pool_io_hints,
2907 };
2908
2909 /*----------------------------------------------------------------
2910  * Thin target methods
2911  *--------------------------------------------------------------*/
2912 static void thin_dtr(struct dm_target *ti)
2913 {
2914         struct thin_c *tc = ti->private;
2915
2916         mutex_lock(&dm_thin_pool_table.mutex);
2917
2918         __pool_dec(tc->pool);
2919         dm_pool_close_thin_device(tc->td);
2920         dm_put_device(ti, tc->pool_dev);
2921         if (tc->origin_dev)
2922                 dm_put_device(ti, tc->origin_dev);
2923         kfree(tc);
2924
2925         mutex_unlock(&dm_thin_pool_table.mutex);
2926 }
2927
2928 /*
2929  * Thin target parameters:
2930  *
2931  * <pool_dev> <dev_id> [origin_dev]
2932  *
2933  * pool_dev: the path to the pool (eg, /dev/mapper/my_pool)
2934  * dev_id: the internal device identifier
2935  * origin_dev: a device external to the pool that should act as the origin
2936  *
2937  * If the pool device has discards disabled, they get disabled for the thin
2938  * device as well.
2939  */
2940 static int thin_ctr(struct dm_target *ti, unsigned argc, char **argv)
2941 {
2942         int r;
2943         struct thin_c *tc;
2944         struct dm_dev *pool_dev, *origin_dev;
2945         struct mapped_device *pool_md;
2946
2947         mutex_lock(&dm_thin_pool_table.mutex);
2948
2949         if (argc != 2 && argc != 3) {
2950                 ti->error = "Invalid argument count";
2951                 r = -EINVAL;
2952                 goto out_unlock;
2953         }
2954
2955         tc = ti->private = kzalloc(sizeof(*tc), GFP_KERNEL);
2956         if (!tc) {
2957                 ti->error = "Out of memory";
2958                 r = -ENOMEM;
2959                 goto out_unlock;
2960         }
2961
2962         if (argc == 3) {
2963                 r = dm_get_device(ti, argv[2], FMODE_READ, &origin_dev);
2964                 if (r) {
2965                         ti->error = "Error opening origin device";
2966                         goto bad_origin_dev;
2967                 }
2968                 tc->origin_dev = origin_dev;
2969         }
2970
2971         r = dm_get_device(ti, argv[0], dm_table_get_mode(ti->table), &pool_dev);
2972         if (r) {
2973                 ti->error = "Error opening pool device";
2974                 goto bad_pool_dev;
2975         }
2976         tc->pool_dev = pool_dev;
2977
2978         if (read_dev_id(argv[1], (unsigned long long *)&tc->dev_id, 0)) {
2979                 ti->error = "Invalid device id";
2980                 r = -EINVAL;
2981                 goto bad_common;
2982         }
2983
2984         pool_md = dm_get_md(tc->pool_dev->bdev->bd_dev);
2985         if (!pool_md) {
2986                 ti->error = "Couldn't get pool mapped device";
2987                 r = -EINVAL;
2988                 goto bad_common;
2989         }
2990
2991         tc->pool = __pool_table_lookup(pool_md);
2992         if (!tc->pool) {
2993                 ti->error = "Couldn't find pool object";
2994                 r = -EINVAL;
2995                 goto bad_pool_lookup;
2996         }
2997         __pool_inc(tc->pool);
2998
2999         if (get_pool_mode(tc->pool) == PM_FAIL) {
3000                 ti->error = "Couldn't open thin device, Pool is in fail mode";
3001                 r = -EINVAL;
3002                 goto bad_thin_open;
3003         }
3004
3005         r = dm_pool_open_thin_device(tc->pool->pmd, tc->dev_id, &tc->td);
3006         if (r) {
3007                 ti->error = "Couldn't open thin internal device";
3008                 goto bad_thin_open;
3009         }
3010
3011         r = dm_set_target_max_io_len(ti, tc->pool->sectors_per_block);
3012         if (r)
3013                 goto bad_target_max_io_len;
3014
3015         ti->num_flush_bios = 1;
3016         ti->flush_supported = true;
3017         ti->per_bio_data_size = sizeof(struct dm_thin_endio_hook);
3018
3019         /* In case the pool supports discards, pass them on. */
3020         ti->discard_zeroes_data_unsupported = true;
3021         if (tc->pool->pf.discard_enabled) {
3022                 ti->discards_supported = true;
3023                 ti->num_discard_bios = 1;
3024                 /* Discard bios must be split on a block boundary */
3025                 ti->split_discard_bios = true;
3026         }
3027
3028         dm_put(pool_md);
3029
3030         mutex_unlock(&dm_thin_pool_table.mutex);
3031
3032         return 0;
3033
3034 bad_target_max_io_len:
3035         dm_pool_close_thin_device(tc->td);
3036 bad_thin_open:
3037         __pool_dec(tc->pool);
3038 bad_pool_lookup:
3039         dm_put(pool_md);
3040 bad_common:
3041         dm_put_device(ti, tc->pool_dev);
3042 bad_pool_dev:
3043         if (tc->origin_dev)
3044                 dm_put_device(ti, tc->origin_dev);
3045 bad_origin_dev:
3046         kfree(tc);
3047 out_unlock:
3048         mutex_unlock(&dm_thin_pool_table.mutex);
3049
3050         return r;
3051 }
3052
3053 static int thin_map(struct dm_target *ti, struct bio *bio)
3054 {
3055         bio->bi_iter.bi_sector = dm_target_offset(ti, bio->bi_iter.bi_sector);
3056
3057         return thin_bio_map(ti, bio);
3058 }
3059
3060 static int thin_endio(struct dm_target *ti, struct bio *bio, int err)
3061 {
3062         unsigned long flags;
3063         struct dm_thin_endio_hook *h = dm_per_bio_data(bio, sizeof(struct dm_thin_endio_hook));
3064         struct list_head work;
3065         struct dm_thin_new_mapping *m, *tmp;
3066         struct pool *pool = h->tc->pool;
3067
3068         if (h->shared_read_entry) {
3069                 INIT_LIST_HEAD(&work);
3070                 dm_deferred_entry_dec(h->shared_read_entry, &work);
3071
3072                 spin_lock_irqsave(&pool->lock, flags);
3073                 list_for_each_entry_safe(m, tmp, &work, list) {
3074                         list_del(&m->list);
3075                         m->quiesced = true;
3076                         __maybe_add_mapping(m);
3077                 }
3078                 spin_unlock_irqrestore(&pool->lock, flags);
3079         }
3080
3081         if (h->all_io_entry) {
3082                 INIT_LIST_HEAD(&work);
3083                 dm_deferred_entry_dec(h->all_io_entry, &work);
3084                 if (!list_empty(&work)) {
3085                         spin_lock_irqsave(&pool->lock, flags);
3086                         list_for_each_entry_safe(m, tmp, &work, list)
3087                                 list_add_tail(&m->list, &pool->prepared_discards);
3088                         spin_unlock_irqrestore(&pool->lock, flags);
3089                         wake_worker(pool);
3090                 }
3091         }
3092
3093         return 0;
3094 }
3095
3096 static void thin_postsuspend(struct dm_target *ti)
3097 {
3098         if (dm_noflush_suspending(ti))
3099                 requeue_io((struct thin_c *)ti->private);
3100 }
3101
3102 /*
3103  * <nr mapped sectors> <highest mapped sector>
3104  */
3105 static void thin_status(struct dm_target *ti, status_type_t type,
3106                         unsigned status_flags, char *result, unsigned maxlen)
3107 {
3108         int r;
3109         ssize_t sz = 0;
3110         dm_block_t mapped, highest;
3111         char buf[BDEVNAME_SIZE];
3112         struct thin_c *tc = ti->private;
3113
3114         if (get_pool_mode(tc->pool) == PM_FAIL) {
3115                 DMEMIT("Fail");
3116                 return;
3117         }
3118
3119         if (!tc->td)
3120                 DMEMIT("-");
3121         else {
3122                 switch (type) {
3123                 case STATUSTYPE_INFO:
3124                         r = dm_thin_get_mapped_count(tc->td, &mapped);
3125                         if (r) {
3126                                 DMERR("dm_thin_get_mapped_count returned %d", r);
3127                                 goto err;
3128                         }
3129
3130                         r = dm_thin_get_highest_mapped_block(tc->td, &highest);
3131                         if (r < 0) {
3132                                 DMERR("dm_thin_get_highest_mapped_block returned %d", r);
3133                                 goto err;
3134                         }
3135
3136                         DMEMIT("%llu ", mapped * tc->pool->sectors_per_block);
3137                         if (r)
3138                                 DMEMIT("%llu", ((highest + 1) *
3139                                                 tc->pool->sectors_per_block) - 1);
3140                         else
3141                                 DMEMIT("-");
3142                         break;
3143
3144                 case STATUSTYPE_TABLE:
3145                         DMEMIT("%s %lu",
3146                                format_dev_t(buf, tc->pool_dev->bdev->bd_dev),
3147                                (unsigned long) tc->dev_id);
3148                         if (tc->origin_dev)
3149                                 DMEMIT(" %s", format_dev_t(buf, tc->origin_dev->bdev->bd_dev));
3150                         break;
3151                 }
3152         }
3153
3154         return;
3155
3156 err:
3157         DMEMIT("Error");
3158 }
3159
3160 static int thin_iterate_devices(struct dm_target *ti,
3161                                 iterate_devices_callout_fn fn, void *data)
3162 {
3163         sector_t blocks;
3164         struct thin_c *tc = ti->private;
3165         struct pool *pool = tc->pool;
3166
3167         /*
3168          * We can't call dm_pool_get_data_dev_size() since that blocks.  So
3169          * we follow a more convoluted path through to the pool's target.
3170          */
3171         if (!pool->ti)
3172                 return 0;       /* nothing is bound */
3173
3174         blocks = pool->ti->len;
3175         (void) sector_div(blocks, pool->sectors_per_block);
3176         if (blocks)
3177                 return fn(ti, tc->pool_dev, 0, pool->sectors_per_block * blocks, data);
3178
3179         return 0;
3180 }
3181
3182 static struct target_type thin_target = {
3183         .name = "thin",
3184         .version = {1, 11, 0},
3185         .module = THIS_MODULE,
3186         .ctr = thin_ctr,
3187         .dtr = thin_dtr,
3188         .map = thin_map,
3189         .end_io = thin_endio,
3190         .postsuspend = thin_postsuspend,
3191         .status = thin_status,
3192         .iterate_devices = thin_iterate_devices,
3193 };
3194
3195 /*----------------------------------------------------------------*/
3196
3197 static int __init dm_thin_init(void)
3198 {
3199         int r;
3200
3201         pool_table_init();
3202
3203         r = dm_register_target(&thin_target);
3204         if (r)
3205                 return r;
3206
3207         r = dm_register_target(&pool_target);
3208         if (r)
3209                 goto bad_pool_target;
3210
3211         r = -ENOMEM;
3212
3213         _new_mapping_cache = KMEM_CACHE(dm_thin_new_mapping, 0);
3214         if (!_new_mapping_cache)
3215                 goto bad_new_mapping_cache;
3216
3217         return 0;
3218
3219 bad_new_mapping_cache:
3220         dm_unregister_target(&pool_target);
3221 bad_pool_target:
3222         dm_unregister_target(&thin_target);
3223
3224         return r;
3225 }
3226
3227 static void dm_thin_exit(void)
3228 {
3229         dm_unregister_target(&thin_target);
3230         dm_unregister_target(&pool_target);
3231
3232         kmem_cache_destroy(_new_mapping_cache);
3233 }
3234
3235 module_init(dm_thin_init);
3236 module_exit(dm_thin_exit);
3237
3238 MODULE_DESCRIPTION(DM_NAME " thin provisioning target");
3239 MODULE_AUTHOR("Joe Thornber <dm-devel@redhat.com>");
3240 MODULE_LICENSE("GPL");