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