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