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