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