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