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