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/vmalloc.h>
22 #include <linux/sort.h>
23 #include <linux/rbtree.h>
25 #define DM_MSG_PREFIX "thin"
30 #define ENDIO_HOOK_POOL_SIZE 1024
31 #define MAPPING_POOL_SIZE 1024
32 #define COMMIT_PERIOD HZ
33 #define NO_SPACE_TIMEOUT_SECS 60
35 static unsigned no_space_timeout_secs = NO_SPACE_TIMEOUT_SECS;
37 DECLARE_DM_KCOPYD_THROTTLE_WITH_MODULE_PARM(snapshot_copy_throttle,
38 "A percentage of time allocated for copy on write");
41 * The block size of the device holding pool data must be
42 * between 64KB and 1GB.
44 #define DATA_DEV_BLOCK_SIZE_MIN_SECTORS (64 * 1024 >> SECTOR_SHIFT)
45 #define DATA_DEV_BLOCK_SIZE_MAX_SECTORS (1024 * 1024 * 1024 >> SECTOR_SHIFT)
48 * Device id is restricted to 24 bits.
50 #define MAX_DEV_ID ((1 << 24) - 1)
53 * How do we handle breaking sharing of data blocks?
54 * =================================================
56 * We use a standard copy-on-write btree to store the mappings for the
57 * devices (note I'm talking about copy-on-write of the metadata here, not
58 * the data). When you take an internal snapshot you clone the root node
59 * of the origin btree. After this there is no concept of an origin or a
60 * snapshot. They are just two device trees that happen to point to the
63 * When we get a write in we decide if it's to a shared data block using
64 * some timestamp magic. If it is, we have to break sharing.
66 * Let's say we write to a shared block in what was the origin. The
69 * i) plug io further to this physical block. (see bio_prison code).
71 * ii) quiesce any read io to that shared data block. Obviously
72 * including all devices that share this block. (see dm_deferred_set code)
74 * iii) copy the data block to a newly allocate block. This step can be
75 * missed out if the io covers the block. (schedule_copy).
77 * iv) insert the new mapping into the origin's btree
78 * (process_prepared_mapping). This act of inserting breaks some
79 * sharing of btree nodes between the two devices. Breaking sharing only
80 * effects the btree of that specific device. Btrees for the other
81 * devices that share the block never change. The btree for the origin
82 * device as it was after the last commit is untouched, ie. we're using
83 * persistent data structures in the functional programming sense.
85 * v) unplug io to this physical block, including the io that triggered
86 * the breaking of sharing.
88 * Steps (ii) and (iii) occur in parallel.
90 * The metadata _doesn't_ need to be committed before the io continues. We
91 * get away with this because the io is always written to a _new_ block.
92 * If there's a crash, then:
94 * - The origin mapping will point to the old origin block (the shared
95 * one). This will contain the data as it was before the io that triggered
96 * the breaking of sharing came in.
98 * - The snap mapping still points to the old block. As it would after
101 * The downside of this scheme is the timestamp magic isn't perfect, and
102 * will continue to think that data block in the snapshot device is shared
103 * even after the write to the origin has broken sharing. I suspect data
104 * blocks will typically be shared by many different devices, so we're
105 * breaking sharing n + 1 times, rather than n, where n is the number of
106 * devices that reference this data block. At the moment I think the
107 * benefits far, far outweigh the disadvantages.
110 /*----------------------------------------------------------------*/
120 static void build_key(struct dm_thin_device *td, enum lock_space ls,
121 dm_block_t b, dm_block_t e, struct dm_cell_key *key)
123 key->virtual = (ls == VIRTUAL);
124 key->dev = dm_thin_dev_id(td);
125 key->block_begin = b;
129 static void build_data_key(struct dm_thin_device *td, dm_block_t b,
130 struct dm_cell_key *key)
132 build_key(td, PHYSICAL, b, b + 1llu, key);
135 static void build_virtual_key(struct dm_thin_device *td, dm_block_t b,
136 struct dm_cell_key *key)
138 build_key(td, VIRTUAL, b, b + 1llu, key);
141 /*----------------------------------------------------------------*/
143 #define THROTTLE_THRESHOLD (1 * HZ)
146 struct rw_semaphore lock;
147 unsigned long threshold;
148 bool throttle_applied;
151 static void throttle_init(struct throttle *t)
153 init_rwsem(&t->lock);
154 t->throttle_applied = false;
157 static void throttle_work_start(struct throttle *t)
159 t->threshold = jiffies + THROTTLE_THRESHOLD;
162 static void throttle_work_update(struct throttle *t)
164 if (!t->throttle_applied && jiffies > t->threshold) {
165 down_write(&t->lock);
166 t->throttle_applied = true;
170 static void throttle_work_complete(struct throttle *t)
172 if (t->throttle_applied) {
173 t->throttle_applied = false;
178 static void throttle_lock(struct throttle *t)
183 static void throttle_unlock(struct throttle *t)
188 /*----------------------------------------------------------------*/
191 * A pool device ties together a metadata device and a data device. It
192 * also provides the interface for creating and destroying internal
195 struct dm_thin_new_mapping;
198 * The pool runs in 4 modes. Ordered in degraded order for comparisons.
201 PM_WRITE, /* metadata may be changed */
202 PM_OUT_OF_DATA_SPACE, /* metadata may be changed, though data may not be allocated */
203 PM_READ_ONLY, /* metadata may not be changed */
204 PM_FAIL, /* all I/O fails */
207 struct pool_features {
210 bool zero_new_blocks:1;
211 bool discard_enabled:1;
212 bool discard_passdown:1;
213 bool error_if_no_space:1;
217 typedef void (*process_bio_fn)(struct thin_c *tc, struct bio *bio);
218 typedef void (*process_cell_fn)(struct thin_c *tc, struct dm_bio_prison_cell *cell);
219 typedef void (*process_mapping_fn)(struct dm_thin_new_mapping *m);
221 #define CELL_SORT_ARRAY_SIZE 8192
224 struct list_head list;
225 struct dm_target *ti; /* Only set if a pool target is bound */
227 struct mapped_device *pool_md;
228 struct block_device *md_dev;
229 struct dm_pool_metadata *pmd;
231 dm_block_t low_water_blocks;
232 uint32_t sectors_per_block;
233 int sectors_per_block_shift;
235 struct pool_features pf;
236 bool low_water_triggered:1; /* A dm event has been sent */
239 struct dm_bio_prison *prison;
240 struct dm_kcopyd_client *copier;
242 struct workqueue_struct *wq;
243 struct throttle throttle;
244 struct work_struct worker;
245 struct delayed_work waker;
246 struct delayed_work no_space_timeout;
248 unsigned long last_commit_jiffies;
252 struct bio_list deferred_flush_bios;
253 struct list_head prepared_mappings;
254 struct list_head prepared_discards;
255 struct list_head active_thins;
257 struct dm_deferred_set *shared_read_ds;
258 struct dm_deferred_set *all_io_ds;
260 struct dm_thin_new_mapping *next_mapping;
261 mempool_t *mapping_pool;
263 process_bio_fn process_bio;
264 process_bio_fn process_discard;
266 process_cell_fn process_cell;
267 process_cell_fn process_discard_cell;
269 process_mapping_fn process_prepared_mapping;
270 process_mapping_fn process_prepared_discard;
272 struct dm_bio_prison_cell **cell_sort_array;
275 static enum pool_mode get_pool_mode(struct pool *pool);
276 static void metadata_operation_failed(struct pool *pool, const char *op, int r);
279 * Target context for a pool.
282 struct dm_target *ti;
284 struct dm_dev *data_dev;
285 struct dm_dev *metadata_dev;
286 struct dm_target_callbacks callbacks;
288 dm_block_t low_water_blocks;
289 struct pool_features requested_pf; /* Features requested during table load */
290 struct pool_features adjusted_pf; /* Features used after adjusting for constituent devices */
294 * Target context for a thin.
297 struct list_head list;
298 struct dm_dev *pool_dev;
299 struct dm_dev *origin_dev;
300 sector_t origin_size;
304 struct dm_thin_device *td;
305 struct mapped_device *thin_md;
309 struct list_head deferred_cells;
310 struct bio_list deferred_bio_list;
311 struct bio_list retry_on_resume_list;
312 struct rb_root sort_bio_list; /* sorted list of deferred bios */
315 * Ensures the thin is not destroyed until the worker has finished
316 * iterating the active_thins list.
319 struct completion can_destroy;
322 /*----------------------------------------------------------------*/
325 * __blkdev_issue_discard_async - queue a discard with async completion
326 * @bdev: blockdev to issue discard for
327 * @sector: start sector
328 * @nr_sects: number of sectors to discard
329 * @gfp_mask: memory allocation flags (for bio_alloc)
330 * @flags: BLKDEV_IFL_* flags to control behaviour
331 * @parent_bio: parent discard bio that all sub discards get chained to
334 * Asynchronously issue a discard request for the sectors in question.
335 * NOTE: this variant of blk-core's blkdev_issue_discard() is a stop-gap
336 * that is being kept local to DM thinp until the block changes to allow
337 * late bio splitting land upstream.
339 static int __blkdev_issue_discard_async(struct block_device *bdev, sector_t sector,
340 sector_t nr_sects, gfp_t gfp_mask, unsigned long flags,
341 struct bio *parent_bio)
343 struct request_queue *q = bdev_get_queue(bdev);
344 int type = REQ_WRITE | REQ_DISCARD;
345 unsigned int max_discard_sectors, granularity;
349 struct blk_plug plug;
354 if (!blk_queue_discard(q))
357 /* Zero-sector (unknown) and one-sector granularities are the same. */
358 granularity = max(q->limits.discard_granularity >> 9, 1U);
359 alignment = (bdev_discard_alignment(bdev) >> 9) % granularity;
362 * Ensure that max_discard_sectors is of the proper
363 * granularity, so that requests stay aligned after a split.
365 max_discard_sectors = min(q->limits.max_discard_sectors, UINT_MAX >> 9);
366 max_discard_sectors -= max_discard_sectors % granularity;
367 if (unlikely(!max_discard_sectors)) {
368 /* Avoid infinite loop below. Being cautious never hurts. */
372 if (flags & BLKDEV_DISCARD_SECURE) {
373 if (!blk_queue_secdiscard(q))
378 blk_start_plug(&plug);
380 unsigned int req_sects;
381 sector_t end_sect, tmp;
384 * Required bio_put occurs in bio_endio thanks to bio_chain below
386 bio = bio_alloc(gfp_mask, 1);
392 req_sects = min_t(sector_t, nr_sects, max_discard_sectors);
395 * If splitting a request, and the next starting sector would be
396 * misaligned, stop the discard at the previous aligned sector.
398 end_sect = sector + req_sects;
400 if (req_sects < nr_sects &&
401 sector_div(tmp, granularity) != alignment) {
402 end_sect = end_sect - alignment;
403 sector_div(end_sect, granularity);
404 end_sect = end_sect * granularity + alignment;
405 req_sects = end_sect - sector;
408 bio_chain(bio, parent_bio);
410 bio->bi_iter.bi_sector = sector;
413 bio->bi_iter.bi_size = req_sects << 9;
414 nr_sects -= req_sects;
417 submit_bio(type, bio);
420 * We can loop for a long time in here, if someone does
421 * full device discards (like mkfs). Be nice and allow
422 * us to schedule out to avoid softlocking if preempt
427 blk_finish_plug(&plug);
432 static bool block_size_is_power_of_two(struct pool *pool)
434 return pool->sectors_per_block_shift >= 0;
437 static sector_t block_to_sectors(struct pool *pool, dm_block_t b)
439 return block_size_is_power_of_two(pool) ?
440 (b << pool->sectors_per_block_shift) :
441 (b * pool->sectors_per_block);
444 static int issue_discard(struct thin_c *tc, dm_block_t data_b, dm_block_t data_e,
445 struct bio *parent_bio)
447 sector_t s = block_to_sectors(tc->pool, data_b);
448 sector_t len = block_to_sectors(tc->pool, data_e - data_b);
450 return __blkdev_issue_discard_async(tc->pool_dev->bdev, s, len,
451 GFP_NOWAIT, 0, parent_bio);
454 /*----------------------------------------------------------------*/
457 * wake_worker() is used when new work is queued and when pool_resume is
458 * ready to continue deferred IO processing.
460 static void wake_worker(struct pool *pool)
462 queue_work(pool->wq, &pool->worker);
465 /*----------------------------------------------------------------*/
467 static int bio_detain(struct pool *pool, struct dm_cell_key *key, struct bio *bio,
468 struct dm_bio_prison_cell **cell_result)
471 struct dm_bio_prison_cell *cell_prealloc;
474 * Allocate a cell from the prison's mempool.
475 * This might block but it can't fail.
477 cell_prealloc = dm_bio_prison_alloc_cell(pool->prison, GFP_NOIO);
479 r = dm_bio_detain(pool->prison, key, bio, cell_prealloc, cell_result);
482 * We reused an old cell; we can get rid of
485 dm_bio_prison_free_cell(pool->prison, cell_prealloc);
490 static void cell_release(struct pool *pool,
491 struct dm_bio_prison_cell *cell,
492 struct bio_list *bios)
494 dm_cell_release(pool->prison, cell, bios);
495 dm_bio_prison_free_cell(pool->prison, cell);
498 static void cell_visit_release(struct pool *pool,
499 void (*fn)(void *, struct dm_bio_prison_cell *),
501 struct dm_bio_prison_cell *cell)
503 dm_cell_visit_release(pool->prison, fn, context, cell);
504 dm_bio_prison_free_cell(pool->prison, cell);
507 static void cell_release_no_holder(struct pool *pool,
508 struct dm_bio_prison_cell *cell,
509 struct bio_list *bios)
511 dm_cell_release_no_holder(pool->prison, cell, bios);
512 dm_bio_prison_free_cell(pool->prison, cell);
515 static void cell_error_with_code(struct pool *pool,
516 struct dm_bio_prison_cell *cell, int error_code)
518 dm_cell_error(pool->prison, cell, error_code);
519 dm_bio_prison_free_cell(pool->prison, cell);
522 static void cell_error(struct pool *pool, struct dm_bio_prison_cell *cell)
524 cell_error_with_code(pool, cell, -EIO);
527 static void cell_success(struct pool *pool, struct dm_bio_prison_cell *cell)
529 cell_error_with_code(pool, cell, 0);
532 static void cell_requeue(struct pool *pool, struct dm_bio_prison_cell *cell)
534 cell_error_with_code(pool, cell, DM_ENDIO_REQUEUE);
537 /*----------------------------------------------------------------*/
540 * A global list of pools that uses a struct mapped_device as a key.
542 static struct dm_thin_pool_table {
544 struct list_head pools;
545 } dm_thin_pool_table;
547 static void pool_table_init(void)
549 mutex_init(&dm_thin_pool_table.mutex);
550 INIT_LIST_HEAD(&dm_thin_pool_table.pools);
553 static void __pool_table_insert(struct pool *pool)
555 BUG_ON(!mutex_is_locked(&dm_thin_pool_table.mutex));
556 list_add(&pool->list, &dm_thin_pool_table.pools);
559 static void __pool_table_remove(struct pool *pool)
561 BUG_ON(!mutex_is_locked(&dm_thin_pool_table.mutex));
562 list_del(&pool->list);
565 static struct pool *__pool_table_lookup(struct mapped_device *md)
567 struct pool *pool = NULL, *tmp;
569 BUG_ON(!mutex_is_locked(&dm_thin_pool_table.mutex));
571 list_for_each_entry(tmp, &dm_thin_pool_table.pools, list) {
572 if (tmp->pool_md == md) {
581 static struct pool *__pool_table_lookup_metadata_dev(struct block_device *md_dev)
583 struct pool *pool = NULL, *tmp;
585 BUG_ON(!mutex_is_locked(&dm_thin_pool_table.mutex));
587 list_for_each_entry(tmp, &dm_thin_pool_table.pools, list) {
588 if (tmp->md_dev == md_dev) {
597 /*----------------------------------------------------------------*/
599 struct dm_thin_endio_hook {
601 struct dm_deferred_entry *shared_read_entry;
602 struct dm_deferred_entry *all_io_entry;
603 struct dm_thin_new_mapping *overwrite_mapping;
604 struct rb_node rb_node;
605 struct dm_bio_prison_cell *cell;
608 static void __merge_bio_list(struct bio_list *bios, struct bio_list *master)
610 bio_list_merge(bios, master);
611 bio_list_init(master);
614 static void error_bio_list(struct bio_list *bios, int error)
618 while ((bio = bio_list_pop(bios)))
619 bio_endio(bio, error);
622 static void error_thin_bio_list(struct thin_c *tc, struct bio_list *master, int error)
624 struct bio_list bios;
627 bio_list_init(&bios);
629 spin_lock_irqsave(&tc->lock, flags);
630 __merge_bio_list(&bios, master);
631 spin_unlock_irqrestore(&tc->lock, flags);
633 error_bio_list(&bios, error);
636 static void requeue_deferred_cells(struct thin_c *tc)
638 struct pool *pool = tc->pool;
640 struct list_head cells;
641 struct dm_bio_prison_cell *cell, *tmp;
643 INIT_LIST_HEAD(&cells);
645 spin_lock_irqsave(&tc->lock, flags);
646 list_splice_init(&tc->deferred_cells, &cells);
647 spin_unlock_irqrestore(&tc->lock, flags);
649 list_for_each_entry_safe(cell, tmp, &cells, user_list)
650 cell_requeue(pool, cell);
653 static void requeue_io(struct thin_c *tc)
655 struct bio_list bios;
658 bio_list_init(&bios);
660 spin_lock_irqsave(&tc->lock, flags);
661 __merge_bio_list(&bios, &tc->deferred_bio_list);
662 __merge_bio_list(&bios, &tc->retry_on_resume_list);
663 spin_unlock_irqrestore(&tc->lock, flags);
665 error_bio_list(&bios, DM_ENDIO_REQUEUE);
666 requeue_deferred_cells(tc);
669 static void error_retry_list_with_code(struct pool *pool, int error)
674 list_for_each_entry_rcu(tc, &pool->active_thins, list)
675 error_thin_bio_list(tc, &tc->retry_on_resume_list, error);
679 static void error_retry_list(struct pool *pool)
681 return error_retry_list_with_code(pool, -EIO);
685 * This section of code contains the logic for processing a thin device's IO.
686 * Much of the code depends on pool object resources (lists, workqueues, etc)
687 * but most is exclusively called from the thin target rather than the thin-pool
691 static dm_block_t get_bio_block(struct thin_c *tc, struct bio *bio)
693 struct pool *pool = tc->pool;
694 sector_t block_nr = bio->bi_iter.bi_sector;
696 if (block_size_is_power_of_two(pool))
697 block_nr >>= pool->sectors_per_block_shift;
699 (void) sector_div(block_nr, pool->sectors_per_block);
705 * Returns the _complete_ blocks that this bio covers.
707 static void get_bio_block_range(struct thin_c *tc, struct bio *bio,
708 dm_block_t *begin, dm_block_t *end)
710 struct pool *pool = tc->pool;
711 sector_t b = bio->bi_iter.bi_sector;
712 sector_t e = b + (bio->bi_iter.bi_size >> SECTOR_SHIFT);
714 b += pool->sectors_per_block - 1ull; /* so we round up */
716 if (block_size_is_power_of_two(pool)) {
717 b >>= pool->sectors_per_block_shift;
718 e >>= pool->sectors_per_block_shift;
720 (void) sector_div(b, pool->sectors_per_block);
721 (void) sector_div(e, pool->sectors_per_block);
725 /* Can happen if the bio is within a single block. */
732 static void remap(struct thin_c *tc, struct bio *bio, dm_block_t block)
734 struct pool *pool = tc->pool;
735 sector_t bi_sector = bio->bi_iter.bi_sector;
737 bio->bi_bdev = tc->pool_dev->bdev;
738 if (block_size_is_power_of_two(pool))
739 bio->bi_iter.bi_sector =
740 (block << pool->sectors_per_block_shift) |
741 (bi_sector & (pool->sectors_per_block - 1));
743 bio->bi_iter.bi_sector = (block * pool->sectors_per_block) +
744 sector_div(bi_sector, pool->sectors_per_block);
747 static void remap_to_origin(struct thin_c *tc, struct bio *bio)
749 bio->bi_bdev = tc->origin_dev->bdev;
752 static int bio_triggers_commit(struct thin_c *tc, struct bio *bio)
754 return (bio->bi_rw & (REQ_FLUSH | REQ_FUA)) &&
755 dm_thin_changed_this_transaction(tc->td);
758 static void inc_all_io_entry(struct pool *pool, struct bio *bio)
760 struct dm_thin_endio_hook *h;
762 if (bio->bi_rw & REQ_DISCARD)
765 h = dm_per_bio_data(bio, sizeof(struct dm_thin_endio_hook));
766 h->all_io_entry = dm_deferred_entry_inc(pool->all_io_ds);
769 static void issue(struct thin_c *tc, struct bio *bio)
771 struct pool *pool = tc->pool;
774 if (!bio_triggers_commit(tc, bio)) {
775 generic_make_request(bio);
780 * Complete bio with an error if earlier I/O caused changes to
781 * the metadata that can't be committed e.g, due to I/O errors
782 * on the metadata device.
784 if (dm_thin_aborted_changes(tc->td)) {
790 * Batch together any bios that trigger commits and then issue a
791 * single commit for them in process_deferred_bios().
793 spin_lock_irqsave(&pool->lock, flags);
794 bio_list_add(&pool->deferred_flush_bios, bio);
795 spin_unlock_irqrestore(&pool->lock, flags);
798 static void remap_to_origin_and_issue(struct thin_c *tc, struct bio *bio)
800 remap_to_origin(tc, bio);
804 static void remap_and_issue(struct thin_c *tc, struct bio *bio,
807 remap(tc, bio, block);
811 /*----------------------------------------------------------------*/
814 * Bio endio functions.
816 struct dm_thin_new_mapping {
817 struct list_head list;
823 * Track quiescing, copying and zeroing preparation actions. When this
824 * counter hits zero the block is prepared and can be inserted into the
827 atomic_t prepare_actions;
831 dm_block_t virt_begin, virt_end;
832 dm_block_t data_block;
833 struct dm_bio_prison_cell *cell;
836 * If the bio covers the whole area of a block then we can avoid
837 * zeroing or copying. Instead this bio is hooked. The bio will
838 * still be in the cell, so care has to be taken to avoid issuing
842 bio_end_io_t *saved_bi_end_io;
845 static void __complete_mapping_preparation(struct dm_thin_new_mapping *m)
847 struct pool *pool = m->tc->pool;
849 if (atomic_dec_and_test(&m->prepare_actions)) {
850 list_add_tail(&m->list, &pool->prepared_mappings);
855 static void complete_mapping_preparation(struct dm_thin_new_mapping *m)
858 struct pool *pool = m->tc->pool;
860 spin_lock_irqsave(&pool->lock, flags);
861 __complete_mapping_preparation(m);
862 spin_unlock_irqrestore(&pool->lock, flags);
865 static void copy_complete(int read_err, unsigned long write_err, void *context)
867 struct dm_thin_new_mapping *m = context;
869 m->err = read_err || write_err ? -EIO : 0;
870 complete_mapping_preparation(m);
873 static void overwrite_endio(struct bio *bio, int err)
875 struct dm_thin_endio_hook *h = dm_per_bio_data(bio, sizeof(struct dm_thin_endio_hook));
876 struct dm_thin_new_mapping *m = h->overwrite_mapping;
878 bio->bi_end_io = m->saved_bi_end_io;
881 complete_mapping_preparation(m);
884 /*----------------------------------------------------------------*/
891 * Prepared mapping jobs.
895 * This sends the bios in the cell, except the original holder, back
896 * to the deferred_bios list.
898 static void cell_defer_no_holder(struct thin_c *tc, struct dm_bio_prison_cell *cell)
900 struct pool *pool = tc->pool;
903 spin_lock_irqsave(&tc->lock, flags);
904 cell_release_no_holder(pool, cell, &tc->deferred_bio_list);
905 spin_unlock_irqrestore(&tc->lock, flags);
910 static void thin_defer_bio(struct thin_c *tc, struct bio *bio);
914 struct bio_list defer_bios;
915 struct bio_list issue_bios;
918 static void __inc_remap_and_issue_cell(void *context,
919 struct dm_bio_prison_cell *cell)
921 struct remap_info *info = context;
924 while ((bio = bio_list_pop(&cell->bios))) {
925 if (bio->bi_rw & (REQ_DISCARD | REQ_FLUSH | REQ_FUA))
926 bio_list_add(&info->defer_bios, bio);
928 inc_all_io_entry(info->tc->pool, bio);
931 * We can't issue the bios with the bio prison lock
932 * held, so we add them to a list to issue on
933 * return from this function.
935 bio_list_add(&info->issue_bios, bio);
940 static void inc_remap_and_issue_cell(struct thin_c *tc,
941 struct dm_bio_prison_cell *cell,
945 struct remap_info info;
948 bio_list_init(&info.defer_bios);
949 bio_list_init(&info.issue_bios);
952 * We have to be careful to inc any bios we're about to issue
953 * before the cell is released, and avoid a race with new bios
954 * being added to the cell.
956 cell_visit_release(tc->pool, __inc_remap_and_issue_cell,
959 while ((bio = bio_list_pop(&info.defer_bios)))
960 thin_defer_bio(tc, bio);
962 while ((bio = bio_list_pop(&info.issue_bios)))
963 remap_and_issue(info.tc, bio, block);
966 static void process_prepared_mapping_fail(struct dm_thin_new_mapping *m)
968 cell_error(m->tc->pool, m->cell);
970 mempool_free(m, m->tc->pool->mapping_pool);
973 static void process_prepared_mapping(struct dm_thin_new_mapping *m)
975 struct thin_c *tc = m->tc;
976 struct pool *pool = tc->pool;
977 struct bio *bio = m->bio;
981 cell_error(pool, m->cell);
986 * Commit the prepared block into the mapping btree.
987 * Any I/O for this block arriving after this point will get
988 * remapped to it directly.
990 r = dm_thin_insert_block(tc->td, m->virt_begin, m->data_block);
992 metadata_operation_failed(pool, "dm_thin_insert_block", r);
993 cell_error(pool, m->cell);
998 * Release any bios held while the block was being provisioned.
999 * If we are processing a write bio that completely covers the block,
1000 * we already processed it so can ignore it now when processing
1001 * the bios in the cell.
1004 inc_remap_and_issue_cell(tc, m->cell, m->data_block);
1007 inc_all_io_entry(tc->pool, m->cell->holder);
1008 remap_and_issue(tc, m->cell->holder, m->data_block);
1009 inc_remap_and_issue_cell(tc, m->cell, m->data_block);
1014 mempool_free(m, pool->mapping_pool);
1017 /*----------------------------------------------------------------*/
1019 static void free_discard_mapping(struct dm_thin_new_mapping *m)
1021 struct thin_c *tc = m->tc;
1023 cell_defer_no_holder(tc, m->cell);
1024 mempool_free(m, tc->pool->mapping_pool);
1027 static void process_prepared_discard_fail(struct dm_thin_new_mapping *m)
1029 bio_io_error(m->bio);
1030 free_discard_mapping(m);
1033 static void process_prepared_discard_success(struct dm_thin_new_mapping *m)
1035 bio_endio(m->bio, 0);
1036 free_discard_mapping(m);
1039 static void process_prepared_discard_no_passdown(struct dm_thin_new_mapping *m)
1042 struct thin_c *tc = m->tc;
1044 r = dm_thin_remove_range(tc->td, m->cell->key.block_begin, m->cell->key.block_end);
1046 metadata_operation_failed(tc->pool, "dm_thin_remove_range", r);
1047 bio_io_error(m->bio);
1049 bio_endio(m->bio, 0);
1051 cell_defer_no_holder(tc, m->cell);
1052 mempool_free(m, tc->pool->mapping_pool);
1055 static int passdown_double_checking_shared_status(struct dm_thin_new_mapping *m)
1058 * We've already unmapped this range of blocks, but before we
1059 * passdown we have to check that these blocks are now unused.
1063 struct thin_c *tc = m->tc;
1064 struct pool *pool = tc->pool;
1065 dm_block_t b = m->data_block, e, end = m->data_block + m->virt_end - m->virt_begin;
1068 /* find start of unmapped run */
1069 for (; b < end; b++) {
1070 r = dm_pool_block_is_used(pool->pmd, b, &used);
1081 /* find end of run */
1082 for (e = b + 1; e != end; e++) {
1083 r = dm_pool_block_is_used(pool->pmd, e, &used);
1091 r = issue_discard(tc, b, e, m->bio);
1101 static void process_prepared_discard_passdown(struct dm_thin_new_mapping *m)
1104 struct thin_c *tc = m->tc;
1105 struct pool *pool = tc->pool;
1107 r = dm_thin_remove_range(tc->td, m->virt_begin, m->virt_end);
1109 metadata_operation_failed(pool, "dm_thin_remove_range", r);
1111 else if (m->maybe_shared)
1112 r = passdown_double_checking_shared_status(m);
1114 r = issue_discard(tc, m->data_block, m->data_block + (m->virt_end - m->virt_begin), m->bio);
1117 * Even if r is set, there could be sub discards in flight that we
1120 bio_endio(m->bio, r);
1121 cell_defer_no_holder(tc, m->cell);
1122 mempool_free(m, pool->mapping_pool);
1125 static void process_prepared(struct pool *pool, struct list_head *head,
1126 process_mapping_fn *fn)
1128 unsigned long flags;
1129 struct list_head maps;
1130 struct dm_thin_new_mapping *m, *tmp;
1132 INIT_LIST_HEAD(&maps);
1133 spin_lock_irqsave(&pool->lock, flags);
1134 list_splice_init(head, &maps);
1135 spin_unlock_irqrestore(&pool->lock, flags);
1137 list_for_each_entry_safe(m, tmp, &maps, list)
1142 * Deferred bio jobs.
1144 static int io_overlaps_block(struct pool *pool, struct bio *bio)
1146 return bio->bi_iter.bi_size ==
1147 (pool->sectors_per_block << SECTOR_SHIFT);
1150 static int io_overwrites_block(struct pool *pool, struct bio *bio)
1152 return (bio_data_dir(bio) == WRITE) &&
1153 io_overlaps_block(pool, bio);
1156 static void save_and_set_endio(struct bio *bio, bio_end_io_t **save,
1159 *save = bio->bi_end_io;
1160 bio->bi_end_io = fn;
1163 static int ensure_next_mapping(struct pool *pool)
1165 if (pool->next_mapping)
1168 pool->next_mapping = mempool_alloc(pool->mapping_pool, GFP_ATOMIC);
1170 return pool->next_mapping ? 0 : -ENOMEM;
1173 static struct dm_thin_new_mapping *get_next_mapping(struct pool *pool)
1175 struct dm_thin_new_mapping *m = pool->next_mapping;
1177 BUG_ON(!pool->next_mapping);
1179 memset(m, 0, sizeof(struct dm_thin_new_mapping));
1180 INIT_LIST_HEAD(&m->list);
1183 pool->next_mapping = NULL;
1188 static void ll_zero(struct thin_c *tc, struct dm_thin_new_mapping *m,
1189 sector_t begin, sector_t end)
1192 struct dm_io_region to;
1194 to.bdev = tc->pool_dev->bdev;
1196 to.count = end - begin;
1198 r = dm_kcopyd_zero(tc->pool->copier, 1, &to, 0, copy_complete, m);
1200 DMERR_LIMIT("dm_kcopyd_zero() failed");
1201 copy_complete(1, 1, m);
1205 static void remap_and_issue_overwrite(struct thin_c *tc, struct bio *bio,
1206 dm_block_t data_begin,
1207 struct dm_thin_new_mapping *m)
1209 struct pool *pool = tc->pool;
1210 struct dm_thin_endio_hook *h = dm_per_bio_data(bio, sizeof(struct dm_thin_endio_hook));
1212 h->overwrite_mapping = m;
1214 save_and_set_endio(bio, &m->saved_bi_end_io, overwrite_endio);
1215 inc_all_io_entry(pool, bio);
1216 remap_and_issue(tc, bio, data_begin);
1220 * A partial copy also needs to zero the uncopied region.
1222 static void schedule_copy(struct thin_c *tc, dm_block_t virt_block,
1223 struct dm_dev *origin, dm_block_t data_origin,
1224 dm_block_t data_dest,
1225 struct dm_bio_prison_cell *cell, struct bio *bio,
1229 struct pool *pool = tc->pool;
1230 struct dm_thin_new_mapping *m = get_next_mapping(pool);
1233 m->virt_begin = virt_block;
1234 m->virt_end = virt_block + 1u;
1235 m->data_block = data_dest;
1239 * quiesce action + copy action + an extra reference held for the
1240 * duration of this function (we may need to inc later for a
1243 atomic_set(&m->prepare_actions, 3);
1245 if (!dm_deferred_set_add_work(pool->shared_read_ds, &m->list))
1246 complete_mapping_preparation(m); /* already quiesced */
1249 * IO to pool_dev remaps to the pool target's data_dev.
1251 * If the whole block of data is being overwritten, we can issue the
1252 * bio immediately. Otherwise we use kcopyd to clone the data first.
1254 if (io_overwrites_block(pool, bio))
1255 remap_and_issue_overwrite(tc, bio, data_dest, m);
1257 struct dm_io_region from, to;
1259 from.bdev = origin->bdev;
1260 from.sector = data_origin * pool->sectors_per_block;
1263 to.bdev = tc->pool_dev->bdev;
1264 to.sector = data_dest * pool->sectors_per_block;
1267 r = dm_kcopyd_copy(pool->copier, &from, 1, &to,
1268 0, copy_complete, m);
1270 DMERR_LIMIT("dm_kcopyd_copy() failed");
1271 copy_complete(1, 1, m);
1274 * We allow the zero to be issued, to simplify the
1275 * error path. Otherwise we'd need to start
1276 * worrying about decrementing the prepare_actions
1282 * Do we need to zero a tail region?
1284 if (len < pool->sectors_per_block && pool->pf.zero_new_blocks) {
1285 atomic_inc(&m->prepare_actions);
1287 data_dest * pool->sectors_per_block + len,
1288 (data_dest + 1) * pool->sectors_per_block);
1292 complete_mapping_preparation(m); /* drop our ref */
1295 static void schedule_internal_copy(struct thin_c *tc, dm_block_t virt_block,
1296 dm_block_t data_origin, dm_block_t data_dest,
1297 struct dm_bio_prison_cell *cell, struct bio *bio)
1299 schedule_copy(tc, virt_block, tc->pool_dev,
1300 data_origin, data_dest, cell, bio,
1301 tc->pool->sectors_per_block);
1304 static void schedule_zero(struct thin_c *tc, dm_block_t virt_block,
1305 dm_block_t data_block, struct dm_bio_prison_cell *cell,
1308 struct pool *pool = tc->pool;
1309 struct dm_thin_new_mapping *m = get_next_mapping(pool);
1311 atomic_set(&m->prepare_actions, 1); /* no need to quiesce */
1313 m->virt_begin = virt_block;
1314 m->virt_end = virt_block + 1u;
1315 m->data_block = data_block;
1319 * If the whole block of data is being overwritten or we are not
1320 * zeroing pre-existing data, we can issue the bio immediately.
1321 * Otherwise we use kcopyd to zero the data first.
1323 if (pool->pf.zero_new_blocks) {
1324 if (io_overwrites_block(pool, bio))
1325 remap_and_issue_overwrite(tc, bio, data_block, m);
1327 ll_zero(tc, m, data_block * pool->sectors_per_block,
1328 (data_block + 1) * pool->sectors_per_block);
1330 process_prepared_mapping(m);
1333 static void schedule_external_copy(struct thin_c *tc, dm_block_t virt_block,
1334 dm_block_t data_dest,
1335 struct dm_bio_prison_cell *cell, struct bio *bio)
1337 struct pool *pool = tc->pool;
1338 sector_t virt_block_begin = virt_block * pool->sectors_per_block;
1339 sector_t virt_block_end = (virt_block + 1) * pool->sectors_per_block;
1341 if (virt_block_end <= tc->origin_size)
1342 schedule_copy(tc, virt_block, tc->origin_dev,
1343 virt_block, data_dest, cell, bio,
1344 pool->sectors_per_block);
1346 else if (virt_block_begin < tc->origin_size)
1347 schedule_copy(tc, virt_block, tc->origin_dev,
1348 virt_block, data_dest, cell, bio,
1349 tc->origin_size - virt_block_begin);
1352 schedule_zero(tc, virt_block, data_dest, cell, bio);
1355 static void set_pool_mode(struct pool *pool, enum pool_mode new_mode);
1357 static void check_for_space(struct pool *pool)
1362 if (get_pool_mode(pool) != PM_OUT_OF_DATA_SPACE)
1365 r = dm_pool_get_free_block_count(pool->pmd, &nr_free);
1370 set_pool_mode(pool, PM_WRITE);
1374 * A non-zero return indicates read_only or fail_io mode.
1375 * Many callers don't care about the return value.
1377 static int commit(struct pool *pool)
1381 if (get_pool_mode(pool) >= PM_READ_ONLY)
1384 r = dm_pool_commit_metadata(pool->pmd);
1386 metadata_operation_failed(pool, "dm_pool_commit_metadata", r);
1388 check_for_space(pool);
1393 static void check_low_water_mark(struct pool *pool, dm_block_t free_blocks)
1395 unsigned long flags;
1397 if (free_blocks <= pool->low_water_blocks && !pool->low_water_triggered) {
1398 DMWARN("%s: reached low water mark for data device: sending event.",
1399 dm_device_name(pool->pool_md));
1400 spin_lock_irqsave(&pool->lock, flags);
1401 pool->low_water_triggered = true;
1402 spin_unlock_irqrestore(&pool->lock, flags);
1403 dm_table_event(pool->ti->table);
1407 static int alloc_data_block(struct thin_c *tc, dm_block_t *result)
1410 dm_block_t free_blocks;
1411 struct pool *pool = tc->pool;
1413 if (WARN_ON(get_pool_mode(pool) != PM_WRITE))
1416 r = dm_pool_get_free_block_count(pool->pmd, &free_blocks);
1418 metadata_operation_failed(pool, "dm_pool_get_free_block_count", r);
1422 check_low_water_mark(pool, free_blocks);
1426 * Try to commit to see if that will free up some
1433 r = dm_pool_get_free_block_count(pool->pmd, &free_blocks);
1435 metadata_operation_failed(pool, "dm_pool_get_free_block_count", r);
1440 set_pool_mode(pool, PM_OUT_OF_DATA_SPACE);
1445 r = dm_pool_alloc_data_block(pool->pmd, result);
1447 metadata_operation_failed(pool, "dm_pool_alloc_data_block", r);
1455 * If we have run out of space, queue bios until the device is
1456 * resumed, presumably after having been reloaded with more space.
1458 static void retry_on_resume(struct bio *bio)
1460 struct dm_thin_endio_hook *h = dm_per_bio_data(bio, sizeof(struct dm_thin_endio_hook));
1461 struct thin_c *tc = h->tc;
1462 unsigned long flags;
1464 spin_lock_irqsave(&tc->lock, flags);
1465 bio_list_add(&tc->retry_on_resume_list, bio);
1466 spin_unlock_irqrestore(&tc->lock, flags);
1469 static int should_error_unserviceable_bio(struct pool *pool)
1471 enum pool_mode m = get_pool_mode(pool);
1475 /* Shouldn't get here */
1476 DMERR_LIMIT("bio unserviceable, yet pool is in PM_WRITE mode");
1479 case PM_OUT_OF_DATA_SPACE:
1480 return pool->pf.error_if_no_space ? -ENOSPC : 0;
1486 /* Shouldn't get here */
1487 DMERR_LIMIT("bio unserviceable, yet pool has an unknown mode");
1492 static void handle_unserviceable_bio(struct pool *pool, struct bio *bio)
1494 int error = should_error_unserviceable_bio(pool);
1497 bio_endio(bio, error);
1499 retry_on_resume(bio);
1502 static void retry_bios_on_resume(struct pool *pool, struct dm_bio_prison_cell *cell)
1505 struct bio_list bios;
1508 error = should_error_unserviceable_bio(pool);
1510 cell_error_with_code(pool, cell, error);
1514 bio_list_init(&bios);
1515 cell_release(pool, cell, &bios);
1517 while ((bio = bio_list_pop(&bios)))
1518 retry_on_resume(bio);
1521 static void process_discard_cell_no_passdown(struct thin_c *tc,
1522 struct dm_bio_prison_cell *virt_cell)
1524 struct pool *pool = tc->pool;
1525 struct dm_thin_new_mapping *m = get_next_mapping(pool);
1528 * We don't need to lock the data blocks, since there's no
1529 * passdown. We only lock data blocks for allocation and breaking sharing.
1532 m->virt_begin = virt_cell->key.block_begin;
1533 m->virt_end = virt_cell->key.block_end;
1534 m->cell = virt_cell;
1535 m->bio = virt_cell->holder;
1537 if (!dm_deferred_set_add_work(pool->all_io_ds, &m->list))
1538 pool->process_prepared_discard(m);
1542 * FIXME: DM local hack to defer parent bios's end_io until we
1543 * _know_ all chained sub range discard bios have completed.
1544 * Will go away once late bio splitting lands upstream!
1546 static inline void __bio_inc_remaining(struct bio *bio)
1548 bio->bi_flags |= (1 << BIO_CHAIN);
1549 smp_mb__before_atomic();
1550 atomic_inc(&bio->__bi_remaining);
1553 static void break_up_discard_bio(struct thin_c *tc, dm_block_t begin, dm_block_t end,
1556 struct pool *pool = tc->pool;
1560 struct dm_cell_key data_key;
1561 struct dm_bio_prison_cell *data_cell;
1562 struct dm_thin_new_mapping *m;
1563 dm_block_t virt_begin, virt_end, data_begin;
1565 while (begin != end) {
1566 r = ensure_next_mapping(pool);
1568 /* we did our best */
1571 r = dm_thin_find_mapped_range(tc->td, begin, end, &virt_begin, &virt_end,
1572 &data_begin, &maybe_shared);
1575 * Silently fail, letting any mappings we've
1580 build_key(tc->td, PHYSICAL, data_begin, data_begin + (virt_end - virt_begin), &data_key);
1581 if (bio_detain(tc->pool, &data_key, NULL, &data_cell)) {
1582 /* contention, we'll give up with this range */
1588 * IO may still be going to the destination block. We must
1589 * quiesce before we can do the removal.
1591 m = get_next_mapping(pool);
1593 m->maybe_shared = maybe_shared;
1594 m->virt_begin = virt_begin;
1595 m->virt_end = virt_end;
1596 m->data_block = data_begin;
1597 m->cell = data_cell;
1601 * The parent bio must not complete before sub discard bios are
1602 * chained to it (see __blkdev_issue_discard_async's bio_chain)!
1604 * This per-mapping bi_remaining increment is paired with
1605 * the implicit decrement that occurs via bio_endio() in
1606 * process_prepared_discard_{passdown,no_passdown}.
1608 __bio_inc_remaining(bio);
1609 if (!dm_deferred_set_add_work(pool->all_io_ds, &m->list))
1610 pool->process_prepared_discard(m);
1616 static void process_discard_cell_passdown(struct thin_c *tc, struct dm_bio_prison_cell *virt_cell)
1618 struct bio *bio = virt_cell->holder;
1619 struct dm_thin_endio_hook *h = dm_per_bio_data(bio, sizeof(struct dm_thin_endio_hook));
1622 * The virt_cell will only get freed once the origin bio completes.
1623 * This means it will remain locked while all the individual
1624 * passdown bios are in flight.
1626 h->cell = virt_cell;
1627 break_up_discard_bio(tc, virt_cell->key.block_begin, virt_cell->key.block_end, bio);
1630 * We complete the bio now, knowing that the bi_remaining field
1631 * will prevent completion until the sub range discards have
1637 static void process_discard_bio(struct thin_c *tc, struct bio *bio)
1639 dm_block_t begin, end;
1640 struct dm_cell_key virt_key;
1641 struct dm_bio_prison_cell *virt_cell;
1643 get_bio_block_range(tc, bio, &begin, &end);
1646 * The discard covers less than a block.
1652 build_key(tc->td, VIRTUAL, begin, end, &virt_key);
1653 if (bio_detain(tc->pool, &virt_key, bio, &virt_cell))
1655 * Potential starvation issue: We're relying on the
1656 * fs/application being well behaved, and not trying to
1657 * send IO to a region at the same time as discarding it.
1658 * If they do this persistently then it's possible this
1659 * cell will never be granted.
1663 tc->pool->process_discard_cell(tc, virt_cell);
1666 static void break_sharing(struct thin_c *tc, struct bio *bio, dm_block_t block,
1667 struct dm_cell_key *key,
1668 struct dm_thin_lookup_result *lookup_result,
1669 struct dm_bio_prison_cell *cell)
1672 dm_block_t data_block;
1673 struct pool *pool = tc->pool;
1675 r = alloc_data_block(tc, &data_block);
1678 schedule_internal_copy(tc, block, lookup_result->block,
1679 data_block, cell, bio);
1683 retry_bios_on_resume(pool, cell);
1687 DMERR_LIMIT("%s: alloc_data_block() failed: error = %d",
1689 cell_error(pool, cell);
1694 static void __remap_and_issue_shared_cell(void *context,
1695 struct dm_bio_prison_cell *cell)
1697 struct remap_info *info = context;
1700 while ((bio = bio_list_pop(&cell->bios))) {
1701 if ((bio_data_dir(bio) == WRITE) ||
1702 (bio->bi_rw & (REQ_DISCARD | REQ_FLUSH | REQ_FUA)))
1703 bio_list_add(&info->defer_bios, bio);
1705 struct dm_thin_endio_hook *h = dm_per_bio_data(bio, sizeof(struct dm_thin_endio_hook));;
1707 h->shared_read_entry = dm_deferred_entry_inc(info->tc->pool->shared_read_ds);
1708 inc_all_io_entry(info->tc->pool, bio);
1709 bio_list_add(&info->issue_bios, bio);
1714 static void remap_and_issue_shared_cell(struct thin_c *tc,
1715 struct dm_bio_prison_cell *cell,
1719 struct remap_info info;
1722 bio_list_init(&info.defer_bios);
1723 bio_list_init(&info.issue_bios);
1725 cell_visit_release(tc->pool, __remap_and_issue_shared_cell,
1728 while ((bio = bio_list_pop(&info.defer_bios)))
1729 thin_defer_bio(tc, bio);
1731 while ((bio = bio_list_pop(&info.issue_bios)))
1732 remap_and_issue(tc, bio, block);
1735 static void process_shared_bio(struct thin_c *tc, struct bio *bio,
1737 struct dm_thin_lookup_result *lookup_result,
1738 struct dm_bio_prison_cell *virt_cell)
1740 struct dm_bio_prison_cell *data_cell;
1741 struct pool *pool = tc->pool;
1742 struct dm_cell_key key;
1745 * If cell is already occupied, then sharing is already in the process
1746 * of being broken so we have nothing further to do here.
1748 build_data_key(tc->td, lookup_result->block, &key);
1749 if (bio_detain(pool, &key, bio, &data_cell)) {
1750 cell_defer_no_holder(tc, virt_cell);
1754 if (bio_data_dir(bio) == WRITE && bio->bi_iter.bi_size) {
1755 break_sharing(tc, bio, block, &key, lookup_result, data_cell);
1756 cell_defer_no_holder(tc, virt_cell);
1758 struct dm_thin_endio_hook *h = dm_per_bio_data(bio, sizeof(struct dm_thin_endio_hook));
1760 h->shared_read_entry = dm_deferred_entry_inc(pool->shared_read_ds);
1761 inc_all_io_entry(pool, bio);
1762 remap_and_issue(tc, bio, lookup_result->block);
1764 remap_and_issue_shared_cell(tc, data_cell, lookup_result->block);
1765 remap_and_issue_shared_cell(tc, virt_cell, lookup_result->block);
1769 static void provision_block(struct thin_c *tc, struct bio *bio, dm_block_t block,
1770 struct dm_bio_prison_cell *cell)
1773 dm_block_t data_block;
1774 struct pool *pool = tc->pool;
1777 * Remap empty bios (flushes) immediately, without provisioning.
1779 if (!bio->bi_iter.bi_size) {
1780 inc_all_io_entry(pool, bio);
1781 cell_defer_no_holder(tc, cell);
1783 remap_and_issue(tc, bio, 0);
1788 * Fill read bios with zeroes and complete them immediately.
1790 if (bio_data_dir(bio) == READ) {
1792 cell_defer_no_holder(tc, cell);
1797 r = alloc_data_block(tc, &data_block);
1801 schedule_external_copy(tc, block, data_block, cell, bio);
1803 schedule_zero(tc, block, data_block, cell, bio);
1807 retry_bios_on_resume(pool, cell);
1811 DMERR_LIMIT("%s: alloc_data_block() failed: error = %d",
1813 cell_error(pool, cell);
1818 static void process_cell(struct thin_c *tc, struct dm_bio_prison_cell *cell)
1821 struct pool *pool = tc->pool;
1822 struct bio *bio = cell->holder;
1823 dm_block_t block = get_bio_block(tc, bio);
1824 struct dm_thin_lookup_result lookup_result;
1826 if (tc->requeue_mode) {
1827 cell_requeue(pool, cell);
1831 r = dm_thin_find_block(tc->td, block, 1, &lookup_result);
1834 if (lookup_result.shared)
1835 process_shared_bio(tc, bio, block, &lookup_result, cell);
1837 inc_all_io_entry(pool, bio);
1838 remap_and_issue(tc, bio, lookup_result.block);
1839 inc_remap_and_issue_cell(tc, cell, lookup_result.block);
1844 if (bio_data_dir(bio) == READ && tc->origin_dev) {
1845 inc_all_io_entry(pool, bio);
1846 cell_defer_no_holder(tc, cell);
1848 if (bio_end_sector(bio) <= tc->origin_size)
1849 remap_to_origin_and_issue(tc, bio);
1851 else if (bio->bi_iter.bi_sector < tc->origin_size) {
1853 bio->bi_iter.bi_size = (tc->origin_size - bio->bi_iter.bi_sector) << SECTOR_SHIFT;
1854 remap_to_origin_and_issue(tc, bio);
1861 provision_block(tc, bio, block, cell);
1865 DMERR_LIMIT("%s: dm_thin_find_block() failed: error = %d",
1867 cell_defer_no_holder(tc, cell);
1873 static void process_bio(struct thin_c *tc, struct bio *bio)
1875 struct pool *pool = tc->pool;
1876 dm_block_t block = get_bio_block(tc, bio);
1877 struct dm_bio_prison_cell *cell;
1878 struct dm_cell_key key;
1881 * If cell is already occupied, then the block is already
1882 * being provisioned so we have nothing further to do here.
1884 build_virtual_key(tc->td, block, &key);
1885 if (bio_detain(pool, &key, bio, &cell))
1888 process_cell(tc, cell);
1891 static void __process_bio_read_only(struct thin_c *tc, struct bio *bio,
1892 struct dm_bio_prison_cell *cell)
1895 int rw = bio_data_dir(bio);
1896 dm_block_t block = get_bio_block(tc, bio);
1897 struct dm_thin_lookup_result lookup_result;
1899 r = dm_thin_find_block(tc->td, block, 1, &lookup_result);
1902 if (lookup_result.shared && (rw == WRITE) && bio->bi_iter.bi_size) {
1903 handle_unserviceable_bio(tc->pool, bio);
1905 cell_defer_no_holder(tc, cell);
1907 inc_all_io_entry(tc->pool, bio);
1908 remap_and_issue(tc, bio, lookup_result.block);
1910 inc_remap_and_issue_cell(tc, cell, lookup_result.block);
1916 cell_defer_no_holder(tc, cell);
1918 handle_unserviceable_bio(tc->pool, bio);
1922 if (tc->origin_dev) {
1923 inc_all_io_entry(tc->pool, bio);
1924 remap_to_origin_and_issue(tc, bio);
1933 DMERR_LIMIT("%s: dm_thin_find_block() failed: error = %d",
1936 cell_defer_no_holder(tc, cell);
1942 static void process_bio_read_only(struct thin_c *tc, struct bio *bio)
1944 __process_bio_read_only(tc, bio, NULL);
1947 static void process_cell_read_only(struct thin_c *tc, struct dm_bio_prison_cell *cell)
1949 __process_bio_read_only(tc, cell->holder, cell);
1952 static void process_bio_success(struct thin_c *tc, struct bio *bio)
1957 static void process_bio_fail(struct thin_c *tc, struct bio *bio)
1962 static void process_cell_success(struct thin_c *tc, struct dm_bio_prison_cell *cell)
1964 cell_success(tc->pool, cell);
1967 static void process_cell_fail(struct thin_c *tc, struct dm_bio_prison_cell *cell)
1969 cell_error(tc->pool, cell);
1973 * FIXME: should we also commit due to size of transaction, measured in
1976 static int need_commit_due_to_time(struct pool *pool)
1978 return !time_in_range(jiffies, pool->last_commit_jiffies,
1979 pool->last_commit_jiffies + COMMIT_PERIOD);
1982 #define thin_pbd(node) rb_entry((node), struct dm_thin_endio_hook, rb_node)
1983 #define thin_bio(pbd) dm_bio_from_per_bio_data((pbd), sizeof(struct dm_thin_endio_hook))
1985 static void __thin_bio_rb_add(struct thin_c *tc, struct bio *bio)
1987 struct rb_node **rbp, *parent;
1988 struct dm_thin_endio_hook *pbd;
1989 sector_t bi_sector = bio->bi_iter.bi_sector;
1991 rbp = &tc->sort_bio_list.rb_node;
1995 pbd = thin_pbd(parent);
1997 if (bi_sector < thin_bio(pbd)->bi_iter.bi_sector)
1998 rbp = &(*rbp)->rb_left;
2000 rbp = &(*rbp)->rb_right;
2003 pbd = dm_per_bio_data(bio, sizeof(struct dm_thin_endio_hook));
2004 rb_link_node(&pbd->rb_node, parent, rbp);
2005 rb_insert_color(&pbd->rb_node, &tc->sort_bio_list);
2008 static void __extract_sorted_bios(struct thin_c *tc)
2010 struct rb_node *node;
2011 struct dm_thin_endio_hook *pbd;
2014 for (node = rb_first(&tc->sort_bio_list); node; node = rb_next(node)) {
2015 pbd = thin_pbd(node);
2016 bio = thin_bio(pbd);
2018 bio_list_add(&tc->deferred_bio_list, bio);
2019 rb_erase(&pbd->rb_node, &tc->sort_bio_list);
2022 WARN_ON(!RB_EMPTY_ROOT(&tc->sort_bio_list));
2025 static void __sort_thin_deferred_bios(struct thin_c *tc)
2028 struct bio_list bios;
2030 bio_list_init(&bios);
2031 bio_list_merge(&bios, &tc->deferred_bio_list);
2032 bio_list_init(&tc->deferred_bio_list);
2034 /* Sort deferred_bio_list using rb-tree */
2035 while ((bio = bio_list_pop(&bios)))
2036 __thin_bio_rb_add(tc, bio);
2039 * Transfer the sorted bios in sort_bio_list back to
2040 * deferred_bio_list to allow lockless submission of
2043 __extract_sorted_bios(tc);
2046 static void process_thin_deferred_bios(struct thin_c *tc)
2048 struct pool *pool = tc->pool;
2049 unsigned long flags;
2051 struct bio_list bios;
2052 struct blk_plug plug;
2055 if (tc->requeue_mode) {
2056 error_thin_bio_list(tc, &tc->deferred_bio_list, DM_ENDIO_REQUEUE);
2060 bio_list_init(&bios);
2062 spin_lock_irqsave(&tc->lock, flags);
2064 if (bio_list_empty(&tc->deferred_bio_list)) {
2065 spin_unlock_irqrestore(&tc->lock, flags);
2069 __sort_thin_deferred_bios(tc);
2071 bio_list_merge(&bios, &tc->deferred_bio_list);
2072 bio_list_init(&tc->deferred_bio_list);
2074 spin_unlock_irqrestore(&tc->lock, flags);
2076 blk_start_plug(&plug);
2077 while ((bio = bio_list_pop(&bios))) {
2079 * If we've got no free new_mapping structs, and processing
2080 * this bio might require one, we pause until there are some
2081 * prepared mappings to process.
2083 if (ensure_next_mapping(pool)) {
2084 spin_lock_irqsave(&tc->lock, flags);
2085 bio_list_add(&tc->deferred_bio_list, bio);
2086 bio_list_merge(&tc->deferred_bio_list, &bios);
2087 spin_unlock_irqrestore(&tc->lock, flags);
2091 if (bio->bi_rw & REQ_DISCARD)
2092 pool->process_discard(tc, bio);
2094 pool->process_bio(tc, bio);
2096 if ((count++ & 127) == 0) {
2097 throttle_work_update(&pool->throttle);
2098 dm_pool_issue_prefetches(pool->pmd);
2101 blk_finish_plug(&plug);
2104 static int cmp_cells(const void *lhs, const void *rhs)
2106 struct dm_bio_prison_cell *lhs_cell = *((struct dm_bio_prison_cell **) lhs);
2107 struct dm_bio_prison_cell *rhs_cell = *((struct dm_bio_prison_cell **) rhs);
2109 BUG_ON(!lhs_cell->holder);
2110 BUG_ON(!rhs_cell->holder);
2112 if (lhs_cell->holder->bi_iter.bi_sector < rhs_cell->holder->bi_iter.bi_sector)
2115 if (lhs_cell->holder->bi_iter.bi_sector > rhs_cell->holder->bi_iter.bi_sector)
2121 static unsigned sort_cells(struct pool *pool, struct list_head *cells)
2124 struct dm_bio_prison_cell *cell, *tmp;
2126 list_for_each_entry_safe(cell, tmp, cells, user_list) {
2127 if (count >= CELL_SORT_ARRAY_SIZE)
2130 pool->cell_sort_array[count++] = cell;
2131 list_del(&cell->user_list);
2134 sort(pool->cell_sort_array, count, sizeof(cell), cmp_cells, NULL);
2139 static void process_thin_deferred_cells(struct thin_c *tc)
2141 struct pool *pool = tc->pool;
2142 unsigned long flags;
2143 struct list_head cells;
2144 struct dm_bio_prison_cell *cell;
2145 unsigned i, j, count;
2147 INIT_LIST_HEAD(&cells);
2149 spin_lock_irqsave(&tc->lock, flags);
2150 list_splice_init(&tc->deferred_cells, &cells);
2151 spin_unlock_irqrestore(&tc->lock, flags);
2153 if (list_empty(&cells))
2157 count = sort_cells(tc->pool, &cells);
2159 for (i = 0; i < count; i++) {
2160 cell = pool->cell_sort_array[i];
2161 BUG_ON(!cell->holder);
2164 * If we've got no free new_mapping structs, and processing
2165 * this bio might require one, we pause until there are some
2166 * prepared mappings to process.
2168 if (ensure_next_mapping(pool)) {
2169 for (j = i; j < count; j++)
2170 list_add(&pool->cell_sort_array[j]->user_list, &cells);
2172 spin_lock_irqsave(&tc->lock, flags);
2173 list_splice(&cells, &tc->deferred_cells);
2174 spin_unlock_irqrestore(&tc->lock, flags);
2178 if (cell->holder->bi_rw & REQ_DISCARD)
2179 pool->process_discard_cell(tc, cell);
2181 pool->process_cell(tc, cell);
2183 } while (!list_empty(&cells));
2186 static void thin_get(struct thin_c *tc);
2187 static void thin_put(struct thin_c *tc);
2190 * We can't hold rcu_read_lock() around code that can block. So we
2191 * find a thin with the rcu lock held; bump a refcount; then drop
2194 static struct thin_c *get_first_thin(struct pool *pool)
2196 struct thin_c *tc = NULL;
2199 if (!list_empty(&pool->active_thins)) {
2200 tc = list_entry_rcu(pool->active_thins.next, struct thin_c, list);
2208 static struct thin_c *get_next_thin(struct pool *pool, struct thin_c *tc)
2210 struct thin_c *old_tc = tc;
2213 list_for_each_entry_continue_rcu(tc, &pool->active_thins, list) {
2225 static void process_deferred_bios(struct pool *pool)
2227 unsigned long flags;
2229 struct bio_list bios;
2232 tc = get_first_thin(pool);
2234 process_thin_deferred_cells(tc);
2235 process_thin_deferred_bios(tc);
2236 tc = get_next_thin(pool, tc);
2240 * If there are any deferred flush bios, we must commit
2241 * the metadata before issuing them.
2243 bio_list_init(&bios);
2244 spin_lock_irqsave(&pool->lock, flags);
2245 bio_list_merge(&bios, &pool->deferred_flush_bios);
2246 bio_list_init(&pool->deferred_flush_bios);
2247 spin_unlock_irqrestore(&pool->lock, flags);
2249 if (bio_list_empty(&bios) &&
2250 !(dm_pool_changed_this_transaction(pool->pmd) && need_commit_due_to_time(pool)))
2254 while ((bio = bio_list_pop(&bios)))
2258 pool->last_commit_jiffies = jiffies;
2260 while ((bio = bio_list_pop(&bios)))
2261 generic_make_request(bio);
2264 static void do_worker(struct work_struct *ws)
2266 struct pool *pool = container_of(ws, struct pool, worker);
2268 throttle_work_start(&pool->throttle);
2269 dm_pool_issue_prefetches(pool->pmd);
2270 throttle_work_update(&pool->throttle);
2271 process_prepared(pool, &pool->prepared_mappings, &pool->process_prepared_mapping);
2272 throttle_work_update(&pool->throttle);
2273 process_prepared(pool, &pool->prepared_discards, &pool->process_prepared_discard);
2274 throttle_work_update(&pool->throttle);
2275 process_deferred_bios(pool);
2276 throttle_work_complete(&pool->throttle);
2280 * We want to commit periodically so that not too much
2281 * unwritten data builds up.
2283 static void do_waker(struct work_struct *ws)
2285 struct pool *pool = container_of(to_delayed_work(ws), struct pool, waker);
2287 queue_delayed_work(pool->wq, &pool->waker, COMMIT_PERIOD);
2290 static void notify_of_pool_mode_change_to_oods(struct pool *pool);
2293 * We're holding onto IO to allow userland time to react. After the
2294 * timeout either the pool will have been resized (and thus back in
2295 * PM_WRITE mode), or we degrade to PM_OUT_OF_DATA_SPACE w/ error_if_no_space.
2297 static void do_no_space_timeout(struct work_struct *ws)
2299 struct pool *pool = container_of(to_delayed_work(ws), struct pool,
2302 if (get_pool_mode(pool) == PM_OUT_OF_DATA_SPACE && !pool->pf.error_if_no_space) {
2303 pool->pf.error_if_no_space = true;
2304 notify_of_pool_mode_change_to_oods(pool);
2305 error_retry_list_with_code(pool, -ENOSPC);
2309 /*----------------------------------------------------------------*/
2312 struct work_struct worker;
2313 struct completion complete;
2316 static struct pool_work *to_pool_work(struct work_struct *ws)
2318 return container_of(ws, struct pool_work, worker);
2321 static void pool_work_complete(struct pool_work *pw)
2323 complete(&pw->complete);
2326 static void pool_work_wait(struct pool_work *pw, struct pool *pool,
2327 void (*fn)(struct work_struct *))
2329 INIT_WORK_ONSTACK(&pw->worker, fn);
2330 init_completion(&pw->complete);
2331 queue_work(pool->wq, &pw->worker);
2332 wait_for_completion(&pw->complete);
2335 /*----------------------------------------------------------------*/
2337 struct noflush_work {
2338 struct pool_work pw;
2342 static struct noflush_work *to_noflush(struct work_struct *ws)
2344 return container_of(to_pool_work(ws), struct noflush_work, pw);
2347 static void do_noflush_start(struct work_struct *ws)
2349 struct noflush_work *w = to_noflush(ws);
2350 w->tc->requeue_mode = true;
2352 pool_work_complete(&w->pw);
2355 static void do_noflush_stop(struct work_struct *ws)
2357 struct noflush_work *w = to_noflush(ws);
2358 w->tc->requeue_mode = false;
2359 pool_work_complete(&w->pw);
2362 static void noflush_work(struct thin_c *tc, void (*fn)(struct work_struct *))
2364 struct noflush_work w;
2367 pool_work_wait(&w.pw, tc->pool, fn);
2370 /*----------------------------------------------------------------*/
2372 static enum pool_mode get_pool_mode(struct pool *pool)
2374 return pool->pf.mode;
2377 static void notify_of_pool_mode_change(struct pool *pool, const char *new_mode)
2379 dm_table_event(pool->ti->table);
2380 DMINFO("%s: switching pool to %s mode",
2381 dm_device_name(pool->pool_md), new_mode);
2384 static void notify_of_pool_mode_change_to_oods(struct pool *pool)
2386 if (!pool->pf.error_if_no_space)
2387 notify_of_pool_mode_change(pool, "out-of-data-space (queue IO)");
2389 notify_of_pool_mode_change(pool, "out-of-data-space (error IO)");
2392 static bool passdown_enabled(struct pool_c *pt)
2394 return pt->adjusted_pf.discard_passdown;
2397 static void set_discard_callbacks(struct pool *pool)
2399 struct pool_c *pt = pool->ti->private;
2401 if (passdown_enabled(pt)) {
2402 pool->process_discard_cell = process_discard_cell_passdown;
2403 pool->process_prepared_discard = process_prepared_discard_passdown;
2405 pool->process_discard_cell = process_discard_cell_no_passdown;
2406 pool->process_prepared_discard = process_prepared_discard_no_passdown;
2410 static void set_pool_mode(struct pool *pool, enum pool_mode new_mode)
2412 struct pool_c *pt = pool->ti->private;
2413 bool needs_check = dm_pool_metadata_needs_check(pool->pmd);
2414 enum pool_mode old_mode = get_pool_mode(pool);
2415 unsigned long no_space_timeout = ACCESS_ONCE(no_space_timeout_secs) * HZ;
2418 * Never allow the pool to transition to PM_WRITE mode if user
2419 * intervention is required to verify metadata and data consistency.
2421 if (new_mode == PM_WRITE && needs_check) {
2422 DMERR("%s: unable to switch pool to write mode until repaired.",
2423 dm_device_name(pool->pool_md));
2424 if (old_mode != new_mode)
2425 new_mode = old_mode;
2427 new_mode = PM_READ_ONLY;
2430 * If we were in PM_FAIL mode, rollback of metadata failed. We're
2431 * not going to recover without a thin_repair. So we never let the
2432 * pool move out of the old mode.
2434 if (old_mode == PM_FAIL)
2435 new_mode = old_mode;
2439 if (old_mode != new_mode)
2440 notify_of_pool_mode_change(pool, "failure");
2441 dm_pool_metadata_read_only(pool->pmd);
2442 pool->process_bio = process_bio_fail;
2443 pool->process_discard = process_bio_fail;
2444 pool->process_cell = process_cell_fail;
2445 pool->process_discard_cell = process_cell_fail;
2446 pool->process_prepared_mapping = process_prepared_mapping_fail;
2447 pool->process_prepared_discard = process_prepared_discard_fail;
2449 error_retry_list(pool);
2453 if (old_mode != new_mode)
2454 notify_of_pool_mode_change(pool, "read-only");
2455 dm_pool_metadata_read_only(pool->pmd);
2456 pool->process_bio = process_bio_read_only;
2457 pool->process_discard = process_bio_success;
2458 pool->process_cell = process_cell_read_only;
2459 pool->process_discard_cell = process_cell_success;
2460 pool->process_prepared_mapping = process_prepared_mapping_fail;
2461 pool->process_prepared_discard = process_prepared_discard_success;
2463 error_retry_list(pool);
2466 case PM_OUT_OF_DATA_SPACE:
2468 * Ideally we'd never hit this state; the low water mark
2469 * would trigger userland to extend the pool before we
2470 * completely run out of data space. However, many small
2471 * IOs to unprovisioned space can consume data space at an
2472 * alarming rate. Adjust your low water mark if you're
2473 * frequently seeing this mode.
2475 if (old_mode != new_mode)
2476 notify_of_pool_mode_change_to_oods(pool);
2477 pool->process_bio = process_bio_read_only;
2478 pool->process_discard = process_discard_bio;
2479 pool->process_cell = process_cell_read_only;
2480 pool->process_prepared_mapping = process_prepared_mapping;
2481 set_discard_callbacks(pool);
2483 if (!pool->pf.error_if_no_space && no_space_timeout)
2484 queue_delayed_work(pool->wq, &pool->no_space_timeout, no_space_timeout);
2488 if (old_mode != new_mode)
2489 notify_of_pool_mode_change(pool, "write");
2490 dm_pool_metadata_read_write(pool->pmd);
2491 pool->process_bio = process_bio;
2492 pool->process_discard = process_discard_bio;
2493 pool->process_cell = process_cell;
2494 pool->process_prepared_mapping = process_prepared_mapping;
2495 set_discard_callbacks(pool);
2499 pool->pf.mode = new_mode;
2501 * The pool mode may have changed, sync it so bind_control_target()
2502 * doesn't cause an unexpected mode transition on resume.
2504 pt->adjusted_pf.mode = new_mode;
2507 static void abort_transaction(struct pool *pool)
2509 const char *dev_name = dm_device_name(pool->pool_md);
2511 DMERR_LIMIT("%s: aborting current metadata transaction", dev_name);
2512 if (dm_pool_abort_metadata(pool->pmd)) {
2513 DMERR("%s: failed to abort metadata transaction", dev_name);
2514 set_pool_mode(pool, PM_FAIL);
2517 if (dm_pool_metadata_set_needs_check(pool->pmd)) {
2518 DMERR("%s: failed to set 'needs_check' flag in metadata", dev_name);
2519 set_pool_mode(pool, PM_FAIL);
2523 static void metadata_operation_failed(struct pool *pool, const char *op, int r)
2525 DMERR_LIMIT("%s: metadata operation '%s' failed: error = %d",
2526 dm_device_name(pool->pool_md), op, r);
2528 abort_transaction(pool);
2529 set_pool_mode(pool, PM_READ_ONLY);
2532 /*----------------------------------------------------------------*/
2535 * Mapping functions.
2539 * Called only while mapping a thin bio to hand it over to the workqueue.
2541 static void thin_defer_bio(struct thin_c *tc, struct bio *bio)
2543 unsigned long flags;
2544 struct pool *pool = tc->pool;
2546 spin_lock_irqsave(&tc->lock, flags);
2547 bio_list_add(&tc->deferred_bio_list, bio);
2548 spin_unlock_irqrestore(&tc->lock, flags);
2553 static void thin_defer_bio_with_throttle(struct thin_c *tc, struct bio *bio)
2555 struct pool *pool = tc->pool;
2557 throttle_lock(&pool->throttle);
2558 thin_defer_bio(tc, bio);
2559 throttle_unlock(&pool->throttle);
2562 static void thin_defer_cell(struct thin_c *tc, struct dm_bio_prison_cell *cell)
2564 unsigned long flags;
2565 struct pool *pool = tc->pool;
2567 throttle_lock(&pool->throttle);
2568 spin_lock_irqsave(&tc->lock, flags);
2569 list_add_tail(&cell->user_list, &tc->deferred_cells);
2570 spin_unlock_irqrestore(&tc->lock, flags);
2571 throttle_unlock(&pool->throttle);
2576 static void thin_hook_bio(struct thin_c *tc, struct bio *bio)
2578 struct dm_thin_endio_hook *h = dm_per_bio_data(bio, sizeof(struct dm_thin_endio_hook));
2581 h->shared_read_entry = NULL;
2582 h->all_io_entry = NULL;
2583 h->overwrite_mapping = NULL;
2588 * Non-blocking function called from the thin target's map function.
2590 static int thin_bio_map(struct dm_target *ti, struct bio *bio)
2593 struct thin_c *tc = ti->private;
2594 dm_block_t block = get_bio_block(tc, bio);
2595 struct dm_thin_device *td = tc->td;
2596 struct dm_thin_lookup_result result;
2597 struct dm_bio_prison_cell *virt_cell, *data_cell;
2598 struct dm_cell_key key;
2600 thin_hook_bio(tc, bio);
2602 if (tc->requeue_mode) {
2603 bio_endio(bio, DM_ENDIO_REQUEUE);
2604 return DM_MAPIO_SUBMITTED;
2607 if (get_pool_mode(tc->pool) == PM_FAIL) {
2609 return DM_MAPIO_SUBMITTED;
2612 if (bio->bi_rw & (REQ_DISCARD | REQ_FLUSH | REQ_FUA)) {
2613 thin_defer_bio_with_throttle(tc, bio);
2614 return DM_MAPIO_SUBMITTED;
2618 * We must hold the virtual cell before doing the lookup, otherwise
2619 * there's a race with discard.
2621 build_virtual_key(tc->td, block, &key);
2622 if (bio_detain(tc->pool, &key, bio, &virt_cell))
2623 return DM_MAPIO_SUBMITTED;
2625 r = dm_thin_find_block(td, block, 0, &result);
2628 * Note that we defer readahead too.
2632 if (unlikely(result.shared)) {
2634 * We have a race condition here between the
2635 * result.shared value returned by the lookup and
2636 * snapshot creation, which may cause new
2639 * To avoid this always quiesce the origin before
2640 * taking the snap. You want to do this anyway to
2641 * ensure a consistent application view
2644 * More distant ancestors are irrelevant. The
2645 * shared flag will be set in their case.
2647 thin_defer_cell(tc, virt_cell);
2648 return DM_MAPIO_SUBMITTED;
2651 build_data_key(tc->td, result.block, &key);
2652 if (bio_detain(tc->pool, &key, bio, &data_cell)) {
2653 cell_defer_no_holder(tc, virt_cell);
2654 return DM_MAPIO_SUBMITTED;
2657 inc_all_io_entry(tc->pool, bio);
2658 cell_defer_no_holder(tc, data_cell);
2659 cell_defer_no_holder(tc, virt_cell);
2661 remap(tc, bio, result.block);
2662 return DM_MAPIO_REMAPPED;
2666 thin_defer_cell(tc, virt_cell);
2667 return DM_MAPIO_SUBMITTED;
2671 * Must always call bio_io_error on failure.
2672 * dm_thin_find_block can fail with -EINVAL if the
2673 * pool is switched to fail-io mode.
2676 cell_defer_no_holder(tc, virt_cell);
2677 return DM_MAPIO_SUBMITTED;
2681 static int pool_is_congested(struct dm_target_callbacks *cb, int bdi_bits)
2683 struct pool_c *pt = container_of(cb, struct pool_c, callbacks);
2684 struct request_queue *q;
2686 if (get_pool_mode(pt->pool) == PM_OUT_OF_DATA_SPACE)
2689 q = bdev_get_queue(pt->data_dev->bdev);
2690 return bdi_congested(&q->backing_dev_info, bdi_bits);
2693 static void requeue_bios(struct pool *pool)
2695 unsigned long flags;
2699 list_for_each_entry_rcu(tc, &pool->active_thins, list) {
2700 spin_lock_irqsave(&tc->lock, flags);
2701 bio_list_merge(&tc->deferred_bio_list, &tc->retry_on_resume_list);
2702 bio_list_init(&tc->retry_on_resume_list);
2703 spin_unlock_irqrestore(&tc->lock, flags);
2708 /*----------------------------------------------------------------
2709 * Binding of control targets to a pool object
2710 *--------------------------------------------------------------*/
2711 static bool data_dev_supports_discard(struct pool_c *pt)
2713 struct request_queue *q = bdev_get_queue(pt->data_dev->bdev);
2715 return q && blk_queue_discard(q);
2718 static bool is_factor(sector_t block_size, uint32_t n)
2720 return !sector_div(block_size, n);
2724 * If discard_passdown was enabled verify that the data device
2725 * supports discards. Disable discard_passdown if not.
2727 static void disable_passdown_if_not_supported(struct pool_c *pt)
2729 struct pool *pool = pt->pool;
2730 struct block_device *data_bdev = pt->data_dev->bdev;
2731 struct queue_limits *data_limits = &bdev_get_queue(data_bdev)->limits;
2732 const char *reason = NULL;
2733 char buf[BDEVNAME_SIZE];
2735 if (!pt->adjusted_pf.discard_passdown)
2738 if (!data_dev_supports_discard(pt))
2739 reason = "discard unsupported";
2741 else if (data_limits->max_discard_sectors < pool->sectors_per_block)
2742 reason = "max discard sectors smaller than a block";
2745 DMWARN("Data device (%s) %s: Disabling discard passdown.", bdevname(data_bdev, buf), reason);
2746 pt->adjusted_pf.discard_passdown = false;
2750 static int bind_control_target(struct pool *pool, struct dm_target *ti)
2752 struct pool_c *pt = ti->private;
2755 * We want to make sure that a pool in PM_FAIL mode is never upgraded.
2757 enum pool_mode old_mode = get_pool_mode(pool);
2758 enum pool_mode new_mode = pt->adjusted_pf.mode;
2761 * Don't change the pool's mode until set_pool_mode() below.
2762 * Otherwise the pool's process_* function pointers may
2763 * not match the desired pool mode.
2765 pt->adjusted_pf.mode = old_mode;
2768 pool->pf = pt->adjusted_pf;
2769 pool->low_water_blocks = pt->low_water_blocks;
2771 set_pool_mode(pool, new_mode);
2776 static void unbind_control_target(struct pool *pool, struct dm_target *ti)
2782 /*----------------------------------------------------------------
2784 *--------------------------------------------------------------*/
2785 /* Initialize pool features. */
2786 static void pool_features_init(struct pool_features *pf)
2788 pf->mode = PM_WRITE;
2789 pf->zero_new_blocks = true;
2790 pf->discard_enabled = true;
2791 pf->discard_passdown = true;
2792 pf->error_if_no_space = false;
2795 static void __pool_destroy(struct pool *pool)
2797 __pool_table_remove(pool);
2799 vfree(pool->cell_sort_array);
2800 if (dm_pool_metadata_close(pool->pmd) < 0)
2801 DMWARN("%s: dm_pool_metadata_close() failed.", __func__);
2803 dm_bio_prison_destroy(pool->prison);
2804 dm_kcopyd_client_destroy(pool->copier);
2807 destroy_workqueue(pool->wq);
2809 if (pool->next_mapping)
2810 mempool_free(pool->next_mapping, pool->mapping_pool);
2811 mempool_destroy(pool->mapping_pool);
2812 dm_deferred_set_destroy(pool->shared_read_ds);
2813 dm_deferred_set_destroy(pool->all_io_ds);
2817 static struct kmem_cache *_new_mapping_cache;
2819 static struct pool *pool_create(struct mapped_device *pool_md,
2820 struct block_device *metadata_dev,
2821 unsigned long block_size,
2822 int read_only, char **error)
2827 struct dm_pool_metadata *pmd;
2828 bool format_device = read_only ? false : true;
2830 pmd = dm_pool_metadata_open(metadata_dev, block_size, format_device);
2832 *error = "Error creating metadata object";
2833 return (struct pool *)pmd;
2836 pool = kmalloc(sizeof(*pool), GFP_KERNEL);
2838 *error = "Error allocating memory for pool";
2839 err_p = ERR_PTR(-ENOMEM);
2844 pool->sectors_per_block = block_size;
2845 if (block_size & (block_size - 1))
2846 pool->sectors_per_block_shift = -1;
2848 pool->sectors_per_block_shift = __ffs(block_size);
2849 pool->low_water_blocks = 0;
2850 pool_features_init(&pool->pf);
2851 pool->prison = dm_bio_prison_create();
2852 if (!pool->prison) {
2853 *error = "Error creating pool's bio prison";
2854 err_p = ERR_PTR(-ENOMEM);
2858 pool->copier = dm_kcopyd_client_create(&dm_kcopyd_throttle);
2859 if (IS_ERR(pool->copier)) {
2860 r = PTR_ERR(pool->copier);
2861 *error = "Error creating pool's kcopyd client";
2863 goto bad_kcopyd_client;
2867 * Create singlethreaded workqueue that will service all devices
2868 * that use this metadata.
2870 pool->wq = alloc_ordered_workqueue("dm-" DM_MSG_PREFIX, WQ_MEM_RECLAIM);
2872 *error = "Error creating pool's workqueue";
2873 err_p = ERR_PTR(-ENOMEM);
2877 throttle_init(&pool->throttle);
2878 INIT_WORK(&pool->worker, do_worker);
2879 INIT_DELAYED_WORK(&pool->waker, do_waker);
2880 INIT_DELAYED_WORK(&pool->no_space_timeout, do_no_space_timeout);
2881 spin_lock_init(&pool->lock);
2882 bio_list_init(&pool->deferred_flush_bios);
2883 INIT_LIST_HEAD(&pool->prepared_mappings);
2884 INIT_LIST_HEAD(&pool->prepared_discards);
2885 INIT_LIST_HEAD(&pool->active_thins);
2886 pool->low_water_triggered = false;
2887 pool->suspended = true;
2889 pool->shared_read_ds = dm_deferred_set_create();
2890 if (!pool->shared_read_ds) {
2891 *error = "Error creating pool's shared read deferred set";
2892 err_p = ERR_PTR(-ENOMEM);
2893 goto bad_shared_read_ds;
2896 pool->all_io_ds = dm_deferred_set_create();
2897 if (!pool->all_io_ds) {
2898 *error = "Error creating pool's all io deferred set";
2899 err_p = ERR_PTR(-ENOMEM);
2903 pool->next_mapping = NULL;
2904 pool->mapping_pool = mempool_create_slab_pool(MAPPING_POOL_SIZE,
2905 _new_mapping_cache);
2906 if (!pool->mapping_pool) {
2907 *error = "Error creating pool's mapping mempool";
2908 err_p = ERR_PTR(-ENOMEM);
2909 goto bad_mapping_pool;
2912 pool->cell_sort_array = vmalloc(sizeof(*pool->cell_sort_array) * CELL_SORT_ARRAY_SIZE);
2913 if (!pool->cell_sort_array) {
2914 *error = "Error allocating cell sort array";
2915 err_p = ERR_PTR(-ENOMEM);
2916 goto bad_sort_array;
2919 pool->ref_count = 1;
2920 pool->last_commit_jiffies = jiffies;
2921 pool->pool_md = pool_md;
2922 pool->md_dev = metadata_dev;
2923 __pool_table_insert(pool);
2928 mempool_destroy(pool->mapping_pool);
2930 dm_deferred_set_destroy(pool->all_io_ds);
2932 dm_deferred_set_destroy(pool->shared_read_ds);
2934 destroy_workqueue(pool->wq);
2936 dm_kcopyd_client_destroy(pool->copier);
2938 dm_bio_prison_destroy(pool->prison);
2942 if (dm_pool_metadata_close(pmd))
2943 DMWARN("%s: dm_pool_metadata_close() failed.", __func__);
2948 static void __pool_inc(struct pool *pool)
2950 BUG_ON(!mutex_is_locked(&dm_thin_pool_table.mutex));
2954 static void __pool_dec(struct pool *pool)
2956 BUG_ON(!mutex_is_locked(&dm_thin_pool_table.mutex));
2957 BUG_ON(!pool->ref_count);
2958 if (!--pool->ref_count)
2959 __pool_destroy(pool);
2962 static struct pool *__pool_find(struct mapped_device *pool_md,
2963 struct block_device *metadata_dev,
2964 unsigned long block_size, int read_only,
2965 char **error, int *created)
2967 struct pool *pool = __pool_table_lookup_metadata_dev(metadata_dev);
2970 if (pool->pool_md != pool_md) {
2971 *error = "metadata device already in use by a pool";
2972 return ERR_PTR(-EBUSY);
2977 pool = __pool_table_lookup(pool_md);
2979 if (pool->md_dev != metadata_dev) {
2980 *error = "different pool cannot replace a pool";
2981 return ERR_PTR(-EINVAL);
2986 pool = pool_create(pool_md, metadata_dev, block_size, read_only, error);
2994 /*----------------------------------------------------------------
2995 * Pool target methods
2996 *--------------------------------------------------------------*/
2997 static void pool_dtr(struct dm_target *ti)
2999 struct pool_c *pt = ti->private;
3001 mutex_lock(&dm_thin_pool_table.mutex);
3003 unbind_control_target(pt->pool, ti);
3004 __pool_dec(pt->pool);
3005 dm_put_device(ti, pt->metadata_dev);
3006 dm_put_device(ti, pt->data_dev);
3009 mutex_unlock(&dm_thin_pool_table.mutex);
3012 static int parse_pool_features(struct dm_arg_set *as, struct pool_features *pf,
3013 struct dm_target *ti)
3017 const char *arg_name;
3019 static struct dm_arg _args[] = {
3020 {0, 4, "Invalid number of pool feature arguments"},
3024 * No feature arguments supplied.
3029 r = dm_read_arg_group(_args, as, &argc, &ti->error);
3033 while (argc && !r) {
3034 arg_name = dm_shift_arg(as);
3037 if (!strcasecmp(arg_name, "skip_block_zeroing"))
3038 pf->zero_new_blocks = false;
3040 else if (!strcasecmp(arg_name, "ignore_discard"))
3041 pf->discard_enabled = false;
3043 else if (!strcasecmp(arg_name, "no_discard_passdown"))
3044 pf->discard_passdown = false;
3046 else if (!strcasecmp(arg_name, "read_only"))
3047 pf->mode = PM_READ_ONLY;
3049 else if (!strcasecmp(arg_name, "error_if_no_space"))
3050 pf->error_if_no_space = true;
3053 ti->error = "Unrecognised pool feature requested";
3062 static void metadata_low_callback(void *context)
3064 struct pool *pool = context;
3066 DMWARN("%s: reached low water mark for metadata device: sending event.",
3067 dm_device_name(pool->pool_md));
3069 dm_table_event(pool->ti->table);
3072 static sector_t get_dev_size(struct block_device *bdev)
3074 return i_size_read(bdev->bd_inode) >> SECTOR_SHIFT;
3077 static void warn_if_metadata_device_too_big(struct block_device *bdev)
3079 sector_t metadata_dev_size = get_dev_size(bdev);
3080 char buffer[BDEVNAME_SIZE];
3082 if (metadata_dev_size > THIN_METADATA_MAX_SECTORS_WARNING)
3083 DMWARN("Metadata device %s is larger than %u sectors: excess space will not be used.",
3084 bdevname(bdev, buffer), THIN_METADATA_MAX_SECTORS);
3087 static sector_t get_metadata_dev_size(struct block_device *bdev)
3089 sector_t metadata_dev_size = get_dev_size(bdev);
3091 if (metadata_dev_size > THIN_METADATA_MAX_SECTORS)
3092 metadata_dev_size = THIN_METADATA_MAX_SECTORS;
3094 return metadata_dev_size;
3097 static dm_block_t get_metadata_dev_size_in_blocks(struct block_device *bdev)
3099 sector_t metadata_dev_size = get_metadata_dev_size(bdev);
3101 sector_div(metadata_dev_size, THIN_METADATA_BLOCK_SIZE);
3103 return metadata_dev_size;
3107 * When a metadata threshold is crossed a dm event is triggered, and
3108 * userland should respond by growing the metadata device. We could let
3109 * userland set the threshold, like we do with the data threshold, but I'm
3110 * not sure they know enough to do this well.
3112 static dm_block_t calc_metadata_threshold(struct pool_c *pt)
3115 * 4M is ample for all ops with the possible exception of thin
3116 * device deletion which is harmless if it fails (just retry the
3117 * delete after you've grown the device).
3119 dm_block_t quarter = get_metadata_dev_size_in_blocks(pt->metadata_dev->bdev) / 4;
3120 return min((dm_block_t)1024ULL /* 4M */, quarter);
3124 * thin-pool <metadata dev> <data dev>
3125 * <data block size (sectors)>
3126 * <low water mark (blocks)>
3127 * [<#feature args> [<arg>]*]
3129 * Optional feature arguments are:
3130 * skip_block_zeroing: skips the zeroing of newly-provisioned blocks.
3131 * ignore_discard: disable discard
3132 * no_discard_passdown: don't pass discards down to the data device
3133 * read_only: Don't allow any changes to be made to the pool metadata.
3134 * error_if_no_space: error IOs, instead of queueing, if no space.
3136 static int pool_ctr(struct dm_target *ti, unsigned argc, char **argv)
3138 int r, pool_created = 0;
3141 struct pool_features pf;
3142 struct dm_arg_set as;
3143 struct dm_dev *data_dev;
3144 unsigned long block_size;
3145 dm_block_t low_water_blocks;
3146 struct dm_dev *metadata_dev;
3147 fmode_t metadata_mode;
3150 * FIXME Remove validation from scope of lock.
3152 mutex_lock(&dm_thin_pool_table.mutex);
3155 ti->error = "Invalid argument count";
3164 * Set default pool features.
3166 pool_features_init(&pf);
3168 dm_consume_args(&as, 4);
3169 r = parse_pool_features(&as, &pf, ti);
3173 metadata_mode = FMODE_READ | ((pf.mode == PM_READ_ONLY) ? 0 : FMODE_WRITE);
3174 r = dm_get_device(ti, argv[0], metadata_mode, &metadata_dev);
3176 ti->error = "Error opening metadata block device";
3179 warn_if_metadata_device_too_big(metadata_dev->bdev);
3181 r = dm_get_device(ti, argv[1], FMODE_READ | FMODE_WRITE, &data_dev);
3183 ti->error = "Error getting data device";
3187 if (kstrtoul(argv[2], 10, &block_size) || !block_size ||
3188 block_size < DATA_DEV_BLOCK_SIZE_MIN_SECTORS ||
3189 block_size > DATA_DEV_BLOCK_SIZE_MAX_SECTORS ||
3190 block_size & (DATA_DEV_BLOCK_SIZE_MIN_SECTORS - 1)) {
3191 ti->error = "Invalid block size";
3196 if (kstrtoull(argv[3], 10, (unsigned long long *)&low_water_blocks)) {
3197 ti->error = "Invalid low water mark";
3202 pt = kzalloc(sizeof(*pt), GFP_KERNEL);
3208 pool = __pool_find(dm_table_get_md(ti->table), metadata_dev->bdev,
3209 block_size, pf.mode == PM_READ_ONLY, &ti->error, &pool_created);
3216 * 'pool_created' reflects whether this is the first table load.
3217 * Top level discard support is not allowed to be changed after
3218 * initial load. This would require a pool reload to trigger thin
3221 if (!pool_created && pf.discard_enabled != pool->pf.discard_enabled) {
3222 ti->error = "Discard support cannot be disabled once enabled";
3224 goto out_flags_changed;
3229 pt->metadata_dev = metadata_dev;
3230 pt->data_dev = data_dev;
3231 pt->low_water_blocks = low_water_blocks;
3232 pt->adjusted_pf = pt->requested_pf = pf;
3233 ti->num_flush_bios = 1;
3236 * Only need to enable discards if the pool should pass
3237 * them down to the data device. The thin device's discard
3238 * processing will cause mappings to be removed from the btree.
3240 ti->discard_zeroes_data_unsupported = true;
3241 if (pf.discard_enabled && pf.discard_passdown) {
3242 ti->num_discard_bios = 1;
3245 * Setting 'discards_supported' circumvents the normal
3246 * stacking of discard limits (this keeps the pool and
3247 * thin devices' discard limits consistent).
3249 ti->discards_supported = true;
3253 r = dm_pool_register_metadata_threshold(pt->pool->pmd,
3254 calc_metadata_threshold(pt),
3255 metadata_low_callback,
3260 pt->callbacks.congested_fn = pool_is_congested;
3261 dm_table_add_target_callbacks(ti->table, &pt->callbacks);
3263 mutex_unlock(&dm_thin_pool_table.mutex);
3272 dm_put_device(ti, data_dev);
3274 dm_put_device(ti, metadata_dev);
3276 mutex_unlock(&dm_thin_pool_table.mutex);
3281 static int pool_map(struct dm_target *ti, struct bio *bio)
3284 struct pool_c *pt = ti->private;
3285 struct pool *pool = pt->pool;
3286 unsigned long flags;
3289 * As this is a singleton target, ti->begin is always zero.
3291 spin_lock_irqsave(&pool->lock, flags);
3292 bio->bi_bdev = pt->data_dev->bdev;
3293 r = DM_MAPIO_REMAPPED;
3294 spin_unlock_irqrestore(&pool->lock, flags);
3299 static int maybe_resize_data_dev(struct dm_target *ti, bool *need_commit)
3302 struct pool_c *pt = ti->private;
3303 struct pool *pool = pt->pool;
3304 sector_t data_size = ti->len;
3305 dm_block_t sb_data_size;
3307 *need_commit = false;
3309 (void) sector_div(data_size, pool->sectors_per_block);
3311 r = dm_pool_get_data_dev_size(pool->pmd, &sb_data_size);
3313 DMERR("%s: failed to retrieve data device size",
3314 dm_device_name(pool->pool_md));
3318 if (data_size < sb_data_size) {
3319 DMERR("%s: pool target (%llu blocks) too small: expected %llu",
3320 dm_device_name(pool->pool_md),
3321 (unsigned long long)data_size, sb_data_size);
3324 } else if (data_size > sb_data_size) {
3325 if (dm_pool_metadata_needs_check(pool->pmd)) {
3326 DMERR("%s: unable to grow the data device until repaired.",
3327 dm_device_name(pool->pool_md));
3332 DMINFO("%s: growing the data device from %llu to %llu blocks",
3333 dm_device_name(pool->pool_md),
3334 sb_data_size, (unsigned long long)data_size);
3335 r = dm_pool_resize_data_dev(pool->pmd, data_size);
3337 metadata_operation_failed(pool, "dm_pool_resize_data_dev", r);
3341 *need_commit = true;
3347 static int maybe_resize_metadata_dev(struct dm_target *ti, bool *need_commit)
3350 struct pool_c *pt = ti->private;
3351 struct pool *pool = pt->pool;
3352 dm_block_t metadata_dev_size, sb_metadata_dev_size;
3354 *need_commit = false;
3356 metadata_dev_size = get_metadata_dev_size_in_blocks(pool->md_dev);
3358 r = dm_pool_get_metadata_dev_size(pool->pmd, &sb_metadata_dev_size);
3360 DMERR("%s: failed to retrieve metadata device size",
3361 dm_device_name(pool->pool_md));
3365 if (metadata_dev_size < sb_metadata_dev_size) {
3366 DMERR("%s: metadata device (%llu blocks) too small: expected %llu",
3367 dm_device_name(pool->pool_md),
3368 metadata_dev_size, sb_metadata_dev_size);
3371 } else if (metadata_dev_size > sb_metadata_dev_size) {
3372 if (dm_pool_metadata_needs_check(pool->pmd)) {
3373 DMERR("%s: unable to grow the metadata device until repaired.",
3374 dm_device_name(pool->pool_md));
3378 warn_if_metadata_device_too_big(pool->md_dev);
3379 DMINFO("%s: growing the metadata device from %llu to %llu blocks",
3380 dm_device_name(pool->pool_md),
3381 sb_metadata_dev_size, metadata_dev_size);
3382 r = dm_pool_resize_metadata_dev(pool->pmd, metadata_dev_size);
3384 metadata_operation_failed(pool, "dm_pool_resize_metadata_dev", r);
3388 *need_commit = true;
3395 * Retrieves the number of blocks of the data device from
3396 * the superblock and compares it to the actual device size,
3397 * thus resizing the data device in case it has grown.
3399 * This both copes with opening preallocated data devices in the ctr
3400 * being followed by a resume
3402 * calling the resume method individually after userspace has
3403 * grown the data device in reaction to a table event.
3405 static int pool_preresume(struct dm_target *ti)
3408 bool need_commit1, need_commit2;
3409 struct pool_c *pt = ti->private;
3410 struct pool *pool = pt->pool;
3413 * Take control of the pool object.
3415 r = bind_control_target(pool, ti);
3419 r = maybe_resize_data_dev(ti, &need_commit1);
3423 r = maybe_resize_metadata_dev(ti, &need_commit2);
3427 if (need_commit1 || need_commit2)
3428 (void) commit(pool);
3433 static void pool_suspend_active_thins(struct pool *pool)
3437 /* Suspend all active thin devices */
3438 tc = get_first_thin(pool);
3440 dm_internal_suspend_noflush(tc->thin_md);
3441 tc = get_next_thin(pool, tc);
3445 static void pool_resume_active_thins(struct pool *pool)
3449 /* Resume all active thin devices */
3450 tc = get_first_thin(pool);
3452 dm_internal_resume(tc->thin_md);
3453 tc = get_next_thin(pool, tc);
3457 static void pool_resume(struct dm_target *ti)
3459 struct pool_c *pt = ti->private;
3460 struct pool *pool = pt->pool;
3461 unsigned long flags;
3464 * Must requeue active_thins' bios and then resume
3465 * active_thins _before_ clearing 'suspend' flag.
3468 pool_resume_active_thins(pool);
3470 spin_lock_irqsave(&pool->lock, flags);
3471 pool->low_water_triggered = false;
3472 pool->suspended = false;
3473 spin_unlock_irqrestore(&pool->lock, flags);
3475 do_waker(&pool->waker.work);
3478 static void pool_presuspend(struct dm_target *ti)
3480 struct pool_c *pt = ti->private;
3481 struct pool *pool = pt->pool;
3482 unsigned long flags;
3484 spin_lock_irqsave(&pool->lock, flags);
3485 pool->suspended = true;
3486 spin_unlock_irqrestore(&pool->lock, flags);
3488 pool_suspend_active_thins(pool);
3491 static void pool_presuspend_undo(struct dm_target *ti)
3493 struct pool_c *pt = ti->private;
3494 struct pool *pool = pt->pool;
3495 unsigned long flags;
3497 pool_resume_active_thins(pool);
3499 spin_lock_irqsave(&pool->lock, flags);
3500 pool->suspended = false;
3501 spin_unlock_irqrestore(&pool->lock, flags);
3504 static void pool_postsuspend(struct dm_target *ti)
3506 struct pool_c *pt = ti->private;
3507 struct pool *pool = pt->pool;
3509 cancel_delayed_work(&pool->waker);
3510 cancel_delayed_work(&pool->no_space_timeout);
3511 flush_workqueue(pool->wq);
3512 (void) commit(pool);
3515 static int check_arg_count(unsigned argc, unsigned args_required)
3517 if (argc != args_required) {
3518 DMWARN("Message received with %u arguments instead of %u.",
3519 argc, args_required);
3526 static int read_dev_id(char *arg, dm_thin_id *dev_id, int warning)
3528 if (!kstrtoull(arg, 10, (unsigned long long *)dev_id) &&
3529 *dev_id <= MAX_DEV_ID)
3533 DMWARN("Message received with invalid device id: %s", arg);
3538 static int process_create_thin_mesg(unsigned argc, char **argv, struct pool *pool)
3543 r = check_arg_count(argc, 2);
3547 r = read_dev_id(argv[1], &dev_id, 1);
3551 r = dm_pool_create_thin(pool->pmd, dev_id);
3553 DMWARN("Creation of new thinly-provisioned device with id %s failed.",
3561 static int process_create_snap_mesg(unsigned argc, char **argv, struct pool *pool)
3564 dm_thin_id origin_dev_id;
3567 r = check_arg_count(argc, 3);
3571 r = read_dev_id(argv[1], &dev_id, 1);
3575 r = read_dev_id(argv[2], &origin_dev_id, 1);
3579 r = dm_pool_create_snap(pool->pmd, dev_id, origin_dev_id);
3581 DMWARN("Creation of new snapshot %s of device %s failed.",
3589 static int process_delete_mesg(unsigned argc, char **argv, struct pool *pool)
3594 r = check_arg_count(argc, 2);
3598 r = read_dev_id(argv[1], &dev_id, 1);
3602 r = dm_pool_delete_thin_device(pool->pmd, dev_id);
3604 DMWARN("Deletion of thin device %s failed.", argv[1]);
3609 static int process_set_transaction_id_mesg(unsigned argc, char **argv, struct pool *pool)
3611 dm_thin_id old_id, new_id;
3614 r = check_arg_count(argc, 3);
3618 if (kstrtoull(argv[1], 10, (unsigned long long *)&old_id)) {
3619 DMWARN("set_transaction_id message: Unrecognised id %s.", argv[1]);
3623 if (kstrtoull(argv[2], 10, (unsigned long long *)&new_id)) {
3624 DMWARN("set_transaction_id message: Unrecognised new id %s.", argv[2]);
3628 r = dm_pool_set_metadata_transaction_id(pool->pmd, old_id, new_id);
3630 DMWARN("Failed to change transaction id from %s to %s.",
3638 static int process_reserve_metadata_snap_mesg(unsigned argc, char **argv, struct pool *pool)
3642 r = check_arg_count(argc, 1);
3646 (void) commit(pool);
3648 r = dm_pool_reserve_metadata_snap(pool->pmd);
3650 DMWARN("reserve_metadata_snap message failed.");
3655 static int process_release_metadata_snap_mesg(unsigned argc, char **argv, struct pool *pool)
3659 r = check_arg_count(argc, 1);
3663 r = dm_pool_release_metadata_snap(pool->pmd);
3665 DMWARN("release_metadata_snap message failed.");
3671 * Messages supported:
3672 * create_thin <dev_id>
3673 * create_snap <dev_id> <origin_id>
3675 * set_transaction_id <current_trans_id> <new_trans_id>
3676 * reserve_metadata_snap
3677 * release_metadata_snap
3679 static int pool_message(struct dm_target *ti, unsigned argc, char **argv)
3682 struct pool_c *pt = ti->private;
3683 struct pool *pool = pt->pool;
3685 if (get_pool_mode(pool) >= PM_READ_ONLY) {
3686 DMERR("%s: unable to service pool target messages in READ_ONLY or FAIL mode",
3687 dm_device_name(pool->pool_md));
3691 if (!strcasecmp(argv[0], "create_thin"))
3692 r = process_create_thin_mesg(argc, argv, pool);
3694 else if (!strcasecmp(argv[0], "create_snap"))
3695 r = process_create_snap_mesg(argc, argv, pool);
3697 else if (!strcasecmp(argv[0], "delete"))
3698 r = process_delete_mesg(argc, argv, pool);
3700 else if (!strcasecmp(argv[0], "set_transaction_id"))
3701 r = process_set_transaction_id_mesg(argc, argv, pool);
3703 else if (!strcasecmp(argv[0], "reserve_metadata_snap"))
3704 r = process_reserve_metadata_snap_mesg(argc, argv, pool);
3706 else if (!strcasecmp(argv[0], "release_metadata_snap"))
3707 r = process_release_metadata_snap_mesg(argc, argv, pool);
3710 DMWARN("Unrecognised thin pool target message received: %s", argv[0]);
3713 (void) commit(pool);
3718 static void emit_flags(struct pool_features *pf, char *result,
3719 unsigned sz, unsigned maxlen)
3721 unsigned count = !pf->zero_new_blocks + !pf->discard_enabled +
3722 !pf->discard_passdown + (pf->mode == PM_READ_ONLY) +
3723 pf->error_if_no_space;
3724 DMEMIT("%u ", count);
3726 if (!pf->zero_new_blocks)
3727 DMEMIT("skip_block_zeroing ");
3729 if (!pf->discard_enabled)
3730 DMEMIT("ignore_discard ");
3732 if (!pf->discard_passdown)
3733 DMEMIT("no_discard_passdown ");
3735 if (pf->mode == PM_READ_ONLY)
3736 DMEMIT("read_only ");
3738 if (pf->error_if_no_space)
3739 DMEMIT("error_if_no_space ");
3744 * <transaction id> <used metadata sectors>/<total metadata sectors>
3745 * <used data sectors>/<total data sectors> <held metadata root>
3746 * <pool mode> <discard config> <no space config> <needs_check>
3748 static void pool_status(struct dm_target *ti, status_type_t type,
3749 unsigned status_flags, char *result, unsigned maxlen)
3753 uint64_t transaction_id;
3754 dm_block_t nr_free_blocks_data;
3755 dm_block_t nr_free_blocks_metadata;
3756 dm_block_t nr_blocks_data;
3757 dm_block_t nr_blocks_metadata;
3758 dm_block_t held_root;
3759 char buf[BDEVNAME_SIZE];
3760 char buf2[BDEVNAME_SIZE];
3761 struct pool_c *pt = ti->private;
3762 struct pool *pool = pt->pool;
3765 case STATUSTYPE_INFO:
3766 if (get_pool_mode(pool) == PM_FAIL) {
3771 /* Commit to ensure statistics aren't out-of-date */
3772 if (!(status_flags & DM_STATUS_NOFLUSH_FLAG) && !dm_suspended(ti))
3773 (void) commit(pool);
3775 r = dm_pool_get_metadata_transaction_id(pool->pmd, &transaction_id);
3777 DMERR("%s: dm_pool_get_metadata_transaction_id returned %d",
3778 dm_device_name(pool->pool_md), r);
3782 r = dm_pool_get_free_metadata_block_count(pool->pmd, &nr_free_blocks_metadata);
3784 DMERR("%s: dm_pool_get_free_metadata_block_count returned %d",
3785 dm_device_name(pool->pool_md), r);
3789 r = dm_pool_get_metadata_dev_size(pool->pmd, &nr_blocks_metadata);
3791 DMERR("%s: dm_pool_get_metadata_dev_size returned %d",
3792 dm_device_name(pool->pool_md), r);
3796 r = dm_pool_get_free_block_count(pool->pmd, &nr_free_blocks_data);
3798 DMERR("%s: dm_pool_get_free_block_count returned %d",
3799 dm_device_name(pool->pool_md), r);
3803 r = dm_pool_get_data_dev_size(pool->pmd, &nr_blocks_data);
3805 DMERR("%s: dm_pool_get_data_dev_size returned %d",
3806 dm_device_name(pool->pool_md), r);
3810 r = dm_pool_get_metadata_snap(pool->pmd, &held_root);
3812 DMERR("%s: dm_pool_get_metadata_snap returned %d",
3813 dm_device_name(pool->pool_md), r);
3817 DMEMIT("%llu %llu/%llu %llu/%llu ",
3818 (unsigned long long)transaction_id,
3819 (unsigned long long)(nr_blocks_metadata - nr_free_blocks_metadata),
3820 (unsigned long long)nr_blocks_metadata,
3821 (unsigned long long)(nr_blocks_data - nr_free_blocks_data),
3822 (unsigned long long)nr_blocks_data);
3825 DMEMIT("%llu ", held_root);
3829 if (pool->pf.mode == PM_OUT_OF_DATA_SPACE)
3830 DMEMIT("out_of_data_space ");
3831 else if (pool->pf.mode == PM_READ_ONLY)
3836 if (!pool->pf.discard_enabled)
3837 DMEMIT("ignore_discard ");
3838 else if (pool->pf.discard_passdown)
3839 DMEMIT("discard_passdown ");
3841 DMEMIT("no_discard_passdown ");
3843 if (pool->pf.error_if_no_space)
3844 DMEMIT("error_if_no_space ");
3846 DMEMIT("queue_if_no_space ");
3848 if (dm_pool_metadata_needs_check(pool->pmd))
3849 DMEMIT("needs_check ");
3855 case STATUSTYPE_TABLE:
3856 DMEMIT("%s %s %lu %llu ",
3857 format_dev_t(buf, pt->metadata_dev->bdev->bd_dev),
3858 format_dev_t(buf2, pt->data_dev->bdev->bd_dev),
3859 (unsigned long)pool->sectors_per_block,
3860 (unsigned long long)pt->low_water_blocks);
3861 emit_flags(&pt->requested_pf, result, sz, maxlen);
3870 static int pool_iterate_devices(struct dm_target *ti,
3871 iterate_devices_callout_fn fn, void *data)
3873 struct pool_c *pt = ti->private;
3875 return fn(ti, pt->data_dev, 0, ti->len, data);
3878 static int pool_merge(struct dm_target *ti, struct bvec_merge_data *bvm,
3879 struct bio_vec *biovec, int max_size)
3881 struct pool_c *pt = ti->private;
3882 struct request_queue *q = bdev_get_queue(pt->data_dev->bdev);
3884 if (!q->merge_bvec_fn)
3887 bvm->bi_bdev = pt->data_dev->bdev;
3889 return min(max_size, q->merge_bvec_fn(q, bvm, biovec));
3892 static void pool_io_hints(struct dm_target *ti, struct queue_limits *limits)
3894 struct pool_c *pt = ti->private;
3895 struct pool *pool = pt->pool;
3896 sector_t io_opt_sectors = limits->io_opt >> SECTOR_SHIFT;
3899 * If max_sectors is smaller than pool->sectors_per_block adjust it
3900 * to the highest possible power-of-2 factor of pool->sectors_per_block.
3901 * This is especially beneficial when the pool's data device is a RAID
3902 * device that has a full stripe width that matches pool->sectors_per_block
3903 * -- because even though partial RAID stripe-sized IOs will be issued to a
3904 * single RAID stripe; when aggregated they will end on a full RAID stripe
3905 * boundary.. which avoids additional partial RAID stripe writes cascading
3907 if (limits->max_sectors < pool->sectors_per_block) {
3908 while (!is_factor(pool->sectors_per_block, limits->max_sectors)) {
3909 if ((limits->max_sectors & (limits->max_sectors - 1)) == 0)
3910 limits->max_sectors--;
3911 limits->max_sectors = rounddown_pow_of_two(limits->max_sectors);
3916 * If the system-determined stacked limits are compatible with the
3917 * pool's blocksize (io_opt is a factor) do not override them.
3919 if (io_opt_sectors < pool->sectors_per_block ||
3920 !is_factor(io_opt_sectors, pool->sectors_per_block)) {
3921 if (is_factor(pool->sectors_per_block, limits->max_sectors))
3922 blk_limits_io_min(limits, limits->max_sectors << SECTOR_SHIFT);
3924 blk_limits_io_min(limits, pool->sectors_per_block << SECTOR_SHIFT);
3925 blk_limits_io_opt(limits, pool->sectors_per_block << SECTOR_SHIFT);
3929 * pt->adjusted_pf is a staging area for the actual features to use.
3930 * They get transferred to the live pool in bind_control_target()
3931 * called from pool_preresume().
3933 if (!pt->adjusted_pf.discard_enabled) {
3935 * Must explicitly disallow stacking discard limits otherwise the
3936 * block layer will stack them if pool's data device has support.
3937 * QUEUE_FLAG_DISCARD wouldn't be set but there is no way for the
3938 * user to see that, so make sure to set all discard limits to 0.
3940 limits->discard_granularity = 0;
3944 disable_passdown_if_not_supported(pt);
3947 * The pool uses the same discard limits as the underlying data
3948 * device. DM core has already set this up.
3952 static struct target_type pool_target = {
3953 .name = "thin-pool",
3954 .features = DM_TARGET_SINGLETON | DM_TARGET_ALWAYS_WRITEABLE |
3955 DM_TARGET_IMMUTABLE,
3956 .version = {1, 16, 0},
3957 .module = THIS_MODULE,
3961 .presuspend = pool_presuspend,
3962 .presuspend_undo = pool_presuspend_undo,
3963 .postsuspend = pool_postsuspend,
3964 .preresume = pool_preresume,
3965 .resume = pool_resume,
3966 .message = pool_message,
3967 .status = pool_status,
3968 .merge = pool_merge,
3969 .iterate_devices = pool_iterate_devices,
3970 .io_hints = pool_io_hints,
3973 /*----------------------------------------------------------------
3974 * Thin target methods
3975 *--------------------------------------------------------------*/
3976 static void thin_get(struct thin_c *tc)
3978 atomic_inc(&tc->refcount);
3981 static void thin_put(struct thin_c *tc)
3983 if (atomic_dec_and_test(&tc->refcount))
3984 complete(&tc->can_destroy);
3987 static void thin_dtr(struct dm_target *ti)
3989 struct thin_c *tc = ti->private;
3990 unsigned long flags;
3992 spin_lock_irqsave(&tc->pool->lock, flags);
3993 list_del_rcu(&tc->list);
3994 spin_unlock_irqrestore(&tc->pool->lock, flags);
3998 wait_for_completion(&tc->can_destroy);
4000 mutex_lock(&dm_thin_pool_table.mutex);
4002 __pool_dec(tc->pool);
4003 dm_pool_close_thin_device(tc->td);
4004 dm_put_device(ti, tc->pool_dev);
4006 dm_put_device(ti, tc->origin_dev);
4009 mutex_unlock(&dm_thin_pool_table.mutex);
4013 * Thin target parameters:
4015 * <pool_dev> <dev_id> [origin_dev]
4017 * pool_dev: the path to the pool (eg, /dev/mapper/my_pool)
4018 * dev_id: the internal device identifier
4019 * origin_dev: a device external to the pool that should act as the origin
4021 * If the pool device has discards disabled, they get disabled for the thin
4024 static int thin_ctr(struct dm_target *ti, unsigned argc, char **argv)
4028 struct dm_dev *pool_dev, *origin_dev;
4029 struct mapped_device *pool_md;
4030 unsigned long flags;
4032 mutex_lock(&dm_thin_pool_table.mutex);
4034 if (argc != 2 && argc != 3) {
4035 ti->error = "Invalid argument count";
4040 tc = ti->private = kzalloc(sizeof(*tc), GFP_KERNEL);
4042 ti->error = "Out of memory";
4046 tc->thin_md = dm_table_get_md(ti->table);
4047 spin_lock_init(&tc->lock);
4048 INIT_LIST_HEAD(&tc->deferred_cells);
4049 bio_list_init(&tc->deferred_bio_list);
4050 bio_list_init(&tc->retry_on_resume_list);
4051 tc->sort_bio_list = RB_ROOT;
4054 r = dm_get_device(ti, argv[2], FMODE_READ, &origin_dev);
4056 ti->error = "Error opening origin device";
4057 goto bad_origin_dev;
4059 tc->origin_dev = origin_dev;
4062 r = dm_get_device(ti, argv[0], dm_table_get_mode(ti->table), &pool_dev);
4064 ti->error = "Error opening pool device";
4067 tc->pool_dev = pool_dev;
4069 if (read_dev_id(argv[1], (unsigned long long *)&tc->dev_id, 0)) {
4070 ti->error = "Invalid device id";
4075 pool_md = dm_get_md(tc->pool_dev->bdev->bd_dev);
4077 ti->error = "Couldn't get pool mapped device";
4082 tc->pool = __pool_table_lookup(pool_md);
4084 ti->error = "Couldn't find pool object";
4086 goto bad_pool_lookup;
4088 __pool_inc(tc->pool);
4090 if (get_pool_mode(tc->pool) == PM_FAIL) {
4091 ti->error = "Couldn't open thin device, Pool is in fail mode";
4096 r = dm_pool_open_thin_device(tc->pool->pmd, tc->dev_id, &tc->td);
4098 ti->error = "Couldn't open thin internal device";
4102 r = dm_set_target_max_io_len(ti, tc->pool->sectors_per_block);
4106 ti->num_flush_bios = 1;
4107 ti->flush_supported = true;
4108 ti->per_bio_data_size = sizeof(struct dm_thin_endio_hook);
4110 /* In case the pool supports discards, pass them on. */
4111 ti->discard_zeroes_data_unsupported = true;
4112 if (tc->pool->pf.discard_enabled) {
4113 ti->discards_supported = true;
4114 ti->num_discard_bios = 1;
4115 ti->split_discard_bios = false;
4118 mutex_unlock(&dm_thin_pool_table.mutex);
4120 spin_lock_irqsave(&tc->pool->lock, flags);
4121 if (tc->pool->suspended) {
4122 spin_unlock_irqrestore(&tc->pool->lock, flags);
4123 mutex_lock(&dm_thin_pool_table.mutex); /* reacquire for __pool_dec */
4124 ti->error = "Unable to activate thin device while pool is suspended";
4128 atomic_set(&tc->refcount, 1);
4129 init_completion(&tc->can_destroy);
4130 list_add_tail_rcu(&tc->list, &tc->pool->active_thins);
4131 spin_unlock_irqrestore(&tc->pool->lock, flags);
4133 * This synchronize_rcu() call is needed here otherwise we risk a
4134 * wake_worker() call finding no bios to process (because the newly
4135 * added tc isn't yet visible). So this reduces latency since we
4136 * aren't then dependent on the periodic commit to wake_worker().
4145 dm_pool_close_thin_device(tc->td);
4147 __pool_dec(tc->pool);
4151 dm_put_device(ti, tc->pool_dev);
4154 dm_put_device(ti, tc->origin_dev);
4158 mutex_unlock(&dm_thin_pool_table.mutex);
4163 static int thin_map(struct dm_target *ti, struct bio *bio)
4165 bio->bi_iter.bi_sector = dm_target_offset(ti, bio->bi_iter.bi_sector);
4167 return thin_bio_map(ti, bio);
4170 static int thin_endio(struct dm_target *ti, struct bio *bio, int err)
4172 unsigned long flags;
4173 struct dm_thin_endio_hook *h = dm_per_bio_data(bio, sizeof(struct dm_thin_endio_hook));
4174 struct list_head work;
4175 struct dm_thin_new_mapping *m, *tmp;
4176 struct pool *pool = h->tc->pool;
4178 if (h->shared_read_entry) {
4179 INIT_LIST_HEAD(&work);
4180 dm_deferred_entry_dec(h->shared_read_entry, &work);
4182 spin_lock_irqsave(&pool->lock, flags);
4183 list_for_each_entry_safe(m, tmp, &work, list) {
4185 __complete_mapping_preparation(m);
4187 spin_unlock_irqrestore(&pool->lock, flags);
4190 if (h->all_io_entry) {
4191 INIT_LIST_HEAD(&work);
4192 dm_deferred_entry_dec(h->all_io_entry, &work);
4193 if (!list_empty(&work)) {
4194 spin_lock_irqsave(&pool->lock, flags);
4195 list_for_each_entry_safe(m, tmp, &work, list)
4196 list_add_tail(&m->list, &pool->prepared_discards);
4197 spin_unlock_irqrestore(&pool->lock, flags);
4203 cell_defer_no_holder(h->tc, h->cell);
4208 static void thin_presuspend(struct dm_target *ti)
4210 struct thin_c *tc = ti->private;
4212 if (dm_noflush_suspending(ti))
4213 noflush_work(tc, do_noflush_start);
4216 static void thin_postsuspend(struct dm_target *ti)
4218 struct thin_c *tc = ti->private;
4221 * The dm_noflush_suspending flag has been cleared by now, so
4222 * unfortunately we must always run this.
4224 noflush_work(tc, do_noflush_stop);
4227 static int thin_preresume(struct dm_target *ti)
4229 struct thin_c *tc = ti->private;
4232 tc->origin_size = get_dev_size(tc->origin_dev->bdev);
4238 * <nr mapped sectors> <highest mapped sector>
4240 static void thin_status(struct dm_target *ti, status_type_t type,
4241 unsigned status_flags, char *result, unsigned maxlen)
4245 dm_block_t mapped, highest;
4246 char buf[BDEVNAME_SIZE];
4247 struct thin_c *tc = ti->private;
4249 if (get_pool_mode(tc->pool) == PM_FAIL) {
4258 case STATUSTYPE_INFO:
4259 r = dm_thin_get_mapped_count(tc->td, &mapped);
4261 DMERR("dm_thin_get_mapped_count returned %d", r);
4265 r = dm_thin_get_highest_mapped_block(tc->td, &highest);
4267 DMERR("dm_thin_get_highest_mapped_block returned %d", r);
4271 DMEMIT("%llu ", mapped * tc->pool->sectors_per_block);
4273 DMEMIT("%llu", ((highest + 1) *
4274 tc->pool->sectors_per_block) - 1);
4279 case STATUSTYPE_TABLE:
4281 format_dev_t(buf, tc->pool_dev->bdev->bd_dev),
4282 (unsigned long) tc->dev_id);
4284 DMEMIT(" %s", format_dev_t(buf, tc->origin_dev->bdev->bd_dev));
4295 static int thin_merge(struct dm_target *ti, struct bvec_merge_data *bvm,
4296 struct bio_vec *biovec, int max_size)
4298 struct thin_c *tc = ti->private;
4299 struct request_queue *q = bdev_get_queue(tc->pool_dev->bdev);
4301 if (!q->merge_bvec_fn)
4304 bvm->bi_bdev = tc->pool_dev->bdev;
4305 bvm->bi_sector = dm_target_offset(ti, bvm->bi_sector);
4307 return min(max_size, q->merge_bvec_fn(q, bvm, biovec));
4310 static int thin_iterate_devices(struct dm_target *ti,
4311 iterate_devices_callout_fn fn, void *data)
4314 struct thin_c *tc = ti->private;
4315 struct pool *pool = tc->pool;
4318 * We can't call dm_pool_get_data_dev_size() since that blocks. So
4319 * we follow a more convoluted path through to the pool's target.
4322 return 0; /* nothing is bound */
4324 blocks = pool->ti->len;
4325 (void) sector_div(blocks, pool->sectors_per_block);
4327 return fn(ti, tc->pool_dev, 0, pool->sectors_per_block * blocks, data);
4332 static void thin_io_hints(struct dm_target *ti, struct queue_limits *limits)
4334 struct thin_c *tc = ti->private;
4335 struct pool *pool = tc->pool;
4337 limits->discard_granularity = pool->sectors_per_block << SECTOR_SHIFT;
4338 limits->max_discard_sectors = 2048 * 1024 * 16; /* 16G */
4341 static struct target_type thin_target = {
4343 .version = {1, 16, 0},
4344 .module = THIS_MODULE,
4348 .end_io = thin_endio,
4349 .preresume = thin_preresume,
4350 .presuspend = thin_presuspend,
4351 .postsuspend = thin_postsuspend,
4352 .status = thin_status,
4353 .merge = thin_merge,
4354 .iterate_devices = thin_iterate_devices,
4355 .io_hints = thin_io_hints,
4358 /*----------------------------------------------------------------*/
4360 static int __init dm_thin_init(void)
4366 r = dm_register_target(&thin_target);
4370 r = dm_register_target(&pool_target);
4372 goto bad_pool_target;
4376 _new_mapping_cache = KMEM_CACHE(dm_thin_new_mapping, 0);
4377 if (!_new_mapping_cache)
4378 goto bad_new_mapping_cache;
4382 bad_new_mapping_cache:
4383 dm_unregister_target(&pool_target);
4385 dm_unregister_target(&thin_target);
4390 static void dm_thin_exit(void)
4392 dm_unregister_target(&thin_target);
4393 dm_unregister_target(&pool_target);
4395 kmem_cache_destroy(_new_mapping_cache);
4398 module_init(dm_thin_init);
4399 module_exit(dm_thin_exit);
4401 module_param_named(no_space_timeout, no_space_timeout_secs, uint, S_IRUGO | S_IWUSR);
4402 MODULE_PARM_DESC(no_space_timeout, "Out of data space queue IO timeout in seconds");
4404 MODULE_DESCRIPTION(DM_NAME " thin provisioning target");
4405 MODULE_AUTHOR("Joe Thornber <dm-devel@redhat.com>");
4406 MODULE_LICENSE("GPL");