2 * Copyright (C) 2011-2012 Red Hat UK.
4 * This file is released under the GPL.
7 #include "dm-thin-metadata.h"
8 #include "dm-bio-prison.h"
11 #include <linux/device-mapper.h>
12 #include <linux/dm-io.h>
13 #include <linux/dm-kcopyd.h>
14 #include <linux/jiffies.h>
15 #include <linux/log2.h>
16 #include <linux/list.h>
17 #include <linux/rculist.h>
18 #include <linux/init.h>
19 #include <linux/module.h>
20 #include <linux/slab.h>
21 #include <linux/sort.h>
22 #include <linux/rbtree.h>
24 #define DM_MSG_PREFIX "thin"
29 #define ENDIO_HOOK_POOL_SIZE 1024
30 #define MAPPING_POOL_SIZE 1024
31 #define COMMIT_PERIOD HZ
32 #define NO_SPACE_TIMEOUT_SECS 60
34 static unsigned no_space_timeout_secs = NO_SPACE_TIMEOUT_SECS;
36 DECLARE_DM_KCOPYD_THROTTLE_WITH_MODULE_PARM(snapshot_copy_throttle,
37 "A percentage of time allocated for copy on write");
40 * The block size of the device holding pool data must be
41 * between 64KB and 1GB.
43 #define DATA_DEV_BLOCK_SIZE_MIN_SECTORS (64 * 1024 >> SECTOR_SHIFT)
44 #define DATA_DEV_BLOCK_SIZE_MAX_SECTORS (1024 * 1024 * 1024 >> SECTOR_SHIFT)
47 * Device id is restricted to 24 bits.
49 #define MAX_DEV_ID ((1 << 24) - 1)
52 * How do we handle breaking sharing of data blocks?
53 * =================================================
55 * We use a standard copy-on-write btree to store the mappings for the
56 * devices (note I'm talking about copy-on-write of the metadata here, not
57 * the data). When you take an internal snapshot you clone the root node
58 * of the origin btree. After this there is no concept of an origin or a
59 * snapshot. They are just two device trees that happen to point to the
62 * When we get a write in we decide if it's to a shared data block using
63 * some timestamp magic. If it is, we have to break sharing.
65 * Let's say we write to a shared block in what was the origin. The
68 * i) plug io further to this physical block. (see bio_prison code).
70 * ii) quiesce any read io to that shared data block. Obviously
71 * including all devices that share this block. (see dm_deferred_set code)
73 * iii) copy the data block to a newly allocate block. This step can be
74 * missed out if the io covers the block. (schedule_copy).
76 * iv) insert the new mapping into the origin's btree
77 * (process_prepared_mapping). This act of inserting breaks some
78 * sharing of btree nodes between the two devices. Breaking sharing only
79 * effects the btree of that specific device. Btrees for the other
80 * devices that share the block never change. The btree for the origin
81 * device as it was after the last commit is untouched, ie. we're using
82 * persistent data structures in the functional programming sense.
84 * v) unplug io to this physical block, including the io that triggered
85 * the breaking of sharing.
87 * Steps (ii) and (iii) occur in parallel.
89 * The metadata _doesn't_ need to be committed before the io continues. We
90 * get away with this because the io is always written to a _new_ block.
91 * If there's a crash, then:
93 * - The origin mapping will point to the old origin block (the shared
94 * one). This will contain the data as it was before the io that triggered
95 * the breaking of sharing came in.
97 * - The snap mapping still points to the old block. As it would after
100 * The downside of this scheme is the timestamp magic isn't perfect, and
101 * will continue to think that data block in the snapshot device is shared
102 * even after the write to the origin has broken sharing. I suspect data
103 * blocks will typically be shared by many different devices, so we're
104 * breaking sharing n + 1 times, rather than n, where n is the number of
105 * devices that reference this data block. At the moment I think the
106 * benefits far, far outweigh the disadvantages.
109 /*----------------------------------------------------------------*/
114 static void build_data_key(struct dm_thin_device *td,
115 dm_block_t b, struct dm_cell_key *key)
118 key->dev = dm_thin_dev_id(td);
119 key->block_begin = b;
120 key->block_end = b + 1ULL;
123 static void build_virtual_key(struct dm_thin_device *td, dm_block_t b,
124 struct dm_cell_key *key)
127 key->dev = dm_thin_dev_id(td);
128 key->block_begin = b;
129 key->block_end = b + 1ULL;
132 /*----------------------------------------------------------------*/
134 #define THROTTLE_THRESHOLD (1 * HZ)
137 struct rw_semaphore lock;
138 unsigned long threshold;
139 bool throttle_applied;
142 static void throttle_init(struct throttle *t)
144 init_rwsem(&t->lock);
145 t->throttle_applied = false;
148 static void throttle_work_start(struct throttle *t)
150 t->threshold = jiffies + THROTTLE_THRESHOLD;
153 static void throttle_work_update(struct throttle *t)
155 if (!t->throttle_applied && jiffies > t->threshold) {
156 down_write(&t->lock);
157 t->throttle_applied = true;
161 static void throttle_work_complete(struct throttle *t)
163 if (t->throttle_applied) {
164 t->throttle_applied = false;
169 static void throttle_lock(struct throttle *t)
174 static void throttle_unlock(struct throttle *t)
179 /*----------------------------------------------------------------*/
182 * A pool device ties together a metadata device and a data device. It
183 * also provides the interface for creating and destroying internal
186 struct dm_thin_new_mapping;
189 * The pool runs in 4 modes. Ordered in degraded order for comparisons.
192 PM_WRITE, /* metadata may be changed */
193 PM_OUT_OF_DATA_SPACE, /* metadata may be changed, though data may not be allocated */
194 PM_READ_ONLY, /* metadata may not be changed */
195 PM_FAIL, /* all I/O fails */
198 struct pool_features {
201 bool zero_new_blocks:1;
202 bool discard_enabled:1;
203 bool discard_passdown:1;
204 bool error_if_no_space:1;
208 typedef void (*process_bio_fn)(struct thin_c *tc, struct bio *bio);
209 typedef void (*process_cell_fn)(struct thin_c *tc, struct dm_bio_prison_cell *cell);
210 typedef void (*process_mapping_fn)(struct dm_thin_new_mapping *m);
212 #define CELL_SORT_ARRAY_SIZE 8192
215 struct list_head list;
216 struct dm_target *ti; /* Only set if a pool target is bound */
218 struct mapped_device *pool_md;
219 struct block_device *md_dev;
220 struct dm_pool_metadata *pmd;
222 dm_block_t low_water_blocks;
223 uint32_t sectors_per_block;
224 int sectors_per_block_shift;
226 struct pool_features pf;
227 bool low_water_triggered:1; /* A dm event has been sent */
230 struct dm_bio_prison *prison;
231 struct dm_kcopyd_client *copier;
233 struct workqueue_struct *wq;
234 struct throttle throttle;
235 struct work_struct worker;
236 struct delayed_work waker;
237 struct delayed_work no_space_timeout;
239 unsigned long last_commit_jiffies;
243 struct bio_list deferred_flush_bios;
244 struct list_head prepared_mappings;
245 struct list_head prepared_discards;
246 struct list_head active_thins;
248 struct dm_deferred_set *shared_read_ds;
249 struct dm_deferred_set *all_io_ds;
251 struct dm_thin_new_mapping *next_mapping;
252 mempool_t *mapping_pool;
254 process_bio_fn process_bio;
255 process_bio_fn process_discard;
257 process_cell_fn process_cell;
258 process_cell_fn process_discard_cell;
260 process_mapping_fn process_prepared_mapping;
261 process_mapping_fn process_prepared_discard;
263 struct dm_bio_prison_cell *cell_sort_array[CELL_SORT_ARRAY_SIZE];
266 static enum pool_mode get_pool_mode(struct pool *pool);
267 static void metadata_operation_failed(struct pool *pool, const char *op, int r);
270 * Target context for a pool.
273 struct dm_target *ti;
275 struct dm_dev *data_dev;
276 struct dm_dev *metadata_dev;
277 struct dm_target_callbacks callbacks;
279 dm_block_t low_water_blocks;
280 struct pool_features requested_pf; /* Features requested during table load */
281 struct pool_features adjusted_pf; /* Features used after adjusting for constituent devices */
285 * Target context for a thin.
288 struct list_head list;
289 struct dm_dev *pool_dev;
290 struct dm_dev *origin_dev;
291 sector_t origin_size;
295 struct dm_thin_device *td;
296 struct mapped_device *thin_md;
300 struct list_head deferred_cells;
301 struct bio_list deferred_bio_list;
302 struct bio_list retry_on_resume_list;
303 struct rb_root sort_bio_list; /* sorted list of deferred bios */
306 * Ensures the thin is not destroyed until the worker has finished
307 * iterating the active_thins list.
310 struct completion can_destroy;
313 /*----------------------------------------------------------------*/
316 * wake_worker() is used when new work is queued and when pool_resume is
317 * ready to continue deferred IO processing.
319 static void wake_worker(struct pool *pool)
321 queue_work(pool->wq, &pool->worker);
324 /*----------------------------------------------------------------*/
326 static int bio_detain(struct pool *pool, struct dm_cell_key *key, struct bio *bio,
327 struct dm_bio_prison_cell **cell_result)
330 struct dm_bio_prison_cell *cell_prealloc;
333 * Allocate a cell from the prison's mempool.
334 * This might block but it can't fail.
336 cell_prealloc = dm_bio_prison_alloc_cell(pool->prison, GFP_NOIO);
338 r = dm_bio_detain(pool->prison, key, bio, cell_prealloc, cell_result);
341 * We reused an old cell; we can get rid of
344 dm_bio_prison_free_cell(pool->prison, cell_prealloc);
349 static void cell_release(struct pool *pool,
350 struct dm_bio_prison_cell *cell,
351 struct bio_list *bios)
353 dm_cell_release(pool->prison, cell, bios);
354 dm_bio_prison_free_cell(pool->prison, cell);
357 static void cell_visit_release(struct pool *pool,
358 void (*fn)(void *, struct dm_bio_prison_cell *),
360 struct dm_bio_prison_cell *cell)
362 dm_cell_visit_release(pool->prison, fn, context, cell);
363 dm_bio_prison_free_cell(pool->prison, cell);
366 static void cell_release_no_holder(struct pool *pool,
367 struct dm_bio_prison_cell *cell,
368 struct bio_list *bios)
370 dm_cell_release_no_holder(pool->prison, cell, bios);
371 dm_bio_prison_free_cell(pool->prison, cell);
374 static void cell_error_with_code(struct pool *pool,
375 struct dm_bio_prison_cell *cell, int error_code)
377 dm_cell_error(pool->prison, cell, error_code);
378 dm_bio_prison_free_cell(pool->prison, cell);
381 static void cell_error(struct pool *pool, struct dm_bio_prison_cell *cell)
383 cell_error_with_code(pool, cell, -EIO);
386 static void cell_success(struct pool *pool, struct dm_bio_prison_cell *cell)
388 cell_error_with_code(pool, cell, 0);
391 static void cell_requeue(struct pool *pool, struct dm_bio_prison_cell *cell)
393 cell_error_with_code(pool, cell, DM_ENDIO_REQUEUE);
396 /*----------------------------------------------------------------*/
399 * A global list of pools that uses a struct mapped_device as a key.
401 static struct dm_thin_pool_table {
403 struct list_head pools;
404 } dm_thin_pool_table;
406 static void pool_table_init(void)
408 mutex_init(&dm_thin_pool_table.mutex);
409 INIT_LIST_HEAD(&dm_thin_pool_table.pools);
412 static void __pool_table_insert(struct pool *pool)
414 BUG_ON(!mutex_is_locked(&dm_thin_pool_table.mutex));
415 list_add(&pool->list, &dm_thin_pool_table.pools);
418 static void __pool_table_remove(struct pool *pool)
420 BUG_ON(!mutex_is_locked(&dm_thin_pool_table.mutex));
421 list_del(&pool->list);
424 static struct pool *__pool_table_lookup(struct mapped_device *md)
426 struct pool *pool = NULL, *tmp;
428 BUG_ON(!mutex_is_locked(&dm_thin_pool_table.mutex));
430 list_for_each_entry(tmp, &dm_thin_pool_table.pools, list) {
431 if (tmp->pool_md == md) {
440 static struct pool *__pool_table_lookup_metadata_dev(struct block_device *md_dev)
442 struct pool *pool = NULL, *tmp;
444 BUG_ON(!mutex_is_locked(&dm_thin_pool_table.mutex));
446 list_for_each_entry(tmp, &dm_thin_pool_table.pools, list) {
447 if (tmp->md_dev == md_dev) {
456 /*----------------------------------------------------------------*/
458 struct dm_thin_endio_hook {
460 struct dm_deferred_entry *shared_read_entry;
461 struct dm_deferred_entry *all_io_entry;
462 struct dm_thin_new_mapping *overwrite_mapping;
463 struct rb_node rb_node;
466 static void __merge_bio_list(struct bio_list *bios, struct bio_list *master)
468 bio_list_merge(bios, master);
469 bio_list_init(master);
472 static void error_bio_list(struct bio_list *bios, int error)
476 while ((bio = bio_list_pop(bios)))
477 bio_endio(bio, error);
480 static void error_thin_bio_list(struct thin_c *tc, struct bio_list *master, int error)
482 struct bio_list bios;
485 bio_list_init(&bios);
487 spin_lock_irqsave(&tc->lock, flags);
488 __merge_bio_list(&bios, master);
489 spin_unlock_irqrestore(&tc->lock, flags);
491 error_bio_list(&bios, error);
494 static void requeue_deferred_cells(struct thin_c *tc)
496 struct pool *pool = tc->pool;
498 struct list_head cells;
499 struct dm_bio_prison_cell *cell, *tmp;
501 INIT_LIST_HEAD(&cells);
503 spin_lock_irqsave(&tc->lock, flags);
504 list_splice_init(&tc->deferred_cells, &cells);
505 spin_unlock_irqrestore(&tc->lock, flags);
507 list_for_each_entry_safe(cell, tmp, &cells, user_list)
508 cell_requeue(pool, cell);
511 static void requeue_io(struct thin_c *tc)
513 struct bio_list bios;
516 bio_list_init(&bios);
518 spin_lock_irqsave(&tc->lock, flags);
519 __merge_bio_list(&bios, &tc->deferred_bio_list);
520 __merge_bio_list(&bios, &tc->retry_on_resume_list);
521 spin_unlock_irqrestore(&tc->lock, flags);
523 error_bio_list(&bios, DM_ENDIO_REQUEUE);
524 requeue_deferred_cells(tc);
527 static void error_retry_list(struct pool *pool)
532 list_for_each_entry_rcu(tc, &pool->active_thins, list)
533 error_thin_bio_list(tc, &tc->retry_on_resume_list, -EIO);
538 * This section of code contains the logic for processing a thin device's IO.
539 * Much of the code depends on pool object resources (lists, workqueues, etc)
540 * but most is exclusively called from the thin target rather than the thin-pool
544 static bool block_size_is_power_of_two(struct pool *pool)
546 return pool->sectors_per_block_shift >= 0;
549 static dm_block_t get_bio_block(struct thin_c *tc, struct bio *bio)
551 struct pool *pool = tc->pool;
552 sector_t block_nr = bio->bi_iter.bi_sector;
554 if (block_size_is_power_of_two(pool))
555 block_nr >>= pool->sectors_per_block_shift;
557 (void) sector_div(block_nr, pool->sectors_per_block);
562 static void remap(struct thin_c *tc, struct bio *bio, dm_block_t block)
564 struct pool *pool = tc->pool;
565 sector_t bi_sector = bio->bi_iter.bi_sector;
567 bio->bi_bdev = tc->pool_dev->bdev;
568 if (block_size_is_power_of_two(pool))
569 bio->bi_iter.bi_sector =
570 (block << pool->sectors_per_block_shift) |
571 (bi_sector & (pool->sectors_per_block - 1));
573 bio->bi_iter.bi_sector = (block * pool->sectors_per_block) +
574 sector_div(bi_sector, pool->sectors_per_block);
577 static void remap_to_origin(struct thin_c *tc, struct bio *bio)
579 bio->bi_bdev = tc->origin_dev->bdev;
582 static int bio_triggers_commit(struct thin_c *tc, struct bio *bio)
584 return (bio->bi_rw & (REQ_FLUSH | REQ_FUA)) &&
585 dm_thin_changed_this_transaction(tc->td);
588 static void inc_all_io_entry(struct pool *pool, struct bio *bio)
590 struct dm_thin_endio_hook *h;
592 if (bio->bi_rw & REQ_DISCARD)
595 h = dm_per_bio_data(bio, sizeof(struct dm_thin_endio_hook));
596 h->all_io_entry = dm_deferred_entry_inc(pool->all_io_ds);
599 static void issue(struct thin_c *tc, struct bio *bio)
601 struct pool *pool = tc->pool;
604 if (!bio_triggers_commit(tc, bio)) {
605 generic_make_request(bio);
610 * Complete bio with an error if earlier I/O caused changes to
611 * the metadata that can't be committed e.g, due to I/O errors
612 * on the metadata device.
614 if (dm_thin_aborted_changes(tc->td)) {
620 * Batch together any bios that trigger commits and then issue a
621 * single commit for them in process_deferred_bios().
623 spin_lock_irqsave(&pool->lock, flags);
624 bio_list_add(&pool->deferred_flush_bios, bio);
625 spin_unlock_irqrestore(&pool->lock, flags);
628 static void remap_to_origin_and_issue(struct thin_c *tc, struct bio *bio)
630 remap_to_origin(tc, bio);
634 static void remap_and_issue(struct thin_c *tc, struct bio *bio,
637 remap(tc, bio, block);
641 /*----------------------------------------------------------------*/
644 * Bio endio functions.
646 struct dm_thin_new_mapping {
647 struct list_head list;
650 bool definitely_not_shared:1;
653 * Track quiescing, copying and zeroing preparation actions. When this
654 * counter hits zero the block is prepared and can be inserted into the
657 atomic_t prepare_actions;
661 dm_block_t virt_block;
662 dm_block_t data_block;
663 struct dm_bio_prison_cell *cell, *cell2;
666 * If the bio covers the whole area of a block then we can avoid
667 * zeroing or copying. Instead this bio is hooked. The bio will
668 * still be in the cell, so care has to be taken to avoid issuing
672 bio_end_io_t *saved_bi_end_io;
675 static void __complete_mapping_preparation(struct dm_thin_new_mapping *m)
677 struct pool *pool = m->tc->pool;
679 if (atomic_dec_and_test(&m->prepare_actions)) {
680 list_add_tail(&m->list, &pool->prepared_mappings);
685 static void complete_mapping_preparation(struct dm_thin_new_mapping *m)
688 struct pool *pool = m->tc->pool;
690 spin_lock_irqsave(&pool->lock, flags);
691 __complete_mapping_preparation(m);
692 spin_unlock_irqrestore(&pool->lock, flags);
695 static void copy_complete(int read_err, unsigned long write_err, void *context)
697 struct dm_thin_new_mapping *m = context;
699 m->err = read_err || write_err ? -EIO : 0;
700 complete_mapping_preparation(m);
703 static void overwrite_endio(struct bio *bio, int err)
705 struct dm_thin_endio_hook *h = dm_per_bio_data(bio, sizeof(struct dm_thin_endio_hook));
706 struct dm_thin_new_mapping *m = h->overwrite_mapping;
708 bio->bi_end_io = m->saved_bi_end_io;
711 complete_mapping_preparation(m);
714 /*----------------------------------------------------------------*/
721 * Prepared mapping jobs.
725 * This sends the bios in the cell, except the original holder, back
726 * to the deferred_bios list.
728 static void cell_defer_no_holder(struct thin_c *tc, struct dm_bio_prison_cell *cell)
730 struct pool *pool = tc->pool;
733 spin_lock_irqsave(&tc->lock, flags);
734 cell_release_no_holder(pool, cell, &tc->deferred_bio_list);
735 spin_unlock_irqrestore(&tc->lock, flags);
740 static void thin_defer_bio(struct thin_c *tc, struct bio *bio);
744 struct bio_list defer_bios;
745 struct bio_list issue_bios;
748 static void __inc_remap_and_issue_cell(void *context,
749 struct dm_bio_prison_cell *cell)
751 struct remap_info *info = context;
754 while ((bio = bio_list_pop(&cell->bios))) {
755 if (bio->bi_rw & (REQ_DISCARD | REQ_FLUSH | REQ_FUA))
756 bio_list_add(&info->defer_bios, bio);
758 inc_all_io_entry(info->tc->pool, bio);
761 * We can't issue the bios with the bio prison lock
762 * held, so we add them to a list to issue on
763 * return from this function.
765 bio_list_add(&info->issue_bios, bio);
770 static void inc_remap_and_issue_cell(struct thin_c *tc,
771 struct dm_bio_prison_cell *cell,
775 struct remap_info info;
778 bio_list_init(&info.defer_bios);
779 bio_list_init(&info.issue_bios);
782 * We have to be careful to inc any bios we're about to issue
783 * before the cell is released, and avoid a race with new bios
784 * being added to the cell.
786 cell_visit_release(tc->pool, __inc_remap_and_issue_cell,
789 while ((bio = bio_list_pop(&info.defer_bios)))
790 thin_defer_bio(tc, bio);
792 while ((bio = bio_list_pop(&info.issue_bios)))
793 remap_and_issue(info.tc, bio, block);
796 static void process_prepared_mapping_fail(struct dm_thin_new_mapping *m)
798 cell_error(m->tc->pool, m->cell);
800 mempool_free(m, m->tc->pool->mapping_pool);
803 static void process_prepared_mapping(struct dm_thin_new_mapping *m)
805 struct thin_c *tc = m->tc;
806 struct pool *pool = tc->pool;
807 struct bio *bio = m->bio;
811 cell_error(pool, m->cell);
816 * Commit the prepared block into the mapping btree.
817 * Any I/O for this block arriving after this point will get
818 * remapped to it directly.
820 r = dm_thin_insert_block(tc->td, m->virt_block, m->data_block);
822 metadata_operation_failed(pool, "dm_thin_insert_block", r);
823 cell_error(pool, m->cell);
828 * Release any bios held while the block was being provisioned.
829 * If we are processing a write bio that completely covers the block,
830 * we already processed it so can ignore it now when processing
831 * the bios in the cell.
834 inc_remap_and_issue_cell(tc, m->cell, m->data_block);
837 inc_all_io_entry(tc->pool, m->cell->holder);
838 remap_and_issue(tc, m->cell->holder, m->data_block);
839 inc_remap_and_issue_cell(tc, m->cell, m->data_block);
844 mempool_free(m, pool->mapping_pool);
847 static void process_prepared_discard_fail(struct dm_thin_new_mapping *m)
849 struct thin_c *tc = m->tc;
851 bio_io_error(m->bio);
852 cell_defer_no_holder(tc, m->cell);
853 cell_defer_no_holder(tc, m->cell2);
854 mempool_free(m, tc->pool->mapping_pool);
857 static void process_prepared_discard_passdown(struct dm_thin_new_mapping *m)
859 struct thin_c *tc = m->tc;
861 inc_all_io_entry(tc->pool, m->bio);
862 cell_defer_no_holder(tc, m->cell);
863 cell_defer_no_holder(tc, m->cell2);
866 if (m->definitely_not_shared)
867 remap_and_issue(tc, m->bio, m->data_block);
870 if (dm_pool_block_is_used(tc->pool->pmd, m->data_block, &used) || used)
871 bio_endio(m->bio, 0);
873 remap_and_issue(tc, m->bio, m->data_block);
876 bio_endio(m->bio, 0);
878 mempool_free(m, tc->pool->mapping_pool);
881 static void process_prepared_discard(struct dm_thin_new_mapping *m)
884 struct thin_c *tc = m->tc;
886 r = dm_thin_remove_block(tc->td, m->virt_block);
888 DMERR_LIMIT("dm_thin_remove_block() failed");
890 process_prepared_discard_passdown(m);
893 static void process_prepared(struct pool *pool, struct list_head *head,
894 process_mapping_fn *fn)
897 struct list_head maps;
898 struct dm_thin_new_mapping *m, *tmp;
900 INIT_LIST_HEAD(&maps);
901 spin_lock_irqsave(&pool->lock, flags);
902 list_splice_init(head, &maps);
903 spin_unlock_irqrestore(&pool->lock, flags);
905 list_for_each_entry_safe(m, tmp, &maps, list)
912 static int io_overlaps_block(struct pool *pool, struct bio *bio)
914 return bio->bi_iter.bi_size ==
915 (pool->sectors_per_block << SECTOR_SHIFT);
918 static int io_overwrites_block(struct pool *pool, struct bio *bio)
920 return (bio_data_dir(bio) == WRITE) &&
921 io_overlaps_block(pool, bio);
924 static void save_and_set_endio(struct bio *bio, bio_end_io_t **save,
927 *save = bio->bi_end_io;
931 static int ensure_next_mapping(struct pool *pool)
933 if (pool->next_mapping)
936 pool->next_mapping = mempool_alloc(pool->mapping_pool, GFP_ATOMIC);
938 return pool->next_mapping ? 0 : -ENOMEM;
941 static struct dm_thin_new_mapping *get_next_mapping(struct pool *pool)
943 struct dm_thin_new_mapping *m = pool->next_mapping;
945 BUG_ON(!pool->next_mapping);
947 memset(m, 0, sizeof(struct dm_thin_new_mapping));
948 INIT_LIST_HEAD(&m->list);
951 pool->next_mapping = NULL;
956 static void ll_zero(struct thin_c *tc, struct dm_thin_new_mapping *m,
957 sector_t begin, sector_t end)
960 struct dm_io_region to;
962 to.bdev = tc->pool_dev->bdev;
964 to.count = end - begin;
966 r = dm_kcopyd_zero(tc->pool->copier, 1, &to, 0, copy_complete, m);
968 DMERR_LIMIT("dm_kcopyd_zero() failed");
969 copy_complete(1, 1, m);
973 static void remap_and_issue_overwrite(struct thin_c *tc, struct bio *bio,
974 dm_block_t data_block,
975 struct dm_thin_new_mapping *m)
977 struct pool *pool = tc->pool;
978 struct dm_thin_endio_hook *h = dm_per_bio_data(bio, sizeof(struct dm_thin_endio_hook));
980 h->overwrite_mapping = m;
982 save_and_set_endio(bio, &m->saved_bi_end_io, overwrite_endio);
983 inc_all_io_entry(pool, bio);
984 remap_and_issue(tc, bio, data_block);
988 * A partial copy also needs to zero the uncopied region.
990 static void schedule_copy(struct thin_c *tc, dm_block_t virt_block,
991 struct dm_dev *origin, dm_block_t data_origin,
992 dm_block_t data_dest,
993 struct dm_bio_prison_cell *cell, struct bio *bio,
997 struct pool *pool = tc->pool;
998 struct dm_thin_new_mapping *m = get_next_mapping(pool);
1001 m->virt_block = virt_block;
1002 m->data_block = data_dest;
1006 * quiesce action + copy action + an extra reference held for the
1007 * duration of this function (we may need to inc later for a
1010 atomic_set(&m->prepare_actions, 3);
1012 if (!dm_deferred_set_add_work(pool->shared_read_ds, &m->list))
1013 complete_mapping_preparation(m); /* already quiesced */
1016 * IO to pool_dev remaps to the pool target's data_dev.
1018 * If the whole block of data is being overwritten, we can issue the
1019 * bio immediately. Otherwise we use kcopyd to clone the data first.
1021 if (io_overwrites_block(pool, bio))
1022 remap_and_issue_overwrite(tc, bio, data_dest, m);
1024 struct dm_io_region from, to;
1026 from.bdev = origin->bdev;
1027 from.sector = data_origin * pool->sectors_per_block;
1030 to.bdev = tc->pool_dev->bdev;
1031 to.sector = data_dest * pool->sectors_per_block;
1034 r = dm_kcopyd_copy(pool->copier, &from, 1, &to,
1035 0, copy_complete, m);
1037 DMERR_LIMIT("dm_kcopyd_copy() failed");
1038 copy_complete(1, 1, m);
1041 * We allow the zero to be issued, to simplify the
1042 * error path. Otherwise we'd need to start
1043 * worrying about decrementing the prepare_actions
1049 * Do we need to zero a tail region?
1051 if (len < pool->sectors_per_block && pool->pf.zero_new_blocks) {
1052 atomic_inc(&m->prepare_actions);
1054 data_dest * pool->sectors_per_block + len,
1055 (data_dest + 1) * pool->sectors_per_block);
1059 complete_mapping_preparation(m); /* drop our ref */
1062 static void schedule_internal_copy(struct thin_c *tc, dm_block_t virt_block,
1063 dm_block_t data_origin, dm_block_t data_dest,
1064 struct dm_bio_prison_cell *cell, struct bio *bio)
1066 schedule_copy(tc, virt_block, tc->pool_dev,
1067 data_origin, data_dest, cell, bio,
1068 tc->pool->sectors_per_block);
1071 static void schedule_zero(struct thin_c *tc, dm_block_t virt_block,
1072 dm_block_t data_block, struct dm_bio_prison_cell *cell,
1075 struct pool *pool = tc->pool;
1076 struct dm_thin_new_mapping *m = get_next_mapping(pool);
1078 atomic_set(&m->prepare_actions, 1); /* no need to quiesce */
1080 m->virt_block = virt_block;
1081 m->data_block = data_block;
1085 * If the whole block of data is being overwritten or we are not
1086 * zeroing pre-existing data, we can issue the bio immediately.
1087 * Otherwise we use kcopyd to zero the data first.
1089 if (pool->pf.zero_new_blocks) {
1090 if (io_overwrites_block(pool, bio))
1091 remap_and_issue_overwrite(tc, bio, data_block, m);
1093 ll_zero(tc, m, data_block * pool->sectors_per_block,
1094 (data_block + 1) * pool->sectors_per_block);
1096 process_prepared_mapping(m);
1099 static void schedule_external_copy(struct thin_c *tc, dm_block_t virt_block,
1100 dm_block_t data_dest,
1101 struct dm_bio_prison_cell *cell, struct bio *bio)
1103 struct pool *pool = tc->pool;
1104 sector_t virt_block_begin = virt_block * pool->sectors_per_block;
1105 sector_t virt_block_end = (virt_block + 1) * pool->sectors_per_block;
1107 if (virt_block_end <= tc->origin_size)
1108 schedule_copy(tc, virt_block, tc->origin_dev,
1109 virt_block, data_dest, cell, bio,
1110 pool->sectors_per_block);
1112 else if (virt_block_begin < tc->origin_size)
1113 schedule_copy(tc, virt_block, tc->origin_dev,
1114 virt_block, data_dest, cell, bio,
1115 tc->origin_size - virt_block_begin);
1118 schedule_zero(tc, virt_block, data_dest, cell, bio);
1121 static void set_pool_mode(struct pool *pool, enum pool_mode new_mode);
1123 static void check_for_space(struct pool *pool)
1128 if (get_pool_mode(pool) != PM_OUT_OF_DATA_SPACE)
1131 r = dm_pool_get_free_block_count(pool->pmd, &nr_free);
1136 set_pool_mode(pool, PM_WRITE);
1140 * A non-zero return indicates read_only or fail_io mode.
1141 * Many callers don't care about the return value.
1143 static int commit(struct pool *pool)
1147 if (get_pool_mode(pool) >= PM_READ_ONLY)
1150 r = dm_pool_commit_metadata(pool->pmd);
1152 metadata_operation_failed(pool, "dm_pool_commit_metadata", r);
1154 check_for_space(pool);
1159 static void check_low_water_mark(struct pool *pool, dm_block_t free_blocks)
1161 unsigned long flags;
1163 if (free_blocks <= pool->low_water_blocks && !pool->low_water_triggered) {
1164 DMWARN("%s: reached low water mark for data device: sending event.",
1165 dm_device_name(pool->pool_md));
1166 spin_lock_irqsave(&pool->lock, flags);
1167 pool->low_water_triggered = true;
1168 spin_unlock_irqrestore(&pool->lock, flags);
1169 dm_table_event(pool->ti->table);
1173 static int alloc_data_block(struct thin_c *tc, dm_block_t *result)
1176 dm_block_t free_blocks;
1177 struct pool *pool = tc->pool;
1179 if (WARN_ON(get_pool_mode(pool) != PM_WRITE))
1182 r = dm_pool_get_free_block_count(pool->pmd, &free_blocks);
1184 metadata_operation_failed(pool, "dm_pool_get_free_block_count", r);
1188 check_low_water_mark(pool, free_blocks);
1192 * Try to commit to see if that will free up some
1199 r = dm_pool_get_free_block_count(pool->pmd, &free_blocks);
1201 metadata_operation_failed(pool, "dm_pool_get_free_block_count", r);
1206 set_pool_mode(pool, PM_OUT_OF_DATA_SPACE);
1211 r = dm_pool_alloc_data_block(pool->pmd, result);
1213 metadata_operation_failed(pool, "dm_pool_alloc_data_block", r);
1221 * If we have run out of space, queue bios until the device is
1222 * resumed, presumably after having been reloaded with more space.
1224 static void retry_on_resume(struct bio *bio)
1226 struct dm_thin_endio_hook *h = dm_per_bio_data(bio, sizeof(struct dm_thin_endio_hook));
1227 struct thin_c *tc = h->tc;
1228 unsigned long flags;
1230 spin_lock_irqsave(&tc->lock, flags);
1231 bio_list_add(&tc->retry_on_resume_list, bio);
1232 spin_unlock_irqrestore(&tc->lock, flags);
1235 static int should_error_unserviceable_bio(struct pool *pool)
1237 enum pool_mode m = get_pool_mode(pool);
1241 /* Shouldn't get here */
1242 DMERR_LIMIT("bio unserviceable, yet pool is in PM_WRITE mode");
1245 case PM_OUT_OF_DATA_SPACE:
1246 return pool->pf.error_if_no_space ? -ENOSPC : 0;
1252 /* Shouldn't get here */
1253 DMERR_LIMIT("bio unserviceable, yet pool has an unknown mode");
1258 static void handle_unserviceable_bio(struct pool *pool, struct bio *bio)
1260 int error = should_error_unserviceable_bio(pool);
1263 bio_endio(bio, error);
1265 retry_on_resume(bio);
1268 static void retry_bios_on_resume(struct pool *pool, struct dm_bio_prison_cell *cell)
1271 struct bio_list bios;
1274 error = should_error_unserviceable_bio(pool);
1276 cell_error_with_code(pool, cell, error);
1280 bio_list_init(&bios);
1281 cell_release(pool, cell, &bios);
1283 while ((bio = bio_list_pop(&bios)))
1284 retry_on_resume(bio);
1287 static void process_discard_cell(struct thin_c *tc, struct dm_bio_prison_cell *cell)
1290 struct bio *bio = cell->holder;
1291 struct pool *pool = tc->pool;
1292 struct dm_bio_prison_cell *cell2;
1293 struct dm_cell_key key2;
1294 dm_block_t block = get_bio_block(tc, bio);
1295 struct dm_thin_lookup_result lookup_result;
1296 struct dm_thin_new_mapping *m;
1298 if (tc->requeue_mode) {
1299 cell_requeue(pool, cell);
1303 r = dm_thin_find_block(tc->td, block, 1, &lookup_result);
1307 * Check nobody is fiddling with this pool block. This can
1308 * happen if someone's in the process of breaking sharing
1311 build_data_key(tc->td, lookup_result.block, &key2);
1312 if (bio_detain(tc->pool, &key2, bio, &cell2)) {
1313 cell_defer_no_holder(tc, cell);
1317 if (io_overlaps_block(pool, bio)) {
1319 * IO may still be going to the destination block. We must
1320 * quiesce before we can do the removal.
1322 m = get_next_mapping(pool);
1324 m->pass_discard = pool->pf.discard_passdown;
1325 m->definitely_not_shared = !lookup_result.shared;
1326 m->virt_block = block;
1327 m->data_block = lookup_result.block;
1332 if (!dm_deferred_set_add_work(pool->all_io_ds, &m->list))
1333 pool->process_prepared_discard(m);
1336 inc_all_io_entry(pool, bio);
1337 cell_defer_no_holder(tc, cell);
1338 cell_defer_no_holder(tc, cell2);
1341 * The DM core makes sure that the discard doesn't span
1342 * a block boundary. So we submit the discard of a
1343 * partial block appropriately.
1345 if ((!lookup_result.shared) && pool->pf.discard_passdown)
1346 remap_and_issue(tc, bio, lookup_result.block);
1354 * It isn't provisioned, just forget it.
1356 cell_defer_no_holder(tc, cell);
1361 DMERR_LIMIT("%s: dm_thin_find_block() failed: error = %d",
1363 cell_defer_no_holder(tc, cell);
1369 static void process_discard_bio(struct thin_c *tc, struct bio *bio)
1371 struct dm_bio_prison_cell *cell;
1372 struct dm_cell_key key;
1373 dm_block_t block = get_bio_block(tc, bio);
1375 build_virtual_key(tc->td, block, &key);
1376 if (bio_detain(tc->pool, &key, bio, &cell))
1379 process_discard_cell(tc, cell);
1382 static void break_sharing(struct thin_c *tc, struct bio *bio, dm_block_t block,
1383 struct dm_cell_key *key,
1384 struct dm_thin_lookup_result *lookup_result,
1385 struct dm_bio_prison_cell *cell)
1388 dm_block_t data_block;
1389 struct pool *pool = tc->pool;
1391 r = alloc_data_block(tc, &data_block);
1394 schedule_internal_copy(tc, block, lookup_result->block,
1395 data_block, cell, bio);
1399 retry_bios_on_resume(pool, cell);
1403 DMERR_LIMIT("%s: alloc_data_block() failed: error = %d",
1405 cell_error(pool, cell);
1410 static void __remap_and_issue_shared_cell(void *context,
1411 struct dm_bio_prison_cell *cell)
1413 struct remap_info *info = context;
1416 while ((bio = bio_list_pop(&cell->bios))) {
1417 if ((bio_data_dir(bio) == WRITE) ||
1418 (bio->bi_rw & (REQ_DISCARD | REQ_FLUSH | REQ_FUA)))
1419 bio_list_add(&info->defer_bios, bio);
1421 struct dm_thin_endio_hook *h = dm_per_bio_data(bio, sizeof(struct dm_thin_endio_hook));;
1423 h->shared_read_entry = dm_deferred_entry_inc(info->tc->pool->shared_read_ds);
1424 inc_all_io_entry(info->tc->pool, bio);
1425 bio_list_add(&info->issue_bios, bio);
1430 static void remap_and_issue_shared_cell(struct thin_c *tc,
1431 struct dm_bio_prison_cell *cell,
1435 struct remap_info info;
1438 bio_list_init(&info.defer_bios);
1439 bio_list_init(&info.issue_bios);
1441 cell_visit_release(tc->pool, __remap_and_issue_shared_cell,
1444 while ((bio = bio_list_pop(&info.defer_bios)))
1445 thin_defer_bio(tc, bio);
1447 while ((bio = bio_list_pop(&info.issue_bios)))
1448 remap_and_issue(tc, bio, block);
1451 static void process_shared_bio(struct thin_c *tc, struct bio *bio,
1453 struct dm_thin_lookup_result *lookup_result,
1454 struct dm_bio_prison_cell *virt_cell)
1456 struct dm_bio_prison_cell *data_cell;
1457 struct pool *pool = tc->pool;
1458 struct dm_cell_key key;
1461 * If cell is already occupied, then sharing is already in the process
1462 * of being broken so we have nothing further to do here.
1464 build_data_key(tc->td, lookup_result->block, &key);
1465 if (bio_detain(pool, &key, bio, &data_cell)) {
1466 cell_defer_no_holder(tc, virt_cell);
1470 if (bio_data_dir(bio) == WRITE && bio->bi_iter.bi_size) {
1471 break_sharing(tc, bio, block, &key, lookup_result, data_cell);
1472 cell_defer_no_holder(tc, virt_cell);
1474 struct dm_thin_endio_hook *h = dm_per_bio_data(bio, sizeof(struct dm_thin_endio_hook));
1476 h->shared_read_entry = dm_deferred_entry_inc(pool->shared_read_ds);
1477 inc_all_io_entry(pool, bio);
1478 remap_and_issue(tc, bio, lookup_result->block);
1480 remap_and_issue_shared_cell(tc, data_cell, lookup_result->block);
1481 remap_and_issue_shared_cell(tc, virt_cell, lookup_result->block);
1485 static void provision_block(struct thin_c *tc, struct bio *bio, dm_block_t block,
1486 struct dm_bio_prison_cell *cell)
1489 dm_block_t data_block;
1490 struct pool *pool = tc->pool;
1493 * Remap empty bios (flushes) immediately, without provisioning.
1495 if (!bio->bi_iter.bi_size) {
1496 inc_all_io_entry(pool, bio);
1497 cell_defer_no_holder(tc, cell);
1499 remap_and_issue(tc, bio, 0);
1504 * Fill read bios with zeroes and complete them immediately.
1506 if (bio_data_dir(bio) == READ) {
1508 cell_defer_no_holder(tc, cell);
1513 r = alloc_data_block(tc, &data_block);
1517 schedule_external_copy(tc, block, data_block, cell, bio);
1519 schedule_zero(tc, block, data_block, cell, bio);
1523 retry_bios_on_resume(pool, cell);
1527 DMERR_LIMIT("%s: alloc_data_block() failed: error = %d",
1529 cell_error(pool, cell);
1534 static void process_cell(struct thin_c *tc, struct dm_bio_prison_cell *cell)
1537 struct pool *pool = tc->pool;
1538 struct bio *bio = cell->holder;
1539 dm_block_t block = get_bio_block(tc, bio);
1540 struct dm_thin_lookup_result lookup_result;
1542 if (tc->requeue_mode) {
1543 cell_requeue(pool, cell);
1547 r = dm_thin_find_block(tc->td, block, 1, &lookup_result);
1550 if (lookup_result.shared)
1551 process_shared_bio(tc, bio, block, &lookup_result, cell);
1553 inc_all_io_entry(pool, bio);
1554 remap_and_issue(tc, bio, lookup_result.block);
1555 inc_remap_and_issue_cell(tc, cell, lookup_result.block);
1560 if (bio_data_dir(bio) == READ && tc->origin_dev) {
1561 inc_all_io_entry(pool, bio);
1562 cell_defer_no_holder(tc, cell);
1564 if (bio_end_sector(bio) <= tc->origin_size)
1565 remap_to_origin_and_issue(tc, bio);
1567 else if (bio->bi_iter.bi_sector < tc->origin_size) {
1569 bio->bi_iter.bi_size = (tc->origin_size - bio->bi_iter.bi_sector) << SECTOR_SHIFT;
1570 remap_to_origin_and_issue(tc, bio);
1577 provision_block(tc, bio, block, cell);
1581 DMERR_LIMIT("%s: dm_thin_find_block() failed: error = %d",
1583 cell_defer_no_holder(tc, cell);
1589 static void process_bio(struct thin_c *tc, struct bio *bio)
1591 struct pool *pool = tc->pool;
1592 dm_block_t block = get_bio_block(tc, bio);
1593 struct dm_bio_prison_cell *cell;
1594 struct dm_cell_key key;
1597 * If cell is already occupied, then the block is already
1598 * being provisioned so we have nothing further to do here.
1600 build_virtual_key(tc->td, block, &key);
1601 if (bio_detain(pool, &key, bio, &cell))
1604 process_cell(tc, cell);
1607 static void __process_bio_read_only(struct thin_c *tc, struct bio *bio,
1608 struct dm_bio_prison_cell *cell)
1611 int rw = bio_data_dir(bio);
1612 dm_block_t block = get_bio_block(tc, bio);
1613 struct dm_thin_lookup_result lookup_result;
1615 r = dm_thin_find_block(tc->td, block, 1, &lookup_result);
1618 if (lookup_result.shared && (rw == WRITE) && bio->bi_iter.bi_size) {
1619 handle_unserviceable_bio(tc->pool, bio);
1621 cell_defer_no_holder(tc, cell);
1623 inc_all_io_entry(tc->pool, bio);
1624 remap_and_issue(tc, bio, lookup_result.block);
1626 inc_remap_and_issue_cell(tc, cell, lookup_result.block);
1632 cell_defer_no_holder(tc, cell);
1634 handle_unserviceable_bio(tc->pool, bio);
1638 if (tc->origin_dev) {
1639 inc_all_io_entry(tc->pool, bio);
1640 remap_to_origin_and_issue(tc, bio);
1649 DMERR_LIMIT("%s: dm_thin_find_block() failed: error = %d",
1652 cell_defer_no_holder(tc, cell);
1658 static void process_bio_read_only(struct thin_c *tc, struct bio *bio)
1660 __process_bio_read_only(tc, bio, NULL);
1663 static void process_cell_read_only(struct thin_c *tc, struct dm_bio_prison_cell *cell)
1665 __process_bio_read_only(tc, cell->holder, cell);
1668 static void process_bio_success(struct thin_c *tc, struct bio *bio)
1673 static void process_bio_fail(struct thin_c *tc, struct bio *bio)
1678 static void process_cell_success(struct thin_c *tc, struct dm_bio_prison_cell *cell)
1680 cell_success(tc->pool, cell);
1683 static void process_cell_fail(struct thin_c *tc, struct dm_bio_prison_cell *cell)
1685 cell_error(tc->pool, cell);
1689 * FIXME: should we also commit due to size of transaction, measured in
1692 static int need_commit_due_to_time(struct pool *pool)
1694 return !time_in_range(jiffies, pool->last_commit_jiffies,
1695 pool->last_commit_jiffies + COMMIT_PERIOD);
1698 #define thin_pbd(node) rb_entry((node), struct dm_thin_endio_hook, rb_node)
1699 #define thin_bio(pbd) dm_bio_from_per_bio_data((pbd), sizeof(struct dm_thin_endio_hook))
1701 static void __thin_bio_rb_add(struct thin_c *tc, struct bio *bio)
1703 struct rb_node **rbp, *parent;
1704 struct dm_thin_endio_hook *pbd;
1705 sector_t bi_sector = bio->bi_iter.bi_sector;
1707 rbp = &tc->sort_bio_list.rb_node;
1711 pbd = thin_pbd(parent);
1713 if (bi_sector < thin_bio(pbd)->bi_iter.bi_sector)
1714 rbp = &(*rbp)->rb_left;
1716 rbp = &(*rbp)->rb_right;
1719 pbd = dm_per_bio_data(bio, sizeof(struct dm_thin_endio_hook));
1720 rb_link_node(&pbd->rb_node, parent, rbp);
1721 rb_insert_color(&pbd->rb_node, &tc->sort_bio_list);
1724 static void __extract_sorted_bios(struct thin_c *tc)
1726 struct rb_node *node;
1727 struct dm_thin_endio_hook *pbd;
1730 for (node = rb_first(&tc->sort_bio_list); node; node = rb_next(node)) {
1731 pbd = thin_pbd(node);
1732 bio = thin_bio(pbd);
1734 bio_list_add(&tc->deferred_bio_list, bio);
1735 rb_erase(&pbd->rb_node, &tc->sort_bio_list);
1738 WARN_ON(!RB_EMPTY_ROOT(&tc->sort_bio_list));
1741 static void __sort_thin_deferred_bios(struct thin_c *tc)
1744 struct bio_list bios;
1746 bio_list_init(&bios);
1747 bio_list_merge(&bios, &tc->deferred_bio_list);
1748 bio_list_init(&tc->deferred_bio_list);
1750 /* Sort deferred_bio_list using rb-tree */
1751 while ((bio = bio_list_pop(&bios)))
1752 __thin_bio_rb_add(tc, bio);
1755 * Transfer the sorted bios in sort_bio_list back to
1756 * deferred_bio_list to allow lockless submission of
1759 __extract_sorted_bios(tc);
1762 static void process_thin_deferred_bios(struct thin_c *tc)
1764 struct pool *pool = tc->pool;
1765 unsigned long flags;
1767 struct bio_list bios;
1768 struct blk_plug plug;
1771 if (tc->requeue_mode) {
1772 error_thin_bio_list(tc, &tc->deferred_bio_list, DM_ENDIO_REQUEUE);
1776 bio_list_init(&bios);
1778 spin_lock_irqsave(&tc->lock, flags);
1780 if (bio_list_empty(&tc->deferred_bio_list)) {
1781 spin_unlock_irqrestore(&tc->lock, flags);
1785 __sort_thin_deferred_bios(tc);
1787 bio_list_merge(&bios, &tc->deferred_bio_list);
1788 bio_list_init(&tc->deferred_bio_list);
1790 spin_unlock_irqrestore(&tc->lock, flags);
1792 blk_start_plug(&plug);
1793 while ((bio = bio_list_pop(&bios))) {
1795 * If we've got no free new_mapping structs, and processing
1796 * this bio might require one, we pause until there are some
1797 * prepared mappings to process.
1799 if (ensure_next_mapping(pool)) {
1800 spin_lock_irqsave(&tc->lock, flags);
1801 bio_list_add(&tc->deferred_bio_list, bio);
1802 bio_list_merge(&tc->deferred_bio_list, &bios);
1803 spin_unlock_irqrestore(&tc->lock, flags);
1807 if (bio->bi_rw & REQ_DISCARD)
1808 pool->process_discard(tc, bio);
1810 pool->process_bio(tc, bio);
1812 if ((count++ & 127) == 0) {
1813 throttle_work_update(&pool->throttle);
1814 dm_pool_issue_prefetches(pool->pmd);
1817 blk_finish_plug(&plug);
1820 static int cmp_cells(const void *lhs, const void *rhs)
1822 struct dm_bio_prison_cell *lhs_cell = *((struct dm_bio_prison_cell **) lhs);
1823 struct dm_bio_prison_cell *rhs_cell = *((struct dm_bio_prison_cell **) rhs);
1825 BUG_ON(!lhs_cell->holder);
1826 BUG_ON(!rhs_cell->holder);
1828 if (lhs_cell->holder->bi_iter.bi_sector < rhs_cell->holder->bi_iter.bi_sector)
1831 if (lhs_cell->holder->bi_iter.bi_sector > rhs_cell->holder->bi_iter.bi_sector)
1837 static unsigned sort_cells(struct pool *pool, struct list_head *cells)
1840 struct dm_bio_prison_cell *cell, *tmp;
1842 list_for_each_entry_safe(cell, tmp, cells, user_list) {
1843 if (count >= CELL_SORT_ARRAY_SIZE)
1846 pool->cell_sort_array[count++] = cell;
1847 list_del(&cell->user_list);
1850 sort(pool->cell_sort_array, count, sizeof(cell), cmp_cells, NULL);
1855 static void process_thin_deferred_cells(struct thin_c *tc)
1857 struct pool *pool = tc->pool;
1858 unsigned long flags;
1859 struct list_head cells;
1860 struct dm_bio_prison_cell *cell;
1861 unsigned i, j, count;
1863 INIT_LIST_HEAD(&cells);
1865 spin_lock_irqsave(&tc->lock, flags);
1866 list_splice_init(&tc->deferred_cells, &cells);
1867 spin_unlock_irqrestore(&tc->lock, flags);
1869 if (list_empty(&cells))
1873 count = sort_cells(tc->pool, &cells);
1875 for (i = 0; i < count; i++) {
1876 cell = pool->cell_sort_array[i];
1877 BUG_ON(!cell->holder);
1880 * If we've got no free new_mapping structs, and processing
1881 * this bio might require one, we pause until there are some
1882 * prepared mappings to process.
1884 if (ensure_next_mapping(pool)) {
1885 for (j = i; j < count; j++)
1886 list_add(&pool->cell_sort_array[j]->user_list, &cells);
1888 spin_lock_irqsave(&tc->lock, flags);
1889 list_splice(&cells, &tc->deferred_cells);
1890 spin_unlock_irqrestore(&tc->lock, flags);
1894 if (cell->holder->bi_rw & REQ_DISCARD)
1895 pool->process_discard_cell(tc, cell);
1897 pool->process_cell(tc, cell);
1899 } while (!list_empty(&cells));
1902 static void thin_get(struct thin_c *tc);
1903 static void thin_put(struct thin_c *tc);
1906 * We can't hold rcu_read_lock() around code that can block. So we
1907 * find a thin with the rcu lock held; bump a refcount; then drop
1910 static struct thin_c *get_first_thin(struct pool *pool)
1912 struct thin_c *tc = NULL;
1915 if (!list_empty(&pool->active_thins)) {
1916 tc = list_entry_rcu(pool->active_thins.next, struct thin_c, list);
1924 static struct thin_c *get_next_thin(struct pool *pool, struct thin_c *tc)
1926 struct thin_c *old_tc = tc;
1929 list_for_each_entry_continue_rcu(tc, &pool->active_thins, list) {
1941 static void process_deferred_bios(struct pool *pool)
1943 unsigned long flags;
1945 struct bio_list bios;
1948 tc = get_first_thin(pool);
1950 process_thin_deferred_cells(tc);
1951 process_thin_deferred_bios(tc);
1952 tc = get_next_thin(pool, tc);
1956 * If there are any deferred flush bios, we must commit
1957 * the metadata before issuing them.
1959 bio_list_init(&bios);
1960 spin_lock_irqsave(&pool->lock, flags);
1961 bio_list_merge(&bios, &pool->deferred_flush_bios);
1962 bio_list_init(&pool->deferred_flush_bios);
1963 spin_unlock_irqrestore(&pool->lock, flags);
1965 if (bio_list_empty(&bios) &&
1966 !(dm_pool_changed_this_transaction(pool->pmd) && need_commit_due_to_time(pool)))
1970 while ((bio = bio_list_pop(&bios)))
1974 pool->last_commit_jiffies = jiffies;
1976 while ((bio = bio_list_pop(&bios)))
1977 generic_make_request(bio);
1980 static void do_worker(struct work_struct *ws)
1982 struct pool *pool = container_of(ws, struct pool, worker);
1984 throttle_work_start(&pool->throttle);
1985 dm_pool_issue_prefetches(pool->pmd);
1986 throttle_work_update(&pool->throttle);
1987 process_prepared(pool, &pool->prepared_mappings, &pool->process_prepared_mapping);
1988 throttle_work_update(&pool->throttle);
1989 process_prepared(pool, &pool->prepared_discards, &pool->process_prepared_discard);
1990 throttle_work_update(&pool->throttle);
1991 process_deferred_bios(pool);
1992 throttle_work_complete(&pool->throttle);
1996 * We want to commit periodically so that not too much
1997 * unwritten data builds up.
1999 static void do_waker(struct work_struct *ws)
2001 struct pool *pool = container_of(to_delayed_work(ws), struct pool, waker);
2003 queue_delayed_work(pool->wq, &pool->waker, COMMIT_PERIOD);
2007 * We're holding onto IO to allow userland time to react. After the
2008 * timeout either the pool will have been resized (and thus back in
2009 * PM_WRITE mode), or we degrade to PM_READ_ONLY and start erroring IO.
2011 static void do_no_space_timeout(struct work_struct *ws)
2013 struct pool *pool = container_of(to_delayed_work(ws), struct pool,
2016 if (get_pool_mode(pool) == PM_OUT_OF_DATA_SPACE && !pool->pf.error_if_no_space)
2017 set_pool_mode(pool, PM_READ_ONLY);
2020 /*----------------------------------------------------------------*/
2023 struct work_struct worker;
2024 struct completion complete;
2027 static struct pool_work *to_pool_work(struct work_struct *ws)
2029 return container_of(ws, struct pool_work, worker);
2032 static void pool_work_complete(struct pool_work *pw)
2034 complete(&pw->complete);
2037 static void pool_work_wait(struct pool_work *pw, struct pool *pool,
2038 void (*fn)(struct work_struct *))
2040 INIT_WORK_ONSTACK(&pw->worker, fn);
2041 init_completion(&pw->complete);
2042 queue_work(pool->wq, &pw->worker);
2043 wait_for_completion(&pw->complete);
2046 /*----------------------------------------------------------------*/
2048 struct noflush_work {
2049 struct pool_work pw;
2053 static struct noflush_work *to_noflush(struct work_struct *ws)
2055 return container_of(to_pool_work(ws), struct noflush_work, pw);
2058 static void do_noflush_start(struct work_struct *ws)
2060 struct noflush_work *w = to_noflush(ws);
2061 w->tc->requeue_mode = true;
2063 pool_work_complete(&w->pw);
2066 static void do_noflush_stop(struct work_struct *ws)
2068 struct noflush_work *w = to_noflush(ws);
2069 w->tc->requeue_mode = false;
2070 pool_work_complete(&w->pw);
2073 static void noflush_work(struct thin_c *tc, void (*fn)(struct work_struct *))
2075 struct noflush_work w;
2078 pool_work_wait(&w.pw, tc->pool, fn);
2081 /*----------------------------------------------------------------*/
2083 static enum pool_mode get_pool_mode(struct pool *pool)
2085 return pool->pf.mode;
2088 static void notify_of_pool_mode_change(struct pool *pool, const char *new_mode)
2090 dm_table_event(pool->ti->table);
2091 DMINFO("%s: switching pool to %s mode",
2092 dm_device_name(pool->pool_md), new_mode);
2095 static void set_pool_mode(struct pool *pool, enum pool_mode new_mode)
2097 struct pool_c *pt = pool->ti->private;
2098 bool needs_check = dm_pool_metadata_needs_check(pool->pmd);
2099 enum pool_mode old_mode = get_pool_mode(pool);
2100 unsigned long no_space_timeout = ACCESS_ONCE(no_space_timeout_secs) * HZ;
2103 * Never allow the pool to transition to PM_WRITE mode if user
2104 * intervention is required to verify metadata and data consistency.
2106 if (new_mode == PM_WRITE && needs_check) {
2107 DMERR("%s: unable to switch pool to write mode until repaired.",
2108 dm_device_name(pool->pool_md));
2109 if (old_mode != new_mode)
2110 new_mode = old_mode;
2112 new_mode = PM_READ_ONLY;
2115 * If we were in PM_FAIL mode, rollback of metadata failed. We're
2116 * not going to recover without a thin_repair. So we never let the
2117 * pool move out of the old mode.
2119 if (old_mode == PM_FAIL)
2120 new_mode = old_mode;
2124 if (old_mode != new_mode)
2125 notify_of_pool_mode_change(pool, "failure");
2126 dm_pool_metadata_read_only(pool->pmd);
2127 pool->process_bio = process_bio_fail;
2128 pool->process_discard = process_bio_fail;
2129 pool->process_cell = process_cell_fail;
2130 pool->process_discard_cell = process_cell_fail;
2131 pool->process_prepared_mapping = process_prepared_mapping_fail;
2132 pool->process_prepared_discard = process_prepared_discard_fail;
2134 error_retry_list(pool);
2138 if (old_mode != new_mode)
2139 notify_of_pool_mode_change(pool, "read-only");
2140 dm_pool_metadata_read_only(pool->pmd);
2141 pool->process_bio = process_bio_read_only;
2142 pool->process_discard = process_bio_success;
2143 pool->process_cell = process_cell_read_only;
2144 pool->process_discard_cell = process_cell_success;
2145 pool->process_prepared_mapping = process_prepared_mapping_fail;
2146 pool->process_prepared_discard = process_prepared_discard_passdown;
2148 error_retry_list(pool);
2151 case PM_OUT_OF_DATA_SPACE:
2153 * Ideally we'd never hit this state; the low water mark
2154 * would trigger userland to extend the pool before we
2155 * completely run out of data space. However, many small
2156 * IOs to unprovisioned space can consume data space at an
2157 * alarming rate. Adjust your low water mark if you're
2158 * frequently seeing this mode.
2160 if (old_mode != new_mode)
2161 notify_of_pool_mode_change(pool, "out-of-data-space");
2162 pool->process_bio = process_bio_read_only;
2163 pool->process_discard = process_discard_bio;
2164 pool->process_cell = process_cell_read_only;
2165 pool->process_discard_cell = process_discard_cell;
2166 pool->process_prepared_mapping = process_prepared_mapping;
2167 pool->process_prepared_discard = process_prepared_discard;
2169 if (!pool->pf.error_if_no_space && no_space_timeout)
2170 queue_delayed_work(pool->wq, &pool->no_space_timeout, no_space_timeout);
2174 if (old_mode != new_mode)
2175 notify_of_pool_mode_change(pool, "write");
2176 dm_pool_metadata_read_write(pool->pmd);
2177 pool->process_bio = process_bio;
2178 pool->process_discard = process_discard_bio;
2179 pool->process_cell = process_cell;
2180 pool->process_discard_cell = process_discard_cell;
2181 pool->process_prepared_mapping = process_prepared_mapping;
2182 pool->process_prepared_discard = process_prepared_discard;
2186 pool->pf.mode = new_mode;
2188 * The pool mode may have changed, sync it so bind_control_target()
2189 * doesn't cause an unexpected mode transition on resume.
2191 pt->adjusted_pf.mode = new_mode;
2194 static void abort_transaction(struct pool *pool)
2196 const char *dev_name = dm_device_name(pool->pool_md);
2198 DMERR_LIMIT("%s: aborting current metadata transaction", dev_name);
2199 if (dm_pool_abort_metadata(pool->pmd)) {
2200 DMERR("%s: failed to abort metadata transaction", dev_name);
2201 set_pool_mode(pool, PM_FAIL);
2204 if (dm_pool_metadata_set_needs_check(pool->pmd)) {
2205 DMERR("%s: failed to set 'needs_check' flag in metadata", dev_name);
2206 set_pool_mode(pool, PM_FAIL);
2210 static void metadata_operation_failed(struct pool *pool, const char *op, int r)
2212 DMERR_LIMIT("%s: metadata operation '%s' failed: error = %d",
2213 dm_device_name(pool->pool_md), op, r);
2215 abort_transaction(pool);
2216 set_pool_mode(pool, PM_READ_ONLY);
2219 /*----------------------------------------------------------------*/
2222 * Mapping functions.
2226 * Called only while mapping a thin bio to hand it over to the workqueue.
2228 static void thin_defer_bio(struct thin_c *tc, struct bio *bio)
2230 unsigned long flags;
2231 struct pool *pool = tc->pool;
2233 spin_lock_irqsave(&tc->lock, flags);
2234 bio_list_add(&tc->deferred_bio_list, bio);
2235 spin_unlock_irqrestore(&tc->lock, flags);
2240 static void thin_defer_bio_with_throttle(struct thin_c *tc, struct bio *bio)
2242 struct pool *pool = tc->pool;
2244 throttle_lock(&pool->throttle);
2245 thin_defer_bio(tc, bio);
2246 throttle_unlock(&pool->throttle);
2249 static void thin_defer_cell(struct thin_c *tc, struct dm_bio_prison_cell *cell)
2251 unsigned long flags;
2252 struct pool *pool = tc->pool;
2254 throttle_lock(&pool->throttle);
2255 spin_lock_irqsave(&tc->lock, flags);
2256 list_add_tail(&cell->user_list, &tc->deferred_cells);
2257 spin_unlock_irqrestore(&tc->lock, flags);
2258 throttle_unlock(&pool->throttle);
2263 static void thin_hook_bio(struct thin_c *tc, struct bio *bio)
2265 struct dm_thin_endio_hook *h = dm_per_bio_data(bio, sizeof(struct dm_thin_endio_hook));
2268 h->shared_read_entry = NULL;
2269 h->all_io_entry = NULL;
2270 h->overwrite_mapping = NULL;
2274 * Non-blocking function called from the thin target's map function.
2276 static int thin_bio_map(struct dm_target *ti, struct bio *bio)
2279 struct thin_c *tc = ti->private;
2280 dm_block_t block = get_bio_block(tc, bio);
2281 struct dm_thin_device *td = tc->td;
2282 struct dm_thin_lookup_result result;
2283 struct dm_bio_prison_cell *virt_cell, *data_cell;
2284 struct dm_cell_key key;
2286 thin_hook_bio(tc, bio);
2288 if (tc->requeue_mode) {
2289 bio_endio(bio, DM_ENDIO_REQUEUE);
2290 return DM_MAPIO_SUBMITTED;
2293 if (get_pool_mode(tc->pool) == PM_FAIL) {
2295 return DM_MAPIO_SUBMITTED;
2298 if (bio->bi_rw & (REQ_DISCARD | REQ_FLUSH | REQ_FUA)) {
2299 thin_defer_bio_with_throttle(tc, bio);
2300 return DM_MAPIO_SUBMITTED;
2304 * We must hold the virtual cell before doing the lookup, otherwise
2305 * there's a race with discard.
2307 build_virtual_key(tc->td, block, &key);
2308 if (bio_detain(tc->pool, &key, bio, &virt_cell))
2309 return DM_MAPIO_SUBMITTED;
2311 r = dm_thin_find_block(td, block, 0, &result);
2314 * Note that we defer readahead too.
2318 if (unlikely(result.shared)) {
2320 * We have a race condition here between the
2321 * result.shared value returned by the lookup and
2322 * snapshot creation, which may cause new
2325 * To avoid this always quiesce the origin before
2326 * taking the snap. You want to do this anyway to
2327 * ensure a consistent application view
2330 * More distant ancestors are irrelevant. The
2331 * shared flag will be set in their case.
2333 thin_defer_cell(tc, virt_cell);
2334 return DM_MAPIO_SUBMITTED;
2337 build_data_key(tc->td, result.block, &key);
2338 if (bio_detain(tc->pool, &key, bio, &data_cell)) {
2339 cell_defer_no_holder(tc, virt_cell);
2340 return DM_MAPIO_SUBMITTED;
2343 inc_all_io_entry(tc->pool, bio);
2344 cell_defer_no_holder(tc, data_cell);
2345 cell_defer_no_holder(tc, virt_cell);
2347 remap(tc, bio, result.block);
2348 return DM_MAPIO_REMAPPED;
2352 thin_defer_cell(tc, virt_cell);
2353 return DM_MAPIO_SUBMITTED;
2357 * Must always call bio_io_error on failure.
2358 * dm_thin_find_block can fail with -EINVAL if the
2359 * pool is switched to fail-io mode.
2362 cell_defer_no_holder(tc, virt_cell);
2363 return DM_MAPIO_SUBMITTED;
2367 static int pool_is_congested(struct dm_target_callbacks *cb, int bdi_bits)
2369 struct pool_c *pt = container_of(cb, struct pool_c, callbacks);
2370 struct request_queue *q;
2372 if (get_pool_mode(pt->pool) == PM_OUT_OF_DATA_SPACE)
2375 q = bdev_get_queue(pt->data_dev->bdev);
2376 return bdi_congested(&q->backing_dev_info, bdi_bits);
2379 static void requeue_bios(struct pool *pool)
2381 unsigned long flags;
2385 list_for_each_entry_rcu(tc, &pool->active_thins, list) {
2386 spin_lock_irqsave(&tc->lock, flags);
2387 bio_list_merge(&tc->deferred_bio_list, &tc->retry_on_resume_list);
2388 bio_list_init(&tc->retry_on_resume_list);
2389 spin_unlock_irqrestore(&tc->lock, flags);
2394 /*----------------------------------------------------------------
2395 * Binding of control targets to a pool object
2396 *--------------------------------------------------------------*/
2397 static bool data_dev_supports_discard(struct pool_c *pt)
2399 struct request_queue *q = bdev_get_queue(pt->data_dev->bdev);
2401 return q && blk_queue_discard(q);
2404 static bool is_factor(sector_t block_size, uint32_t n)
2406 return !sector_div(block_size, n);
2410 * If discard_passdown was enabled verify that the data device
2411 * supports discards. Disable discard_passdown if not.
2413 static void disable_passdown_if_not_supported(struct pool_c *pt)
2415 struct pool *pool = pt->pool;
2416 struct block_device *data_bdev = pt->data_dev->bdev;
2417 struct queue_limits *data_limits = &bdev_get_queue(data_bdev)->limits;
2418 sector_t block_size = pool->sectors_per_block << SECTOR_SHIFT;
2419 const char *reason = NULL;
2420 char buf[BDEVNAME_SIZE];
2422 if (!pt->adjusted_pf.discard_passdown)
2425 if (!data_dev_supports_discard(pt))
2426 reason = "discard unsupported";
2428 else if (data_limits->max_discard_sectors < pool->sectors_per_block)
2429 reason = "max discard sectors smaller than a block";
2431 else if (data_limits->discard_granularity > block_size)
2432 reason = "discard granularity larger than a block";
2434 else if (!is_factor(block_size, data_limits->discard_granularity))
2435 reason = "discard granularity not a factor of block size";
2438 DMWARN("Data device (%s) %s: Disabling discard passdown.", bdevname(data_bdev, buf), reason);
2439 pt->adjusted_pf.discard_passdown = false;
2443 static int bind_control_target(struct pool *pool, struct dm_target *ti)
2445 struct pool_c *pt = ti->private;
2448 * We want to make sure that a pool in PM_FAIL mode is never upgraded.
2450 enum pool_mode old_mode = get_pool_mode(pool);
2451 enum pool_mode new_mode = pt->adjusted_pf.mode;
2454 * Don't change the pool's mode until set_pool_mode() below.
2455 * Otherwise the pool's process_* function pointers may
2456 * not match the desired pool mode.
2458 pt->adjusted_pf.mode = old_mode;
2461 pool->pf = pt->adjusted_pf;
2462 pool->low_water_blocks = pt->low_water_blocks;
2464 set_pool_mode(pool, new_mode);
2469 static void unbind_control_target(struct pool *pool, struct dm_target *ti)
2475 /*----------------------------------------------------------------
2477 *--------------------------------------------------------------*/
2478 /* Initialize pool features. */
2479 static void pool_features_init(struct pool_features *pf)
2481 pf->mode = PM_WRITE;
2482 pf->zero_new_blocks = true;
2483 pf->discard_enabled = true;
2484 pf->discard_passdown = true;
2485 pf->error_if_no_space = false;
2488 static void __pool_destroy(struct pool *pool)
2490 __pool_table_remove(pool);
2492 if (dm_pool_metadata_close(pool->pmd) < 0)
2493 DMWARN("%s: dm_pool_metadata_close() failed.", __func__);
2495 dm_bio_prison_destroy(pool->prison);
2496 dm_kcopyd_client_destroy(pool->copier);
2499 destroy_workqueue(pool->wq);
2501 if (pool->next_mapping)
2502 mempool_free(pool->next_mapping, pool->mapping_pool);
2503 mempool_destroy(pool->mapping_pool);
2504 dm_deferred_set_destroy(pool->shared_read_ds);
2505 dm_deferred_set_destroy(pool->all_io_ds);
2509 static struct kmem_cache *_new_mapping_cache;
2511 static struct pool *pool_create(struct mapped_device *pool_md,
2512 struct block_device *metadata_dev,
2513 unsigned long block_size,
2514 int read_only, char **error)
2519 struct dm_pool_metadata *pmd;
2520 bool format_device = read_only ? false : true;
2522 pmd = dm_pool_metadata_open(metadata_dev, block_size, format_device);
2524 *error = "Error creating metadata object";
2525 return (struct pool *)pmd;
2528 pool = kmalloc(sizeof(*pool), GFP_KERNEL);
2530 *error = "Error allocating memory for pool";
2531 err_p = ERR_PTR(-ENOMEM);
2536 pool->sectors_per_block = block_size;
2537 if (block_size & (block_size - 1))
2538 pool->sectors_per_block_shift = -1;
2540 pool->sectors_per_block_shift = __ffs(block_size);
2541 pool->low_water_blocks = 0;
2542 pool_features_init(&pool->pf);
2543 pool->prison = dm_bio_prison_create();
2544 if (!pool->prison) {
2545 *error = "Error creating pool's bio prison";
2546 err_p = ERR_PTR(-ENOMEM);
2550 pool->copier = dm_kcopyd_client_create(&dm_kcopyd_throttle);
2551 if (IS_ERR(pool->copier)) {
2552 r = PTR_ERR(pool->copier);
2553 *error = "Error creating pool's kcopyd client";
2555 goto bad_kcopyd_client;
2559 * Create singlethreaded workqueue that will service all devices
2560 * that use this metadata.
2562 pool->wq = alloc_ordered_workqueue("dm-" DM_MSG_PREFIX, WQ_MEM_RECLAIM);
2564 *error = "Error creating pool's workqueue";
2565 err_p = ERR_PTR(-ENOMEM);
2569 throttle_init(&pool->throttle);
2570 INIT_WORK(&pool->worker, do_worker);
2571 INIT_DELAYED_WORK(&pool->waker, do_waker);
2572 INIT_DELAYED_WORK(&pool->no_space_timeout, do_no_space_timeout);
2573 spin_lock_init(&pool->lock);
2574 bio_list_init(&pool->deferred_flush_bios);
2575 INIT_LIST_HEAD(&pool->prepared_mappings);
2576 INIT_LIST_HEAD(&pool->prepared_discards);
2577 INIT_LIST_HEAD(&pool->active_thins);
2578 pool->low_water_triggered = false;
2579 pool->suspended = true;
2581 pool->shared_read_ds = dm_deferred_set_create();
2582 if (!pool->shared_read_ds) {
2583 *error = "Error creating pool's shared read deferred set";
2584 err_p = ERR_PTR(-ENOMEM);
2585 goto bad_shared_read_ds;
2588 pool->all_io_ds = dm_deferred_set_create();
2589 if (!pool->all_io_ds) {
2590 *error = "Error creating pool's all io deferred set";
2591 err_p = ERR_PTR(-ENOMEM);
2595 pool->next_mapping = NULL;
2596 pool->mapping_pool = mempool_create_slab_pool(MAPPING_POOL_SIZE,
2597 _new_mapping_cache);
2598 if (!pool->mapping_pool) {
2599 *error = "Error creating pool's mapping mempool";
2600 err_p = ERR_PTR(-ENOMEM);
2601 goto bad_mapping_pool;
2604 pool->ref_count = 1;
2605 pool->last_commit_jiffies = jiffies;
2606 pool->pool_md = pool_md;
2607 pool->md_dev = metadata_dev;
2608 __pool_table_insert(pool);
2613 dm_deferred_set_destroy(pool->all_io_ds);
2615 dm_deferred_set_destroy(pool->shared_read_ds);
2617 destroy_workqueue(pool->wq);
2619 dm_kcopyd_client_destroy(pool->copier);
2621 dm_bio_prison_destroy(pool->prison);
2625 if (dm_pool_metadata_close(pmd))
2626 DMWARN("%s: dm_pool_metadata_close() failed.", __func__);
2631 static void __pool_inc(struct pool *pool)
2633 BUG_ON(!mutex_is_locked(&dm_thin_pool_table.mutex));
2637 static void __pool_dec(struct pool *pool)
2639 BUG_ON(!mutex_is_locked(&dm_thin_pool_table.mutex));
2640 BUG_ON(!pool->ref_count);
2641 if (!--pool->ref_count)
2642 __pool_destroy(pool);
2645 static struct pool *__pool_find(struct mapped_device *pool_md,
2646 struct block_device *metadata_dev,
2647 unsigned long block_size, int read_only,
2648 char **error, int *created)
2650 struct pool *pool = __pool_table_lookup_metadata_dev(metadata_dev);
2653 if (pool->pool_md != pool_md) {
2654 *error = "metadata device already in use by a pool";
2655 return ERR_PTR(-EBUSY);
2660 pool = __pool_table_lookup(pool_md);
2662 if (pool->md_dev != metadata_dev) {
2663 *error = "different pool cannot replace a pool";
2664 return ERR_PTR(-EINVAL);
2669 pool = pool_create(pool_md, metadata_dev, block_size, read_only, error);
2677 /*----------------------------------------------------------------
2678 * Pool target methods
2679 *--------------------------------------------------------------*/
2680 static void pool_dtr(struct dm_target *ti)
2682 struct pool_c *pt = ti->private;
2684 mutex_lock(&dm_thin_pool_table.mutex);
2686 unbind_control_target(pt->pool, ti);
2687 __pool_dec(pt->pool);
2688 dm_put_device(ti, pt->metadata_dev);
2689 dm_put_device(ti, pt->data_dev);
2692 mutex_unlock(&dm_thin_pool_table.mutex);
2695 static int parse_pool_features(struct dm_arg_set *as, struct pool_features *pf,
2696 struct dm_target *ti)
2700 const char *arg_name;
2702 static struct dm_arg _args[] = {
2703 {0, 4, "Invalid number of pool feature arguments"},
2707 * No feature arguments supplied.
2712 r = dm_read_arg_group(_args, as, &argc, &ti->error);
2716 while (argc && !r) {
2717 arg_name = dm_shift_arg(as);
2720 if (!strcasecmp(arg_name, "skip_block_zeroing"))
2721 pf->zero_new_blocks = false;
2723 else if (!strcasecmp(arg_name, "ignore_discard"))
2724 pf->discard_enabled = false;
2726 else if (!strcasecmp(arg_name, "no_discard_passdown"))
2727 pf->discard_passdown = false;
2729 else if (!strcasecmp(arg_name, "read_only"))
2730 pf->mode = PM_READ_ONLY;
2732 else if (!strcasecmp(arg_name, "error_if_no_space"))
2733 pf->error_if_no_space = true;
2736 ti->error = "Unrecognised pool feature requested";
2745 static void metadata_low_callback(void *context)
2747 struct pool *pool = context;
2749 DMWARN("%s: reached low water mark for metadata device: sending event.",
2750 dm_device_name(pool->pool_md));
2752 dm_table_event(pool->ti->table);
2755 static sector_t get_dev_size(struct block_device *bdev)
2757 return i_size_read(bdev->bd_inode) >> SECTOR_SHIFT;
2760 static void warn_if_metadata_device_too_big(struct block_device *bdev)
2762 sector_t metadata_dev_size = get_dev_size(bdev);
2763 char buffer[BDEVNAME_SIZE];
2765 if (metadata_dev_size > THIN_METADATA_MAX_SECTORS_WARNING)
2766 DMWARN("Metadata device %s is larger than %u sectors: excess space will not be used.",
2767 bdevname(bdev, buffer), THIN_METADATA_MAX_SECTORS);
2770 static sector_t get_metadata_dev_size(struct block_device *bdev)
2772 sector_t metadata_dev_size = get_dev_size(bdev);
2774 if (metadata_dev_size > THIN_METADATA_MAX_SECTORS)
2775 metadata_dev_size = THIN_METADATA_MAX_SECTORS;
2777 return metadata_dev_size;
2780 static dm_block_t get_metadata_dev_size_in_blocks(struct block_device *bdev)
2782 sector_t metadata_dev_size = get_metadata_dev_size(bdev);
2784 sector_div(metadata_dev_size, THIN_METADATA_BLOCK_SIZE);
2786 return metadata_dev_size;
2790 * When a metadata threshold is crossed a dm event is triggered, and
2791 * userland should respond by growing the metadata device. We could let
2792 * userland set the threshold, like we do with the data threshold, but I'm
2793 * not sure they know enough to do this well.
2795 static dm_block_t calc_metadata_threshold(struct pool_c *pt)
2798 * 4M is ample for all ops with the possible exception of thin
2799 * device deletion which is harmless if it fails (just retry the
2800 * delete after you've grown the device).
2802 dm_block_t quarter = get_metadata_dev_size_in_blocks(pt->metadata_dev->bdev) / 4;
2803 return min((dm_block_t)1024ULL /* 4M */, quarter);
2807 * thin-pool <metadata dev> <data dev>
2808 * <data block size (sectors)>
2809 * <low water mark (blocks)>
2810 * [<#feature args> [<arg>]*]
2812 * Optional feature arguments are:
2813 * skip_block_zeroing: skips the zeroing of newly-provisioned blocks.
2814 * ignore_discard: disable discard
2815 * no_discard_passdown: don't pass discards down to the data device
2816 * read_only: Don't allow any changes to be made to the pool metadata.
2817 * error_if_no_space: error IOs, instead of queueing, if no space.
2819 static int pool_ctr(struct dm_target *ti, unsigned argc, char **argv)
2821 int r, pool_created = 0;
2824 struct pool_features pf;
2825 struct dm_arg_set as;
2826 struct dm_dev *data_dev;
2827 unsigned long block_size;
2828 dm_block_t low_water_blocks;
2829 struct dm_dev *metadata_dev;
2830 fmode_t metadata_mode;
2833 * FIXME Remove validation from scope of lock.
2835 mutex_lock(&dm_thin_pool_table.mutex);
2838 ti->error = "Invalid argument count";
2847 * Set default pool features.
2849 pool_features_init(&pf);
2851 dm_consume_args(&as, 4);
2852 r = parse_pool_features(&as, &pf, ti);
2856 metadata_mode = FMODE_READ | ((pf.mode == PM_READ_ONLY) ? 0 : FMODE_WRITE);
2857 r = dm_get_device(ti, argv[0], metadata_mode, &metadata_dev);
2859 ti->error = "Error opening metadata block device";
2862 warn_if_metadata_device_too_big(metadata_dev->bdev);
2864 r = dm_get_device(ti, argv[1], FMODE_READ | FMODE_WRITE, &data_dev);
2866 ti->error = "Error getting data device";
2870 if (kstrtoul(argv[2], 10, &block_size) || !block_size ||
2871 block_size < DATA_DEV_BLOCK_SIZE_MIN_SECTORS ||
2872 block_size > DATA_DEV_BLOCK_SIZE_MAX_SECTORS ||
2873 block_size & (DATA_DEV_BLOCK_SIZE_MIN_SECTORS - 1)) {
2874 ti->error = "Invalid block size";
2879 if (kstrtoull(argv[3], 10, (unsigned long long *)&low_water_blocks)) {
2880 ti->error = "Invalid low water mark";
2885 pt = kzalloc(sizeof(*pt), GFP_KERNEL);
2891 pool = __pool_find(dm_table_get_md(ti->table), metadata_dev->bdev,
2892 block_size, pf.mode == PM_READ_ONLY, &ti->error, &pool_created);
2899 * 'pool_created' reflects whether this is the first table load.
2900 * Top level discard support is not allowed to be changed after
2901 * initial load. This would require a pool reload to trigger thin
2904 if (!pool_created && pf.discard_enabled != pool->pf.discard_enabled) {
2905 ti->error = "Discard support cannot be disabled once enabled";
2907 goto out_flags_changed;
2912 pt->metadata_dev = metadata_dev;
2913 pt->data_dev = data_dev;
2914 pt->low_water_blocks = low_water_blocks;
2915 pt->adjusted_pf = pt->requested_pf = pf;
2916 ti->num_flush_bios = 1;
2919 * Only need to enable discards if the pool should pass
2920 * them down to the data device. The thin device's discard
2921 * processing will cause mappings to be removed from the btree.
2923 ti->discard_zeroes_data_unsupported = true;
2924 if (pf.discard_enabled && pf.discard_passdown) {
2925 ti->num_discard_bios = 1;
2928 * Setting 'discards_supported' circumvents the normal
2929 * stacking of discard limits (this keeps the pool and
2930 * thin devices' discard limits consistent).
2932 ti->discards_supported = true;
2936 r = dm_pool_register_metadata_threshold(pt->pool->pmd,
2937 calc_metadata_threshold(pt),
2938 metadata_low_callback,
2943 pt->callbacks.congested_fn = pool_is_congested;
2944 dm_table_add_target_callbacks(ti->table, &pt->callbacks);
2946 mutex_unlock(&dm_thin_pool_table.mutex);
2955 dm_put_device(ti, data_dev);
2957 dm_put_device(ti, metadata_dev);
2959 mutex_unlock(&dm_thin_pool_table.mutex);
2964 static int pool_map(struct dm_target *ti, struct bio *bio)
2967 struct pool_c *pt = ti->private;
2968 struct pool *pool = pt->pool;
2969 unsigned long flags;
2972 * As this is a singleton target, ti->begin is always zero.
2974 spin_lock_irqsave(&pool->lock, flags);
2975 bio->bi_bdev = pt->data_dev->bdev;
2976 r = DM_MAPIO_REMAPPED;
2977 spin_unlock_irqrestore(&pool->lock, flags);
2982 static int maybe_resize_data_dev(struct dm_target *ti, bool *need_commit)
2985 struct pool_c *pt = ti->private;
2986 struct pool *pool = pt->pool;
2987 sector_t data_size = ti->len;
2988 dm_block_t sb_data_size;
2990 *need_commit = false;
2992 (void) sector_div(data_size, pool->sectors_per_block);
2994 r = dm_pool_get_data_dev_size(pool->pmd, &sb_data_size);
2996 DMERR("%s: failed to retrieve data device size",
2997 dm_device_name(pool->pool_md));
3001 if (data_size < sb_data_size) {
3002 DMERR("%s: pool target (%llu blocks) too small: expected %llu",
3003 dm_device_name(pool->pool_md),
3004 (unsigned long long)data_size, sb_data_size);
3007 } else if (data_size > sb_data_size) {
3008 if (dm_pool_metadata_needs_check(pool->pmd)) {
3009 DMERR("%s: unable to grow the data device until repaired.",
3010 dm_device_name(pool->pool_md));
3015 DMINFO("%s: growing the data device from %llu to %llu blocks",
3016 dm_device_name(pool->pool_md),
3017 sb_data_size, (unsigned long long)data_size);
3018 r = dm_pool_resize_data_dev(pool->pmd, data_size);
3020 metadata_operation_failed(pool, "dm_pool_resize_data_dev", r);
3024 *need_commit = true;
3030 static int maybe_resize_metadata_dev(struct dm_target *ti, bool *need_commit)
3033 struct pool_c *pt = ti->private;
3034 struct pool *pool = pt->pool;
3035 dm_block_t metadata_dev_size, sb_metadata_dev_size;
3037 *need_commit = false;
3039 metadata_dev_size = get_metadata_dev_size_in_blocks(pool->md_dev);
3041 r = dm_pool_get_metadata_dev_size(pool->pmd, &sb_metadata_dev_size);
3043 DMERR("%s: failed to retrieve metadata device size",
3044 dm_device_name(pool->pool_md));
3048 if (metadata_dev_size < sb_metadata_dev_size) {
3049 DMERR("%s: metadata device (%llu blocks) too small: expected %llu",
3050 dm_device_name(pool->pool_md),
3051 metadata_dev_size, sb_metadata_dev_size);
3054 } else if (metadata_dev_size > sb_metadata_dev_size) {
3055 if (dm_pool_metadata_needs_check(pool->pmd)) {
3056 DMERR("%s: unable to grow the metadata device until repaired.",
3057 dm_device_name(pool->pool_md));
3061 warn_if_metadata_device_too_big(pool->md_dev);
3062 DMINFO("%s: growing the metadata device from %llu to %llu blocks",
3063 dm_device_name(pool->pool_md),
3064 sb_metadata_dev_size, metadata_dev_size);
3065 r = dm_pool_resize_metadata_dev(pool->pmd, metadata_dev_size);
3067 metadata_operation_failed(pool, "dm_pool_resize_metadata_dev", r);
3071 *need_commit = true;
3078 * Retrieves the number of blocks of the data device from
3079 * the superblock and compares it to the actual device size,
3080 * thus resizing the data device in case it has grown.
3082 * This both copes with opening preallocated data devices in the ctr
3083 * being followed by a resume
3085 * calling the resume method individually after userspace has
3086 * grown the data device in reaction to a table event.
3088 static int pool_preresume(struct dm_target *ti)
3091 bool need_commit1, need_commit2;
3092 struct pool_c *pt = ti->private;
3093 struct pool *pool = pt->pool;
3096 * Take control of the pool object.
3098 r = bind_control_target(pool, ti);
3102 r = maybe_resize_data_dev(ti, &need_commit1);
3106 r = maybe_resize_metadata_dev(ti, &need_commit2);
3110 if (need_commit1 || need_commit2)
3111 (void) commit(pool);
3116 static void pool_suspend_active_thins(struct pool *pool)
3120 /* Suspend all active thin devices */
3121 tc = get_first_thin(pool);
3123 dm_internal_suspend_noflush(tc->thin_md);
3124 tc = get_next_thin(pool, tc);
3128 static void pool_resume_active_thins(struct pool *pool)
3132 /* Resume all active thin devices */
3133 tc = get_first_thin(pool);
3135 dm_internal_resume(tc->thin_md);
3136 tc = get_next_thin(pool, tc);
3140 static void pool_resume(struct dm_target *ti)
3142 struct pool_c *pt = ti->private;
3143 struct pool *pool = pt->pool;
3144 unsigned long flags;
3147 * Must requeue active_thins' bios and then resume
3148 * active_thins _before_ clearing 'suspend' flag.
3151 pool_resume_active_thins(pool);
3153 spin_lock_irqsave(&pool->lock, flags);
3154 pool->low_water_triggered = false;
3155 pool->suspended = false;
3156 spin_unlock_irqrestore(&pool->lock, flags);
3158 do_waker(&pool->waker.work);
3161 static void pool_presuspend(struct dm_target *ti)
3163 struct pool_c *pt = ti->private;
3164 struct pool *pool = pt->pool;
3165 unsigned long flags;
3167 spin_lock_irqsave(&pool->lock, flags);
3168 pool->suspended = true;
3169 spin_unlock_irqrestore(&pool->lock, flags);
3171 pool_suspend_active_thins(pool);
3174 static void pool_presuspend_undo(struct dm_target *ti)
3176 struct pool_c *pt = ti->private;
3177 struct pool *pool = pt->pool;
3178 unsigned long flags;
3180 pool_resume_active_thins(pool);
3182 spin_lock_irqsave(&pool->lock, flags);
3183 pool->suspended = false;
3184 spin_unlock_irqrestore(&pool->lock, flags);
3187 static void pool_postsuspend(struct dm_target *ti)
3189 struct pool_c *pt = ti->private;
3190 struct pool *pool = pt->pool;
3192 cancel_delayed_work(&pool->waker);
3193 cancel_delayed_work(&pool->no_space_timeout);
3194 flush_workqueue(pool->wq);
3195 (void) commit(pool);
3198 static int check_arg_count(unsigned argc, unsigned args_required)
3200 if (argc != args_required) {
3201 DMWARN("Message received with %u arguments instead of %u.",
3202 argc, args_required);
3209 static int read_dev_id(char *arg, dm_thin_id *dev_id, int warning)
3211 if (!kstrtoull(arg, 10, (unsigned long long *)dev_id) &&
3212 *dev_id <= MAX_DEV_ID)
3216 DMWARN("Message received with invalid device id: %s", arg);
3221 static int process_create_thin_mesg(unsigned argc, char **argv, struct pool *pool)
3226 r = check_arg_count(argc, 2);
3230 r = read_dev_id(argv[1], &dev_id, 1);
3234 r = dm_pool_create_thin(pool->pmd, dev_id);
3236 DMWARN("Creation of new thinly-provisioned device with id %s failed.",
3244 static int process_create_snap_mesg(unsigned argc, char **argv, struct pool *pool)
3247 dm_thin_id origin_dev_id;
3250 r = check_arg_count(argc, 3);
3254 r = read_dev_id(argv[1], &dev_id, 1);
3258 r = read_dev_id(argv[2], &origin_dev_id, 1);
3262 r = dm_pool_create_snap(pool->pmd, dev_id, origin_dev_id);
3264 DMWARN("Creation of new snapshot %s of device %s failed.",
3272 static int process_delete_mesg(unsigned argc, char **argv, struct pool *pool)
3277 r = check_arg_count(argc, 2);
3281 r = read_dev_id(argv[1], &dev_id, 1);
3285 r = dm_pool_delete_thin_device(pool->pmd, dev_id);
3287 DMWARN("Deletion of thin device %s failed.", argv[1]);
3292 static int process_set_transaction_id_mesg(unsigned argc, char **argv, struct pool *pool)
3294 dm_thin_id old_id, new_id;
3297 r = check_arg_count(argc, 3);
3301 if (kstrtoull(argv[1], 10, (unsigned long long *)&old_id)) {
3302 DMWARN("set_transaction_id message: Unrecognised id %s.", argv[1]);
3306 if (kstrtoull(argv[2], 10, (unsigned long long *)&new_id)) {
3307 DMWARN("set_transaction_id message: Unrecognised new id %s.", argv[2]);
3311 r = dm_pool_set_metadata_transaction_id(pool->pmd, old_id, new_id);
3313 DMWARN("Failed to change transaction id from %s to %s.",
3321 static int process_reserve_metadata_snap_mesg(unsigned argc, char **argv, struct pool *pool)
3325 r = check_arg_count(argc, 1);
3329 (void) commit(pool);
3331 r = dm_pool_reserve_metadata_snap(pool->pmd);
3333 DMWARN("reserve_metadata_snap message failed.");
3338 static int process_release_metadata_snap_mesg(unsigned argc, char **argv, struct pool *pool)
3342 r = check_arg_count(argc, 1);
3346 r = dm_pool_release_metadata_snap(pool->pmd);
3348 DMWARN("release_metadata_snap message failed.");
3354 * Messages supported:
3355 * create_thin <dev_id>
3356 * create_snap <dev_id> <origin_id>
3358 * set_transaction_id <current_trans_id> <new_trans_id>
3359 * reserve_metadata_snap
3360 * release_metadata_snap
3362 static int pool_message(struct dm_target *ti, unsigned argc, char **argv)
3365 struct pool_c *pt = ti->private;
3366 struct pool *pool = pt->pool;
3368 if (get_pool_mode(pool) >= PM_READ_ONLY) {
3369 DMERR("%s: unable to service pool target messages in READ_ONLY or FAIL mode",
3370 dm_device_name(pool->pool_md));
3374 if (!strcasecmp(argv[0], "create_thin"))
3375 r = process_create_thin_mesg(argc, argv, pool);
3377 else if (!strcasecmp(argv[0], "create_snap"))
3378 r = process_create_snap_mesg(argc, argv, pool);
3380 else if (!strcasecmp(argv[0], "delete"))
3381 r = process_delete_mesg(argc, argv, pool);
3383 else if (!strcasecmp(argv[0], "set_transaction_id"))
3384 r = process_set_transaction_id_mesg(argc, argv, pool);
3386 else if (!strcasecmp(argv[0], "reserve_metadata_snap"))
3387 r = process_reserve_metadata_snap_mesg(argc, argv, pool);
3389 else if (!strcasecmp(argv[0], "release_metadata_snap"))
3390 r = process_release_metadata_snap_mesg(argc, argv, pool);
3393 DMWARN("Unrecognised thin pool target message received: %s", argv[0]);
3396 (void) commit(pool);
3401 static void emit_flags(struct pool_features *pf, char *result,
3402 unsigned sz, unsigned maxlen)
3404 unsigned count = !pf->zero_new_blocks + !pf->discard_enabled +
3405 !pf->discard_passdown + (pf->mode == PM_READ_ONLY) +
3406 pf->error_if_no_space;
3407 DMEMIT("%u ", count);
3409 if (!pf->zero_new_blocks)
3410 DMEMIT("skip_block_zeroing ");
3412 if (!pf->discard_enabled)
3413 DMEMIT("ignore_discard ");
3415 if (!pf->discard_passdown)
3416 DMEMIT("no_discard_passdown ");
3418 if (pf->mode == PM_READ_ONLY)
3419 DMEMIT("read_only ");
3421 if (pf->error_if_no_space)
3422 DMEMIT("error_if_no_space ");
3427 * <transaction id> <used metadata sectors>/<total metadata sectors>
3428 * <used data sectors>/<total data sectors> <held metadata root>
3430 static void pool_status(struct dm_target *ti, status_type_t type,
3431 unsigned status_flags, char *result, unsigned maxlen)
3435 uint64_t transaction_id;
3436 dm_block_t nr_free_blocks_data;
3437 dm_block_t nr_free_blocks_metadata;
3438 dm_block_t nr_blocks_data;
3439 dm_block_t nr_blocks_metadata;
3440 dm_block_t held_root;
3441 char buf[BDEVNAME_SIZE];
3442 char buf2[BDEVNAME_SIZE];
3443 struct pool_c *pt = ti->private;
3444 struct pool *pool = pt->pool;
3447 case STATUSTYPE_INFO:
3448 if (get_pool_mode(pool) == PM_FAIL) {
3453 /* Commit to ensure statistics aren't out-of-date */
3454 if (!(status_flags & DM_STATUS_NOFLUSH_FLAG) && !dm_suspended(ti))
3455 (void) commit(pool);
3457 r = dm_pool_get_metadata_transaction_id(pool->pmd, &transaction_id);
3459 DMERR("%s: dm_pool_get_metadata_transaction_id returned %d",
3460 dm_device_name(pool->pool_md), r);
3464 r = dm_pool_get_free_metadata_block_count(pool->pmd, &nr_free_blocks_metadata);
3466 DMERR("%s: dm_pool_get_free_metadata_block_count returned %d",
3467 dm_device_name(pool->pool_md), r);
3471 r = dm_pool_get_metadata_dev_size(pool->pmd, &nr_blocks_metadata);
3473 DMERR("%s: dm_pool_get_metadata_dev_size returned %d",
3474 dm_device_name(pool->pool_md), r);
3478 r = dm_pool_get_free_block_count(pool->pmd, &nr_free_blocks_data);
3480 DMERR("%s: dm_pool_get_free_block_count returned %d",
3481 dm_device_name(pool->pool_md), r);
3485 r = dm_pool_get_data_dev_size(pool->pmd, &nr_blocks_data);
3487 DMERR("%s: dm_pool_get_data_dev_size returned %d",
3488 dm_device_name(pool->pool_md), r);
3492 r = dm_pool_get_metadata_snap(pool->pmd, &held_root);
3494 DMERR("%s: dm_pool_get_metadata_snap returned %d",
3495 dm_device_name(pool->pool_md), r);
3499 DMEMIT("%llu %llu/%llu %llu/%llu ",
3500 (unsigned long long)transaction_id,
3501 (unsigned long long)(nr_blocks_metadata - nr_free_blocks_metadata),
3502 (unsigned long long)nr_blocks_metadata,
3503 (unsigned long long)(nr_blocks_data - nr_free_blocks_data),
3504 (unsigned long long)nr_blocks_data);
3507 DMEMIT("%llu ", held_root);
3511 if (pool->pf.mode == PM_OUT_OF_DATA_SPACE)
3512 DMEMIT("out_of_data_space ");
3513 else if (pool->pf.mode == PM_READ_ONLY)
3518 if (!pool->pf.discard_enabled)
3519 DMEMIT("ignore_discard ");
3520 else if (pool->pf.discard_passdown)
3521 DMEMIT("discard_passdown ");
3523 DMEMIT("no_discard_passdown ");
3525 if (pool->pf.error_if_no_space)
3526 DMEMIT("error_if_no_space ");
3528 DMEMIT("queue_if_no_space ");
3532 case STATUSTYPE_TABLE:
3533 DMEMIT("%s %s %lu %llu ",
3534 format_dev_t(buf, pt->metadata_dev->bdev->bd_dev),
3535 format_dev_t(buf2, pt->data_dev->bdev->bd_dev),
3536 (unsigned long)pool->sectors_per_block,
3537 (unsigned long long)pt->low_water_blocks);
3538 emit_flags(&pt->requested_pf, result, sz, maxlen);
3547 static int pool_iterate_devices(struct dm_target *ti,
3548 iterate_devices_callout_fn fn, void *data)
3550 struct pool_c *pt = ti->private;
3552 return fn(ti, pt->data_dev, 0, ti->len, data);
3555 static int pool_merge(struct dm_target *ti, struct bvec_merge_data *bvm,
3556 struct bio_vec *biovec, int max_size)
3558 struct pool_c *pt = ti->private;
3559 struct request_queue *q = bdev_get_queue(pt->data_dev->bdev);
3561 if (!q->merge_bvec_fn)
3564 bvm->bi_bdev = pt->data_dev->bdev;
3566 return min(max_size, q->merge_bvec_fn(q, bvm, biovec));
3569 static void set_discard_limits(struct pool_c *pt, struct queue_limits *limits)
3571 struct pool *pool = pt->pool;
3572 struct queue_limits *data_limits;
3574 limits->max_discard_sectors = pool->sectors_per_block;
3577 * discard_granularity is just a hint, and not enforced.
3579 if (pt->adjusted_pf.discard_passdown) {
3580 data_limits = &bdev_get_queue(pt->data_dev->bdev)->limits;
3581 limits->discard_granularity = max(data_limits->discard_granularity,
3582 pool->sectors_per_block << SECTOR_SHIFT);
3584 limits->discard_granularity = pool->sectors_per_block << SECTOR_SHIFT;
3587 static void pool_io_hints(struct dm_target *ti, struct queue_limits *limits)
3589 struct pool_c *pt = ti->private;
3590 struct pool *pool = pt->pool;
3591 sector_t io_opt_sectors = limits->io_opt >> SECTOR_SHIFT;
3594 * If max_sectors is smaller than pool->sectors_per_block adjust it
3595 * to the highest possible power-of-2 factor of pool->sectors_per_block.
3596 * This is especially beneficial when the pool's data device is a RAID
3597 * device that has a full stripe width that matches pool->sectors_per_block
3598 * -- because even though partial RAID stripe-sized IOs will be issued to a
3599 * single RAID stripe; when aggregated they will end on a full RAID stripe
3600 * boundary.. which avoids additional partial RAID stripe writes cascading
3602 if (limits->max_sectors < pool->sectors_per_block) {
3603 while (!is_factor(pool->sectors_per_block, limits->max_sectors)) {
3604 if ((limits->max_sectors & (limits->max_sectors - 1)) == 0)
3605 limits->max_sectors--;
3606 limits->max_sectors = rounddown_pow_of_two(limits->max_sectors);
3611 * If the system-determined stacked limits are compatible with the
3612 * pool's blocksize (io_opt is a factor) do not override them.
3614 if (io_opt_sectors < pool->sectors_per_block ||
3615 !is_factor(io_opt_sectors, pool->sectors_per_block)) {
3616 if (is_factor(pool->sectors_per_block, limits->max_sectors))
3617 blk_limits_io_min(limits, limits->max_sectors << SECTOR_SHIFT);
3619 blk_limits_io_min(limits, pool->sectors_per_block << SECTOR_SHIFT);
3620 blk_limits_io_opt(limits, pool->sectors_per_block << SECTOR_SHIFT);
3624 * pt->adjusted_pf is a staging area for the actual features to use.
3625 * They get transferred to the live pool in bind_control_target()
3626 * called from pool_preresume().
3628 if (!pt->adjusted_pf.discard_enabled) {
3630 * Must explicitly disallow stacking discard limits otherwise the
3631 * block layer will stack them if pool's data device has support.
3632 * QUEUE_FLAG_DISCARD wouldn't be set but there is no way for the
3633 * user to see that, so make sure to set all discard limits to 0.
3635 limits->discard_granularity = 0;
3639 disable_passdown_if_not_supported(pt);
3641 set_discard_limits(pt, limits);
3644 static struct target_type pool_target = {
3645 .name = "thin-pool",
3646 .features = DM_TARGET_SINGLETON | DM_TARGET_ALWAYS_WRITEABLE |
3647 DM_TARGET_IMMUTABLE,
3648 .version = {1, 14, 0},
3649 .module = THIS_MODULE,
3653 .presuspend = pool_presuspend,
3654 .presuspend_undo = pool_presuspend_undo,
3655 .postsuspend = pool_postsuspend,
3656 .preresume = pool_preresume,
3657 .resume = pool_resume,
3658 .message = pool_message,
3659 .status = pool_status,
3660 .merge = pool_merge,
3661 .iterate_devices = pool_iterate_devices,
3662 .io_hints = pool_io_hints,
3665 /*----------------------------------------------------------------
3666 * Thin target methods
3667 *--------------------------------------------------------------*/
3668 static void thin_get(struct thin_c *tc)
3670 atomic_inc(&tc->refcount);
3673 static void thin_put(struct thin_c *tc)
3675 if (atomic_dec_and_test(&tc->refcount))
3676 complete(&tc->can_destroy);
3679 static void thin_dtr(struct dm_target *ti)
3681 struct thin_c *tc = ti->private;
3682 unsigned long flags;
3684 spin_lock_irqsave(&tc->pool->lock, flags);
3685 list_del_rcu(&tc->list);
3686 spin_unlock_irqrestore(&tc->pool->lock, flags);
3690 wait_for_completion(&tc->can_destroy);
3692 mutex_lock(&dm_thin_pool_table.mutex);
3694 __pool_dec(tc->pool);
3695 dm_pool_close_thin_device(tc->td);
3696 dm_put_device(ti, tc->pool_dev);
3698 dm_put_device(ti, tc->origin_dev);
3701 mutex_unlock(&dm_thin_pool_table.mutex);
3705 * Thin target parameters:
3707 * <pool_dev> <dev_id> [origin_dev]
3709 * pool_dev: the path to the pool (eg, /dev/mapper/my_pool)
3710 * dev_id: the internal device identifier
3711 * origin_dev: a device external to the pool that should act as the origin
3713 * If the pool device has discards disabled, they get disabled for the thin
3716 static int thin_ctr(struct dm_target *ti, unsigned argc, char **argv)
3720 struct dm_dev *pool_dev, *origin_dev;
3721 struct mapped_device *pool_md;
3722 unsigned long flags;
3724 mutex_lock(&dm_thin_pool_table.mutex);
3726 if (argc != 2 && argc != 3) {
3727 ti->error = "Invalid argument count";
3732 tc = ti->private = kzalloc(sizeof(*tc), GFP_KERNEL);
3734 ti->error = "Out of memory";
3738 tc->thin_md = dm_table_get_md(ti->table);
3739 spin_lock_init(&tc->lock);
3740 INIT_LIST_HEAD(&tc->deferred_cells);
3741 bio_list_init(&tc->deferred_bio_list);
3742 bio_list_init(&tc->retry_on_resume_list);
3743 tc->sort_bio_list = RB_ROOT;
3746 r = dm_get_device(ti, argv[2], FMODE_READ, &origin_dev);
3748 ti->error = "Error opening origin device";
3749 goto bad_origin_dev;
3751 tc->origin_dev = origin_dev;
3754 r = dm_get_device(ti, argv[0], dm_table_get_mode(ti->table), &pool_dev);
3756 ti->error = "Error opening pool device";
3759 tc->pool_dev = pool_dev;
3761 if (read_dev_id(argv[1], (unsigned long long *)&tc->dev_id, 0)) {
3762 ti->error = "Invalid device id";
3767 pool_md = dm_get_md(tc->pool_dev->bdev->bd_dev);
3769 ti->error = "Couldn't get pool mapped device";
3774 tc->pool = __pool_table_lookup(pool_md);
3776 ti->error = "Couldn't find pool object";
3778 goto bad_pool_lookup;
3780 __pool_inc(tc->pool);
3782 if (get_pool_mode(tc->pool) == PM_FAIL) {
3783 ti->error = "Couldn't open thin device, Pool is in fail mode";
3788 r = dm_pool_open_thin_device(tc->pool->pmd, tc->dev_id, &tc->td);
3790 ti->error = "Couldn't open thin internal device";
3794 r = dm_set_target_max_io_len(ti, tc->pool->sectors_per_block);
3798 ti->num_flush_bios = 1;
3799 ti->flush_supported = true;
3800 ti->per_bio_data_size = sizeof(struct dm_thin_endio_hook);
3802 /* In case the pool supports discards, pass them on. */
3803 ti->discard_zeroes_data_unsupported = true;
3804 if (tc->pool->pf.discard_enabled) {
3805 ti->discards_supported = true;
3806 ti->num_discard_bios = 1;
3807 /* Discard bios must be split on a block boundary */
3808 ti->split_discard_bios = true;
3811 mutex_unlock(&dm_thin_pool_table.mutex);
3813 spin_lock_irqsave(&tc->pool->lock, flags);
3814 if (tc->pool->suspended) {
3815 spin_unlock_irqrestore(&tc->pool->lock, flags);
3816 mutex_lock(&dm_thin_pool_table.mutex); /* reacquire for __pool_dec */
3817 ti->error = "Unable to activate thin device while pool is suspended";
3821 atomic_set(&tc->refcount, 1);
3822 init_completion(&tc->can_destroy);
3823 list_add_tail_rcu(&tc->list, &tc->pool->active_thins);
3824 spin_unlock_irqrestore(&tc->pool->lock, flags);
3826 * This synchronize_rcu() call is needed here otherwise we risk a
3827 * wake_worker() call finding no bios to process (because the newly
3828 * added tc isn't yet visible). So this reduces latency since we
3829 * aren't then dependent on the periodic commit to wake_worker().
3838 dm_pool_close_thin_device(tc->td);
3840 __pool_dec(tc->pool);
3844 dm_put_device(ti, tc->pool_dev);
3847 dm_put_device(ti, tc->origin_dev);
3851 mutex_unlock(&dm_thin_pool_table.mutex);
3856 static int thin_map(struct dm_target *ti, struct bio *bio)
3858 bio->bi_iter.bi_sector = dm_target_offset(ti, bio->bi_iter.bi_sector);
3860 return thin_bio_map(ti, bio);
3863 static int thin_endio(struct dm_target *ti, struct bio *bio, int err)
3865 unsigned long flags;
3866 struct dm_thin_endio_hook *h = dm_per_bio_data(bio, sizeof(struct dm_thin_endio_hook));
3867 struct list_head work;
3868 struct dm_thin_new_mapping *m, *tmp;
3869 struct pool *pool = h->tc->pool;
3871 if (h->shared_read_entry) {
3872 INIT_LIST_HEAD(&work);
3873 dm_deferred_entry_dec(h->shared_read_entry, &work);
3875 spin_lock_irqsave(&pool->lock, flags);
3876 list_for_each_entry_safe(m, tmp, &work, list) {
3878 __complete_mapping_preparation(m);
3880 spin_unlock_irqrestore(&pool->lock, flags);
3883 if (h->all_io_entry) {
3884 INIT_LIST_HEAD(&work);
3885 dm_deferred_entry_dec(h->all_io_entry, &work);
3886 if (!list_empty(&work)) {
3887 spin_lock_irqsave(&pool->lock, flags);
3888 list_for_each_entry_safe(m, tmp, &work, list)
3889 list_add_tail(&m->list, &pool->prepared_discards);
3890 spin_unlock_irqrestore(&pool->lock, flags);
3898 static void thin_presuspend(struct dm_target *ti)
3900 struct thin_c *tc = ti->private;
3902 if (dm_noflush_suspending(ti))
3903 noflush_work(tc, do_noflush_start);
3906 static void thin_postsuspend(struct dm_target *ti)
3908 struct thin_c *tc = ti->private;
3911 * The dm_noflush_suspending flag has been cleared by now, so
3912 * unfortunately we must always run this.
3914 noflush_work(tc, do_noflush_stop);
3917 static int thin_preresume(struct dm_target *ti)
3919 struct thin_c *tc = ti->private;
3922 tc->origin_size = get_dev_size(tc->origin_dev->bdev);
3928 * <nr mapped sectors> <highest mapped sector>
3930 static void thin_status(struct dm_target *ti, status_type_t type,
3931 unsigned status_flags, char *result, unsigned maxlen)
3935 dm_block_t mapped, highest;
3936 char buf[BDEVNAME_SIZE];
3937 struct thin_c *tc = ti->private;
3939 if (get_pool_mode(tc->pool) == PM_FAIL) {
3948 case STATUSTYPE_INFO:
3949 r = dm_thin_get_mapped_count(tc->td, &mapped);
3951 DMERR("dm_thin_get_mapped_count returned %d", r);
3955 r = dm_thin_get_highest_mapped_block(tc->td, &highest);
3957 DMERR("dm_thin_get_highest_mapped_block returned %d", r);
3961 DMEMIT("%llu ", mapped * tc->pool->sectors_per_block);
3963 DMEMIT("%llu", ((highest + 1) *
3964 tc->pool->sectors_per_block) - 1);
3969 case STATUSTYPE_TABLE:
3971 format_dev_t(buf, tc->pool_dev->bdev->bd_dev),
3972 (unsigned long) tc->dev_id);
3974 DMEMIT(" %s", format_dev_t(buf, tc->origin_dev->bdev->bd_dev));
3985 static int thin_merge(struct dm_target *ti, struct bvec_merge_data *bvm,
3986 struct bio_vec *biovec, int max_size)
3988 struct thin_c *tc = ti->private;
3989 struct request_queue *q = bdev_get_queue(tc->pool_dev->bdev);
3991 if (!q->merge_bvec_fn)
3994 bvm->bi_bdev = tc->pool_dev->bdev;
3995 bvm->bi_sector = dm_target_offset(ti, bvm->bi_sector);
3997 return min(max_size, q->merge_bvec_fn(q, bvm, biovec));
4000 static int thin_iterate_devices(struct dm_target *ti,
4001 iterate_devices_callout_fn fn, void *data)
4004 struct thin_c *tc = ti->private;
4005 struct pool *pool = tc->pool;
4008 * We can't call dm_pool_get_data_dev_size() since that blocks. So
4009 * we follow a more convoluted path through to the pool's target.
4012 return 0; /* nothing is bound */
4014 blocks = pool->ti->len;
4015 (void) sector_div(blocks, pool->sectors_per_block);
4017 return fn(ti, tc->pool_dev, 0, pool->sectors_per_block * blocks, data);
4022 static struct target_type thin_target = {
4024 .version = {1, 14, 0},
4025 .module = THIS_MODULE,
4029 .end_io = thin_endio,
4030 .preresume = thin_preresume,
4031 .presuspend = thin_presuspend,
4032 .postsuspend = thin_postsuspend,
4033 .status = thin_status,
4034 .merge = thin_merge,
4035 .iterate_devices = thin_iterate_devices,
4038 /*----------------------------------------------------------------*/
4040 static int __init dm_thin_init(void)
4046 r = dm_register_target(&thin_target);
4050 r = dm_register_target(&pool_target);
4052 goto bad_pool_target;
4056 _new_mapping_cache = KMEM_CACHE(dm_thin_new_mapping, 0);
4057 if (!_new_mapping_cache)
4058 goto bad_new_mapping_cache;
4062 bad_new_mapping_cache:
4063 dm_unregister_target(&pool_target);
4065 dm_unregister_target(&thin_target);
4070 static void dm_thin_exit(void)
4072 dm_unregister_target(&thin_target);
4073 dm_unregister_target(&pool_target);
4075 kmem_cache_destroy(_new_mapping_cache);
4078 module_init(dm_thin_init);
4079 module_exit(dm_thin_exit);
4081 module_param_named(no_space_timeout, no_space_timeout_secs, uint, S_IRUGO | S_IWUSR);
4082 MODULE_PARM_DESC(no_space_timeout, "Out of data space queue IO timeout in seconds");
4084 MODULE_DESCRIPTION(DM_NAME " thin provisioning target");
4085 MODULE_AUTHOR("Joe Thornber <dm-devel@redhat.com>");
4086 MODULE_LICENSE("GPL");