GNU Linux-libre 4.4.284-gnu1
[releases.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/jiffies.h>
15 #include <linux/log2.h>
16 #include <linux/list.h>
17 #include <linux/rculist.h>
18 #include <linux/init.h>
19 #include <linux/module.h>
20 #include <linux/slab.h>
21 #include <linux/vmalloc.h>
22 #include <linux/sort.h>
23 #include <linux/rbtree.h>
24
25 #define DM_MSG_PREFIX   "thin"
26
27 /*
28  * Tunable constants
29  */
30 #define ENDIO_HOOK_POOL_SIZE 1024
31 #define MAPPING_POOL_SIZE 1024
32 #define COMMIT_PERIOD HZ
33 #define NO_SPACE_TIMEOUT_SECS 60
34
35 static unsigned no_space_timeout_secs = NO_SPACE_TIMEOUT_SECS;
36
37 DECLARE_DM_KCOPYD_THROTTLE_WITH_MODULE_PARM(snapshot_copy_throttle,
38                 "A percentage of time allocated for copy on write");
39
40 /*
41  * The block size of the device holding pool data must be
42  * between 64KB and 1GB.
43  */
44 #define DATA_DEV_BLOCK_SIZE_MIN_SECTORS (64 * 1024 >> SECTOR_SHIFT)
45 #define DATA_DEV_BLOCK_SIZE_MAX_SECTORS (1024 * 1024 * 1024 >> SECTOR_SHIFT)
46
47 /*
48  * Device id is restricted to 24 bits.
49  */
50 #define MAX_DEV_ID ((1 << 24) - 1)
51
52 /*
53  * How do we handle breaking sharing of data blocks?
54  * =================================================
55  *
56  * We use a standard copy-on-write btree to store the mappings for the
57  * devices (note I'm talking about copy-on-write of the metadata here, not
58  * the data).  When you take an internal snapshot you clone the root node
59  * of the origin btree.  After this there is no concept of an origin or a
60  * snapshot.  They are just two device trees that happen to point to the
61  * same data blocks.
62  *
63  * When we get a write in we decide if it's to a shared data block using
64  * some timestamp magic.  If it is, we have to break sharing.
65  *
66  * Let's say we write to a shared block in what was the origin.  The
67  * steps are:
68  *
69  * i) plug io further to this physical block. (see bio_prison code).
70  *
71  * ii) quiesce any read io to that shared data block.  Obviously
72  * including all devices that share this block.  (see dm_deferred_set code)
73  *
74  * iii) copy the data block to a newly allocate block.  This step can be
75  * missed out if the io covers the block. (schedule_copy).
76  *
77  * iv) insert the new mapping into the origin's btree
78  * (process_prepared_mapping).  This act of inserting breaks some
79  * sharing of btree nodes between the two devices.  Breaking sharing only
80  * effects the btree of that specific device.  Btrees for the other
81  * devices that share the block never change.  The btree for the origin
82  * device as it was after the last commit is untouched, ie. we're using
83  * persistent data structures in the functional programming sense.
84  *
85  * v) unplug io to this physical block, including the io that triggered
86  * the breaking of sharing.
87  *
88  * Steps (ii) and (iii) occur in parallel.
89  *
90  * The metadata _doesn't_ need to be committed before the io continues.  We
91  * get away with this because the io is always written to a _new_ block.
92  * If there's a crash, then:
93  *
94  * - The origin mapping will point to the old origin block (the shared
95  * one).  This will contain the data as it was before the io that triggered
96  * the breaking of sharing came in.
97  *
98  * - The snap mapping still points to the old block.  As it would after
99  * the commit.
100  *
101  * The downside of this scheme is the timestamp magic isn't perfect, and
102  * will continue to think that data block in the snapshot device is shared
103  * even after the write to the origin has broken sharing.  I suspect data
104  * blocks will typically be shared by many different devices, so we're
105  * breaking sharing n + 1 times, rather than n, where n is the number of
106  * devices that reference this data block.  At the moment I think the
107  * benefits far, far outweigh the disadvantages.
108  */
109
110 /*----------------------------------------------------------------*/
111
112 /*
113  * Key building.
114  */
115 enum lock_space {
116         VIRTUAL,
117         PHYSICAL
118 };
119
120 static void build_key(struct dm_thin_device *td, enum lock_space ls,
121                       dm_block_t b, dm_block_t e, struct dm_cell_key *key)
122 {
123         key->virtual = (ls == VIRTUAL);
124         key->dev = dm_thin_dev_id(td);
125         key->block_begin = b;
126         key->block_end = e;
127 }
128
129 static void build_data_key(struct dm_thin_device *td, dm_block_t b,
130                            struct dm_cell_key *key)
131 {
132         build_key(td, PHYSICAL, b, b + 1llu, key);
133 }
134
135 static void build_virtual_key(struct dm_thin_device *td, dm_block_t b,
136                               struct dm_cell_key *key)
137 {
138         build_key(td, VIRTUAL, b, b + 1llu, key);
139 }
140
141 /*----------------------------------------------------------------*/
142
143 #define THROTTLE_THRESHOLD (1 * HZ)
144
145 struct throttle {
146         struct rw_semaphore lock;
147         unsigned long threshold;
148         bool throttle_applied;
149 };
150
151 static void throttle_init(struct throttle *t)
152 {
153         init_rwsem(&t->lock);
154         t->throttle_applied = false;
155 }
156
157 static void throttle_work_start(struct throttle *t)
158 {
159         t->threshold = jiffies + THROTTLE_THRESHOLD;
160 }
161
162 static void throttle_work_update(struct throttle *t)
163 {
164         if (!t->throttle_applied && jiffies > t->threshold) {
165                 down_write(&t->lock);
166                 t->throttle_applied = true;
167         }
168 }
169
170 static void throttle_work_complete(struct throttle *t)
171 {
172         if (t->throttle_applied) {
173                 t->throttle_applied = false;
174                 up_write(&t->lock);
175         }
176 }
177
178 static void throttle_lock(struct throttle *t)
179 {
180         down_read(&t->lock);
181 }
182
183 static void throttle_unlock(struct throttle *t)
184 {
185         up_read(&t->lock);
186 }
187
188 /*----------------------------------------------------------------*/
189
190 /*
191  * A pool device ties together a metadata device and a data device.  It
192  * also provides the interface for creating and destroying internal
193  * devices.
194  */
195 struct dm_thin_new_mapping;
196
197 /*
198  * The pool runs in 4 modes.  Ordered in degraded order for comparisons.
199  */
200 enum pool_mode {
201         PM_WRITE,               /* metadata may be changed */
202         PM_OUT_OF_DATA_SPACE,   /* metadata may be changed, though data may not be allocated */
203
204         /*
205          * Like READ_ONLY, except may switch back to WRITE on metadata resize. Reported as READ_ONLY.
206          */
207         PM_OUT_OF_METADATA_SPACE,
208         PM_READ_ONLY,           /* metadata may not be changed */
209
210         PM_FAIL,                /* all I/O fails */
211 };
212
213 struct pool_features {
214         enum pool_mode mode;
215
216         bool zero_new_blocks:1;
217         bool discard_enabled:1;
218         bool discard_passdown:1;
219         bool error_if_no_space:1;
220 };
221
222 struct thin_c;
223 typedef void (*process_bio_fn)(struct thin_c *tc, struct bio *bio);
224 typedef void (*process_cell_fn)(struct thin_c *tc, struct dm_bio_prison_cell *cell);
225 typedef void (*process_mapping_fn)(struct dm_thin_new_mapping *m);
226
227 #define CELL_SORT_ARRAY_SIZE 8192
228
229 struct pool {
230         struct list_head list;
231         struct dm_target *ti;   /* Only set if a pool target is bound */
232
233         struct mapped_device *pool_md;
234         struct block_device *md_dev;
235         struct dm_pool_metadata *pmd;
236
237         dm_block_t low_water_blocks;
238         uint32_t sectors_per_block;
239         int sectors_per_block_shift;
240
241         struct pool_features pf;
242         bool low_water_triggered:1;     /* A dm event has been sent */
243         bool suspended:1;
244
245         struct dm_bio_prison *prison;
246         struct dm_kcopyd_client *copier;
247
248         struct workqueue_struct *wq;
249         struct throttle throttle;
250         struct work_struct worker;
251         struct delayed_work waker;
252         struct delayed_work no_space_timeout;
253
254         unsigned long last_commit_jiffies;
255         unsigned ref_count;
256
257         spinlock_t lock;
258         struct bio_list deferred_flush_bios;
259         struct bio_list deferred_flush_completions;
260         struct list_head prepared_mappings;
261         struct list_head prepared_discards;
262         struct list_head active_thins;
263
264         struct dm_deferred_set *shared_read_ds;
265         struct dm_deferred_set *all_io_ds;
266
267         struct dm_thin_new_mapping *next_mapping;
268         mempool_t *mapping_pool;
269
270         process_bio_fn process_bio;
271         process_bio_fn process_discard;
272
273         process_cell_fn process_cell;
274         process_cell_fn process_discard_cell;
275
276         process_mapping_fn process_prepared_mapping;
277         process_mapping_fn process_prepared_discard;
278
279         struct dm_bio_prison_cell **cell_sort_array;
280 };
281
282 static enum pool_mode get_pool_mode(struct pool *pool);
283 static void metadata_operation_failed(struct pool *pool, const char *op, int r);
284
285 /*
286  * Target context for a pool.
287  */
288 struct pool_c {
289         struct dm_target *ti;
290         struct pool *pool;
291         struct dm_dev *data_dev;
292         struct dm_dev *metadata_dev;
293         struct dm_target_callbacks callbacks;
294
295         dm_block_t low_water_blocks;
296         struct pool_features requested_pf; /* Features requested during table load */
297         struct pool_features adjusted_pf;  /* Features used after adjusting for constituent devices */
298 };
299
300 /*
301  * Target context for a thin.
302  */
303 struct thin_c {
304         struct list_head list;
305         struct dm_dev *pool_dev;
306         struct dm_dev *origin_dev;
307         sector_t origin_size;
308         dm_thin_id dev_id;
309
310         struct pool *pool;
311         struct dm_thin_device *td;
312         struct mapped_device *thin_md;
313
314         bool requeue_mode:1;
315         spinlock_t lock;
316         struct list_head deferred_cells;
317         struct bio_list deferred_bio_list;
318         struct bio_list retry_on_resume_list;
319         struct rb_root sort_bio_list; /* sorted list of deferred bios */
320
321         /*
322          * Ensures the thin is not destroyed until the worker has finished
323          * iterating the active_thins list.
324          */
325         atomic_t refcount;
326         struct completion can_destroy;
327 };
328
329 /*----------------------------------------------------------------*/
330
331 /**
332  * __blkdev_issue_discard_async - queue a discard with async completion
333  * @bdev:       blockdev to issue discard for
334  * @sector:     start sector
335  * @nr_sects:   number of sectors to discard
336  * @gfp_mask:   memory allocation flags (for bio_alloc)
337  * @flags:      BLKDEV_IFL_* flags to control behaviour
338  * @parent_bio: parent discard bio that all sub discards get chained to
339  *
340  * Description:
341  *    Asynchronously issue a discard request for the sectors in question.
342  */
343 static int __blkdev_issue_discard_async(struct block_device *bdev, sector_t sector,
344                                         sector_t nr_sects, gfp_t gfp_mask, unsigned long flags,
345                                         struct bio *parent_bio)
346 {
347         struct request_queue *q = bdev_get_queue(bdev);
348         int type = REQ_WRITE | REQ_DISCARD;
349         struct bio *bio;
350
351         if (!q || !nr_sects)
352                 return -ENXIO;
353
354         if (!blk_queue_discard(q))
355                 return -EOPNOTSUPP;
356
357         if (flags & BLKDEV_DISCARD_SECURE) {
358                 if (!blk_queue_secdiscard(q))
359                         return -EOPNOTSUPP;
360                 type |= REQ_SECURE;
361         }
362
363         /*
364          * Required bio_put occurs in bio_endio thanks to bio_chain below
365          */
366         bio = bio_alloc(gfp_mask, 1);
367         if (!bio)
368                 return -ENOMEM;
369
370         bio_chain(bio, parent_bio);
371
372         bio->bi_iter.bi_sector = sector;
373         bio->bi_bdev = bdev;
374         bio->bi_iter.bi_size = nr_sects << 9;
375
376         submit_bio(type, bio);
377
378         return 0;
379 }
380
381 static bool block_size_is_power_of_two(struct pool *pool)
382 {
383         return pool->sectors_per_block_shift >= 0;
384 }
385
386 static sector_t block_to_sectors(struct pool *pool, dm_block_t b)
387 {
388         return block_size_is_power_of_two(pool) ?
389                 (b << pool->sectors_per_block_shift) :
390                 (b * pool->sectors_per_block);
391 }
392
393 static int issue_discard(struct thin_c *tc, dm_block_t data_b, dm_block_t data_e,
394                          struct bio *parent_bio)
395 {
396         sector_t s = block_to_sectors(tc->pool, data_b);
397         sector_t len = block_to_sectors(tc->pool, data_e - data_b);
398
399         return __blkdev_issue_discard_async(tc->pool_dev->bdev, s, len,
400                                             GFP_NOWAIT, 0, parent_bio);
401 }
402
403 /*----------------------------------------------------------------*/
404
405 /*
406  * wake_worker() is used when new work is queued and when pool_resume is
407  * ready to continue deferred IO processing.
408  */
409 static void wake_worker(struct pool *pool)
410 {
411         queue_work(pool->wq, &pool->worker);
412 }
413
414 /*----------------------------------------------------------------*/
415
416 static int bio_detain(struct pool *pool, struct dm_cell_key *key, struct bio *bio,
417                       struct dm_bio_prison_cell **cell_result)
418 {
419         int r;
420         struct dm_bio_prison_cell *cell_prealloc;
421
422         /*
423          * Allocate a cell from the prison's mempool.
424          * This might block but it can't fail.
425          */
426         cell_prealloc = dm_bio_prison_alloc_cell(pool->prison, GFP_NOIO);
427
428         r = dm_bio_detain(pool->prison, key, bio, cell_prealloc, cell_result);
429         if (r)
430                 /*
431                  * We reused an old cell; we can get rid of
432                  * the new one.
433                  */
434                 dm_bio_prison_free_cell(pool->prison, cell_prealloc);
435
436         return r;
437 }
438
439 static void cell_release(struct pool *pool,
440                          struct dm_bio_prison_cell *cell,
441                          struct bio_list *bios)
442 {
443         dm_cell_release(pool->prison, cell, bios);
444         dm_bio_prison_free_cell(pool->prison, cell);
445 }
446
447 static void cell_visit_release(struct pool *pool,
448                                void (*fn)(void *, struct dm_bio_prison_cell *),
449                                void *context,
450                                struct dm_bio_prison_cell *cell)
451 {
452         dm_cell_visit_release(pool->prison, fn, context, cell);
453         dm_bio_prison_free_cell(pool->prison, cell);
454 }
455
456 static void cell_release_no_holder(struct pool *pool,
457                                    struct dm_bio_prison_cell *cell,
458                                    struct bio_list *bios)
459 {
460         dm_cell_release_no_holder(pool->prison, cell, bios);
461         dm_bio_prison_free_cell(pool->prison, cell);
462 }
463
464 static void cell_error_with_code(struct pool *pool,
465                                  struct dm_bio_prison_cell *cell, int error_code)
466 {
467         dm_cell_error(pool->prison, cell, error_code);
468         dm_bio_prison_free_cell(pool->prison, cell);
469 }
470
471 static void cell_error(struct pool *pool, struct dm_bio_prison_cell *cell)
472 {
473         cell_error_with_code(pool, cell, -EIO);
474 }
475
476 static void cell_success(struct pool *pool, struct dm_bio_prison_cell *cell)
477 {
478         cell_error_with_code(pool, cell, 0);
479 }
480
481 static void cell_requeue(struct pool *pool, struct dm_bio_prison_cell *cell)
482 {
483         cell_error_with_code(pool, cell, DM_ENDIO_REQUEUE);
484 }
485
486 /*----------------------------------------------------------------*/
487
488 /*
489  * A global list of pools that uses a struct mapped_device as a key.
490  */
491 static struct dm_thin_pool_table {
492         struct mutex mutex;
493         struct list_head pools;
494 } dm_thin_pool_table;
495
496 static void pool_table_init(void)
497 {
498         mutex_init(&dm_thin_pool_table.mutex);
499         INIT_LIST_HEAD(&dm_thin_pool_table.pools);
500 }
501
502 static void __pool_table_insert(struct pool *pool)
503 {
504         BUG_ON(!mutex_is_locked(&dm_thin_pool_table.mutex));
505         list_add(&pool->list, &dm_thin_pool_table.pools);
506 }
507
508 static void __pool_table_remove(struct pool *pool)
509 {
510         BUG_ON(!mutex_is_locked(&dm_thin_pool_table.mutex));
511         list_del(&pool->list);
512 }
513
514 static struct pool *__pool_table_lookup(struct mapped_device *md)
515 {
516         struct pool *pool = NULL, *tmp;
517
518         BUG_ON(!mutex_is_locked(&dm_thin_pool_table.mutex));
519
520         list_for_each_entry(tmp, &dm_thin_pool_table.pools, list) {
521                 if (tmp->pool_md == md) {
522                         pool = tmp;
523                         break;
524                 }
525         }
526
527         return pool;
528 }
529
530 static struct pool *__pool_table_lookup_metadata_dev(struct block_device *md_dev)
531 {
532         struct pool *pool = NULL, *tmp;
533
534         BUG_ON(!mutex_is_locked(&dm_thin_pool_table.mutex));
535
536         list_for_each_entry(tmp, &dm_thin_pool_table.pools, list) {
537                 if (tmp->md_dev == md_dev) {
538                         pool = tmp;
539                         break;
540                 }
541         }
542
543         return pool;
544 }
545
546 /*----------------------------------------------------------------*/
547
548 struct dm_thin_endio_hook {
549         struct thin_c *tc;
550         struct dm_deferred_entry *shared_read_entry;
551         struct dm_deferred_entry *all_io_entry;
552         struct dm_thin_new_mapping *overwrite_mapping;
553         struct rb_node rb_node;
554         struct dm_bio_prison_cell *cell;
555 };
556
557 static void __merge_bio_list(struct bio_list *bios, struct bio_list *master)
558 {
559         bio_list_merge(bios, master);
560         bio_list_init(master);
561 }
562
563 static void error_bio_list(struct bio_list *bios, int error)
564 {
565         struct bio *bio;
566
567         while ((bio = bio_list_pop(bios))) {
568                 bio->bi_error = error;
569                 bio_endio(bio);
570         }
571 }
572
573 static void error_thin_bio_list(struct thin_c *tc, struct bio_list *master, int error)
574 {
575         struct bio_list bios;
576         unsigned long flags;
577
578         bio_list_init(&bios);
579
580         spin_lock_irqsave(&tc->lock, flags);
581         __merge_bio_list(&bios, master);
582         spin_unlock_irqrestore(&tc->lock, flags);
583
584         error_bio_list(&bios, error);
585 }
586
587 static void requeue_deferred_cells(struct thin_c *tc)
588 {
589         struct pool *pool = tc->pool;
590         unsigned long flags;
591         struct list_head cells;
592         struct dm_bio_prison_cell *cell, *tmp;
593
594         INIT_LIST_HEAD(&cells);
595
596         spin_lock_irqsave(&tc->lock, flags);
597         list_splice_init(&tc->deferred_cells, &cells);
598         spin_unlock_irqrestore(&tc->lock, flags);
599
600         list_for_each_entry_safe(cell, tmp, &cells, user_list)
601                 cell_requeue(pool, cell);
602 }
603
604 static void requeue_io(struct thin_c *tc)
605 {
606         struct bio_list bios;
607         unsigned long flags;
608
609         bio_list_init(&bios);
610
611         spin_lock_irqsave(&tc->lock, flags);
612         __merge_bio_list(&bios, &tc->deferred_bio_list);
613         __merge_bio_list(&bios, &tc->retry_on_resume_list);
614         spin_unlock_irqrestore(&tc->lock, flags);
615
616         error_bio_list(&bios, DM_ENDIO_REQUEUE);
617         requeue_deferred_cells(tc);
618 }
619
620 static void error_retry_list_with_code(struct pool *pool, int error)
621 {
622         struct thin_c *tc;
623
624         rcu_read_lock();
625         list_for_each_entry_rcu(tc, &pool->active_thins, list)
626                 error_thin_bio_list(tc, &tc->retry_on_resume_list, error);
627         rcu_read_unlock();
628 }
629
630 static void error_retry_list(struct pool *pool)
631 {
632         return error_retry_list_with_code(pool, -EIO);
633 }
634
635 /*
636  * This section of code contains the logic for processing a thin device's IO.
637  * Much of the code depends on pool object resources (lists, workqueues, etc)
638  * but most is exclusively called from the thin target rather than the thin-pool
639  * target.
640  */
641
642 static dm_block_t get_bio_block(struct thin_c *tc, struct bio *bio)
643 {
644         struct pool *pool = tc->pool;
645         sector_t block_nr = bio->bi_iter.bi_sector;
646
647         if (block_size_is_power_of_two(pool))
648                 block_nr >>= pool->sectors_per_block_shift;
649         else
650                 (void) sector_div(block_nr, pool->sectors_per_block);
651
652         return block_nr;
653 }
654
655 /*
656  * Returns the _complete_ blocks that this bio covers.
657  */
658 static void get_bio_block_range(struct thin_c *tc, struct bio *bio,
659                                 dm_block_t *begin, dm_block_t *end)
660 {
661         struct pool *pool = tc->pool;
662         sector_t b = bio->bi_iter.bi_sector;
663         sector_t e = b + (bio->bi_iter.bi_size >> SECTOR_SHIFT);
664
665         b += pool->sectors_per_block - 1ull; /* so we round up */
666
667         if (block_size_is_power_of_two(pool)) {
668                 b >>= pool->sectors_per_block_shift;
669                 e >>= pool->sectors_per_block_shift;
670         } else {
671                 (void) sector_div(b, pool->sectors_per_block);
672                 (void) sector_div(e, pool->sectors_per_block);
673         }
674
675         if (e < b)
676                 /* Can happen if the bio is within a single block. */
677                 e = b;
678
679         *begin = b;
680         *end = e;
681 }
682
683 static void remap(struct thin_c *tc, struct bio *bio, dm_block_t block)
684 {
685         struct pool *pool = tc->pool;
686         sector_t bi_sector = bio->bi_iter.bi_sector;
687
688         bio->bi_bdev = tc->pool_dev->bdev;
689         if (block_size_is_power_of_two(pool))
690                 bio->bi_iter.bi_sector =
691                         (block << pool->sectors_per_block_shift) |
692                         (bi_sector & (pool->sectors_per_block - 1));
693         else
694                 bio->bi_iter.bi_sector = (block * pool->sectors_per_block) +
695                                  sector_div(bi_sector, pool->sectors_per_block);
696 }
697
698 static void remap_to_origin(struct thin_c *tc, struct bio *bio)
699 {
700         bio->bi_bdev = tc->origin_dev->bdev;
701 }
702
703 static int bio_triggers_commit(struct thin_c *tc, struct bio *bio)
704 {
705         return (bio->bi_rw & (REQ_FLUSH | REQ_FUA)) &&
706                 dm_thin_changed_this_transaction(tc->td);
707 }
708
709 static void inc_all_io_entry(struct pool *pool, struct bio *bio)
710 {
711         struct dm_thin_endio_hook *h;
712
713         if (bio->bi_rw & REQ_DISCARD)
714                 return;
715
716         h = dm_per_bio_data(bio, sizeof(struct dm_thin_endio_hook));
717         h->all_io_entry = dm_deferred_entry_inc(pool->all_io_ds);
718 }
719
720 static void issue(struct thin_c *tc, struct bio *bio)
721 {
722         struct pool *pool = tc->pool;
723         unsigned long flags;
724
725         if (!bio_triggers_commit(tc, bio)) {
726                 generic_make_request(bio);
727                 return;
728         }
729
730         /*
731          * Complete bio with an error if earlier I/O caused changes to
732          * the metadata that can't be committed e.g, due to I/O errors
733          * on the metadata device.
734          */
735         if (dm_thin_aborted_changes(tc->td)) {
736                 bio_io_error(bio);
737                 return;
738         }
739
740         /*
741          * Batch together any bios that trigger commits and then issue a
742          * single commit for them in process_deferred_bios().
743          */
744         spin_lock_irqsave(&pool->lock, flags);
745         bio_list_add(&pool->deferred_flush_bios, bio);
746         spin_unlock_irqrestore(&pool->lock, flags);
747 }
748
749 static void remap_to_origin_and_issue(struct thin_c *tc, struct bio *bio)
750 {
751         remap_to_origin(tc, bio);
752         issue(tc, bio);
753 }
754
755 static void remap_and_issue(struct thin_c *tc, struct bio *bio,
756                             dm_block_t block)
757 {
758         remap(tc, bio, block);
759         issue(tc, bio);
760 }
761
762 /*----------------------------------------------------------------*/
763
764 /*
765  * Bio endio functions.
766  */
767 struct dm_thin_new_mapping {
768         struct list_head list;
769
770         bool pass_discard:1;
771         bool maybe_shared:1;
772
773         /*
774          * Track quiescing, copying and zeroing preparation actions.  When this
775          * counter hits zero the block is prepared and can be inserted into the
776          * btree.
777          */
778         atomic_t prepare_actions;
779
780         int err;
781         struct thin_c *tc;
782         dm_block_t virt_begin, virt_end;
783         dm_block_t data_block;
784         struct dm_bio_prison_cell *cell;
785
786         /*
787          * If the bio covers the whole area of a block then we can avoid
788          * zeroing or copying.  Instead this bio is hooked.  The bio will
789          * still be in the cell, so care has to be taken to avoid issuing
790          * the bio twice.
791          */
792         struct bio *bio;
793         bio_end_io_t *saved_bi_end_io;
794 };
795
796 static void __complete_mapping_preparation(struct dm_thin_new_mapping *m)
797 {
798         struct pool *pool = m->tc->pool;
799
800         if (atomic_dec_and_test(&m->prepare_actions)) {
801                 list_add_tail(&m->list, &pool->prepared_mappings);
802                 wake_worker(pool);
803         }
804 }
805
806 static void complete_mapping_preparation(struct dm_thin_new_mapping *m)
807 {
808         unsigned long flags;
809         struct pool *pool = m->tc->pool;
810
811         spin_lock_irqsave(&pool->lock, flags);
812         __complete_mapping_preparation(m);
813         spin_unlock_irqrestore(&pool->lock, flags);
814 }
815
816 static void copy_complete(int read_err, unsigned long write_err, void *context)
817 {
818         struct dm_thin_new_mapping *m = context;
819
820         m->err = read_err || write_err ? -EIO : 0;
821         complete_mapping_preparation(m);
822 }
823
824 static void overwrite_endio(struct bio *bio)
825 {
826         struct dm_thin_endio_hook *h = dm_per_bio_data(bio, sizeof(struct dm_thin_endio_hook));
827         struct dm_thin_new_mapping *m = h->overwrite_mapping;
828
829         bio->bi_end_io = m->saved_bi_end_io;
830
831         m->err = bio->bi_error;
832         complete_mapping_preparation(m);
833 }
834
835 /*----------------------------------------------------------------*/
836
837 /*
838  * Workqueue.
839  */
840
841 /*
842  * Prepared mapping jobs.
843  */
844
845 /*
846  * This sends the bios in the cell, except the original holder, back
847  * to the deferred_bios list.
848  */
849 static void cell_defer_no_holder(struct thin_c *tc, struct dm_bio_prison_cell *cell)
850 {
851         struct pool *pool = tc->pool;
852         unsigned long flags;
853
854         spin_lock_irqsave(&tc->lock, flags);
855         cell_release_no_holder(pool, cell, &tc->deferred_bio_list);
856         spin_unlock_irqrestore(&tc->lock, flags);
857
858         wake_worker(pool);
859 }
860
861 static void thin_defer_bio(struct thin_c *tc, struct bio *bio);
862
863 struct remap_info {
864         struct thin_c *tc;
865         struct bio_list defer_bios;
866         struct bio_list issue_bios;
867 };
868
869 static void __inc_remap_and_issue_cell(void *context,
870                                        struct dm_bio_prison_cell *cell)
871 {
872         struct remap_info *info = context;
873         struct bio *bio;
874
875         while ((bio = bio_list_pop(&cell->bios))) {
876                 if (bio->bi_rw & (REQ_DISCARD | REQ_FLUSH | REQ_FUA))
877                         bio_list_add(&info->defer_bios, bio);
878                 else {
879                         inc_all_io_entry(info->tc->pool, bio);
880
881                         /*
882                          * We can't issue the bios with the bio prison lock
883                          * held, so we add them to a list to issue on
884                          * return from this function.
885                          */
886                         bio_list_add(&info->issue_bios, bio);
887                 }
888         }
889 }
890
891 static void inc_remap_and_issue_cell(struct thin_c *tc,
892                                      struct dm_bio_prison_cell *cell,
893                                      dm_block_t block)
894 {
895         struct bio *bio;
896         struct remap_info info;
897
898         info.tc = tc;
899         bio_list_init(&info.defer_bios);
900         bio_list_init(&info.issue_bios);
901
902         /*
903          * We have to be careful to inc any bios we're about to issue
904          * before the cell is released, and avoid a race with new bios
905          * being added to the cell.
906          */
907         cell_visit_release(tc->pool, __inc_remap_and_issue_cell,
908                            &info, cell);
909
910         while ((bio = bio_list_pop(&info.defer_bios)))
911                 thin_defer_bio(tc, bio);
912
913         while ((bio = bio_list_pop(&info.issue_bios)))
914                 remap_and_issue(info.tc, bio, block);
915 }
916
917 static void process_prepared_mapping_fail(struct dm_thin_new_mapping *m)
918 {
919         cell_error(m->tc->pool, m->cell);
920         list_del(&m->list);
921         mempool_free(m, m->tc->pool->mapping_pool);
922 }
923
924 static void complete_overwrite_bio(struct thin_c *tc, struct bio *bio)
925 {
926         struct pool *pool = tc->pool;
927         unsigned long flags;
928
929         /*
930          * If the bio has the REQ_FUA flag set we must commit the metadata
931          * before signaling its completion.
932          */
933         if (!bio_triggers_commit(tc, bio)) {
934                 bio_endio(bio);
935                 return;
936         }
937
938         /*
939          * Complete bio with an error if earlier I/O caused changes to the
940          * metadata that can't be committed, e.g, due to I/O errors on the
941          * metadata device.
942          */
943         if (dm_thin_aborted_changes(tc->td)) {
944                 bio_io_error(bio);
945                 return;
946         }
947
948         /*
949          * Batch together any bios that trigger commits and then issue a
950          * single commit for them in process_deferred_bios().
951          */
952         spin_lock_irqsave(&pool->lock, flags);
953         bio_list_add(&pool->deferred_flush_completions, bio);
954         spin_unlock_irqrestore(&pool->lock, flags);
955 }
956
957 static void process_prepared_mapping(struct dm_thin_new_mapping *m)
958 {
959         struct thin_c *tc = m->tc;
960         struct pool *pool = tc->pool;
961         struct bio *bio = m->bio;
962         int r;
963
964         if (m->err) {
965                 cell_error(pool, m->cell);
966                 goto out;
967         }
968
969         /*
970          * Commit the prepared block into the mapping btree.
971          * Any I/O for this block arriving after this point will get
972          * remapped to it directly.
973          */
974         r = dm_thin_insert_block(tc->td, m->virt_begin, m->data_block);
975         if (r) {
976                 metadata_operation_failed(pool, "dm_thin_insert_block", r);
977                 cell_error(pool, m->cell);
978                 goto out;
979         }
980
981         /*
982          * Release any bios held while the block was being provisioned.
983          * If we are processing a write bio that completely covers the block,
984          * we already processed it so can ignore it now when processing
985          * the bios in the cell.
986          */
987         if (bio) {
988                 inc_remap_and_issue_cell(tc, m->cell, m->data_block);
989                 complete_overwrite_bio(tc, bio);
990         } else {
991                 inc_all_io_entry(tc->pool, m->cell->holder);
992                 remap_and_issue(tc, m->cell->holder, m->data_block);
993                 inc_remap_and_issue_cell(tc, m->cell, m->data_block);
994         }
995
996 out:
997         list_del(&m->list);
998         mempool_free(m, pool->mapping_pool);
999 }
1000
1001 /*----------------------------------------------------------------*/
1002
1003 static void free_discard_mapping(struct dm_thin_new_mapping *m)
1004 {
1005         struct thin_c *tc = m->tc;
1006         if (m->cell)
1007                 cell_defer_no_holder(tc, m->cell);
1008         mempool_free(m, tc->pool->mapping_pool);
1009 }
1010
1011 static void process_prepared_discard_fail(struct dm_thin_new_mapping *m)
1012 {
1013         bio_io_error(m->bio);
1014         free_discard_mapping(m);
1015 }
1016
1017 static void process_prepared_discard_success(struct dm_thin_new_mapping *m)
1018 {
1019         bio_endio(m->bio);
1020         free_discard_mapping(m);
1021 }
1022
1023 static void process_prepared_discard_no_passdown(struct dm_thin_new_mapping *m)
1024 {
1025         int r;
1026         struct thin_c *tc = m->tc;
1027
1028         r = dm_thin_remove_range(tc->td, m->cell->key.block_begin, m->cell->key.block_end);
1029         if (r) {
1030                 metadata_operation_failed(tc->pool, "dm_thin_remove_range", r);
1031                 bio_io_error(m->bio);
1032         } else
1033                 bio_endio(m->bio);
1034
1035         cell_defer_no_holder(tc, m->cell);
1036         mempool_free(m, tc->pool->mapping_pool);
1037 }
1038
1039 static int passdown_double_checking_shared_status(struct dm_thin_new_mapping *m)
1040 {
1041         /*
1042          * We've already unmapped this range of blocks, but before we
1043          * passdown we have to check that these blocks are now unused.
1044          */
1045         int r;
1046         bool used = true;
1047         struct thin_c *tc = m->tc;
1048         struct pool *pool = tc->pool;
1049         dm_block_t b = m->data_block, e, end = m->data_block + m->virt_end - m->virt_begin;
1050
1051         while (b != end) {
1052                 /* find start of unmapped run */
1053                 for (; b < end; b++) {
1054                         r = dm_pool_block_is_used(pool->pmd, b, &used);
1055                         if (r)
1056                                 return r;
1057
1058                         if (!used)
1059                                 break;
1060                 }
1061
1062                 if (b == end)
1063                         break;
1064
1065                 /* find end of run */
1066                 for (e = b + 1; e != end; e++) {
1067                         r = dm_pool_block_is_used(pool->pmd, e, &used);
1068                         if (r)
1069                                 return r;
1070
1071                         if (used)
1072                                 break;
1073                 }
1074
1075                 r = issue_discard(tc, b, e, m->bio);
1076                 if (r)
1077                         return r;
1078
1079                 b = e;
1080         }
1081
1082         return 0;
1083 }
1084
1085 static void process_prepared_discard_passdown(struct dm_thin_new_mapping *m)
1086 {
1087         int r;
1088         struct thin_c *tc = m->tc;
1089         struct pool *pool = tc->pool;
1090
1091         r = dm_thin_remove_range(tc->td, m->virt_begin, m->virt_end);
1092         if (r)
1093                 metadata_operation_failed(pool, "dm_thin_remove_range", r);
1094
1095         else if (m->maybe_shared)
1096                 r = passdown_double_checking_shared_status(m);
1097         else
1098                 r = issue_discard(tc, m->data_block, m->data_block + (m->virt_end - m->virt_begin), m->bio);
1099
1100         /*
1101          * Even if r is set, there could be sub discards in flight that we
1102          * need to wait for.
1103          */
1104         m->bio->bi_error = r;
1105         bio_endio(m->bio);
1106         cell_defer_no_holder(tc, m->cell);
1107         mempool_free(m, pool->mapping_pool);
1108 }
1109
1110 static void process_prepared(struct pool *pool, struct list_head *head,
1111                              process_mapping_fn *fn)
1112 {
1113         unsigned long flags;
1114         struct list_head maps;
1115         struct dm_thin_new_mapping *m, *tmp;
1116
1117         INIT_LIST_HEAD(&maps);
1118         spin_lock_irqsave(&pool->lock, flags);
1119         list_splice_init(head, &maps);
1120         spin_unlock_irqrestore(&pool->lock, flags);
1121
1122         list_for_each_entry_safe(m, tmp, &maps, list)
1123                 (*fn)(m);
1124 }
1125
1126 /*
1127  * Deferred bio jobs.
1128  */
1129 static int io_overlaps_block(struct pool *pool, struct bio *bio)
1130 {
1131         return bio->bi_iter.bi_size ==
1132                 (pool->sectors_per_block << SECTOR_SHIFT);
1133 }
1134
1135 static int io_overwrites_block(struct pool *pool, struct bio *bio)
1136 {
1137         return (bio_data_dir(bio) == WRITE) &&
1138                 io_overlaps_block(pool, bio);
1139 }
1140
1141 static void save_and_set_endio(struct bio *bio, bio_end_io_t **save,
1142                                bio_end_io_t *fn)
1143 {
1144         *save = bio->bi_end_io;
1145         bio->bi_end_io = fn;
1146 }
1147
1148 static int ensure_next_mapping(struct pool *pool)
1149 {
1150         if (pool->next_mapping)
1151                 return 0;
1152
1153         pool->next_mapping = mempool_alloc(pool->mapping_pool, GFP_ATOMIC);
1154
1155         return pool->next_mapping ? 0 : -ENOMEM;
1156 }
1157
1158 static struct dm_thin_new_mapping *get_next_mapping(struct pool *pool)
1159 {
1160         struct dm_thin_new_mapping *m = pool->next_mapping;
1161
1162         BUG_ON(!pool->next_mapping);
1163
1164         memset(m, 0, sizeof(struct dm_thin_new_mapping));
1165         INIT_LIST_HEAD(&m->list);
1166         m->bio = NULL;
1167
1168         pool->next_mapping = NULL;
1169
1170         return m;
1171 }
1172
1173 static void ll_zero(struct thin_c *tc, struct dm_thin_new_mapping *m,
1174                     sector_t begin, sector_t end)
1175 {
1176         int r;
1177         struct dm_io_region to;
1178
1179         to.bdev = tc->pool_dev->bdev;
1180         to.sector = begin;
1181         to.count = end - begin;
1182
1183         r = dm_kcopyd_zero(tc->pool->copier, 1, &to, 0, copy_complete, m);
1184         if (r < 0) {
1185                 DMERR_LIMIT("dm_kcopyd_zero() failed");
1186                 copy_complete(1, 1, m);
1187         }
1188 }
1189
1190 static void remap_and_issue_overwrite(struct thin_c *tc, struct bio *bio,
1191                                       dm_block_t data_begin,
1192                                       struct dm_thin_new_mapping *m)
1193 {
1194         struct pool *pool = tc->pool;
1195         struct dm_thin_endio_hook *h = dm_per_bio_data(bio, sizeof(struct dm_thin_endio_hook));
1196
1197         h->overwrite_mapping = m;
1198         m->bio = bio;
1199         save_and_set_endio(bio, &m->saved_bi_end_io, overwrite_endio);
1200         inc_all_io_entry(pool, bio);
1201         remap_and_issue(tc, bio, data_begin);
1202 }
1203
1204 /*
1205  * A partial copy also needs to zero the uncopied region.
1206  */
1207 static void schedule_copy(struct thin_c *tc, dm_block_t virt_block,
1208                           struct dm_dev *origin, dm_block_t data_origin,
1209                           dm_block_t data_dest,
1210                           struct dm_bio_prison_cell *cell, struct bio *bio,
1211                           sector_t len)
1212 {
1213         int r;
1214         struct pool *pool = tc->pool;
1215         struct dm_thin_new_mapping *m = get_next_mapping(pool);
1216
1217         m->tc = tc;
1218         m->virt_begin = virt_block;
1219         m->virt_end = virt_block + 1u;
1220         m->data_block = data_dest;
1221         m->cell = cell;
1222
1223         /*
1224          * quiesce action + copy action + an extra reference held for the
1225          * duration of this function (we may need to inc later for a
1226          * partial zero).
1227          */
1228         atomic_set(&m->prepare_actions, 3);
1229
1230         if (!dm_deferred_set_add_work(pool->shared_read_ds, &m->list))
1231                 complete_mapping_preparation(m); /* already quiesced */
1232
1233         /*
1234          * IO to pool_dev remaps to the pool target's data_dev.
1235          *
1236          * If the whole block of data is being overwritten, we can issue the
1237          * bio immediately. Otherwise we use kcopyd to clone the data first.
1238          */
1239         if (io_overwrites_block(pool, bio))
1240                 remap_and_issue_overwrite(tc, bio, data_dest, m);
1241         else {
1242                 struct dm_io_region from, to;
1243
1244                 from.bdev = origin->bdev;
1245                 from.sector = data_origin * pool->sectors_per_block;
1246                 from.count = len;
1247
1248                 to.bdev = tc->pool_dev->bdev;
1249                 to.sector = data_dest * pool->sectors_per_block;
1250                 to.count = len;
1251
1252                 r = dm_kcopyd_copy(pool->copier, &from, 1, &to,
1253                                    0, copy_complete, m);
1254                 if (r < 0) {
1255                         DMERR_LIMIT("dm_kcopyd_copy() failed");
1256                         copy_complete(1, 1, m);
1257
1258                         /*
1259                          * We allow the zero to be issued, to simplify the
1260                          * error path.  Otherwise we'd need to start
1261                          * worrying about decrementing the prepare_actions
1262                          * counter.
1263                          */
1264                 }
1265
1266                 /*
1267                  * Do we need to zero a tail region?
1268                  */
1269                 if (len < pool->sectors_per_block && pool->pf.zero_new_blocks) {
1270                         atomic_inc(&m->prepare_actions);
1271                         ll_zero(tc, m,
1272                                 data_dest * pool->sectors_per_block + len,
1273                                 (data_dest + 1) * pool->sectors_per_block);
1274                 }
1275         }
1276
1277         complete_mapping_preparation(m); /* drop our ref */
1278 }
1279
1280 static void schedule_internal_copy(struct thin_c *tc, dm_block_t virt_block,
1281                                    dm_block_t data_origin, dm_block_t data_dest,
1282                                    struct dm_bio_prison_cell *cell, struct bio *bio)
1283 {
1284         schedule_copy(tc, virt_block, tc->pool_dev,
1285                       data_origin, data_dest, cell, bio,
1286                       tc->pool->sectors_per_block);
1287 }
1288
1289 static void schedule_zero(struct thin_c *tc, dm_block_t virt_block,
1290                           dm_block_t data_block, struct dm_bio_prison_cell *cell,
1291                           struct bio *bio)
1292 {
1293         struct pool *pool = tc->pool;
1294         struct dm_thin_new_mapping *m = get_next_mapping(pool);
1295
1296         atomic_set(&m->prepare_actions, 1); /* no need to quiesce */
1297         m->tc = tc;
1298         m->virt_begin = virt_block;
1299         m->virt_end = virt_block + 1u;
1300         m->data_block = data_block;
1301         m->cell = cell;
1302
1303         /*
1304          * If the whole block of data is being overwritten or we are not
1305          * zeroing pre-existing data, we can issue the bio immediately.
1306          * Otherwise we use kcopyd to zero the data first.
1307          */
1308         if (pool->pf.zero_new_blocks) {
1309                 if (io_overwrites_block(pool, bio))
1310                         remap_and_issue_overwrite(tc, bio, data_block, m);
1311                 else
1312                         ll_zero(tc, m, data_block * pool->sectors_per_block,
1313                                 (data_block + 1) * pool->sectors_per_block);
1314         } else
1315                 process_prepared_mapping(m);
1316 }
1317
1318 static void schedule_external_copy(struct thin_c *tc, dm_block_t virt_block,
1319                                    dm_block_t data_dest,
1320                                    struct dm_bio_prison_cell *cell, struct bio *bio)
1321 {
1322         struct pool *pool = tc->pool;
1323         sector_t virt_block_begin = virt_block * pool->sectors_per_block;
1324         sector_t virt_block_end = (virt_block + 1) * pool->sectors_per_block;
1325
1326         if (virt_block_end <= tc->origin_size)
1327                 schedule_copy(tc, virt_block, tc->origin_dev,
1328                               virt_block, data_dest, cell, bio,
1329                               pool->sectors_per_block);
1330
1331         else if (virt_block_begin < tc->origin_size)
1332                 schedule_copy(tc, virt_block, tc->origin_dev,
1333                               virt_block, data_dest, cell, bio,
1334                               tc->origin_size - virt_block_begin);
1335
1336         else
1337                 schedule_zero(tc, virt_block, data_dest, cell, bio);
1338 }
1339
1340 static void set_pool_mode(struct pool *pool, enum pool_mode new_mode);
1341
1342 static void requeue_bios(struct pool *pool);
1343
1344 static bool is_read_only_pool_mode(enum pool_mode mode)
1345 {
1346         return (mode == PM_OUT_OF_METADATA_SPACE || mode == PM_READ_ONLY);
1347 }
1348
1349 static bool is_read_only(struct pool *pool)
1350 {
1351         return is_read_only_pool_mode(get_pool_mode(pool));
1352 }
1353
1354 static void check_for_metadata_space(struct pool *pool)
1355 {
1356         int r;
1357         const char *ooms_reason = NULL;
1358         dm_block_t nr_free;
1359
1360         r = dm_pool_get_free_metadata_block_count(pool->pmd, &nr_free);
1361         if (r)
1362                 ooms_reason = "Could not get free metadata blocks";
1363         else if (!nr_free)
1364                 ooms_reason = "No free metadata blocks";
1365
1366         if (ooms_reason && !is_read_only(pool)) {
1367                 DMERR("%s", ooms_reason);
1368                 set_pool_mode(pool, PM_OUT_OF_METADATA_SPACE);
1369         }
1370 }
1371
1372 static void check_for_data_space(struct pool *pool)
1373 {
1374         int r;
1375         dm_block_t nr_free;
1376
1377         if (get_pool_mode(pool) != PM_OUT_OF_DATA_SPACE)
1378                 return;
1379
1380         r = dm_pool_get_free_block_count(pool->pmd, &nr_free);
1381         if (r)
1382                 return;
1383
1384         if (nr_free) {
1385                 set_pool_mode(pool, PM_WRITE);
1386                 requeue_bios(pool);
1387         }
1388 }
1389
1390 /*
1391  * A non-zero return indicates read_only or fail_io mode.
1392  * Many callers don't care about the return value.
1393  */
1394 static int commit(struct pool *pool)
1395 {
1396         int r;
1397
1398         if (get_pool_mode(pool) >= PM_OUT_OF_METADATA_SPACE)
1399                 return -EINVAL;
1400
1401         r = dm_pool_commit_metadata(pool->pmd);
1402         if (r)
1403                 metadata_operation_failed(pool, "dm_pool_commit_metadata", r);
1404         else {
1405                 check_for_metadata_space(pool);
1406                 check_for_data_space(pool);
1407         }
1408
1409         return r;
1410 }
1411
1412 static void check_low_water_mark(struct pool *pool, dm_block_t free_blocks)
1413 {
1414         unsigned long flags;
1415
1416         if (free_blocks <= pool->low_water_blocks && !pool->low_water_triggered) {
1417                 DMWARN("%s: reached low water mark for data device: sending event.",
1418                        dm_device_name(pool->pool_md));
1419                 spin_lock_irqsave(&pool->lock, flags);
1420                 pool->low_water_triggered = true;
1421                 spin_unlock_irqrestore(&pool->lock, flags);
1422                 dm_table_event(pool->ti->table);
1423         }
1424 }
1425
1426 static int alloc_data_block(struct thin_c *tc, dm_block_t *result)
1427 {
1428         int r;
1429         dm_block_t free_blocks;
1430         struct pool *pool = tc->pool;
1431
1432         if (WARN_ON(get_pool_mode(pool) != PM_WRITE))
1433                 return -EINVAL;
1434
1435         r = dm_pool_get_free_block_count(pool->pmd, &free_blocks);
1436         if (r) {
1437                 metadata_operation_failed(pool, "dm_pool_get_free_block_count", r);
1438                 return r;
1439         }
1440
1441         check_low_water_mark(pool, free_blocks);
1442
1443         if (!free_blocks) {
1444                 /*
1445                  * Try to commit to see if that will free up some
1446                  * more space.
1447                  */
1448                 r = commit(pool);
1449                 if (r)
1450                         return r;
1451
1452                 r = dm_pool_get_free_block_count(pool->pmd, &free_blocks);
1453                 if (r) {
1454                         metadata_operation_failed(pool, "dm_pool_get_free_block_count", r);
1455                         return r;
1456                 }
1457
1458                 if (!free_blocks) {
1459                         set_pool_mode(pool, PM_OUT_OF_DATA_SPACE);
1460                         return -ENOSPC;
1461                 }
1462         }
1463
1464         r = dm_pool_alloc_data_block(pool->pmd, result);
1465         if (r) {
1466                 if (r == -ENOSPC)
1467                         set_pool_mode(pool, PM_OUT_OF_DATA_SPACE);
1468                 else
1469                         metadata_operation_failed(pool, "dm_pool_alloc_data_block", r);
1470                 return r;
1471         }
1472
1473         r = dm_pool_get_free_metadata_block_count(pool->pmd, &free_blocks);
1474         if (r) {
1475                 metadata_operation_failed(pool, "dm_pool_get_free_metadata_block_count", r);
1476                 return r;
1477         }
1478
1479         if (!free_blocks) {
1480                 /* Let's commit before we use up the metadata reserve. */
1481                 r = commit(pool);
1482                 if (r)
1483                         return r;
1484         }
1485
1486         return 0;
1487 }
1488
1489 /*
1490  * If we have run out of space, queue bios until the device is
1491  * resumed, presumably after having been reloaded with more space.
1492  */
1493 static void retry_on_resume(struct bio *bio)
1494 {
1495         struct dm_thin_endio_hook *h = dm_per_bio_data(bio, sizeof(struct dm_thin_endio_hook));
1496         struct thin_c *tc = h->tc;
1497         unsigned long flags;
1498
1499         spin_lock_irqsave(&tc->lock, flags);
1500         bio_list_add(&tc->retry_on_resume_list, bio);
1501         spin_unlock_irqrestore(&tc->lock, flags);
1502 }
1503
1504 static int should_error_unserviceable_bio(struct pool *pool)
1505 {
1506         enum pool_mode m = get_pool_mode(pool);
1507
1508         switch (m) {
1509         case PM_WRITE:
1510                 /* Shouldn't get here */
1511                 DMERR_LIMIT("bio unserviceable, yet pool is in PM_WRITE mode");
1512                 return -EIO;
1513
1514         case PM_OUT_OF_DATA_SPACE:
1515                 return pool->pf.error_if_no_space ? -ENOSPC : 0;
1516
1517         case PM_OUT_OF_METADATA_SPACE:
1518         case PM_READ_ONLY:
1519         case PM_FAIL:
1520                 return -EIO;
1521         default:
1522                 /* Shouldn't get here */
1523                 DMERR_LIMIT("bio unserviceable, yet pool has an unknown mode");
1524                 return -EIO;
1525         }
1526 }
1527
1528 static void handle_unserviceable_bio(struct pool *pool, struct bio *bio)
1529 {
1530         int error = should_error_unserviceable_bio(pool);
1531
1532         if (error) {
1533                 bio->bi_error = error;
1534                 bio_endio(bio);
1535         } else
1536                 retry_on_resume(bio);
1537 }
1538
1539 static void retry_bios_on_resume(struct pool *pool, struct dm_bio_prison_cell *cell)
1540 {
1541         struct bio *bio;
1542         struct bio_list bios;
1543         int error;
1544
1545         error = should_error_unserviceable_bio(pool);
1546         if (error) {
1547                 cell_error_with_code(pool, cell, error);
1548                 return;
1549         }
1550
1551         bio_list_init(&bios);
1552         cell_release(pool, cell, &bios);
1553
1554         while ((bio = bio_list_pop(&bios)))
1555                 retry_on_resume(bio);
1556 }
1557
1558 static void process_discard_cell_no_passdown(struct thin_c *tc,
1559                                              struct dm_bio_prison_cell *virt_cell)
1560 {
1561         struct pool *pool = tc->pool;
1562         struct dm_thin_new_mapping *m = get_next_mapping(pool);
1563
1564         /*
1565          * We don't need to lock the data blocks, since there's no
1566          * passdown.  We only lock data blocks for allocation and breaking sharing.
1567          */
1568         m->tc = tc;
1569         m->virt_begin = virt_cell->key.block_begin;
1570         m->virt_end = virt_cell->key.block_end;
1571         m->cell = virt_cell;
1572         m->bio = virt_cell->holder;
1573
1574         if (!dm_deferred_set_add_work(pool->all_io_ds, &m->list))
1575                 pool->process_prepared_discard(m);
1576 }
1577
1578 /*
1579  * __bio_inc_remaining() is used to defer parent bios's end_io until
1580  * we _know_ all chained sub range discard bios have completed.
1581  */
1582 static inline void __bio_inc_remaining(struct bio *bio)
1583 {
1584         bio->bi_flags |= (1 << BIO_CHAIN);
1585         smp_mb__before_atomic();
1586         atomic_inc(&bio->__bi_remaining);
1587 }
1588
1589 static void break_up_discard_bio(struct thin_c *tc, dm_block_t begin, dm_block_t end,
1590                                  struct bio *bio)
1591 {
1592         struct pool *pool = tc->pool;
1593
1594         int r;
1595         bool maybe_shared;
1596         struct dm_cell_key data_key;
1597         struct dm_bio_prison_cell *data_cell;
1598         struct dm_thin_new_mapping *m;
1599         dm_block_t virt_begin, virt_end, data_begin;
1600
1601         while (begin != end) {
1602                 r = ensure_next_mapping(pool);
1603                 if (r)
1604                         /* we did our best */
1605                         return;
1606
1607                 r = dm_thin_find_mapped_range(tc->td, begin, end, &virt_begin, &virt_end,
1608                                               &data_begin, &maybe_shared);
1609                 if (r)
1610                         /*
1611                          * Silently fail, letting any mappings we've
1612                          * created complete.
1613                          */
1614                         break;
1615
1616                 build_key(tc->td, PHYSICAL, data_begin, data_begin + (virt_end - virt_begin), &data_key);
1617                 if (bio_detain(tc->pool, &data_key, NULL, &data_cell)) {
1618                         /* contention, we'll give up with this range */
1619                         begin = virt_end;
1620                         continue;
1621                 }
1622
1623                 /*
1624                  * IO may still be going to the destination block.  We must
1625                  * quiesce before we can do the removal.
1626                  */
1627                 m = get_next_mapping(pool);
1628                 m->tc = tc;
1629                 m->maybe_shared = maybe_shared;
1630                 m->virt_begin = virt_begin;
1631                 m->virt_end = virt_end;
1632                 m->data_block = data_begin;
1633                 m->cell = data_cell;
1634                 m->bio = bio;
1635
1636                 /*
1637                  * The parent bio must not complete before sub discard bios are
1638                  * chained to it (see __blkdev_issue_discard_async's bio_chain)!
1639                  *
1640                  * This per-mapping bi_remaining increment is paired with
1641                  * the implicit decrement that occurs via bio_endio() in
1642                  * process_prepared_discard_{passdown,no_passdown}.
1643                  */
1644                 __bio_inc_remaining(bio);
1645                 if (!dm_deferred_set_add_work(pool->all_io_ds, &m->list))
1646                         pool->process_prepared_discard(m);
1647
1648                 begin = virt_end;
1649         }
1650 }
1651
1652 static void process_discard_cell_passdown(struct thin_c *tc, struct dm_bio_prison_cell *virt_cell)
1653 {
1654         struct bio *bio = virt_cell->holder;
1655         struct dm_thin_endio_hook *h = dm_per_bio_data(bio, sizeof(struct dm_thin_endio_hook));
1656
1657         /*
1658          * The virt_cell will only get freed once the origin bio completes.
1659          * This means it will remain locked while all the individual
1660          * passdown bios are in flight.
1661          */
1662         h->cell = virt_cell;
1663         break_up_discard_bio(tc, virt_cell->key.block_begin, virt_cell->key.block_end, bio);
1664
1665         /*
1666          * We complete the bio now, knowing that the bi_remaining field
1667          * will prevent completion until the sub range discards have
1668          * completed.
1669          */
1670         bio_endio(bio);
1671 }
1672
1673 static void process_discard_bio(struct thin_c *tc, struct bio *bio)
1674 {
1675         dm_block_t begin, end;
1676         struct dm_cell_key virt_key;
1677         struct dm_bio_prison_cell *virt_cell;
1678
1679         get_bio_block_range(tc, bio, &begin, &end);
1680         if (begin == end) {
1681                 /*
1682                  * The discard covers less than a block.
1683                  */
1684                 bio_endio(bio);
1685                 return;
1686         }
1687
1688         build_key(tc->td, VIRTUAL, begin, end, &virt_key);
1689         if (bio_detain(tc->pool, &virt_key, bio, &virt_cell))
1690                 /*
1691                  * Potential starvation issue: We're relying on the
1692                  * fs/application being well behaved, and not trying to
1693                  * send IO to a region at the same time as discarding it.
1694                  * If they do this persistently then it's possible this
1695                  * cell will never be granted.
1696                  */
1697                 return;
1698
1699         tc->pool->process_discard_cell(tc, virt_cell);
1700 }
1701
1702 static void break_sharing(struct thin_c *tc, struct bio *bio, dm_block_t block,
1703                           struct dm_cell_key *key,
1704                           struct dm_thin_lookup_result *lookup_result,
1705                           struct dm_bio_prison_cell *cell)
1706 {
1707         int r;
1708         dm_block_t data_block;
1709         struct pool *pool = tc->pool;
1710
1711         r = alloc_data_block(tc, &data_block);
1712         switch (r) {
1713         case 0:
1714                 schedule_internal_copy(tc, block, lookup_result->block,
1715                                        data_block, cell, bio);
1716                 break;
1717
1718         case -ENOSPC:
1719                 retry_bios_on_resume(pool, cell);
1720                 break;
1721
1722         default:
1723                 DMERR_LIMIT("%s: alloc_data_block() failed: error = %d",
1724                             __func__, r);
1725                 cell_error(pool, cell);
1726                 break;
1727         }
1728 }
1729
1730 static void __remap_and_issue_shared_cell(void *context,
1731                                           struct dm_bio_prison_cell *cell)
1732 {
1733         struct remap_info *info = context;
1734         struct bio *bio;
1735
1736         while ((bio = bio_list_pop(&cell->bios))) {
1737                 if ((bio_data_dir(bio) == WRITE) ||
1738                     (bio->bi_rw & (REQ_DISCARD | REQ_FLUSH | REQ_FUA)))
1739                         bio_list_add(&info->defer_bios, bio);
1740                 else {
1741                         struct dm_thin_endio_hook *h = dm_per_bio_data(bio, sizeof(struct dm_thin_endio_hook));;
1742
1743                         h->shared_read_entry = dm_deferred_entry_inc(info->tc->pool->shared_read_ds);
1744                         inc_all_io_entry(info->tc->pool, bio);
1745                         bio_list_add(&info->issue_bios, bio);
1746                 }
1747         }
1748 }
1749
1750 static void remap_and_issue_shared_cell(struct thin_c *tc,
1751                                         struct dm_bio_prison_cell *cell,
1752                                         dm_block_t block)
1753 {
1754         struct bio *bio;
1755         struct remap_info info;
1756
1757         info.tc = tc;
1758         bio_list_init(&info.defer_bios);
1759         bio_list_init(&info.issue_bios);
1760
1761         cell_visit_release(tc->pool, __remap_and_issue_shared_cell,
1762                            &info, cell);
1763
1764         while ((bio = bio_list_pop(&info.defer_bios)))
1765                 thin_defer_bio(tc, bio);
1766
1767         while ((bio = bio_list_pop(&info.issue_bios)))
1768                 remap_and_issue(tc, bio, block);
1769 }
1770
1771 static void process_shared_bio(struct thin_c *tc, struct bio *bio,
1772                                dm_block_t block,
1773                                struct dm_thin_lookup_result *lookup_result,
1774                                struct dm_bio_prison_cell *virt_cell)
1775 {
1776         struct dm_bio_prison_cell *data_cell;
1777         struct pool *pool = tc->pool;
1778         struct dm_cell_key key;
1779
1780         /*
1781          * If cell is already occupied, then sharing is already in the process
1782          * of being broken so we have nothing further to do here.
1783          */
1784         build_data_key(tc->td, lookup_result->block, &key);
1785         if (bio_detain(pool, &key, bio, &data_cell)) {
1786                 cell_defer_no_holder(tc, virt_cell);
1787                 return;
1788         }
1789
1790         if (bio_data_dir(bio) == WRITE && bio->bi_iter.bi_size) {
1791                 break_sharing(tc, bio, block, &key, lookup_result, data_cell);
1792                 cell_defer_no_holder(tc, virt_cell);
1793         } else {
1794                 struct dm_thin_endio_hook *h = dm_per_bio_data(bio, sizeof(struct dm_thin_endio_hook));
1795
1796                 h->shared_read_entry = dm_deferred_entry_inc(pool->shared_read_ds);
1797                 inc_all_io_entry(pool, bio);
1798                 remap_and_issue(tc, bio, lookup_result->block);
1799
1800                 remap_and_issue_shared_cell(tc, data_cell, lookup_result->block);
1801                 remap_and_issue_shared_cell(tc, virt_cell, lookup_result->block);
1802         }
1803 }
1804
1805 static void provision_block(struct thin_c *tc, struct bio *bio, dm_block_t block,
1806                             struct dm_bio_prison_cell *cell)
1807 {
1808         int r;
1809         dm_block_t data_block;
1810         struct pool *pool = tc->pool;
1811
1812         /*
1813          * Remap empty bios (flushes) immediately, without provisioning.
1814          */
1815         if (!bio->bi_iter.bi_size) {
1816                 inc_all_io_entry(pool, bio);
1817                 cell_defer_no_holder(tc, cell);
1818
1819                 remap_and_issue(tc, bio, 0);
1820                 return;
1821         }
1822
1823         /*
1824          * Fill read bios with zeroes and complete them immediately.
1825          */
1826         if (bio_data_dir(bio) == READ) {
1827                 zero_fill_bio(bio);
1828                 cell_defer_no_holder(tc, cell);
1829                 bio_endio(bio);
1830                 return;
1831         }
1832
1833         r = alloc_data_block(tc, &data_block);
1834         switch (r) {
1835         case 0:
1836                 if (tc->origin_dev)
1837                         schedule_external_copy(tc, block, data_block, cell, bio);
1838                 else
1839                         schedule_zero(tc, block, data_block, cell, bio);
1840                 break;
1841
1842         case -ENOSPC:
1843                 retry_bios_on_resume(pool, cell);
1844                 break;
1845
1846         default:
1847                 DMERR_LIMIT("%s: alloc_data_block() failed: error = %d",
1848                             __func__, r);
1849                 cell_error(pool, cell);
1850                 break;
1851         }
1852 }
1853
1854 static void process_cell(struct thin_c *tc, struct dm_bio_prison_cell *cell)
1855 {
1856         int r;
1857         struct pool *pool = tc->pool;
1858         struct bio *bio = cell->holder;
1859         dm_block_t block = get_bio_block(tc, bio);
1860         struct dm_thin_lookup_result lookup_result;
1861
1862         if (tc->requeue_mode) {
1863                 cell_requeue(pool, cell);
1864                 return;
1865         }
1866
1867         r = dm_thin_find_block(tc->td, block, 1, &lookup_result);
1868         switch (r) {
1869         case 0:
1870                 if (lookup_result.shared)
1871                         process_shared_bio(tc, bio, block, &lookup_result, cell);
1872                 else {
1873                         inc_all_io_entry(pool, bio);
1874                         remap_and_issue(tc, bio, lookup_result.block);
1875                         inc_remap_and_issue_cell(tc, cell, lookup_result.block);
1876                 }
1877                 break;
1878
1879         case -ENODATA:
1880                 if (bio_data_dir(bio) == READ && tc->origin_dev) {
1881                         inc_all_io_entry(pool, bio);
1882                         cell_defer_no_holder(tc, cell);
1883
1884                         if (bio_end_sector(bio) <= tc->origin_size)
1885                                 remap_to_origin_and_issue(tc, bio);
1886
1887                         else if (bio->bi_iter.bi_sector < tc->origin_size) {
1888                                 zero_fill_bio(bio);
1889                                 bio->bi_iter.bi_size = (tc->origin_size - bio->bi_iter.bi_sector) << SECTOR_SHIFT;
1890                                 remap_to_origin_and_issue(tc, bio);
1891
1892                         } else {
1893                                 zero_fill_bio(bio);
1894                                 bio_endio(bio);
1895                         }
1896                 } else
1897                         provision_block(tc, bio, block, cell);
1898                 break;
1899
1900         default:
1901                 DMERR_LIMIT("%s: dm_thin_find_block() failed: error = %d",
1902                             __func__, r);
1903                 cell_defer_no_holder(tc, cell);
1904                 bio_io_error(bio);
1905                 break;
1906         }
1907 }
1908
1909 static void process_bio(struct thin_c *tc, struct bio *bio)
1910 {
1911         struct pool *pool = tc->pool;
1912         dm_block_t block = get_bio_block(tc, bio);
1913         struct dm_bio_prison_cell *cell;
1914         struct dm_cell_key key;
1915
1916         /*
1917          * If cell is already occupied, then the block is already
1918          * being provisioned so we have nothing further to do here.
1919          */
1920         build_virtual_key(tc->td, block, &key);
1921         if (bio_detain(pool, &key, bio, &cell))
1922                 return;
1923
1924         process_cell(tc, cell);
1925 }
1926
1927 static void __process_bio_read_only(struct thin_c *tc, struct bio *bio,
1928                                     struct dm_bio_prison_cell *cell)
1929 {
1930         int r;
1931         int rw = bio_data_dir(bio);
1932         dm_block_t block = get_bio_block(tc, bio);
1933         struct dm_thin_lookup_result lookup_result;
1934
1935         r = dm_thin_find_block(tc->td, block, 1, &lookup_result);
1936         switch (r) {
1937         case 0:
1938                 if (lookup_result.shared && (rw == WRITE) && bio->bi_iter.bi_size) {
1939                         handle_unserviceable_bio(tc->pool, bio);
1940                         if (cell)
1941                                 cell_defer_no_holder(tc, cell);
1942                 } else {
1943                         inc_all_io_entry(tc->pool, bio);
1944                         remap_and_issue(tc, bio, lookup_result.block);
1945                         if (cell)
1946                                 inc_remap_and_issue_cell(tc, cell, lookup_result.block);
1947                 }
1948                 break;
1949
1950         case -ENODATA:
1951                 if (cell)
1952                         cell_defer_no_holder(tc, cell);
1953                 if (rw != READ) {
1954                         handle_unserviceable_bio(tc->pool, bio);
1955                         break;
1956                 }
1957
1958                 if (tc->origin_dev) {
1959                         inc_all_io_entry(tc->pool, bio);
1960                         remap_to_origin_and_issue(tc, bio);
1961                         break;
1962                 }
1963
1964                 zero_fill_bio(bio);
1965                 bio_endio(bio);
1966                 break;
1967
1968         default:
1969                 DMERR_LIMIT("%s: dm_thin_find_block() failed: error = %d",
1970                             __func__, r);
1971                 if (cell)
1972                         cell_defer_no_holder(tc, cell);
1973                 bio_io_error(bio);
1974                 break;
1975         }
1976 }
1977
1978 static void process_bio_read_only(struct thin_c *tc, struct bio *bio)
1979 {
1980         __process_bio_read_only(tc, bio, NULL);
1981 }
1982
1983 static void process_cell_read_only(struct thin_c *tc, struct dm_bio_prison_cell *cell)
1984 {
1985         __process_bio_read_only(tc, cell->holder, cell);
1986 }
1987
1988 static void process_bio_success(struct thin_c *tc, struct bio *bio)
1989 {
1990         bio_endio(bio);
1991 }
1992
1993 static void process_bio_fail(struct thin_c *tc, struct bio *bio)
1994 {
1995         bio_io_error(bio);
1996 }
1997
1998 static void process_cell_success(struct thin_c *tc, struct dm_bio_prison_cell *cell)
1999 {
2000         cell_success(tc->pool, cell);
2001 }
2002
2003 static void process_cell_fail(struct thin_c *tc, struct dm_bio_prison_cell *cell)
2004 {
2005         cell_error(tc->pool, cell);
2006 }
2007
2008 /*
2009  * FIXME: should we also commit due to size of transaction, measured in
2010  * metadata blocks?
2011  */
2012 static int need_commit_due_to_time(struct pool *pool)
2013 {
2014         return !time_in_range(jiffies, pool->last_commit_jiffies,
2015                               pool->last_commit_jiffies + COMMIT_PERIOD);
2016 }
2017
2018 #define thin_pbd(node) rb_entry((node), struct dm_thin_endio_hook, rb_node)
2019 #define thin_bio(pbd) dm_bio_from_per_bio_data((pbd), sizeof(struct dm_thin_endio_hook))
2020
2021 static void __thin_bio_rb_add(struct thin_c *tc, struct bio *bio)
2022 {
2023         struct rb_node **rbp, *parent;
2024         struct dm_thin_endio_hook *pbd;
2025         sector_t bi_sector = bio->bi_iter.bi_sector;
2026
2027         rbp = &tc->sort_bio_list.rb_node;
2028         parent = NULL;
2029         while (*rbp) {
2030                 parent = *rbp;
2031                 pbd = thin_pbd(parent);
2032
2033                 if (bi_sector < thin_bio(pbd)->bi_iter.bi_sector)
2034                         rbp = &(*rbp)->rb_left;
2035                 else
2036                         rbp = &(*rbp)->rb_right;
2037         }
2038
2039         pbd = dm_per_bio_data(bio, sizeof(struct dm_thin_endio_hook));
2040         rb_link_node(&pbd->rb_node, parent, rbp);
2041         rb_insert_color(&pbd->rb_node, &tc->sort_bio_list);
2042 }
2043
2044 static void __extract_sorted_bios(struct thin_c *tc)
2045 {
2046         struct rb_node *node;
2047         struct dm_thin_endio_hook *pbd;
2048         struct bio *bio;
2049
2050         for (node = rb_first(&tc->sort_bio_list); node; node = rb_next(node)) {
2051                 pbd = thin_pbd(node);
2052                 bio = thin_bio(pbd);
2053
2054                 bio_list_add(&tc->deferred_bio_list, bio);
2055                 rb_erase(&pbd->rb_node, &tc->sort_bio_list);
2056         }
2057
2058         WARN_ON(!RB_EMPTY_ROOT(&tc->sort_bio_list));
2059 }
2060
2061 static void __sort_thin_deferred_bios(struct thin_c *tc)
2062 {
2063         struct bio *bio;
2064         struct bio_list bios;
2065
2066         bio_list_init(&bios);
2067         bio_list_merge(&bios, &tc->deferred_bio_list);
2068         bio_list_init(&tc->deferred_bio_list);
2069
2070         /* Sort deferred_bio_list using rb-tree */
2071         while ((bio = bio_list_pop(&bios)))
2072                 __thin_bio_rb_add(tc, bio);
2073
2074         /*
2075          * Transfer the sorted bios in sort_bio_list back to
2076          * deferred_bio_list to allow lockless submission of
2077          * all bios.
2078          */
2079         __extract_sorted_bios(tc);
2080 }
2081
2082 static void process_thin_deferred_bios(struct thin_c *tc)
2083 {
2084         struct pool *pool = tc->pool;
2085         unsigned long flags;
2086         struct bio *bio;
2087         struct bio_list bios;
2088         struct blk_plug plug;
2089         unsigned count = 0;
2090
2091         if (tc->requeue_mode) {
2092                 error_thin_bio_list(tc, &tc->deferred_bio_list, DM_ENDIO_REQUEUE);
2093                 return;
2094         }
2095
2096         bio_list_init(&bios);
2097
2098         spin_lock_irqsave(&tc->lock, flags);
2099
2100         if (bio_list_empty(&tc->deferred_bio_list)) {
2101                 spin_unlock_irqrestore(&tc->lock, flags);
2102                 return;
2103         }
2104
2105         __sort_thin_deferred_bios(tc);
2106
2107         bio_list_merge(&bios, &tc->deferred_bio_list);
2108         bio_list_init(&tc->deferred_bio_list);
2109
2110         spin_unlock_irqrestore(&tc->lock, flags);
2111
2112         blk_start_plug(&plug);
2113         while ((bio = bio_list_pop(&bios))) {
2114                 /*
2115                  * If we've got no free new_mapping structs, and processing
2116                  * this bio might require one, we pause until there are some
2117                  * prepared mappings to process.
2118                  */
2119                 if (ensure_next_mapping(pool)) {
2120                         spin_lock_irqsave(&tc->lock, flags);
2121                         bio_list_add(&tc->deferred_bio_list, bio);
2122                         bio_list_merge(&tc->deferred_bio_list, &bios);
2123                         spin_unlock_irqrestore(&tc->lock, flags);
2124                         break;
2125                 }
2126
2127                 if (bio->bi_rw & REQ_DISCARD)
2128                         pool->process_discard(tc, bio);
2129                 else
2130                         pool->process_bio(tc, bio);
2131
2132                 if ((count++ & 127) == 0) {
2133                         throttle_work_update(&pool->throttle);
2134                         dm_pool_issue_prefetches(pool->pmd);
2135                 }
2136         }
2137         blk_finish_plug(&plug);
2138 }
2139
2140 static int cmp_cells(const void *lhs, const void *rhs)
2141 {
2142         struct dm_bio_prison_cell *lhs_cell = *((struct dm_bio_prison_cell **) lhs);
2143         struct dm_bio_prison_cell *rhs_cell = *((struct dm_bio_prison_cell **) rhs);
2144
2145         BUG_ON(!lhs_cell->holder);
2146         BUG_ON(!rhs_cell->holder);
2147
2148         if (lhs_cell->holder->bi_iter.bi_sector < rhs_cell->holder->bi_iter.bi_sector)
2149                 return -1;
2150
2151         if (lhs_cell->holder->bi_iter.bi_sector > rhs_cell->holder->bi_iter.bi_sector)
2152                 return 1;
2153
2154         return 0;
2155 }
2156
2157 static unsigned sort_cells(struct pool *pool, struct list_head *cells)
2158 {
2159         unsigned count = 0;
2160         struct dm_bio_prison_cell *cell, *tmp;
2161
2162         list_for_each_entry_safe(cell, tmp, cells, user_list) {
2163                 if (count >= CELL_SORT_ARRAY_SIZE)
2164                         break;
2165
2166                 pool->cell_sort_array[count++] = cell;
2167                 list_del(&cell->user_list);
2168         }
2169
2170         sort(pool->cell_sort_array, count, sizeof(cell), cmp_cells, NULL);
2171
2172         return count;
2173 }
2174
2175 static void process_thin_deferred_cells(struct thin_c *tc)
2176 {
2177         struct pool *pool = tc->pool;
2178         unsigned long flags;
2179         struct list_head cells;
2180         struct dm_bio_prison_cell *cell;
2181         unsigned i, j, count;
2182
2183         INIT_LIST_HEAD(&cells);
2184
2185         spin_lock_irqsave(&tc->lock, flags);
2186         list_splice_init(&tc->deferred_cells, &cells);
2187         spin_unlock_irqrestore(&tc->lock, flags);
2188
2189         if (list_empty(&cells))
2190                 return;
2191
2192         do {
2193                 count = sort_cells(tc->pool, &cells);
2194
2195                 for (i = 0; i < count; i++) {
2196                         cell = pool->cell_sort_array[i];
2197                         BUG_ON(!cell->holder);
2198
2199                         /*
2200                          * If we've got no free new_mapping structs, and processing
2201                          * this bio might require one, we pause until there are some
2202                          * prepared mappings to process.
2203                          */
2204                         if (ensure_next_mapping(pool)) {
2205                                 for (j = i; j < count; j++)
2206                                         list_add(&pool->cell_sort_array[j]->user_list, &cells);
2207
2208                                 spin_lock_irqsave(&tc->lock, flags);
2209                                 list_splice(&cells, &tc->deferred_cells);
2210                                 spin_unlock_irqrestore(&tc->lock, flags);
2211                                 return;
2212                         }
2213
2214                         if (cell->holder->bi_rw & REQ_DISCARD)
2215                                 pool->process_discard_cell(tc, cell);
2216                         else
2217                                 pool->process_cell(tc, cell);
2218                 }
2219         } while (!list_empty(&cells));
2220 }
2221
2222 static void thin_get(struct thin_c *tc);
2223 static void thin_put(struct thin_c *tc);
2224
2225 /*
2226  * We can't hold rcu_read_lock() around code that can block.  So we
2227  * find a thin with the rcu lock held; bump a refcount; then drop
2228  * the lock.
2229  */
2230 static struct thin_c *get_first_thin(struct pool *pool)
2231 {
2232         struct thin_c *tc = NULL;
2233
2234         rcu_read_lock();
2235         if (!list_empty(&pool->active_thins)) {
2236                 tc = list_entry_rcu(pool->active_thins.next, struct thin_c, list);
2237                 thin_get(tc);
2238         }
2239         rcu_read_unlock();
2240
2241         return tc;
2242 }
2243
2244 static struct thin_c *get_next_thin(struct pool *pool, struct thin_c *tc)
2245 {
2246         struct thin_c *old_tc = tc;
2247
2248         rcu_read_lock();
2249         list_for_each_entry_continue_rcu(tc, &pool->active_thins, list) {
2250                 thin_get(tc);
2251                 thin_put(old_tc);
2252                 rcu_read_unlock();
2253                 return tc;
2254         }
2255         thin_put(old_tc);
2256         rcu_read_unlock();
2257
2258         return NULL;
2259 }
2260
2261 static void process_deferred_bios(struct pool *pool)
2262 {
2263         unsigned long flags;
2264         struct bio *bio;
2265         struct bio_list bios, bio_completions;
2266         struct thin_c *tc;
2267
2268         tc = get_first_thin(pool);
2269         while (tc) {
2270                 process_thin_deferred_cells(tc);
2271                 process_thin_deferred_bios(tc);
2272                 tc = get_next_thin(pool, tc);
2273         }
2274
2275         /*
2276          * If there are any deferred flush bios, we must commit the metadata
2277          * before issuing them or signaling their completion.
2278          */
2279         bio_list_init(&bios);
2280         bio_list_init(&bio_completions);
2281
2282         spin_lock_irqsave(&pool->lock, flags);
2283         bio_list_merge(&bios, &pool->deferred_flush_bios);
2284         bio_list_init(&pool->deferred_flush_bios);
2285
2286         bio_list_merge(&bio_completions, &pool->deferred_flush_completions);
2287         bio_list_init(&pool->deferred_flush_completions);
2288         spin_unlock_irqrestore(&pool->lock, flags);
2289
2290         if (bio_list_empty(&bios) && bio_list_empty(&bio_completions) &&
2291             !(dm_pool_changed_this_transaction(pool->pmd) && need_commit_due_to_time(pool)))
2292                 return;
2293
2294         if (commit(pool)) {
2295                 bio_list_merge(&bios, &bio_completions);
2296
2297                 while ((bio = bio_list_pop(&bios)))
2298                         bio_io_error(bio);
2299                 return;
2300         }
2301         pool->last_commit_jiffies = jiffies;
2302
2303         while ((bio = bio_list_pop(&bio_completions)))
2304                 bio_endio(bio);
2305
2306         while ((bio = bio_list_pop(&bios)))
2307                 generic_make_request(bio);
2308 }
2309
2310 static void do_worker(struct work_struct *ws)
2311 {
2312         struct pool *pool = container_of(ws, struct pool, worker);
2313
2314         throttle_work_start(&pool->throttle);
2315         dm_pool_issue_prefetches(pool->pmd);
2316         throttle_work_update(&pool->throttle);
2317         process_prepared(pool, &pool->prepared_mappings, &pool->process_prepared_mapping);
2318         throttle_work_update(&pool->throttle);
2319         process_prepared(pool, &pool->prepared_discards, &pool->process_prepared_discard);
2320         throttle_work_update(&pool->throttle);
2321         process_deferred_bios(pool);
2322         throttle_work_complete(&pool->throttle);
2323 }
2324
2325 /*
2326  * We want to commit periodically so that not too much
2327  * unwritten data builds up.
2328  */
2329 static void do_waker(struct work_struct *ws)
2330 {
2331         struct pool *pool = container_of(to_delayed_work(ws), struct pool, waker);
2332         wake_worker(pool);
2333         queue_delayed_work(pool->wq, &pool->waker, COMMIT_PERIOD);
2334 }
2335
2336 static void notify_of_pool_mode_change_to_oods(struct pool *pool);
2337
2338 /*
2339  * We're holding onto IO to allow userland time to react.  After the
2340  * timeout either the pool will have been resized (and thus back in
2341  * PM_WRITE mode), or we degrade to PM_OUT_OF_DATA_SPACE w/ error_if_no_space.
2342  */
2343 static void do_no_space_timeout(struct work_struct *ws)
2344 {
2345         struct pool *pool = container_of(to_delayed_work(ws), struct pool,
2346                                          no_space_timeout);
2347
2348         if (get_pool_mode(pool) == PM_OUT_OF_DATA_SPACE && !pool->pf.error_if_no_space) {
2349                 pool->pf.error_if_no_space = true;
2350                 notify_of_pool_mode_change_to_oods(pool);
2351                 error_retry_list_with_code(pool, -ENOSPC);
2352         }
2353 }
2354
2355 /*----------------------------------------------------------------*/
2356
2357 struct pool_work {
2358         struct work_struct worker;
2359         struct completion complete;
2360 };
2361
2362 static struct pool_work *to_pool_work(struct work_struct *ws)
2363 {
2364         return container_of(ws, struct pool_work, worker);
2365 }
2366
2367 static void pool_work_complete(struct pool_work *pw)
2368 {
2369         complete(&pw->complete);
2370 }
2371
2372 static void pool_work_wait(struct pool_work *pw, struct pool *pool,
2373                            void (*fn)(struct work_struct *))
2374 {
2375         INIT_WORK_ONSTACK(&pw->worker, fn);
2376         init_completion(&pw->complete);
2377         queue_work(pool->wq, &pw->worker);
2378         wait_for_completion(&pw->complete);
2379 }
2380
2381 /*----------------------------------------------------------------*/
2382
2383 struct noflush_work {
2384         struct pool_work pw;
2385         struct thin_c *tc;
2386 };
2387
2388 static struct noflush_work *to_noflush(struct work_struct *ws)
2389 {
2390         return container_of(to_pool_work(ws), struct noflush_work, pw);
2391 }
2392
2393 static void do_noflush_start(struct work_struct *ws)
2394 {
2395         struct noflush_work *w = to_noflush(ws);
2396         w->tc->requeue_mode = true;
2397         requeue_io(w->tc);
2398         pool_work_complete(&w->pw);
2399 }
2400
2401 static void do_noflush_stop(struct work_struct *ws)
2402 {
2403         struct noflush_work *w = to_noflush(ws);
2404         w->tc->requeue_mode = false;
2405         pool_work_complete(&w->pw);
2406 }
2407
2408 static void noflush_work(struct thin_c *tc, void (*fn)(struct work_struct *))
2409 {
2410         struct noflush_work w;
2411
2412         w.tc = tc;
2413         pool_work_wait(&w.pw, tc->pool, fn);
2414 }
2415
2416 /*----------------------------------------------------------------*/
2417
2418 static enum pool_mode get_pool_mode(struct pool *pool)
2419 {
2420         return pool->pf.mode;
2421 }
2422
2423 static void notify_of_pool_mode_change(struct pool *pool, const char *new_mode)
2424 {
2425         dm_table_event(pool->ti->table);
2426         DMINFO("%s: switching pool to %s mode",
2427                dm_device_name(pool->pool_md), new_mode);
2428 }
2429
2430 static void notify_of_pool_mode_change_to_oods(struct pool *pool)
2431 {
2432         if (!pool->pf.error_if_no_space)
2433                 notify_of_pool_mode_change(pool, "out-of-data-space (queue IO)");
2434         else
2435                 notify_of_pool_mode_change(pool, "out-of-data-space (error IO)");
2436 }
2437
2438 static bool passdown_enabled(struct pool_c *pt)
2439 {
2440         return pt->adjusted_pf.discard_passdown;
2441 }
2442
2443 static void set_discard_callbacks(struct pool *pool)
2444 {
2445         struct pool_c *pt = pool->ti->private;
2446
2447         if (passdown_enabled(pt)) {
2448                 pool->process_discard_cell = process_discard_cell_passdown;
2449                 pool->process_prepared_discard = process_prepared_discard_passdown;
2450         } else {
2451                 pool->process_discard_cell = process_discard_cell_no_passdown;
2452                 pool->process_prepared_discard = process_prepared_discard_no_passdown;
2453         }
2454 }
2455
2456 static void set_pool_mode(struct pool *pool, enum pool_mode new_mode)
2457 {
2458         struct pool_c *pt = pool->ti->private;
2459         bool needs_check = dm_pool_metadata_needs_check(pool->pmd);
2460         enum pool_mode old_mode = get_pool_mode(pool);
2461         unsigned long no_space_timeout = ACCESS_ONCE(no_space_timeout_secs) * HZ;
2462
2463         /*
2464          * Never allow the pool to transition to PM_WRITE mode if user
2465          * intervention is required to verify metadata and data consistency.
2466          */
2467         if (new_mode == PM_WRITE && needs_check) {
2468                 DMERR("%s: unable to switch pool to write mode until repaired.",
2469                       dm_device_name(pool->pool_md));
2470                 if (old_mode != new_mode)
2471                         new_mode = old_mode;
2472                 else
2473                         new_mode = PM_READ_ONLY;
2474         }
2475         /*
2476          * If we were in PM_FAIL mode, rollback of metadata failed.  We're
2477          * not going to recover without a thin_repair.  So we never let the
2478          * pool move out of the old mode.
2479          */
2480         if (old_mode == PM_FAIL)
2481                 new_mode = old_mode;
2482
2483         switch (new_mode) {
2484         case PM_FAIL:
2485                 if (old_mode != new_mode)
2486                         notify_of_pool_mode_change(pool, "failure");
2487                 dm_pool_metadata_read_only(pool->pmd);
2488                 pool->process_bio = process_bio_fail;
2489                 pool->process_discard = process_bio_fail;
2490                 pool->process_cell = process_cell_fail;
2491                 pool->process_discard_cell = process_cell_fail;
2492                 pool->process_prepared_mapping = process_prepared_mapping_fail;
2493                 pool->process_prepared_discard = process_prepared_discard_fail;
2494
2495                 error_retry_list(pool);
2496                 break;
2497
2498         case PM_OUT_OF_METADATA_SPACE:
2499         case PM_READ_ONLY:
2500                 if (!is_read_only_pool_mode(old_mode))
2501                         notify_of_pool_mode_change(pool, "read-only");
2502                 dm_pool_metadata_read_only(pool->pmd);
2503                 pool->process_bio = process_bio_read_only;
2504                 pool->process_discard = process_bio_success;
2505                 pool->process_cell = process_cell_read_only;
2506                 pool->process_discard_cell = process_cell_success;
2507                 pool->process_prepared_mapping = process_prepared_mapping_fail;
2508                 pool->process_prepared_discard = process_prepared_discard_success;
2509
2510                 error_retry_list(pool);
2511                 break;
2512
2513         case PM_OUT_OF_DATA_SPACE:
2514                 /*
2515                  * Ideally we'd never hit this state; the low water mark
2516                  * would trigger userland to extend the pool before we
2517                  * completely run out of data space.  However, many small
2518                  * IOs to unprovisioned space can consume data space at an
2519                  * alarming rate.  Adjust your low water mark if you're
2520                  * frequently seeing this mode.
2521                  */
2522                 if (old_mode != new_mode)
2523                         notify_of_pool_mode_change_to_oods(pool);
2524                 pool->process_bio = process_bio_read_only;
2525                 pool->process_discard = process_discard_bio;
2526                 pool->process_cell = process_cell_read_only;
2527                 pool->process_prepared_mapping = process_prepared_mapping;
2528                 set_discard_callbacks(pool);
2529
2530                 if (!pool->pf.error_if_no_space && no_space_timeout)
2531                         queue_delayed_work(pool->wq, &pool->no_space_timeout, no_space_timeout);
2532                 break;
2533
2534         case PM_WRITE:
2535                 if (old_mode != new_mode)
2536                         notify_of_pool_mode_change(pool, "write");
2537                 pool->pf.error_if_no_space = pt->requested_pf.error_if_no_space;
2538                 dm_pool_metadata_read_write(pool->pmd);
2539                 pool->process_bio = process_bio;
2540                 pool->process_discard = process_discard_bio;
2541                 pool->process_cell = process_cell;
2542                 pool->process_prepared_mapping = process_prepared_mapping;
2543                 set_discard_callbacks(pool);
2544                 break;
2545         }
2546
2547         pool->pf.mode = new_mode;
2548         /*
2549          * The pool mode may have changed, sync it so bind_control_target()
2550          * doesn't cause an unexpected mode transition on resume.
2551          */
2552         pt->adjusted_pf.mode = new_mode;
2553 }
2554
2555 static void abort_transaction(struct pool *pool)
2556 {
2557         const char *dev_name = dm_device_name(pool->pool_md);
2558
2559         DMERR_LIMIT("%s: aborting current metadata transaction", dev_name);
2560         if (dm_pool_abort_metadata(pool->pmd)) {
2561                 DMERR("%s: failed to abort metadata transaction", dev_name);
2562                 set_pool_mode(pool, PM_FAIL);
2563         }
2564
2565         if (dm_pool_metadata_set_needs_check(pool->pmd)) {
2566                 DMERR("%s: failed to set 'needs_check' flag in metadata", dev_name);
2567                 set_pool_mode(pool, PM_FAIL);
2568         }
2569 }
2570
2571 static void metadata_operation_failed(struct pool *pool, const char *op, int r)
2572 {
2573         DMERR_LIMIT("%s: metadata operation '%s' failed: error = %d",
2574                     dm_device_name(pool->pool_md), op, r);
2575
2576         abort_transaction(pool);
2577         set_pool_mode(pool, PM_READ_ONLY);
2578 }
2579
2580 /*----------------------------------------------------------------*/
2581
2582 /*
2583  * Mapping functions.
2584  */
2585
2586 /*
2587  * Called only while mapping a thin bio to hand it over to the workqueue.
2588  */
2589 static void thin_defer_bio(struct thin_c *tc, struct bio *bio)
2590 {
2591         unsigned long flags;
2592         struct pool *pool = tc->pool;
2593
2594         spin_lock_irqsave(&tc->lock, flags);
2595         bio_list_add(&tc->deferred_bio_list, bio);
2596         spin_unlock_irqrestore(&tc->lock, flags);
2597
2598         wake_worker(pool);
2599 }
2600
2601 static void thin_defer_bio_with_throttle(struct thin_c *tc, struct bio *bio)
2602 {
2603         struct pool *pool = tc->pool;
2604
2605         throttle_lock(&pool->throttle);
2606         thin_defer_bio(tc, bio);
2607         throttle_unlock(&pool->throttle);
2608 }
2609
2610 static void thin_defer_cell(struct thin_c *tc, struct dm_bio_prison_cell *cell)
2611 {
2612         unsigned long flags;
2613         struct pool *pool = tc->pool;
2614
2615         throttle_lock(&pool->throttle);
2616         spin_lock_irqsave(&tc->lock, flags);
2617         list_add_tail(&cell->user_list, &tc->deferred_cells);
2618         spin_unlock_irqrestore(&tc->lock, flags);
2619         throttle_unlock(&pool->throttle);
2620
2621         wake_worker(pool);
2622 }
2623
2624 static void thin_hook_bio(struct thin_c *tc, struct bio *bio)
2625 {
2626         struct dm_thin_endio_hook *h = dm_per_bio_data(bio, sizeof(struct dm_thin_endio_hook));
2627
2628         h->tc = tc;
2629         h->shared_read_entry = NULL;
2630         h->all_io_entry = NULL;
2631         h->overwrite_mapping = NULL;
2632         h->cell = NULL;
2633 }
2634
2635 /*
2636  * Non-blocking function called from the thin target's map function.
2637  */
2638 static int thin_bio_map(struct dm_target *ti, struct bio *bio)
2639 {
2640         int r;
2641         struct thin_c *tc = ti->private;
2642         dm_block_t block = get_bio_block(tc, bio);
2643         struct dm_thin_device *td = tc->td;
2644         struct dm_thin_lookup_result result;
2645         struct dm_bio_prison_cell *virt_cell, *data_cell;
2646         struct dm_cell_key key;
2647
2648         thin_hook_bio(tc, bio);
2649
2650         if (tc->requeue_mode) {
2651                 bio->bi_error = DM_ENDIO_REQUEUE;
2652                 bio_endio(bio);
2653                 return DM_MAPIO_SUBMITTED;
2654         }
2655
2656         if (get_pool_mode(tc->pool) == PM_FAIL) {
2657                 bio_io_error(bio);
2658                 return DM_MAPIO_SUBMITTED;
2659         }
2660
2661         if (bio->bi_rw & (REQ_DISCARD | REQ_FLUSH | REQ_FUA)) {
2662                 thin_defer_bio_with_throttle(tc, bio);
2663                 return DM_MAPIO_SUBMITTED;
2664         }
2665
2666         /*
2667          * We must hold the virtual cell before doing the lookup, otherwise
2668          * there's a race with discard.
2669          */
2670         build_virtual_key(tc->td, block, &key);
2671         if (bio_detain(tc->pool, &key, bio, &virt_cell))
2672                 return DM_MAPIO_SUBMITTED;
2673
2674         r = dm_thin_find_block(td, block, 0, &result);
2675
2676         /*
2677          * Note that we defer readahead too.
2678          */
2679         switch (r) {
2680         case 0:
2681                 if (unlikely(result.shared)) {
2682                         /*
2683                          * We have a race condition here between the
2684                          * result.shared value returned by the lookup and
2685                          * snapshot creation, which may cause new
2686                          * sharing.
2687                          *
2688                          * To avoid this always quiesce the origin before
2689                          * taking the snap.  You want to do this anyway to
2690                          * ensure a consistent application view
2691                          * (i.e. lockfs).
2692                          *
2693                          * More distant ancestors are irrelevant. The
2694                          * shared flag will be set in their case.
2695                          */
2696                         thin_defer_cell(tc, virt_cell);
2697                         return DM_MAPIO_SUBMITTED;
2698                 }
2699
2700                 build_data_key(tc->td, result.block, &key);
2701                 if (bio_detain(tc->pool, &key, bio, &data_cell)) {
2702                         cell_defer_no_holder(tc, virt_cell);
2703                         return DM_MAPIO_SUBMITTED;
2704                 }
2705
2706                 inc_all_io_entry(tc->pool, bio);
2707                 cell_defer_no_holder(tc, data_cell);
2708                 cell_defer_no_holder(tc, virt_cell);
2709
2710                 remap(tc, bio, result.block);
2711                 return DM_MAPIO_REMAPPED;
2712
2713         case -ENODATA:
2714         case -EWOULDBLOCK:
2715                 thin_defer_cell(tc, virt_cell);
2716                 return DM_MAPIO_SUBMITTED;
2717
2718         default:
2719                 /*
2720                  * Must always call bio_io_error on failure.
2721                  * dm_thin_find_block can fail with -EINVAL if the
2722                  * pool is switched to fail-io mode.
2723                  */
2724                 bio_io_error(bio);
2725                 cell_defer_no_holder(tc, virt_cell);
2726                 return DM_MAPIO_SUBMITTED;
2727         }
2728 }
2729
2730 static int pool_is_congested(struct dm_target_callbacks *cb, int bdi_bits)
2731 {
2732         struct pool_c *pt = container_of(cb, struct pool_c, callbacks);
2733         struct request_queue *q;
2734
2735         if (get_pool_mode(pt->pool) == PM_OUT_OF_DATA_SPACE)
2736                 return 1;
2737
2738         q = bdev_get_queue(pt->data_dev->bdev);
2739         return bdi_congested(&q->backing_dev_info, bdi_bits);
2740 }
2741
2742 static void requeue_bios(struct pool *pool)
2743 {
2744         unsigned long flags;
2745         struct thin_c *tc;
2746
2747         rcu_read_lock();
2748         list_for_each_entry_rcu(tc, &pool->active_thins, list) {
2749                 spin_lock_irqsave(&tc->lock, flags);
2750                 bio_list_merge(&tc->deferred_bio_list, &tc->retry_on_resume_list);
2751                 bio_list_init(&tc->retry_on_resume_list);
2752                 spin_unlock_irqrestore(&tc->lock, flags);
2753         }
2754         rcu_read_unlock();
2755 }
2756
2757 /*----------------------------------------------------------------
2758  * Binding of control targets to a pool object
2759  *--------------------------------------------------------------*/
2760 static bool data_dev_supports_discard(struct pool_c *pt)
2761 {
2762         struct request_queue *q = bdev_get_queue(pt->data_dev->bdev);
2763
2764         return q && blk_queue_discard(q);
2765 }
2766
2767 static bool is_factor(sector_t block_size, uint32_t n)
2768 {
2769         return !sector_div(block_size, n);
2770 }
2771
2772 /*
2773  * If discard_passdown was enabled verify that the data device
2774  * supports discards.  Disable discard_passdown if not.
2775  */
2776 static void disable_passdown_if_not_supported(struct pool_c *pt)
2777 {
2778         struct pool *pool = pt->pool;
2779         struct block_device *data_bdev = pt->data_dev->bdev;
2780         struct queue_limits *data_limits = &bdev_get_queue(data_bdev)->limits;
2781         const char *reason = NULL;
2782         char buf[BDEVNAME_SIZE];
2783
2784         if (!pt->adjusted_pf.discard_passdown)
2785                 return;
2786
2787         if (!data_dev_supports_discard(pt))
2788                 reason = "discard unsupported";
2789
2790         else if (data_limits->max_discard_sectors < pool->sectors_per_block)
2791                 reason = "max discard sectors smaller than a block";
2792
2793         if (reason) {
2794                 DMWARN("Data device (%s) %s: Disabling discard passdown.", bdevname(data_bdev, buf), reason);
2795                 pt->adjusted_pf.discard_passdown = false;
2796         }
2797 }
2798
2799 static int bind_control_target(struct pool *pool, struct dm_target *ti)
2800 {
2801         struct pool_c *pt = ti->private;
2802
2803         /*
2804          * We want to make sure that a pool in PM_FAIL mode is never upgraded.
2805          */
2806         enum pool_mode old_mode = get_pool_mode(pool);
2807         enum pool_mode new_mode = pt->adjusted_pf.mode;
2808
2809         /*
2810          * Don't change the pool's mode until set_pool_mode() below.
2811          * Otherwise the pool's process_* function pointers may
2812          * not match the desired pool mode.
2813          */
2814         pt->adjusted_pf.mode = old_mode;
2815
2816         pool->ti = ti;
2817         pool->pf = pt->adjusted_pf;
2818         pool->low_water_blocks = pt->low_water_blocks;
2819
2820         set_pool_mode(pool, new_mode);
2821
2822         return 0;
2823 }
2824
2825 static void unbind_control_target(struct pool *pool, struct dm_target *ti)
2826 {
2827         if (pool->ti == ti)
2828                 pool->ti = NULL;
2829 }
2830
2831 /*----------------------------------------------------------------
2832  * Pool creation
2833  *--------------------------------------------------------------*/
2834 /* Initialize pool features. */
2835 static void pool_features_init(struct pool_features *pf)
2836 {
2837         pf->mode = PM_WRITE;
2838         pf->zero_new_blocks = true;
2839         pf->discard_enabled = true;
2840         pf->discard_passdown = true;
2841         pf->error_if_no_space = false;
2842 }
2843
2844 static void __pool_destroy(struct pool *pool)
2845 {
2846         __pool_table_remove(pool);
2847
2848         vfree(pool->cell_sort_array);
2849         if (dm_pool_metadata_close(pool->pmd) < 0)
2850                 DMWARN("%s: dm_pool_metadata_close() failed.", __func__);
2851
2852         dm_bio_prison_destroy(pool->prison);
2853         dm_kcopyd_client_destroy(pool->copier);
2854
2855         if (pool->wq)
2856                 destroy_workqueue(pool->wq);
2857
2858         if (pool->next_mapping)
2859                 mempool_free(pool->next_mapping, pool->mapping_pool);
2860         mempool_destroy(pool->mapping_pool);
2861         dm_deferred_set_destroy(pool->shared_read_ds);
2862         dm_deferred_set_destroy(pool->all_io_ds);
2863         kfree(pool);
2864 }
2865
2866 static struct kmem_cache *_new_mapping_cache;
2867
2868 static struct pool *pool_create(struct mapped_device *pool_md,
2869                                 struct block_device *metadata_dev,
2870                                 unsigned long block_size,
2871                                 int read_only, char **error)
2872 {
2873         int r;
2874         void *err_p;
2875         struct pool *pool;
2876         struct dm_pool_metadata *pmd;
2877         bool format_device = read_only ? false : true;
2878
2879         pmd = dm_pool_metadata_open(metadata_dev, block_size, format_device);
2880         if (IS_ERR(pmd)) {
2881                 *error = "Error creating metadata object";
2882                 return (struct pool *)pmd;
2883         }
2884
2885         pool = kzalloc(sizeof(*pool), GFP_KERNEL);
2886         if (!pool) {
2887                 *error = "Error allocating memory for pool";
2888                 err_p = ERR_PTR(-ENOMEM);
2889                 goto bad_pool;
2890         }
2891
2892         pool->pmd = pmd;
2893         pool->sectors_per_block = block_size;
2894         if (block_size & (block_size - 1))
2895                 pool->sectors_per_block_shift = -1;
2896         else
2897                 pool->sectors_per_block_shift = __ffs(block_size);
2898         pool->low_water_blocks = 0;
2899         pool_features_init(&pool->pf);
2900         pool->prison = dm_bio_prison_create();
2901         if (!pool->prison) {
2902                 *error = "Error creating pool's bio prison";
2903                 err_p = ERR_PTR(-ENOMEM);
2904                 goto bad_prison;
2905         }
2906
2907         pool->copier = dm_kcopyd_client_create(&dm_kcopyd_throttle);
2908         if (IS_ERR(pool->copier)) {
2909                 r = PTR_ERR(pool->copier);
2910                 *error = "Error creating pool's kcopyd client";
2911                 err_p = ERR_PTR(r);
2912                 goto bad_kcopyd_client;
2913         }
2914
2915         /*
2916          * Create singlethreaded workqueue that will service all devices
2917          * that use this metadata.
2918          */
2919         pool->wq = alloc_ordered_workqueue("dm-" DM_MSG_PREFIX, WQ_MEM_RECLAIM);
2920         if (!pool->wq) {
2921                 *error = "Error creating pool's workqueue";
2922                 err_p = ERR_PTR(-ENOMEM);
2923                 goto bad_wq;
2924         }
2925
2926         throttle_init(&pool->throttle);
2927         INIT_WORK(&pool->worker, do_worker);
2928         INIT_DELAYED_WORK(&pool->waker, do_waker);
2929         INIT_DELAYED_WORK(&pool->no_space_timeout, do_no_space_timeout);
2930         spin_lock_init(&pool->lock);
2931         bio_list_init(&pool->deferred_flush_bios);
2932         bio_list_init(&pool->deferred_flush_completions);
2933         INIT_LIST_HEAD(&pool->prepared_mappings);
2934         INIT_LIST_HEAD(&pool->prepared_discards);
2935         INIT_LIST_HEAD(&pool->active_thins);
2936         pool->low_water_triggered = false;
2937         pool->suspended = true;
2938
2939         pool->shared_read_ds = dm_deferred_set_create();
2940         if (!pool->shared_read_ds) {
2941                 *error = "Error creating pool's shared read deferred set";
2942                 err_p = ERR_PTR(-ENOMEM);
2943                 goto bad_shared_read_ds;
2944         }
2945
2946         pool->all_io_ds = dm_deferred_set_create();
2947         if (!pool->all_io_ds) {
2948                 *error = "Error creating pool's all io deferred set";
2949                 err_p = ERR_PTR(-ENOMEM);
2950                 goto bad_all_io_ds;
2951         }
2952
2953         pool->next_mapping = NULL;
2954         pool->mapping_pool = mempool_create_slab_pool(MAPPING_POOL_SIZE,
2955                                                       _new_mapping_cache);
2956         if (!pool->mapping_pool) {
2957                 *error = "Error creating pool's mapping mempool";
2958                 err_p = ERR_PTR(-ENOMEM);
2959                 goto bad_mapping_pool;
2960         }
2961
2962         pool->cell_sort_array = vmalloc(sizeof(*pool->cell_sort_array) * CELL_SORT_ARRAY_SIZE);
2963         if (!pool->cell_sort_array) {
2964                 *error = "Error allocating cell sort array";
2965                 err_p = ERR_PTR(-ENOMEM);
2966                 goto bad_sort_array;
2967         }
2968
2969         pool->ref_count = 1;
2970         pool->last_commit_jiffies = jiffies;
2971         pool->pool_md = pool_md;
2972         pool->md_dev = metadata_dev;
2973         __pool_table_insert(pool);
2974
2975         return pool;
2976
2977 bad_sort_array:
2978         mempool_destroy(pool->mapping_pool);
2979 bad_mapping_pool:
2980         dm_deferred_set_destroy(pool->all_io_ds);
2981 bad_all_io_ds:
2982         dm_deferred_set_destroy(pool->shared_read_ds);
2983 bad_shared_read_ds:
2984         destroy_workqueue(pool->wq);
2985 bad_wq:
2986         dm_kcopyd_client_destroy(pool->copier);
2987 bad_kcopyd_client:
2988         dm_bio_prison_destroy(pool->prison);
2989 bad_prison:
2990         kfree(pool);
2991 bad_pool:
2992         if (dm_pool_metadata_close(pmd))
2993                 DMWARN("%s: dm_pool_metadata_close() failed.", __func__);
2994
2995         return err_p;
2996 }
2997
2998 static void __pool_inc(struct pool *pool)
2999 {
3000         BUG_ON(!mutex_is_locked(&dm_thin_pool_table.mutex));
3001         pool->ref_count++;
3002 }
3003
3004 static void __pool_dec(struct pool *pool)
3005 {
3006         BUG_ON(!mutex_is_locked(&dm_thin_pool_table.mutex));
3007         BUG_ON(!pool->ref_count);
3008         if (!--pool->ref_count)
3009                 __pool_destroy(pool);
3010 }
3011
3012 static struct pool *__pool_find(struct mapped_device *pool_md,
3013                                 struct block_device *metadata_dev,
3014                                 unsigned long block_size, int read_only,
3015                                 char **error, int *created)
3016 {
3017         struct pool *pool = __pool_table_lookup_metadata_dev(metadata_dev);
3018
3019         if (pool) {
3020                 if (pool->pool_md != pool_md) {
3021                         *error = "metadata device already in use by a pool";
3022                         return ERR_PTR(-EBUSY);
3023                 }
3024                 __pool_inc(pool);
3025
3026         } else {
3027                 pool = __pool_table_lookup(pool_md);
3028                 if (pool) {
3029                         if (pool->md_dev != metadata_dev) {
3030                                 *error = "different pool cannot replace a pool";
3031                                 return ERR_PTR(-EINVAL);
3032                         }
3033                         __pool_inc(pool);
3034
3035                 } else {
3036                         pool = pool_create(pool_md, metadata_dev, block_size, read_only, error);
3037                         *created = 1;
3038                 }
3039         }
3040
3041         return pool;
3042 }
3043
3044 /*----------------------------------------------------------------
3045  * Pool target methods
3046  *--------------------------------------------------------------*/
3047 static void pool_dtr(struct dm_target *ti)
3048 {
3049         struct pool_c *pt = ti->private;
3050
3051         mutex_lock(&dm_thin_pool_table.mutex);
3052
3053         unbind_control_target(pt->pool, ti);
3054         __pool_dec(pt->pool);
3055         dm_put_device(ti, pt->metadata_dev);
3056         dm_put_device(ti, pt->data_dev);
3057         kfree(pt);
3058
3059         mutex_unlock(&dm_thin_pool_table.mutex);
3060 }
3061
3062 static int parse_pool_features(struct dm_arg_set *as, struct pool_features *pf,
3063                                struct dm_target *ti)
3064 {
3065         int r;
3066         unsigned argc;
3067         const char *arg_name;
3068
3069         static struct dm_arg _args[] = {
3070                 {0, 4, "Invalid number of pool feature arguments"},
3071         };
3072
3073         /*
3074          * No feature arguments supplied.
3075          */
3076         if (!as->argc)
3077                 return 0;
3078
3079         r = dm_read_arg_group(_args, as, &argc, &ti->error);
3080         if (r)
3081                 return -EINVAL;
3082
3083         while (argc && !r) {
3084                 arg_name = dm_shift_arg(as);
3085                 argc--;
3086
3087                 if (!strcasecmp(arg_name, "skip_block_zeroing"))
3088                         pf->zero_new_blocks = false;
3089
3090                 else if (!strcasecmp(arg_name, "ignore_discard"))
3091                         pf->discard_enabled = false;
3092
3093                 else if (!strcasecmp(arg_name, "no_discard_passdown"))
3094                         pf->discard_passdown = false;
3095
3096                 else if (!strcasecmp(arg_name, "read_only"))
3097                         pf->mode = PM_READ_ONLY;
3098
3099                 else if (!strcasecmp(arg_name, "error_if_no_space"))
3100                         pf->error_if_no_space = true;
3101
3102                 else {
3103                         ti->error = "Unrecognised pool feature requested";
3104                         r = -EINVAL;
3105                         break;
3106                 }
3107         }
3108
3109         return r;
3110 }
3111
3112 static void metadata_low_callback(void *context)
3113 {
3114         struct pool *pool = context;
3115
3116         DMWARN("%s: reached low water mark for metadata device: sending event.",
3117                dm_device_name(pool->pool_md));
3118
3119         dm_table_event(pool->ti->table);
3120 }
3121
3122 static sector_t get_dev_size(struct block_device *bdev)
3123 {
3124         return i_size_read(bdev->bd_inode) >> SECTOR_SHIFT;
3125 }
3126
3127 static void warn_if_metadata_device_too_big(struct block_device *bdev)
3128 {
3129         sector_t metadata_dev_size = get_dev_size(bdev);
3130         char buffer[BDEVNAME_SIZE];
3131
3132         if (metadata_dev_size > THIN_METADATA_MAX_SECTORS_WARNING)
3133                 DMWARN("Metadata device %s is larger than %u sectors: excess space will not be used.",
3134                        bdevname(bdev, buffer), THIN_METADATA_MAX_SECTORS);
3135 }
3136
3137 static sector_t get_metadata_dev_size(struct block_device *bdev)
3138 {
3139         sector_t metadata_dev_size = get_dev_size(bdev);
3140
3141         if (metadata_dev_size > THIN_METADATA_MAX_SECTORS)
3142                 metadata_dev_size = THIN_METADATA_MAX_SECTORS;
3143
3144         return metadata_dev_size;
3145 }
3146
3147 static dm_block_t get_metadata_dev_size_in_blocks(struct block_device *bdev)
3148 {
3149         sector_t metadata_dev_size = get_metadata_dev_size(bdev);
3150
3151         sector_div(metadata_dev_size, THIN_METADATA_BLOCK_SIZE);
3152
3153         return metadata_dev_size;
3154 }
3155
3156 /*
3157  * When a metadata threshold is crossed a dm event is triggered, and
3158  * userland should respond by growing the metadata device.  We could let
3159  * userland set the threshold, like we do with the data threshold, but I'm
3160  * not sure they know enough to do this well.
3161  */
3162 static dm_block_t calc_metadata_threshold(struct pool_c *pt)
3163 {
3164         /*
3165          * 4M is ample for all ops with the possible exception of thin
3166          * device deletion which is harmless if it fails (just retry the
3167          * delete after you've grown the device).
3168          */
3169         dm_block_t quarter = get_metadata_dev_size_in_blocks(pt->metadata_dev->bdev) / 4;
3170         return min((dm_block_t)1024ULL /* 4M */, quarter);
3171 }
3172
3173 /*
3174  * thin-pool <metadata dev> <data dev>
3175  *           <data block size (sectors)>
3176  *           <low water mark (blocks)>
3177  *           [<#feature args> [<arg>]*]
3178  *
3179  * Optional feature arguments are:
3180  *           skip_block_zeroing: skips the zeroing of newly-provisioned blocks.
3181  *           ignore_discard: disable discard
3182  *           no_discard_passdown: don't pass discards down to the data device
3183  *           read_only: Don't allow any changes to be made to the pool metadata.
3184  *           error_if_no_space: error IOs, instead of queueing, if no space.
3185  */
3186 static int pool_ctr(struct dm_target *ti, unsigned argc, char **argv)
3187 {
3188         int r, pool_created = 0;
3189         struct pool_c *pt;
3190         struct pool *pool;
3191         struct pool_features pf;
3192         struct dm_arg_set as;
3193         struct dm_dev *data_dev;
3194         unsigned long block_size;
3195         dm_block_t low_water_blocks;
3196         struct dm_dev *metadata_dev;
3197         fmode_t metadata_mode;
3198
3199         /*
3200          * FIXME Remove validation from scope of lock.
3201          */
3202         mutex_lock(&dm_thin_pool_table.mutex);
3203
3204         if (argc < 4) {
3205                 ti->error = "Invalid argument count";
3206                 r = -EINVAL;
3207                 goto out_unlock;
3208         }
3209
3210         as.argc = argc;
3211         as.argv = argv;
3212
3213         /* make sure metadata and data are different devices */
3214         if (!strcmp(argv[0], argv[1])) {
3215                 ti->error = "Error setting metadata or data device";
3216                 r = -EINVAL;
3217                 goto out_unlock;
3218         }
3219
3220         /*
3221          * Set default pool features.
3222          */
3223         pool_features_init(&pf);
3224
3225         dm_consume_args(&as, 4);
3226         r = parse_pool_features(&as, &pf, ti);
3227         if (r)
3228                 goto out_unlock;
3229
3230         metadata_mode = FMODE_READ | ((pf.mode == PM_READ_ONLY) ? 0 : FMODE_WRITE);
3231         r = dm_get_device(ti, argv[0], metadata_mode, &metadata_dev);
3232         if (r) {
3233                 ti->error = "Error opening metadata block device";
3234                 goto out_unlock;
3235         }
3236         warn_if_metadata_device_too_big(metadata_dev->bdev);
3237
3238         r = dm_get_device(ti, argv[1], FMODE_READ | FMODE_WRITE, &data_dev);
3239         if (r) {
3240                 ti->error = "Error getting data device";
3241                 goto out_metadata;
3242         }
3243
3244         if (kstrtoul(argv[2], 10, &block_size) || !block_size ||
3245             block_size < DATA_DEV_BLOCK_SIZE_MIN_SECTORS ||
3246             block_size > DATA_DEV_BLOCK_SIZE_MAX_SECTORS ||
3247             block_size & (DATA_DEV_BLOCK_SIZE_MIN_SECTORS - 1)) {
3248                 ti->error = "Invalid block size";
3249                 r = -EINVAL;
3250                 goto out;
3251         }
3252
3253         if (kstrtoull(argv[3], 10, (unsigned long long *)&low_water_blocks)) {
3254                 ti->error = "Invalid low water mark";
3255                 r = -EINVAL;
3256                 goto out;
3257         }
3258
3259         pt = kzalloc(sizeof(*pt), GFP_KERNEL);
3260         if (!pt) {
3261                 r = -ENOMEM;
3262                 goto out;
3263         }
3264
3265         pool = __pool_find(dm_table_get_md(ti->table), metadata_dev->bdev,
3266                            block_size, pf.mode == PM_READ_ONLY, &ti->error, &pool_created);
3267         if (IS_ERR(pool)) {
3268                 r = PTR_ERR(pool);
3269                 goto out_free_pt;
3270         }
3271
3272         /*
3273          * 'pool_created' reflects whether this is the first table load.
3274          * Top level discard support is not allowed to be changed after
3275          * initial load.  This would require a pool reload to trigger thin
3276          * device changes.
3277          */
3278         if (!pool_created && pf.discard_enabled != pool->pf.discard_enabled) {
3279                 ti->error = "Discard support cannot be disabled once enabled";
3280                 r = -EINVAL;
3281                 goto out_flags_changed;
3282         }
3283
3284         pt->pool = pool;
3285         pt->ti = ti;
3286         pt->metadata_dev = metadata_dev;
3287         pt->data_dev = data_dev;
3288         pt->low_water_blocks = low_water_blocks;
3289         pt->adjusted_pf = pt->requested_pf = pf;
3290         ti->num_flush_bios = 1;
3291
3292         /*
3293          * Only need to enable discards if the pool should pass
3294          * them down to the data device.  The thin device's discard
3295          * processing will cause mappings to be removed from the btree.
3296          */
3297         ti->discard_zeroes_data_unsupported = true;
3298         if (pf.discard_enabled && pf.discard_passdown) {
3299                 ti->num_discard_bios = 1;
3300
3301                 /*
3302                  * Setting 'discards_supported' circumvents the normal
3303                  * stacking of discard limits (this keeps the pool and
3304                  * thin devices' discard limits consistent).
3305                  */
3306                 ti->discards_supported = true;
3307         }
3308         ti->private = pt;
3309
3310         r = dm_pool_register_metadata_threshold(pt->pool->pmd,
3311                                                 calc_metadata_threshold(pt),
3312                                                 metadata_low_callback,
3313                                                 pool);
3314         if (r)
3315                 goto out_flags_changed;
3316
3317         pt->callbacks.congested_fn = pool_is_congested;
3318         dm_table_add_target_callbacks(ti->table, &pt->callbacks);
3319
3320         mutex_unlock(&dm_thin_pool_table.mutex);
3321
3322         return 0;
3323
3324 out_flags_changed:
3325         __pool_dec(pool);
3326 out_free_pt:
3327         kfree(pt);
3328 out:
3329         dm_put_device(ti, data_dev);
3330 out_metadata:
3331         dm_put_device(ti, metadata_dev);
3332 out_unlock:
3333         mutex_unlock(&dm_thin_pool_table.mutex);
3334
3335         return r;
3336 }
3337
3338 static int pool_map(struct dm_target *ti, struct bio *bio)
3339 {
3340         int r;
3341         struct pool_c *pt = ti->private;
3342         struct pool *pool = pt->pool;
3343         unsigned long flags;
3344
3345         /*
3346          * As this is a singleton target, ti->begin is always zero.
3347          */
3348         spin_lock_irqsave(&pool->lock, flags);
3349         bio->bi_bdev = pt->data_dev->bdev;
3350         r = DM_MAPIO_REMAPPED;
3351         spin_unlock_irqrestore(&pool->lock, flags);
3352
3353         return r;
3354 }
3355
3356 static int maybe_resize_data_dev(struct dm_target *ti, bool *need_commit)
3357 {
3358         int r;
3359         struct pool_c *pt = ti->private;
3360         struct pool *pool = pt->pool;
3361         sector_t data_size = ti->len;
3362         dm_block_t sb_data_size;
3363
3364         *need_commit = false;
3365
3366         (void) sector_div(data_size, pool->sectors_per_block);
3367
3368         r = dm_pool_get_data_dev_size(pool->pmd, &sb_data_size);
3369         if (r) {
3370                 DMERR("%s: failed to retrieve data device size",
3371                       dm_device_name(pool->pool_md));
3372                 return r;
3373         }
3374
3375         if (data_size < sb_data_size) {
3376                 DMERR("%s: pool target (%llu blocks) too small: expected %llu",
3377                       dm_device_name(pool->pool_md),
3378                       (unsigned long long)data_size, sb_data_size);
3379                 return -EINVAL;
3380
3381         } else if (data_size > sb_data_size) {
3382                 if (dm_pool_metadata_needs_check(pool->pmd)) {
3383                         DMERR("%s: unable to grow the data device until repaired.",
3384                               dm_device_name(pool->pool_md));
3385                         return 0;
3386                 }
3387
3388                 if (sb_data_size)
3389                         DMINFO("%s: growing the data device from %llu to %llu blocks",
3390                                dm_device_name(pool->pool_md),
3391                                sb_data_size, (unsigned long long)data_size);
3392                 r = dm_pool_resize_data_dev(pool->pmd, data_size);
3393                 if (r) {
3394                         metadata_operation_failed(pool, "dm_pool_resize_data_dev", r);
3395                         return r;
3396                 }
3397
3398                 *need_commit = true;
3399         }
3400
3401         return 0;
3402 }
3403
3404 static int maybe_resize_metadata_dev(struct dm_target *ti, bool *need_commit)
3405 {
3406         int r;
3407         struct pool_c *pt = ti->private;
3408         struct pool *pool = pt->pool;
3409         dm_block_t metadata_dev_size, sb_metadata_dev_size;
3410
3411         *need_commit = false;
3412
3413         metadata_dev_size = get_metadata_dev_size_in_blocks(pool->md_dev);
3414
3415         r = dm_pool_get_metadata_dev_size(pool->pmd, &sb_metadata_dev_size);
3416         if (r) {
3417                 DMERR("%s: failed to retrieve metadata device size",
3418                       dm_device_name(pool->pool_md));
3419                 return r;
3420         }
3421
3422         if (metadata_dev_size < sb_metadata_dev_size) {
3423                 DMERR("%s: metadata device (%llu blocks) too small: expected %llu",
3424                       dm_device_name(pool->pool_md),
3425                       metadata_dev_size, sb_metadata_dev_size);
3426                 return -EINVAL;
3427
3428         } else if (metadata_dev_size > sb_metadata_dev_size) {
3429                 if (dm_pool_metadata_needs_check(pool->pmd)) {
3430                         DMERR("%s: unable to grow the metadata device until repaired.",
3431                               dm_device_name(pool->pool_md));
3432                         return 0;
3433                 }
3434
3435                 warn_if_metadata_device_too_big(pool->md_dev);
3436                 DMINFO("%s: growing the metadata device from %llu to %llu blocks",
3437                        dm_device_name(pool->pool_md),
3438                        sb_metadata_dev_size, metadata_dev_size);
3439
3440                 if (get_pool_mode(pool) == PM_OUT_OF_METADATA_SPACE)
3441                         set_pool_mode(pool, PM_WRITE);
3442
3443                 r = dm_pool_resize_metadata_dev(pool->pmd, metadata_dev_size);
3444                 if (r) {
3445                         metadata_operation_failed(pool, "dm_pool_resize_metadata_dev", r);
3446                         return r;
3447                 }
3448
3449                 *need_commit = true;
3450         }
3451
3452         return 0;
3453 }
3454
3455 /*
3456  * Retrieves the number of blocks of the data device from
3457  * the superblock and compares it to the actual device size,
3458  * thus resizing the data device in case it has grown.
3459  *
3460  * This both copes with opening preallocated data devices in the ctr
3461  * being followed by a resume
3462  * -and-
3463  * calling the resume method individually after userspace has
3464  * grown the data device in reaction to a table event.
3465  */
3466 static int pool_preresume(struct dm_target *ti)
3467 {
3468         int r;
3469         bool need_commit1, need_commit2;
3470         struct pool_c *pt = ti->private;
3471         struct pool *pool = pt->pool;
3472
3473         /*
3474          * Take control of the pool object.
3475          */
3476         r = bind_control_target(pool, ti);
3477         if (r)
3478                 return r;
3479
3480         r = maybe_resize_data_dev(ti, &need_commit1);
3481         if (r)
3482                 return r;
3483
3484         r = maybe_resize_metadata_dev(ti, &need_commit2);
3485         if (r)
3486                 return r;
3487
3488         if (need_commit1 || need_commit2)
3489                 (void) commit(pool);
3490
3491         return 0;
3492 }
3493
3494 static void pool_suspend_active_thins(struct pool *pool)
3495 {
3496         struct thin_c *tc;
3497
3498         /* Suspend all active thin devices */
3499         tc = get_first_thin(pool);
3500         while (tc) {
3501                 dm_internal_suspend_noflush(tc->thin_md);
3502                 tc = get_next_thin(pool, tc);
3503         }
3504 }
3505
3506 static void pool_resume_active_thins(struct pool *pool)
3507 {
3508         struct thin_c *tc;
3509
3510         /* Resume all active thin devices */
3511         tc = get_first_thin(pool);
3512         while (tc) {
3513                 dm_internal_resume(tc->thin_md);
3514                 tc = get_next_thin(pool, tc);
3515         }
3516 }
3517
3518 static void pool_resume(struct dm_target *ti)
3519 {
3520         struct pool_c *pt = ti->private;
3521         struct pool *pool = pt->pool;
3522         unsigned long flags;
3523
3524         /*
3525          * Must requeue active_thins' bios and then resume
3526          * active_thins _before_ clearing 'suspend' flag.
3527          */
3528         requeue_bios(pool);
3529         pool_resume_active_thins(pool);
3530
3531         spin_lock_irqsave(&pool->lock, flags);
3532         pool->low_water_triggered = false;
3533         pool->suspended = false;
3534         spin_unlock_irqrestore(&pool->lock, flags);
3535
3536         do_waker(&pool->waker.work);
3537 }
3538
3539 static void pool_presuspend(struct dm_target *ti)
3540 {
3541         struct pool_c *pt = ti->private;
3542         struct pool *pool = pt->pool;
3543         unsigned long flags;
3544
3545         spin_lock_irqsave(&pool->lock, flags);
3546         pool->suspended = true;
3547         spin_unlock_irqrestore(&pool->lock, flags);
3548
3549         pool_suspend_active_thins(pool);
3550 }
3551
3552 static void pool_presuspend_undo(struct dm_target *ti)
3553 {
3554         struct pool_c *pt = ti->private;
3555         struct pool *pool = pt->pool;
3556         unsigned long flags;
3557
3558         pool_resume_active_thins(pool);
3559
3560         spin_lock_irqsave(&pool->lock, flags);
3561         pool->suspended = false;
3562         spin_unlock_irqrestore(&pool->lock, flags);
3563 }
3564
3565 static void pool_postsuspend(struct dm_target *ti)
3566 {
3567         struct pool_c *pt = ti->private;
3568         struct pool *pool = pt->pool;
3569
3570         cancel_delayed_work_sync(&pool->waker);
3571         cancel_delayed_work_sync(&pool->no_space_timeout);
3572         flush_workqueue(pool->wq);
3573         (void) commit(pool);
3574 }
3575
3576 static int check_arg_count(unsigned argc, unsigned args_required)
3577 {
3578         if (argc != args_required) {
3579                 DMWARN("Message received with %u arguments instead of %u.",
3580                        argc, args_required);
3581                 return -EINVAL;
3582         }
3583
3584         return 0;
3585 }
3586
3587 static int read_dev_id(char *arg, dm_thin_id *dev_id, int warning)
3588 {
3589         if (!kstrtoull(arg, 10, (unsigned long long *)dev_id) &&
3590             *dev_id <= MAX_DEV_ID)
3591                 return 0;
3592
3593         if (warning)
3594                 DMWARN("Message received with invalid device id: %s", arg);
3595
3596         return -EINVAL;
3597 }
3598
3599 static int process_create_thin_mesg(unsigned argc, char **argv, struct pool *pool)
3600 {
3601         dm_thin_id dev_id;
3602         int r;
3603
3604         r = check_arg_count(argc, 2);
3605         if (r)
3606                 return r;
3607
3608         r = read_dev_id(argv[1], &dev_id, 1);
3609         if (r)
3610                 return r;
3611
3612         r = dm_pool_create_thin(pool->pmd, dev_id);
3613         if (r) {
3614                 DMWARN("Creation of new thinly-provisioned device with id %s failed.",
3615                        argv[1]);
3616                 return r;
3617         }
3618
3619         return 0;
3620 }
3621
3622 static int process_create_snap_mesg(unsigned argc, char **argv, struct pool *pool)
3623 {
3624         dm_thin_id dev_id;
3625         dm_thin_id origin_dev_id;
3626         int r;
3627
3628         r = check_arg_count(argc, 3);
3629         if (r)
3630                 return r;
3631
3632         r = read_dev_id(argv[1], &dev_id, 1);
3633         if (r)
3634                 return r;
3635
3636         r = read_dev_id(argv[2], &origin_dev_id, 1);
3637         if (r)
3638                 return r;
3639
3640         r = dm_pool_create_snap(pool->pmd, dev_id, origin_dev_id);
3641         if (r) {
3642                 DMWARN("Creation of new snapshot %s of device %s failed.",
3643                        argv[1], argv[2]);
3644                 return r;
3645         }
3646
3647         return 0;
3648 }
3649
3650 static int process_delete_mesg(unsigned argc, char **argv, struct pool *pool)
3651 {
3652         dm_thin_id dev_id;
3653         int r;
3654
3655         r = check_arg_count(argc, 2);
3656         if (r)
3657                 return r;
3658
3659         r = read_dev_id(argv[1], &dev_id, 1);
3660         if (r)
3661                 return r;
3662
3663         r = dm_pool_delete_thin_device(pool->pmd, dev_id);
3664         if (r)
3665                 DMWARN("Deletion of thin device %s failed.", argv[1]);
3666
3667         return r;
3668 }
3669
3670 static int process_set_transaction_id_mesg(unsigned argc, char **argv, struct pool *pool)
3671 {
3672         dm_thin_id old_id, new_id;
3673         int r;
3674
3675         r = check_arg_count(argc, 3);
3676         if (r)
3677                 return r;
3678
3679         if (kstrtoull(argv[1], 10, (unsigned long long *)&old_id)) {
3680                 DMWARN("set_transaction_id message: Unrecognised id %s.", argv[1]);
3681                 return -EINVAL;
3682         }
3683
3684         if (kstrtoull(argv[2], 10, (unsigned long long *)&new_id)) {
3685                 DMWARN("set_transaction_id message: Unrecognised new id %s.", argv[2]);
3686                 return -EINVAL;
3687         }
3688
3689         r = dm_pool_set_metadata_transaction_id(pool->pmd, old_id, new_id);
3690         if (r) {
3691                 DMWARN("Failed to change transaction id from %s to %s.",
3692                        argv[1], argv[2]);
3693                 return r;
3694         }
3695
3696         return 0;
3697 }
3698
3699 static int process_reserve_metadata_snap_mesg(unsigned argc, char **argv, struct pool *pool)
3700 {
3701         int r;
3702
3703         r = check_arg_count(argc, 1);
3704         if (r)
3705                 return r;
3706
3707         (void) commit(pool);
3708
3709         r = dm_pool_reserve_metadata_snap(pool->pmd);
3710         if (r)
3711                 DMWARN("reserve_metadata_snap message failed.");
3712
3713         return r;
3714 }
3715
3716 static int process_release_metadata_snap_mesg(unsigned argc, char **argv, struct pool *pool)
3717 {
3718         int r;
3719
3720         r = check_arg_count(argc, 1);
3721         if (r)
3722                 return r;
3723
3724         r = dm_pool_release_metadata_snap(pool->pmd);
3725         if (r)
3726                 DMWARN("release_metadata_snap message failed.");
3727
3728         return r;
3729 }
3730
3731 /*
3732  * Messages supported:
3733  *   create_thin        <dev_id>
3734  *   create_snap        <dev_id> <origin_id>
3735  *   delete             <dev_id>
3736  *   set_transaction_id <current_trans_id> <new_trans_id>
3737  *   reserve_metadata_snap
3738  *   release_metadata_snap
3739  */
3740 static int pool_message(struct dm_target *ti, unsigned argc, char **argv)
3741 {
3742         int r = -EINVAL;
3743         struct pool_c *pt = ti->private;
3744         struct pool *pool = pt->pool;
3745
3746         if (get_pool_mode(pool) >= PM_OUT_OF_METADATA_SPACE) {
3747                 DMERR("%s: unable to service pool target messages in READ_ONLY or FAIL mode",
3748                       dm_device_name(pool->pool_md));
3749                 return -EOPNOTSUPP;
3750         }
3751
3752         if (!strcasecmp(argv[0], "create_thin"))
3753                 r = process_create_thin_mesg(argc, argv, pool);
3754
3755         else if (!strcasecmp(argv[0], "create_snap"))
3756                 r = process_create_snap_mesg(argc, argv, pool);
3757
3758         else if (!strcasecmp(argv[0], "delete"))
3759                 r = process_delete_mesg(argc, argv, pool);
3760
3761         else if (!strcasecmp(argv[0], "set_transaction_id"))
3762                 r = process_set_transaction_id_mesg(argc, argv, pool);
3763
3764         else if (!strcasecmp(argv[0], "reserve_metadata_snap"))
3765                 r = process_reserve_metadata_snap_mesg(argc, argv, pool);
3766
3767         else if (!strcasecmp(argv[0], "release_metadata_snap"))
3768                 r = process_release_metadata_snap_mesg(argc, argv, pool);
3769
3770         else
3771                 DMWARN("Unrecognised thin pool target message received: %s", argv[0]);
3772
3773         if (!r)
3774                 (void) commit(pool);
3775
3776         return r;
3777 }
3778
3779 static void emit_flags(struct pool_features *pf, char *result,
3780                        unsigned sz, unsigned maxlen)
3781 {
3782         unsigned count = !pf->zero_new_blocks + !pf->discard_enabled +
3783                 !pf->discard_passdown + (pf->mode == PM_READ_ONLY) +
3784                 pf->error_if_no_space;
3785         DMEMIT("%u ", count);
3786
3787         if (!pf->zero_new_blocks)
3788                 DMEMIT("skip_block_zeroing ");
3789
3790         if (!pf->discard_enabled)
3791                 DMEMIT("ignore_discard ");
3792
3793         if (!pf->discard_passdown)
3794                 DMEMIT("no_discard_passdown ");
3795
3796         if (pf->mode == PM_READ_ONLY)
3797                 DMEMIT("read_only ");
3798
3799         if (pf->error_if_no_space)
3800                 DMEMIT("error_if_no_space ");
3801 }
3802
3803 /*
3804  * Status line is:
3805  *    <transaction id> <used metadata sectors>/<total metadata sectors>
3806  *    <used data sectors>/<total data sectors> <held metadata root>
3807  *    <pool mode> <discard config> <no space config> <needs_check>
3808  */
3809 static void pool_status(struct dm_target *ti, status_type_t type,
3810                         unsigned status_flags, char *result, unsigned maxlen)
3811 {
3812         int r;
3813         unsigned sz = 0;
3814         uint64_t transaction_id;
3815         dm_block_t nr_free_blocks_data;
3816         dm_block_t nr_free_blocks_metadata;
3817         dm_block_t nr_blocks_data;
3818         dm_block_t nr_blocks_metadata;
3819         dm_block_t held_root;
3820         enum pool_mode mode;
3821         char buf[BDEVNAME_SIZE];
3822         char buf2[BDEVNAME_SIZE];
3823         struct pool_c *pt = ti->private;
3824         struct pool *pool = pt->pool;
3825
3826         switch (type) {
3827         case STATUSTYPE_INFO:
3828                 if (get_pool_mode(pool) == PM_FAIL) {
3829                         DMEMIT("Fail");
3830                         break;
3831                 }
3832
3833                 /* Commit to ensure statistics aren't out-of-date */
3834                 if (!(status_flags & DM_STATUS_NOFLUSH_FLAG) && !dm_suspended(ti))
3835                         (void) commit(pool);
3836
3837                 r = dm_pool_get_metadata_transaction_id(pool->pmd, &transaction_id);
3838                 if (r) {
3839                         DMERR("%s: dm_pool_get_metadata_transaction_id returned %d",
3840                               dm_device_name(pool->pool_md), r);
3841                         goto err;
3842                 }
3843
3844                 r = dm_pool_get_free_metadata_block_count(pool->pmd, &nr_free_blocks_metadata);
3845                 if (r) {
3846                         DMERR("%s: dm_pool_get_free_metadata_block_count returned %d",
3847                               dm_device_name(pool->pool_md), r);
3848                         goto err;
3849                 }
3850
3851                 r = dm_pool_get_metadata_dev_size(pool->pmd, &nr_blocks_metadata);
3852                 if (r) {
3853                         DMERR("%s: dm_pool_get_metadata_dev_size returned %d",
3854                               dm_device_name(pool->pool_md), r);
3855                         goto err;
3856                 }
3857
3858                 r = dm_pool_get_free_block_count(pool->pmd, &nr_free_blocks_data);
3859                 if (r) {
3860                         DMERR("%s: dm_pool_get_free_block_count returned %d",
3861                               dm_device_name(pool->pool_md), r);
3862                         goto err;
3863                 }
3864
3865                 r = dm_pool_get_data_dev_size(pool->pmd, &nr_blocks_data);
3866                 if (r) {
3867                         DMERR("%s: dm_pool_get_data_dev_size returned %d",
3868                               dm_device_name(pool->pool_md), r);
3869                         goto err;
3870                 }
3871
3872                 r = dm_pool_get_metadata_snap(pool->pmd, &held_root);
3873                 if (r) {
3874                         DMERR("%s: dm_pool_get_metadata_snap returned %d",
3875                               dm_device_name(pool->pool_md), r);
3876                         goto err;
3877                 }
3878
3879                 DMEMIT("%llu %llu/%llu %llu/%llu ",
3880                        (unsigned long long)transaction_id,
3881                        (unsigned long long)(nr_blocks_metadata - nr_free_blocks_metadata),
3882                        (unsigned long long)nr_blocks_metadata,
3883                        (unsigned long long)(nr_blocks_data - nr_free_blocks_data),
3884                        (unsigned long long)nr_blocks_data);
3885
3886                 if (held_root)
3887                         DMEMIT("%llu ", held_root);
3888                 else
3889                         DMEMIT("- ");
3890
3891                 mode = get_pool_mode(pool);
3892                 if (mode == PM_OUT_OF_DATA_SPACE)
3893                         DMEMIT("out_of_data_space ");
3894                 else if (is_read_only_pool_mode(mode))
3895                         DMEMIT("ro ");
3896                 else
3897                         DMEMIT("rw ");
3898
3899                 if (!pool->pf.discard_enabled)
3900                         DMEMIT("ignore_discard ");
3901                 else if (pool->pf.discard_passdown)
3902                         DMEMIT("discard_passdown ");
3903                 else
3904                         DMEMIT("no_discard_passdown ");
3905
3906                 if (pool->pf.error_if_no_space)
3907                         DMEMIT("error_if_no_space ");
3908                 else
3909                         DMEMIT("queue_if_no_space ");
3910
3911                 if (dm_pool_metadata_needs_check(pool->pmd))
3912                         DMEMIT("needs_check ");
3913                 else
3914                         DMEMIT("- ");
3915
3916                 break;
3917
3918         case STATUSTYPE_TABLE:
3919                 DMEMIT("%s %s %lu %llu ",
3920                        format_dev_t(buf, pt->metadata_dev->bdev->bd_dev),
3921                        format_dev_t(buf2, pt->data_dev->bdev->bd_dev),
3922                        (unsigned long)pool->sectors_per_block,
3923                        (unsigned long long)pt->low_water_blocks);
3924                 emit_flags(&pt->requested_pf, result, sz, maxlen);
3925                 break;
3926         }
3927         return;
3928
3929 err:
3930         DMEMIT("Error");
3931 }
3932
3933 static int pool_iterate_devices(struct dm_target *ti,
3934                                 iterate_devices_callout_fn fn, void *data)
3935 {
3936         struct pool_c *pt = ti->private;
3937
3938         return fn(ti, pt->data_dev, 0, ti->len, data);
3939 }
3940
3941 static void pool_io_hints(struct dm_target *ti, struct queue_limits *limits)
3942 {
3943         struct pool_c *pt = ti->private;
3944         struct pool *pool = pt->pool;
3945         sector_t io_opt_sectors = limits->io_opt >> SECTOR_SHIFT;
3946
3947         /*
3948          * If max_sectors is smaller than pool->sectors_per_block adjust it
3949          * to the highest possible power-of-2 factor of pool->sectors_per_block.
3950          * This is especially beneficial when the pool's data device is a RAID
3951          * device that has a full stripe width that matches pool->sectors_per_block
3952          * -- because even though partial RAID stripe-sized IOs will be issued to a
3953          *    single RAID stripe; when aggregated they will end on a full RAID stripe
3954          *    boundary.. which avoids additional partial RAID stripe writes cascading
3955          */
3956         if (limits->max_sectors < pool->sectors_per_block) {
3957                 while (!is_factor(pool->sectors_per_block, limits->max_sectors)) {
3958                         if ((limits->max_sectors & (limits->max_sectors - 1)) == 0)
3959                                 limits->max_sectors--;
3960                         limits->max_sectors = rounddown_pow_of_two(limits->max_sectors);
3961                 }
3962         }
3963
3964         /*
3965          * If the system-determined stacked limits are compatible with the
3966          * pool's blocksize (io_opt is a factor) do not override them.
3967          */
3968         if (io_opt_sectors < pool->sectors_per_block ||
3969             !is_factor(io_opt_sectors, pool->sectors_per_block)) {
3970                 if (is_factor(pool->sectors_per_block, limits->max_sectors))
3971                         blk_limits_io_min(limits, limits->max_sectors << SECTOR_SHIFT);
3972                 else
3973                         blk_limits_io_min(limits, pool->sectors_per_block << SECTOR_SHIFT);
3974                 blk_limits_io_opt(limits, pool->sectors_per_block << SECTOR_SHIFT);
3975         }
3976
3977         /*
3978          * pt->adjusted_pf is a staging area for the actual features to use.
3979          * They get transferred to the live pool in bind_control_target()
3980          * called from pool_preresume().
3981          */
3982         if (!pt->adjusted_pf.discard_enabled) {
3983                 /*
3984                  * Must explicitly disallow stacking discard limits otherwise the
3985                  * block layer will stack them if pool's data device has support.
3986                  * QUEUE_FLAG_DISCARD wouldn't be set but there is no way for the
3987                  * user to see that, so make sure to set all discard limits to 0.
3988                  */
3989                 limits->discard_granularity = 0;
3990                 return;
3991         }
3992
3993         disable_passdown_if_not_supported(pt);
3994
3995         /*
3996          * The pool uses the same discard limits as the underlying data
3997          * device.  DM core has already set this up.
3998          */
3999 }
4000
4001 static struct target_type pool_target = {
4002         .name = "thin-pool",
4003         .features = DM_TARGET_SINGLETON | DM_TARGET_ALWAYS_WRITEABLE |
4004                     DM_TARGET_IMMUTABLE,
4005         .version = {1, 16, 0},
4006         .module = THIS_MODULE,
4007         .ctr = pool_ctr,
4008         .dtr = pool_dtr,
4009         .map = pool_map,
4010         .presuspend = pool_presuspend,
4011         .presuspend_undo = pool_presuspend_undo,
4012         .postsuspend = pool_postsuspend,
4013         .preresume = pool_preresume,
4014         .resume = pool_resume,
4015         .message = pool_message,
4016         .status = pool_status,
4017         .iterate_devices = pool_iterate_devices,
4018         .io_hints = pool_io_hints,
4019 };
4020
4021 /*----------------------------------------------------------------
4022  * Thin target methods
4023  *--------------------------------------------------------------*/
4024 static void thin_get(struct thin_c *tc)
4025 {
4026         atomic_inc(&tc->refcount);
4027 }
4028
4029 static void thin_put(struct thin_c *tc)
4030 {
4031         if (atomic_dec_and_test(&tc->refcount))
4032                 complete(&tc->can_destroy);
4033 }
4034
4035 static void thin_dtr(struct dm_target *ti)
4036 {
4037         struct thin_c *tc = ti->private;
4038         unsigned long flags;
4039
4040         spin_lock_irqsave(&tc->pool->lock, flags);
4041         list_del_rcu(&tc->list);
4042         spin_unlock_irqrestore(&tc->pool->lock, flags);
4043         synchronize_rcu();
4044
4045         thin_put(tc);
4046         wait_for_completion(&tc->can_destroy);
4047
4048         mutex_lock(&dm_thin_pool_table.mutex);
4049
4050         __pool_dec(tc->pool);
4051         dm_pool_close_thin_device(tc->td);
4052         dm_put_device(ti, tc->pool_dev);
4053         if (tc->origin_dev)
4054                 dm_put_device(ti, tc->origin_dev);
4055         kfree(tc);
4056
4057         mutex_unlock(&dm_thin_pool_table.mutex);
4058 }
4059
4060 /*
4061  * Thin target parameters:
4062  *
4063  * <pool_dev> <dev_id> [origin_dev]
4064  *
4065  * pool_dev: the path to the pool (eg, /dev/mapper/my_pool)
4066  * dev_id: the internal device identifier
4067  * origin_dev: a device external to the pool that should act as the origin
4068  *
4069  * If the pool device has discards disabled, they get disabled for the thin
4070  * device as well.
4071  */
4072 static int thin_ctr(struct dm_target *ti, unsigned argc, char **argv)
4073 {
4074         int r;
4075         struct thin_c *tc;
4076         struct dm_dev *pool_dev, *origin_dev;
4077         struct mapped_device *pool_md;
4078         unsigned long flags;
4079
4080         mutex_lock(&dm_thin_pool_table.mutex);
4081
4082         if (argc != 2 && argc != 3) {
4083                 ti->error = "Invalid argument count";
4084                 r = -EINVAL;
4085                 goto out_unlock;
4086         }
4087
4088         tc = ti->private = kzalloc(sizeof(*tc), GFP_KERNEL);
4089         if (!tc) {
4090                 ti->error = "Out of memory";
4091                 r = -ENOMEM;
4092                 goto out_unlock;
4093         }
4094         tc->thin_md = dm_table_get_md(ti->table);
4095         spin_lock_init(&tc->lock);
4096         INIT_LIST_HEAD(&tc->deferred_cells);
4097         bio_list_init(&tc->deferred_bio_list);
4098         bio_list_init(&tc->retry_on_resume_list);
4099         tc->sort_bio_list = RB_ROOT;
4100
4101         if (argc == 3) {
4102                 if (!strcmp(argv[0], argv[2])) {
4103                         ti->error = "Error setting origin device";
4104                         r = -EINVAL;
4105                         goto bad_origin_dev;
4106                 }
4107
4108                 r = dm_get_device(ti, argv[2], FMODE_READ, &origin_dev);
4109                 if (r) {
4110                         ti->error = "Error opening origin device";
4111                         goto bad_origin_dev;
4112                 }
4113                 tc->origin_dev = origin_dev;
4114         }
4115
4116         r = dm_get_device(ti, argv[0], dm_table_get_mode(ti->table), &pool_dev);
4117         if (r) {
4118                 ti->error = "Error opening pool device";
4119                 goto bad_pool_dev;
4120         }
4121         tc->pool_dev = pool_dev;
4122
4123         if (read_dev_id(argv[1], (unsigned long long *)&tc->dev_id, 0)) {
4124                 ti->error = "Invalid device id";
4125                 r = -EINVAL;
4126                 goto bad_common;
4127         }
4128
4129         pool_md = dm_get_md(tc->pool_dev->bdev->bd_dev);
4130         if (!pool_md) {
4131                 ti->error = "Couldn't get pool mapped device";
4132                 r = -EINVAL;
4133                 goto bad_common;
4134         }
4135
4136         tc->pool = __pool_table_lookup(pool_md);
4137         if (!tc->pool) {
4138                 ti->error = "Couldn't find pool object";
4139                 r = -EINVAL;
4140                 goto bad_pool_lookup;
4141         }
4142         __pool_inc(tc->pool);
4143
4144         if (get_pool_mode(tc->pool) == PM_FAIL) {
4145                 ti->error = "Couldn't open thin device, Pool is in fail mode";
4146                 r = -EINVAL;
4147                 goto bad_pool;
4148         }
4149
4150         r = dm_pool_open_thin_device(tc->pool->pmd, tc->dev_id, &tc->td);
4151         if (r) {
4152                 ti->error = "Couldn't open thin internal device";
4153                 goto bad_pool;
4154         }
4155
4156         r = dm_set_target_max_io_len(ti, tc->pool->sectors_per_block);
4157         if (r)
4158                 goto bad;
4159
4160         ti->num_flush_bios = 1;
4161         ti->flush_supported = true;
4162         ti->per_bio_data_size = sizeof(struct dm_thin_endio_hook);
4163
4164         /* In case the pool supports discards, pass them on. */
4165         ti->discard_zeroes_data_unsupported = true;
4166         if (tc->pool->pf.discard_enabled) {
4167                 ti->discards_supported = true;
4168                 ti->num_discard_bios = 1;
4169                 ti->split_discard_bios = false;
4170         }
4171
4172         mutex_unlock(&dm_thin_pool_table.mutex);
4173
4174         spin_lock_irqsave(&tc->pool->lock, flags);
4175         if (tc->pool->suspended) {
4176                 spin_unlock_irqrestore(&tc->pool->lock, flags);
4177                 mutex_lock(&dm_thin_pool_table.mutex); /* reacquire for __pool_dec */
4178                 ti->error = "Unable to activate thin device while pool is suspended";
4179                 r = -EINVAL;
4180                 goto bad;
4181         }
4182         atomic_set(&tc->refcount, 1);
4183         init_completion(&tc->can_destroy);
4184         list_add_tail_rcu(&tc->list, &tc->pool->active_thins);
4185         spin_unlock_irqrestore(&tc->pool->lock, flags);
4186         /*
4187          * This synchronize_rcu() call is needed here otherwise we risk a
4188          * wake_worker() call finding no bios to process (because the newly
4189          * added tc isn't yet visible).  So this reduces latency since we
4190          * aren't then dependent on the periodic commit to wake_worker().
4191          */
4192         synchronize_rcu();
4193
4194         dm_put(pool_md);
4195
4196         return 0;
4197
4198 bad:
4199         dm_pool_close_thin_device(tc->td);
4200 bad_pool:
4201         __pool_dec(tc->pool);
4202 bad_pool_lookup:
4203         dm_put(pool_md);
4204 bad_common:
4205         dm_put_device(ti, tc->pool_dev);
4206 bad_pool_dev:
4207         if (tc->origin_dev)
4208                 dm_put_device(ti, tc->origin_dev);
4209 bad_origin_dev:
4210         kfree(tc);
4211 out_unlock:
4212         mutex_unlock(&dm_thin_pool_table.mutex);
4213
4214         return r;
4215 }
4216
4217 static int thin_map(struct dm_target *ti, struct bio *bio)
4218 {
4219         bio->bi_iter.bi_sector = dm_target_offset(ti, bio->bi_iter.bi_sector);
4220
4221         return thin_bio_map(ti, bio);
4222 }
4223
4224 static int thin_endio(struct dm_target *ti, struct bio *bio, int err)
4225 {
4226         unsigned long flags;
4227         struct dm_thin_endio_hook *h = dm_per_bio_data(bio, sizeof(struct dm_thin_endio_hook));
4228         struct list_head work;
4229         struct dm_thin_new_mapping *m, *tmp;
4230         struct pool *pool = h->tc->pool;
4231
4232         if (h->shared_read_entry) {
4233                 INIT_LIST_HEAD(&work);
4234                 dm_deferred_entry_dec(h->shared_read_entry, &work);
4235
4236                 spin_lock_irqsave(&pool->lock, flags);
4237                 list_for_each_entry_safe(m, tmp, &work, list) {
4238                         list_del(&m->list);
4239                         __complete_mapping_preparation(m);
4240                 }
4241                 spin_unlock_irqrestore(&pool->lock, flags);
4242         }
4243
4244         if (h->all_io_entry) {
4245                 INIT_LIST_HEAD(&work);
4246                 dm_deferred_entry_dec(h->all_io_entry, &work);
4247                 if (!list_empty(&work)) {
4248                         spin_lock_irqsave(&pool->lock, flags);
4249                         list_for_each_entry_safe(m, tmp, &work, list)
4250                                 list_add_tail(&m->list, &pool->prepared_discards);
4251                         spin_unlock_irqrestore(&pool->lock, flags);
4252                         wake_worker(pool);
4253                 }
4254         }
4255
4256         if (h->cell)
4257                 cell_defer_no_holder(h->tc, h->cell);
4258
4259         return 0;
4260 }
4261
4262 static void thin_presuspend(struct dm_target *ti)
4263 {
4264         struct thin_c *tc = ti->private;
4265
4266         if (dm_noflush_suspending(ti))
4267                 noflush_work(tc, do_noflush_start);
4268 }
4269
4270 static void thin_postsuspend(struct dm_target *ti)
4271 {
4272         struct thin_c *tc = ti->private;
4273
4274         /*
4275          * The dm_noflush_suspending flag has been cleared by now, so
4276          * unfortunately we must always run this.
4277          */
4278         noflush_work(tc, do_noflush_stop);
4279 }
4280
4281 static int thin_preresume(struct dm_target *ti)
4282 {
4283         struct thin_c *tc = ti->private;
4284
4285         if (tc->origin_dev)
4286                 tc->origin_size = get_dev_size(tc->origin_dev->bdev);
4287
4288         return 0;
4289 }
4290
4291 /*
4292  * <nr mapped sectors> <highest mapped sector>
4293  */
4294 static void thin_status(struct dm_target *ti, status_type_t type,
4295                         unsigned status_flags, char *result, unsigned maxlen)
4296 {
4297         int r;
4298         ssize_t sz = 0;
4299         dm_block_t mapped, highest;
4300         char buf[BDEVNAME_SIZE];
4301         struct thin_c *tc = ti->private;
4302
4303         if (get_pool_mode(tc->pool) == PM_FAIL) {
4304                 DMEMIT("Fail");
4305                 return;
4306         }
4307
4308         if (!tc->td)
4309                 DMEMIT("-");
4310         else {
4311                 switch (type) {
4312                 case STATUSTYPE_INFO:
4313                         r = dm_thin_get_mapped_count(tc->td, &mapped);
4314                         if (r) {
4315                                 DMERR("dm_thin_get_mapped_count returned %d", r);
4316                                 goto err;
4317                         }
4318
4319                         r = dm_thin_get_highest_mapped_block(tc->td, &highest);
4320                         if (r < 0) {
4321                                 DMERR("dm_thin_get_highest_mapped_block returned %d", r);
4322                                 goto err;
4323                         }
4324
4325                         DMEMIT("%llu ", mapped * tc->pool->sectors_per_block);
4326                         if (r)
4327                                 DMEMIT("%llu", ((highest + 1) *
4328                                                 tc->pool->sectors_per_block) - 1);
4329                         else
4330                                 DMEMIT("-");
4331                         break;
4332
4333                 case STATUSTYPE_TABLE:
4334                         DMEMIT("%s %lu",
4335                                format_dev_t(buf, tc->pool_dev->bdev->bd_dev),
4336                                (unsigned long) tc->dev_id);
4337                         if (tc->origin_dev)
4338                                 DMEMIT(" %s", format_dev_t(buf, tc->origin_dev->bdev->bd_dev));
4339                         break;
4340                 }
4341         }
4342
4343         return;
4344
4345 err:
4346         DMEMIT("Error");
4347 }
4348
4349 static int thin_iterate_devices(struct dm_target *ti,
4350                                 iterate_devices_callout_fn fn, void *data)
4351 {
4352         sector_t blocks;
4353         struct thin_c *tc = ti->private;
4354         struct pool *pool = tc->pool;
4355
4356         /*
4357          * We can't call dm_pool_get_data_dev_size() since that blocks.  So
4358          * we follow a more convoluted path through to the pool's target.
4359          */
4360         if (!pool->ti)
4361                 return 0;       /* nothing is bound */
4362
4363         blocks = pool->ti->len;
4364         (void) sector_div(blocks, pool->sectors_per_block);
4365         if (blocks)
4366                 return fn(ti, tc->pool_dev, 0, pool->sectors_per_block * blocks, data);
4367
4368         return 0;
4369 }
4370
4371 static void thin_io_hints(struct dm_target *ti, struct queue_limits *limits)
4372 {
4373         struct thin_c *tc = ti->private;
4374         struct pool *pool = tc->pool;
4375
4376         if (!pool->pf.discard_enabled)
4377                 return;
4378
4379         limits->discard_granularity = pool->sectors_per_block << SECTOR_SHIFT;
4380         limits->max_discard_sectors = 2048 * 1024 * 16; /* 16G */
4381 }
4382
4383 static struct target_type thin_target = {
4384         .name = "thin",
4385         .version = {1, 16, 0},
4386         .module = THIS_MODULE,
4387         .ctr = thin_ctr,
4388         .dtr = thin_dtr,
4389         .map = thin_map,
4390         .end_io = thin_endio,
4391         .preresume = thin_preresume,
4392         .presuspend = thin_presuspend,
4393         .postsuspend = thin_postsuspend,
4394         .status = thin_status,
4395         .iterate_devices = thin_iterate_devices,
4396         .io_hints = thin_io_hints,
4397 };
4398
4399 /*----------------------------------------------------------------*/
4400
4401 static int __init dm_thin_init(void)
4402 {
4403         int r;
4404
4405         pool_table_init();
4406
4407         r = dm_register_target(&thin_target);
4408         if (r)
4409                 return r;
4410
4411         r = dm_register_target(&pool_target);
4412         if (r)
4413                 goto bad_pool_target;
4414
4415         r = -ENOMEM;
4416
4417         _new_mapping_cache = KMEM_CACHE(dm_thin_new_mapping, 0);
4418         if (!_new_mapping_cache)
4419                 goto bad_new_mapping_cache;
4420
4421         return 0;
4422
4423 bad_new_mapping_cache:
4424         dm_unregister_target(&pool_target);
4425 bad_pool_target:
4426         dm_unregister_target(&thin_target);
4427
4428         return r;
4429 }
4430
4431 static void dm_thin_exit(void)
4432 {
4433         dm_unregister_target(&thin_target);
4434         dm_unregister_target(&pool_target);
4435
4436         kmem_cache_destroy(_new_mapping_cache);
4437 }
4438
4439 module_init(dm_thin_init);
4440 module_exit(dm_thin_exit);
4441
4442 module_param_named(no_space_timeout, no_space_timeout_secs, uint, S_IRUGO | S_IWUSR);
4443 MODULE_PARM_DESC(no_space_timeout, "Out of data space queue IO timeout in seconds");
4444
4445 MODULE_DESCRIPTION(DM_NAME " thin provisioning target");
4446 MODULE_AUTHOR("Joe Thornber <dm-devel@redhat.com>");
4447 MODULE_LICENSE("GPL");