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