2 * Copyright (C) 2011-2012 Red Hat UK.
4 * This file is released under the GPL.
7 #include "dm-thin-metadata.h"
8 #include "dm-bio-prison.h"
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/sort.h>
22 #include <linux/rbtree.h>
24 #define DM_MSG_PREFIX "thin"
29 #define ENDIO_HOOK_POOL_SIZE 1024
30 #define MAPPING_POOL_SIZE 1024
31 #define COMMIT_PERIOD HZ
32 #define NO_SPACE_TIMEOUT_SECS 60
34 static unsigned no_space_timeout_secs = NO_SPACE_TIMEOUT_SECS;
36 DECLARE_DM_KCOPYD_THROTTLE_WITH_MODULE_PARM(snapshot_copy_throttle,
37 "A percentage of time allocated for copy on write");
40 * The block size of the device holding pool data must be
41 * between 64KB and 1GB.
43 #define DATA_DEV_BLOCK_SIZE_MIN_SECTORS (64 * 1024 >> SECTOR_SHIFT)
44 #define DATA_DEV_BLOCK_SIZE_MAX_SECTORS (1024 * 1024 * 1024 >> SECTOR_SHIFT)
47 * Device id is restricted to 24 bits.
49 #define MAX_DEV_ID ((1 << 24) - 1)
52 * How do we handle breaking sharing of data blocks?
53 * =================================================
55 * We use a standard copy-on-write btree to store the mappings for the
56 * devices (note I'm talking about copy-on-write of the metadata here, not
57 * the data). When you take an internal snapshot you clone the root node
58 * of the origin btree. After this there is no concept of an origin or a
59 * snapshot. They are just two device trees that happen to point to the
62 * When we get a write in we decide if it's to a shared data block using
63 * some timestamp magic. If it is, we have to break sharing.
65 * Let's say we write to a shared block in what was the origin. The
68 * i) plug io further to this physical block. (see bio_prison code).
70 * ii) quiesce any read io to that shared data block. Obviously
71 * including all devices that share this block. (see dm_deferred_set code)
73 * iii) copy the data block to a newly allocate block. This step can be
74 * missed out if the io covers the block. (schedule_copy).
76 * iv) insert the new mapping into the origin's btree
77 * (process_prepared_mapping). This act of inserting breaks some
78 * sharing of btree nodes between the two devices. Breaking sharing only
79 * effects the btree of that specific device. Btrees for the other
80 * devices that share the block never change. The btree for the origin
81 * device as it was after the last commit is untouched, ie. we're using
82 * persistent data structures in the functional programming sense.
84 * v) unplug io to this physical block, including the io that triggered
85 * the breaking of sharing.
87 * Steps (ii) and (iii) occur in parallel.
89 * The metadata _doesn't_ need to be committed before the io continues. We
90 * get away with this because the io is always written to a _new_ block.
91 * If there's a crash, then:
93 * - The origin mapping will point to the old origin block (the shared
94 * one). This will contain the data as it was before the io that triggered
95 * the breaking of sharing came in.
97 * - The snap mapping still points to the old block. As it would after
100 * The downside of this scheme is the timestamp magic isn't perfect, and
101 * will continue to think that data block in the snapshot device is shared
102 * even after the write to the origin has broken sharing. I suspect data
103 * blocks will typically be shared by many different devices, so we're
104 * breaking sharing n + 1 times, rather than n, where n is the number of
105 * devices that reference this data block. At the moment I think the
106 * benefits far, far outweigh the disadvantages.
109 /*----------------------------------------------------------------*/
119 static void build_key(struct dm_thin_device *td, enum lock_space ls,
120 dm_block_t b, dm_block_t e, struct dm_cell_key *key)
122 key->virtual = (ls == VIRTUAL);
123 key->dev = dm_thin_dev_id(td);
124 key->block_begin = b;
128 static void build_data_key(struct dm_thin_device *td, dm_block_t b,
129 struct dm_cell_key *key)
131 build_key(td, PHYSICAL, b, b + 1llu, key);
134 static void build_virtual_key(struct dm_thin_device *td, dm_block_t b,
135 struct dm_cell_key *key)
137 build_key(td, VIRTUAL, b, b + 1llu, key);
140 /*----------------------------------------------------------------*/
142 #define THROTTLE_THRESHOLD (1 * HZ)
145 struct rw_semaphore lock;
146 unsigned long threshold;
147 bool throttle_applied;
150 static void throttle_init(struct throttle *t)
152 init_rwsem(&t->lock);
153 t->throttle_applied = false;
156 static void throttle_work_start(struct throttle *t)
158 t->threshold = jiffies + THROTTLE_THRESHOLD;
161 static void throttle_work_update(struct throttle *t)
163 if (!t->throttle_applied && jiffies > t->threshold) {
164 down_write(&t->lock);
165 t->throttle_applied = true;
169 static void throttle_work_complete(struct throttle *t)
171 if (t->throttle_applied) {
172 t->throttle_applied = false;
177 static void throttle_lock(struct throttle *t)
182 static void throttle_unlock(struct throttle *t)
187 /*----------------------------------------------------------------*/
190 * A pool device ties together a metadata device and a data device. It
191 * also provides the interface for creating and destroying internal
194 struct dm_thin_new_mapping;
197 * The pool runs in 4 modes. Ordered in degraded order for comparisons.
200 PM_WRITE, /* metadata may be changed */
201 PM_OUT_OF_DATA_SPACE, /* metadata may be changed, though data may not be allocated */
202 PM_READ_ONLY, /* metadata may not be changed */
203 PM_FAIL, /* all I/O fails */
206 struct pool_features {
209 bool zero_new_blocks:1;
210 bool discard_enabled:1;
211 bool discard_passdown:1;
212 bool error_if_no_space:1;
216 typedef void (*process_bio_fn)(struct thin_c *tc, struct bio *bio);
217 typedef void (*process_cell_fn)(struct thin_c *tc, struct dm_bio_prison_cell *cell);
218 typedef void (*process_mapping_fn)(struct dm_thin_new_mapping *m);
220 #define CELL_SORT_ARRAY_SIZE 8192
223 struct list_head list;
224 struct dm_target *ti; /* Only set if a pool target is bound */
226 struct mapped_device *pool_md;
227 struct block_device *md_dev;
228 struct dm_pool_metadata *pmd;
230 dm_block_t low_water_blocks;
231 uint32_t sectors_per_block;
232 int sectors_per_block_shift;
234 struct pool_features pf;
235 bool low_water_triggered:1; /* A dm event has been sent */
238 struct dm_bio_prison *prison;
239 struct dm_kcopyd_client *copier;
241 struct workqueue_struct *wq;
242 struct throttle throttle;
243 struct work_struct worker;
244 struct delayed_work waker;
245 struct delayed_work no_space_timeout;
247 unsigned long last_commit_jiffies;
251 struct bio_list deferred_flush_bios;
252 struct list_head prepared_mappings;
253 struct list_head prepared_discards;
254 struct list_head active_thins;
256 struct dm_deferred_set *shared_read_ds;
257 struct dm_deferred_set *all_io_ds;
259 struct dm_thin_new_mapping *next_mapping;
260 mempool_t *mapping_pool;
262 process_bio_fn process_bio;
263 process_bio_fn process_discard;
265 process_cell_fn process_cell;
266 process_cell_fn process_discard_cell;
268 process_mapping_fn process_prepared_mapping;
269 process_mapping_fn process_prepared_discard;
271 struct dm_bio_prison_cell *cell_sort_array[CELL_SORT_ARRAY_SIZE];
274 static enum pool_mode get_pool_mode(struct pool *pool);
275 static void metadata_operation_failed(struct pool *pool, const char *op, int r);
278 * Target context for a pool.
281 struct dm_target *ti;
283 struct dm_dev *data_dev;
284 struct dm_dev *metadata_dev;
285 struct dm_target_callbacks callbacks;
287 dm_block_t low_water_blocks;
288 struct pool_features requested_pf; /* Features requested during table load */
289 struct pool_features adjusted_pf; /* Features used after adjusting for constituent devices */
293 * Target context for a thin.
296 struct list_head list;
297 struct dm_dev *pool_dev;
298 struct dm_dev *origin_dev;
299 sector_t origin_size;
303 struct dm_thin_device *td;
304 struct mapped_device *thin_md;
308 struct list_head deferred_cells;
309 struct bio_list deferred_bio_list;
310 struct bio_list retry_on_resume_list;
311 struct rb_root sort_bio_list; /* sorted list of deferred bios */
314 * Ensures the thin is not destroyed until the worker has finished
315 * iterating the active_thins list.
318 struct completion can_destroy;
321 /*----------------------------------------------------------------*/
324 * __blkdev_issue_discard_async - queue a discard with async completion
325 * @bdev: blockdev to issue discard for
326 * @sector: start sector
327 * @nr_sects: number of sectors to discard
328 * @gfp_mask: memory allocation flags (for bio_alloc)
329 * @flags: BLKDEV_IFL_* flags to control behaviour
330 * @parent_bio: parent discard bio that all sub discards get chained to
333 * Asynchronously issue a discard request for the sectors in question.
334 * NOTE: this variant of blk-core's blkdev_issue_discard() is a stop-gap
335 * that is being kept local to DM thinp until the block changes to allow
336 * late bio splitting land upstream.
338 static int __blkdev_issue_discard_async(struct block_device *bdev, sector_t sector,
339 sector_t nr_sects, gfp_t gfp_mask, unsigned long flags,
340 struct bio *parent_bio)
342 struct request_queue *q = bdev_get_queue(bdev);
343 int type = REQ_WRITE | REQ_DISCARD;
344 unsigned int max_discard_sectors, granularity;
348 struct blk_plug plug;
353 if (!blk_queue_discard(q))
356 /* Zero-sector (unknown) and one-sector granularities are the same. */
357 granularity = max(q->limits.discard_granularity >> 9, 1U);
358 alignment = (bdev_discard_alignment(bdev) >> 9) % granularity;
361 * Ensure that max_discard_sectors is of the proper
362 * granularity, so that requests stay aligned after a split.
364 max_discard_sectors = min(q->limits.max_discard_sectors, UINT_MAX >> 9);
365 max_discard_sectors -= max_discard_sectors % granularity;
366 if (unlikely(!max_discard_sectors)) {
367 /* Avoid infinite loop below. Being cautious never hurts. */
371 if (flags & BLKDEV_DISCARD_SECURE) {
372 if (!blk_queue_secdiscard(q))
377 blk_start_plug(&plug);
379 unsigned int req_sects;
380 sector_t end_sect, tmp;
383 * Required bio_put occurs in bio_endio thanks to bio_chain below
385 bio = bio_alloc(gfp_mask, 1);
391 req_sects = min_t(sector_t, nr_sects, max_discard_sectors);
394 * If splitting a request, and the next starting sector would be
395 * misaligned, stop the discard at the previous aligned sector.
397 end_sect = sector + req_sects;
399 if (req_sects < nr_sects &&
400 sector_div(tmp, granularity) != alignment) {
401 end_sect = end_sect - alignment;
402 sector_div(end_sect, granularity);
403 end_sect = end_sect * granularity + alignment;
404 req_sects = end_sect - sector;
407 bio_chain(bio, parent_bio);
409 bio->bi_iter.bi_sector = sector;
412 bio->bi_iter.bi_size = req_sects << 9;
413 nr_sects -= req_sects;
416 submit_bio(type, bio);
419 * We can loop for a long time in here, if someone does
420 * full device discards (like mkfs). Be nice and allow
421 * us to schedule out to avoid softlocking if preempt
426 blk_finish_plug(&plug);
431 static bool block_size_is_power_of_two(struct pool *pool)
433 return pool->sectors_per_block_shift >= 0;
436 static sector_t block_to_sectors(struct pool *pool, dm_block_t b)
438 return block_size_is_power_of_two(pool) ?
439 (b << pool->sectors_per_block_shift) :
440 (b * pool->sectors_per_block);
443 static int issue_discard(struct thin_c *tc, dm_block_t data_b, dm_block_t data_e,
444 struct bio *parent_bio)
446 sector_t s = block_to_sectors(tc->pool, data_b);
447 sector_t len = block_to_sectors(tc->pool, data_e - data_b);
449 return __blkdev_issue_discard_async(tc->pool_dev->bdev, s, len,
450 GFP_NOWAIT, 0, parent_bio);
453 /*----------------------------------------------------------------*/
456 * wake_worker() is used when new work is queued and when pool_resume is
457 * ready to continue deferred IO processing.
459 static void wake_worker(struct pool *pool)
461 queue_work(pool->wq, &pool->worker);
464 /*----------------------------------------------------------------*/
466 static int bio_detain(struct pool *pool, struct dm_cell_key *key, struct bio *bio,
467 struct dm_bio_prison_cell **cell_result)
470 struct dm_bio_prison_cell *cell_prealloc;
473 * Allocate a cell from the prison's mempool.
474 * This might block but it can't fail.
476 cell_prealloc = dm_bio_prison_alloc_cell(pool->prison, GFP_NOIO);
478 r = dm_bio_detain(pool->prison, key, bio, cell_prealloc, cell_result);
481 * We reused an old cell; we can get rid of
484 dm_bio_prison_free_cell(pool->prison, cell_prealloc);
489 static void cell_release(struct pool *pool,
490 struct dm_bio_prison_cell *cell,
491 struct bio_list *bios)
493 dm_cell_release(pool->prison, cell, bios);
494 dm_bio_prison_free_cell(pool->prison, cell);
497 static void cell_visit_release(struct pool *pool,
498 void (*fn)(void *, struct dm_bio_prison_cell *),
500 struct dm_bio_prison_cell *cell)
502 dm_cell_visit_release(pool->prison, fn, context, cell);
503 dm_bio_prison_free_cell(pool->prison, cell);
506 static void cell_release_no_holder(struct pool *pool,
507 struct dm_bio_prison_cell *cell,
508 struct bio_list *bios)
510 dm_cell_release_no_holder(pool->prison, cell, bios);
511 dm_bio_prison_free_cell(pool->prison, cell);
514 static void cell_error_with_code(struct pool *pool,
515 struct dm_bio_prison_cell *cell, int error_code)
517 dm_cell_error(pool->prison, cell, error_code);
518 dm_bio_prison_free_cell(pool->prison, cell);
521 static void cell_error(struct pool *pool, struct dm_bio_prison_cell *cell)
523 cell_error_with_code(pool, cell, -EIO);
526 static void cell_success(struct pool *pool, struct dm_bio_prison_cell *cell)
528 cell_error_with_code(pool, cell, 0);
531 static void cell_requeue(struct pool *pool, struct dm_bio_prison_cell *cell)
533 cell_error_with_code(pool, cell, DM_ENDIO_REQUEUE);
536 /*----------------------------------------------------------------*/
539 * A global list of pools that uses a struct mapped_device as a key.
541 static struct dm_thin_pool_table {
543 struct list_head pools;
544 } dm_thin_pool_table;
546 static void pool_table_init(void)
548 mutex_init(&dm_thin_pool_table.mutex);
549 INIT_LIST_HEAD(&dm_thin_pool_table.pools);
552 static void __pool_table_insert(struct pool *pool)
554 BUG_ON(!mutex_is_locked(&dm_thin_pool_table.mutex));
555 list_add(&pool->list, &dm_thin_pool_table.pools);
558 static void __pool_table_remove(struct pool *pool)
560 BUG_ON(!mutex_is_locked(&dm_thin_pool_table.mutex));
561 list_del(&pool->list);
564 static struct pool *__pool_table_lookup(struct mapped_device *md)
566 struct pool *pool = NULL, *tmp;
568 BUG_ON(!mutex_is_locked(&dm_thin_pool_table.mutex));
570 list_for_each_entry(tmp, &dm_thin_pool_table.pools, list) {
571 if (tmp->pool_md == md) {
580 static struct pool *__pool_table_lookup_metadata_dev(struct block_device *md_dev)
582 struct pool *pool = NULL, *tmp;
584 BUG_ON(!mutex_is_locked(&dm_thin_pool_table.mutex));
586 list_for_each_entry(tmp, &dm_thin_pool_table.pools, list) {
587 if (tmp->md_dev == md_dev) {
596 /*----------------------------------------------------------------*/
598 struct dm_thin_endio_hook {
600 struct dm_deferred_entry *shared_read_entry;
601 struct dm_deferred_entry *all_io_entry;
602 struct dm_thin_new_mapping *overwrite_mapping;
603 struct rb_node rb_node;
604 struct dm_bio_prison_cell *cell;
607 static void __merge_bio_list(struct bio_list *bios, struct bio_list *master)
609 bio_list_merge(bios, master);
610 bio_list_init(master);
613 static void error_bio_list(struct bio_list *bios, int error)
617 while ((bio = bio_list_pop(bios)))
618 bio_endio(bio, error);
621 static void error_thin_bio_list(struct thin_c *tc, struct bio_list *master, int error)
623 struct bio_list bios;
626 bio_list_init(&bios);
628 spin_lock_irqsave(&tc->lock, flags);
629 __merge_bio_list(&bios, master);
630 spin_unlock_irqrestore(&tc->lock, flags);
632 error_bio_list(&bios, error);
635 static void requeue_deferred_cells(struct thin_c *tc)
637 struct pool *pool = tc->pool;
639 struct list_head cells;
640 struct dm_bio_prison_cell *cell, *tmp;
642 INIT_LIST_HEAD(&cells);
644 spin_lock_irqsave(&tc->lock, flags);
645 list_splice_init(&tc->deferred_cells, &cells);
646 spin_unlock_irqrestore(&tc->lock, flags);
648 list_for_each_entry_safe(cell, tmp, &cells, user_list)
649 cell_requeue(pool, cell);
652 static void requeue_io(struct thin_c *tc)
654 struct bio_list bios;
657 bio_list_init(&bios);
659 spin_lock_irqsave(&tc->lock, flags);
660 __merge_bio_list(&bios, &tc->deferred_bio_list);
661 __merge_bio_list(&bios, &tc->retry_on_resume_list);
662 spin_unlock_irqrestore(&tc->lock, flags);
664 error_bio_list(&bios, DM_ENDIO_REQUEUE);
665 requeue_deferred_cells(tc);
668 static void error_retry_list(struct pool *pool)
673 list_for_each_entry_rcu(tc, &pool->active_thins, list)
674 error_thin_bio_list(tc, &tc->retry_on_resume_list, -EIO);
679 * This section of code contains the logic for processing a thin device's IO.
680 * Much of the code depends on pool object resources (lists, workqueues, etc)
681 * but most is exclusively called from the thin target rather than the thin-pool
685 static dm_block_t get_bio_block(struct thin_c *tc, struct bio *bio)
687 struct pool *pool = tc->pool;
688 sector_t block_nr = bio->bi_iter.bi_sector;
690 if (block_size_is_power_of_two(pool))
691 block_nr >>= pool->sectors_per_block_shift;
693 (void) sector_div(block_nr, pool->sectors_per_block);
699 * Returns the _complete_ blocks that this bio covers.
701 static void get_bio_block_range(struct thin_c *tc, struct bio *bio,
702 dm_block_t *begin, dm_block_t *end)
704 struct pool *pool = tc->pool;
705 sector_t b = bio->bi_iter.bi_sector;
706 sector_t e = b + (bio->bi_iter.bi_size >> SECTOR_SHIFT);
708 b += pool->sectors_per_block - 1ull; /* so we round up */
710 if (block_size_is_power_of_two(pool)) {
711 b >>= pool->sectors_per_block_shift;
712 e >>= pool->sectors_per_block_shift;
714 (void) sector_div(b, pool->sectors_per_block);
715 (void) sector_div(e, pool->sectors_per_block);
719 /* Can happen if the bio is within a single block. */
726 static void remap(struct thin_c *tc, struct bio *bio, dm_block_t block)
728 struct pool *pool = tc->pool;
729 sector_t bi_sector = bio->bi_iter.bi_sector;
731 bio->bi_bdev = tc->pool_dev->bdev;
732 if (block_size_is_power_of_two(pool))
733 bio->bi_iter.bi_sector =
734 (block << pool->sectors_per_block_shift) |
735 (bi_sector & (pool->sectors_per_block - 1));
737 bio->bi_iter.bi_sector = (block * pool->sectors_per_block) +
738 sector_div(bi_sector, pool->sectors_per_block);
741 static void remap_to_origin(struct thin_c *tc, struct bio *bio)
743 bio->bi_bdev = tc->origin_dev->bdev;
746 static int bio_triggers_commit(struct thin_c *tc, struct bio *bio)
748 return (bio->bi_rw & (REQ_FLUSH | REQ_FUA)) &&
749 dm_thin_changed_this_transaction(tc->td);
752 static void inc_all_io_entry(struct pool *pool, struct bio *bio)
754 struct dm_thin_endio_hook *h;
756 if (bio->bi_rw & REQ_DISCARD)
759 h = dm_per_bio_data(bio, sizeof(struct dm_thin_endio_hook));
760 h->all_io_entry = dm_deferred_entry_inc(pool->all_io_ds);
763 static void issue(struct thin_c *tc, struct bio *bio)
765 struct pool *pool = tc->pool;
768 if (!bio_triggers_commit(tc, bio)) {
769 generic_make_request(bio);
774 * Complete bio with an error if earlier I/O caused changes to
775 * the metadata that can't be committed e.g, due to I/O errors
776 * on the metadata device.
778 if (dm_thin_aborted_changes(tc->td)) {
784 * Batch together any bios that trigger commits and then issue a
785 * single commit for them in process_deferred_bios().
787 spin_lock_irqsave(&pool->lock, flags);
788 bio_list_add(&pool->deferred_flush_bios, bio);
789 spin_unlock_irqrestore(&pool->lock, flags);
792 static void remap_to_origin_and_issue(struct thin_c *tc, struct bio *bio)
794 remap_to_origin(tc, bio);
798 static void remap_and_issue(struct thin_c *tc, struct bio *bio,
801 remap(tc, bio, block);
805 /*----------------------------------------------------------------*/
808 * Bio endio functions.
810 struct dm_thin_new_mapping {
811 struct list_head list;
817 * Track quiescing, copying and zeroing preparation actions. When this
818 * counter hits zero the block is prepared and can be inserted into the
821 atomic_t prepare_actions;
825 dm_block_t virt_begin, virt_end;
826 dm_block_t data_block;
827 struct dm_bio_prison_cell *cell;
830 * If the bio covers the whole area of a block then we can avoid
831 * zeroing or copying. Instead this bio is hooked. The bio will
832 * still be in the cell, so care has to be taken to avoid issuing
836 bio_end_io_t *saved_bi_end_io;
839 static void __complete_mapping_preparation(struct dm_thin_new_mapping *m)
841 struct pool *pool = m->tc->pool;
843 if (atomic_dec_and_test(&m->prepare_actions)) {
844 list_add_tail(&m->list, &pool->prepared_mappings);
849 static void complete_mapping_preparation(struct dm_thin_new_mapping *m)
852 struct pool *pool = m->tc->pool;
854 spin_lock_irqsave(&pool->lock, flags);
855 __complete_mapping_preparation(m);
856 spin_unlock_irqrestore(&pool->lock, flags);
859 static void copy_complete(int read_err, unsigned long write_err, void *context)
861 struct dm_thin_new_mapping *m = context;
863 m->err = read_err || write_err ? -EIO : 0;
864 complete_mapping_preparation(m);
867 static void overwrite_endio(struct bio *bio, int err)
869 struct dm_thin_endio_hook *h = dm_per_bio_data(bio, sizeof(struct dm_thin_endio_hook));
870 struct dm_thin_new_mapping *m = h->overwrite_mapping;
872 bio->bi_end_io = m->saved_bi_end_io;
875 complete_mapping_preparation(m);
878 /*----------------------------------------------------------------*/
885 * Prepared mapping jobs.
889 * This sends the bios in the cell, except the original holder, back
890 * to the deferred_bios list.
892 static void cell_defer_no_holder(struct thin_c *tc, struct dm_bio_prison_cell *cell)
894 struct pool *pool = tc->pool;
897 spin_lock_irqsave(&tc->lock, flags);
898 cell_release_no_holder(pool, cell, &tc->deferred_bio_list);
899 spin_unlock_irqrestore(&tc->lock, flags);
904 static void thin_defer_bio(struct thin_c *tc, struct bio *bio);
908 struct bio_list defer_bios;
909 struct bio_list issue_bios;
912 static void __inc_remap_and_issue_cell(void *context,
913 struct dm_bio_prison_cell *cell)
915 struct remap_info *info = context;
918 while ((bio = bio_list_pop(&cell->bios))) {
919 if (bio->bi_rw & (REQ_DISCARD | REQ_FLUSH | REQ_FUA))
920 bio_list_add(&info->defer_bios, bio);
922 inc_all_io_entry(info->tc->pool, bio);
925 * We can't issue the bios with the bio prison lock
926 * held, so we add them to a list to issue on
927 * return from this function.
929 bio_list_add(&info->issue_bios, bio);
934 static void inc_remap_and_issue_cell(struct thin_c *tc,
935 struct dm_bio_prison_cell *cell,
939 struct remap_info info;
942 bio_list_init(&info.defer_bios);
943 bio_list_init(&info.issue_bios);
946 * We have to be careful to inc any bios we're about to issue
947 * before the cell is released, and avoid a race with new bios
948 * being added to the cell.
950 cell_visit_release(tc->pool, __inc_remap_and_issue_cell,
953 while ((bio = bio_list_pop(&info.defer_bios)))
954 thin_defer_bio(tc, bio);
956 while ((bio = bio_list_pop(&info.issue_bios)))
957 remap_and_issue(info.tc, bio, block);
960 static void process_prepared_mapping_fail(struct dm_thin_new_mapping *m)
962 cell_error(m->tc->pool, m->cell);
964 mempool_free(m, m->tc->pool->mapping_pool);
967 static void process_prepared_mapping(struct dm_thin_new_mapping *m)
969 struct thin_c *tc = m->tc;
970 struct pool *pool = tc->pool;
971 struct bio *bio = m->bio;
975 cell_error(pool, m->cell);
980 * Commit the prepared block into the mapping btree.
981 * Any I/O for this block arriving after this point will get
982 * remapped to it directly.
984 r = dm_thin_insert_block(tc->td, m->virt_begin, m->data_block);
986 metadata_operation_failed(pool, "dm_thin_insert_block", r);
987 cell_error(pool, m->cell);
992 * Release any bios held while the block was being provisioned.
993 * If we are processing a write bio that completely covers the block,
994 * we already processed it so can ignore it now when processing
995 * the bios in the cell.
998 inc_remap_and_issue_cell(tc, m->cell, m->data_block);
1001 inc_all_io_entry(tc->pool, m->cell->holder);
1002 remap_and_issue(tc, m->cell->holder, m->data_block);
1003 inc_remap_and_issue_cell(tc, m->cell, m->data_block);
1008 mempool_free(m, pool->mapping_pool);
1011 /*----------------------------------------------------------------*/
1013 static void free_discard_mapping(struct dm_thin_new_mapping *m)
1015 struct thin_c *tc = m->tc;
1017 cell_defer_no_holder(tc, m->cell);
1018 mempool_free(m, tc->pool->mapping_pool);
1021 static void process_prepared_discard_fail(struct dm_thin_new_mapping *m)
1023 bio_io_error(m->bio);
1024 free_discard_mapping(m);
1027 static void process_prepared_discard_success(struct dm_thin_new_mapping *m)
1029 bio_endio(m->bio, 0);
1030 free_discard_mapping(m);
1033 static void process_prepared_discard_no_passdown(struct dm_thin_new_mapping *m)
1036 struct thin_c *tc = m->tc;
1038 r = dm_thin_remove_range(tc->td, m->cell->key.block_begin, m->cell->key.block_end);
1040 metadata_operation_failed(tc->pool, "dm_thin_remove_range", r);
1041 bio_io_error(m->bio);
1043 bio_endio(m->bio, 0);
1045 cell_defer_no_holder(tc, m->cell);
1046 mempool_free(m, tc->pool->mapping_pool);
1049 static int passdown_double_checking_shared_status(struct dm_thin_new_mapping *m)
1052 * We've already unmapped this range of blocks, but before we
1053 * passdown we have to check that these blocks are now unused.
1057 struct thin_c *tc = m->tc;
1058 struct pool *pool = tc->pool;
1059 dm_block_t b = m->data_block, e, end = m->data_block + m->virt_end - m->virt_begin;
1062 /* find start of unmapped run */
1063 for (; b < end; b++) {
1064 r = dm_pool_block_is_used(pool->pmd, b, &used);
1075 /* find end of run */
1076 for (e = b + 1; e != end; e++) {
1077 r = dm_pool_block_is_used(pool->pmd, e, &used);
1085 r = issue_discard(tc, b, e, m->bio);
1095 static void process_prepared_discard_passdown(struct dm_thin_new_mapping *m)
1098 struct thin_c *tc = m->tc;
1099 struct pool *pool = tc->pool;
1101 r = dm_thin_remove_range(tc->td, m->virt_begin, m->virt_end);
1103 metadata_operation_failed(pool, "dm_thin_remove_range", r);
1105 else if (m->maybe_shared)
1106 r = passdown_double_checking_shared_status(m);
1108 r = issue_discard(tc, m->data_block, m->data_block + (m->virt_end - m->virt_begin), m->bio);
1111 * Even if r is set, there could be sub discards in flight that we
1114 bio_endio(m->bio, r);
1115 cell_defer_no_holder(tc, m->cell);
1116 mempool_free(m, pool->mapping_pool);
1119 static void process_prepared(struct pool *pool, struct list_head *head,
1120 process_mapping_fn *fn)
1122 unsigned long flags;
1123 struct list_head maps;
1124 struct dm_thin_new_mapping *m, *tmp;
1126 INIT_LIST_HEAD(&maps);
1127 spin_lock_irqsave(&pool->lock, flags);
1128 list_splice_init(head, &maps);
1129 spin_unlock_irqrestore(&pool->lock, flags);
1131 list_for_each_entry_safe(m, tmp, &maps, list)
1136 * Deferred bio jobs.
1138 static int io_overlaps_block(struct pool *pool, struct bio *bio)
1140 return bio->bi_iter.bi_size ==
1141 (pool->sectors_per_block << SECTOR_SHIFT);
1144 static int io_overwrites_block(struct pool *pool, struct bio *bio)
1146 return (bio_data_dir(bio) == WRITE) &&
1147 io_overlaps_block(pool, bio);
1150 static void save_and_set_endio(struct bio *bio, bio_end_io_t **save,
1153 *save = bio->bi_end_io;
1154 bio->bi_end_io = fn;
1157 static int ensure_next_mapping(struct pool *pool)
1159 if (pool->next_mapping)
1162 pool->next_mapping = mempool_alloc(pool->mapping_pool, GFP_ATOMIC);
1164 return pool->next_mapping ? 0 : -ENOMEM;
1167 static struct dm_thin_new_mapping *get_next_mapping(struct pool *pool)
1169 struct dm_thin_new_mapping *m = pool->next_mapping;
1171 BUG_ON(!pool->next_mapping);
1173 memset(m, 0, sizeof(struct dm_thin_new_mapping));
1174 INIT_LIST_HEAD(&m->list);
1177 pool->next_mapping = NULL;
1182 static void ll_zero(struct thin_c *tc, struct dm_thin_new_mapping *m,
1183 sector_t begin, sector_t end)
1186 struct dm_io_region to;
1188 to.bdev = tc->pool_dev->bdev;
1190 to.count = end - begin;
1192 r = dm_kcopyd_zero(tc->pool->copier, 1, &to, 0, copy_complete, m);
1194 DMERR_LIMIT("dm_kcopyd_zero() failed");
1195 copy_complete(1, 1, m);
1199 static void remap_and_issue_overwrite(struct thin_c *tc, struct bio *bio,
1200 dm_block_t data_begin,
1201 struct dm_thin_new_mapping *m)
1203 struct pool *pool = tc->pool;
1204 struct dm_thin_endio_hook *h = dm_per_bio_data(bio, sizeof(struct dm_thin_endio_hook));
1206 h->overwrite_mapping = m;
1208 save_and_set_endio(bio, &m->saved_bi_end_io, overwrite_endio);
1209 inc_all_io_entry(pool, bio);
1210 remap_and_issue(tc, bio, data_begin);
1214 * A partial copy also needs to zero the uncopied region.
1216 static void schedule_copy(struct thin_c *tc, dm_block_t virt_block,
1217 struct dm_dev *origin, dm_block_t data_origin,
1218 dm_block_t data_dest,
1219 struct dm_bio_prison_cell *cell, struct bio *bio,
1223 struct pool *pool = tc->pool;
1224 struct dm_thin_new_mapping *m = get_next_mapping(pool);
1227 m->virt_begin = virt_block;
1228 m->virt_end = virt_block + 1u;
1229 m->data_block = data_dest;
1233 * quiesce action + copy action + an extra reference held for the
1234 * duration of this function (we may need to inc later for a
1237 atomic_set(&m->prepare_actions, 3);
1239 if (!dm_deferred_set_add_work(pool->shared_read_ds, &m->list))
1240 complete_mapping_preparation(m); /* already quiesced */
1243 * IO to pool_dev remaps to the pool target's data_dev.
1245 * If the whole block of data is being overwritten, we can issue the
1246 * bio immediately. Otherwise we use kcopyd to clone the data first.
1248 if (io_overwrites_block(pool, bio))
1249 remap_and_issue_overwrite(tc, bio, data_dest, m);
1251 struct dm_io_region from, to;
1253 from.bdev = origin->bdev;
1254 from.sector = data_origin * pool->sectors_per_block;
1257 to.bdev = tc->pool_dev->bdev;
1258 to.sector = data_dest * pool->sectors_per_block;
1261 r = dm_kcopyd_copy(pool->copier, &from, 1, &to,
1262 0, copy_complete, m);
1264 DMERR_LIMIT("dm_kcopyd_copy() failed");
1265 copy_complete(1, 1, m);
1268 * We allow the zero to be issued, to simplify the
1269 * error path. Otherwise we'd need to start
1270 * worrying about decrementing the prepare_actions
1276 * Do we need to zero a tail region?
1278 if (len < pool->sectors_per_block && pool->pf.zero_new_blocks) {
1279 atomic_inc(&m->prepare_actions);
1281 data_dest * pool->sectors_per_block + len,
1282 (data_dest + 1) * pool->sectors_per_block);
1286 complete_mapping_preparation(m); /* drop our ref */
1289 static void schedule_internal_copy(struct thin_c *tc, dm_block_t virt_block,
1290 dm_block_t data_origin, dm_block_t data_dest,
1291 struct dm_bio_prison_cell *cell, struct bio *bio)
1293 schedule_copy(tc, virt_block, tc->pool_dev,
1294 data_origin, data_dest, cell, bio,
1295 tc->pool->sectors_per_block);
1298 static void schedule_zero(struct thin_c *tc, dm_block_t virt_block,
1299 dm_block_t data_block, struct dm_bio_prison_cell *cell,
1302 struct pool *pool = tc->pool;
1303 struct dm_thin_new_mapping *m = get_next_mapping(pool);
1305 atomic_set(&m->prepare_actions, 1); /* no need to quiesce */
1307 m->virt_begin = virt_block;
1308 m->virt_end = virt_block + 1u;
1309 m->data_block = data_block;
1313 * If the whole block of data is being overwritten or we are not
1314 * zeroing pre-existing data, we can issue the bio immediately.
1315 * Otherwise we use kcopyd to zero the data first.
1317 if (pool->pf.zero_new_blocks) {
1318 if (io_overwrites_block(pool, bio))
1319 remap_and_issue_overwrite(tc, bio, data_block, m);
1321 ll_zero(tc, m, data_block * pool->sectors_per_block,
1322 (data_block + 1) * pool->sectors_per_block);
1324 process_prepared_mapping(m);
1327 static void schedule_external_copy(struct thin_c *tc, dm_block_t virt_block,
1328 dm_block_t data_dest,
1329 struct dm_bio_prison_cell *cell, struct bio *bio)
1331 struct pool *pool = tc->pool;
1332 sector_t virt_block_begin = virt_block * pool->sectors_per_block;
1333 sector_t virt_block_end = (virt_block + 1) * pool->sectors_per_block;
1335 if (virt_block_end <= tc->origin_size)
1336 schedule_copy(tc, virt_block, tc->origin_dev,
1337 virt_block, data_dest, cell, bio,
1338 pool->sectors_per_block);
1340 else if (virt_block_begin < tc->origin_size)
1341 schedule_copy(tc, virt_block, tc->origin_dev,
1342 virt_block, data_dest, cell, bio,
1343 tc->origin_size - virt_block_begin);
1346 schedule_zero(tc, virt_block, data_dest, cell, bio);
1349 static void set_pool_mode(struct pool *pool, enum pool_mode new_mode);
1351 static void check_for_space(struct pool *pool)
1356 if (get_pool_mode(pool) != PM_OUT_OF_DATA_SPACE)
1359 r = dm_pool_get_free_block_count(pool->pmd, &nr_free);
1364 set_pool_mode(pool, PM_WRITE);
1368 * A non-zero return indicates read_only or fail_io mode.
1369 * Many callers don't care about the return value.
1371 static int commit(struct pool *pool)
1375 if (get_pool_mode(pool) >= PM_READ_ONLY)
1378 r = dm_pool_commit_metadata(pool->pmd);
1380 metadata_operation_failed(pool, "dm_pool_commit_metadata", r);
1382 check_for_space(pool);
1387 static void check_low_water_mark(struct pool *pool, dm_block_t free_blocks)
1389 unsigned long flags;
1391 if (free_blocks <= pool->low_water_blocks && !pool->low_water_triggered) {
1392 DMWARN("%s: reached low water mark for data device: sending event.",
1393 dm_device_name(pool->pool_md));
1394 spin_lock_irqsave(&pool->lock, flags);
1395 pool->low_water_triggered = true;
1396 spin_unlock_irqrestore(&pool->lock, flags);
1397 dm_table_event(pool->ti->table);
1401 static int alloc_data_block(struct thin_c *tc, dm_block_t *result)
1404 dm_block_t free_blocks;
1405 struct pool *pool = tc->pool;
1407 if (WARN_ON(get_pool_mode(pool) != PM_WRITE))
1410 r = dm_pool_get_free_block_count(pool->pmd, &free_blocks);
1412 metadata_operation_failed(pool, "dm_pool_get_free_block_count", r);
1416 check_low_water_mark(pool, free_blocks);
1420 * Try to commit to see if that will free up some
1427 r = dm_pool_get_free_block_count(pool->pmd, &free_blocks);
1429 metadata_operation_failed(pool, "dm_pool_get_free_block_count", r);
1434 set_pool_mode(pool, PM_OUT_OF_DATA_SPACE);
1439 r = dm_pool_alloc_data_block(pool->pmd, result);
1441 metadata_operation_failed(pool, "dm_pool_alloc_data_block", r);
1449 * If we have run out of space, queue bios until the device is
1450 * resumed, presumably after having been reloaded with more space.
1452 static void retry_on_resume(struct bio *bio)
1454 struct dm_thin_endio_hook *h = dm_per_bio_data(bio, sizeof(struct dm_thin_endio_hook));
1455 struct thin_c *tc = h->tc;
1456 unsigned long flags;
1458 spin_lock_irqsave(&tc->lock, flags);
1459 bio_list_add(&tc->retry_on_resume_list, bio);
1460 spin_unlock_irqrestore(&tc->lock, flags);
1463 static int should_error_unserviceable_bio(struct pool *pool)
1465 enum pool_mode m = get_pool_mode(pool);
1469 /* Shouldn't get here */
1470 DMERR_LIMIT("bio unserviceable, yet pool is in PM_WRITE mode");
1473 case PM_OUT_OF_DATA_SPACE:
1474 return pool->pf.error_if_no_space ? -ENOSPC : 0;
1480 /* Shouldn't get here */
1481 DMERR_LIMIT("bio unserviceable, yet pool has an unknown mode");
1486 static void handle_unserviceable_bio(struct pool *pool, struct bio *bio)
1488 int error = should_error_unserviceable_bio(pool);
1491 bio_endio(bio, error);
1493 retry_on_resume(bio);
1496 static void retry_bios_on_resume(struct pool *pool, struct dm_bio_prison_cell *cell)
1499 struct bio_list bios;
1502 error = should_error_unserviceable_bio(pool);
1504 cell_error_with_code(pool, cell, error);
1508 bio_list_init(&bios);
1509 cell_release(pool, cell, &bios);
1511 while ((bio = bio_list_pop(&bios)))
1512 retry_on_resume(bio);
1515 static void process_discard_cell_no_passdown(struct thin_c *tc,
1516 struct dm_bio_prison_cell *virt_cell)
1518 struct pool *pool = tc->pool;
1519 struct dm_thin_new_mapping *m = get_next_mapping(pool);
1522 * We don't need to lock the data blocks, since there's no
1523 * passdown. We only lock data blocks for allocation and breaking sharing.
1526 m->virt_begin = virt_cell->key.block_begin;
1527 m->virt_end = virt_cell->key.block_end;
1528 m->cell = virt_cell;
1529 m->bio = virt_cell->holder;
1531 if (!dm_deferred_set_add_work(pool->all_io_ds, &m->list))
1532 pool->process_prepared_discard(m);
1536 * FIXME: DM local hack to defer parent bios's end_io until we
1537 * _know_ all chained sub range discard bios have completed.
1538 * Will go away once late bio splitting lands upstream!
1540 static inline void __bio_inc_remaining(struct bio *bio)
1542 bio->bi_flags |= (1 << BIO_CHAIN);
1543 smp_mb__before_atomic();
1544 atomic_inc(&bio->__bi_remaining);
1547 static void break_up_discard_bio(struct thin_c *tc, dm_block_t begin, dm_block_t end,
1550 struct pool *pool = tc->pool;
1554 struct dm_cell_key data_key;
1555 struct dm_bio_prison_cell *data_cell;
1556 struct dm_thin_new_mapping *m;
1557 dm_block_t virt_begin, virt_end, data_begin;
1559 while (begin != end) {
1560 r = ensure_next_mapping(pool);
1562 /* we did our best */
1565 r = dm_thin_find_mapped_range(tc->td, begin, end, &virt_begin, &virt_end,
1566 &data_begin, &maybe_shared);
1569 * Silently fail, letting any mappings we've
1574 build_key(tc->td, PHYSICAL, data_begin, data_begin + (virt_end - virt_begin), &data_key);
1575 if (bio_detain(tc->pool, &data_key, NULL, &data_cell)) {
1576 /* contention, we'll give up with this range */
1582 * IO may still be going to the destination block. We must
1583 * quiesce before we can do the removal.
1585 m = get_next_mapping(pool);
1587 m->maybe_shared = maybe_shared;
1588 m->virt_begin = virt_begin;
1589 m->virt_end = virt_end;
1590 m->data_block = data_begin;
1591 m->cell = data_cell;
1595 * The parent bio must not complete before sub discard bios are
1596 * chained to it (see __blkdev_issue_discard_async's bio_chain)!
1598 * This per-mapping bi_remaining increment is paired with
1599 * the implicit decrement that occurs via bio_endio() in
1600 * process_prepared_discard_{passdown,no_passdown}.
1602 __bio_inc_remaining(bio);
1603 if (!dm_deferred_set_add_work(pool->all_io_ds, &m->list))
1604 pool->process_prepared_discard(m);
1610 static void process_discard_cell_passdown(struct thin_c *tc, struct dm_bio_prison_cell *virt_cell)
1612 struct bio *bio = virt_cell->holder;
1613 struct dm_thin_endio_hook *h = dm_per_bio_data(bio, sizeof(struct dm_thin_endio_hook));
1616 * The virt_cell will only get freed once the origin bio completes.
1617 * This means it will remain locked while all the individual
1618 * passdown bios are in flight.
1620 h->cell = virt_cell;
1621 break_up_discard_bio(tc, virt_cell->key.block_begin, virt_cell->key.block_end, bio);
1624 * We complete the bio now, knowing that the bi_remaining field
1625 * will prevent completion until the sub range discards have
1631 static void process_discard_bio(struct thin_c *tc, struct bio *bio)
1633 dm_block_t begin, end;
1634 struct dm_cell_key virt_key;
1635 struct dm_bio_prison_cell *virt_cell;
1637 get_bio_block_range(tc, bio, &begin, &end);
1640 * The discard covers less than a block.
1646 build_key(tc->td, VIRTUAL, begin, end, &virt_key);
1647 if (bio_detain(tc->pool, &virt_key, bio, &virt_cell))
1649 * Potential starvation issue: We're relying on the
1650 * fs/application being well behaved, and not trying to
1651 * send IO to a region at the same time as discarding it.
1652 * If they do this persistently then it's possible this
1653 * cell will never be granted.
1657 tc->pool->process_discard_cell(tc, virt_cell);
1660 static void break_sharing(struct thin_c *tc, struct bio *bio, dm_block_t block,
1661 struct dm_cell_key *key,
1662 struct dm_thin_lookup_result *lookup_result,
1663 struct dm_bio_prison_cell *cell)
1666 dm_block_t data_block;
1667 struct pool *pool = tc->pool;
1669 r = alloc_data_block(tc, &data_block);
1672 schedule_internal_copy(tc, block, lookup_result->block,
1673 data_block, cell, bio);
1677 retry_bios_on_resume(pool, cell);
1681 DMERR_LIMIT("%s: alloc_data_block() failed: error = %d",
1683 cell_error(pool, cell);
1688 static void __remap_and_issue_shared_cell(void *context,
1689 struct dm_bio_prison_cell *cell)
1691 struct remap_info *info = context;
1694 while ((bio = bio_list_pop(&cell->bios))) {
1695 if ((bio_data_dir(bio) == WRITE) ||
1696 (bio->bi_rw & (REQ_DISCARD | REQ_FLUSH | REQ_FUA)))
1697 bio_list_add(&info->defer_bios, bio);
1699 struct dm_thin_endio_hook *h = dm_per_bio_data(bio, sizeof(struct dm_thin_endio_hook));;
1701 h->shared_read_entry = dm_deferred_entry_inc(info->tc->pool->shared_read_ds);
1702 inc_all_io_entry(info->tc->pool, bio);
1703 bio_list_add(&info->issue_bios, bio);
1708 static void remap_and_issue_shared_cell(struct thin_c *tc,
1709 struct dm_bio_prison_cell *cell,
1713 struct remap_info info;
1716 bio_list_init(&info.defer_bios);
1717 bio_list_init(&info.issue_bios);
1719 cell_visit_release(tc->pool, __remap_and_issue_shared_cell,
1722 while ((bio = bio_list_pop(&info.defer_bios)))
1723 thin_defer_bio(tc, bio);
1725 while ((bio = bio_list_pop(&info.issue_bios)))
1726 remap_and_issue(tc, bio, block);
1729 static void process_shared_bio(struct thin_c *tc, struct bio *bio,
1731 struct dm_thin_lookup_result *lookup_result,
1732 struct dm_bio_prison_cell *virt_cell)
1734 struct dm_bio_prison_cell *data_cell;
1735 struct pool *pool = tc->pool;
1736 struct dm_cell_key key;
1739 * If cell is already occupied, then sharing is already in the process
1740 * of being broken so we have nothing further to do here.
1742 build_data_key(tc->td, lookup_result->block, &key);
1743 if (bio_detain(pool, &key, bio, &data_cell)) {
1744 cell_defer_no_holder(tc, virt_cell);
1748 if (bio_data_dir(bio) == WRITE && bio->bi_iter.bi_size) {
1749 break_sharing(tc, bio, block, &key, lookup_result, data_cell);
1750 cell_defer_no_holder(tc, virt_cell);
1752 struct dm_thin_endio_hook *h = dm_per_bio_data(bio, sizeof(struct dm_thin_endio_hook));
1754 h->shared_read_entry = dm_deferred_entry_inc(pool->shared_read_ds);
1755 inc_all_io_entry(pool, bio);
1756 remap_and_issue(tc, bio, lookup_result->block);
1758 remap_and_issue_shared_cell(tc, data_cell, lookup_result->block);
1759 remap_and_issue_shared_cell(tc, virt_cell, lookup_result->block);
1763 static void provision_block(struct thin_c *tc, struct bio *bio, dm_block_t block,
1764 struct dm_bio_prison_cell *cell)
1767 dm_block_t data_block;
1768 struct pool *pool = tc->pool;
1771 * Remap empty bios (flushes) immediately, without provisioning.
1773 if (!bio->bi_iter.bi_size) {
1774 inc_all_io_entry(pool, bio);
1775 cell_defer_no_holder(tc, cell);
1777 remap_and_issue(tc, bio, 0);
1782 * Fill read bios with zeroes and complete them immediately.
1784 if (bio_data_dir(bio) == READ) {
1786 cell_defer_no_holder(tc, cell);
1791 r = alloc_data_block(tc, &data_block);
1795 schedule_external_copy(tc, block, data_block, cell, bio);
1797 schedule_zero(tc, block, data_block, cell, bio);
1801 retry_bios_on_resume(pool, cell);
1805 DMERR_LIMIT("%s: alloc_data_block() failed: error = %d",
1807 cell_error(pool, cell);
1812 static void process_cell(struct thin_c *tc, struct dm_bio_prison_cell *cell)
1815 struct pool *pool = tc->pool;
1816 struct bio *bio = cell->holder;
1817 dm_block_t block = get_bio_block(tc, bio);
1818 struct dm_thin_lookup_result lookup_result;
1820 if (tc->requeue_mode) {
1821 cell_requeue(pool, cell);
1825 r = dm_thin_find_block(tc->td, block, 1, &lookup_result);
1828 if (lookup_result.shared)
1829 process_shared_bio(tc, bio, block, &lookup_result, cell);
1831 inc_all_io_entry(pool, bio);
1832 remap_and_issue(tc, bio, lookup_result.block);
1833 inc_remap_and_issue_cell(tc, cell, lookup_result.block);
1838 if (bio_data_dir(bio) == READ && tc->origin_dev) {
1839 inc_all_io_entry(pool, bio);
1840 cell_defer_no_holder(tc, cell);
1842 if (bio_end_sector(bio) <= tc->origin_size)
1843 remap_to_origin_and_issue(tc, bio);
1845 else if (bio->bi_iter.bi_sector < tc->origin_size) {
1847 bio->bi_iter.bi_size = (tc->origin_size - bio->bi_iter.bi_sector) << SECTOR_SHIFT;
1848 remap_to_origin_and_issue(tc, bio);
1855 provision_block(tc, bio, block, cell);
1859 DMERR_LIMIT("%s: dm_thin_find_block() failed: error = %d",
1861 cell_defer_no_holder(tc, cell);
1867 static void process_bio(struct thin_c *tc, struct bio *bio)
1869 struct pool *pool = tc->pool;
1870 dm_block_t block = get_bio_block(tc, bio);
1871 struct dm_bio_prison_cell *cell;
1872 struct dm_cell_key key;
1875 * If cell is already occupied, then the block is already
1876 * being provisioned so we have nothing further to do here.
1878 build_virtual_key(tc->td, block, &key);
1879 if (bio_detain(pool, &key, bio, &cell))
1882 process_cell(tc, cell);
1885 static void __process_bio_read_only(struct thin_c *tc, struct bio *bio,
1886 struct dm_bio_prison_cell *cell)
1889 int rw = bio_data_dir(bio);
1890 dm_block_t block = get_bio_block(tc, bio);
1891 struct dm_thin_lookup_result lookup_result;
1893 r = dm_thin_find_block(tc->td, block, 1, &lookup_result);
1896 if (lookup_result.shared && (rw == WRITE) && bio->bi_iter.bi_size) {
1897 handle_unserviceable_bio(tc->pool, bio);
1899 cell_defer_no_holder(tc, cell);
1901 inc_all_io_entry(tc->pool, bio);
1902 remap_and_issue(tc, bio, lookup_result.block);
1904 inc_remap_and_issue_cell(tc, cell, lookup_result.block);
1910 cell_defer_no_holder(tc, cell);
1912 handle_unserviceable_bio(tc->pool, bio);
1916 if (tc->origin_dev) {
1917 inc_all_io_entry(tc->pool, bio);
1918 remap_to_origin_and_issue(tc, bio);
1927 DMERR_LIMIT("%s: dm_thin_find_block() failed: error = %d",
1930 cell_defer_no_holder(tc, cell);
1936 static void process_bio_read_only(struct thin_c *tc, struct bio *bio)
1938 __process_bio_read_only(tc, bio, NULL);
1941 static void process_cell_read_only(struct thin_c *tc, struct dm_bio_prison_cell *cell)
1943 __process_bio_read_only(tc, cell->holder, cell);
1946 static void process_bio_success(struct thin_c *tc, struct bio *bio)
1951 static void process_bio_fail(struct thin_c *tc, struct bio *bio)
1956 static void process_cell_success(struct thin_c *tc, struct dm_bio_prison_cell *cell)
1958 cell_success(tc->pool, cell);
1961 static void process_cell_fail(struct thin_c *tc, struct dm_bio_prison_cell *cell)
1963 cell_error(tc->pool, cell);
1967 * FIXME: should we also commit due to size of transaction, measured in
1970 static int need_commit_due_to_time(struct pool *pool)
1972 return !time_in_range(jiffies, pool->last_commit_jiffies,
1973 pool->last_commit_jiffies + COMMIT_PERIOD);
1976 #define thin_pbd(node) rb_entry((node), struct dm_thin_endio_hook, rb_node)
1977 #define thin_bio(pbd) dm_bio_from_per_bio_data((pbd), sizeof(struct dm_thin_endio_hook))
1979 static void __thin_bio_rb_add(struct thin_c *tc, struct bio *bio)
1981 struct rb_node **rbp, *parent;
1982 struct dm_thin_endio_hook *pbd;
1983 sector_t bi_sector = bio->bi_iter.bi_sector;
1985 rbp = &tc->sort_bio_list.rb_node;
1989 pbd = thin_pbd(parent);
1991 if (bi_sector < thin_bio(pbd)->bi_iter.bi_sector)
1992 rbp = &(*rbp)->rb_left;
1994 rbp = &(*rbp)->rb_right;
1997 pbd = dm_per_bio_data(bio, sizeof(struct dm_thin_endio_hook));
1998 rb_link_node(&pbd->rb_node, parent, rbp);
1999 rb_insert_color(&pbd->rb_node, &tc->sort_bio_list);
2002 static void __extract_sorted_bios(struct thin_c *tc)
2004 struct rb_node *node;
2005 struct dm_thin_endio_hook *pbd;
2008 for (node = rb_first(&tc->sort_bio_list); node; node = rb_next(node)) {
2009 pbd = thin_pbd(node);
2010 bio = thin_bio(pbd);
2012 bio_list_add(&tc->deferred_bio_list, bio);
2013 rb_erase(&pbd->rb_node, &tc->sort_bio_list);
2016 WARN_ON(!RB_EMPTY_ROOT(&tc->sort_bio_list));
2019 static void __sort_thin_deferred_bios(struct thin_c *tc)
2022 struct bio_list bios;
2024 bio_list_init(&bios);
2025 bio_list_merge(&bios, &tc->deferred_bio_list);
2026 bio_list_init(&tc->deferred_bio_list);
2028 /* Sort deferred_bio_list using rb-tree */
2029 while ((bio = bio_list_pop(&bios)))
2030 __thin_bio_rb_add(tc, bio);
2033 * Transfer the sorted bios in sort_bio_list back to
2034 * deferred_bio_list to allow lockless submission of
2037 __extract_sorted_bios(tc);
2040 static void process_thin_deferred_bios(struct thin_c *tc)
2042 struct pool *pool = tc->pool;
2043 unsigned long flags;
2045 struct bio_list bios;
2046 struct blk_plug plug;
2049 if (tc->requeue_mode) {
2050 error_thin_bio_list(tc, &tc->deferred_bio_list, DM_ENDIO_REQUEUE);
2054 bio_list_init(&bios);
2056 spin_lock_irqsave(&tc->lock, flags);
2058 if (bio_list_empty(&tc->deferred_bio_list)) {
2059 spin_unlock_irqrestore(&tc->lock, flags);
2063 __sort_thin_deferred_bios(tc);
2065 bio_list_merge(&bios, &tc->deferred_bio_list);
2066 bio_list_init(&tc->deferred_bio_list);
2068 spin_unlock_irqrestore(&tc->lock, flags);
2070 blk_start_plug(&plug);
2071 while ((bio = bio_list_pop(&bios))) {
2073 * If we've got no free new_mapping structs, and processing
2074 * this bio might require one, we pause until there are some
2075 * prepared mappings to process.
2077 if (ensure_next_mapping(pool)) {
2078 spin_lock_irqsave(&tc->lock, flags);
2079 bio_list_add(&tc->deferred_bio_list, bio);
2080 bio_list_merge(&tc->deferred_bio_list, &bios);
2081 spin_unlock_irqrestore(&tc->lock, flags);
2085 if (bio->bi_rw & REQ_DISCARD)
2086 pool->process_discard(tc, bio);
2088 pool->process_bio(tc, bio);
2090 if ((count++ & 127) == 0) {
2091 throttle_work_update(&pool->throttle);
2092 dm_pool_issue_prefetches(pool->pmd);
2095 blk_finish_plug(&plug);
2098 static int cmp_cells(const void *lhs, const void *rhs)
2100 struct dm_bio_prison_cell *lhs_cell = *((struct dm_bio_prison_cell **) lhs);
2101 struct dm_bio_prison_cell *rhs_cell = *((struct dm_bio_prison_cell **) rhs);
2103 BUG_ON(!lhs_cell->holder);
2104 BUG_ON(!rhs_cell->holder);
2106 if (lhs_cell->holder->bi_iter.bi_sector < rhs_cell->holder->bi_iter.bi_sector)
2109 if (lhs_cell->holder->bi_iter.bi_sector > rhs_cell->holder->bi_iter.bi_sector)
2115 static unsigned sort_cells(struct pool *pool, struct list_head *cells)
2118 struct dm_bio_prison_cell *cell, *tmp;
2120 list_for_each_entry_safe(cell, tmp, cells, user_list) {
2121 if (count >= CELL_SORT_ARRAY_SIZE)
2124 pool->cell_sort_array[count++] = cell;
2125 list_del(&cell->user_list);
2128 sort(pool->cell_sort_array, count, sizeof(cell), cmp_cells, NULL);
2133 static void process_thin_deferred_cells(struct thin_c *tc)
2135 struct pool *pool = tc->pool;
2136 unsigned long flags;
2137 struct list_head cells;
2138 struct dm_bio_prison_cell *cell;
2139 unsigned i, j, count;
2141 INIT_LIST_HEAD(&cells);
2143 spin_lock_irqsave(&tc->lock, flags);
2144 list_splice_init(&tc->deferred_cells, &cells);
2145 spin_unlock_irqrestore(&tc->lock, flags);
2147 if (list_empty(&cells))
2151 count = sort_cells(tc->pool, &cells);
2153 for (i = 0; i < count; i++) {
2154 cell = pool->cell_sort_array[i];
2155 BUG_ON(!cell->holder);
2158 * If we've got no free new_mapping structs, and processing
2159 * this bio might require one, we pause until there are some
2160 * prepared mappings to process.
2162 if (ensure_next_mapping(pool)) {
2163 for (j = i; j < count; j++)
2164 list_add(&pool->cell_sort_array[j]->user_list, &cells);
2166 spin_lock_irqsave(&tc->lock, flags);
2167 list_splice(&cells, &tc->deferred_cells);
2168 spin_unlock_irqrestore(&tc->lock, flags);
2172 if (cell->holder->bi_rw & REQ_DISCARD)
2173 pool->process_discard_cell(tc, cell);
2175 pool->process_cell(tc, cell);
2177 } while (!list_empty(&cells));
2180 static void thin_get(struct thin_c *tc);
2181 static void thin_put(struct thin_c *tc);
2184 * We can't hold rcu_read_lock() around code that can block. So we
2185 * find a thin with the rcu lock held; bump a refcount; then drop
2188 static struct thin_c *get_first_thin(struct pool *pool)
2190 struct thin_c *tc = NULL;
2193 if (!list_empty(&pool->active_thins)) {
2194 tc = list_entry_rcu(pool->active_thins.next, struct thin_c, list);
2202 static struct thin_c *get_next_thin(struct pool *pool, struct thin_c *tc)
2204 struct thin_c *old_tc = tc;
2207 list_for_each_entry_continue_rcu(tc, &pool->active_thins, list) {
2219 static void process_deferred_bios(struct pool *pool)
2221 unsigned long flags;
2223 struct bio_list bios;
2226 tc = get_first_thin(pool);
2228 process_thin_deferred_cells(tc);
2229 process_thin_deferred_bios(tc);
2230 tc = get_next_thin(pool, tc);
2234 * If there are any deferred flush bios, we must commit
2235 * the metadata before issuing them.
2237 bio_list_init(&bios);
2238 spin_lock_irqsave(&pool->lock, flags);
2239 bio_list_merge(&bios, &pool->deferred_flush_bios);
2240 bio_list_init(&pool->deferred_flush_bios);
2241 spin_unlock_irqrestore(&pool->lock, flags);
2243 if (bio_list_empty(&bios) &&
2244 !(dm_pool_changed_this_transaction(pool->pmd) && need_commit_due_to_time(pool)))
2248 while ((bio = bio_list_pop(&bios)))
2252 pool->last_commit_jiffies = jiffies;
2254 while ((bio = bio_list_pop(&bios)))
2255 generic_make_request(bio);
2258 static void do_worker(struct work_struct *ws)
2260 struct pool *pool = container_of(ws, struct pool, worker);
2262 throttle_work_start(&pool->throttle);
2263 dm_pool_issue_prefetches(pool->pmd);
2264 throttle_work_update(&pool->throttle);
2265 process_prepared(pool, &pool->prepared_mappings, &pool->process_prepared_mapping);
2266 throttle_work_update(&pool->throttle);
2267 process_prepared(pool, &pool->prepared_discards, &pool->process_prepared_discard);
2268 throttle_work_update(&pool->throttle);
2269 process_deferred_bios(pool);
2270 throttle_work_complete(&pool->throttle);
2274 * We want to commit periodically so that not too much
2275 * unwritten data builds up.
2277 static void do_waker(struct work_struct *ws)
2279 struct pool *pool = container_of(to_delayed_work(ws), struct pool, waker);
2281 queue_delayed_work(pool->wq, &pool->waker, COMMIT_PERIOD);
2285 * We're holding onto IO to allow userland time to react. After the
2286 * timeout either the pool will have been resized (and thus back in
2287 * PM_WRITE mode), or we degrade to PM_READ_ONLY and start erroring IO.
2289 static void do_no_space_timeout(struct work_struct *ws)
2291 struct pool *pool = container_of(to_delayed_work(ws), struct pool,
2294 if (get_pool_mode(pool) == PM_OUT_OF_DATA_SPACE && !pool->pf.error_if_no_space)
2295 set_pool_mode(pool, PM_READ_ONLY);
2298 /*----------------------------------------------------------------*/
2301 struct work_struct worker;
2302 struct completion complete;
2305 static struct pool_work *to_pool_work(struct work_struct *ws)
2307 return container_of(ws, struct pool_work, worker);
2310 static void pool_work_complete(struct pool_work *pw)
2312 complete(&pw->complete);
2315 static void pool_work_wait(struct pool_work *pw, struct pool *pool,
2316 void (*fn)(struct work_struct *))
2318 INIT_WORK_ONSTACK(&pw->worker, fn);
2319 init_completion(&pw->complete);
2320 queue_work(pool->wq, &pw->worker);
2321 wait_for_completion(&pw->complete);
2324 /*----------------------------------------------------------------*/
2326 struct noflush_work {
2327 struct pool_work pw;
2331 static struct noflush_work *to_noflush(struct work_struct *ws)
2333 return container_of(to_pool_work(ws), struct noflush_work, pw);
2336 static void do_noflush_start(struct work_struct *ws)
2338 struct noflush_work *w = to_noflush(ws);
2339 w->tc->requeue_mode = true;
2341 pool_work_complete(&w->pw);
2344 static void do_noflush_stop(struct work_struct *ws)
2346 struct noflush_work *w = to_noflush(ws);
2347 w->tc->requeue_mode = false;
2348 pool_work_complete(&w->pw);
2351 static void noflush_work(struct thin_c *tc, void (*fn)(struct work_struct *))
2353 struct noflush_work w;
2356 pool_work_wait(&w.pw, tc->pool, fn);
2359 /*----------------------------------------------------------------*/
2361 static enum pool_mode get_pool_mode(struct pool *pool)
2363 return pool->pf.mode;
2366 static void notify_of_pool_mode_change(struct pool *pool, const char *new_mode)
2368 dm_table_event(pool->ti->table);
2369 DMINFO("%s: switching pool to %s mode",
2370 dm_device_name(pool->pool_md), new_mode);
2373 static bool passdown_enabled(struct pool_c *pt)
2375 return pt->adjusted_pf.discard_passdown;
2378 static void set_discard_callbacks(struct pool *pool)
2380 struct pool_c *pt = pool->ti->private;
2382 if (passdown_enabled(pt)) {
2383 pool->process_discard_cell = process_discard_cell_passdown;
2384 pool->process_prepared_discard = process_prepared_discard_passdown;
2386 pool->process_discard_cell = process_discard_cell_no_passdown;
2387 pool->process_prepared_discard = process_prepared_discard_no_passdown;
2391 static void set_pool_mode(struct pool *pool, enum pool_mode new_mode)
2393 struct pool_c *pt = pool->ti->private;
2394 bool needs_check = dm_pool_metadata_needs_check(pool->pmd);
2395 enum pool_mode old_mode = get_pool_mode(pool);
2396 unsigned long no_space_timeout = ACCESS_ONCE(no_space_timeout_secs) * HZ;
2399 * Never allow the pool to transition to PM_WRITE mode if user
2400 * intervention is required to verify metadata and data consistency.
2402 if (new_mode == PM_WRITE && needs_check) {
2403 DMERR("%s: unable to switch pool to write mode until repaired.",
2404 dm_device_name(pool->pool_md));
2405 if (old_mode != new_mode)
2406 new_mode = old_mode;
2408 new_mode = PM_READ_ONLY;
2411 * If we were in PM_FAIL mode, rollback of metadata failed. We're
2412 * not going to recover without a thin_repair. So we never let the
2413 * pool move out of the old mode.
2415 if (old_mode == PM_FAIL)
2416 new_mode = old_mode;
2420 if (old_mode != new_mode)
2421 notify_of_pool_mode_change(pool, "failure");
2422 dm_pool_metadata_read_only(pool->pmd);
2423 pool->process_bio = process_bio_fail;
2424 pool->process_discard = process_bio_fail;
2425 pool->process_cell = process_cell_fail;
2426 pool->process_discard_cell = process_cell_fail;
2427 pool->process_prepared_mapping = process_prepared_mapping_fail;
2428 pool->process_prepared_discard = process_prepared_discard_fail;
2430 error_retry_list(pool);
2434 if (old_mode != new_mode)
2435 notify_of_pool_mode_change(pool, "read-only");
2436 dm_pool_metadata_read_only(pool->pmd);
2437 pool->process_bio = process_bio_read_only;
2438 pool->process_discard = process_bio_success;
2439 pool->process_cell = process_cell_read_only;
2440 pool->process_discard_cell = process_cell_success;
2441 pool->process_prepared_mapping = process_prepared_mapping_fail;
2442 pool->process_prepared_discard = process_prepared_discard_success;
2444 error_retry_list(pool);
2447 case PM_OUT_OF_DATA_SPACE:
2449 * Ideally we'd never hit this state; the low water mark
2450 * would trigger userland to extend the pool before we
2451 * completely run out of data space. However, many small
2452 * IOs to unprovisioned space can consume data space at an
2453 * alarming rate. Adjust your low water mark if you're
2454 * frequently seeing this mode.
2456 if (old_mode != new_mode)
2457 notify_of_pool_mode_change(pool, "out-of-data-space");
2458 pool->process_bio = process_bio_read_only;
2459 pool->process_discard = process_discard_bio;
2460 pool->process_cell = process_cell_read_only;
2461 pool->process_prepared_mapping = process_prepared_mapping;
2462 set_discard_callbacks(pool);
2464 if (!pool->pf.error_if_no_space && no_space_timeout)
2465 queue_delayed_work(pool->wq, &pool->no_space_timeout, no_space_timeout);
2469 if (old_mode != new_mode)
2470 notify_of_pool_mode_change(pool, "write");
2471 dm_pool_metadata_read_write(pool->pmd);
2472 pool->process_bio = process_bio;
2473 pool->process_discard = process_discard_bio;
2474 pool->process_cell = process_cell;
2475 pool->process_prepared_mapping = process_prepared_mapping;
2476 set_discard_callbacks(pool);
2480 pool->pf.mode = new_mode;
2482 * The pool mode may have changed, sync it so bind_control_target()
2483 * doesn't cause an unexpected mode transition on resume.
2485 pt->adjusted_pf.mode = new_mode;
2488 static void abort_transaction(struct pool *pool)
2490 const char *dev_name = dm_device_name(pool->pool_md);
2492 DMERR_LIMIT("%s: aborting current metadata transaction", dev_name);
2493 if (dm_pool_abort_metadata(pool->pmd)) {
2494 DMERR("%s: failed to abort metadata transaction", dev_name);
2495 set_pool_mode(pool, PM_FAIL);
2498 if (dm_pool_metadata_set_needs_check(pool->pmd)) {
2499 DMERR("%s: failed to set 'needs_check' flag in metadata", dev_name);
2500 set_pool_mode(pool, PM_FAIL);
2504 static void metadata_operation_failed(struct pool *pool, const char *op, int r)
2506 DMERR_LIMIT("%s: metadata operation '%s' failed: error = %d",
2507 dm_device_name(pool->pool_md), op, r);
2509 abort_transaction(pool);
2510 set_pool_mode(pool, PM_READ_ONLY);
2513 /*----------------------------------------------------------------*/
2516 * Mapping functions.
2520 * Called only while mapping a thin bio to hand it over to the workqueue.
2522 static void thin_defer_bio(struct thin_c *tc, struct bio *bio)
2524 unsigned long flags;
2525 struct pool *pool = tc->pool;
2527 spin_lock_irqsave(&tc->lock, flags);
2528 bio_list_add(&tc->deferred_bio_list, bio);
2529 spin_unlock_irqrestore(&tc->lock, flags);
2534 static void thin_defer_bio_with_throttle(struct thin_c *tc, struct bio *bio)
2536 struct pool *pool = tc->pool;
2538 throttle_lock(&pool->throttle);
2539 thin_defer_bio(tc, bio);
2540 throttle_unlock(&pool->throttle);
2543 static void thin_defer_cell(struct thin_c *tc, struct dm_bio_prison_cell *cell)
2545 unsigned long flags;
2546 struct pool *pool = tc->pool;
2548 throttle_lock(&pool->throttle);
2549 spin_lock_irqsave(&tc->lock, flags);
2550 list_add_tail(&cell->user_list, &tc->deferred_cells);
2551 spin_unlock_irqrestore(&tc->lock, flags);
2552 throttle_unlock(&pool->throttle);
2557 static void thin_hook_bio(struct thin_c *tc, struct bio *bio)
2559 struct dm_thin_endio_hook *h = dm_per_bio_data(bio, sizeof(struct dm_thin_endio_hook));
2562 h->shared_read_entry = NULL;
2563 h->all_io_entry = NULL;
2564 h->overwrite_mapping = NULL;
2569 * Non-blocking function called from the thin target's map function.
2571 static int thin_bio_map(struct dm_target *ti, struct bio *bio)
2574 struct thin_c *tc = ti->private;
2575 dm_block_t block = get_bio_block(tc, bio);
2576 struct dm_thin_device *td = tc->td;
2577 struct dm_thin_lookup_result result;
2578 struct dm_bio_prison_cell *virt_cell, *data_cell;
2579 struct dm_cell_key key;
2581 thin_hook_bio(tc, bio);
2583 if (tc->requeue_mode) {
2584 bio_endio(bio, DM_ENDIO_REQUEUE);
2585 return DM_MAPIO_SUBMITTED;
2588 if (get_pool_mode(tc->pool) == PM_FAIL) {
2590 return DM_MAPIO_SUBMITTED;
2593 if (bio->bi_rw & (REQ_DISCARD | REQ_FLUSH | REQ_FUA)) {
2594 thin_defer_bio_with_throttle(tc, bio);
2595 return DM_MAPIO_SUBMITTED;
2599 * We must hold the virtual cell before doing the lookup, otherwise
2600 * there's a race with discard.
2602 build_virtual_key(tc->td, block, &key);
2603 if (bio_detain(tc->pool, &key, bio, &virt_cell))
2604 return DM_MAPIO_SUBMITTED;
2606 r = dm_thin_find_block(td, block, 0, &result);
2609 * Note that we defer readahead too.
2613 if (unlikely(result.shared)) {
2615 * We have a race condition here between the
2616 * result.shared value returned by the lookup and
2617 * snapshot creation, which may cause new
2620 * To avoid this always quiesce the origin before
2621 * taking the snap. You want to do this anyway to
2622 * ensure a consistent application view
2625 * More distant ancestors are irrelevant. The
2626 * shared flag will be set in their case.
2628 thin_defer_cell(tc, virt_cell);
2629 return DM_MAPIO_SUBMITTED;
2632 build_data_key(tc->td, result.block, &key);
2633 if (bio_detain(tc->pool, &key, bio, &data_cell)) {
2634 cell_defer_no_holder(tc, virt_cell);
2635 return DM_MAPIO_SUBMITTED;
2638 inc_all_io_entry(tc->pool, bio);
2639 cell_defer_no_holder(tc, data_cell);
2640 cell_defer_no_holder(tc, virt_cell);
2642 remap(tc, bio, result.block);
2643 return DM_MAPIO_REMAPPED;
2647 thin_defer_cell(tc, virt_cell);
2648 return DM_MAPIO_SUBMITTED;
2652 * Must always call bio_io_error on failure.
2653 * dm_thin_find_block can fail with -EINVAL if the
2654 * pool is switched to fail-io mode.
2657 cell_defer_no_holder(tc, virt_cell);
2658 return DM_MAPIO_SUBMITTED;
2662 static int pool_is_congested(struct dm_target_callbacks *cb, int bdi_bits)
2664 struct pool_c *pt = container_of(cb, struct pool_c, callbacks);
2665 struct request_queue *q;
2667 if (get_pool_mode(pt->pool) == PM_OUT_OF_DATA_SPACE)
2670 q = bdev_get_queue(pt->data_dev->bdev);
2671 return bdi_congested(&q->backing_dev_info, bdi_bits);
2674 static void requeue_bios(struct pool *pool)
2676 unsigned long flags;
2680 list_for_each_entry_rcu(tc, &pool->active_thins, list) {
2681 spin_lock_irqsave(&tc->lock, flags);
2682 bio_list_merge(&tc->deferred_bio_list, &tc->retry_on_resume_list);
2683 bio_list_init(&tc->retry_on_resume_list);
2684 spin_unlock_irqrestore(&tc->lock, flags);
2689 /*----------------------------------------------------------------
2690 * Binding of control targets to a pool object
2691 *--------------------------------------------------------------*/
2692 static bool data_dev_supports_discard(struct pool_c *pt)
2694 struct request_queue *q = bdev_get_queue(pt->data_dev->bdev);
2696 return q && blk_queue_discard(q);
2699 static bool is_factor(sector_t block_size, uint32_t n)
2701 return !sector_div(block_size, n);
2705 * If discard_passdown was enabled verify that the data device
2706 * supports discards. Disable discard_passdown if not.
2708 static void disable_passdown_if_not_supported(struct pool_c *pt)
2710 struct pool *pool = pt->pool;
2711 struct block_device *data_bdev = pt->data_dev->bdev;
2712 struct queue_limits *data_limits = &bdev_get_queue(data_bdev)->limits;
2713 const char *reason = NULL;
2714 char buf[BDEVNAME_SIZE];
2716 if (!pt->adjusted_pf.discard_passdown)
2719 if (!data_dev_supports_discard(pt))
2720 reason = "discard unsupported";
2722 else if (data_limits->max_discard_sectors < pool->sectors_per_block)
2723 reason = "max discard sectors smaller than a block";
2726 DMWARN("Data device (%s) %s: Disabling discard passdown.", bdevname(data_bdev, buf), reason);
2727 pt->adjusted_pf.discard_passdown = false;
2731 static int bind_control_target(struct pool *pool, struct dm_target *ti)
2733 struct pool_c *pt = ti->private;
2736 * We want to make sure that a pool in PM_FAIL mode is never upgraded.
2738 enum pool_mode old_mode = get_pool_mode(pool);
2739 enum pool_mode new_mode = pt->adjusted_pf.mode;
2742 * Don't change the pool's mode until set_pool_mode() below.
2743 * Otherwise the pool's process_* function pointers may
2744 * not match the desired pool mode.
2746 pt->adjusted_pf.mode = old_mode;
2749 pool->pf = pt->adjusted_pf;
2750 pool->low_water_blocks = pt->low_water_blocks;
2752 set_pool_mode(pool, new_mode);
2757 static void unbind_control_target(struct pool *pool, struct dm_target *ti)
2763 /*----------------------------------------------------------------
2765 *--------------------------------------------------------------*/
2766 /* Initialize pool features. */
2767 static void pool_features_init(struct pool_features *pf)
2769 pf->mode = PM_WRITE;
2770 pf->zero_new_blocks = true;
2771 pf->discard_enabled = true;
2772 pf->discard_passdown = true;
2773 pf->error_if_no_space = false;
2776 static void __pool_destroy(struct pool *pool)
2778 __pool_table_remove(pool);
2780 if (dm_pool_metadata_close(pool->pmd) < 0)
2781 DMWARN("%s: dm_pool_metadata_close() failed.", __func__);
2783 dm_bio_prison_destroy(pool->prison);
2784 dm_kcopyd_client_destroy(pool->copier);
2787 destroy_workqueue(pool->wq);
2789 if (pool->next_mapping)
2790 mempool_free(pool->next_mapping, pool->mapping_pool);
2791 mempool_destroy(pool->mapping_pool);
2792 dm_deferred_set_destroy(pool->shared_read_ds);
2793 dm_deferred_set_destroy(pool->all_io_ds);
2797 static struct kmem_cache *_new_mapping_cache;
2799 static struct pool *pool_create(struct mapped_device *pool_md,
2800 struct block_device *metadata_dev,
2801 unsigned long block_size,
2802 int read_only, char **error)
2807 struct dm_pool_metadata *pmd;
2808 bool format_device = read_only ? false : true;
2810 pmd = dm_pool_metadata_open(metadata_dev, block_size, format_device);
2812 *error = "Error creating metadata object";
2813 return (struct pool *)pmd;
2816 pool = kmalloc(sizeof(*pool), GFP_KERNEL);
2818 *error = "Error allocating memory for pool";
2819 err_p = ERR_PTR(-ENOMEM);
2824 pool->sectors_per_block = block_size;
2825 if (block_size & (block_size - 1))
2826 pool->sectors_per_block_shift = -1;
2828 pool->sectors_per_block_shift = __ffs(block_size);
2829 pool->low_water_blocks = 0;
2830 pool_features_init(&pool->pf);
2831 pool->prison = dm_bio_prison_create();
2832 if (!pool->prison) {
2833 *error = "Error creating pool's bio prison";
2834 err_p = ERR_PTR(-ENOMEM);
2838 pool->copier = dm_kcopyd_client_create(&dm_kcopyd_throttle);
2839 if (IS_ERR(pool->copier)) {
2840 r = PTR_ERR(pool->copier);
2841 *error = "Error creating pool's kcopyd client";
2843 goto bad_kcopyd_client;
2847 * Create singlethreaded workqueue that will service all devices
2848 * that use this metadata.
2850 pool->wq = alloc_ordered_workqueue("dm-" DM_MSG_PREFIX, WQ_MEM_RECLAIM);
2852 *error = "Error creating pool's workqueue";
2853 err_p = ERR_PTR(-ENOMEM);
2857 throttle_init(&pool->throttle);
2858 INIT_WORK(&pool->worker, do_worker);
2859 INIT_DELAYED_WORK(&pool->waker, do_waker);
2860 INIT_DELAYED_WORK(&pool->no_space_timeout, do_no_space_timeout);
2861 spin_lock_init(&pool->lock);
2862 bio_list_init(&pool->deferred_flush_bios);
2863 INIT_LIST_HEAD(&pool->prepared_mappings);
2864 INIT_LIST_HEAD(&pool->prepared_discards);
2865 INIT_LIST_HEAD(&pool->active_thins);
2866 pool->low_water_triggered = false;
2867 pool->suspended = true;
2869 pool->shared_read_ds = dm_deferred_set_create();
2870 if (!pool->shared_read_ds) {
2871 *error = "Error creating pool's shared read deferred set";
2872 err_p = ERR_PTR(-ENOMEM);
2873 goto bad_shared_read_ds;
2876 pool->all_io_ds = dm_deferred_set_create();
2877 if (!pool->all_io_ds) {
2878 *error = "Error creating pool's all io deferred set";
2879 err_p = ERR_PTR(-ENOMEM);
2883 pool->next_mapping = NULL;
2884 pool->mapping_pool = mempool_create_slab_pool(MAPPING_POOL_SIZE,
2885 _new_mapping_cache);
2886 if (!pool->mapping_pool) {
2887 *error = "Error creating pool's mapping mempool";
2888 err_p = ERR_PTR(-ENOMEM);
2889 goto bad_mapping_pool;
2892 pool->ref_count = 1;
2893 pool->last_commit_jiffies = jiffies;
2894 pool->pool_md = pool_md;
2895 pool->md_dev = metadata_dev;
2896 __pool_table_insert(pool);
2901 dm_deferred_set_destroy(pool->all_io_ds);
2903 dm_deferred_set_destroy(pool->shared_read_ds);
2905 destroy_workqueue(pool->wq);
2907 dm_kcopyd_client_destroy(pool->copier);
2909 dm_bio_prison_destroy(pool->prison);
2913 if (dm_pool_metadata_close(pmd))
2914 DMWARN("%s: dm_pool_metadata_close() failed.", __func__);
2919 static void __pool_inc(struct pool *pool)
2921 BUG_ON(!mutex_is_locked(&dm_thin_pool_table.mutex));
2925 static void __pool_dec(struct pool *pool)
2927 BUG_ON(!mutex_is_locked(&dm_thin_pool_table.mutex));
2928 BUG_ON(!pool->ref_count);
2929 if (!--pool->ref_count)
2930 __pool_destroy(pool);
2933 static struct pool *__pool_find(struct mapped_device *pool_md,
2934 struct block_device *metadata_dev,
2935 unsigned long block_size, int read_only,
2936 char **error, int *created)
2938 struct pool *pool = __pool_table_lookup_metadata_dev(metadata_dev);
2941 if (pool->pool_md != pool_md) {
2942 *error = "metadata device already in use by a pool";
2943 return ERR_PTR(-EBUSY);
2948 pool = __pool_table_lookup(pool_md);
2950 if (pool->md_dev != metadata_dev) {
2951 *error = "different pool cannot replace a pool";
2952 return ERR_PTR(-EINVAL);
2957 pool = pool_create(pool_md, metadata_dev, block_size, read_only, error);
2965 /*----------------------------------------------------------------
2966 * Pool target methods
2967 *--------------------------------------------------------------*/
2968 static void pool_dtr(struct dm_target *ti)
2970 struct pool_c *pt = ti->private;
2972 mutex_lock(&dm_thin_pool_table.mutex);
2974 unbind_control_target(pt->pool, ti);
2975 __pool_dec(pt->pool);
2976 dm_put_device(ti, pt->metadata_dev);
2977 dm_put_device(ti, pt->data_dev);
2980 mutex_unlock(&dm_thin_pool_table.mutex);
2983 static int parse_pool_features(struct dm_arg_set *as, struct pool_features *pf,
2984 struct dm_target *ti)
2988 const char *arg_name;
2990 static struct dm_arg _args[] = {
2991 {0, 4, "Invalid number of pool feature arguments"},
2995 * No feature arguments supplied.
3000 r = dm_read_arg_group(_args, as, &argc, &ti->error);
3004 while (argc && !r) {
3005 arg_name = dm_shift_arg(as);
3008 if (!strcasecmp(arg_name, "skip_block_zeroing"))
3009 pf->zero_new_blocks = false;
3011 else if (!strcasecmp(arg_name, "ignore_discard"))
3012 pf->discard_enabled = false;
3014 else if (!strcasecmp(arg_name, "no_discard_passdown"))
3015 pf->discard_passdown = false;
3017 else if (!strcasecmp(arg_name, "read_only"))
3018 pf->mode = PM_READ_ONLY;
3020 else if (!strcasecmp(arg_name, "error_if_no_space"))
3021 pf->error_if_no_space = true;
3024 ti->error = "Unrecognised pool feature requested";
3033 static void metadata_low_callback(void *context)
3035 struct pool *pool = context;
3037 DMWARN("%s: reached low water mark for metadata device: sending event.",
3038 dm_device_name(pool->pool_md));
3040 dm_table_event(pool->ti->table);
3043 static sector_t get_dev_size(struct block_device *bdev)
3045 return i_size_read(bdev->bd_inode) >> SECTOR_SHIFT;
3048 static void warn_if_metadata_device_too_big(struct block_device *bdev)
3050 sector_t metadata_dev_size = get_dev_size(bdev);
3051 char buffer[BDEVNAME_SIZE];
3053 if (metadata_dev_size > THIN_METADATA_MAX_SECTORS_WARNING)
3054 DMWARN("Metadata device %s is larger than %u sectors: excess space will not be used.",
3055 bdevname(bdev, buffer), THIN_METADATA_MAX_SECTORS);
3058 static sector_t get_metadata_dev_size(struct block_device *bdev)
3060 sector_t metadata_dev_size = get_dev_size(bdev);
3062 if (metadata_dev_size > THIN_METADATA_MAX_SECTORS)
3063 metadata_dev_size = THIN_METADATA_MAX_SECTORS;
3065 return metadata_dev_size;
3068 static dm_block_t get_metadata_dev_size_in_blocks(struct block_device *bdev)
3070 sector_t metadata_dev_size = get_metadata_dev_size(bdev);
3072 sector_div(metadata_dev_size, THIN_METADATA_BLOCK_SIZE);
3074 return metadata_dev_size;
3078 * When a metadata threshold is crossed a dm event is triggered, and
3079 * userland should respond by growing the metadata device. We could let
3080 * userland set the threshold, like we do with the data threshold, but I'm
3081 * not sure they know enough to do this well.
3083 static dm_block_t calc_metadata_threshold(struct pool_c *pt)
3086 * 4M is ample for all ops with the possible exception of thin
3087 * device deletion which is harmless if it fails (just retry the
3088 * delete after you've grown the device).
3090 dm_block_t quarter = get_metadata_dev_size_in_blocks(pt->metadata_dev->bdev) / 4;
3091 return min((dm_block_t)1024ULL /* 4M */, quarter);
3095 * thin-pool <metadata dev> <data dev>
3096 * <data block size (sectors)>
3097 * <low water mark (blocks)>
3098 * [<#feature args> [<arg>]*]
3100 * Optional feature arguments are:
3101 * skip_block_zeroing: skips the zeroing of newly-provisioned blocks.
3102 * ignore_discard: disable discard
3103 * no_discard_passdown: don't pass discards down to the data device
3104 * read_only: Don't allow any changes to be made to the pool metadata.
3105 * error_if_no_space: error IOs, instead of queueing, if no space.
3107 static int pool_ctr(struct dm_target *ti, unsigned argc, char **argv)
3109 int r, pool_created = 0;
3112 struct pool_features pf;
3113 struct dm_arg_set as;
3114 struct dm_dev *data_dev;
3115 unsigned long block_size;
3116 dm_block_t low_water_blocks;
3117 struct dm_dev *metadata_dev;
3118 fmode_t metadata_mode;
3121 * FIXME Remove validation from scope of lock.
3123 mutex_lock(&dm_thin_pool_table.mutex);
3126 ti->error = "Invalid argument count";
3135 * Set default pool features.
3137 pool_features_init(&pf);
3139 dm_consume_args(&as, 4);
3140 r = parse_pool_features(&as, &pf, ti);
3144 metadata_mode = FMODE_READ | ((pf.mode == PM_READ_ONLY) ? 0 : FMODE_WRITE);
3145 r = dm_get_device(ti, argv[0], metadata_mode, &metadata_dev);
3147 ti->error = "Error opening metadata block device";
3150 warn_if_metadata_device_too_big(metadata_dev->bdev);
3152 r = dm_get_device(ti, argv[1], FMODE_READ | FMODE_WRITE, &data_dev);
3154 ti->error = "Error getting data device";
3158 if (kstrtoul(argv[2], 10, &block_size) || !block_size ||
3159 block_size < DATA_DEV_BLOCK_SIZE_MIN_SECTORS ||
3160 block_size > DATA_DEV_BLOCK_SIZE_MAX_SECTORS ||
3161 block_size & (DATA_DEV_BLOCK_SIZE_MIN_SECTORS - 1)) {
3162 ti->error = "Invalid block size";
3167 if (kstrtoull(argv[3], 10, (unsigned long long *)&low_water_blocks)) {
3168 ti->error = "Invalid low water mark";
3173 pt = kzalloc(sizeof(*pt), GFP_KERNEL);
3179 pool = __pool_find(dm_table_get_md(ti->table), metadata_dev->bdev,
3180 block_size, pf.mode == PM_READ_ONLY, &ti->error, &pool_created);
3187 * 'pool_created' reflects whether this is the first table load.
3188 * Top level discard support is not allowed to be changed after
3189 * initial load. This would require a pool reload to trigger thin
3192 if (!pool_created && pf.discard_enabled != pool->pf.discard_enabled) {
3193 ti->error = "Discard support cannot be disabled once enabled";
3195 goto out_flags_changed;
3200 pt->metadata_dev = metadata_dev;
3201 pt->data_dev = data_dev;
3202 pt->low_water_blocks = low_water_blocks;
3203 pt->adjusted_pf = pt->requested_pf = pf;
3204 ti->num_flush_bios = 1;
3207 * Only need to enable discards if the pool should pass
3208 * them down to the data device. The thin device's discard
3209 * processing will cause mappings to be removed from the btree.
3211 ti->discard_zeroes_data_unsupported = true;
3212 if (pf.discard_enabled && pf.discard_passdown) {
3213 ti->num_discard_bios = 1;
3216 * Setting 'discards_supported' circumvents the normal
3217 * stacking of discard limits (this keeps the pool and
3218 * thin devices' discard limits consistent).
3220 ti->discards_supported = true;
3224 r = dm_pool_register_metadata_threshold(pt->pool->pmd,
3225 calc_metadata_threshold(pt),
3226 metadata_low_callback,
3231 pt->callbacks.congested_fn = pool_is_congested;
3232 dm_table_add_target_callbacks(ti->table, &pt->callbacks);
3234 mutex_unlock(&dm_thin_pool_table.mutex);
3243 dm_put_device(ti, data_dev);
3245 dm_put_device(ti, metadata_dev);
3247 mutex_unlock(&dm_thin_pool_table.mutex);
3252 static int pool_map(struct dm_target *ti, struct bio *bio)
3255 struct pool_c *pt = ti->private;
3256 struct pool *pool = pt->pool;
3257 unsigned long flags;
3260 * As this is a singleton target, ti->begin is always zero.
3262 spin_lock_irqsave(&pool->lock, flags);
3263 bio->bi_bdev = pt->data_dev->bdev;
3264 r = DM_MAPIO_REMAPPED;
3265 spin_unlock_irqrestore(&pool->lock, flags);
3270 static int maybe_resize_data_dev(struct dm_target *ti, bool *need_commit)
3273 struct pool_c *pt = ti->private;
3274 struct pool *pool = pt->pool;
3275 sector_t data_size = ti->len;
3276 dm_block_t sb_data_size;
3278 *need_commit = false;
3280 (void) sector_div(data_size, pool->sectors_per_block);
3282 r = dm_pool_get_data_dev_size(pool->pmd, &sb_data_size);
3284 DMERR("%s: failed to retrieve data device size",
3285 dm_device_name(pool->pool_md));
3289 if (data_size < sb_data_size) {
3290 DMERR("%s: pool target (%llu blocks) too small: expected %llu",
3291 dm_device_name(pool->pool_md),
3292 (unsigned long long)data_size, sb_data_size);
3295 } else if (data_size > sb_data_size) {
3296 if (dm_pool_metadata_needs_check(pool->pmd)) {
3297 DMERR("%s: unable to grow the data device until repaired.",
3298 dm_device_name(pool->pool_md));
3303 DMINFO("%s: growing the data device from %llu to %llu blocks",
3304 dm_device_name(pool->pool_md),
3305 sb_data_size, (unsigned long long)data_size);
3306 r = dm_pool_resize_data_dev(pool->pmd, data_size);
3308 metadata_operation_failed(pool, "dm_pool_resize_data_dev", r);
3312 *need_commit = true;
3318 static int maybe_resize_metadata_dev(struct dm_target *ti, bool *need_commit)
3321 struct pool_c *pt = ti->private;
3322 struct pool *pool = pt->pool;
3323 dm_block_t metadata_dev_size, sb_metadata_dev_size;
3325 *need_commit = false;
3327 metadata_dev_size = get_metadata_dev_size_in_blocks(pool->md_dev);
3329 r = dm_pool_get_metadata_dev_size(pool->pmd, &sb_metadata_dev_size);
3331 DMERR("%s: failed to retrieve metadata device size",
3332 dm_device_name(pool->pool_md));
3336 if (metadata_dev_size < sb_metadata_dev_size) {
3337 DMERR("%s: metadata device (%llu blocks) too small: expected %llu",
3338 dm_device_name(pool->pool_md),
3339 metadata_dev_size, sb_metadata_dev_size);
3342 } else if (metadata_dev_size > sb_metadata_dev_size) {
3343 if (dm_pool_metadata_needs_check(pool->pmd)) {
3344 DMERR("%s: unable to grow the metadata device until repaired.",
3345 dm_device_name(pool->pool_md));
3349 warn_if_metadata_device_too_big(pool->md_dev);
3350 DMINFO("%s: growing the metadata device from %llu to %llu blocks",
3351 dm_device_name(pool->pool_md),
3352 sb_metadata_dev_size, metadata_dev_size);
3353 r = dm_pool_resize_metadata_dev(pool->pmd, metadata_dev_size);
3355 metadata_operation_failed(pool, "dm_pool_resize_metadata_dev", r);
3359 *need_commit = true;
3366 * Retrieves the number of blocks of the data device from
3367 * the superblock and compares it to the actual device size,
3368 * thus resizing the data device in case it has grown.
3370 * This both copes with opening preallocated data devices in the ctr
3371 * being followed by a resume
3373 * calling the resume method individually after userspace has
3374 * grown the data device in reaction to a table event.
3376 static int pool_preresume(struct dm_target *ti)
3379 bool need_commit1, need_commit2;
3380 struct pool_c *pt = ti->private;
3381 struct pool *pool = pt->pool;
3384 * Take control of the pool object.
3386 r = bind_control_target(pool, ti);
3390 r = maybe_resize_data_dev(ti, &need_commit1);
3394 r = maybe_resize_metadata_dev(ti, &need_commit2);
3398 if (need_commit1 || need_commit2)
3399 (void) commit(pool);
3404 static void pool_suspend_active_thins(struct pool *pool)
3408 /* Suspend all active thin devices */
3409 tc = get_first_thin(pool);
3411 dm_internal_suspend_noflush(tc->thin_md);
3412 tc = get_next_thin(pool, tc);
3416 static void pool_resume_active_thins(struct pool *pool)
3420 /* Resume all active thin devices */
3421 tc = get_first_thin(pool);
3423 dm_internal_resume(tc->thin_md);
3424 tc = get_next_thin(pool, tc);
3428 static void pool_resume(struct dm_target *ti)
3430 struct pool_c *pt = ti->private;
3431 struct pool *pool = pt->pool;
3432 unsigned long flags;
3435 * Must requeue active_thins' bios and then resume
3436 * active_thins _before_ clearing 'suspend' flag.
3439 pool_resume_active_thins(pool);
3441 spin_lock_irqsave(&pool->lock, flags);
3442 pool->low_water_triggered = false;
3443 pool->suspended = false;
3444 spin_unlock_irqrestore(&pool->lock, flags);
3446 do_waker(&pool->waker.work);
3449 static void pool_presuspend(struct dm_target *ti)
3451 struct pool_c *pt = ti->private;
3452 struct pool *pool = pt->pool;
3453 unsigned long flags;
3455 spin_lock_irqsave(&pool->lock, flags);
3456 pool->suspended = true;
3457 spin_unlock_irqrestore(&pool->lock, flags);
3459 pool_suspend_active_thins(pool);
3462 static void pool_presuspend_undo(struct dm_target *ti)
3464 struct pool_c *pt = ti->private;
3465 struct pool *pool = pt->pool;
3466 unsigned long flags;
3468 pool_resume_active_thins(pool);
3470 spin_lock_irqsave(&pool->lock, flags);
3471 pool->suspended = false;
3472 spin_unlock_irqrestore(&pool->lock, flags);
3475 static void pool_postsuspend(struct dm_target *ti)
3477 struct pool_c *pt = ti->private;
3478 struct pool *pool = pt->pool;
3480 cancel_delayed_work(&pool->waker);
3481 cancel_delayed_work(&pool->no_space_timeout);
3482 flush_workqueue(pool->wq);
3483 (void) commit(pool);
3486 static int check_arg_count(unsigned argc, unsigned args_required)
3488 if (argc != args_required) {
3489 DMWARN("Message received with %u arguments instead of %u.",
3490 argc, args_required);
3497 static int read_dev_id(char *arg, dm_thin_id *dev_id, int warning)
3499 if (!kstrtoull(arg, 10, (unsigned long long *)dev_id) &&
3500 *dev_id <= MAX_DEV_ID)
3504 DMWARN("Message received with invalid device id: %s", arg);
3509 static int process_create_thin_mesg(unsigned argc, char **argv, struct pool *pool)
3514 r = check_arg_count(argc, 2);
3518 r = read_dev_id(argv[1], &dev_id, 1);
3522 r = dm_pool_create_thin(pool->pmd, dev_id);
3524 DMWARN("Creation of new thinly-provisioned device with id %s failed.",
3532 static int process_create_snap_mesg(unsigned argc, char **argv, struct pool *pool)
3535 dm_thin_id origin_dev_id;
3538 r = check_arg_count(argc, 3);
3542 r = read_dev_id(argv[1], &dev_id, 1);
3546 r = read_dev_id(argv[2], &origin_dev_id, 1);
3550 r = dm_pool_create_snap(pool->pmd, dev_id, origin_dev_id);
3552 DMWARN("Creation of new snapshot %s of device %s failed.",
3560 static int process_delete_mesg(unsigned argc, char **argv, struct pool *pool)
3565 r = check_arg_count(argc, 2);
3569 r = read_dev_id(argv[1], &dev_id, 1);
3573 r = dm_pool_delete_thin_device(pool->pmd, dev_id);
3575 DMWARN("Deletion of thin device %s failed.", argv[1]);
3580 static int process_set_transaction_id_mesg(unsigned argc, char **argv, struct pool *pool)
3582 dm_thin_id old_id, new_id;
3585 r = check_arg_count(argc, 3);
3589 if (kstrtoull(argv[1], 10, (unsigned long long *)&old_id)) {
3590 DMWARN("set_transaction_id message: Unrecognised id %s.", argv[1]);
3594 if (kstrtoull(argv[2], 10, (unsigned long long *)&new_id)) {
3595 DMWARN("set_transaction_id message: Unrecognised new id %s.", argv[2]);
3599 r = dm_pool_set_metadata_transaction_id(pool->pmd, old_id, new_id);
3601 DMWARN("Failed to change transaction id from %s to %s.",
3609 static int process_reserve_metadata_snap_mesg(unsigned argc, char **argv, struct pool *pool)
3613 r = check_arg_count(argc, 1);
3617 (void) commit(pool);
3619 r = dm_pool_reserve_metadata_snap(pool->pmd);
3621 DMWARN("reserve_metadata_snap message failed.");
3626 static int process_release_metadata_snap_mesg(unsigned argc, char **argv, struct pool *pool)
3630 r = check_arg_count(argc, 1);
3634 r = dm_pool_release_metadata_snap(pool->pmd);
3636 DMWARN("release_metadata_snap message failed.");
3642 * Messages supported:
3643 * create_thin <dev_id>
3644 * create_snap <dev_id> <origin_id>
3646 * set_transaction_id <current_trans_id> <new_trans_id>
3647 * reserve_metadata_snap
3648 * release_metadata_snap
3650 static int pool_message(struct dm_target *ti, unsigned argc, char **argv)
3653 struct pool_c *pt = ti->private;
3654 struct pool *pool = pt->pool;
3656 if (get_pool_mode(pool) >= PM_READ_ONLY) {
3657 DMERR("%s: unable to service pool target messages in READ_ONLY or FAIL mode",
3658 dm_device_name(pool->pool_md));
3662 if (!strcasecmp(argv[0], "create_thin"))
3663 r = process_create_thin_mesg(argc, argv, pool);
3665 else if (!strcasecmp(argv[0], "create_snap"))
3666 r = process_create_snap_mesg(argc, argv, pool);
3668 else if (!strcasecmp(argv[0], "delete"))
3669 r = process_delete_mesg(argc, argv, pool);
3671 else if (!strcasecmp(argv[0], "set_transaction_id"))
3672 r = process_set_transaction_id_mesg(argc, argv, pool);
3674 else if (!strcasecmp(argv[0], "reserve_metadata_snap"))
3675 r = process_reserve_metadata_snap_mesg(argc, argv, pool);
3677 else if (!strcasecmp(argv[0], "release_metadata_snap"))
3678 r = process_release_metadata_snap_mesg(argc, argv, pool);
3681 DMWARN("Unrecognised thin pool target message received: %s", argv[0]);
3684 (void) commit(pool);
3689 static void emit_flags(struct pool_features *pf, char *result,
3690 unsigned sz, unsigned maxlen)
3692 unsigned count = !pf->zero_new_blocks + !pf->discard_enabled +
3693 !pf->discard_passdown + (pf->mode == PM_READ_ONLY) +
3694 pf->error_if_no_space;
3695 DMEMIT("%u ", count);
3697 if (!pf->zero_new_blocks)
3698 DMEMIT("skip_block_zeroing ");
3700 if (!pf->discard_enabled)
3701 DMEMIT("ignore_discard ");
3703 if (!pf->discard_passdown)
3704 DMEMIT("no_discard_passdown ");
3706 if (pf->mode == PM_READ_ONLY)
3707 DMEMIT("read_only ");
3709 if (pf->error_if_no_space)
3710 DMEMIT("error_if_no_space ");
3715 * <transaction id> <used metadata sectors>/<total metadata sectors>
3716 * <used data sectors>/<total data sectors> <held metadata root>
3718 static void pool_status(struct dm_target *ti, status_type_t type,
3719 unsigned status_flags, char *result, unsigned maxlen)
3723 uint64_t transaction_id;
3724 dm_block_t nr_free_blocks_data;
3725 dm_block_t nr_free_blocks_metadata;
3726 dm_block_t nr_blocks_data;
3727 dm_block_t nr_blocks_metadata;
3728 dm_block_t held_root;
3729 char buf[BDEVNAME_SIZE];
3730 char buf2[BDEVNAME_SIZE];
3731 struct pool_c *pt = ti->private;
3732 struct pool *pool = pt->pool;
3735 case STATUSTYPE_INFO:
3736 if (get_pool_mode(pool) == PM_FAIL) {
3741 /* Commit to ensure statistics aren't out-of-date */
3742 if (!(status_flags & DM_STATUS_NOFLUSH_FLAG) && !dm_suspended(ti))
3743 (void) commit(pool);
3745 r = dm_pool_get_metadata_transaction_id(pool->pmd, &transaction_id);
3747 DMERR("%s: dm_pool_get_metadata_transaction_id returned %d",
3748 dm_device_name(pool->pool_md), r);
3752 r = dm_pool_get_free_metadata_block_count(pool->pmd, &nr_free_blocks_metadata);
3754 DMERR("%s: dm_pool_get_free_metadata_block_count returned %d",
3755 dm_device_name(pool->pool_md), r);
3759 r = dm_pool_get_metadata_dev_size(pool->pmd, &nr_blocks_metadata);
3761 DMERR("%s: dm_pool_get_metadata_dev_size returned %d",
3762 dm_device_name(pool->pool_md), r);
3766 r = dm_pool_get_free_block_count(pool->pmd, &nr_free_blocks_data);
3768 DMERR("%s: dm_pool_get_free_block_count returned %d",
3769 dm_device_name(pool->pool_md), r);
3773 r = dm_pool_get_data_dev_size(pool->pmd, &nr_blocks_data);
3775 DMERR("%s: dm_pool_get_data_dev_size returned %d",
3776 dm_device_name(pool->pool_md), r);
3780 r = dm_pool_get_metadata_snap(pool->pmd, &held_root);
3782 DMERR("%s: dm_pool_get_metadata_snap returned %d",
3783 dm_device_name(pool->pool_md), r);
3787 DMEMIT("%llu %llu/%llu %llu/%llu ",
3788 (unsigned long long)transaction_id,
3789 (unsigned long long)(nr_blocks_metadata - nr_free_blocks_metadata),
3790 (unsigned long long)nr_blocks_metadata,
3791 (unsigned long long)(nr_blocks_data - nr_free_blocks_data),
3792 (unsigned long long)nr_blocks_data);
3795 DMEMIT("%llu ", held_root);
3799 if (pool->pf.mode == PM_OUT_OF_DATA_SPACE)
3800 DMEMIT("out_of_data_space ");
3801 else if (pool->pf.mode == PM_READ_ONLY)
3806 if (!pool->pf.discard_enabled)
3807 DMEMIT("ignore_discard ");
3808 else if (pool->pf.discard_passdown)
3809 DMEMIT("discard_passdown ");
3811 DMEMIT("no_discard_passdown ");
3813 if (pool->pf.error_if_no_space)
3814 DMEMIT("error_if_no_space ");
3816 DMEMIT("queue_if_no_space ");
3820 case STATUSTYPE_TABLE:
3821 DMEMIT("%s %s %lu %llu ",
3822 format_dev_t(buf, pt->metadata_dev->bdev->bd_dev),
3823 format_dev_t(buf2, pt->data_dev->bdev->bd_dev),
3824 (unsigned long)pool->sectors_per_block,
3825 (unsigned long long)pt->low_water_blocks);
3826 emit_flags(&pt->requested_pf, result, sz, maxlen);
3835 static int pool_iterate_devices(struct dm_target *ti,
3836 iterate_devices_callout_fn fn, void *data)
3838 struct pool_c *pt = ti->private;
3840 return fn(ti, pt->data_dev, 0, ti->len, data);
3843 static int pool_merge(struct dm_target *ti, struct bvec_merge_data *bvm,
3844 struct bio_vec *biovec, int max_size)
3846 struct pool_c *pt = ti->private;
3847 struct request_queue *q = bdev_get_queue(pt->data_dev->bdev);
3849 if (!q->merge_bvec_fn)
3852 bvm->bi_bdev = pt->data_dev->bdev;
3854 return min(max_size, q->merge_bvec_fn(q, bvm, biovec));
3857 static void pool_io_hints(struct dm_target *ti, struct queue_limits *limits)
3859 struct pool_c *pt = ti->private;
3860 struct pool *pool = pt->pool;
3861 sector_t io_opt_sectors = limits->io_opt >> SECTOR_SHIFT;
3864 * If max_sectors is smaller than pool->sectors_per_block adjust it
3865 * to the highest possible power-of-2 factor of pool->sectors_per_block.
3866 * This is especially beneficial when the pool's data device is a RAID
3867 * device that has a full stripe width that matches pool->sectors_per_block
3868 * -- because even though partial RAID stripe-sized IOs will be issued to a
3869 * single RAID stripe; when aggregated they will end on a full RAID stripe
3870 * boundary.. which avoids additional partial RAID stripe writes cascading
3872 if (limits->max_sectors < pool->sectors_per_block) {
3873 while (!is_factor(pool->sectors_per_block, limits->max_sectors)) {
3874 if ((limits->max_sectors & (limits->max_sectors - 1)) == 0)
3875 limits->max_sectors--;
3876 limits->max_sectors = rounddown_pow_of_two(limits->max_sectors);
3881 * If the system-determined stacked limits are compatible with the
3882 * pool's blocksize (io_opt is a factor) do not override them.
3884 if (io_opt_sectors < pool->sectors_per_block ||
3885 !is_factor(io_opt_sectors, pool->sectors_per_block)) {
3886 if (is_factor(pool->sectors_per_block, limits->max_sectors))
3887 blk_limits_io_min(limits, limits->max_sectors << SECTOR_SHIFT);
3889 blk_limits_io_min(limits, pool->sectors_per_block << SECTOR_SHIFT);
3890 blk_limits_io_opt(limits, pool->sectors_per_block << SECTOR_SHIFT);
3894 * pt->adjusted_pf is a staging area for the actual features to use.
3895 * They get transferred to the live pool in bind_control_target()
3896 * called from pool_preresume().
3898 if (!pt->adjusted_pf.discard_enabled) {
3900 * Must explicitly disallow stacking discard limits otherwise the
3901 * block layer will stack them if pool's data device has support.
3902 * QUEUE_FLAG_DISCARD wouldn't be set but there is no way for the
3903 * user to see that, so make sure to set all discard limits to 0.
3905 limits->discard_granularity = 0;
3909 disable_passdown_if_not_supported(pt);
3912 * The pool uses the same discard limits as the underlying data
3913 * device. DM core has already set this up.
3917 static struct target_type pool_target = {
3918 .name = "thin-pool",
3919 .features = DM_TARGET_SINGLETON | DM_TARGET_ALWAYS_WRITEABLE |
3920 DM_TARGET_IMMUTABLE,
3921 .version = {1, 15, 0},
3922 .module = THIS_MODULE,
3926 .presuspend = pool_presuspend,
3927 .presuspend_undo = pool_presuspend_undo,
3928 .postsuspend = pool_postsuspend,
3929 .preresume = pool_preresume,
3930 .resume = pool_resume,
3931 .message = pool_message,
3932 .status = pool_status,
3933 .merge = pool_merge,
3934 .iterate_devices = pool_iterate_devices,
3935 .io_hints = pool_io_hints,
3938 /*----------------------------------------------------------------
3939 * Thin target methods
3940 *--------------------------------------------------------------*/
3941 static void thin_get(struct thin_c *tc)
3943 atomic_inc(&tc->refcount);
3946 static void thin_put(struct thin_c *tc)
3948 if (atomic_dec_and_test(&tc->refcount))
3949 complete(&tc->can_destroy);
3952 static void thin_dtr(struct dm_target *ti)
3954 struct thin_c *tc = ti->private;
3955 unsigned long flags;
3957 spin_lock_irqsave(&tc->pool->lock, flags);
3958 list_del_rcu(&tc->list);
3959 spin_unlock_irqrestore(&tc->pool->lock, flags);
3963 wait_for_completion(&tc->can_destroy);
3965 mutex_lock(&dm_thin_pool_table.mutex);
3967 __pool_dec(tc->pool);
3968 dm_pool_close_thin_device(tc->td);
3969 dm_put_device(ti, tc->pool_dev);
3971 dm_put_device(ti, tc->origin_dev);
3974 mutex_unlock(&dm_thin_pool_table.mutex);
3978 * Thin target parameters:
3980 * <pool_dev> <dev_id> [origin_dev]
3982 * pool_dev: the path to the pool (eg, /dev/mapper/my_pool)
3983 * dev_id: the internal device identifier
3984 * origin_dev: a device external to the pool that should act as the origin
3986 * If the pool device has discards disabled, they get disabled for the thin
3989 static int thin_ctr(struct dm_target *ti, unsigned argc, char **argv)
3993 struct dm_dev *pool_dev, *origin_dev;
3994 struct mapped_device *pool_md;
3995 unsigned long flags;
3997 mutex_lock(&dm_thin_pool_table.mutex);
3999 if (argc != 2 && argc != 3) {
4000 ti->error = "Invalid argument count";
4005 tc = ti->private = kzalloc(sizeof(*tc), GFP_KERNEL);
4007 ti->error = "Out of memory";
4011 tc->thin_md = dm_table_get_md(ti->table);
4012 spin_lock_init(&tc->lock);
4013 INIT_LIST_HEAD(&tc->deferred_cells);
4014 bio_list_init(&tc->deferred_bio_list);
4015 bio_list_init(&tc->retry_on_resume_list);
4016 tc->sort_bio_list = RB_ROOT;
4019 r = dm_get_device(ti, argv[2], FMODE_READ, &origin_dev);
4021 ti->error = "Error opening origin device";
4022 goto bad_origin_dev;
4024 tc->origin_dev = origin_dev;
4027 r = dm_get_device(ti, argv[0], dm_table_get_mode(ti->table), &pool_dev);
4029 ti->error = "Error opening pool device";
4032 tc->pool_dev = pool_dev;
4034 if (read_dev_id(argv[1], (unsigned long long *)&tc->dev_id, 0)) {
4035 ti->error = "Invalid device id";
4040 pool_md = dm_get_md(tc->pool_dev->bdev->bd_dev);
4042 ti->error = "Couldn't get pool mapped device";
4047 tc->pool = __pool_table_lookup(pool_md);
4049 ti->error = "Couldn't find pool object";
4051 goto bad_pool_lookup;
4053 __pool_inc(tc->pool);
4055 if (get_pool_mode(tc->pool) == PM_FAIL) {
4056 ti->error = "Couldn't open thin device, Pool is in fail mode";
4061 r = dm_pool_open_thin_device(tc->pool->pmd, tc->dev_id, &tc->td);
4063 ti->error = "Couldn't open thin internal device";
4067 r = dm_set_target_max_io_len(ti, tc->pool->sectors_per_block);
4071 ti->num_flush_bios = 1;
4072 ti->flush_supported = true;
4073 ti->per_bio_data_size = sizeof(struct dm_thin_endio_hook);
4075 /* In case the pool supports discards, pass them on. */
4076 ti->discard_zeroes_data_unsupported = true;
4077 if (tc->pool->pf.discard_enabled) {
4078 ti->discards_supported = true;
4079 ti->num_discard_bios = 1;
4080 ti->split_discard_bios = false;
4083 mutex_unlock(&dm_thin_pool_table.mutex);
4085 spin_lock_irqsave(&tc->pool->lock, flags);
4086 if (tc->pool->suspended) {
4087 spin_unlock_irqrestore(&tc->pool->lock, flags);
4088 mutex_lock(&dm_thin_pool_table.mutex); /* reacquire for __pool_dec */
4089 ti->error = "Unable to activate thin device while pool is suspended";
4093 atomic_set(&tc->refcount, 1);
4094 init_completion(&tc->can_destroy);
4095 list_add_tail_rcu(&tc->list, &tc->pool->active_thins);
4096 spin_unlock_irqrestore(&tc->pool->lock, flags);
4098 * This synchronize_rcu() call is needed here otherwise we risk a
4099 * wake_worker() call finding no bios to process (because the newly
4100 * added tc isn't yet visible). So this reduces latency since we
4101 * aren't then dependent on the periodic commit to wake_worker().
4110 dm_pool_close_thin_device(tc->td);
4112 __pool_dec(tc->pool);
4116 dm_put_device(ti, tc->pool_dev);
4119 dm_put_device(ti, tc->origin_dev);
4123 mutex_unlock(&dm_thin_pool_table.mutex);
4128 static int thin_map(struct dm_target *ti, struct bio *bio)
4130 bio->bi_iter.bi_sector = dm_target_offset(ti, bio->bi_iter.bi_sector);
4132 return thin_bio_map(ti, bio);
4135 static int thin_endio(struct dm_target *ti, struct bio *bio, int err)
4137 unsigned long flags;
4138 struct dm_thin_endio_hook *h = dm_per_bio_data(bio, sizeof(struct dm_thin_endio_hook));
4139 struct list_head work;
4140 struct dm_thin_new_mapping *m, *tmp;
4141 struct pool *pool = h->tc->pool;
4143 if (h->shared_read_entry) {
4144 INIT_LIST_HEAD(&work);
4145 dm_deferred_entry_dec(h->shared_read_entry, &work);
4147 spin_lock_irqsave(&pool->lock, flags);
4148 list_for_each_entry_safe(m, tmp, &work, list) {
4150 __complete_mapping_preparation(m);
4152 spin_unlock_irqrestore(&pool->lock, flags);
4155 if (h->all_io_entry) {
4156 INIT_LIST_HEAD(&work);
4157 dm_deferred_entry_dec(h->all_io_entry, &work);
4158 if (!list_empty(&work)) {
4159 spin_lock_irqsave(&pool->lock, flags);
4160 list_for_each_entry_safe(m, tmp, &work, list)
4161 list_add_tail(&m->list, &pool->prepared_discards);
4162 spin_unlock_irqrestore(&pool->lock, flags);
4168 cell_defer_no_holder(h->tc, h->cell);
4173 static void thin_presuspend(struct dm_target *ti)
4175 struct thin_c *tc = ti->private;
4177 if (dm_noflush_suspending(ti))
4178 noflush_work(tc, do_noflush_start);
4181 static void thin_postsuspend(struct dm_target *ti)
4183 struct thin_c *tc = ti->private;
4186 * The dm_noflush_suspending flag has been cleared by now, so
4187 * unfortunately we must always run this.
4189 noflush_work(tc, do_noflush_stop);
4192 static int thin_preresume(struct dm_target *ti)
4194 struct thin_c *tc = ti->private;
4197 tc->origin_size = get_dev_size(tc->origin_dev->bdev);
4203 * <nr mapped sectors> <highest mapped sector>
4205 static void thin_status(struct dm_target *ti, status_type_t type,
4206 unsigned status_flags, char *result, unsigned maxlen)
4210 dm_block_t mapped, highest;
4211 char buf[BDEVNAME_SIZE];
4212 struct thin_c *tc = ti->private;
4214 if (get_pool_mode(tc->pool) == PM_FAIL) {
4223 case STATUSTYPE_INFO:
4224 r = dm_thin_get_mapped_count(tc->td, &mapped);
4226 DMERR("dm_thin_get_mapped_count returned %d", r);
4230 r = dm_thin_get_highest_mapped_block(tc->td, &highest);
4232 DMERR("dm_thin_get_highest_mapped_block returned %d", r);
4236 DMEMIT("%llu ", mapped * tc->pool->sectors_per_block);
4238 DMEMIT("%llu", ((highest + 1) *
4239 tc->pool->sectors_per_block) - 1);
4244 case STATUSTYPE_TABLE:
4246 format_dev_t(buf, tc->pool_dev->bdev->bd_dev),
4247 (unsigned long) tc->dev_id);
4249 DMEMIT(" %s", format_dev_t(buf, tc->origin_dev->bdev->bd_dev));
4260 static int thin_merge(struct dm_target *ti, struct bvec_merge_data *bvm,
4261 struct bio_vec *biovec, int max_size)
4263 struct thin_c *tc = ti->private;
4264 struct request_queue *q = bdev_get_queue(tc->pool_dev->bdev);
4266 if (!q->merge_bvec_fn)
4269 bvm->bi_bdev = tc->pool_dev->bdev;
4270 bvm->bi_sector = dm_target_offset(ti, bvm->bi_sector);
4272 return min(max_size, q->merge_bvec_fn(q, bvm, biovec));
4275 static int thin_iterate_devices(struct dm_target *ti,
4276 iterate_devices_callout_fn fn, void *data)
4279 struct thin_c *tc = ti->private;
4280 struct pool *pool = tc->pool;
4283 * We can't call dm_pool_get_data_dev_size() since that blocks. So
4284 * we follow a more convoluted path through to the pool's target.
4287 return 0; /* nothing is bound */
4289 blocks = pool->ti->len;
4290 (void) sector_div(blocks, pool->sectors_per_block);
4292 return fn(ti, tc->pool_dev, 0, pool->sectors_per_block * blocks, data);
4297 static void thin_io_hints(struct dm_target *ti, struct queue_limits *limits)
4299 struct thin_c *tc = ti->private;
4300 struct pool *pool = tc->pool;
4302 limits->discard_granularity = pool->sectors_per_block << SECTOR_SHIFT;
4303 limits->max_discard_sectors = 2048 * 1024 * 16; /* 16G */
4306 static struct target_type thin_target = {
4308 .version = {1, 15, 0},
4309 .module = THIS_MODULE,
4313 .end_io = thin_endio,
4314 .preresume = thin_preresume,
4315 .presuspend = thin_presuspend,
4316 .postsuspend = thin_postsuspend,
4317 .status = thin_status,
4318 .merge = thin_merge,
4319 .iterate_devices = thin_iterate_devices,
4320 .io_hints = thin_io_hints,
4323 /*----------------------------------------------------------------*/
4325 static int __init dm_thin_init(void)
4331 r = dm_register_target(&thin_target);
4335 r = dm_register_target(&pool_target);
4337 goto bad_pool_target;
4341 _new_mapping_cache = KMEM_CACHE(dm_thin_new_mapping, 0);
4342 if (!_new_mapping_cache)
4343 goto bad_new_mapping_cache;
4347 bad_new_mapping_cache:
4348 dm_unregister_target(&pool_target);
4350 dm_unregister_target(&thin_target);
4355 static void dm_thin_exit(void)
4357 dm_unregister_target(&thin_target);
4358 dm_unregister_target(&pool_target);
4360 kmem_cache_destroy(_new_mapping_cache);
4363 module_init(dm_thin_init);
4364 module_exit(dm_thin_exit);
4366 module_param_named(no_space_timeout, no_space_timeout_secs, uint, S_IRUGO | S_IWUSR);
4367 MODULE_PARM_DESC(no_space_timeout, "Out of data space queue IO timeout in seconds");
4369 MODULE_DESCRIPTION(DM_NAME " thin provisioning target");
4370 MODULE_AUTHOR("Joe Thornber <dm-devel@redhat.com>");
4371 MODULE_LICENSE("GPL");