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