dm snapshot: queue writes to chunks being merged
[pandora-kernel.git] / drivers / md / dm-snap.c
1 /*
2  * dm-snapshot.c
3  *
4  * Copyright (C) 2001-2002 Sistina Software (UK) Limited.
5  *
6  * This file is released under the GPL.
7  */
8
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>
23
24 #include "dm-exception-store.h"
25
26 #define DM_MSG_PREFIX "snapshots"
27
28 static const char dm_snapshot_merge_target_name[] = "snapshot-merge";
29
30 #define dm_target_is_snapshot_merge(ti) \
31         ((ti)->type->name == dm_snapshot_merge_target_name)
32
33 /*
34  * The percentage increment we will wake up users at
35  */
36 #define WAKE_UP_PERCENT 5
37
38 /*
39  * kcopyd priority of snapshot operations
40  */
41 #define SNAPSHOT_COPY_PRIORITY 2
42
43 /*
44  * Reserve 1MB for each snapshot initially (with minimum of 1 page).
45  */
46 #define SNAPSHOT_PAGES (((1UL << 20) >> PAGE_SHIFT) ? : 1)
47
48 /*
49  * The size of the mempool used to track chunks in use.
50  */
51 #define MIN_IOS 256
52
53 #define DM_TRACKED_CHUNK_HASH_SIZE      16
54 #define DM_TRACKED_CHUNK_HASH(x)        ((unsigned long)(x) & \
55                                          (DM_TRACKED_CHUNK_HASH_SIZE - 1))
56
57 struct dm_exception_table {
58         uint32_t hash_mask;
59         unsigned hash_shift;
60         struct list_head *table;
61 };
62
63 struct dm_snapshot {
64         struct rw_semaphore lock;
65
66         struct dm_dev *origin;
67         struct dm_dev *cow;
68
69         struct dm_target *ti;
70
71         /* List of snapshots per Origin */
72         struct list_head list;
73
74         /* You can't use a snapshot if this is 0 (e.g. if full) */
75         int valid;
76
77         /* Origin writes don't trigger exceptions until this is set */
78         int active;
79
80         /* Whether or not owning mapped_device is suspended */
81         int suspended;
82
83         mempool_t *pending_pool;
84
85         atomic_t pending_exceptions_count;
86
87         struct dm_exception_table pending;
88         struct dm_exception_table complete;
89
90         /*
91          * pe_lock protects all pending_exception operations and access
92          * as well as the snapshot_bios list.
93          */
94         spinlock_t pe_lock;
95
96         /* The on disk metadata handler */
97         struct dm_exception_store *store;
98
99         struct dm_kcopyd_client *kcopyd_client;
100
101         /* Queue of snapshot writes for ksnapd to flush */
102         struct bio_list queued_bios;
103         struct work_struct queued_bios_work;
104
105         /* Chunks with outstanding reads */
106         mempool_t *tracked_chunk_pool;
107         spinlock_t tracked_chunk_lock;
108         struct hlist_head tracked_chunk_hash[DM_TRACKED_CHUNK_HASH_SIZE];
109
110         /* Wait for events based on state_bits */
111         unsigned long state_bits;
112
113         /* Range of chunks currently being merged. */
114         chunk_t first_merging_chunk;
115         int num_merging_chunks;
116
117         /*
118          * Incoming bios that overlap with chunks being merged must wait
119          * for them to be committed.
120          */
121         struct bio_list bios_queued_during_merge;
122 };
123
124 /*
125  * state_bits:
126  *   RUNNING_MERGE  - Merge operation is in progress.
127  *   SHUTDOWN_MERGE - Set to signal that merge needs to be stopped;
128  *                    cleared afterwards.
129  */
130 #define RUNNING_MERGE          0
131 #define SHUTDOWN_MERGE         1
132
133 struct dm_dev *dm_snap_cow(struct dm_snapshot *s)
134 {
135         return s->cow;
136 }
137 EXPORT_SYMBOL(dm_snap_cow);
138
139 static struct workqueue_struct *ksnapd;
140 static void flush_queued_bios(struct work_struct *work);
141
142 static sector_t chunk_to_sector(struct dm_exception_store *store,
143                                 chunk_t chunk)
144 {
145         return chunk << store->chunk_shift;
146 }
147
148 static int bdev_equal(struct block_device *lhs, struct block_device *rhs)
149 {
150         /*
151          * There is only ever one instance of a particular block
152          * device so we can compare pointers safely.
153          */
154         return lhs == rhs;
155 }
156
157 struct dm_snap_pending_exception {
158         struct dm_exception e;
159
160         /*
161          * Origin buffers waiting for this to complete are held
162          * in a bio list
163          */
164         struct bio_list origin_bios;
165         struct bio_list snapshot_bios;
166
167         /* Pointer back to snapshot context */
168         struct dm_snapshot *snap;
169
170         /*
171          * 1 indicates the exception has already been sent to
172          * kcopyd.
173          */
174         int started;
175 };
176
177 /*
178  * Hash table mapping origin volumes to lists of snapshots and
179  * a lock to protect it
180  */
181 static struct kmem_cache *exception_cache;
182 static struct kmem_cache *pending_cache;
183
184 struct dm_snap_tracked_chunk {
185         struct hlist_node node;
186         chunk_t chunk;
187 };
188
189 static struct kmem_cache *tracked_chunk_cache;
190
191 static struct dm_snap_tracked_chunk *track_chunk(struct dm_snapshot *s,
192                                                  chunk_t chunk)
193 {
194         struct dm_snap_tracked_chunk *c = mempool_alloc(s->tracked_chunk_pool,
195                                                         GFP_NOIO);
196         unsigned long flags;
197
198         c->chunk = chunk;
199
200         spin_lock_irqsave(&s->tracked_chunk_lock, flags);
201         hlist_add_head(&c->node,
202                        &s->tracked_chunk_hash[DM_TRACKED_CHUNK_HASH(chunk)]);
203         spin_unlock_irqrestore(&s->tracked_chunk_lock, flags);
204
205         return c;
206 }
207
208 static void stop_tracking_chunk(struct dm_snapshot *s,
209                                 struct dm_snap_tracked_chunk *c)
210 {
211         unsigned long flags;
212
213         spin_lock_irqsave(&s->tracked_chunk_lock, flags);
214         hlist_del(&c->node);
215         spin_unlock_irqrestore(&s->tracked_chunk_lock, flags);
216
217         mempool_free(c, s->tracked_chunk_pool);
218 }
219
220 static int __chunk_is_tracked(struct dm_snapshot *s, chunk_t chunk)
221 {
222         struct dm_snap_tracked_chunk *c;
223         struct hlist_node *hn;
224         int found = 0;
225
226         spin_lock_irq(&s->tracked_chunk_lock);
227
228         hlist_for_each_entry(c, hn,
229             &s->tracked_chunk_hash[DM_TRACKED_CHUNK_HASH(chunk)], node) {
230                 if (c->chunk == chunk) {
231                         found = 1;
232                         break;
233                 }
234         }
235
236         spin_unlock_irq(&s->tracked_chunk_lock);
237
238         return found;
239 }
240
241 /*
242  * This conflicting I/O is extremely improbable in the caller,
243  * so msleep(1) is sufficient and there is no need for a wait queue.
244  */
245 static void __check_for_conflicting_io(struct dm_snapshot *s, chunk_t chunk)
246 {
247         while (__chunk_is_tracked(s, chunk))
248                 msleep(1);
249 }
250
251 /*
252  * One of these per registered origin, held in the snapshot_origins hash
253  */
254 struct origin {
255         /* The origin device */
256         struct block_device *bdev;
257
258         struct list_head hash_list;
259
260         /* List of snapshots for this origin */
261         struct list_head snapshots;
262 };
263
264 /*
265  * Size of the hash table for origin volumes. If we make this
266  * the size of the minors list then it should be nearly perfect
267  */
268 #define ORIGIN_HASH_SIZE 256
269 #define ORIGIN_MASK      0xFF
270 static struct list_head *_origins;
271 static struct rw_semaphore _origins_lock;
272
273 static int init_origin_hash(void)
274 {
275         int i;
276
277         _origins = kmalloc(ORIGIN_HASH_SIZE * sizeof(struct list_head),
278                            GFP_KERNEL);
279         if (!_origins) {
280                 DMERR("unable to allocate memory");
281                 return -ENOMEM;
282         }
283
284         for (i = 0; i < ORIGIN_HASH_SIZE; i++)
285                 INIT_LIST_HEAD(_origins + i);
286         init_rwsem(&_origins_lock);
287
288         return 0;
289 }
290
291 static void exit_origin_hash(void)
292 {
293         kfree(_origins);
294 }
295
296 static unsigned origin_hash(struct block_device *bdev)
297 {
298         return bdev->bd_dev & ORIGIN_MASK;
299 }
300
301 static struct origin *__lookup_origin(struct block_device *origin)
302 {
303         struct list_head *ol;
304         struct origin *o;
305
306         ol = &_origins[origin_hash(origin)];
307         list_for_each_entry (o, ol, hash_list)
308                 if (bdev_equal(o->bdev, origin))
309                         return o;
310
311         return NULL;
312 }
313
314 static void __insert_origin(struct origin *o)
315 {
316         struct list_head *sl = &_origins[origin_hash(o->bdev)];
317         list_add_tail(&o->hash_list, sl);
318 }
319
320 /*
321  * _origins_lock must be held when calling this function.
322  * Returns number of snapshots registered using the supplied cow device, plus:
323  * snap_src - a snapshot suitable for use as a source of exception handover
324  * snap_dest - a snapshot capable of receiving exception handover.
325  * snap_merge - an existing snapshot-merge target linked to the same origin.
326  *   There can be at most one snapshot-merge target. The parameter is optional.
327  *
328  * Possible return values and states of snap_src and snap_dest.
329  *   0: NULL, NULL  - first new snapshot
330  *   1: snap_src, NULL - normal snapshot
331  *   2: snap_src, snap_dest  - waiting for handover
332  *   2: snap_src, NULL - handed over, waiting for old to be deleted
333  *   1: NULL, snap_dest - source got destroyed without handover
334  */
335 static int __find_snapshots_sharing_cow(struct dm_snapshot *snap,
336                                         struct dm_snapshot **snap_src,
337                                         struct dm_snapshot **snap_dest,
338                                         struct dm_snapshot **snap_merge)
339 {
340         struct dm_snapshot *s;
341         struct origin *o;
342         int count = 0;
343         int active;
344
345         o = __lookup_origin(snap->origin->bdev);
346         if (!o)
347                 goto out;
348
349         list_for_each_entry(s, &o->snapshots, list) {
350                 if (dm_target_is_snapshot_merge(s->ti) && snap_merge)
351                         *snap_merge = s;
352                 if (!bdev_equal(s->cow->bdev, snap->cow->bdev))
353                         continue;
354
355                 down_read(&s->lock);
356                 active = s->active;
357                 up_read(&s->lock);
358
359                 if (active) {
360                         if (snap_src)
361                                 *snap_src = s;
362                 } else if (snap_dest)
363                         *snap_dest = s;
364
365                 count++;
366         }
367
368 out:
369         return count;
370 }
371
372 /*
373  * On success, returns 1 if this snapshot is a handover destination,
374  * otherwise returns 0.
375  */
376 static int __validate_exception_handover(struct dm_snapshot *snap)
377 {
378         struct dm_snapshot *snap_src = NULL, *snap_dest = NULL;
379         struct dm_snapshot *snap_merge = NULL;
380
381         /* Does snapshot need exceptions handed over to it? */
382         if ((__find_snapshots_sharing_cow(snap, &snap_src, &snap_dest,
383                                           &snap_merge) == 2) ||
384             snap_dest) {
385                 snap->ti->error = "Snapshot cow pairing for exception "
386                                   "table handover failed";
387                 return -EINVAL;
388         }
389
390         /*
391          * If no snap_src was found, snap cannot become a handover
392          * destination.
393          */
394         if (!snap_src)
395                 return 0;
396
397         /*
398          * Non-snapshot-merge handover?
399          */
400         if (!dm_target_is_snapshot_merge(snap->ti))
401                 return 1;
402
403         /*
404          * Do not allow more than one merging snapshot.
405          */
406         if (snap_merge) {
407                 snap->ti->error = "A snapshot is already merging.";
408                 return -EINVAL;
409         }
410
411         if (!snap_src->store->type->prepare_merge ||
412             !snap_src->store->type->commit_merge) {
413                 snap->ti->error = "Snapshot exception store does not "
414                                   "support snapshot-merge.";
415                 return -EINVAL;
416         }
417
418         return 1;
419 }
420
421 static void __insert_snapshot(struct origin *o, struct dm_snapshot *s)
422 {
423         struct dm_snapshot *l;
424
425         /* Sort the list according to chunk size, largest-first smallest-last */
426         list_for_each_entry(l, &o->snapshots, list)
427                 if (l->store->chunk_size < s->store->chunk_size)
428                         break;
429         list_add_tail(&s->list, &l->list);
430 }
431
432 /*
433  * Make a note of the snapshot and its origin so we can look it
434  * up when the origin has a write on it.
435  *
436  * Also validate snapshot exception store handovers.
437  * On success, returns 1 if this registration is a handover destination,
438  * otherwise returns 0.
439  */
440 static int register_snapshot(struct dm_snapshot *snap)
441 {
442         struct origin *o, *new_o = NULL;
443         struct block_device *bdev = snap->origin->bdev;
444         int r = 0;
445
446         new_o = kmalloc(sizeof(*new_o), GFP_KERNEL);
447         if (!new_o)
448                 return -ENOMEM;
449
450         down_write(&_origins_lock);
451
452         r = __validate_exception_handover(snap);
453         if (r < 0) {
454                 kfree(new_o);
455                 goto out;
456         }
457
458         o = __lookup_origin(bdev);
459         if (o)
460                 kfree(new_o);
461         else {
462                 /* New origin */
463                 o = new_o;
464
465                 /* Initialise the struct */
466                 INIT_LIST_HEAD(&o->snapshots);
467                 o->bdev = bdev;
468
469                 __insert_origin(o);
470         }
471
472         __insert_snapshot(o, snap);
473
474 out:
475         up_write(&_origins_lock);
476
477         return r;
478 }
479
480 /*
481  * Move snapshot to correct place in list according to chunk size.
482  */
483 static void reregister_snapshot(struct dm_snapshot *s)
484 {
485         struct block_device *bdev = s->origin->bdev;
486
487         down_write(&_origins_lock);
488
489         list_del(&s->list);
490         __insert_snapshot(__lookup_origin(bdev), s);
491
492         up_write(&_origins_lock);
493 }
494
495 static void unregister_snapshot(struct dm_snapshot *s)
496 {
497         struct origin *o;
498
499         down_write(&_origins_lock);
500         o = __lookup_origin(s->origin->bdev);
501
502         list_del(&s->list);
503         if (o && list_empty(&o->snapshots)) {
504                 list_del(&o->hash_list);
505                 kfree(o);
506         }
507
508         up_write(&_origins_lock);
509 }
510
511 /*
512  * Implementation of the exception hash tables.
513  * The lowest hash_shift bits of the chunk number are ignored, allowing
514  * some consecutive chunks to be grouped together.
515  */
516 static int dm_exception_table_init(struct dm_exception_table *et,
517                                    uint32_t size, unsigned hash_shift)
518 {
519         unsigned int i;
520
521         et->hash_shift = hash_shift;
522         et->hash_mask = size - 1;
523         et->table = dm_vcalloc(size, sizeof(struct list_head));
524         if (!et->table)
525                 return -ENOMEM;
526
527         for (i = 0; i < size; i++)
528                 INIT_LIST_HEAD(et->table + i);
529
530         return 0;
531 }
532
533 static void dm_exception_table_exit(struct dm_exception_table *et,
534                                     struct kmem_cache *mem)
535 {
536         struct list_head *slot;
537         struct dm_exception *ex, *next;
538         int i, size;
539
540         size = et->hash_mask + 1;
541         for (i = 0; i < size; i++) {
542                 slot = et->table + i;
543
544                 list_for_each_entry_safe (ex, next, slot, hash_list)
545                         kmem_cache_free(mem, ex);
546         }
547
548         vfree(et->table);
549 }
550
551 static uint32_t exception_hash(struct dm_exception_table *et, chunk_t chunk)
552 {
553         return (chunk >> et->hash_shift) & et->hash_mask;
554 }
555
556 static void dm_remove_exception(struct dm_exception *e)
557 {
558         list_del(&e->hash_list);
559 }
560
561 /*
562  * Return the exception data for a sector, or NULL if not
563  * remapped.
564  */
565 static struct dm_exception *dm_lookup_exception(struct dm_exception_table *et,
566                                                 chunk_t chunk)
567 {
568         struct list_head *slot;
569         struct dm_exception *e;
570
571         slot = &et->table[exception_hash(et, chunk)];
572         list_for_each_entry (e, slot, hash_list)
573                 if (chunk >= e->old_chunk &&
574                     chunk <= e->old_chunk + dm_consecutive_chunk_count(e))
575                         return e;
576
577         return NULL;
578 }
579
580 static struct dm_exception *alloc_completed_exception(void)
581 {
582         struct dm_exception *e;
583
584         e = kmem_cache_alloc(exception_cache, GFP_NOIO);
585         if (!e)
586                 e = kmem_cache_alloc(exception_cache, GFP_ATOMIC);
587
588         return e;
589 }
590
591 static void free_completed_exception(struct dm_exception *e)
592 {
593         kmem_cache_free(exception_cache, e);
594 }
595
596 static struct dm_snap_pending_exception *alloc_pending_exception(struct dm_snapshot *s)
597 {
598         struct dm_snap_pending_exception *pe = mempool_alloc(s->pending_pool,
599                                                              GFP_NOIO);
600
601         atomic_inc(&s->pending_exceptions_count);
602         pe->snap = s;
603
604         return pe;
605 }
606
607 static void free_pending_exception(struct dm_snap_pending_exception *pe)
608 {
609         struct dm_snapshot *s = pe->snap;
610
611         mempool_free(pe, s->pending_pool);
612         smp_mb__before_atomic_dec();
613         atomic_dec(&s->pending_exceptions_count);
614 }
615
616 static void dm_insert_exception(struct dm_exception_table *eh,
617                                 struct dm_exception *new_e)
618 {
619         struct list_head *l;
620         struct dm_exception *e = NULL;
621
622         l = &eh->table[exception_hash(eh, new_e->old_chunk)];
623
624         /* Add immediately if this table doesn't support consecutive chunks */
625         if (!eh->hash_shift)
626                 goto out;
627
628         /* List is ordered by old_chunk */
629         list_for_each_entry_reverse(e, l, hash_list) {
630                 /* Insert after an existing chunk? */
631                 if (new_e->old_chunk == (e->old_chunk +
632                                          dm_consecutive_chunk_count(e) + 1) &&
633                     new_e->new_chunk == (dm_chunk_number(e->new_chunk) +
634                                          dm_consecutive_chunk_count(e) + 1)) {
635                         dm_consecutive_chunk_count_inc(e);
636                         free_completed_exception(new_e);
637                         return;
638                 }
639
640                 /* Insert before an existing chunk? */
641                 if (new_e->old_chunk == (e->old_chunk - 1) &&
642                     new_e->new_chunk == (dm_chunk_number(e->new_chunk) - 1)) {
643                         dm_consecutive_chunk_count_inc(e);
644                         e->old_chunk--;
645                         e->new_chunk--;
646                         free_completed_exception(new_e);
647                         return;
648                 }
649
650                 if (new_e->old_chunk > e->old_chunk)
651                         break;
652         }
653
654 out:
655         list_add(&new_e->hash_list, e ? &e->hash_list : l);
656 }
657
658 /*
659  * Callback used by the exception stores to load exceptions when
660  * initialising.
661  */
662 static int dm_add_exception(void *context, chunk_t old, chunk_t new)
663 {
664         struct dm_snapshot *s = context;
665         struct dm_exception *e;
666
667         e = alloc_completed_exception();
668         if (!e)
669                 return -ENOMEM;
670
671         e->old_chunk = old;
672
673         /* Consecutive_count is implicitly initialised to zero */
674         e->new_chunk = new;
675
676         dm_insert_exception(&s->complete, e);
677
678         return 0;
679 }
680
681 #define min_not_zero(l, r) (((l) == 0) ? (r) : (((r) == 0) ? (l) : min(l, r)))
682
683 /*
684  * Return a minimum chunk size of all snapshots that have the specified origin.
685  * Return zero if the origin has no snapshots.
686  */
687 static sector_t __minimum_chunk_size(struct origin *o)
688 {
689         struct dm_snapshot *snap;
690         unsigned chunk_size = 0;
691
692         if (o)
693                 list_for_each_entry(snap, &o->snapshots, list)
694                         chunk_size = min_not_zero(chunk_size,
695                                                   snap->store->chunk_size);
696
697         return chunk_size;
698 }
699
700 /*
701  * Hard coded magic.
702  */
703 static int calc_max_buckets(void)
704 {
705         /* use a fixed size of 2MB */
706         unsigned long mem = 2 * 1024 * 1024;
707         mem /= sizeof(struct list_head);
708
709         return mem;
710 }
711
712 /*
713  * Allocate room for a suitable hash table.
714  */
715 static int init_hash_tables(struct dm_snapshot *s)
716 {
717         sector_t hash_size, cow_dev_size, origin_dev_size, max_buckets;
718
719         /*
720          * Calculate based on the size of the original volume or
721          * the COW volume...
722          */
723         cow_dev_size = get_dev_size(s->cow->bdev);
724         origin_dev_size = get_dev_size(s->origin->bdev);
725         max_buckets = calc_max_buckets();
726
727         hash_size = min(origin_dev_size, cow_dev_size) >> s->store->chunk_shift;
728         hash_size = min(hash_size, max_buckets);
729
730         if (hash_size < 64)
731                 hash_size = 64;
732         hash_size = rounddown_pow_of_two(hash_size);
733         if (dm_exception_table_init(&s->complete, hash_size,
734                                     DM_CHUNK_CONSECUTIVE_BITS))
735                 return -ENOMEM;
736
737         /*
738          * Allocate hash table for in-flight exceptions
739          * Make this smaller than the real hash table
740          */
741         hash_size >>= 3;
742         if (hash_size < 64)
743                 hash_size = 64;
744
745         if (dm_exception_table_init(&s->pending, hash_size, 0)) {
746                 dm_exception_table_exit(&s->complete, exception_cache);
747                 return -ENOMEM;
748         }
749
750         return 0;
751 }
752
753 static void merge_shutdown(struct dm_snapshot *s)
754 {
755         clear_bit_unlock(RUNNING_MERGE, &s->state_bits);
756         smp_mb__after_clear_bit();
757         wake_up_bit(&s->state_bits, RUNNING_MERGE);
758 }
759
760 static struct bio *__release_queued_bios_after_merge(struct dm_snapshot *s)
761 {
762         s->first_merging_chunk = 0;
763         s->num_merging_chunks = 0;
764
765         return bio_list_get(&s->bios_queued_during_merge);
766 }
767
768 /*
769  * Remove one chunk from the index of completed exceptions.
770  */
771 static int __remove_single_exception_chunk(struct dm_snapshot *s,
772                                            chunk_t old_chunk)
773 {
774         struct dm_exception *e;
775
776         e = dm_lookup_exception(&s->complete, old_chunk);
777         if (!e) {
778                 DMERR("Corruption detected: exception for block %llu is "
779                       "on disk but not in memory",
780                       (unsigned long long)old_chunk);
781                 return -EINVAL;
782         }
783
784         /*
785          * If this is the only chunk using this exception, remove exception.
786          */
787         if (!dm_consecutive_chunk_count(e)) {
788                 dm_remove_exception(e);
789                 free_completed_exception(e);
790                 return 0;
791         }
792
793         /*
794          * The chunk may be either at the beginning or the end of a
795          * group of consecutive chunks - never in the middle.  We are
796          * removing chunks in the opposite order to that in which they
797          * were added, so this should always be true.
798          * Decrement the consecutive chunk counter and adjust the
799          * starting point if necessary.
800          */
801         if (old_chunk == e->old_chunk) {
802                 e->old_chunk++;
803                 e->new_chunk++;
804         } else if (old_chunk != e->old_chunk +
805                    dm_consecutive_chunk_count(e)) {
806                 DMERR("Attempt to merge block %llu from the "
807                       "middle of a chunk range [%llu - %llu]",
808                       (unsigned long long)old_chunk,
809                       (unsigned long long)e->old_chunk,
810                       (unsigned long long)
811                       e->old_chunk + dm_consecutive_chunk_count(e));
812                 return -EINVAL;
813         }
814
815         dm_consecutive_chunk_count_dec(e);
816
817         return 0;
818 }
819
820 static void flush_bios(struct bio *bio);
821
822 static int remove_single_exception_chunk(struct dm_snapshot *s)
823 {
824         struct bio *b = NULL;
825         int r;
826         chunk_t old_chunk = s->first_merging_chunk + s->num_merging_chunks - 1;
827
828         down_write(&s->lock);
829
830         /*
831          * Process chunks (and associated exceptions) in reverse order
832          * so that dm_consecutive_chunk_count_dec() accounting works.
833          */
834         do {
835                 r = __remove_single_exception_chunk(s, old_chunk);
836                 if (r)
837                         goto out;
838         } while (old_chunk-- > s->first_merging_chunk);
839
840         b = __release_queued_bios_after_merge(s);
841
842 out:
843         up_write(&s->lock);
844         if (b)
845                 flush_bios(b);
846
847         return r;
848 }
849
850 static void merge_callback(int read_err, unsigned long write_err,
851                            void *context);
852
853 static void snapshot_merge_next_chunks(struct dm_snapshot *s)
854 {
855         int r;
856         chunk_t old_chunk, new_chunk;
857         struct dm_io_region src, dest;
858
859         BUG_ON(!test_bit(RUNNING_MERGE, &s->state_bits));
860         if (unlikely(test_bit(SHUTDOWN_MERGE, &s->state_bits)))
861                 goto shut;
862
863         /*
864          * valid flag never changes during merge, so no lock required.
865          */
866         if (!s->valid) {
867                 DMERR("Snapshot is invalid: can't merge");
868                 goto shut;
869         }
870
871         r = s->store->type->prepare_merge(s->store, &old_chunk, &new_chunk);
872         if (r <= 0) {
873                 if (r < 0)
874                         DMERR("Read error in exception store: "
875                               "shutting down merge");
876                 goto shut;
877         }
878
879         /* TODO: use larger I/O size once we verify that kcopyd handles it */
880
881         dest.bdev = s->origin->bdev;
882         dest.sector = chunk_to_sector(s->store, old_chunk);
883         dest.count = min((sector_t)s->store->chunk_size,
884                          get_dev_size(dest.bdev) - dest.sector);
885
886         src.bdev = s->cow->bdev;
887         src.sector = chunk_to_sector(s->store, new_chunk);
888         src.count = dest.count;
889
890         down_write(&s->lock);
891         s->first_merging_chunk = old_chunk;
892         s->num_merging_chunks = 1;
893         up_write(&s->lock);
894
895         /* !!! FIXME: wait until writes to this chunk drain */
896
897         dm_kcopyd_copy(s->kcopyd_client, &src, 1, &dest, 0, merge_callback, s);
898         return;
899
900 shut:
901         merge_shutdown(s);
902 }
903
904 static void error_bios(struct bio *bio);
905
906 static void merge_callback(int read_err, unsigned long write_err, void *context)
907 {
908         struct dm_snapshot *s = context;
909         struct bio *b = NULL;
910
911         if (read_err || write_err) {
912                 if (read_err)
913                         DMERR("Read error: shutting down merge.");
914                 else
915                         DMERR("Write error: shutting down merge.");
916                 goto shut;
917         }
918
919         if (s->store->type->commit_merge(s->store,
920                                          s->num_merging_chunks) < 0) {
921                 DMERR("Write error in exception store: shutting down merge");
922                 goto shut;
923         }
924
925         if (remove_single_exception_chunk(s) < 0)
926                 goto shut;
927
928         snapshot_merge_next_chunks(s);
929
930         return;
931
932 shut:
933         down_write(&s->lock);
934         b = __release_queued_bios_after_merge(s);
935         up_write(&s->lock);
936         error_bios(b);
937
938         merge_shutdown(s);
939 }
940
941 static void start_merge(struct dm_snapshot *s)
942 {
943         if (!test_and_set_bit(RUNNING_MERGE, &s->state_bits))
944                 snapshot_merge_next_chunks(s);
945 }
946
947 static int wait_schedule(void *ptr)
948 {
949         schedule();
950
951         return 0;
952 }
953
954 /*
955  * Stop the merging process and wait until it finishes.
956  */
957 static void stop_merge(struct dm_snapshot *s)
958 {
959         set_bit(SHUTDOWN_MERGE, &s->state_bits);
960         wait_on_bit(&s->state_bits, RUNNING_MERGE, wait_schedule,
961                     TASK_UNINTERRUPTIBLE);
962         clear_bit(SHUTDOWN_MERGE, &s->state_bits);
963 }
964
965 /*
966  * Construct a snapshot mapping: <origin_dev> <COW-dev> <p/n> <chunk-size>
967  */
968 static int snapshot_ctr(struct dm_target *ti, unsigned int argc, char **argv)
969 {
970         struct dm_snapshot *s;
971         int i;
972         int r = -EINVAL;
973         char *origin_path, *cow_path;
974         unsigned args_used, num_flush_requests = 1;
975         fmode_t origin_mode = FMODE_READ;
976
977         if (argc != 4) {
978                 ti->error = "requires exactly 4 arguments";
979                 r = -EINVAL;
980                 goto bad;
981         }
982
983         if (dm_target_is_snapshot_merge(ti)) {
984                 num_flush_requests = 2;
985                 origin_mode = FMODE_WRITE;
986         }
987
988         origin_path = argv[0];
989         argv++;
990         argc--;
991
992         s = kmalloc(sizeof(*s), GFP_KERNEL);
993         if (!s) {
994                 ti->error = "Cannot allocate snapshot context private "
995                     "structure";
996                 r = -ENOMEM;
997                 goto bad;
998         }
999
1000         cow_path = argv[0];
1001         argv++;
1002         argc--;
1003
1004         r = dm_get_device(ti, cow_path, 0, 0,
1005                           FMODE_READ | FMODE_WRITE, &s->cow);
1006         if (r) {
1007                 ti->error = "Cannot get COW device";
1008                 goto bad_cow;
1009         }
1010
1011         r = dm_exception_store_create(ti, argc, argv, s, &args_used, &s->store);
1012         if (r) {
1013                 ti->error = "Couldn't create exception store";
1014                 r = -EINVAL;
1015                 goto bad_store;
1016         }
1017
1018         argv += args_used;
1019         argc -= args_used;
1020
1021         r = dm_get_device(ti, origin_path, 0, ti->len, origin_mode, &s->origin);
1022         if (r) {
1023                 ti->error = "Cannot get origin device";
1024                 goto bad_origin;
1025         }
1026
1027         s->ti = ti;
1028         s->valid = 1;
1029         s->active = 0;
1030         s->suspended = 0;
1031         atomic_set(&s->pending_exceptions_count, 0);
1032         init_rwsem(&s->lock);
1033         INIT_LIST_HEAD(&s->list);
1034         spin_lock_init(&s->pe_lock);
1035         s->state_bits = 0;
1036         s->first_merging_chunk = 0;
1037         s->num_merging_chunks = 0;
1038         bio_list_init(&s->bios_queued_during_merge);
1039
1040         /* Allocate hash table for COW data */
1041         if (init_hash_tables(s)) {
1042                 ti->error = "Unable to allocate hash table space";
1043                 r = -ENOMEM;
1044                 goto bad_hash_tables;
1045         }
1046
1047         r = dm_kcopyd_client_create(SNAPSHOT_PAGES, &s->kcopyd_client);
1048         if (r) {
1049                 ti->error = "Could not create kcopyd client";
1050                 goto bad_kcopyd;
1051         }
1052
1053         s->pending_pool = mempool_create_slab_pool(MIN_IOS, pending_cache);
1054         if (!s->pending_pool) {
1055                 ti->error = "Could not allocate mempool for pending exceptions";
1056                 goto bad_pending_pool;
1057         }
1058
1059         s->tracked_chunk_pool = mempool_create_slab_pool(MIN_IOS,
1060                                                          tracked_chunk_cache);
1061         if (!s->tracked_chunk_pool) {
1062                 ti->error = "Could not allocate tracked_chunk mempool for "
1063                             "tracking reads";
1064                 goto bad_tracked_chunk_pool;
1065         }
1066
1067         for (i = 0; i < DM_TRACKED_CHUNK_HASH_SIZE; i++)
1068                 INIT_HLIST_HEAD(&s->tracked_chunk_hash[i]);
1069
1070         spin_lock_init(&s->tracked_chunk_lock);
1071
1072         bio_list_init(&s->queued_bios);
1073         INIT_WORK(&s->queued_bios_work, flush_queued_bios);
1074
1075         ti->private = s;
1076         ti->num_flush_requests = num_flush_requests;
1077
1078         /* Add snapshot to the list of snapshots for this origin */
1079         /* Exceptions aren't triggered till snapshot_resume() is called */
1080         r = register_snapshot(s);
1081         if (r == -ENOMEM) {
1082                 ti->error = "Snapshot origin struct allocation failed";
1083                 goto bad_load_and_register;
1084         } else if (r < 0) {
1085                 /* invalid handover, register_snapshot has set ti->error */
1086                 goto bad_load_and_register;
1087         }
1088
1089         /*
1090          * Metadata must only be loaded into one table at once, so skip this
1091          * if metadata will be handed over during resume.
1092          * Chunk size will be set during the handover - set it to zero to
1093          * ensure it's ignored.
1094          */
1095         if (r > 0) {
1096                 s->store->chunk_size = 0;
1097                 return 0;
1098         }
1099
1100         r = s->store->type->read_metadata(s->store, dm_add_exception,
1101                                           (void *)s);
1102         if (r < 0) {
1103                 ti->error = "Failed to read snapshot metadata";
1104                 goto bad_read_metadata;
1105         } else if (r > 0) {
1106                 s->valid = 0;
1107                 DMWARN("Snapshot is marked invalid.");
1108         }
1109
1110         if (!s->store->chunk_size) {
1111                 ti->error = "Chunk size not set";
1112                 goto bad_read_metadata;
1113         }
1114         ti->split_io = s->store->chunk_size;
1115
1116         return 0;
1117
1118 bad_read_metadata:
1119         unregister_snapshot(s);
1120
1121 bad_load_and_register:
1122         mempool_destroy(s->tracked_chunk_pool);
1123
1124 bad_tracked_chunk_pool:
1125         mempool_destroy(s->pending_pool);
1126
1127 bad_pending_pool:
1128         dm_kcopyd_client_destroy(s->kcopyd_client);
1129
1130 bad_kcopyd:
1131         dm_exception_table_exit(&s->pending, pending_cache);
1132         dm_exception_table_exit(&s->complete, exception_cache);
1133
1134 bad_hash_tables:
1135         dm_put_device(ti, s->origin);
1136
1137 bad_origin:
1138         dm_exception_store_destroy(s->store);
1139
1140 bad_store:
1141         dm_put_device(ti, s->cow);
1142
1143 bad_cow:
1144         kfree(s);
1145
1146 bad:
1147         return r;
1148 }
1149
1150 static void __free_exceptions(struct dm_snapshot *s)
1151 {
1152         dm_kcopyd_client_destroy(s->kcopyd_client);
1153         s->kcopyd_client = NULL;
1154
1155         dm_exception_table_exit(&s->pending, pending_cache);
1156         dm_exception_table_exit(&s->complete, exception_cache);
1157 }
1158
1159 static void __handover_exceptions(struct dm_snapshot *snap_src,
1160                                   struct dm_snapshot *snap_dest)
1161 {
1162         union {
1163                 struct dm_exception_table table_swap;
1164                 struct dm_exception_store *store_swap;
1165         } u;
1166
1167         /*
1168          * Swap all snapshot context information between the two instances.
1169          */
1170         u.table_swap = snap_dest->complete;
1171         snap_dest->complete = snap_src->complete;
1172         snap_src->complete = u.table_swap;
1173
1174         u.store_swap = snap_dest->store;
1175         snap_dest->store = snap_src->store;
1176         snap_src->store = u.store_swap;
1177
1178         snap_dest->store->snap = snap_dest;
1179         snap_src->store->snap = snap_src;
1180
1181         snap_dest->ti->split_io = snap_dest->store->chunk_size;
1182         snap_dest->valid = snap_src->valid;
1183
1184         /*
1185          * Set source invalid to ensure it receives no further I/O.
1186          */
1187         snap_src->valid = 0;
1188 }
1189
1190 static void snapshot_dtr(struct dm_target *ti)
1191 {
1192 #ifdef CONFIG_DM_DEBUG
1193         int i;
1194 #endif
1195         struct dm_snapshot *s = ti->private;
1196         struct dm_snapshot *snap_src = NULL, *snap_dest = NULL;
1197
1198         flush_workqueue(ksnapd);
1199
1200         down_read(&_origins_lock);
1201         /* Check whether exception handover must be cancelled */
1202         (void) __find_snapshots_sharing_cow(s, &snap_src, &snap_dest, NULL);
1203         if (snap_src && snap_dest && (s == snap_src)) {
1204                 down_write(&snap_dest->lock);
1205                 snap_dest->valid = 0;
1206                 up_write(&snap_dest->lock);
1207                 DMERR("Cancelling snapshot handover.");
1208         }
1209         up_read(&_origins_lock);
1210
1211         if (dm_target_is_snapshot_merge(ti))
1212                 stop_merge(s);
1213
1214         /* Prevent further origin writes from using this snapshot. */
1215         /* After this returns there can be no new kcopyd jobs. */
1216         unregister_snapshot(s);
1217
1218         while (atomic_read(&s->pending_exceptions_count))
1219                 msleep(1);
1220         /*
1221          * Ensure instructions in mempool_destroy aren't reordered
1222          * before atomic_read.
1223          */
1224         smp_mb();
1225
1226 #ifdef CONFIG_DM_DEBUG
1227         for (i = 0; i < DM_TRACKED_CHUNK_HASH_SIZE; i++)
1228                 BUG_ON(!hlist_empty(&s->tracked_chunk_hash[i]));
1229 #endif
1230
1231         mempool_destroy(s->tracked_chunk_pool);
1232
1233         __free_exceptions(s);
1234
1235         mempool_destroy(s->pending_pool);
1236
1237         dm_put_device(ti, s->origin);
1238
1239         dm_exception_store_destroy(s->store);
1240
1241         dm_put_device(ti, s->cow);
1242
1243         kfree(s);
1244 }
1245
1246 /*
1247  * Flush a list of buffers.
1248  */
1249 static void flush_bios(struct bio *bio)
1250 {
1251         struct bio *n;
1252
1253         while (bio) {
1254                 n = bio->bi_next;
1255                 bio->bi_next = NULL;
1256                 generic_make_request(bio);
1257                 bio = n;
1258         }
1259 }
1260
1261 static void flush_queued_bios(struct work_struct *work)
1262 {
1263         struct dm_snapshot *s =
1264                 container_of(work, struct dm_snapshot, queued_bios_work);
1265         struct bio *queued_bios;
1266         unsigned long flags;
1267
1268         spin_lock_irqsave(&s->pe_lock, flags);
1269         queued_bios = bio_list_get(&s->queued_bios);
1270         spin_unlock_irqrestore(&s->pe_lock, flags);
1271
1272         flush_bios(queued_bios);
1273 }
1274
1275 static int do_origin(struct dm_dev *origin, struct bio *bio);
1276
1277 /*
1278  * Flush a list of buffers.
1279  */
1280 static void retry_origin_bios(struct dm_snapshot *s, struct bio *bio)
1281 {
1282         struct bio *n;
1283         int r;
1284
1285         while (bio) {
1286                 n = bio->bi_next;
1287                 bio->bi_next = NULL;
1288                 r = do_origin(s->origin, bio);
1289                 if (r == DM_MAPIO_REMAPPED)
1290                         generic_make_request(bio);
1291                 bio = n;
1292         }
1293 }
1294
1295 /*
1296  * Error a list of buffers.
1297  */
1298 static void error_bios(struct bio *bio)
1299 {
1300         struct bio *n;
1301
1302         while (bio) {
1303                 n = bio->bi_next;
1304                 bio->bi_next = NULL;
1305                 bio_io_error(bio);
1306                 bio = n;
1307         }
1308 }
1309
1310 static void __invalidate_snapshot(struct dm_snapshot *s, int err)
1311 {
1312         if (!s->valid)
1313                 return;
1314
1315         if (err == -EIO)
1316                 DMERR("Invalidating snapshot: Error reading/writing.");
1317         else if (err == -ENOMEM)
1318                 DMERR("Invalidating snapshot: Unable to allocate exception.");
1319
1320         if (s->store->type->drop_snapshot)
1321                 s->store->type->drop_snapshot(s->store);
1322
1323         s->valid = 0;
1324
1325         dm_table_event(s->ti->table);
1326 }
1327
1328 static void pending_complete(struct dm_snap_pending_exception *pe, int success)
1329 {
1330         struct dm_exception *e;
1331         struct dm_snapshot *s = pe->snap;
1332         struct bio *origin_bios = NULL;
1333         struct bio *snapshot_bios = NULL;
1334         int error = 0;
1335
1336         if (!success) {
1337                 /* Read/write error - snapshot is unusable */
1338                 down_write(&s->lock);
1339                 __invalidate_snapshot(s, -EIO);
1340                 error = 1;
1341                 goto out;
1342         }
1343
1344         e = alloc_completed_exception();
1345         if (!e) {
1346                 down_write(&s->lock);
1347                 __invalidate_snapshot(s, -ENOMEM);
1348                 error = 1;
1349                 goto out;
1350         }
1351         *e = pe->e;
1352
1353         down_write(&s->lock);
1354         if (!s->valid) {
1355                 free_completed_exception(e);
1356                 error = 1;
1357                 goto out;
1358         }
1359
1360         /* Check for conflicting reads */
1361         __check_for_conflicting_io(s, pe->e.old_chunk);
1362
1363         /*
1364          * Add a proper exception, and remove the
1365          * in-flight exception from the list.
1366          */
1367         dm_insert_exception(&s->complete, e);
1368
1369  out:
1370         dm_remove_exception(&pe->e);
1371         snapshot_bios = bio_list_get(&pe->snapshot_bios);
1372         origin_bios = bio_list_get(&pe->origin_bios);
1373         free_pending_exception(pe);
1374
1375         up_write(&s->lock);
1376
1377         /* Submit any pending write bios */
1378         if (error)
1379                 error_bios(snapshot_bios);
1380         else
1381                 flush_bios(snapshot_bios);
1382
1383         retry_origin_bios(s, origin_bios);
1384 }
1385
1386 static void commit_callback(void *context, int success)
1387 {
1388         struct dm_snap_pending_exception *pe = context;
1389
1390         pending_complete(pe, success);
1391 }
1392
1393 /*
1394  * Called when the copy I/O has finished.  kcopyd actually runs
1395  * this code so don't block.
1396  */
1397 static void copy_callback(int read_err, unsigned long write_err, void *context)
1398 {
1399         struct dm_snap_pending_exception *pe = context;
1400         struct dm_snapshot *s = pe->snap;
1401
1402         if (read_err || write_err)
1403                 pending_complete(pe, 0);
1404
1405         else
1406                 /* Update the metadata if we are persistent */
1407                 s->store->type->commit_exception(s->store, &pe->e,
1408                                                  commit_callback, pe);
1409 }
1410
1411 /*
1412  * Dispatches the copy operation to kcopyd.
1413  */
1414 static void start_copy(struct dm_snap_pending_exception *pe)
1415 {
1416         struct dm_snapshot *s = pe->snap;
1417         struct dm_io_region src, dest;
1418         struct block_device *bdev = s->origin->bdev;
1419         sector_t dev_size;
1420
1421         dev_size = get_dev_size(bdev);
1422
1423         src.bdev = bdev;
1424         src.sector = chunk_to_sector(s->store, pe->e.old_chunk);
1425         src.count = min((sector_t)s->store->chunk_size, dev_size - src.sector);
1426
1427         dest.bdev = s->cow->bdev;
1428         dest.sector = chunk_to_sector(s->store, pe->e.new_chunk);
1429         dest.count = src.count;
1430
1431         /* Hand over to kcopyd */
1432         dm_kcopyd_copy(s->kcopyd_client,
1433                     &src, 1, &dest, 0, copy_callback, pe);
1434 }
1435
1436 static struct dm_snap_pending_exception *
1437 __lookup_pending_exception(struct dm_snapshot *s, chunk_t chunk)
1438 {
1439         struct dm_exception *e = dm_lookup_exception(&s->pending, chunk);
1440
1441         if (!e)
1442                 return NULL;
1443
1444         return container_of(e, struct dm_snap_pending_exception, e);
1445 }
1446
1447 /*
1448  * Looks to see if this snapshot already has a pending exception
1449  * for this chunk, otherwise it allocates a new one and inserts
1450  * it into the pending table.
1451  *
1452  * NOTE: a write lock must be held on snap->lock before calling
1453  * this.
1454  */
1455 static struct dm_snap_pending_exception *
1456 __find_pending_exception(struct dm_snapshot *s,
1457                          struct dm_snap_pending_exception *pe, chunk_t chunk)
1458 {
1459         struct dm_snap_pending_exception *pe2;
1460
1461         pe2 = __lookup_pending_exception(s, chunk);
1462         if (pe2) {
1463                 free_pending_exception(pe);
1464                 return pe2;
1465         }
1466
1467         pe->e.old_chunk = chunk;
1468         bio_list_init(&pe->origin_bios);
1469         bio_list_init(&pe->snapshot_bios);
1470         pe->started = 0;
1471
1472         if (s->store->type->prepare_exception(s->store, &pe->e)) {
1473                 free_pending_exception(pe);
1474                 return NULL;
1475         }
1476
1477         dm_insert_exception(&s->pending, &pe->e);
1478
1479         return pe;
1480 }
1481
1482 static void remap_exception(struct dm_snapshot *s, struct dm_exception *e,
1483                             struct bio *bio, chunk_t chunk)
1484 {
1485         bio->bi_bdev = s->cow->bdev;
1486         bio->bi_sector = chunk_to_sector(s->store,
1487                                          dm_chunk_number(e->new_chunk) +
1488                                          (chunk - e->old_chunk)) +
1489                                          (bio->bi_sector &
1490                                           s->store->chunk_mask);
1491 }
1492
1493 static int snapshot_map(struct dm_target *ti, struct bio *bio,
1494                         union map_info *map_context)
1495 {
1496         struct dm_exception *e;
1497         struct dm_snapshot *s = ti->private;
1498         int r = DM_MAPIO_REMAPPED;
1499         chunk_t chunk;
1500         struct dm_snap_pending_exception *pe = NULL;
1501
1502         if (unlikely(bio_empty_barrier(bio))) {
1503                 bio->bi_bdev = s->cow->bdev;
1504                 return DM_MAPIO_REMAPPED;
1505         }
1506
1507         chunk = sector_to_chunk(s->store, bio->bi_sector);
1508
1509         /* Full snapshots are not usable */
1510         /* To get here the table must be live so s->active is always set. */
1511         if (!s->valid)
1512                 return -EIO;
1513
1514         /* FIXME: should only take write lock if we need
1515          * to copy an exception */
1516         down_write(&s->lock);
1517
1518         if (!s->valid) {
1519                 r = -EIO;
1520                 goto out_unlock;
1521         }
1522
1523         /* If the block is already remapped - use that, else remap it */
1524         e = dm_lookup_exception(&s->complete, chunk);
1525         if (e) {
1526                 remap_exception(s, e, bio, chunk);
1527                 goto out_unlock;
1528         }
1529
1530         /*
1531          * Write to snapshot - higher level takes care of RW/RO
1532          * flags so we should only get this if we are
1533          * writeable.
1534          */
1535         if (bio_rw(bio) == WRITE) {
1536                 pe = __lookup_pending_exception(s, chunk);
1537                 if (!pe) {
1538                         up_write(&s->lock);
1539                         pe = alloc_pending_exception(s);
1540                         down_write(&s->lock);
1541
1542                         if (!s->valid) {
1543                                 free_pending_exception(pe);
1544                                 r = -EIO;
1545                                 goto out_unlock;
1546                         }
1547
1548                         e = dm_lookup_exception(&s->complete, chunk);
1549                         if (e) {
1550                                 free_pending_exception(pe);
1551                                 remap_exception(s, e, bio, chunk);
1552                                 goto out_unlock;
1553                         }
1554
1555                         pe = __find_pending_exception(s, pe, chunk);
1556                         if (!pe) {
1557                                 __invalidate_snapshot(s, -ENOMEM);
1558                                 r = -EIO;
1559                                 goto out_unlock;
1560                         }
1561                 }
1562
1563                 remap_exception(s, &pe->e, bio, chunk);
1564                 bio_list_add(&pe->snapshot_bios, bio);
1565
1566                 r = DM_MAPIO_SUBMITTED;
1567
1568                 if (!pe->started) {
1569                         /* this is protected by snap->lock */
1570                         pe->started = 1;
1571                         up_write(&s->lock);
1572                         start_copy(pe);
1573                         goto out;
1574                 }
1575         } else {
1576                 bio->bi_bdev = s->origin->bdev;
1577                 map_context->ptr = track_chunk(s, chunk);
1578         }
1579
1580  out_unlock:
1581         up_write(&s->lock);
1582  out:
1583         return r;
1584 }
1585
1586 /*
1587  * A snapshot-merge target behaves like a combination of a snapshot
1588  * target and a snapshot-origin target.  It only generates new
1589  * exceptions in other snapshots and not in the one that is being
1590  * merged.
1591  *
1592  * For each chunk, if there is an existing exception, it is used to
1593  * redirect I/O to the cow device.  Otherwise I/O is sent to the origin,
1594  * which in turn might generate exceptions in other snapshots.
1595  * If merging is currently taking place on the chunk in question, the
1596  * I/O is deferred by adding it to s->bios_queued_during_merge.
1597  */
1598 static int snapshot_merge_map(struct dm_target *ti, struct bio *bio,
1599                               union map_info *map_context)
1600 {
1601         struct dm_exception *e;
1602         struct dm_snapshot *s = ti->private;
1603         int r = DM_MAPIO_REMAPPED;
1604         chunk_t chunk;
1605
1606         if (unlikely(bio_empty_barrier(bio))) {
1607                 if (!map_context->flush_request)
1608                         bio->bi_bdev = s->origin->bdev;
1609                 else
1610                         bio->bi_bdev = s->cow->bdev;
1611                 map_context->ptr = NULL;
1612                 return DM_MAPIO_REMAPPED;
1613         }
1614
1615         chunk = sector_to_chunk(s->store, bio->bi_sector);
1616
1617         down_write(&s->lock);
1618
1619         /* Full snapshots are not usable */
1620         if (!s->valid) {
1621                 r = -EIO;
1622                 goto out_unlock;
1623         }
1624
1625         /* If the block is already remapped - use that */
1626         e = dm_lookup_exception(&s->complete, chunk);
1627         if (e) {
1628                 /* Queue writes overlapping with chunks being merged */
1629                 if (bio_rw(bio) == WRITE &&
1630                     chunk >= s->first_merging_chunk &&
1631                     chunk < (s->first_merging_chunk +
1632                              s->num_merging_chunks)) {
1633                         bio->bi_bdev = s->origin->bdev;
1634                         bio_list_add(&s->bios_queued_during_merge, bio);
1635                         r = DM_MAPIO_SUBMITTED;
1636                         goto out_unlock;
1637                 }
1638                 remap_exception(s, e, bio, chunk);
1639                 goto out_unlock;
1640         }
1641
1642         bio->bi_bdev = s->origin->bdev;
1643
1644         if (bio_rw(bio) == WRITE) {
1645                 up_write(&s->lock);
1646                 return do_origin(s->origin, bio);
1647         }
1648
1649 out_unlock:
1650         up_write(&s->lock);
1651
1652         return r;
1653 }
1654
1655 static int snapshot_end_io(struct dm_target *ti, struct bio *bio,
1656                            int error, union map_info *map_context)
1657 {
1658         struct dm_snapshot *s = ti->private;
1659         struct dm_snap_tracked_chunk *c = map_context->ptr;
1660
1661         if (c)
1662                 stop_tracking_chunk(s, c);
1663
1664         return 0;
1665 }
1666
1667 static void snapshot_merge_presuspend(struct dm_target *ti)
1668 {
1669         struct dm_snapshot *s = ti->private;
1670
1671         stop_merge(s);
1672 }
1673
1674 static void snapshot_postsuspend(struct dm_target *ti)
1675 {
1676         struct dm_snapshot *s = ti->private;
1677
1678         down_write(&s->lock);
1679         s->suspended = 1;
1680         up_write(&s->lock);
1681 }
1682
1683 static int snapshot_preresume(struct dm_target *ti)
1684 {
1685         int r = 0;
1686         struct dm_snapshot *s = ti->private;
1687         struct dm_snapshot *snap_src = NULL, *snap_dest = NULL;
1688
1689         down_read(&_origins_lock);
1690         (void) __find_snapshots_sharing_cow(s, &snap_src, &snap_dest, NULL);
1691         if (snap_src && snap_dest) {
1692                 down_read(&snap_src->lock);
1693                 if (s == snap_src) {
1694                         DMERR("Unable to resume snapshot source until "
1695                               "handover completes.");
1696                         r = -EINVAL;
1697                 } else if (!snap_src->suspended) {
1698                         DMERR("Unable to perform snapshot handover until "
1699                               "source is suspended.");
1700                         r = -EINVAL;
1701                 }
1702                 up_read(&snap_src->lock);
1703         }
1704         up_read(&_origins_lock);
1705
1706         return r;
1707 }
1708
1709 static void snapshot_resume(struct dm_target *ti)
1710 {
1711         struct dm_snapshot *s = ti->private;
1712         struct dm_snapshot *snap_src = NULL, *snap_dest = NULL;
1713
1714         down_read(&_origins_lock);
1715         (void) __find_snapshots_sharing_cow(s, &snap_src, &snap_dest, NULL);
1716         if (snap_src && snap_dest) {
1717                 down_write(&snap_src->lock);
1718                 down_write_nested(&snap_dest->lock, SINGLE_DEPTH_NESTING);
1719                 __handover_exceptions(snap_src, snap_dest);
1720                 up_write(&snap_dest->lock);
1721                 up_write(&snap_src->lock);
1722         }
1723         up_read(&_origins_lock);
1724
1725         /* Now we have correct chunk size, reregister */
1726         reregister_snapshot(s);
1727
1728         down_write(&s->lock);
1729         s->active = 1;
1730         s->suspended = 0;
1731         up_write(&s->lock);
1732 }
1733
1734 static sector_t get_origin_minimum_chunksize(struct block_device *bdev)
1735 {
1736         sector_t min_chunksize;
1737
1738         down_read(&_origins_lock);
1739         min_chunksize = __minimum_chunk_size(__lookup_origin(bdev));
1740         up_read(&_origins_lock);
1741
1742         return min_chunksize;
1743 }
1744
1745 static void snapshot_merge_resume(struct dm_target *ti)
1746 {
1747         struct dm_snapshot *s = ti->private;
1748
1749         /*
1750          * Handover exceptions from existing snapshot.
1751          */
1752         snapshot_resume(ti);
1753
1754         /*
1755          * snapshot-merge acts as an origin, so set ti->split_io
1756          */
1757         ti->split_io = get_origin_minimum_chunksize(s->origin->bdev);
1758
1759         start_merge(s);
1760 }
1761
1762 static int snapshot_status(struct dm_target *ti, status_type_t type,
1763                            char *result, unsigned int maxlen)
1764 {
1765         unsigned sz = 0;
1766         struct dm_snapshot *snap = ti->private;
1767
1768         switch (type) {
1769         case STATUSTYPE_INFO:
1770
1771                 down_write(&snap->lock);
1772
1773                 if (!snap->valid)
1774                         DMEMIT("Invalid");
1775                 else {
1776                         if (snap->store->type->usage) {
1777                                 sector_t total_sectors, sectors_allocated,
1778                                          metadata_sectors;
1779                                 snap->store->type->usage(snap->store,
1780                                                          &total_sectors,
1781                                                          &sectors_allocated,
1782                                                          &metadata_sectors);
1783                                 DMEMIT("%llu/%llu %llu",
1784                                        (unsigned long long)sectors_allocated,
1785                                        (unsigned long long)total_sectors,
1786                                        (unsigned long long)metadata_sectors);
1787                         }
1788                         else
1789                                 DMEMIT("Unknown");
1790                 }
1791
1792                 up_write(&snap->lock);
1793
1794                 break;
1795
1796         case STATUSTYPE_TABLE:
1797                 /*
1798                  * kdevname returns a static pointer so we need
1799                  * to make private copies if the output is to
1800                  * make sense.
1801                  */
1802                 DMEMIT("%s %s", snap->origin->name, snap->cow->name);
1803                 snap->store->type->status(snap->store, type, result + sz,
1804                                           maxlen - sz);
1805                 break;
1806         }
1807
1808         return 0;
1809 }
1810
1811 static int snapshot_iterate_devices(struct dm_target *ti,
1812                                     iterate_devices_callout_fn fn, void *data)
1813 {
1814         struct dm_snapshot *snap = ti->private;
1815
1816         return fn(ti, snap->origin, 0, ti->len, data);
1817 }
1818
1819
1820 /*-----------------------------------------------------------------
1821  * Origin methods
1822  *---------------------------------------------------------------*/
1823
1824 /*
1825  * If no exceptions need creating, DM_MAPIO_REMAPPED is returned and any
1826  * supplied bio was ignored.  The caller may submit it immediately.
1827  * (No remapping actually occurs as the origin is always a direct linear
1828  * map.)
1829  *
1830  * If further exceptions are required, DM_MAPIO_SUBMITTED is returned
1831  * and any supplied bio is added to a list to be submitted once all
1832  * the necessary exceptions exist.
1833  */
1834 static int __origin_write(struct list_head *snapshots, sector_t sector,
1835                           struct bio *bio)
1836 {
1837         int r = DM_MAPIO_REMAPPED;
1838         struct dm_snapshot *snap;
1839         struct dm_exception *e;
1840         struct dm_snap_pending_exception *pe;
1841         struct dm_snap_pending_exception *pe_to_start_now = NULL;
1842         struct dm_snap_pending_exception *pe_to_start_last = NULL;
1843         chunk_t chunk;
1844
1845         /* Do all the snapshots on this origin */
1846         list_for_each_entry (snap, snapshots, list) {
1847                 /*
1848                  * Don't make new exceptions in a merging snapshot
1849                  * because it has effectively been deleted
1850                  */
1851                 if (dm_target_is_snapshot_merge(snap->ti))
1852                         continue;
1853
1854                 down_write(&snap->lock);
1855
1856                 /* Only deal with valid and active snapshots */
1857                 if (!snap->valid || !snap->active)
1858                         goto next_snapshot;
1859
1860                 /* Nothing to do if writing beyond end of snapshot */
1861                 if (sector >= dm_table_get_size(snap->ti->table))
1862                         goto next_snapshot;
1863
1864                 /*
1865                  * Remember, different snapshots can have
1866                  * different chunk sizes.
1867                  */
1868                 chunk = sector_to_chunk(snap->store, sector);
1869
1870                 /*
1871                  * Check exception table to see if block
1872                  * is already remapped in this snapshot
1873                  * and trigger an exception if not.
1874                  */
1875                 e = dm_lookup_exception(&snap->complete, chunk);
1876                 if (e)
1877                         goto next_snapshot;
1878
1879                 pe = __lookup_pending_exception(snap, chunk);
1880                 if (!pe) {
1881                         up_write(&snap->lock);
1882                         pe = alloc_pending_exception(snap);
1883                         down_write(&snap->lock);
1884
1885                         if (!snap->valid) {
1886                                 free_pending_exception(pe);
1887                                 goto next_snapshot;
1888                         }
1889
1890                         e = dm_lookup_exception(&snap->complete, chunk);
1891                         if (e) {
1892                                 free_pending_exception(pe);
1893                                 goto next_snapshot;
1894                         }
1895
1896                         pe = __find_pending_exception(snap, pe, chunk);
1897                         if (!pe) {
1898                                 __invalidate_snapshot(snap, -ENOMEM);
1899                                 goto next_snapshot;
1900                         }
1901                 }
1902
1903                 r = DM_MAPIO_SUBMITTED;
1904
1905                 /*
1906                  * If an origin bio was supplied, queue it to wait for the
1907                  * completion of this exception, and start this one last,
1908                  * at the end of the function.
1909                  */
1910                 if (bio) {
1911                         bio_list_add(&pe->origin_bios, bio);
1912                         bio = NULL;
1913
1914                         if (!pe->started) {
1915                                 pe->started = 1;
1916                                 pe_to_start_last = pe;
1917                         }
1918                 }
1919
1920                 if (!pe->started) {
1921                         pe->started = 1;
1922                         pe_to_start_now = pe;
1923                 }
1924
1925  next_snapshot:
1926                 up_write(&snap->lock);
1927
1928                 if (pe_to_start_now) {
1929                         start_copy(pe_to_start_now);
1930                         pe_to_start_now = NULL;
1931                 }
1932         }
1933
1934         /*
1935          * Submit the exception against which the bio is queued last,
1936          * to give the other exceptions a head start.
1937          */
1938         if (pe_to_start_last)
1939                 start_copy(pe_to_start_last);
1940
1941         return r;
1942 }
1943
1944 /*
1945  * Called on a write from the origin driver.
1946  */
1947 static int do_origin(struct dm_dev *origin, struct bio *bio)
1948 {
1949         struct origin *o;
1950         int r = DM_MAPIO_REMAPPED;
1951
1952         down_read(&_origins_lock);
1953         o = __lookup_origin(origin->bdev);
1954         if (o)
1955                 r = __origin_write(&o->snapshots, bio->bi_sector, bio);
1956         up_read(&_origins_lock);
1957
1958         return r;
1959 }
1960
1961 /*
1962  * Origin: maps a linear range of a device, with hooks for snapshotting.
1963  */
1964
1965 /*
1966  * Construct an origin mapping: <dev_path>
1967  * The context for an origin is merely a 'struct dm_dev *'
1968  * pointing to the real device.
1969  */
1970 static int origin_ctr(struct dm_target *ti, unsigned int argc, char **argv)
1971 {
1972         int r;
1973         struct dm_dev *dev;
1974
1975         if (argc != 1) {
1976                 ti->error = "origin: incorrect number of arguments";
1977                 return -EINVAL;
1978         }
1979
1980         r = dm_get_device(ti, argv[0], 0, ti->len,
1981                           dm_table_get_mode(ti->table), &dev);
1982         if (r) {
1983                 ti->error = "Cannot get target device";
1984                 return r;
1985         }
1986
1987         ti->private = dev;
1988         ti->num_flush_requests = 1;
1989
1990         return 0;
1991 }
1992
1993 static void origin_dtr(struct dm_target *ti)
1994 {
1995         struct dm_dev *dev = ti->private;
1996         dm_put_device(ti, dev);
1997 }
1998
1999 static int origin_map(struct dm_target *ti, struct bio *bio,
2000                       union map_info *map_context)
2001 {
2002         struct dm_dev *dev = ti->private;
2003         bio->bi_bdev = dev->bdev;
2004
2005         if (unlikely(bio_empty_barrier(bio)))
2006                 return DM_MAPIO_REMAPPED;
2007
2008         /* Only tell snapshots if this is a write */
2009         return (bio_rw(bio) == WRITE) ? do_origin(dev, bio) : DM_MAPIO_REMAPPED;
2010 }
2011
2012 /*
2013  * Set the target "split_io" field to the minimum of all the snapshots'
2014  * chunk sizes.
2015  */
2016 static void origin_resume(struct dm_target *ti)
2017 {
2018         struct dm_dev *dev = ti->private;
2019
2020         ti->split_io = get_origin_minimum_chunksize(dev->bdev);
2021 }
2022
2023 static int origin_status(struct dm_target *ti, status_type_t type, char *result,
2024                          unsigned int maxlen)
2025 {
2026         struct dm_dev *dev = ti->private;
2027
2028         switch (type) {
2029         case STATUSTYPE_INFO:
2030                 result[0] = '\0';
2031                 break;
2032
2033         case STATUSTYPE_TABLE:
2034                 snprintf(result, maxlen, "%s", dev->name);
2035                 break;
2036         }
2037
2038         return 0;
2039 }
2040
2041 static int origin_iterate_devices(struct dm_target *ti,
2042                                   iterate_devices_callout_fn fn, void *data)
2043 {
2044         struct dm_dev *dev = ti->private;
2045
2046         return fn(ti, dev, 0, ti->len, data);
2047 }
2048
2049 static struct target_type origin_target = {
2050         .name    = "snapshot-origin",
2051         .version = {1, 7, 0},
2052         .module  = THIS_MODULE,
2053         .ctr     = origin_ctr,
2054         .dtr     = origin_dtr,
2055         .map     = origin_map,
2056         .resume  = origin_resume,
2057         .status  = origin_status,
2058         .iterate_devices = origin_iterate_devices,
2059 };
2060
2061 static struct target_type snapshot_target = {
2062         .name    = "snapshot",
2063         .version = {1, 9, 0},
2064         .module  = THIS_MODULE,
2065         .ctr     = snapshot_ctr,
2066         .dtr     = snapshot_dtr,
2067         .map     = snapshot_map,
2068         .end_io  = snapshot_end_io,
2069         .postsuspend = snapshot_postsuspend,
2070         .preresume  = snapshot_preresume,
2071         .resume  = snapshot_resume,
2072         .status  = snapshot_status,
2073         .iterate_devices = snapshot_iterate_devices,
2074 };
2075
2076 static struct target_type merge_target = {
2077         .name    = dm_snapshot_merge_target_name,
2078         .version = {1, 0, 0},
2079         .module  = THIS_MODULE,
2080         .ctr     = snapshot_ctr,
2081         .dtr     = snapshot_dtr,
2082         .map     = snapshot_merge_map,
2083         .end_io  = snapshot_end_io,
2084         .presuspend = snapshot_merge_presuspend,
2085         .postsuspend = snapshot_postsuspend,
2086         .preresume  = snapshot_preresume,
2087         .resume  = snapshot_merge_resume,
2088         .status  = snapshot_status,
2089         .iterate_devices = snapshot_iterate_devices,
2090 };
2091
2092 static int __init dm_snapshot_init(void)
2093 {
2094         int r;
2095
2096         r = dm_exception_store_init();
2097         if (r) {
2098                 DMERR("Failed to initialize exception stores");
2099                 return r;
2100         }
2101
2102         r = dm_register_target(&snapshot_target);
2103         if (r < 0) {
2104                 DMERR("snapshot target register failed %d", r);
2105                 goto bad_register_snapshot_target;
2106         }
2107
2108         r = dm_register_target(&origin_target);
2109         if (r < 0) {
2110                 DMERR("Origin target register failed %d", r);
2111                 goto bad_register_origin_target;
2112         }
2113
2114         r = dm_register_target(&merge_target);
2115         if (r < 0) {
2116                 DMERR("Merge target register failed %d", r);
2117                 goto bad_register_merge_target;
2118         }
2119
2120         r = init_origin_hash();
2121         if (r) {
2122                 DMERR("init_origin_hash failed.");
2123                 goto bad_origin_hash;
2124         }
2125
2126         exception_cache = KMEM_CACHE(dm_exception, 0);
2127         if (!exception_cache) {
2128                 DMERR("Couldn't create exception cache.");
2129                 r = -ENOMEM;
2130                 goto bad_exception_cache;
2131         }
2132
2133         pending_cache = KMEM_CACHE(dm_snap_pending_exception, 0);
2134         if (!pending_cache) {
2135                 DMERR("Couldn't create pending cache.");
2136                 r = -ENOMEM;
2137                 goto bad_pending_cache;
2138         }
2139
2140         tracked_chunk_cache = KMEM_CACHE(dm_snap_tracked_chunk, 0);
2141         if (!tracked_chunk_cache) {
2142                 DMERR("Couldn't create cache to track chunks in use.");
2143                 r = -ENOMEM;
2144                 goto bad_tracked_chunk_cache;
2145         }
2146
2147         ksnapd = create_singlethread_workqueue("ksnapd");
2148         if (!ksnapd) {
2149                 DMERR("Failed to create ksnapd workqueue.");
2150                 r = -ENOMEM;
2151                 goto bad_pending_pool;
2152         }
2153
2154         return 0;
2155
2156 bad_pending_pool:
2157         kmem_cache_destroy(tracked_chunk_cache);
2158 bad_tracked_chunk_cache:
2159         kmem_cache_destroy(pending_cache);
2160 bad_pending_cache:
2161         kmem_cache_destroy(exception_cache);
2162 bad_exception_cache:
2163         exit_origin_hash();
2164 bad_origin_hash:
2165         dm_unregister_target(&merge_target);
2166 bad_register_merge_target:
2167         dm_unregister_target(&origin_target);
2168 bad_register_origin_target:
2169         dm_unregister_target(&snapshot_target);
2170 bad_register_snapshot_target:
2171         dm_exception_store_exit();
2172
2173         return r;
2174 }
2175
2176 static void __exit dm_snapshot_exit(void)
2177 {
2178         destroy_workqueue(ksnapd);
2179
2180         dm_unregister_target(&snapshot_target);
2181         dm_unregister_target(&origin_target);
2182         dm_unregister_target(&merge_target);
2183
2184         exit_origin_hash();
2185         kmem_cache_destroy(pending_cache);
2186         kmem_cache_destroy(exception_cache);
2187         kmem_cache_destroy(tracked_chunk_cache);
2188
2189         dm_exception_store_exit();
2190 }
2191
2192 /* Module hooks */
2193 module_init(dm_snapshot_init);
2194 module_exit(dm_snapshot_exit);
2195
2196 MODULE_DESCRIPTION(DM_NAME " snapshot target");
2197 MODULE_AUTHOR("Joe Thornber");
2198 MODULE_LICENSE("GPL");