On Tue, Nov 06, 2007 at 02:33:53AM -0800, akpm@linux-foundation.org wrote:
[mmotm.git] / drivers / md / dm-snap.c
blob01cda374630a0a5ee1f68db33b6f7617e0efeaa6
1 /*
2 * dm-snapshot.c
4 * Copyright (C) 2001-2002 Sistina Software (UK) Limited.
6 * This file is released under the GPL.
7 */
9 #include <linux/blkdev.h>
10 #include <linux/device-mapper.h>
11 #include <linux/delay.h>
12 #include <linux/fs.h>
13 #include <linux/init.h>
14 #include <linux/kdev_t.h>
15 #include <linux/list.h>
16 #include <linux/mempool.h>
17 #include <linux/module.h>
18 #include <linux/slab.h>
19 #include <linux/vmalloc.h>
20 #include <linux/log2.h>
21 #include <linux/dm-kcopyd.h>
22 #include <linux/workqueue.h>
24 #include "dm-exception-store.h"
26 #define DM_MSG_PREFIX "snapshots"
29 * The percentage increment we will wake up users at
31 #define WAKE_UP_PERCENT 5
34 * kcopyd priority of snapshot operations
36 #define SNAPSHOT_COPY_PRIORITY 2
39 * Reserve 1MB for each snapshot initially (with minimum of 1 page).
41 #define SNAPSHOT_PAGES (((1UL << 20) >> PAGE_SHIFT) ? : 1)
44 * The size of the mempool used to track chunks in use.
46 #define MIN_IOS 256
48 #define DM_TRACKED_CHUNK_HASH_SIZE 16
49 #define DM_TRACKED_CHUNK_HASH(x) ((unsigned long)(x) & \
50 (DM_TRACKED_CHUNK_HASH_SIZE - 1))
52 struct dm_exception_table {
53 uint32_t hash_mask;
54 unsigned hash_shift;
55 struct list_head *table;
58 struct dm_snapshot {
59 struct rw_semaphore lock;
61 struct dm_dev *origin;
62 struct dm_dev *cow;
64 struct dm_target *ti;
66 /* List of snapshots per Origin */
67 struct list_head list;
69 /* You can't use a snapshot if this is 0 (e.g. if full) */
70 int valid;
72 /* Origin writes don't trigger exceptions until this is set */
73 int active;
75 mempool_t *pending_pool;
77 atomic_t pending_exceptions_count;
79 struct dm_exception_table pending;
80 struct dm_exception_table complete;
83 * pe_lock protects all pending_exception operations and access
84 * as well as the snapshot_bios list.
86 spinlock_t pe_lock;
88 /* The on disk metadata handler */
89 struct dm_exception_store *store;
91 struct dm_kcopyd_client *kcopyd_client;
93 /* Queue of snapshot writes for ksnapd to flush */
94 struct bio_list queued_bios;
95 struct work_struct queued_bios_work;
97 /* Chunks with outstanding reads */
98 mempool_t *tracked_chunk_pool;
99 spinlock_t tracked_chunk_lock;
100 struct hlist_head tracked_chunk_hash[DM_TRACKED_CHUNK_HASH_SIZE];
103 struct dm_dev *dm_snap_cow(struct dm_snapshot *s)
105 return s->cow;
107 EXPORT_SYMBOL(dm_snap_cow);
109 static struct workqueue_struct *ksnapd;
110 static void flush_queued_bios(struct work_struct *work);
112 static sector_t chunk_to_sector(struct dm_exception_store *store,
113 chunk_t chunk)
115 return chunk << store->chunk_shift;
118 static int bdev_equal(struct block_device *lhs, struct block_device *rhs)
121 * There is only ever one instance of a particular block
122 * device so we can compare pointers safely.
124 return lhs == rhs;
127 struct dm_snap_pending_exception {
128 struct dm_exception e;
131 * Origin buffers waiting for this to complete are held
132 * in a bio list
134 struct bio_list origin_bios;
135 struct bio_list snapshot_bios;
138 * Short-term queue of pending exceptions prior to submission.
140 struct list_head list;
143 * The primary pending_exception is the one that holds
144 * the ref_count and the list of origin_bios for a
145 * group of pending_exceptions. It is always last to get freed.
146 * These fields get set up when writing to the origin.
148 struct dm_snap_pending_exception *primary_pe;
151 * Number of pending_exceptions processing this chunk.
152 * When this drops to zero we must complete the origin bios.
153 * If incrementing or decrementing this, hold pe->snap->lock for
154 * the sibling concerned and not pe->primary_pe->snap->lock unless
155 * they are the same.
157 atomic_t ref_count;
159 /* Pointer back to snapshot context */
160 struct dm_snapshot *snap;
163 * 1 indicates the exception has already been sent to
164 * kcopyd.
166 int started;
170 * Hash table mapping origin volumes to lists of snapshots and
171 * a lock to protect it
173 static struct kmem_cache *exception_cache;
174 static struct kmem_cache *pending_cache;
176 struct dm_snap_tracked_chunk {
177 struct hlist_node node;
178 chunk_t chunk;
181 static struct kmem_cache *tracked_chunk_cache;
183 static struct dm_snap_tracked_chunk *track_chunk(struct dm_snapshot *s,
184 chunk_t chunk)
186 struct dm_snap_tracked_chunk *c = mempool_alloc(s->tracked_chunk_pool,
187 GFP_NOIO);
188 unsigned long flags;
190 c->chunk = chunk;
192 spin_lock_irqsave(&s->tracked_chunk_lock, flags);
193 hlist_add_head(&c->node,
194 &s->tracked_chunk_hash[DM_TRACKED_CHUNK_HASH(chunk)]);
195 spin_unlock_irqrestore(&s->tracked_chunk_lock, flags);
197 return c;
200 static void stop_tracking_chunk(struct dm_snapshot *s,
201 struct dm_snap_tracked_chunk *c)
203 unsigned long flags;
205 spin_lock_irqsave(&s->tracked_chunk_lock, flags);
206 hlist_del(&c->node);
207 spin_unlock_irqrestore(&s->tracked_chunk_lock, flags);
209 mempool_free(c, s->tracked_chunk_pool);
212 static int __chunk_is_tracked(struct dm_snapshot *s, chunk_t chunk)
214 struct dm_snap_tracked_chunk *c;
215 struct hlist_node *hn;
216 int found = 0;
218 spin_lock_irq(&s->tracked_chunk_lock);
220 hlist_for_each_entry(c, hn,
221 &s->tracked_chunk_hash[DM_TRACKED_CHUNK_HASH(chunk)], node) {
222 if (c->chunk == chunk) {
223 found = 1;
224 break;
228 spin_unlock_irq(&s->tracked_chunk_lock);
230 return found;
234 * One of these per registered origin, held in the snapshot_origins hash
236 struct origin {
237 /* The origin device */
238 struct block_device *bdev;
240 struct list_head hash_list;
242 /* List of snapshots for this origin */
243 struct list_head snapshots;
247 * Size of the hash table for origin volumes. If we make this
248 * the size of the minors list then it should be nearly perfect
250 #define ORIGIN_HASH_SIZE 256
251 #define ORIGIN_MASK 0xFF
252 static struct list_head *_origins;
253 static struct rw_semaphore _origins_lock;
255 static int init_origin_hash(void)
257 int i;
259 _origins = kmalloc(ORIGIN_HASH_SIZE * sizeof(struct list_head),
260 GFP_KERNEL);
261 if (!_origins) {
262 DMERR("unable to allocate memory");
263 return -ENOMEM;
266 for (i = 0; i < ORIGIN_HASH_SIZE; i++)
267 INIT_LIST_HEAD(_origins + i);
268 init_rwsem(&_origins_lock);
270 return 0;
273 static void exit_origin_hash(void)
275 kfree(_origins);
278 static unsigned origin_hash(struct block_device *bdev)
280 return bdev->bd_dev & ORIGIN_MASK;
283 static struct origin *__lookup_origin(struct block_device *origin)
285 struct list_head *ol;
286 struct origin *o;
288 ol = &_origins[origin_hash(origin)];
289 list_for_each_entry (o, ol, hash_list)
290 if (bdev_equal(o->bdev, origin))
291 return o;
293 return NULL;
296 static void __insert_origin(struct origin *o)
298 struct list_head *sl = &_origins[origin_hash(o->bdev)];
299 list_add_tail(&o->hash_list, sl);
303 * Make a note of the snapshot and its origin so we can look it
304 * up when the origin has a write on it.
306 static int register_snapshot(struct dm_snapshot *snap)
308 struct origin *o, *new_o;
309 struct block_device *bdev = snap->origin->bdev;
311 new_o = kmalloc(sizeof(*new_o), GFP_KERNEL);
312 if (!new_o)
313 return -ENOMEM;
315 down_write(&_origins_lock);
316 o = __lookup_origin(bdev);
318 if (o)
319 kfree(new_o);
320 else {
321 /* New origin */
322 o = new_o;
324 /* Initialise the struct */
325 INIT_LIST_HEAD(&o->snapshots);
326 o->bdev = bdev;
328 __insert_origin(o);
331 list_add_tail(&snap->list, &o->snapshots);
333 up_write(&_origins_lock);
334 return 0;
337 static void unregister_snapshot(struct dm_snapshot *s)
339 struct origin *o;
341 down_write(&_origins_lock);
342 o = __lookup_origin(s->origin->bdev);
344 list_del(&s->list);
345 if (list_empty(&o->snapshots)) {
346 list_del(&o->hash_list);
347 kfree(o);
350 up_write(&_origins_lock);
354 * Implementation of the exception hash tables.
355 * The lowest hash_shift bits of the chunk number are ignored, allowing
356 * some consecutive chunks to be grouped together.
358 static int dm_exception_table_init(struct dm_exception_table *et,
359 uint32_t size, unsigned hash_shift)
361 unsigned int i;
363 et->hash_shift = hash_shift;
364 et->hash_mask = size - 1;
365 et->table = dm_vcalloc(size, sizeof(struct list_head));
366 if (!et->table)
367 return -ENOMEM;
369 for (i = 0; i < size; i++)
370 INIT_LIST_HEAD(et->table + i);
372 return 0;
375 static void dm_exception_table_exit(struct dm_exception_table *et,
376 struct kmem_cache *mem)
378 struct list_head *slot;
379 struct dm_exception *ex, *next;
380 int i, size;
382 size = et->hash_mask + 1;
383 for (i = 0; i < size; i++) {
384 slot = et->table + i;
386 list_for_each_entry_safe (ex, next, slot, hash_list)
387 kmem_cache_free(mem, ex);
390 vfree(et->table);
393 static uint32_t exception_hash(struct dm_exception_table *et, chunk_t chunk)
395 return (chunk >> et->hash_shift) & et->hash_mask;
398 static void dm_remove_exception(struct dm_exception *e)
400 list_del(&e->hash_list);
404 * Return the exception data for a sector, or NULL if not
405 * remapped.
407 static struct dm_exception *dm_lookup_exception(struct dm_exception_table *et,
408 chunk_t chunk)
410 struct list_head *slot;
411 struct dm_exception *e;
413 slot = &et->table[exception_hash(et, chunk)];
414 list_for_each_entry (e, slot, hash_list)
415 if (chunk >= e->old_chunk &&
416 chunk <= e->old_chunk + dm_consecutive_chunk_count(e))
417 return e;
419 return NULL;
422 static struct dm_exception *alloc_completed_exception(void)
424 struct dm_exception *e;
426 e = kmem_cache_alloc(exception_cache, GFP_NOIO);
427 if (!e)
428 e = kmem_cache_alloc(exception_cache, GFP_ATOMIC);
430 return e;
433 static void free_completed_exception(struct dm_exception *e)
435 kmem_cache_free(exception_cache, e);
438 static struct dm_snap_pending_exception *alloc_pending_exception(struct dm_snapshot *s)
440 struct dm_snap_pending_exception *pe = mempool_alloc(s->pending_pool,
441 GFP_NOIO);
443 atomic_inc(&s->pending_exceptions_count);
444 pe->snap = s;
446 return pe;
449 static void free_pending_exception(struct dm_snap_pending_exception *pe)
451 struct dm_snapshot *s = pe->snap;
453 mempool_free(pe, s->pending_pool);
454 smp_mb__before_atomic_dec();
455 atomic_dec(&s->pending_exceptions_count);
458 static void dm_insert_exception(struct dm_exception_table *eh,
459 struct dm_exception *new_e)
461 struct list_head *l;
462 struct dm_exception *e = NULL;
464 l = &eh->table[exception_hash(eh, new_e->old_chunk)];
466 /* Add immediately if this table doesn't support consecutive chunks */
467 if (!eh->hash_shift)
468 goto out;
470 /* List is ordered by old_chunk */
471 list_for_each_entry_reverse(e, l, hash_list) {
472 /* Insert after an existing chunk? */
473 if (new_e->old_chunk == (e->old_chunk +
474 dm_consecutive_chunk_count(e) + 1) &&
475 new_e->new_chunk == (dm_chunk_number(e->new_chunk) +
476 dm_consecutive_chunk_count(e) + 1)) {
477 dm_consecutive_chunk_count_inc(e);
478 free_completed_exception(new_e);
479 return;
482 /* Insert before an existing chunk? */
483 if (new_e->old_chunk == (e->old_chunk - 1) &&
484 new_e->new_chunk == (dm_chunk_number(e->new_chunk) - 1)) {
485 dm_consecutive_chunk_count_inc(e);
486 e->old_chunk--;
487 e->new_chunk--;
488 free_completed_exception(new_e);
489 return;
492 if (new_e->old_chunk > e->old_chunk)
493 break;
496 out:
497 list_add(&new_e->hash_list, e ? &e->hash_list : l);
501 * Callback used by the exception stores to load exceptions when
502 * initialising.
504 static int dm_add_exception(void *context, chunk_t old, chunk_t new)
506 struct dm_snapshot *s = context;
507 struct dm_exception *e;
509 e = alloc_completed_exception();
510 if (!e)
511 return -ENOMEM;
513 e->old_chunk = old;
515 /* Consecutive_count is implicitly initialised to zero */
516 e->new_chunk = new;
518 dm_insert_exception(&s->complete, e);
520 return 0;
523 #define min_not_zero(l, r) (((l) == 0) ? (r) : (((r) == 0) ? (l) : min(l, r)))
526 * Return a minimum chunk size of all snapshots that have the specified origin.
527 * Return zero if the origin has no snapshots.
529 static sector_t __minimum_chunk_size(struct origin *o)
531 struct dm_snapshot *snap;
532 unsigned chunk_size = 0;
534 if (o)
535 list_for_each_entry(snap, &o->snapshots, list)
536 chunk_size = min_not_zero(chunk_size,
537 snap->store->chunk_size);
539 return chunk_size;
543 * Hard coded magic.
545 static int calc_max_buckets(void)
547 /* use a fixed size of 2MB */
548 unsigned long mem = 2 * 1024 * 1024;
549 mem /= sizeof(struct list_head);
551 return mem;
555 * Allocate room for a suitable hash table.
557 static int init_hash_tables(struct dm_snapshot *s)
559 sector_t hash_size, cow_dev_size, origin_dev_size, max_buckets;
562 * Calculate based on the size of the original volume or
563 * the COW volume...
565 cow_dev_size = get_dev_size(s->cow->bdev);
566 origin_dev_size = get_dev_size(s->origin->bdev);
567 max_buckets = calc_max_buckets();
569 hash_size = min(origin_dev_size, cow_dev_size) >> s->store->chunk_shift;
570 hash_size = min(hash_size, max_buckets);
572 hash_size = rounddown_pow_of_two(hash_size);
573 if (dm_exception_table_init(&s->complete, hash_size,
574 DM_CHUNK_CONSECUTIVE_BITS))
575 return -ENOMEM;
578 * Allocate hash table for in-flight exceptions
579 * Make this smaller than the real hash table
581 hash_size >>= 3;
582 if (hash_size < 64)
583 hash_size = 64;
585 if (dm_exception_table_init(&s->pending, hash_size, 0)) {
586 dm_exception_table_exit(&s->complete, exception_cache);
587 return -ENOMEM;
590 return 0;
594 * Construct a snapshot mapping: <origin_dev> <COW-dev> <p/n> <chunk-size>
596 static int snapshot_ctr(struct dm_target *ti, unsigned int argc, char **argv)
598 struct dm_snapshot *s;
599 int i;
600 int r = -EINVAL;
601 char *origin_path, *cow_path;
602 unsigned args_used;
604 if (argc != 4) {
605 ti->error = "requires exactly 4 arguments";
606 r = -EINVAL;
607 goto bad;
610 origin_path = argv[0];
611 argv++;
612 argc--;
614 s = kmalloc(sizeof(*s), GFP_KERNEL);
615 if (!s) {
616 ti->error = "Cannot allocate snapshot context private "
617 "structure";
618 r = -ENOMEM;
619 goto bad;
622 cow_path = argv[0];
623 argv++;
624 argc--;
626 r = dm_get_device(ti, cow_path, 0, 0,
627 FMODE_READ | FMODE_WRITE, &s->cow);
628 if (r) {
629 ti->error = "Cannot get COW device";
630 goto bad_cow;
633 r = dm_exception_store_create(ti, argc, argv, s, &args_used, &s->store);
634 if (r) {
635 ti->error = "Couldn't create exception store";
636 r = -EINVAL;
637 goto bad_store;
640 argv += args_used;
641 argc -= args_used;
643 r = dm_get_device(ti, origin_path, 0, ti->len, FMODE_READ, &s->origin);
644 if (r) {
645 ti->error = "Cannot get origin device";
646 goto bad_origin;
649 s->ti = ti;
650 s->valid = 1;
651 s->active = 0;
652 atomic_set(&s->pending_exceptions_count, 0);
653 init_rwsem(&s->lock);
654 spin_lock_init(&s->pe_lock);
656 /* Allocate hash table for COW data */
657 if (init_hash_tables(s)) {
658 ti->error = "Unable to allocate hash table space";
659 r = -ENOMEM;
660 goto bad_hash_tables;
663 r = dm_kcopyd_client_create(SNAPSHOT_PAGES, &s->kcopyd_client);
664 if (r) {
665 ti->error = "Could not create kcopyd client";
666 goto bad_kcopyd;
669 s->pending_pool = mempool_create_slab_pool(MIN_IOS, pending_cache);
670 if (!s->pending_pool) {
671 ti->error = "Could not allocate mempool for pending exceptions";
672 goto bad_pending_pool;
675 s->tracked_chunk_pool = mempool_create_slab_pool(MIN_IOS,
676 tracked_chunk_cache);
677 if (!s->tracked_chunk_pool) {
678 ti->error = "Could not allocate tracked_chunk mempool for "
679 "tracking reads";
680 goto bad_tracked_chunk_pool;
683 for (i = 0; i < DM_TRACKED_CHUNK_HASH_SIZE; i++)
684 INIT_HLIST_HEAD(&s->tracked_chunk_hash[i]);
686 spin_lock_init(&s->tracked_chunk_lock);
688 /* Metadata must only be loaded into one table at once */
689 r = s->store->type->read_metadata(s->store, dm_add_exception,
690 (void *)s);
691 if (r < 0) {
692 ti->error = "Failed to read snapshot metadata";
693 goto bad_load_and_register;
694 } else if (r > 0) {
695 s->valid = 0;
696 DMWARN("Snapshot is marked invalid.");
699 bio_list_init(&s->queued_bios);
700 INIT_WORK(&s->queued_bios_work, flush_queued_bios);
702 if (!s->store->chunk_size) {
703 ti->error = "Chunk size not set";
704 goto bad_load_and_register;
707 /* Add snapshot to the list of snapshots for this origin */
708 /* Exceptions aren't triggered till snapshot_resume() is called */
709 if (register_snapshot(s)) {
710 r = -EINVAL;
711 ti->error = "Cannot register snapshot origin";
712 goto bad_load_and_register;
715 ti->private = s;
716 ti->split_io = s->store->chunk_size;
717 ti->num_flush_requests = 1;
719 return 0;
721 bad_load_and_register:
722 mempool_destroy(s->tracked_chunk_pool);
724 bad_tracked_chunk_pool:
725 mempool_destroy(s->pending_pool);
727 bad_pending_pool:
728 dm_kcopyd_client_destroy(s->kcopyd_client);
730 bad_kcopyd:
731 dm_exception_table_exit(&s->pending, pending_cache);
732 dm_exception_table_exit(&s->complete, exception_cache);
734 bad_hash_tables:
735 dm_put_device(ti, s->origin);
737 bad_origin:
738 dm_exception_store_destroy(s->store);
740 bad_store:
741 dm_put_device(ti, s->cow);
743 bad_cow:
744 kfree(s);
746 bad:
747 return r;
750 static void __free_exceptions(struct dm_snapshot *s)
752 dm_kcopyd_client_destroy(s->kcopyd_client);
753 s->kcopyd_client = NULL;
755 dm_exception_table_exit(&s->pending, pending_cache);
756 dm_exception_table_exit(&s->complete, exception_cache);
759 static void snapshot_dtr(struct dm_target *ti)
761 #ifdef CONFIG_DM_DEBUG
762 int i;
763 #endif
764 struct dm_snapshot *s = ti->private;
766 flush_workqueue(ksnapd);
768 /* Prevent further origin writes from using this snapshot. */
769 /* After this returns there can be no new kcopyd jobs. */
770 unregister_snapshot(s);
772 while (atomic_read(&s->pending_exceptions_count))
773 msleep(1);
775 * Ensure instructions in mempool_destroy aren't reordered
776 * before atomic_read.
778 smp_mb();
780 #ifdef CONFIG_DM_DEBUG
781 for (i = 0; i < DM_TRACKED_CHUNK_HASH_SIZE; i++)
782 BUG_ON(!hlist_empty(&s->tracked_chunk_hash[i]));
783 #endif
785 mempool_destroy(s->tracked_chunk_pool);
787 __free_exceptions(s);
789 mempool_destroy(s->pending_pool);
791 dm_put_device(ti, s->origin);
793 dm_exception_store_destroy(s->store);
795 dm_put_device(ti, s->cow);
797 kfree(s);
801 * Flush a list of buffers.
803 static void flush_bios(struct bio *bio)
805 struct bio *n;
807 while (bio) {
808 n = bio->bi_next;
809 bio->bi_next = NULL;
810 generic_make_request(bio);
811 bio = n;
815 static void flush_queued_bios(struct work_struct *work)
817 struct dm_snapshot *s =
818 container_of(work, struct dm_snapshot, queued_bios_work);
819 struct bio *queued_bios;
820 unsigned long flags;
822 spin_lock_irqsave(&s->pe_lock, flags);
823 queued_bios = bio_list_get(&s->queued_bios);
824 spin_unlock_irqrestore(&s->pe_lock, flags);
826 flush_bios(queued_bios);
830 * Error a list of buffers.
832 static void error_bios(struct bio *bio)
834 struct bio *n;
836 while (bio) {
837 n = bio->bi_next;
838 bio->bi_next = NULL;
839 bio_io_error(bio);
840 bio = n;
844 static void __invalidate_snapshot(struct dm_snapshot *s, int err)
846 if (!s->valid)
847 return;
849 if (err == -EIO)
850 DMERR("Invalidating snapshot: Error reading/writing.");
851 else if (err == -ENOMEM)
852 DMERR("Invalidating snapshot: Unable to allocate exception.");
854 if (s->store->type->drop_snapshot)
855 s->store->type->drop_snapshot(s->store);
857 s->valid = 0;
859 dm_table_event(s->ti->table);
862 static void get_pending_exception(struct dm_snap_pending_exception *pe)
864 atomic_inc(&pe->ref_count);
867 static struct bio *put_pending_exception(struct dm_snap_pending_exception *pe)
869 struct dm_snap_pending_exception *primary_pe;
870 struct bio *origin_bios = NULL;
872 primary_pe = pe->primary_pe;
875 * If this pe is involved in a write to the origin and
876 * it is the last sibling to complete then release
877 * the bios for the original write to the origin.
879 if (primary_pe &&
880 atomic_dec_and_test(&primary_pe->ref_count)) {
881 origin_bios = bio_list_get(&primary_pe->origin_bios);
882 free_pending_exception(primary_pe);
886 * Free the pe if it's not linked to an origin write or if
887 * it's not itself a primary pe.
889 if (!primary_pe || primary_pe != pe)
890 free_pending_exception(pe);
892 return origin_bios;
895 static void pending_complete(struct dm_snap_pending_exception *pe, int success)
897 struct dm_exception *e;
898 struct dm_snapshot *s = pe->snap;
899 struct bio *origin_bios = NULL;
900 struct bio *snapshot_bios = NULL;
901 int error = 0;
903 if (!success) {
904 /* Read/write error - snapshot is unusable */
905 down_write(&s->lock);
906 __invalidate_snapshot(s, -EIO);
907 error = 1;
908 goto out;
911 e = alloc_completed_exception();
912 if (!e) {
913 down_write(&s->lock);
914 __invalidate_snapshot(s, -ENOMEM);
915 error = 1;
916 goto out;
918 *e = pe->e;
920 down_write(&s->lock);
921 if (!s->valid) {
922 free_completed_exception(e);
923 error = 1;
924 goto out;
928 * Check for conflicting reads. This is extremely improbable,
929 * so msleep(1) is sufficient and there is no need for a wait queue.
931 while (__chunk_is_tracked(s, pe->e.old_chunk))
932 msleep(1);
935 * Add a proper exception, and remove the
936 * in-flight exception from the list.
938 dm_insert_exception(&s->complete, e);
940 out:
941 dm_remove_exception(&pe->e);
942 snapshot_bios = bio_list_get(&pe->snapshot_bios);
943 origin_bios = put_pending_exception(pe);
945 up_write(&s->lock);
947 /* Submit any pending write bios */
948 if (error)
949 error_bios(snapshot_bios);
950 else
951 flush_bios(snapshot_bios);
953 flush_bios(origin_bios);
956 static void commit_callback(void *context, int success)
958 struct dm_snap_pending_exception *pe = context;
960 pending_complete(pe, success);
964 * Called when the copy I/O has finished. kcopyd actually runs
965 * this code so don't block.
967 static void copy_callback(int read_err, unsigned long write_err, void *context)
969 struct dm_snap_pending_exception *pe = context;
970 struct dm_snapshot *s = pe->snap;
972 if (read_err || write_err)
973 pending_complete(pe, 0);
975 else
976 /* Update the metadata if we are persistent */
977 s->store->type->commit_exception(s->store, &pe->e,
978 commit_callback, pe);
982 * Dispatches the copy operation to kcopyd.
984 static void start_copy(struct dm_snap_pending_exception *pe)
986 struct dm_snapshot *s = pe->snap;
987 struct dm_io_region src, dest;
988 struct block_device *bdev = s->origin->bdev;
989 sector_t dev_size;
991 dev_size = get_dev_size(bdev);
993 src.bdev = bdev;
994 src.sector = chunk_to_sector(s->store, pe->e.old_chunk);
995 src.count = min((sector_t)s->store->chunk_size, dev_size - src.sector);
997 dest.bdev = s->cow->bdev;
998 dest.sector = chunk_to_sector(s->store, pe->e.new_chunk);
999 dest.count = src.count;
1001 /* Hand over to kcopyd */
1002 dm_kcopyd_copy(s->kcopyd_client,
1003 &src, 1, &dest, 0, copy_callback, pe);
1006 static struct dm_snap_pending_exception *
1007 __lookup_pending_exception(struct dm_snapshot *s, chunk_t chunk)
1009 struct dm_exception *e = dm_lookup_exception(&s->pending, chunk);
1011 if (!e)
1012 return NULL;
1014 return container_of(e, struct dm_snap_pending_exception, e);
1018 * Looks to see if this snapshot already has a pending exception
1019 * for this chunk, otherwise it allocates a new one and inserts
1020 * it into the pending table.
1022 * NOTE: a write lock must be held on snap->lock before calling
1023 * this.
1025 static struct dm_snap_pending_exception *
1026 __find_pending_exception(struct dm_snapshot *s,
1027 struct dm_snap_pending_exception *pe, chunk_t chunk)
1029 struct dm_snap_pending_exception *pe2;
1031 pe2 = __lookup_pending_exception(s, chunk);
1032 if (pe2) {
1033 free_pending_exception(pe);
1034 return pe2;
1037 pe->e.old_chunk = chunk;
1038 bio_list_init(&pe->origin_bios);
1039 bio_list_init(&pe->snapshot_bios);
1040 pe->primary_pe = NULL;
1041 atomic_set(&pe->ref_count, 0);
1042 pe->started = 0;
1044 if (s->store->type->prepare_exception(s->store, &pe->e)) {
1045 free_pending_exception(pe);
1046 return NULL;
1049 get_pending_exception(pe);
1050 dm_insert_exception(&s->pending, &pe->e);
1052 return pe;
1055 static void remap_exception(struct dm_snapshot *s, struct dm_exception *e,
1056 struct bio *bio, chunk_t chunk)
1058 bio->bi_bdev = s->cow->bdev;
1059 bio->bi_sector = chunk_to_sector(s->store,
1060 dm_chunk_number(e->new_chunk) +
1061 (chunk - e->old_chunk)) +
1062 (bio->bi_sector &
1063 s->store->chunk_mask);
1066 static int snapshot_map(struct dm_target *ti, struct bio *bio,
1067 union map_info *map_context)
1069 struct dm_exception *e;
1070 struct dm_snapshot *s = ti->private;
1071 int r = DM_MAPIO_REMAPPED;
1072 chunk_t chunk;
1073 struct dm_snap_pending_exception *pe = NULL;
1075 if (unlikely(bio_empty_barrier(bio))) {
1076 bio->bi_bdev = s->cow->bdev;
1077 return DM_MAPIO_REMAPPED;
1080 chunk = sector_to_chunk(s->store, bio->bi_sector);
1082 /* Full snapshots are not usable */
1083 /* To get here the table must be live so s->active is always set. */
1084 if (!s->valid)
1085 return -EIO;
1087 /* FIXME: should only take write lock if we need
1088 * to copy an exception */
1089 down_write(&s->lock);
1091 if (!s->valid) {
1092 r = -EIO;
1093 goto out_unlock;
1096 /* If the block is already remapped - use that, else remap it */
1097 e = dm_lookup_exception(&s->complete, chunk);
1098 if (e) {
1099 remap_exception(s, e, bio, chunk);
1100 goto out_unlock;
1104 * Write to snapshot - higher level takes care of RW/RO
1105 * flags so we should only get this if we are
1106 * writeable.
1108 if (bio_rw(bio) == WRITE) {
1109 pe = __lookup_pending_exception(s, chunk);
1110 if (!pe) {
1111 up_write(&s->lock);
1112 pe = alloc_pending_exception(s);
1113 down_write(&s->lock);
1115 if (!s->valid) {
1116 free_pending_exception(pe);
1117 r = -EIO;
1118 goto out_unlock;
1121 e = dm_lookup_exception(&s->complete, chunk);
1122 if (e) {
1123 free_pending_exception(pe);
1124 remap_exception(s, e, bio, chunk);
1125 goto out_unlock;
1128 pe = __find_pending_exception(s, pe, chunk);
1129 if (!pe) {
1130 __invalidate_snapshot(s, -ENOMEM);
1131 r = -EIO;
1132 goto out_unlock;
1136 remap_exception(s, &pe->e, bio, chunk);
1137 bio_list_add(&pe->snapshot_bios, bio);
1139 r = DM_MAPIO_SUBMITTED;
1141 if (!pe->started) {
1142 /* this is protected by snap->lock */
1143 pe->started = 1;
1144 up_write(&s->lock);
1145 start_copy(pe);
1146 goto out;
1148 } else {
1149 bio->bi_bdev = s->origin->bdev;
1150 map_context->ptr = track_chunk(s, chunk);
1153 out_unlock:
1154 up_write(&s->lock);
1155 out:
1156 return r;
1159 static int snapshot_end_io(struct dm_target *ti, struct bio *bio,
1160 int error, union map_info *map_context)
1162 struct dm_snapshot *s = ti->private;
1163 struct dm_snap_tracked_chunk *c = map_context->ptr;
1165 if (c)
1166 stop_tracking_chunk(s, c);
1168 return 0;
1171 static void snapshot_resume(struct dm_target *ti)
1173 struct dm_snapshot *s = ti->private;
1175 down_write(&s->lock);
1176 s->active = 1;
1177 up_write(&s->lock);
1180 static int snapshot_status(struct dm_target *ti, status_type_t type,
1181 char *result, unsigned int maxlen)
1183 unsigned sz = 0;
1184 struct dm_snapshot *snap = ti->private;
1186 down_write(&snap->lock);
1188 switch (type) {
1189 case STATUSTYPE_INFO:
1190 if (!snap->valid)
1191 DMEMIT("Invalid");
1192 else {
1193 if (snap->store->type->usage) {
1194 sector_t total_sectors, sectors_allocated,
1195 metadata_sectors;
1196 snap->store->type->usage(snap->store,
1197 &total_sectors,
1198 &sectors_allocated,
1199 &metadata_sectors);
1200 DMEMIT("%llu/%llu %llu",
1201 (unsigned long long)sectors_allocated,
1202 (unsigned long long)total_sectors,
1203 (unsigned long long)metadata_sectors);
1205 else
1206 DMEMIT("Unknown");
1208 break;
1210 case STATUSTYPE_TABLE:
1212 * kdevname returns a static pointer so we need
1213 * to make private copies if the output is to
1214 * make sense.
1216 DMEMIT("%s %s", snap->origin->name, snap->cow->name);
1217 snap->store->type->status(snap->store, type, result + sz,
1218 maxlen - sz);
1219 break;
1222 up_write(&snap->lock);
1224 return 0;
1227 static int snapshot_iterate_devices(struct dm_target *ti,
1228 iterate_devices_callout_fn fn, void *data)
1230 struct dm_snapshot *snap = ti->private;
1232 return fn(ti, snap->origin, 0, ti->len, data);
1236 /*-----------------------------------------------------------------
1237 * Origin methods
1238 *---------------------------------------------------------------*/
1239 static int __origin_write(struct list_head *snapshots, struct bio *bio)
1241 int r = DM_MAPIO_REMAPPED, first = 0;
1242 struct dm_snapshot *snap;
1243 struct dm_exception *e;
1244 struct dm_snap_pending_exception *pe, *next_pe, *primary_pe = NULL;
1245 chunk_t chunk;
1246 LIST_HEAD(pe_queue);
1248 /* Do all the snapshots on this origin */
1249 list_for_each_entry (snap, snapshots, list) {
1251 down_write(&snap->lock);
1253 /* Only deal with valid and active snapshots */
1254 if (!snap->valid || !snap->active)
1255 goto next_snapshot;
1257 /* Nothing to do if writing beyond end of snapshot */
1258 if (bio->bi_sector >= dm_table_get_size(snap->ti->table))
1259 goto next_snapshot;
1262 * Remember, different snapshots can have
1263 * different chunk sizes.
1265 chunk = sector_to_chunk(snap->store, bio->bi_sector);
1268 * Check exception table to see if block
1269 * is already remapped in this snapshot
1270 * and trigger an exception if not.
1272 * ref_count is initialised to 1 so pending_complete()
1273 * won't destroy the primary_pe while we're inside this loop.
1275 e = dm_lookup_exception(&snap->complete, chunk);
1276 if (e)
1277 goto next_snapshot;
1279 pe = __lookup_pending_exception(snap, chunk);
1280 if (!pe) {
1281 up_write(&snap->lock);
1282 pe = alloc_pending_exception(snap);
1283 down_write(&snap->lock);
1285 if (!snap->valid) {
1286 free_pending_exception(pe);
1287 goto next_snapshot;
1290 e = dm_lookup_exception(&snap->complete, chunk);
1291 if (e) {
1292 free_pending_exception(pe);
1293 goto next_snapshot;
1296 pe = __find_pending_exception(snap, pe, chunk);
1297 if (!pe) {
1298 __invalidate_snapshot(snap, -ENOMEM);
1299 goto next_snapshot;
1303 if (!primary_pe) {
1305 * Either every pe here has same
1306 * primary_pe or none has one yet.
1308 if (pe->primary_pe)
1309 primary_pe = pe->primary_pe;
1310 else {
1311 primary_pe = pe;
1312 first = 1;
1315 bio_list_add(&primary_pe->origin_bios, bio);
1317 r = DM_MAPIO_SUBMITTED;
1320 if (!pe->primary_pe) {
1321 pe->primary_pe = primary_pe;
1322 get_pending_exception(primary_pe);
1325 if (!pe->started) {
1326 pe->started = 1;
1327 list_add_tail(&pe->list, &pe_queue);
1330 next_snapshot:
1331 up_write(&snap->lock);
1334 if (!primary_pe)
1335 return r;
1338 * If this is the first time we're processing this chunk and
1339 * ref_count is now 1 it means all the pending exceptions
1340 * got completed while we were in the loop above, so it falls to
1341 * us here to remove the primary_pe and submit any origin_bios.
1344 if (first && atomic_dec_and_test(&primary_pe->ref_count)) {
1345 flush_bios(bio_list_get(&primary_pe->origin_bios));
1346 free_pending_exception(primary_pe);
1347 /* If we got here, pe_queue is necessarily empty. */
1348 return r;
1352 * Now that we have a complete pe list we can start the copying.
1354 list_for_each_entry_safe(pe, next_pe, &pe_queue, list)
1355 start_copy(pe);
1357 return r;
1361 * Called on a write from the origin driver.
1363 static int do_origin(struct dm_dev *origin, struct bio *bio)
1365 struct origin *o;
1366 int r = DM_MAPIO_REMAPPED;
1368 down_read(&_origins_lock);
1369 o = __lookup_origin(origin->bdev);
1370 if (o)
1371 r = __origin_write(&o->snapshots, bio);
1372 up_read(&_origins_lock);
1374 return r;
1378 * Origin: maps a linear range of a device, with hooks for snapshotting.
1382 * Construct an origin mapping: <dev_path>
1383 * The context for an origin is merely a 'struct dm_dev *'
1384 * pointing to the real device.
1386 static int origin_ctr(struct dm_target *ti, unsigned int argc, char **argv)
1388 int r;
1389 struct dm_dev *dev;
1391 if (argc != 1) {
1392 ti->error = "origin: incorrect number of arguments";
1393 return -EINVAL;
1396 r = dm_get_device(ti, argv[0], 0, ti->len,
1397 dm_table_get_mode(ti->table), &dev);
1398 if (r) {
1399 ti->error = "Cannot get target device";
1400 return r;
1403 ti->private = dev;
1404 ti->num_flush_requests = 1;
1406 return 0;
1409 static void origin_dtr(struct dm_target *ti)
1411 struct dm_dev *dev = ti->private;
1412 dm_put_device(ti, dev);
1415 static int origin_map(struct dm_target *ti, struct bio *bio,
1416 union map_info *map_context)
1418 struct dm_dev *dev = ti->private;
1419 bio->bi_bdev = dev->bdev;
1421 if (unlikely(bio_empty_barrier(bio)))
1422 return DM_MAPIO_REMAPPED;
1424 /* Only tell snapshots if this is a write */
1425 return (bio_rw(bio) == WRITE) ? do_origin(dev, bio) : DM_MAPIO_REMAPPED;
1429 * Set the target "split_io" field to the minimum of all the snapshots'
1430 * chunk sizes.
1432 static void origin_resume(struct dm_target *ti)
1434 struct dm_dev *dev = ti->private;
1436 down_read(&_origins_lock);
1438 ti->split_io = __minimum_chunk_size(__lookup_origin(dev->bdev));
1440 up_read(&_origins_lock);
1443 static int origin_status(struct dm_target *ti, status_type_t type, char *result,
1444 unsigned int maxlen)
1446 struct dm_dev *dev = ti->private;
1448 switch (type) {
1449 case STATUSTYPE_INFO:
1450 result[0] = '\0';
1451 break;
1453 case STATUSTYPE_TABLE:
1454 snprintf(result, maxlen, "%s", dev->name);
1455 break;
1458 return 0;
1461 static int origin_iterate_devices(struct dm_target *ti,
1462 iterate_devices_callout_fn fn, void *data)
1464 struct dm_dev *dev = ti->private;
1466 return fn(ti, dev, 0, ti->len, data);
1469 static struct target_type origin_target = {
1470 .name = "snapshot-origin",
1471 .version = {1, 7, 0},
1472 .module = THIS_MODULE,
1473 .ctr = origin_ctr,
1474 .dtr = origin_dtr,
1475 .map = origin_map,
1476 .resume = origin_resume,
1477 .status = origin_status,
1478 .iterate_devices = origin_iterate_devices,
1481 static struct target_type snapshot_target = {
1482 .name = "snapshot",
1483 .version = {1, 8, 0},
1484 .module = THIS_MODULE,
1485 .ctr = snapshot_ctr,
1486 .dtr = snapshot_dtr,
1487 .map = snapshot_map,
1488 .end_io = snapshot_end_io,
1489 .resume = snapshot_resume,
1490 .status = snapshot_status,
1491 .iterate_devices = snapshot_iterate_devices,
1494 static int __init dm_snapshot_init(void)
1496 int r;
1498 r = dm_exception_store_init();
1499 if (r) {
1500 DMERR("Failed to initialize exception stores");
1501 return r;
1504 r = dm_register_target(&snapshot_target);
1505 if (r) {
1506 DMERR("snapshot target register failed %d", r);
1507 goto bad_register_snapshot_target;
1510 r = dm_register_target(&origin_target);
1511 if (r < 0) {
1512 DMERR("Origin target register failed %d", r);
1513 goto bad1;
1516 r = init_origin_hash();
1517 if (r) {
1518 DMERR("init_origin_hash failed.");
1519 goto bad2;
1522 exception_cache = KMEM_CACHE(dm_exception, 0);
1523 if (!exception_cache) {
1524 DMERR("Couldn't create exception cache.");
1525 r = -ENOMEM;
1526 goto bad3;
1529 pending_cache = KMEM_CACHE(dm_snap_pending_exception, 0);
1530 if (!pending_cache) {
1531 DMERR("Couldn't create pending cache.");
1532 r = -ENOMEM;
1533 goto bad4;
1536 tracked_chunk_cache = KMEM_CACHE(dm_snap_tracked_chunk, 0);
1537 if (!tracked_chunk_cache) {
1538 DMERR("Couldn't create cache to track chunks in use.");
1539 r = -ENOMEM;
1540 goto bad5;
1543 ksnapd = create_singlethread_workqueue("ksnapd");
1544 if (!ksnapd) {
1545 DMERR("Failed to create ksnapd workqueue.");
1546 r = -ENOMEM;
1547 goto bad_pending_pool;
1550 return 0;
1552 bad_pending_pool:
1553 kmem_cache_destroy(tracked_chunk_cache);
1554 bad5:
1555 kmem_cache_destroy(pending_cache);
1556 bad4:
1557 kmem_cache_destroy(exception_cache);
1558 bad3:
1559 exit_origin_hash();
1560 bad2:
1561 dm_unregister_target(&origin_target);
1562 bad1:
1563 dm_unregister_target(&snapshot_target);
1565 bad_register_snapshot_target:
1566 dm_exception_store_exit();
1567 return r;
1570 static void __exit dm_snapshot_exit(void)
1572 destroy_workqueue(ksnapd);
1574 dm_unregister_target(&snapshot_target);
1575 dm_unregister_target(&origin_target);
1577 exit_origin_hash();
1578 kmem_cache_destroy(pending_cache);
1579 kmem_cache_destroy(exception_cache);
1580 kmem_cache_destroy(tracked_chunk_cache);
1582 dm_exception_store_exit();
1585 /* Module hooks */
1586 module_init(dm_snapshot_init);
1587 module_exit(dm_snapshot_exit);
1589 MODULE_DESCRIPTION(DM_NAME " snapshot target");
1590 MODULE_AUTHOR("Joe Thornber");
1591 MODULE_LICENSE("GPL");