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