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