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