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