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