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/log2.h>
15 #include <linux/list.h>
16 #include <linux/rculist.h>
17 #include <linux/init.h>
18 #include <linux/module.h>
19 #include <linux/slab.h>
20 #include <linux/sort.h>
21 #include <linux/rbtree.h>
23 #define DM_MSG_PREFIX "thin"
28 #define ENDIO_HOOK_POOL_SIZE 1024
29 #define MAPPING_POOL_SIZE 1024
30 #define COMMIT_PERIOD HZ
31 #define NO_SPACE_TIMEOUT_SECS 60
33 static unsigned no_space_timeout_secs = NO_SPACE_TIMEOUT_SECS;
35 DECLARE_DM_KCOPYD_THROTTLE_WITH_MODULE_PARM(snapshot_copy_throttle,
36 "A percentage of time allocated for copy on write");
39 * The block size of the device holding pool data must be
40 * between 64KB and 1GB.
42 #define DATA_DEV_BLOCK_SIZE_MIN_SECTORS (64 * 1024 >> SECTOR_SHIFT)
43 #define DATA_DEV_BLOCK_SIZE_MAX_SECTORS (1024 * 1024 * 1024 >> SECTOR_SHIFT)
46 * Device id is restricted to 24 bits.
48 #define MAX_DEV_ID ((1 << 24) - 1)
51 * How do we handle breaking sharing of data blocks?
52 * =================================================
54 * We use a standard copy-on-write btree to store the mappings for the
55 * devices (note I'm talking about copy-on-write of the metadata here, not
56 * the data). When you take an internal snapshot you clone the root node
57 * of the origin btree. After this there is no concept of an origin or a
58 * snapshot. They are just two device trees that happen to point to the
61 * When we get a write in we decide if it's to a shared data block using
62 * some timestamp magic. If it is, we have to break sharing.
64 * Let's say we write to a shared block in what was the origin. The
67 * i) plug io further to this physical block. (see bio_prison code).
69 * ii) quiesce any read io to that shared data block. Obviously
70 * including all devices that share this block. (see dm_deferred_set code)
72 * iii) copy the data block to a newly allocate block. This step can be
73 * missed out if the io covers the block. (schedule_copy).
75 * iv) insert the new mapping into the origin's btree
76 * (process_prepared_mapping). This act of inserting breaks some
77 * sharing of btree nodes between the two devices. Breaking sharing only
78 * effects the btree of that specific device. Btrees for the other
79 * devices that share the block never change. The btree for the origin
80 * device as it was after the last commit is untouched, ie. we're using
81 * persistent data structures in the functional programming sense.
83 * v) unplug io to this physical block, including the io that triggered
84 * the breaking of sharing.
86 * Steps (ii) and (iii) occur in parallel.
88 * The metadata _doesn't_ need to be committed before the io continues. We
89 * get away with this because the io is always written to a _new_ block.
90 * If there's a crash, then:
92 * - The origin mapping will point to the old origin block (the shared
93 * one). This will contain the data as it was before the io that triggered
94 * the breaking of sharing came in.
96 * - The snap mapping still points to the old block. As it would after
99 * The downside of this scheme is the timestamp magic isn't perfect, and
100 * will continue to think that data block in the snapshot device is shared
101 * even after the write to the origin has broken sharing. I suspect data
102 * blocks will typically be shared by many different devices, so we're
103 * breaking sharing n + 1 times, rather than n, where n is the number of
104 * devices that reference this data block. At the moment I think the
105 * benefits far, far outweigh the disadvantages.
108 /*----------------------------------------------------------------*/
113 static void build_data_key(struct dm_thin_device *td,
114 dm_block_t b, struct dm_cell_key *key)
117 key->dev = dm_thin_dev_id(td);
121 static void build_virtual_key(struct dm_thin_device *td, dm_block_t b,
122 struct dm_cell_key *key)
125 key->dev = dm_thin_dev_id(td);
129 /*----------------------------------------------------------------*/
131 #define THROTTLE_THRESHOLD (1 * HZ)
134 struct rw_semaphore lock;
135 unsigned long threshold;
136 bool throttle_applied;
139 static void throttle_init(struct throttle *t)
141 init_rwsem(&t->lock);
142 t->throttle_applied = false;
145 static void throttle_work_start(struct throttle *t)
147 t->threshold = jiffies + THROTTLE_THRESHOLD;
150 static void throttle_work_update(struct throttle *t)
152 if (!t->throttle_applied && jiffies > t->threshold) {
153 down_write(&t->lock);
154 t->throttle_applied = true;
158 static void throttle_work_complete(struct throttle *t)
160 if (t->throttle_applied) {
161 t->throttle_applied = false;
166 static void throttle_lock(struct throttle *t)
171 static void throttle_unlock(struct throttle *t)
176 /*----------------------------------------------------------------*/
179 * A pool device ties together a metadata device and a data device. It
180 * also provides the interface for creating and destroying internal
183 struct dm_thin_new_mapping;
186 * The pool runs in 4 modes. Ordered in degraded order for comparisons.
189 PM_WRITE, /* metadata may be changed */
190 PM_OUT_OF_DATA_SPACE, /* metadata may be changed, though data may not be allocated */
191 PM_READ_ONLY, /* metadata may not be changed */
192 PM_FAIL, /* all I/O fails */
195 struct pool_features {
198 bool zero_new_blocks:1;
199 bool discard_enabled:1;
200 bool discard_passdown:1;
201 bool error_if_no_space:1;
205 typedef void (*process_bio_fn)(struct thin_c *tc, struct bio *bio);
206 typedef void (*process_cell_fn)(struct thin_c *tc, struct dm_bio_prison_cell *cell);
207 typedef void (*process_mapping_fn)(struct dm_thin_new_mapping *m);
209 #define CELL_SORT_ARRAY_SIZE 8192
212 struct list_head list;
213 struct dm_target *ti; /* Only set if a pool target is bound */
215 struct mapped_device *pool_md;
216 struct block_device *md_dev;
217 struct dm_pool_metadata *pmd;
219 dm_block_t low_water_blocks;
220 uint32_t sectors_per_block;
221 int sectors_per_block_shift;
223 struct pool_features pf;
224 bool low_water_triggered:1; /* A dm event has been sent */
226 struct dm_bio_prison *prison;
227 struct dm_kcopyd_client *copier;
229 struct workqueue_struct *wq;
230 struct throttle throttle;
231 struct work_struct worker;
232 struct delayed_work waker;
233 struct delayed_work no_space_timeout;
235 unsigned long last_commit_jiffies;
239 struct bio_list deferred_flush_bios;
240 struct list_head prepared_mappings;
241 struct list_head prepared_discards;
242 struct list_head active_thins;
244 struct dm_deferred_set *shared_read_ds;
245 struct dm_deferred_set *all_io_ds;
247 struct dm_thin_new_mapping *next_mapping;
248 mempool_t *mapping_pool;
250 process_bio_fn process_bio;
251 process_bio_fn process_discard;
253 process_cell_fn process_cell;
254 process_cell_fn process_discard_cell;
256 process_mapping_fn process_prepared_mapping;
257 process_mapping_fn process_prepared_discard;
259 struct dm_bio_prison_cell *cell_sort_array[CELL_SORT_ARRAY_SIZE];
262 static enum pool_mode get_pool_mode(struct pool *pool);
263 static void metadata_operation_failed(struct pool *pool, const char *op, int r);
266 * Target context for a pool.
269 struct dm_target *ti;
271 struct dm_dev *data_dev;
272 struct dm_dev *metadata_dev;
273 struct dm_target_callbacks callbacks;
275 dm_block_t low_water_blocks;
276 struct pool_features requested_pf; /* Features requested during table load */
277 struct pool_features adjusted_pf; /* Features used after adjusting for constituent devices */
281 * Target context for a thin.
284 struct list_head list;
285 struct dm_dev *pool_dev;
286 struct dm_dev *origin_dev;
287 sector_t origin_size;
291 struct dm_thin_device *td;
294 struct list_head deferred_cells;
295 struct bio_list deferred_bio_list;
296 struct bio_list retry_on_resume_list;
297 struct rb_root sort_bio_list; /* sorted list of deferred bios */
300 * Ensures the thin is not destroyed until the worker has finished
301 * iterating the active_thins list.
304 struct completion can_destroy;
307 /*----------------------------------------------------------------*/
310 * wake_worker() is used when new work is queued and when pool_resume is
311 * ready to continue deferred IO processing.
313 static void wake_worker(struct pool *pool)
315 queue_work(pool->wq, &pool->worker);
318 /*----------------------------------------------------------------*/
320 static int bio_detain(struct pool *pool, struct dm_cell_key *key, struct bio *bio,
321 struct dm_bio_prison_cell **cell_result)
324 struct dm_bio_prison_cell *cell_prealloc;
327 * Allocate a cell from the prison's mempool.
328 * This might block but it can't fail.
330 cell_prealloc = dm_bio_prison_alloc_cell(pool->prison, GFP_NOIO);
332 r = dm_bio_detain(pool->prison, key, bio, cell_prealloc, cell_result);
335 * We reused an old cell; we can get rid of
338 dm_bio_prison_free_cell(pool->prison, cell_prealloc);
343 static void cell_release(struct pool *pool,
344 struct dm_bio_prison_cell *cell,
345 struct bio_list *bios)
347 dm_cell_release(pool->prison, cell, bios);
348 dm_bio_prison_free_cell(pool->prison, cell);
351 static void cell_visit_release(struct pool *pool,
352 void (*fn)(void *, struct dm_bio_prison_cell *),
354 struct dm_bio_prison_cell *cell)
356 dm_cell_visit_release(pool->prison, fn, context, cell);
357 dm_bio_prison_free_cell(pool->prison, cell);
360 static void cell_release_no_holder(struct pool *pool,
361 struct dm_bio_prison_cell *cell,
362 struct bio_list *bios)
364 dm_cell_release_no_holder(pool->prison, cell, bios);
365 dm_bio_prison_free_cell(pool->prison, cell);
368 static void cell_error_with_code(struct pool *pool,
369 struct dm_bio_prison_cell *cell, int error_code)
371 dm_cell_error(pool->prison, cell, error_code);
372 dm_bio_prison_free_cell(pool->prison, cell);
375 static void cell_error(struct pool *pool, struct dm_bio_prison_cell *cell)
377 cell_error_with_code(pool, cell, -EIO);
380 static void cell_success(struct pool *pool, struct dm_bio_prison_cell *cell)
382 cell_error_with_code(pool, cell, 0);
385 static void cell_requeue(struct pool *pool, struct dm_bio_prison_cell *cell)
387 cell_error_with_code(pool, cell, DM_ENDIO_REQUEUE);
390 /*----------------------------------------------------------------*/
393 * A global list of pools that uses a struct mapped_device as a key.
395 static struct dm_thin_pool_table {
397 struct list_head pools;
398 } dm_thin_pool_table;
400 static void pool_table_init(void)
402 mutex_init(&dm_thin_pool_table.mutex);
403 INIT_LIST_HEAD(&dm_thin_pool_table.pools);
406 static void __pool_table_insert(struct pool *pool)
408 BUG_ON(!mutex_is_locked(&dm_thin_pool_table.mutex));
409 list_add(&pool->list, &dm_thin_pool_table.pools);
412 static void __pool_table_remove(struct pool *pool)
414 BUG_ON(!mutex_is_locked(&dm_thin_pool_table.mutex));
415 list_del(&pool->list);
418 static struct pool *__pool_table_lookup(struct mapped_device *md)
420 struct pool *pool = NULL, *tmp;
422 BUG_ON(!mutex_is_locked(&dm_thin_pool_table.mutex));
424 list_for_each_entry(tmp, &dm_thin_pool_table.pools, list) {
425 if (tmp->pool_md == md) {
434 static struct pool *__pool_table_lookup_metadata_dev(struct block_device *md_dev)
436 struct pool *pool = NULL, *tmp;
438 BUG_ON(!mutex_is_locked(&dm_thin_pool_table.mutex));
440 list_for_each_entry(tmp, &dm_thin_pool_table.pools, list) {
441 if (tmp->md_dev == md_dev) {
450 /*----------------------------------------------------------------*/
452 struct dm_thin_endio_hook {
454 struct dm_deferred_entry *shared_read_entry;
455 struct dm_deferred_entry *all_io_entry;
456 struct dm_thin_new_mapping *overwrite_mapping;
457 struct rb_node rb_node;
460 static void requeue_bio_list(struct thin_c *tc, struct bio_list *master)
463 struct bio_list bios;
466 bio_list_init(&bios);
468 spin_lock_irqsave(&tc->lock, flags);
469 bio_list_merge(&bios, master);
470 bio_list_init(master);
471 spin_unlock_irqrestore(&tc->lock, flags);
473 while ((bio = bio_list_pop(&bios)))
474 bio_endio(bio, DM_ENDIO_REQUEUE);
477 static void requeue_deferred_cells(struct thin_c *tc)
479 struct pool *pool = tc->pool;
481 struct list_head cells;
482 struct dm_bio_prison_cell *cell, *tmp;
484 INIT_LIST_HEAD(&cells);
486 spin_lock_irqsave(&tc->lock, flags);
487 list_splice_init(&tc->deferred_cells, &cells);
488 spin_unlock_irqrestore(&tc->lock, flags);
490 list_for_each_entry_safe(cell, tmp, &cells, user_list)
491 cell_requeue(pool, cell);
494 static void requeue_io(struct thin_c *tc)
496 requeue_bio_list(tc, &tc->deferred_bio_list);
497 requeue_bio_list(tc, &tc->retry_on_resume_list);
498 requeue_deferred_cells(tc);
501 static void error_thin_retry_list(struct thin_c *tc)
505 struct bio_list bios;
507 bio_list_init(&bios);
509 spin_lock_irqsave(&tc->lock, flags);
510 bio_list_merge(&bios, &tc->retry_on_resume_list);
511 bio_list_init(&tc->retry_on_resume_list);
512 spin_unlock_irqrestore(&tc->lock, flags);
514 while ((bio = bio_list_pop(&bios)))
518 static void error_retry_list(struct pool *pool)
523 list_for_each_entry_rcu(tc, &pool->active_thins, list)
524 error_thin_retry_list(tc);
529 * This section of code contains the logic for processing a thin device's IO.
530 * Much of the code depends on pool object resources (lists, workqueues, etc)
531 * but most is exclusively called from the thin target rather than the thin-pool
535 static bool block_size_is_power_of_two(struct pool *pool)
537 return pool->sectors_per_block_shift >= 0;
540 static dm_block_t get_bio_block(struct thin_c *tc, struct bio *bio)
542 struct pool *pool = tc->pool;
543 sector_t block_nr = bio->bi_iter.bi_sector;
545 if (block_size_is_power_of_two(pool))
546 block_nr >>= pool->sectors_per_block_shift;
548 (void) sector_div(block_nr, pool->sectors_per_block);
553 static void remap(struct thin_c *tc, struct bio *bio, dm_block_t block)
555 struct pool *pool = tc->pool;
556 sector_t bi_sector = bio->bi_iter.bi_sector;
558 bio->bi_bdev = tc->pool_dev->bdev;
559 if (block_size_is_power_of_two(pool))
560 bio->bi_iter.bi_sector =
561 (block << pool->sectors_per_block_shift) |
562 (bi_sector & (pool->sectors_per_block - 1));
564 bio->bi_iter.bi_sector = (block * pool->sectors_per_block) +
565 sector_div(bi_sector, pool->sectors_per_block);
568 static void remap_to_origin(struct thin_c *tc, struct bio *bio)
570 bio->bi_bdev = tc->origin_dev->bdev;
573 static int bio_triggers_commit(struct thin_c *tc, struct bio *bio)
575 return (bio->bi_rw & (REQ_FLUSH | REQ_FUA)) &&
576 dm_thin_changed_this_transaction(tc->td);
579 static void inc_all_io_entry(struct pool *pool, struct bio *bio)
581 struct dm_thin_endio_hook *h;
583 if (bio->bi_rw & REQ_DISCARD)
586 h = dm_per_bio_data(bio, sizeof(struct dm_thin_endio_hook));
587 h->all_io_entry = dm_deferred_entry_inc(pool->all_io_ds);
590 static void issue(struct thin_c *tc, struct bio *bio)
592 struct pool *pool = tc->pool;
595 if (!bio_triggers_commit(tc, bio)) {
596 generic_make_request(bio);
601 * Complete bio with an error if earlier I/O caused changes to
602 * the metadata that can't be committed e.g, due to I/O errors
603 * on the metadata device.
605 if (dm_thin_aborted_changes(tc->td)) {
611 * Batch together any bios that trigger commits and then issue a
612 * single commit for them in process_deferred_bios().
614 spin_lock_irqsave(&pool->lock, flags);
615 bio_list_add(&pool->deferred_flush_bios, bio);
616 spin_unlock_irqrestore(&pool->lock, flags);
619 static void remap_to_origin_and_issue(struct thin_c *tc, struct bio *bio)
621 remap_to_origin(tc, bio);
625 static void remap_and_issue(struct thin_c *tc, struct bio *bio,
628 remap(tc, bio, block);
632 /*----------------------------------------------------------------*/
635 * Bio endio functions.
637 struct dm_thin_new_mapping {
638 struct list_head list;
641 bool definitely_not_shared:1;
644 * Track quiescing, copying and zeroing preparation actions. When this
645 * counter hits zero the block is prepared and can be inserted into the
648 atomic_t prepare_actions;
652 dm_block_t virt_block;
653 dm_block_t data_block;
654 struct dm_bio_prison_cell *cell, *cell2;
657 * If the bio covers the whole area of a block then we can avoid
658 * zeroing or copying. Instead this bio is hooked. The bio will
659 * still be in the cell, so care has to be taken to avoid issuing
663 bio_end_io_t *saved_bi_end_io;
666 static void __complete_mapping_preparation(struct dm_thin_new_mapping *m)
668 struct pool *pool = m->tc->pool;
670 if (atomic_dec_and_test(&m->prepare_actions)) {
671 list_add_tail(&m->list, &pool->prepared_mappings);
676 static void complete_mapping_preparation(struct dm_thin_new_mapping *m)
679 struct pool *pool = m->tc->pool;
681 spin_lock_irqsave(&pool->lock, flags);
682 __complete_mapping_preparation(m);
683 spin_unlock_irqrestore(&pool->lock, flags);
686 static void copy_complete(int read_err, unsigned long write_err, void *context)
688 struct dm_thin_new_mapping *m = context;
690 m->err = read_err || write_err ? -EIO : 0;
691 complete_mapping_preparation(m);
694 static void overwrite_endio(struct bio *bio, int err)
696 struct dm_thin_endio_hook *h = dm_per_bio_data(bio, sizeof(struct dm_thin_endio_hook));
697 struct dm_thin_new_mapping *m = h->overwrite_mapping;
700 complete_mapping_preparation(m);
703 /*----------------------------------------------------------------*/
710 * Prepared mapping jobs.
714 * This sends the bios in the cell, except the original holder, back
715 * to the deferred_bios list.
717 static void cell_defer_no_holder(struct thin_c *tc, struct dm_bio_prison_cell *cell)
719 struct pool *pool = tc->pool;
722 spin_lock_irqsave(&tc->lock, flags);
723 cell_release_no_holder(pool, cell, &tc->deferred_bio_list);
724 spin_unlock_irqrestore(&tc->lock, flags);
729 static void thin_defer_bio(struct thin_c *tc, struct bio *bio);
733 struct bio_list defer_bios;
734 struct bio_list issue_bios;
737 static void __inc_remap_and_issue_cell(void *context,
738 struct dm_bio_prison_cell *cell)
740 struct remap_info *info = context;
743 while ((bio = bio_list_pop(&cell->bios))) {
744 if (bio->bi_rw & (REQ_DISCARD | REQ_FLUSH | REQ_FUA))
745 bio_list_add(&info->defer_bios, bio);
747 inc_all_io_entry(info->tc->pool, bio);
750 * We can't issue the bios with the bio prison lock
751 * held, so we add them to a list to issue on
752 * return from this function.
754 bio_list_add(&info->issue_bios, bio);
759 static void inc_remap_and_issue_cell(struct thin_c *tc,
760 struct dm_bio_prison_cell *cell,
764 struct remap_info info;
767 bio_list_init(&info.defer_bios);
768 bio_list_init(&info.issue_bios);
771 * We have to be careful to inc any bios we're about to issue
772 * before the cell is released, and avoid a race with new bios
773 * being added to the cell.
775 cell_visit_release(tc->pool, __inc_remap_and_issue_cell,
778 while ((bio = bio_list_pop(&info.defer_bios)))
779 thin_defer_bio(tc, bio);
781 while ((bio = bio_list_pop(&info.issue_bios)))
782 remap_and_issue(info.tc, bio, block);
785 static void process_prepared_mapping_fail(struct dm_thin_new_mapping *m)
788 m->bio->bi_end_io = m->saved_bi_end_io;
789 atomic_inc(&m->bio->bi_remaining);
791 cell_error(m->tc->pool, m->cell);
793 mempool_free(m, m->tc->pool->mapping_pool);
796 static void process_prepared_mapping(struct dm_thin_new_mapping *m)
798 struct thin_c *tc = m->tc;
799 struct pool *pool = tc->pool;
805 bio->bi_end_io = m->saved_bi_end_io;
806 atomic_inc(&bio->bi_remaining);
810 cell_error(pool, m->cell);
815 * Commit the prepared block into the mapping btree.
816 * Any I/O for this block arriving after this point will get
817 * remapped to it directly.
819 r = dm_thin_insert_block(tc->td, m->virt_block, m->data_block);
821 metadata_operation_failed(pool, "dm_thin_insert_block", r);
822 cell_error(pool, m->cell);
827 * Release any bios held while the block was being provisioned.
828 * If we are processing a write bio that completely covers the block,
829 * we already processed it so can ignore it now when processing
830 * the bios in the cell.
833 inc_remap_and_issue_cell(tc, m->cell, m->data_block);
836 inc_all_io_entry(tc->pool, m->cell->holder);
837 remap_and_issue(tc, m->cell->holder, m->data_block);
838 inc_remap_and_issue_cell(tc, m->cell, m->data_block);
843 mempool_free(m, pool->mapping_pool);
846 static void process_prepared_discard_fail(struct dm_thin_new_mapping *m)
848 struct thin_c *tc = m->tc;
850 bio_io_error(m->bio);
851 cell_defer_no_holder(tc, m->cell);
852 cell_defer_no_holder(tc, m->cell2);
853 mempool_free(m, tc->pool->mapping_pool);
856 static void process_prepared_discard_passdown(struct dm_thin_new_mapping *m)
858 struct thin_c *tc = m->tc;
860 inc_all_io_entry(tc->pool, m->bio);
861 cell_defer_no_holder(tc, m->cell);
862 cell_defer_no_holder(tc, m->cell2);
865 if (m->definitely_not_shared)
866 remap_and_issue(tc, m->bio, m->data_block);
869 if (dm_pool_block_is_used(tc->pool->pmd, m->data_block, &used) || used)
870 bio_endio(m->bio, 0);
872 remap_and_issue(tc, m->bio, m->data_block);
875 bio_endio(m->bio, 0);
877 mempool_free(m, tc->pool->mapping_pool);
880 static void process_prepared_discard(struct dm_thin_new_mapping *m)
883 struct thin_c *tc = m->tc;
885 r = dm_thin_remove_block(tc->td, m->virt_block);
887 DMERR_LIMIT("dm_thin_remove_block() failed");
889 process_prepared_discard_passdown(m);
892 static void process_prepared(struct pool *pool, struct list_head *head,
893 process_mapping_fn *fn)
896 struct list_head maps;
897 struct dm_thin_new_mapping *m, *tmp;
899 INIT_LIST_HEAD(&maps);
900 spin_lock_irqsave(&pool->lock, flags);
901 list_splice_init(head, &maps);
902 spin_unlock_irqrestore(&pool->lock, flags);
904 list_for_each_entry_safe(m, tmp, &maps, list)
911 static int io_overlaps_block(struct pool *pool, struct bio *bio)
913 return bio->bi_iter.bi_size ==
914 (pool->sectors_per_block << SECTOR_SHIFT);
917 static int io_overwrites_block(struct pool *pool, struct bio *bio)
919 return (bio_data_dir(bio) == WRITE) &&
920 io_overlaps_block(pool, bio);
923 static void save_and_set_endio(struct bio *bio, bio_end_io_t **save,
926 *save = bio->bi_end_io;
930 static int ensure_next_mapping(struct pool *pool)
932 if (pool->next_mapping)
935 pool->next_mapping = mempool_alloc(pool->mapping_pool, GFP_ATOMIC);
937 return pool->next_mapping ? 0 : -ENOMEM;
940 static struct dm_thin_new_mapping *get_next_mapping(struct pool *pool)
942 struct dm_thin_new_mapping *m = pool->next_mapping;
944 BUG_ON(!pool->next_mapping);
946 memset(m, 0, sizeof(struct dm_thin_new_mapping));
947 INIT_LIST_HEAD(&m->list);
950 pool->next_mapping = NULL;
955 static void ll_zero(struct thin_c *tc, struct dm_thin_new_mapping *m,
956 sector_t begin, sector_t end)
959 struct dm_io_region to;
961 to.bdev = tc->pool_dev->bdev;
963 to.count = end - begin;
965 r = dm_kcopyd_zero(tc->pool->copier, 1, &to, 0, copy_complete, m);
967 DMERR_LIMIT("dm_kcopyd_zero() failed");
968 copy_complete(1, 1, m);
972 static void remap_and_issue_overwrite(struct thin_c *tc, struct bio *bio,
973 dm_block_t data_block,
974 struct dm_thin_new_mapping *m)
976 struct pool *pool = tc->pool;
977 struct dm_thin_endio_hook *h = dm_per_bio_data(bio, sizeof(struct dm_thin_endio_hook));
979 h->overwrite_mapping = m;
981 save_and_set_endio(bio, &m->saved_bi_end_io, overwrite_endio);
982 inc_all_io_entry(pool, bio);
983 remap_and_issue(tc, bio, data_block);
987 * A partial copy also needs to zero the uncopied region.
989 static void schedule_copy(struct thin_c *tc, dm_block_t virt_block,
990 struct dm_dev *origin, dm_block_t data_origin,
991 dm_block_t data_dest,
992 struct dm_bio_prison_cell *cell, struct bio *bio,
996 struct pool *pool = tc->pool;
997 struct dm_thin_new_mapping *m = get_next_mapping(pool);
1000 m->virt_block = virt_block;
1001 m->data_block = data_dest;
1005 * quiesce action + copy action + an extra reference held for the
1006 * duration of this function (we may need to inc later for a
1009 atomic_set(&m->prepare_actions, 3);
1011 if (!dm_deferred_set_add_work(pool->shared_read_ds, &m->list))
1012 complete_mapping_preparation(m); /* already quiesced */
1015 * IO to pool_dev remaps to the pool target's data_dev.
1017 * If the whole block of data is being overwritten, we can issue the
1018 * bio immediately. Otherwise we use kcopyd to clone the data first.
1020 if (io_overwrites_block(pool, bio))
1021 remap_and_issue_overwrite(tc, bio, data_dest, m);
1023 struct dm_io_region from, to;
1025 from.bdev = origin->bdev;
1026 from.sector = data_origin * pool->sectors_per_block;
1029 to.bdev = tc->pool_dev->bdev;
1030 to.sector = data_dest * pool->sectors_per_block;
1033 r = dm_kcopyd_copy(pool->copier, &from, 1, &to,
1034 0, copy_complete, m);
1036 DMERR_LIMIT("dm_kcopyd_copy() failed");
1037 copy_complete(1, 1, m);
1040 * We allow the zero to be issued, to simplify the
1041 * error path. Otherwise we'd need to start
1042 * worrying about decrementing the prepare_actions
1048 * Do we need to zero a tail region?
1050 if (len < pool->sectors_per_block && pool->pf.zero_new_blocks) {
1051 atomic_inc(&m->prepare_actions);
1053 data_dest * pool->sectors_per_block + len,
1054 (data_dest + 1) * pool->sectors_per_block);
1058 complete_mapping_preparation(m); /* drop our ref */
1061 static void schedule_internal_copy(struct thin_c *tc, dm_block_t virt_block,
1062 dm_block_t data_origin, dm_block_t data_dest,
1063 struct dm_bio_prison_cell *cell, struct bio *bio)
1065 schedule_copy(tc, virt_block, tc->pool_dev,
1066 data_origin, data_dest, cell, bio,
1067 tc->pool->sectors_per_block);
1070 static void schedule_zero(struct thin_c *tc, dm_block_t virt_block,
1071 dm_block_t data_block, struct dm_bio_prison_cell *cell,
1074 struct pool *pool = tc->pool;
1075 struct dm_thin_new_mapping *m = get_next_mapping(pool);
1077 atomic_set(&m->prepare_actions, 1); /* no need to quiesce */
1079 m->virt_block = virt_block;
1080 m->data_block = data_block;
1084 * If the whole block of data is being overwritten or we are not
1085 * zeroing pre-existing data, we can issue the bio immediately.
1086 * Otherwise we use kcopyd to zero the data first.
1088 if (!pool->pf.zero_new_blocks)
1089 process_prepared_mapping(m);
1091 else if (io_overwrites_block(pool, bio))
1092 remap_and_issue_overwrite(tc, bio, data_block, m);
1096 data_block * pool->sectors_per_block,
1097 (data_block + 1) * pool->sectors_per_block);
1100 static void schedule_external_copy(struct thin_c *tc, dm_block_t virt_block,
1101 dm_block_t data_dest,
1102 struct dm_bio_prison_cell *cell, struct bio *bio)
1104 struct pool *pool = tc->pool;
1105 sector_t virt_block_begin = virt_block * pool->sectors_per_block;
1106 sector_t virt_block_end = (virt_block + 1) * pool->sectors_per_block;
1108 if (virt_block_end <= tc->origin_size)
1109 schedule_copy(tc, virt_block, tc->origin_dev,
1110 virt_block, data_dest, cell, bio,
1111 pool->sectors_per_block);
1113 else if (virt_block_begin < tc->origin_size)
1114 schedule_copy(tc, virt_block, tc->origin_dev,
1115 virt_block, data_dest, cell, bio,
1116 tc->origin_size - virt_block_begin);
1119 schedule_zero(tc, virt_block, data_dest, cell, bio);
1123 * A non-zero return indicates read_only or fail_io mode.
1124 * Many callers don't care about the return value.
1126 static int commit(struct pool *pool)
1130 if (get_pool_mode(pool) >= PM_READ_ONLY)
1133 r = dm_pool_commit_metadata(pool->pmd);
1135 metadata_operation_failed(pool, "dm_pool_commit_metadata", r);
1140 static void check_low_water_mark(struct pool *pool, dm_block_t free_blocks)
1142 unsigned long flags;
1144 if (free_blocks <= pool->low_water_blocks && !pool->low_water_triggered) {
1145 DMWARN("%s: reached low water mark for data device: sending event.",
1146 dm_device_name(pool->pool_md));
1147 spin_lock_irqsave(&pool->lock, flags);
1148 pool->low_water_triggered = true;
1149 spin_unlock_irqrestore(&pool->lock, flags);
1150 dm_table_event(pool->ti->table);
1154 static void set_pool_mode(struct pool *pool, enum pool_mode new_mode);
1156 static int alloc_data_block(struct thin_c *tc, dm_block_t *result)
1159 dm_block_t free_blocks;
1160 struct pool *pool = tc->pool;
1162 if (WARN_ON(get_pool_mode(pool) != PM_WRITE))
1165 r = dm_pool_get_free_block_count(pool->pmd, &free_blocks);
1167 metadata_operation_failed(pool, "dm_pool_get_free_block_count", r);
1171 check_low_water_mark(pool, free_blocks);
1175 * Try to commit to see if that will free up some
1182 r = dm_pool_get_free_block_count(pool->pmd, &free_blocks);
1184 metadata_operation_failed(pool, "dm_pool_get_free_block_count", r);
1189 set_pool_mode(pool, PM_OUT_OF_DATA_SPACE);
1194 r = dm_pool_alloc_data_block(pool->pmd, result);
1196 metadata_operation_failed(pool, "dm_pool_alloc_data_block", r);
1204 * If we have run out of space, queue bios until the device is
1205 * resumed, presumably after having been reloaded with more space.
1207 static void retry_on_resume(struct bio *bio)
1209 struct dm_thin_endio_hook *h = dm_per_bio_data(bio, sizeof(struct dm_thin_endio_hook));
1210 struct thin_c *tc = h->tc;
1211 unsigned long flags;
1213 spin_lock_irqsave(&tc->lock, flags);
1214 bio_list_add(&tc->retry_on_resume_list, bio);
1215 spin_unlock_irqrestore(&tc->lock, flags);
1218 static int should_error_unserviceable_bio(struct pool *pool)
1220 enum pool_mode m = get_pool_mode(pool);
1224 /* Shouldn't get here */
1225 DMERR_LIMIT("bio unserviceable, yet pool is in PM_WRITE mode");
1228 case PM_OUT_OF_DATA_SPACE:
1229 return pool->pf.error_if_no_space ? -ENOSPC : 0;
1235 /* Shouldn't get here */
1236 DMERR_LIMIT("bio unserviceable, yet pool has an unknown mode");
1241 static void handle_unserviceable_bio(struct pool *pool, struct bio *bio)
1243 int error = should_error_unserviceable_bio(pool);
1246 bio_endio(bio, error);
1248 retry_on_resume(bio);
1251 static void retry_bios_on_resume(struct pool *pool, struct dm_bio_prison_cell *cell)
1254 struct bio_list bios;
1257 error = should_error_unserviceable_bio(pool);
1259 cell_error_with_code(pool, cell, error);
1263 bio_list_init(&bios);
1264 cell_release(pool, cell, &bios);
1266 while ((bio = bio_list_pop(&bios)))
1267 retry_on_resume(bio);
1270 static void process_discard_cell(struct thin_c *tc, struct dm_bio_prison_cell *cell)
1273 struct bio *bio = cell->holder;
1274 struct pool *pool = tc->pool;
1275 struct dm_bio_prison_cell *cell2;
1276 struct dm_cell_key key2;
1277 dm_block_t block = get_bio_block(tc, bio);
1278 struct dm_thin_lookup_result lookup_result;
1279 struct dm_thin_new_mapping *m;
1281 if (tc->requeue_mode) {
1282 cell_requeue(pool, cell);
1286 r = dm_thin_find_block(tc->td, block, 1, &lookup_result);
1290 * Check nobody is fiddling with this pool block. This can
1291 * happen if someone's in the process of breaking sharing
1294 build_data_key(tc->td, lookup_result.block, &key2);
1295 if (bio_detain(tc->pool, &key2, bio, &cell2)) {
1296 cell_defer_no_holder(tc, cell);
1300 if (io_overlaps_block(pool, bio)) {
1302 * IO may still be going to the destination block. We must
1303 * quiesce before we can do the removal.
1305 m = get_next_mapping(pool);
1307 m->pass_discard = pool->pf.discard_passdown;
1308 m->definitely_not_shared = !lookup_result.shared;
1309 m->virt_block = block;
1310 m->data_block = lookup_result.block;
1315 if (!dm_deferred_set_add_work(pool->all_io_ds, &m->list))
1316 pool->process_prepared_discard(m);
1319 inc_all_io_entry(pool, bio);
1320 cell_defer_no_holder(tc, cell);
1321 cell_defer_no_holder(tc, cell2);
1324 * The DM core makes sure that the discard doesn't span
1325 * a block boundary. So we submit the discard of a
1326 * partial block appropriately.
1328 if ((!lookup_result.shared) && pool->pf.discard_passdown)
1329 remap_and_issue(tc, bio, lookup_result.block);
1337 * It isn't provisioned, just forget it.
1339 cell_defer_no_holder(tc, cell);
1344 DMERR_LIMIT("%s: dm_thin_find_block() failed: error = %d",
1346 cell_defer_no_holder(tc, cell);
1352 static void process_discard_bio(struct thin_c *tc, struct bio *bio)
1354 struct dm_bio_prison_cell *cell;
1355 struct dm_cell_key key;
1356 dm_block_t block = get_bio_block(tc, bio);
1358 build_virtual_key(tc->td, block, &key);
1359 if (bio_detain(tc->pool, &key, bio, &cell))
1362 process_discard_cell(tc, cell);
1365 static void break_sharing(struct thin_c *tc, struct bio *bio, dm_block_t block,
1366 struct dm_cell_key *key,
1367 struct dm_thin_lookup_result *lookup_result,
1368 struct dm_bio_prison_cell *cell)
1371 dm_block_t data_block;
1372 struct pool *pool = tc->pool;
1374 r = alloc_data_block(tc, &data_block);
1377 schedule_internal_copy(tc, block, lookup_result->block,
1378 data_block, cell, bio);
1382 retry_bios_on_resume(pool, cell);
1386 DMERR_LIMIT("%s: alloc_data_block() failed: error = %d",
1388 cell_error(pool, cell);
1393 static void __remap_and_issue_shared_cell(void *context,
1394 struct dm_bio_prison_cell *cell)
1396 struct remap_info *info = context;
1399 while ((bio = bio_list_pop(&cell->bios))) {
1400 if ((bio_data_dir(bio) == WRITE) ||
1401 (bio->bi_rw & (REQ_DISCARD | REQ_FLUSH | REQ_FUA)))
1402 bio_list_add(&info->defer_bios, bio);
1404 struct dm_thin_endio_hook *h = dm_per_bio_data(bio, sizeof(struct dm_thin_endio_hook));;
1406 h->shared_read_entry = dm_deferred_entry_inc(info->tc->pool->shared_read_ds);
1407 inc_all_io_entry(info->tc->pool, bio);
1408 bio_list_add(&info->issue_bios, bio);
1413 static void remap_and_issue_shared_cell(struct thin_c *tc,
1414 struct dm_bio_prison_cell *cell,
1418 struct remap_info info;
1421 bio_list_init(&info.defer_bios);
1422 bio_list_init(&info.issue_bios);
1424 cell_visit_release(tc->pool, __remap_and_issue_shared_cell,
1427 while ((bio = bio_list_pop(&info.defer_bios)))
1428 thin_defer_bio(tc, bio);
1430 while ((bio = bio_list_pop(&info.issue_bios)))
1431 remap_and_issue(tc, bio, block);
1434 static void process_shared_bio(struct thin_c *tc, struct bio *bio,
1436 struct dm_thin_lookup_result *lookup_result,
1437 struct dm_bio_prison_cell *virt_cell)
1439 struct dm_bio_prison_cell *data_cell;
1440 struct pool *pool = tc->pool;
1441 struct dm_cell_key key;
1444 * If cell is already occupied, then sharing is already in the process
1445 * of being broken so we have nothing further to do here.
1447 build_data_key(tc->td, lookup_result->block, &key);
1448 if (bio_detain(pool, &key, bio, &data_cell)) {
1449 cell_defer_no_holder(tc, virt_cell);
1453 if (bio_data_dir(bio) == WRITE && bio->bi_iter.bi_size) {
1454 break_sharing(tc, bio, block, &key, lookup_result, data_cell);
1455 cell_defer_no_holder(tc, virt_cell);
1457 struct dm_thin_endio_hook *h = dm_per_bio_data(bio, sizeof(struct dm_thin_endio_hook));
1459 h->shared_read_entry = dm_deferred_entry_inc(pool->shared_read_ds);
1460 inc_all_io_entry(pool, bio);
1461 remap_and_issue(tc, bio, lookup_result->block);
1463 remap_and_issue_shared_cell(tc, data_cell, lookup_result->block);
1464 remap_and_issue_shared_cell(tc, virt_cell, lookup_result->block);
1468 static void provision_block(struct thin_c *tc, struct bio *bio, dm_block_t block,
1469 struct dm_bio_prison_cell *cell)
1472 dm_block_t data_block;
1473 struct pool *pool = tc->pool;
1476 * Remap empty bios (flushes) immediately, without provisioning.
1478 if (!bio->bi_iter.bi_size) {
1479 inc_all_io_entry(pool, bio);
1480 cell_defer_no_holder(tc, cell);
1482 remap_and_issue(tc, bio, 0);
1487 * Fill read bios with zeroes and complete them immediately.
1489 if (bio_data_dir(bio) == READ) {
1491 cell_defer_no_holder(tc, cell);
1496 r = alloc_data_block(tc, &data_block);
1500 schedule_external_copy(tc, block, data_block, cell, bio);
1502 schedule_zero(tc, block, data_block, cell, bio);
1506 retry_bios_on_resume(pool, cell);
1510 DMERR_LIMIT("%s: alloc_data_block() failed: error = %d",
1512 cell_error(pool, cell);
1517 static void process_cell(struct thin_c *tc, struct dm_bio_prison_cell *cell)
1520 struct pool *pool = tc->pool;
1521 struct bio *bio = cell->holder;
1522 dm_block_t block = get_bio_block(tc, bio);
1523 struct dm_thin_lookup_result lookup_result;
1525 if (tc->requeue_mode) {
1526 cell_requeue(pool, cell);
1530 r = dm_thin_find_block(tc->td, block, 1, &lookup_result);
1533 if (lookup_result.shared)
1534 process_shared_bio(tc, bio, block, &lookup_result, cell);
1536 inc_all_io_entry(pool, bio);
1537 remap_and_issue(tc, bio, lookup_result.block);
1538 inc_remap_and_issue_cell(tc, cell, lookup_result.block);
1543 if (bio_data_dir(bio) == READ && tc->origin_dev) {
1544 inc_all_io_entry(pool, bio);
1545 cell_defer_no_holder(tc, cell);
1547 if (bio_end_sector(bio) <= tc->origin_size)
1548 remap_to_origin_and_issue(tc, bio);
1550 else if (bio->bi_iter.bi_sector < tc->origin_size) {
1552 bio->bi_iter.bi_size = (tc->origin_size - bio->bi_iter.bi_sector) << SECTOR_SHIFT;
1553 remap_to_origin_and_issue(tc, bio);
1560 provision_block(tc, bio, block, cell);
1564 DMERR_LIMIT("%s: dm_thin_find_block() failed: error = %d",
1566 cell_defer_no_holder(tc, cell);
1572 static void process_bio(struct thin_c *tc, struct bio *bio)
1574 struct pool *pool = tc->pool;
1575 dm_block_t block = get_bio_block(tc, bio);
1576 struct dm_bio_prison_cell *cell;
1577 struct dm_cell_key key;
1580 * If cell is already occupied, then the block is already
1581 * being provisioned so we have nothing further to do here.
1583 build_virtual_key(tc->td, block, &key);
1584 if (bio_detain(pool, &key, bio, &cell))
1587 process_cell(tc, cell);
1590 static void __process_bio_read_only(struct thin_c *tc, struct bio *bio,
1591 struct dm_bio_prison_cell *cell)
1594 int rw = bio_data_dir(bio);
1595 dm_block_t block = get_bio_block(tc, bio);
1596 struct dm_thin_lookup_result lookup_result;
1598 r = dm_thin_find_block(tc->td, block, 1, &lookup_result);
1601 if (lookup_result.shared && (rw == WRITE) && bio->bi_iter.bi_size) {
1602 handle_unserviceable_bio(tc->pool, bio);
1604 cell_defer_no_holder(tc, cell);
1606 inc_all_io_entry(tc->pool, bio);
1607 remap_and_issue(tc, bio, lookup_result.block);
1609 inc_remap_and_issue_cell(tc, cell, lookup_result.block);
1615 cell_defer_no_holder(tc, cell);
1617 handle_unserviceable_bio(tc->pool, bio);
1621 if (tc->origin_dev) {
1622 inc_all_io_entry(tc->pool, bio);
1623 remap_to_origin_and_issue(tc, bio);
1632 DMERR_LIMIT("%s: dm_thin_find_block() failed: error = %d",
1635 cell_defer_no_holder(tc, cell);
1641 static void process_bio_read_only(struct thin_c *tc, struct bio *bio)
1643 __process_bio_read_only(tc, bio, NULL);
1646 static void process_cell_read_only(struct thin_c *tc, struct dm_bio_prison_cell *cell)
1648 __process_bio_read_only(tc, cell->holder, cell);
1651 static void process_bio_success(struct thin_c *tc, struct bio *bio)
1656 static void process_bio_fail(struct thin_c *tc, struct bio *bio)
1661 static void process_cell_success(struct thin_c *tc, struct dm_bio_prison_cell *cell)
1663 cell_success(tc->pool, cell);
1666 static void process_cell_fail(struct thin_c *tc, struct dm_bio_prison_cell *cell)
1668 cell_error(tc->pool, cell);
1672 * FIXME: should we also commit due to size of transaction, measured in
1675 static int need_commit_due_to_time(struct pool *pool)
1677 return jiffies < pool->last_commit_jiffies ||
1678 jiffies > pool->last_commit_jiffies + COMMIT_PERIOD;
1681 #define thin_pbd(node) rb_entry((node), struct dm_thin_endio_hook, rb_node)
1682 #define thin_bio(pbd) dm_bio_from_per_bio_data((pbd), sizeof(struct dm_thin_endio_hook))
1684 static void __thin_bio_rb_add(struct thin_c *tc, struct bio *bio)
1686 struct rb_node **rbp, *parent;
1687 struct dm_thin_endio_hook *pbd;
1688 sector_t bi_sector = bio->bi_iter.bi_sector;
1690 rbp = &tc->sort_bio_list.rb_node;
1694 pbd = thin_pbd(parent);
1696 if (bi_sector < thin_bio(pbd)->bi_iter.bi_sector)
1697 rbp = &(*rbp)->rb_left;
1699 rbp = &(*rbp)->rb_right;
1702 pbd = dm_per_bio_data(bio, sizeof(struct dm_thin_endio_hook));
1703 rb_link_node(&pbd->rb_node, parent, rbp);
1704 rb_insert_color(&pbd->rb_node, &tc->sort_bio_list);
1707 static void __extract_sorted_bios(struct thin_c *tc)
1709 struct rb_node *node;
1710 struct dm_thin_endio_hook *pbd;
1713 for (node = rb_first(&tc->sort_bio_list); node; node = rb_next(node)) {
1714 pbd = thin_pbd(node);
1715 bio = thin_bio(pbd);
1717 bio_list_add(&tc->deferred_bio_list, bio);
1718 rb_erase(&pbd->rb_node, &tc->sort_bio_list);
1721 WARN_ON(!RB_EMPTY_ROOT(&tc->sort_bio_list));
1724 static void __sort_thin_deferred_bios(struct thin_c *tc)
1727 struct bio_list bios;
1729 bio_list_init(&bios);
1730 bio_list_merge(&bios, &tc->deferred_bio_list);
1731 bio_list_init(&tc->deferred_bio_list);
1733 /* Sort deferred_bio_list using rb-tree */
1734 while ((bio = bio_list_pop(&bios)))
1735 __thin_bio_rb_add(tc, bio);
1738 * Transfer the sorted bios in sort_bio_list back to
1739 * deferred_bio_list to allow lockless submission of
1742 __extract_sorted_bios(tc);
1745 static void process_thin_deferred_bios(struct thin_c *tc)
1747 struct pool *pool = tc->pool;
1748 unsigned long flags;
1750 struct bio_list bios;
1751 struct blk_plug plug;
1754 if (tc->requeue_mode) {
1755 requeue_bio_list(tc, &tc->deferred_bio_list);
1759 bio_list_init(&bios);
1761 spin_lock_irqsave(&tc->lock, flags);
1763 if (bio_list_empty(&tc->deferred_bio_list)) {
1764 spin_unlock_irqrestore(&tc->lock, flags);
1768 __sort_thin_deferred_bios(tc);
1770 bio_list_merge(&bios, &tc->deferred_bio_list);
1771 bio_list_init(&tc->deferred_bio_list);
1773 spin_unlock_irqrestore(&tc->lock, flags);
1775 blk_start_plug(&plug);
1776 while ((bio = bio_list_pop(&bios))) {
1778 * If we've got no free new_mapping structs, and processing
1779 * this bio might require one, we pause until there are some
1780 * prepared mappings to process.
1782 if (ensure_next_mapping(pool)) {
1783 spin_lock_irqsave(&tc->lock, flags);
1784 bio_list_add(&tc->deferred_bio_list, bio);
1785 bio_list_merge(&tc->deferred_bio_list, &bios);
1786 spin_unlock_irqrestore(&tc->lock, flags);
1790 if (bio->bi_rw & REQ_DISCARD)
1791 pool->process_discard(tc, bio);
1793 pool->process_bio(tc, bio);
1795 if ((count++ & 127) == 0) {
1796 throttle_work_update(&pool->throttle);
1797 dm_pool_issue_prefetches(pool->pmd);
1800 blk_finish_plug(&plug);
1803 static int cmp_cells(const void *lhs, const void *rhs)
1805 struct dm_bio_prison_cell *lhs_cell = *((struct dm_bio_prison_cell **) lhs);
1806 struct dm_bio_prison_cell *rhs_cell = *((struct dm_bio_prison_cell **) rhs);
1808 BUG_ON(!lhs_cell->holder);
1809 BUG_ON(!rhs_cell->holder);
1811 if (lhs_cell->holder->bi_iter.bi_sector < rhs_cell->holder->bi_iter.bi_sector)
1814 if (lhs_cell->holder->bi_iter.bi_sector > rhs_cell->holder->bi_iter.bi_sector)
1820 static unsigned sort_cells(struct pool *pool, struct list_head *cells)
1823 struct dm_bio_prison_cell *cell, *tmp;
1825 list_for_each_entry_safe(cell, tmp, cells, user_list) {
1826 if (count >= CELL_SORT_ARRAY_SIZE)
1829 pool->cell_sort_array[count++] = cell;
1830 list_del(&cell->user_list);
1833 sort(pool->cell_sort_array, count, sizeof(cell), cmp_cells, NULL);
1838 static void process_thin_deferred_cells(struct thin_c *tc)
1840 struct pool *pool = tc->pool;
1841 unsigned long flags;
1842 struct list_head cells;
1843 struct dm_bio_prison_cell *cell;
1844 unsigned i, j, count;
1846 INIT_LIST_HEAD(&cells);
1848 spin_lock_irqsave(&tc->lock, flags);
1849 list_splice_init(&tc->deferred_cells, &cells);
1850 spin_unlock_irqrestore(&tc->lock, flags);
1852 if (list_empty(&cells))
1856 count = sort_cells(tc->pool, &cells);
1858 for (i = 0; i < count; i++) {
1859 cell = pool->cell_sort_array[i];
1860 BUG_ON(!cell->holder);
1863 * If we've got no free new_mapping structs, and processing
1864 * this bio might require one, we pause until there are some
1865 * prepared mappings to process.
1867 if (ensure_next_mapping(pool)) {
1868 for (j = i; j < count; j++)
1869 list_add(&pool->cell_sort_array[j]->user_list, &cells);
1871 spin_lock_irqsave(&tc->lock, flags);
1872 list_splice(&cells, &tc->deferred_cells);
1873 spin_unlock_irqrestore(&tc->lock, flags);
1877 if (cell->holder->bi_rw & REQ_DISCARD)
1878 pool->process_discard_cell(tc, cell);
1880 pool->process_cell(tc, cell);
1882 } while (!list_empty(&cells));
1885 static void thin_get(struct thin_c *tc);
1886 static void thin_put(struct thin_c *tc);
1889 * We can't hold rcu_read_lock() around code that can block. So we
1890 * find a thin with the rcu lock held; bump a refcount; then drop
1893 static struct thin_c *get_first_thin(struct pool *pool)
1895 struct thin_c *tc = NULL;
1898 if (!list_empty(&pool->active_thins)) {
1899 tc = list_entry_rcu(pool->active_thins.next, struct thin_c, list);
1907 static struct thin_c *get_next_thin(struct pool *pool, struct thin_c *tc)
1909 struct thin_c *old_tc = tc;
1912 list_for_each_entry_continue_rcu(tc, &pool->active_thins, list) {
1924 static void process_deferred_bios(struct pool *pool)
1926 unsigned long flags;
1928 struct bio_list bios;
1931 tc = get_first_thin(pool);
1933 process_thin_deferred_cells(tc);
1934 process_thin_deferred_bios(tc);
1935 tc = get_next_thin(pool, tc);
1939 * If there are any deferred flush bios, we must commit
1940 * the metadata before issuing them.
1942 bio_list_init(&bios);
1943 spin_lock_irqsave(&pool->lock, flags);
1944 bio_list_merge(&bios, &pool->deferred_flush_bios);
1945 bio_list_init(&pool->deferred_flush_bios);
1946 spin_unlock_irqrestore(&pool->lock, flags);
1948 if (bio_list_empty(&bios) &&
1949 !(dm_pool_changed_this_transaction(pool->pmd) && need_commit_due_to_time(pool)))
1953 while ((bio = bio_list_pop(&bios)))
1957 pool->last_commit_jiffies = jiffies;
1959 while ((bio = bio_list_pop(&bios)))
1960 generic_make_request(bio);
1963 static void do_worker(struct work_struct *ws)
1965 struct pool *pool = container_of(ws, struct pool, worker);
1967 throttle_work_start(&pool->throttle);
1968 dm_pool_issue_prefetches(pool->pmd);
1969 throttle_work_update(&pool->throttle);
1970 process_prepared(pool, &pool->prepared_mappings, &pool->process_prepared_mapping);
1971 throttle_work_update(&pool->throttle);
1972 process_prepared(pool, &pool->prepared_discards, &pool->process_prepared_discard);
1973 throttle_work_update(&pool->throttle);
1974 process_deferred_bios(pool);
1975 throttle_work_complete(&pool->throttle);
1979 * We want to commit periodically so that not too much
1980 * unwritten data builds up.
1982 static void do_waker(struct work_struct *ws)
1984 struct pool *pool = container_of(to_delayed_work(ws), struct pool, waker);
1986 queue_delayed_work(pool->wq, &pool->waker, COMMIT_PERIOD);
1990 * We're holding onto IO to allow userland time to react. After the
1991 * timeout either the pool will have been resized (and thus back in
1992 * PM_WRITE mode), or we degrade to PM_READ_ONLY and start erroring IO.
1994 static void do_no_space_timeout(struct work_struct *ws)
1996 struct pool *pool = container_of(to_delayed_work(ws), struct pool,
1999 if (get_pool_mode(pool) == PM_OUT_OF_DATA_SPACE && !pool->pf.error_if_no_space)
2000 set_pool_mode(pool, PM_READ_ONLY);
2003 /*----------------------------------------------------------------*/
2006 struct work_struct worker;
2007 struct completion complete;
2010 static struct pool_work *to_pool_work(struct work_struct *ws)
2012 return container_of(ws, struct pool_work, worker);
2015 static void pool_work_complete(struct pool_work *pw)
2017 complete(&pw->complete);
2020 static void pool_work_wait(struct pool_work *pw, struct pool *pool,
2021 void (*fn)(struct work_struct *))
2023 INIT_WORK_ONSTACK(&pw->worker, fn);
2024 init_completion(&pw->complete);
2025 queue_work(pool->wq, &pw->worker);
2026 wait_for_completion(&pw->complete);
2029 /*----------------------------------------------------------------*/
2031 struct noflush_work {
2032 struct pool_work pw;
2036 static struct noflush_work *to_noflush(struct work_struct *ws)
2038 return container_of(to_pool_work(ws), struct noflush_work, pw);
2041 static void do_noflush_start(struct work_struct *ws)
2043 struct noflush_work *w = to_noflush(ws);
2044 w->tc->requeue_mode = true;
2046 pool_work_complete(&w->pw);
2049 static void do_noflush_stop(struct work_struct *ws)
2051 struct noflush_work *w = to_noflush(ws);
2052 w->tc->requeue_mode = false;
2053 pool_work_complete(&w->pw);
2056 static void noflush_work(struct thin_c *tc, void (*fn)(struct work_struct *))
2058 struct noflush_work w;
2061 pool_work_wait(&w.pw, tc->pool, fn);
2064 /*----------------------------------------------------------------*/
2066 static enum pool_mode get_pool_mode(struct pool *pool)
2068 return pool->pf.mode;
2071 static void notify_of_pool_mode_change(struct pool *pool, const char *new_mode)
2073 dm_table_event(pool->ti->table);
2074 DMINFO("%s: switching pool to %s mode",
2075 dm_device_name(pool->pool_md), new_mode);
2078 static void set_pool_mode(struct pool *pool, enum pool_mode new_mode)
2080 struct pool_c *pt = pool->ti->private;
2081 bool needs_check = dm_pool_metadata_needs_check(pool->pmd);
2082 enum pool_mode old_mode = get_pool_mode(pool);
2083 unsigned long no_space_timeout = ACCESS_ONCE(no_space_timeout_secs) * HZ;
2086 * Never allow the pool to transition to PM_WRITE mode if user
2087 * intervention is required to verify metadata and data consistency.
2089 if (new_mode == PM_WRITE && needs_check) {
2090 DMERR("%s: unable to switch pool to write mode until repaired.",
2091 dm_device_name(pool->pool_md));
2092 if (old_mode != new_mode)
2093 new_mode = old_mode;
2095 new_mode = PM_READ_ONLY;
2098 * If we were in PM_FAIL mode, rollback of metadata failed. We're
2099 * not going to recover without a thin_repair. So we never let the
2100 * pool move out of the old mode.
2102 if (old_mode == PM_FAIL)
2103 new_mode = old_mode;
2107 if (old_mode != new_mode)
2108 notify_of_pool_mode_change(pool, "failure");
2109 dm_pool_metadata_read_only(pool->pmd);
2110 pool->process_bio = process_bio_fail;
2111 pool->process_discard = process_bio_fail;
2112 pool->process_cell = process_cell_fail;
2113 pool->process_discard_cell = process_cell_fail;
2114 pool->process_prepared_mapping = process_prepared_mapping_fail;
2115 pool->process_prepared_discard = process_prepared_discard_fail;
2117 error_retry_list(pool);
2121 if (old_mode != new_mode)
2122 notify_of_pool_mode_change(pool, "read-only");
2123 dm_pool_metadata_read_only(pool->pmd);
2124 pool->process_bio = process_bio_read_only;
2125 pool->process_discard = process_bio_success;
2126 pool->process_cell = process_cell_read_only;
2127 pool->process_discard_cell = process_cell_success;
2128 pool->process_prepared_mapping = process_prepared_mapping_fail;
2129 pool->process_prepared_discard = process_prepared_discard_passdown;
2131 error_retry_list(pool);
2134 case PM_OUT_OF_DATA_SPACE:
2136 * Ideally we'd never hit this state; the low water mark
2137 * would trigger userland to extend the pool before we
2138 * completely run out of data space. However, many small
2139 * IOs to unprovisioned space can consume data space at an
2140 * alarming rate. Adjust your low water mark if you're
2141 * frequently seeing this mode.
2143 if (old_mode != new_mode)
2144 notify_of_pool_mode_change(pool, "out-of-data-space");
2145 pool->process_bio = process_bio_read_only;
2146 pool->process_discard = process_discard_bio;
2147 pool->process_cell = process_cell_read_only;
2148 pool->process_discard_cell = process_discard_cell;
2149 pool->process_prepared_mapping = process_prepared_mapping;
2150 pool->process_prepared_discard = process_prepared_discard_passdown;
2152 if (!pool->pf.error_if_no_space && no_space_timeout)
2153 queue_delayed_work(pool->wq, &pool->no_space_timeout, no_space_timeout);
2157 if (old_mode != new_mode)
2158 notify_of_pool_mode_change(pool, "write");
2159 dm_pool_metadata_read_write(pool->pmd);
2160 pool->process_bio = process_bio;
2161 pool->process_discard = process_discard_bio;
2162 pool->process_cell = process_cell;
2163 pool->process_discard_cell = process_discard_cell;
2164 pool->process_prepared_mapping = process_prepared_mapping;
2165 pool->process_prepared_discard = process_prepared_discard;
2169 pool->pf.mode = new_mode;
2171 * The pool mode may have changed, sync it so bind_control_target()
2172 * doesn't cause an unexpected mode transition on resume.
2174 pt->adjusted_pf.mode = new_mode;
2177 static void abort_transaction(struct pool *pool)
2179 const char *dev_name = dm_device_name(pool->pool_md);
2181 DMERR_LIMIT("%s: aborting current metadata transaction", dev_name);
2182 if (dm_pool_abort_metadata(pool->pmd)) {
2183 DMERR("%s: failed to abort metadata transaction", dev_name);
2184 set_pool_mode(pool, PM_FAIL);
2187 if (dm_pool_metadata_set_needs_check(pool->pmd)) {
2188 DMERR("%s: failed to set 'needs_check' flag in metadata", dev_name);
2189 set_pool_mode(pool, PM_FAIL);
2193 static void metadata_operation_failed(struct pool *pool, const char *op, int r)
2195 DMERR_LIMIT("%s: metadata operation '%s' failed: error = %d",
2196 dm_device_name(pool->pool_md), op, r);
2198 abort_transaction(pool);
2199 set_pool_mode(pool, PM_READ_ONLY);
2202 /*----------------------------------------------------------------*/
2205 * Mapping functions.
2209 * Called only while mapping a thin bio to hand it over to the workqueue.
2211 static void thin_defer_bio(struct thin_c *tc, struct bio *bio)
2213 unsigned long flags;
2214 struct pool *pool = tc->pool;
2216 spin_lock_irqsave(&tc->lock, flags);
2217 bio_list_add(&tc->deferred_bio_list, bio);
2218 spin_unlock_irqrestore(&tc->lock, flags);
2223 static void thin_defer_bio_with_throttle(struct thin_c *tc, struct bio *bio)
2225 struct pool *pool = tc->pool;
2227 throttle_lock(&pool->throttle);
2228 thin_defer_bio(tc, bio);
2229 throttle_unlock(&pool->throttle);
2232 static void thin_defer_cell(struct thin_c *tc, struct dm_bio_prison_cell *cell)
2234 unsigned long flags;
2235 struct pool *pool = tc->pool;
2237 throttle_lock(&pool->throttle);
2238 spin_lock_irqsave(&tc->lock, flags);
2239 list_add_tail(&cell->user_list, &tc->deferred_cells);
2240 spin_unlock_irqrestore(&tc->lock, flags);
2241 throttle_unlock(&pool->throttle);
2246 static void thin_hook_bio(struct thin_c *tc, struct bio *bio)
2248 struct dm_thin_endio_hook *h = dm_per_bio_data(bio, sizeof(struct dm_thin_endio_hook));
2251 h->shared_read_entry = NULL;
2252 h->all_io_entry = NULL;
2253 h->overwrite_mapping = NULL;
2257 * Non-blocking function called from the thin target's map function.
2259 static int thin_bio_map(struct dm_target *ti, struct bio *bio)
2262 struct thin_c *tc = ti->private;
2263 dm_block_t block = get_bio_block(tc, bio);
2264 struct dm_thin_device *td = tc->td;
2265 struct dm_thin_lookup_result result;
2266 struct dm_bio_prison_cell *virt_cell, *data_cell;
2267 struct dm_cell_key key;
2269 thin_hook_bio(tc, bio);
2271 if (tc->requeue_mode) {
2272 bio_endio(bio, DM_ENDIO_REQUEUE);
2273 return DM_MAPIO_SUBMITTED;
2276 if (get_pool_mode(tc->pool) == PM_FAIL) {
2278 return DM_MAPIO_SUBMITTED;
2281 if (bio->bi_rw & (REQ_DISCARD | REQ_FLUSH | REQ_FUA)) {
2282 thin_defer_bio_with_throttle(tc, bio);
2283 return DM_MAPIO_SUBMITTED;
2287 * We must hold the virtual cell before doing the lookup, otherwise
2288 * there's a race with discard.
2290 build_virtual_key(tc->td, block, &key);
2291 if (bio_detain(tc->pool, &key, bio, &virt_cell))
2292 return DM_MAPIO_SUBMITTED;
2294 r = dm_thin_find_block(td, block, 0, &result);
2297 * Note that we defer readahead too.
2301 if (unlikely(result.shared)) {
2303 * We have a race condition here between the
2304 * result.shared value returned by the lookup and
2305 * snapshot creation, which may cause new
2308 * To avoid this always quiesce the origin before
2309 * taking the snap. You want to do this anyway to
2310 * ensure a consistent application view
2313 * More distant ancestors are irrelevant. The
2314 * shared flag will be set in their case.
2316 thin_defer_cell(tc, virt_cell);
2317 return DM_MAPIO_SUBMITTED;
2320 build_data_key(tc->td, result.block, &key);
2321 if (bio_detain(tc->pool, &key, bio, &data_cell)) {
2322 cell_defer_no_holder(tc, virt_cell);
2323 return DM_MAPIO_SUBMITTED;
2326 inc_all_io_entry(tc->pool, bio);
2327 cell_defer_no_holder(tc, data_cell);
2328 cell_defer_no_holder(tc, virt_cell);
2330 remap(tc, bio, result.block);
2331 return DM_MAPIO_REMAPPED;
2334 if (get_pool_mode(tc->pool) == PM_READ_ONLY) {
2336 * This block isn't provisioned, and we have no way
2339 handle_unserviceable_bio(tc->pool, bio);
2340 cell_defer_no_holder(tc, virt_cell);
2341 return DM_MAPIO_SUBMITTED;
2346 thin_defer_cell(tc, virt_cell);
2347 return DM_MAPIO_SUBMITTED;
2351 * Must always call bio_io_error on failure.
2352 * dm_thin_find_block can fail with -EINVAL if the
2353 * pool is switched to fail-io mode.
2356 cell_defer_no_holder(tc, virt_cell);
2357 return DM_MAPIO_SUBMITTED;
2361 static int pool_is_congested(struct dm_target_callbacks *cb, int bdi_bits)
2363 struct pool_c *pt = container_of(cb, struct pool_c, callbacks);
2364 struct request_queue *q;
2366 if (get_pool_mode(pt->pool) == PM_OUT_OF_DATA_SPACE)
2369 q = bdev_get_queue(pt->data_dev->bdev);
2370 return bdi_congested(&q->backing_dev_info, bdi_bits);
2373 static void requeue_bios(struct pool *pool)
2375 unsigned long flags;
2379 list_for_each_entry_rcu(tc, &pool->active_thins, list) {
2380 spin_lock_irqsave(&tc->lock, flags);
2381 bio_list_merge(&tc->deferred_bio_list, &tc->retry_on_resume_list);
2382 bio_list_init(&tc->retry_on_resume_list);
2383 spin_unlock_irqrestore(&tc->lock, flags);
2388 /*----------------------------------------------------------------
2389 * Binding of control targets to a pool object
2390 *--------------------------------------------------------------*/
2391 static bool data_dev_supports_discard(struct pool_c *pt)
2393 struct request_queue *q = bdev_get_queue(pt->data_dev->bdev);
2395 return q && blk_queue_discard(q);
2398 static bool is_factor(sector_t block_size, uint32_t n)
2400 return !sector_div(block_size, n);
2404 * If discard_passdown was enabled verify that the data device
2405 * supports discards. Disable discard_passdown if not.
2407 static void disable_passdown_if_not_supported(struct pool_c *pt)
2409 struct pool *pool = pt->pool;
2410 struct block_device *data_bdev = pt->data_dev->bdev;
2411 struct queue_limits *data_limits = &bdev_get_queue(data_bdev)->limits;
2412 sector_t block_size = pool->sectors_per_block << SECTOR_SHIFT;
2413 const char *reason = NULL;
2414 char buf[BDEVNAME_SIZE];
2416 if (!pt->adjusted_pf.discard_passdown)
2419 if (!data_dev_supports_discard(pt))
2420 reason = "discard unsupported";
2422 else if (data_limits->max_discard_sectors < pool->sectors_per_block)
2423 reason = "max discard sectors smaller than a block";
2425 else if (data_limits->discard_granularity > block_size)
2426 reason = "discard granularity larger than a block";
2428 else if (!is_factor(block_size, data_limits->discard_granularity))
2429 reason = "discard granularity not a factor of block size";
2432 DMWARN("Data device (%s) %s: Disabling discard passdown.", bdevname(data_bdev, buf), reason);
2433 pt->adjusted_pf.discard_passdown = false;
2437 static int bind_control_target(struct pool *pool, struct dm_target *ti)
2439 struct pool_c *pt = ti->private;
2442 * We want to make sure that a pool in PM_FAIL mode is never upgraded.
2444 enum pool_mode old_mode = get_pool_mode(pool);
2445 enum pool_mode new_mode = pt->adjusted_pf.mode;
2448 * Don't change the pool's mode until set_pool_mode() below.
2449 * Otherwise the pool's process_* function pointers may
2450 * not match the desired pool mode.
2452 pt->adjusted_pf.mode = old_mode;
2455 pool->pf = pt->adjusted_pf;
2456 pool->low_water_blocks = pt->low_water_blocks;
2458 set_pool_mode(pool, new_mode);
2463 static void unbind_control_target(struct pool *pool, struct dm_target *ti)
2469 /*----------------------------------------------------------------
2471 *--------------------------------------------------------------*/
2472 /* Initialize pool features. */
2473 static void pool_features_init(struct pool_features *pf)
2475 pf->mode = PM_WRITE;
2476 pf->zero_new_blocks = true;
2477 pf->discard_enabled = true;
2478 pf->discard_passdown = true;
2479 pf->error_if_no_space = false;
2482 static void __pool_destroy(struct pool *pool)
2484 __pool_table_remove(pool);
2486 if (dm_pool_metadata_close(pool->pmd) < 0)
2487 DMWARN("%s: dm_pool_metadata_close() failed.", __func__);
2489 dm_bio_prison_destroy(pool->prison);
2490 dm_kcopyd_client_destroy(pool->copier);
2493 destroy_workqueue(pool->wq);
2495 if (pool->next_mapping)
2496 mempool_free(pool->next_mapping, pool->mapping_pool);
2497 mempool_destroy(pool->mapping_pool);
2498 dm_deferred_set_destroy(pool->shared_read_ds);
2499 dm_deferred_set_destroy(pool->all_io_ds);
2503 static struct kmem_cache *_new_mapping_cache;
2505 static struct pool *pool_create(struct mapped_device *pool_md,
2506 struct block_device *metadata_dev,
2507 unsigned long block_size,
2508 int read_only, char **error)
2513 struct dm_pool_metadata *pmd;
2514 bool format_device = read_only ? false : true;
2516 pmd = dm_pool_metadata_open(metadata_dev, block_size, format_device);
2518 *error = "Error creating metadata object";
2519 return (struct pool *)pmd;
2522 pool = kmalloc(sizeof(*pool), GFP_KERNEL);
2524 *error = "Error allocating memory for pool";
2525 err_p = ERR_PTR(-ENOMEM);
2530 pool->sectors_per_block = block_size;
2531 if (block_size & (block_size - 1))
2532 pool->sectors_per_block_shift = -1;
2534 pool->sectors_per_block_shift = __ffs(block_size);
2535 pool->low_water_blocks = 0;
2536 pool_features_init(&pool->pf);
2537 pool->prison = dm_bio_prison_create();
2538 if (!pool->prison) {
2539 *error = "Error creating pool's bio prison";
2540 err_p = ERR_PTR(-ENOMEM);
2544 pool->copier = dm_kcopyd_client_create(&dm_kcopyd_throttle);
2545 if (IS_ERR(pool->copier)) {
2546 r = PTR_ERR(pool->copier);
2547 *error = "Error creating pool's kcopyd client";
2549 goto bad_kcopyd_client;
2553 * Create singlethreaded workqueue that will service all devices
2554 * that use this metadata.
2556 pool->wq = alloc_ordered_workqueue("dm-" DM_MSG_PREFIX, WQ_MEM_RECLAIM);
2558 *error = "Error creating pool's workqueue";
2559 err_p = ERR_PTR(-ENOMEM);
2563 throttle_init(&pool->throttle);
2564 INIT_WORK(&pool->worker, do_worker);
2565 INIT_DELAYED_WORK(&pool->waker, do_waker);
2566 INIT_DELAYED_WORK(&pool->no_space_timeout, do_no_space_timeout);
2567 spin_lock_init(&pool->lock);
2568 bio_list_init(&pool->deferred_flush_bios);
2569 INIT_LIST_HEAD(&pool->prepared_mappings);
2570 INIT_LIST_HEAD(&pool->prepared_discards);
2571 INIT_LIST_HEAD(&pool->active_thins);
2572 pool->low_water_triggered = false;
2574 pool->shared_read_ds = dm_deferred_set_create();
2575 if (!pool->shared_read_ds) {
2576 *error = "Error creating pool's shared read deferred set";
2577 err_p = ERR_PTR(-ENOMEM);
2578 goto bad_shared_read_ds;
2581 pool->all_io_ds = dm_deferred_set_create();
2582 if (!pool->all_io_ds) {
2583 *error = "Error creating pool's all io deferred set";
2584 err_p = ERR_PTR(-ENOMEM);
2588 pool->next_mapping = NULL;
2589 pool->mapping_pool = mempool_create_slab_pool(MAPPING_POOL_SIZE,
2590 _new_mapping_cache);
2591 if (!pool->mapping_pool) {
2592 *error = "Error creating pool's mapping mempool";
2593 err_p = ERR_PTR(-ENOMEM);
2594 goto bad_mapping_pool;
2597 pool->ref_count = 1;
2598 pool->last_commit_jiffies = jiffies;
2599 pool->pool_md = pool_md;
2600 pool->md_dev = metadata_dev;
2601 __pool_table_insert(pool);
2606 dm_deferred_set_destroy(pool->all_io_ds);
2608 dm_deferred_set_destroy(pool->shared_read_ds);
2610 destroy_workqueue(pool->wq);
2612 dm_kcopyd_client_destroy(pool->copier);
2614 dm_bio_prison_destroy(pool->prison);
2618 if (dm_pool_metadata_close(pmd))
2619 DMWARN("%s: dm_pool_metadata_close() failed.", __func__);
2624 static void __pool_inc(struct pool *pool)
2626 BUG_ON(!mutex_is_locked(&dm_thin_pool_table.mutex));
2630 static void __pool_dec(struct pool *pool)
2632 BUG_ON(!mutex_is_locked(&dm_thin_pool_table.mutex));
2633 BUG_ON(!pool->ref_count);
2634 if (!--pool->ref_count)
2635 __pool_destroy(pool);
2638 static struct pool *__pool_find(struct mapped_device *pool_md,
2639 struct block_device *metadata_dev,
2640 unsigned long block_size, int read_only,
2641 char **error, int *created)
2643 struct pool *pool = __pool_table_lookup_metadata_dev(metadata_dev);
2646 if (pool->pool_md != pool_md) {
2647 *error = "metadata device already in use by a pool";
2648 return ERR_PTR(-EBUSY);
2653 pool = __pool_table_lookup(pool_md);
2655 if (pool->md_dev != metadata_dev) {
2656 *error = "different pool cannot replace a pool";
2657 return ERR_PTR(-EINVAL);
2662 pool = pool_create(pool_md, metadata_dev, block_size, read_only, error);
2670 /*----------------------------------------------------------------
2671 * Pool target methods
2672 *--------------------------------------------------------------*/
2673 static void pool_dtr(struct dm_target *ti)
2675 struct pool_c *pt = ti->private;
2677 mutex_lock(&dm_thin_pool_table.mutex);
2679 unbind_control_target(pt->pool, ti);
2680 __pool_dec(pt->pool);
2681 dm_put_device(ti, pt->metadata_dev);
2682 dm_put_device(ti, pt->data_dev);
2685 mutex_unlock(&dm_thin_pool_table.mutex);
2688 static int parse_pool_features(struct dm_arg_set *as, struct pool_features *pf,
2689 struct dm_target *ti)
2693 const char *arg_name;
2695 static struct dm_arg _args[] = {
2696 {0, 4, "Invalid number of pool feature arguments"},
2700 * No feature arguments supplied.
2705 r = dm_read_arg_group(_args, as, &argc, &ti->error);
2709 while (argc && !r) {
2710 arg_name = dm_shift_arg(as);
2713 if (!strcasecmp(arg_name, "skip_block_zeroing"))
2714 pf->zero_new_blocks = false;
2716 else if (!strcasecmp(arg_name, "ignore_discard"))
2717 pf->discard_enabled = false;
2719 else if (!strcasecmp(arg_name, "no_discard_passdown"))
2720 pf->discard_passdown = false;
2722 else if (!strcasecmp(arg_name, "read_only"))
2723 pf->mode = PM_READ_ONLY;
2725 else if (!strcasecmp(arg_name, "error_if_no_space"))
2726 pf->error_if_no_space = true;
2729 ti->error = "Unrecognised pool feature requested";
2738 static void metadata_low_callback(void *context)
2740 struct pool *pool = context;
2742 DMWARN("%s: reached low water mark for metadata device: sending event.",
2743 dm_device_name(pool->pool_md));
2745 dm_table_event(pool->ti->table);
2748 static sector_t get_dev_size(struct block_device *bdev)
2750 return i_size_read(bdev->bd_inode) >> SECTOR_SHIFT;
2753 static void warn_if_metadata_device_too_big(struct block_device *bdev)
2755 sector_t metadata_dev_size = get_dev_size(bdev);
2756 char buffer[BDEVNAME_SIZE];
2758 if (metadata_dev_size > THIN_METADATA_MAX_SECTORS_WARNING)
2759 DMWARN("Metadata device %s is larger than %u sectors: excess space will not be used.",
2760 bdevname(bdev, buffer), THIN_METADATA_MAX_SECTORS);
2763 static sector_t get_metadata_dev_size(struct block_device *bdev)
2765 sector_t metadata_dev_size = get_dev_size(bdev);
2767 if (metadata_dev_size > THIN_METADATA_MAX_SECTORS)
2768 metadata_dev_size = THIN_METADATA_MAX_SECTORS;
2770 return metadata_dev_size;
2773 static dm_block_t get_metadata_dev_size_in_blocks(struct block_device *bdev)
2775 sector_t metadata_dev_size = get_metadata_dev_size(bdev);
2777 sector_div(metadata_dev_size, THIN_METADATA_BLOCK_SIZE);
2779 return metadata_dev_size;
2783 * When a metadata threshold is crossed a dm event is triggered, and
2784 * userland should respond by growing the metadata device. We could let
2785 * userland set the threshold, like we do with the data threshold, but I'm
2786 * not sure they know enough to do this well.
2788 static dm_block_t calc_metadata_threshold(struct pool_c *pt)
2791 * 4M is ample for all ops with the possible exception of thin
2792 * device deletion which is harmless if it fails (just retry the
2793 * delete after you've grown the device).
2795 dm_block_t quarter = get_metadata_dev_size_in_blocks(pt->metadata_dev->bdev) / 4;
2796 return min((dm_block_t)1024ULL /* 4M */, quarter);
2800 * thin-pool <metadata dev> <data dev>
2801 * <data block size (sectors)>
2802 * <low water mark (blocks)>
2803 * [<#feature args> [<arg>]*]
2805 * Optional feature arguments are:
2806 * skip_block_zeroing: skips the zeroing of newly-provisioned blocks.
2807 * ignore_discard: disable discard
2808 * no_discard_passdown: don't pass discards down to the data device
2809 * read_only: Don't allow any changes to be made to the pool metadata.
2810 * error_if_no_space: error IOs, instead of queueing, if no space.
2812 static int pool_ctr(struct dm_target *ti, unsigned argc, char **argv)
2814 int r, pool_created = 0;
2817 struct pool_features pf;
2818 struct dm_arg_set as;
2819 struct dm_dev *data_dev;
2820 unsigned long block_size;
2821 dm_block_t low_water_blocks;
2822 struct dm_dev *metadata_dev;
2823 fmode_t metadata_mode;
2826 * FIXME Remove validation from scope of lock.
2828 mutex_lock(&dm_thin_pool_table.mutex);
2831 ti->error = "Invalid argument count";
2840 * Set default pool features.
2842 pool_features_init(&pf);
2844 dm_consume_args(&as, 4);
2845 r = parse_pool_features(&as, &pf, ti);
2849 metadata_mode = FMODE_READ | ((pf.mode == PM_READ_ONLY) ? 0 : FMODE_WRITE);
2850 r = dm_get_device(ti, argv[0], metadata_mode, &metadata_dev);
2852 ti->error = "Error opening metadata block device";
2855 warn_if_metadata_device_too_big(metadata_dev->bdev);
2857 r = dm_get_device(ti, argv[1], FMODE_READ | FMODE_WRITE, &data_dev);
2859 ti->error = "Error getting data device";
2863 if (kstrtoul(argv[2], 10, &block_size) || !block_size ||
2864 block_size < DATA_DEV_BLOCK_SIZE_MIN_SECTORS ||
2865 block_size > DATA_DEV_BLOCK_SIZE_MAX_SECTORS ||
2866 block_size & (DATA_DEV_BLOCK_SIZE_MIN_SECTORS - 1)) {
2867 ti->error = "Invalid block size";
2872 if (kstrtoull(argv[3], 10, (unsigned long long *)&low_water_blocks)) {
2873 ti->error = "Invalid low water mark";
2878 pt = kzalloc(sizeof(*pt), GFP_KERNEL);
2884 pool = __pool_find(dm_table_get_md(ti->table), metadata_dev->bdev,
2885 block_size, pf.mode == PM_READ_ONLY, &ti->error, &pool_created);
2892 * 'pool_created' reflects whether this is the first table load.
2893 * Top level discard support is not allowed to be changed after
2894 * initial load. This would require a pool reload to trigger thin
2897 if (!pool_created && pf.discard_enabled != pool->pf.discard_enabled) {
2898 ti->error = "Discard support cannot be disabled once enabled";
2900 goto out_flags_changed;
2905 pt->metadata_dev = metadata_dev;
2906 pt->data_dev = data_dev;
2907 pt->low_water_blocks = low_water_blocks;
2908 pt->adjusted_pf = pt->requested_pf = pf;
2909 ti->num_flush_bios = 1;
2912 * Only need to enable discards if the pool should pass
2913 * them down to the data device. The thin device's discard
2914 * processing will cause mappings to be removed from the btree.
2916 ti->discard_zeroes_data_unsupported = true;
2917 if (pf.discard_enabled && pf.discard_passdown) {
2918 ti->num_discard_bios = 1;
2921 * Setting 'discards_supported' circumvents the normal
2922 * stacking of discard limits (this keeps the pool and
2923 * thin devices' discard limits consistent).
2925 ti->discards_supported = true;
2929 r = dm_pool_register_metadata_threshold(pt->pool->pmd,
2930 calc_metadata_threshold(pt),
2931 metadata_low_callback,
2936 pt->callbacks.congested_fn = pool_is_congested;
2937 dm_table_add_target_callbacks(ti->table, &pt->callbacks);
2939 mutex_unlock(&dm_thin_pool_table.mutex);
2948 dm_put_device(ti, data_dev);
2950 dm_put_device(ti, metadata_dev);
2952 mutex_unlock(&dm_thin_pool_table.mutex);
2957 static int pool_map(struct dm_target *ti, struct bio *bio)
2960 struct pool_c *pt = ti->private;
2961 struct pool *pool = pt->pool;
2962 unsigned long flags;
2965 * As this is a singleton target, ti->begin is always zero.
2967 spin_lock_irqsave(&pool->lock, flags);
2968 bio->bi_bdev = pt->data_dev->bdev;
2969 r = DM_MAPIO_REMAPPED;
2970 spin_unlock_irqrestore(&pool->lock, flags);
2975 static int maybe_resize_data_dev(struct dm_target *ti, bool *need_commit)
2978 struct pool_c *pt = ti->private;
2979 struct pool *pool = pt->pool;
2980 sector_t data_size = ti->len;
2981 dm_block_t sb_data_size;
2983 *need_commit = false;
2985 (void) sector_div(data_size, pool->sectors_per_block);
2987 r = dm_pool_get_data_dev_size(pool->pmd, &sb_data_size);
2989 DMERR("%s: failed to retrieve data device size",
2990 dm_device_name(pool->pool_md));
2994 if (data_size < sb_data_size) {
2995 DMERR("%s: pool target (%llu blocks) too small: expected %llu",
2996 dm_device_name(pool->pool_md),
2997 (unsigned long long)data_size, sb_data_size);
3000 } else if (data_size > sb_data_size) {
3001 if (dm_pool_metadata_needs_check(pool->pmd)) {
3002 DMERR("%s: unable to grow the data device until repaired.",
3003 dm_device_name(pool->pool_md));
3008 DMINFO("%s: growing the data device from %llu to %llu blocks",
3009 dm_device_name(pool->pool_md),
3010 sb_data_size, (unsigned long long)data_size);
3011 r = dm_pool_resize_data_dev(pool->pmd, data_size);
3013 metadata_operation_failed(pool, "dm_pool_resize_data_dev", r);
3017 *need_commit = true;
3023 static int maybe_resize_metadata_dev(struct dm_target *ti, bool *need_commit)
3026 struct pool_c *pt = ti->private;
3027 struct pool *pool = pt->pool;
3028 dm_block_t metadata_dev_size, sb_metadata_dev_size;
3030 *need_commit = false;
3032 metadata_dev_size = get_metadata_dev_size_in_blocks(pool->md_dev);
3034 r = dm_pool_get_metadata_dev_size(pool->pmd, &sb_metadata_dev_size);
3036 DMERR("%s: failed to retrieve metadata device size",
3037 dm_device_name(pool->pool_md));
3041 if (metadata_dev_size < sb_metadata_dev_size) {
3042 DMERR("%s: metadata device (%llu blocks) too small: expected %llu",
3043 dm_device_name(pool->pool_md),
3044 metadata_dev_size, sb_metadata_dev_size);
3047 } else if (metadata_dev_size > sb_metadata_dev_size) {
3048 if (dm_pool_metadata_needs_check(pool->pmd)) {
3049 DMERR("%s: unable to grow the metadata device until repaired.",
3050 dm_device_name(pool->pool_md));
3054 warn_if_metadata_device_too_big(pool->md_dev);
3055 DMINFO("%s: growing the metadata device from %llu to %llu blocks",
3056 dm_device_name(pool->pool_md),
3057 sb_metadata_dev_size, metadata_dev_size);
3058 r = dm_pool_resize_metadata_dev(pool->pmd, metadata_dev_size);
3060 metadata_operation_failed(pool, "dm_pool_resize_metadata_dev", r);
3064 *need_commit = true;
3071 * Retrieves the number of blocks of the data device from
3072 * the superblock and compares it to the actual device size,
3073 * thus resizing the data device in case it has grown.
3075 * This both copes with opening preallocated data devices in the ctr
3076 * being followed by a resume
3078 * calling the resume method individually after userspace has
3079 * grown the data device in reaction to a table event.
3081 static int pool_preresume(struct dm_target *ti)
3084 bool need_commit1, need_commit2;
3085 struct pool_c *pt = ti->private;
3086 struct pool *pool = pt->pool;
3089 * Take control of the pool object.
3091 r = bind_control_target(pool, ti);
3095 r = maybe_resize_data_dev(ti, &need_commit1);
3099 r = maybe_resize_metadata_dev(ti, &need_commit2);
3103 if (need_commit1 || need_commit2)
3104 (void) commit(pool);
3109 static void pool_resume(struct dm_target *ti)
3111 struct pool_c *pt = ti->private;
3112 struct pool *pool = pt->pool;
3113 unsigned long flags;
3115 spin_lock_irqsave(&pool->lock, flags);
3116 pool->low_water_triggered = false;
3117 spin_unlock_irqrestore(&pool->lock, flags);
3120 do_waker(&pool->waker.work);
3123 static void pool_postsuspend(struct dm_target *ti)
3125 struct pool_c *pt = ti->private;
3126 struct pool *pool = pt->pool;
3128 cancel_delayed_work(&pool->waker);
3129 cancel_delayed_work(&pool->no_space_timeout);
3130 flush_workqueue(pool->wq);
3131 (void) commit(pool);
3134 static int check_arg_count(unsigned argc, unsigned args_required)
3136 if (argc != args_required) {
3137 DMWARN("Message received with %u arguments instead of %u.",
3138 argc, args_required);
3145 static int read_dev_id(char *arg, dm_thin_id *dev_id, int warning)
3147 if (!kstrtoull(arg, 10, (unsigned long long *)dev_id) &&
3148 *dev_id <= MAX_DEV_ID)
3152 DMWARN("Message received with invalid device id: %s", arg);
3157 static int process_create_thin_mesg(unsigned argc, char **argv, struct pool *pool)
3162 r = check_arg_count(argc, 2);
3166 r = read_dev_id(argv[1], &dev_id, 1);
3170 r = dm_pool_create_thin(pool->pmd, dev_id);
3172 DMWARN("Creation of new thinly-provisioned device with id %s failed.",
3180 static int process_create_snap_mesg(unsigned argc, char **argv, struct pool *pool)
3183 dm_thin_id origin_dev_id;
3186 r = check_arg_count(argc, 3);
3190 r = read_dev_id(argv[1], &dev_id, 1);
3194 r = read_dev_id(argv[2], &origin_dev_id, 1);
3198 r = dm_pool_create_snap(pool->pmd, dev_id, origin_dev_id);
3200 DMWARN("Creation of new snapshot %s of device %s failed.",
3208 static int process_delete_mesg(unsigned argc, char **argv, struct pool *pool)
3213 r = check_arg_count(argc, 2);
3217 r = read_dev_id(argv[1], &dev_id, 1);
3221 r = dm_pool_delete_thin_device(pool->pmd, dev_id);
3223 DMWARN("Deletion of thin device %s failed.", argv[1]);
3228 static int process_set_transaction_id_mesg(unsigned argc, char **argv, struct pool *pool)
3230 dm_thin_id old_id, new_id;
3233 r = check_arg_count(argc, 3);
3237 if (kstrtoull(argv[1], 10, (unsigned long long *)&old_id)) {
3238 DMWARN("set_transaction_id message: Unrecognised id %s.", argv[1]);
3242 if (kstrtoull(argv[2], 10, (unsigned long long *)&new_id)) {
3243 DMWARN("set_transaction_id message: Unrecognised new id %s.", argv[2]);
3247 r = dm_pool_set_metadata_transaction_id(pool->pmd, old_id, new_id);
3249 DMWARN("Failed to change transaction id from %s to %s.",
3257 static int process_reserve_metadata_snap_mesg(unsigned argc, char **argv, struct pool *pool)
3261 r = check_arg_count(argc, 1);
3265 (void) commit(pool);
3267 r = dm_pool_reserve_metadata_snap(pool->pmd);
3269 DMWARN("reserve_metadata_snap message failed.");
3274 static int process_release_metadata_snap_mesg(unsigned argc, char **argv, struct pool *pool)
3278 r = check_arg_count(argc, 1);
3282 r = dm_pool_release_metadata_snap(pool->pmd);
3284 DMWARN("release_metadata_snap message failed.");
3290 * Messages supported:
3291 * create_thin <dev_id>
3292 * create_snap <dev_id> <origin_id>
3294 * trim <dev_id> <new_size_in_sectors>
3295 * set_transaction_id <current_trans_id> <new_trans_id>
3296 * reserve_metadata_snap
3297 * release_metadata_snap
3299 static int pool_message(struct dm_target *ti, unsigned argc, char **argv)
3302 struct pool_c *pt = ti->private;
3303 struct pool *pool = pt->pool;
3305 if (!strcasecmp(argv[0], "create_thin"))
3306 r = process_create_thin_mesg(argc, argv, pool);
3308 else if (!strcasecmp(argv[0], "create_snap"))
3309 r = process_create_snap_mesg(argc, argv, pool);
3311 else if (!strcasecmp(argv[0], "delete"))
3312 r = process_delete_mesg(argc, argv, pool);
3314 else if (!strcasecmp(argv[0], "set_transaction_id"))
3315 r = process_set_transaction_id_mesg(argc, argv, pool);
3317 else if (!strcasecmp(argv[0], "reserve_metadata_snap"))
3318 r = process_reserve_metadata_snap_mesg(argc, argv, pool);
3320 else if (!strcasecmp(argv[0], "release_metadata_snap"))
3321 r = process_release_metadata_snap_mesg(argc, argv, pool);
3324 DMWARN("Unrecognised thin pool target message received: %s", argv[0]);
3327 (void) commit(pool);
3332 static void emit_flags(struct pool_features *pf, char *result,
3333 unsigned sz, unsigned maxlen)
3335 unsigned count = !pf->zero_new_blocks + !pf->discard_enabled +
3336 !pf->discard_passdown + (pf->mode == PM_READ_ONLY) +
3337 pf->error_if_no_space;
3338 DMEMIT("%u ", count);
3340 if (!pf->zero_new_blocks)
3341 DMEMIT("skip_block_zeroing ");
3343 if (!pf->discard_enabled)
3344 DMEMIT("ignore_discard ");
3346 if (!pf->discard_passdown)
3347 DMEMIT("no_discard_passdown ");
3349 if (pf->mode == PM_READ_ONLY)
3350 DMEMIT("read_only ");
3352 if (pf->error_if_no_space)
3353 DMEMIT("error_if_no_space ");
3358 * <transaction id> <used metadata sectors>/<total metadata sectors>
3359 * <used data sectors>/<total data sectors> <held metadata root>
3361 static void pool_status(struct dm_target *ti, status_type_t type,
3362 unsigned status_flags, char *result, unsigned maxlen)
3366 uint64_t transaction_id;
3367 dm_block_t nr_free_blocks_data;
3368 dm_block_t nr_free_blocks_metadata;
3369 dm_block_t nr_blocks_data;
3370 dm_block_t nr_blocks_metadata;
3371 dm_block_t held_root;
3372 char buf[BDEVNAME_SIZE];
3373 char buf2[BDEVNAME_SIZE];
3374 struct pool_c *pt = ti->private;
3375 struct pool *pool = pt->pool;
3378 case STATUSTYPE_INFO:
3379 if (get_pool_mode(pool) == PM_FAIL) {
3384 /* Commit to ensure statistics aren't out-of-date */
3385 if (!(status_flags & DM_STATUS_NOFLUSH_FLAG) && !dm_suspended(ti))
3386 (void) commit(pool);
3388 r = dm_pool_get_metadata_transaction_id(pool->pmd, &transaction_id);
3390 DMERR("%s: dm_pool_get_metadata_transaction_id returned %d",
3391 dm_device_name(pool->pool_md), r);
3395 r = dm_pool_get_free_metadata_block_count(pool->pmd, &nr_free_blocks_metadata);
3397 DMERR("%s: dm_pool_get_free_metadata_block_count returned %d",
3398 dm_device_name(pool->pool_md), r);
3402 r = dm_pool_get_metadata_dev_size(pool->pmd, &nr_blocks_metadata);
3404 DMERR("%s: dm_pool_get_metadata_dev_size returned %d",
3405 dm_device_name(pool->pool_md), r);
3409 r = dm_pool_get_free_block_count(pool->pmd, &nr_free_blocks_data);
3411 DMERR("%s: dm_pool_get_free_block_count returned %d",
3412 dm_device_name(pool->pool_md), r);
3416 r = dm_pool_get_data_dev_size(pool->pmd, &nr_blocks_data);
3418 DMERR("%s: dm_pool_get_data_dev_size returned %d",
3419 dm_device_name(pool->pool_md), r);
3423 r = dm_pool_get_metadata_snap(pool->pmd, &held_root);
3425 DMERR("%s: dm_pool_get_metadata_snap returned %d",
3426 dm_device_name(pool->pool_md), r);
3430 DMEMIT("%llu %llu/%llu %llu/%llu ",
3431 (unsigned long long)transaction_id,
3432 (unsigned long long)(nr_blocks_metadata - nr_free_blocks_metadata),
3433 (unsigned long long)nr_blocks_metadata,
3434 (unsigned long long)(nr_blocks_data - nr_free_blocks_data),
3435 (unsigned long long)nr_blocks_data);
3438 DMEMIT("%llu ", held_root);
3442 if (pool->pf.mode == PM_OUT_OF_DATA_SPACE)
3443 DMEMIT("out_of_data_space ");
3444 else if (pool->pf.mode == PM_READ_ONLY)
3449 if (!pool->pf.discard_enabled)
3450 DMEMIT("ignore_discard ");
3451 else if (pool->pf.discard_passdown)
3452 DMEMIT("discard_passdown ");
3454 DMEMIT("no_discard_passdown ");
3456 if (pool->pf.error_if_no_space)
3457 DMEMIT("error_if_no_space ");
3459 DMEMIT("queue_if_no_space ");
3463 case STATUSTYPE_TABLE:
3464 DMEMIT("%s %s %lu %llu ",
3465 format_dev_t(buf, pt->metadata_dev->bdev->bd_dev),
3466 format_dev_t(buf2, pt->data_dev->bdev->bd_dev),
3467 (unsigned long)pool->sectors_per_block,
3468 (unsigned long long)pt->low_water_blocks);
3469 emit_flags(&pt->requested_pf, result, sz, maxlen);
3478 static int pool_iterate_devices(struct dm_target *ti,
3479 iterate_devices_callout_fn fn, void *data)
3481 struct pool_c *pt = ti->private;
3483 return fn(ti, pt->data_dev, 0, ti->len, data);
3486 static int pool_merge(struct dm_target *ti, struct bvec_merge_data *bvm,
3487 struct bio_vec *biovec, int max_size)
3489 struct pool_c *pt = ti->private;
3490 struct request_queue *q = bdev_get_queue(pt->data_dev->bdev);
3492 if (!q->merge_bvec_fn)
3495 bvm->bi_bdev = pt->data_dev->bdev;
3497 return min(max_size, q->merge_bvec_fn(q, bvm, biovec));
3500 static void set_discard_limits(struct pool_c *pt, struct queue_limits *limits)
3502 struct pool *pool = pt->pool;
3503 struct queue_limits *data_limits;
3505 limits->max_discard_sectors = pool->sectors_per_block;
3508 * discard_granularity is just a hint, and not enforced.
3510 if (pt->adjusted_pf.discard_passdown) {
3511 data_limits = &bdev_get_queue(pt->data_dev->bdev)->limits;
3512 limits->discard_granularity = max(data_limits->discard_granularity,
3513 pool->sectors_per_block << SECTOR_SHIFT);
3515 limits->discard_granularity = pool->sectors_per_block << SECTOR_SHIFT;
3518 static void pool_io_hints(struct dm_target *ti, struct queue_limits *limits)
3520 struct pool_c *pt = ti->private;
3521 struct pool *pool = pt->pool;
3522 sector_t io_opt_sectors = limits->io_opt >> SECTOR_SHIFT;
3525 * Adjust max_sectors_kb to highest possible power-of-2
3526 * factor of pool->sectors_per_block.
3528 if (limits->max_hw_sectors & (limits->max_hw_sectors - 1))
3529 limits->max_sectors = rounddown_pow_of_two(limits->max_hw_sectors);
3531 limits->max_sectors = limits->max_hw_sectors;
3533 if (limits->max_sectors < pool->sectors_per_block) {
3534 while (!is_factor(pool->sectors_per_block, limits->max_sectors)) {
3535 if ((limits->max_sectors & (limits->max_sectors - 1)) == 0)
3536 limits->max_sectors--;
3537 limits->max_sectors = rounddown_pow_of_two(limits->max_sectors);
3539 } else if (block_size_is_power_of_two(pool)) {
3540 /* max_sectors_kb is >= power-of-2 thinp blocksize */
3541 while (!is_factor(limits->max_sectors, pool->sectors_per_block)) {
3542 if ((limits->max_sectors & (limits->max_sectors - 1)) == 0)
3543 limits->max_sectors--;
3544 limits->max_sectors = rounddown_pow_of_two(limits->max_sectors);
3549 * If the system-determined stacked limits are compatible with the
3550 * pool's blocksize (io_opt is a factor) do not override them.
3552 if (io_opt_sectors < pool->sectors_per_block ||
3553 !is_factor(io_opt_sectors, pool->sectors_per_block)) {
3554 if (is_factor(pool->sectors_per_block, limits->max_sectors))
3555 blk_limits_io_min(limits, limits->max_sectors << SECTOR_SHIFT);
3557 blk_limits_io_min(limits, pool->sectors_per_block << SECTOR_SHIFT);
3558 blk_limits_io_opt(limits, pool->sectors_per_block << SECTOR_SHIFT);
3562 * pt->adjusted_pf is a staging area for the actual features to use.
3563 * They get transferred to the live pool in bind_control_target()
3564 * called from pool_preresume().
3566 if (!pt->adjusted_pf.discard_enabled) {
3568 * Must explicitly disallow stacking discard limits otherwise the
3569 * block layer will stack them if pool's data device has support.
3570 * QUEUE_FLAG_DISCARD wouldn't be set but there is no way for the
3571 * user to see that, so make sure to set all discard limits to 0.
3573 limits->discard_granularity = 0;
3577 disable_passdown_if_not_supported(pt);
3579 set_discard_limits(pt, limits);
3582 static struct target_type pool_target = {
3583 .name = "thin-pool",
3584 .features = DM_TARGET_SINGLETON | DM_TARGET_ALWAYS_WRITEABLE |
3585 DM_TARGET_IMMUTABLE,
3586 .version = {1, 14, 0},
3587 .module = THIS_MODULE,
3591 .postsuspend = pool_postsuspend,
3592 .preresume = pool_preresume,
3593 .resume = pool_resume,
3594 .message = pool_message,
3595 .status = pool_status,
3596 .merge = pool_merge,
3597 .iterate_devices = pool_iterate_devices,
3598 .io_hints = pool_io_hints,
3601 /*----------------------------------------------------------------
3602 * Thin target methods
3603 *--------------------------------------------------------------*/
3604 static void thin_get(struct thin_c *tc)
3606 atomic_inc(&tc->refcount);
3609 static void thin_put(struct thin_c *tc)
3611 if (atomic_dec_and_test(&tc->refcount))
3612 complete(&tc->can_destroy);
3615 static void thin_dtr(struct dm_target *ti)
3617 struct thin_c *tc = ti->private;
3618 unsigned long flags;
3621 wait_for_completion(&tc->can_destroy);
3623 spin_lock_irqsave(&tc->pool->lock, flags);
3624 list_del_rcu(&tc->list);
3625 spin_unlock_irqrestore(&tc->pool->lock, flags);
3628 mutex_lock(&dm_thin_pool_table.mutex);
3630 __pool_dec(tc->pool);
3631 dm_pool_close_thin_device(tc->td);
3632 dm_put_device(ti, tc->pool_dev);
3634 dm_put_device(ti, tc->origin_dev);
3637 mutex_unlock(&dm_thin_pool_table.mutex);
3641 * Thin target parameters:
3643 * <pool_dev> <dev_id> [origin_dev]
3645 * pool_dev: the path to the pool (eg, /dev/mapper/my_pool)
3646 * dev_id: the internal device identifier
3647 * origin_dev: a device external to the pool that should act as the origin
3649 * If the pool device has discards disabled, they get disabled for the thin
3652 static int thin_ctr(struct dm_target *ti, unsigned argc, char **argv)
3656 struct dm_dev *pool_dev, *origin_dev;
3657 struct mapped_device *pool_md;
3658 unsigned long flags;
3660 mutex_lock(&dm_thin_pool_table.mutex);
3662 if (argc != 2 && argc != 3) {
3663 ti->error = "Invalid argument count";
3668 tc = ti->private = kzalloc(sizeof(*tc), GFP_KERNEL);
3670 ti->error = "Out of memory";
3674 spin_lock_init(&tc->lock);
3675 INIT_LIST_HEAD(&tc->deferred_cells);
3676 bio_list_init(&tc->deferred_bio_list);
3677 bio_list_init(&tc->retry_on_resume_list);
3678 tc->sort_bio_list = RB_ROOT;
3681 r = dm_get_device(ti, argv[2], FMODE_READ, &origin_dev);
3683 ti->error = "Error opening origin device";
3684 goto bad_origin_dev;
3686 tc->origin_dev = origin_dev;
3689 r = dm_get_device(ti, argv[0], dm_table_get_mode(ti->table), &pool_dev);
3691 ti->error = "Error opening pool device";
3694 tc->pool_dev = pool_dev;
3696 if (read_dev_id(argv[1], (unsigned long long *)&tc->dev_id, 0)) {
3697 ti->error = "Invalid device id";
3702 pool_md = dm_get_md(tc->pool_dev->bdev->bd_dev);
3704 ti->error = "Couldn't get pool mapped device";
3709 tc->pool = __pool_table_lookup(pool_md);
3711 ti->error = "Couldn't find pool object";
3713 goto bad_pool_lookup;
3715 __pool_inc(tc->pool);
3717 if (get_pool_mode(tc->pool) == PM_FAIL) {
3718 ti->error = "Couldn't open thin device, Pool is in fail mode";
3723 r = dm_pool_open_thin_device(tc->pool->pmd, tc->dev_id, &tc->td);
3725 ti->error = "Couldn't open thin internal device";
3729 r = dm_set_target_max_io_len(ti, tc->pool->sectors_per_block);
3731 goto bad_target_max_io_len;
3733 ti->num_flush_bios = 1;
3734 ti->flush_supported = true;
3735 ti->per_bio_data_size = sizeof(struct dm_thin_endio_hook);
3737 /* In case the pool supports discards, pass them on. */
3738 ti->discard_zeroes_data_unsupported = true;
3739 if (tc->pool->pf.discard_enabled) {
3740 ti->discards_supported = true;
3741 ti->num_discard_bios = 1;
3742 /* Discard bios must be split on a block boundary */
3743 ti->split_discard_bios = true;
3748 mutex_unlock(&dm_thin_pool_table.mutex);
3750 atomic_set(&tc->refcount, 1);
3751 init_completion(&tc->can_destroy);
3753 spin_lock_irqsave(&tc->pool->lock, flags);
3754 list_add_tail_rcu(&tc->list, &tc->pool->active_thins);
3755 spin_unlock_irqrestore(&tc->pool->lock, flags);
3757 * This synchronize_rcu() call is needed here otherwise we risk a
3758 * wake_worker() call finding no bios to process (because the newly
3759 * added tc isn't yet visible). So this reduces latency since we
3760 * aren't then dependent on the periodic commit to wake_worker().
3766 bad_target_max_io_len:
3767 dm_pool_close_thin_device(tc->td);
3769 __pool_dec(tc->pool);
3773 dm_put_device(ti, tc->pool_dev);
3776 dm_put_device(ti, tc->origin_dev);
3780 mutex_unlock(&dm_thin_pool_table.mutex);
3785 static int thin_map(struct dm_target *ti, struct bio *bio)
3787 bio->bi_iter.bi_sector = dm_target_offset(ti, bio->bi_iter.bi_sector);
3789 return thin_bio_map(ti, bio);
3792 static int thin_endio(struct dm_target *ti, struct bio *bio, int err)
3794 unsigned long flags;
3795 struct dm_thin_endio_hook *h = dm_per_bio_data(bio, sizeof(struct dm_thin_endio_hook));
3796 struct list_head work;
3797 struct dm_thin_new_mapping *m, *tmp;
3798 struct pool *pool = h->tc->pool;
3800 if (h->shared_read_entry) {
3801 INIT_LIST_HEAD(&work);
3802 dm_deferred_entry_dec(h->shared_read_entry, &work);
3804 spin_lock_irqsave(&pool->lock, flags);
3805 list_for_each_entry_safe(m, tmp, &work, list) {
3807 __complete_mapping_preparation(m);
3809 spin_unlock_irqrestore(&pool->lock, flags);
3812 if (h->all_io_entry) {
3813 INIT_LIST_HEAD(&work);
3814 dm_deferred_entry_dec(h->all_io_entry, &work);
3815 if (!list_empty(&work)) {
3816 spin_lock_irqsave(&pool->lock, flags);
3817 list_for_each_entry_safe(m, tmp, &work, list)
3818 list_add_tail(&m->list, &pool->prepared_discards);
3819 spin_unlock_irqrestore(&pool->lock, flags);
3827 static void thin_presuspend(struct dm_target *ti)
3829 struct thin_c *tc = ti->private;
3831 if (dm_noflush_suspending(ti))
3832 noflush_work(tc, do_noflush_start);
3835 static void thin_postsuspend(struct dm_target *ti)
3837 struct thin_c *tc = ti->private;
3840 * The dm_noflush_suspending flag has been cleared by now, so
3841 * unfortunately we must always run this.
3843 noflush_work(tc, do_noflush_stop);
3846 static int thin_preresume(struct dm_target *ti)
3848 struct thin_c *tc = ti->private;
3851 tc->origin_size = get_dev_size(tc->origin_dev->bdev);
3857 * <nr mapped sectors> <highest mapped sector>
3859 static void thin_status(struct dm_target *ti, status_type_t type,
3860 unsigned status_flags, char *result, unsigned maxlen)
3864 dm_block_t mapped, highest;
3865 char buf[BDEVNAME_SIZE];
3866 struct thin_c *tc = ti->private;
3868 if (get_pool_mode(tc->pool) == PM_FAIL) {
3877 case STATUSTYPE_INFO:
3878 r = dm_thin_get_mapped_count(tc->td, &mapped);
3880 DMERR("dm_thin_get_mapped_count returned %d", r);
3884 r = dm_thin_get_highest_mapped_block(tc->td, &highest);
3886 DMERR("dm_thin_get_highest_mapped_block returned %d", r);
3890 DMEMIT("%llu ", mapped * tc->pool->sectors_per_block);
3892 DMEMIT("%llu", ((highest + 1) *
3893 tc->pool->sectors_per_block) - 1);
3898 case STATUSTYPE_TABLE:
3900 format_dev_t(buf, tc->pool_dev->bdev->bd_dev),
3901 (unsigned long) tc->dev_id);
3903 DMEMIT(" %s", format_dev_t(buf, tc->origin_dev->bdev->bd_dev));
3914 static int thin_merge(struct dm_target *ti, struct bvec_merge_data *bvm,
3915 struct bio_vec *biovec, int max_size)
3917 struct thin_c *tc = ti->private;
3918 struct request_queue *q = bdev_get_queue(tc->pool_dev->bdev);
3920 if (!q->merge_bvec_fn)
3923 bvm->bi_bdev = tc->pool_dev->bdev;
3924 bvm->bi_sector = dm_target_offset(ti, bvm->bi_sector);
3926 return min(max_size, q->merge_bvec_fn(q, bvm, biovec));
3929 static int thin_iterate_devices(struct dm_target *ti,
3930 iterate_devices_callout_fn fn, void *data)
3933 struct thin_c *tc = ti->private;
3934 struct pool *pool = tc->pool;
3937 * We can't call dm_pool_get_data_dev_size() since that blocks. So
3938 * we follow a more convoluted path through to the pool's target.
3941 return 0; /* nothing is bound */
3943 blocks = pool->ti->len;
3944 (void) sector_div(blocks, pool->sectors_per_block);
3946 return fn(ti, tc->pool_dev, 0, pool->sectors_per_block * blocks, data);
3951 static struct target_type thin_target = {
3953 .version = {1, 14, 0},
3954 .module = THIS_MODULE,
3958 .end_io = thin_endio,
3959 .preresume = thin_preresume,
3960 .presuspend = thin_presuspend,
3961 .postsuspend = thin_postsuspend,
3962 .status = thin_status,
3963 .merge = thin_merge,
3964 .iterate_devices = thin_iterate_devices,
3967 /*----------------------------------------------------------------*/
3969 static int __init dm_thin_init(void)
3975 r = dm_register_target(&thin_target);
3979 r = dm_register_target(&pool_target);
3981 goto bad_pool_target;
3985 _new_mapping_cache = KMEM_CACHE(dm_thin_new_mapping, 0);
3986 if (!_new_mapping_cache)
3987 goto bad_new_mapping_cache;
3991 bad_new_mapping_cache:
3992 dm_unregister_target(&pool_target);
3994 dm_unregister_target(&thin_target);
3999 static void dm_thin_exit(void)
4001 dm_unregister_target(&thin_target);
4002 dm_unregister_target(&pool_target);
4004 kmem_cache_destroy(_new_mapping_cache);
4007 module_init(dm_thin_init);
4008 module_exit(dm_thin_exit);
4010 module_param_named(no_space_timeout, no_space_timeout_secs, uint, S_IRUGO | S_IWUSR);
4011 MODULE_PARM_DESC(no_space_timeout, "Out of data space queue IO timeout in seconds");
4013 MODULE_DESCRIPTION(DM_NAME " thin provisioning target");
4014 MODULE_AUTHOR("Joe Thornber <dm-devel@redhat.com>");
4015 MODULE_LICENSE("GPL");