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