]> pilppa.org Git - linux-2.6-omap-h63xx.git/blob - drivers/md/dm-snap.c
[PATCH] dm: remove SECTOR_FORMAT
[linux-2.6-omap-h63xx.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/config.h>
11 #include <linux/ctype.h>
12 #include <linux/device-mapper.h>
13 #include <linux/fs.h>
14 #include <linux/init.h>
15 #include <linux/kdev_t.h>
16 #include <linux/list.h>
17 #include <linux/mempool.h>
18 #include <linux/module.h>
19 #include <linux/slab.h>
20 #include <linux/vmalloc.h>
21
22 #include "dm-snap.h"
23 #include "dm-bio-list.h"
24 #include "kcopyd.h"
25
26 /*
27  * The percentage increment we will wake up users at
28  */
29 #define WAKE_UP_PERCENT 5
30
31 /*
32  * kcopyd priority of snapshot operations
33  */
34 #define SNAPSHOT_COPY_PRIORITY 2
35
36 /*
37  * Each snapshot reserves this many pages for io
38  */
39 #define SNAPSHOT_PAGES 256
40
41 struct pending_exception {
42         struct exception e;
43
44         /*
45          * Origin buffers waiting for this to complete are held
46          * in a bio list
47          */
48         struct bio_list origin_bios;
49         struct bio_list snapshot_bios;
50
51         /*
52          * Short-term queue of pending exceptions prior to submission.
53          */
54         struct list_head list;
55
56         /*
57          * The primary pending_exception is the one that holds
58          * the sibling_count and the list of origin_bios for a
59          * group of pending_exceptions.  It is always last to get freed.
60          * These fields get set up when writing to the origin.
61          */
62         struct pending_exception *primary_pe;
63
64         /*
65          * Number of pending_exceptions processing this chunk.
66          * When this drops to zero we must complete the origin bios.
67          * If incrementing or decrementing this, hold pe->snap->lock for
68          * the sibling concerned and not pe->primary_pe->snap->lock unless
69          * they are the same.
70          */
71         atomic_t sibling_count;
72
73         /* Pointer back to snapshot context */
74         struct dm_snapshot *snap;
75
76         /*
77          * 1 indicates the exception has already been sent to
78          * kcopyd.
79          */
80         int started;
81 };
82
83 /*
84  * Hash table mapping origin volumes to lists of snapshots and
85  * a lock to protect it
86  */
87 static kmem_cache_t *exception_cache;
88 static kmem_cache_t *pending_cache;
89 static mempool_t *pending_pool;
90
91 /*
92  * One of these per registered origin, held in the snapshot_origins hash
93  */
94 struct origin {
95         /* The origin device */
96         struct block_device *bdev;
97
98         struct list_head hash_list;
99
100         /* List of snapshots for this origin */
101         struct list_head snapshots;
102 };
103
104 /*
105  * Size of the hash table for origin volumes. If we make this
106  * the size of the minors list then it should be nearly perfect
107  */
108 #define ORIGIN_HASH_SIZE 256
109 #define ORIGIN_MASK      0xFF
110 static struct list_head *_origins;
111 static struct rw_semaphore _origins_lock;
112
113 static int init_origin_hash(void)
114 {
115         int i;
116
117         _origins = kmalloc(ORIGIN_HASH_SIZE * sizeof(struct list_head),
118                            GFP_KERNEL);
119         if (!_origins) {
120                 DMERR("Device mapper: Snapshot: unable to allocate memory");
121                 return -ENOMEM;
122         }
123
124         for (i = 0; i < ORIGIN_HASH_SIZE; i++)
125                 INIT_LIST_HEAD(_origins + i);
126         init_rwsem(&_origins_lock);
127
128         return 0;
129 }
130
131 static void exit_origin_hash(void)
132 {
133         kfree(_origins);
134 }
135
136 static inline unsigned int origin_hash(struct block_device *bdev)
137 {
138         return bdev->bd_dev & ORIGIN_MASK;
139 }
140
141 static struct origin *__lookup_origin(struct block_device *origin)
142 {
143         struct list_head *ol;
144         struct origin *o;
145
146         ol = &_origins[origin_hash(origin)];
147         list_for_each_entry (o, ol, hash_list)
148                 if (bdev_equal(o->bdev, origin))
149                         return o;
150
151         return NULL;
152 }
153
154 static void __insert_origin(struct origin *o)
155 {
156         struct list_head *sl = &_origins[origin_hash(o->bdev)];
157         list_add_tail(&o->hash_list, sl);
158 }
159
160 /*
161  * Make a note of the snapshot and its origin so we can look it
162  * up when the origin has a write on it.
163  */
164 static int register_snapshot(struct dm_snapshot *snap)
165 {
166         struct origin *o;
167         struct block_device *bdev = snap->origin->bdev;
168
169         down_write(&_origins_lock);
170         o = __lookup_origin(bdev);
171
172         if (!o) {
173                 /* New origin */
174                 o = kmalloc(sizeof(*o), GFP_KERNEL);
175                 if (!o) {
176                         up_write(&_origins_lock);
177                         return -ENOMEM;
178                 }
179
180                 /* Initialise the struct */
181                 INIT_LIST_HEAD(&o->snapshots);
182                 o->bdev = bdev;
183
184                 __insert_origin(o);
185         }
186
187         list_add_tail(&snap->list, &o->snapshots);
188
189         up_write(&_origins_lock);
190         return 0;
191 }
192
193 static void unregister_snapshot(struct dm_snapshot *s)
194 {
195         struct origin *o;
196
197         down_write(&_origins_lock);
198         o = __lookup_origin(s->origin->bdev);
199
200         list_del(&s->list);
201         if (list_empty(&o->snapshots)) {
202                 list_del(&o->hash_list);
203                 kfree(o);
204         }
205
206         up_write(&_origins_lock);
207 }
208
209 /*
210  * Implementation of the exception hash tables.
211  */
212 static int init_exception_table(struct exception_table *et, uint32_t size)
213 {
214         unsigned int i;
215
216         et->hash_mask = size - 1;
217         et->table = dm_vcalloc(size, sizeof(struct list_head));
218         if (!et->table)
219                 return -ENOMEM;
220
221         for (i = 0; i < size; i++)
222                 INIT_LIST_HEAD(et->table + i);
223
224         return 0;
225 }
226
227 static void exit_exception_table(struct exception_table *et, kmem_cache_t *mem)
228 {
229         struct list_head *slot;
230         struct exception *ex, *next;
231         int i, size;
232
233         size = et->hash_mask + 1;
234         for (i = 0; i < size; i++) {
235                 slot = et->table + i;
236
237                 list_for_each_entry_safe (ex, next, slot, hash_list)
238                         kmem_cache_free(mem, ex);
239         }
240
241         vfree(et->table);
242 }
243
244 static inline uint32_t exception_hash(struct exception_table *et, chunk_t chunk)
245 {
246         return chunk & et->hash_mask;
247 }
248
249 static void insert_exception(struct exception_table *eh, struct exception *e)
250 {
251         struct list_head *l = &eh->table[exception_hash(eh, e->old_chunk)];
252         list_add(&e->hash_list, l);
253 }
254
255 static inline void remove_exception(struct exception *e)
256 {
257         list_del(&e->hash_list);
258 }
259
260 /*
261  * Return the exception data for a sector, or NULL if not
262  * remapped.
263  */
264 static struct exception *lookup_exception(struct exception_table *et,
265                                           chunk_t chunk)
266 {
267         struct list_head *slot;
268         struct exception *e;
269
270         slot = &et->table[exception_hash(et, chunk)];
271         list_for_each_entry (e, slot, hash_list)
272                 if (e->old_chunk == chunk)
273                         return e;
274
275         return NULL;
276 }
277
278 static inline struct exception *alloc_exception(void)
279 {
280         struct exception *e;
281
282         e = kmem_cache_alloc(exception_cache, GFP_NOIO);
283         if (!e)
284                 e = kmem_cache_alloc(exception_cache, GFP_ATOMIC);
285
286         return e;
287 }
288
289 static inline void free_exception(struct exception *e)
290 {
291         kmem_cache_free(exception_cache, e);
292 }
293
294 static inline struct pending_exception *alloc_pending_exception(void)
295 {
296         return mempool_alloc(pending_pool, GFP_NOIO);
297 }
298
299 static inline void free_pending_exception(struct pending_exception *pe)
300 {
301         mempool_free(pe, pending_pool);
302 }
303
304 int dm_add_exception(struct dm_snapshot *s, chunk_t old, chunk_t new)
305 {
306         struct exception *e;
307
308         e = alloc_exception();
309         if (!e)
310                 return -ENOMEM;
311
312         e->old_chunk = old;
313         e->new_chunk = new;
314         insert_exception(&s->complete, e);
315         return 0;
316 }
317
318 /*
319  * Hard coded magic.
320  */
321 static int calc_max_buckets(void)
322 {
323         /* use a fixed size of 2MB */
324         unsigned long mem = 2 * 1024 * 1024;
325         mem /= sizeof(struct list_head);
326
327         return mem;
328 }
329
330 /*
331  * Rounds a number down to a power of 2.
332  */
333 static inline uint32_t round_down(uint32_t n)
334 {
335         while (n & (n - 1))
336                 n &= (n - 1);
337         return n;
338 }
339
340 /*
341  * Allocate room for a suitable hash table.
342  */
343 static int init_hash_tables(struct dm_snapshot *s)
344 {
345         sector_t hash_size, cow_dev_size, origin_dev_size, max_buckets;
346
347         /*
348          * Calculate based on the size of the original volume or
349          * the COW volume...
350          */
351         cow_dev_size = get_dev_size(s->cow->bdev);
352         origin_dev_size = get_dev_size(s->origin->bdev);
353         max_buckets = calc_max_buckets();
354
355         hash_size = min(origin_dev_size, cow_dev_size) >> s->chunk_shift;
356         hash_size = min(hash_size, max_buckets);
357
358         /* Round it down to a power of 2 */
359         hash_size = round_down(hash_size);
360         if (init_exception_table(&s->complete, hash_size))
361                 return -ENOMEM;
362
363         /*
364          * Allocate hash table for in-flight exceptions
365          * Make this smaller than the real hash table
366          */
367         hash_size >>= 3;
368         if (hash_size < 64)
369                 hash_size = 64;
370
371         if (init_exception_table(&s->pending, hash_size)) {
372                 exit_exception_table(&s->complete, exception_cache);
373                 return -ENOMEM;
374         }
375
376         return 0;
377 }
378
379 /*
380  * Round a number up to the nearest 'size' boundary.  size must
381  * be a power of 2.
382  */
383 static inline ulong round_up(ulong n, ulong size)
384 {
385         size--;
386         return (n + size) & ~size;
387 }
388
389 static void read_snapshot_metadata(struct dm_snapshot *s)
390 {
391         if (s->store.read_metadata(&s->store)) {
392                 down_write(&s->lock);
393                 s->valid = 0;
394                 up_write(&s->lock);
395
396                 dm_table_event(s->table);
397         }
398 }
399
400 /*
401  * Construct a snapshot mapping: <origin_dev> <COW-dev> <p/n> <chunk-size>
402  */
403 static int snapshot_ctr(struct dm_target *ti, unsigned int argc, char **argv)
404 {
405         struct dm_snapshot *s;
406         unsigned long chunk_size;
407         int r = -EINVAL;
408         char persistent;
409         char *origin_path;
410         char *cow_path;
411         char *value;
412         int blocksize;
413
414         if (argc < 4) {
415                 ti->error = "dm-snapshot: requires exactly 4 arguments";
416                 r = -EINVAL;
417                 goto bad1;
418         }
419
420         origin_path = argv[0];
421         cow_path = argv[1];
422         persistent = toupper(*argv[2]);
423
424         if (persistent != 'P' && persistent != 'N') {
425                 ti->error = "Persistent flag is not P or N";
426                 r = -EINVAL;
427                 goto bad1;
428         }
429
430         chunk_size = simple_strtoul(argv[3], &value, 10);
431         if (chunk_size == 0 || value == NULL) {
432                 ti->error = "Invalid chunk size";
433                 r = -EINVAL;
434                 goto bad1;
435         }
436
437         s = kmalloc(sizeof(*s), GFP_KERNEL);
438         if (s == NULL) {
439                 ti->error = "Cannot allocate snapshot context private "
440                     "structure";
441                 r = -ENOMEM;
442                 goto bad1;
443         }
444
445         r = dm_get_device(ti, origin_path, 0, ti->len, FMODE_READ, &s->origin);
446         if (r) {
447                 ti->error = "Cannot get origin device";
448                 goto bad2;
449         }
450
451         r = dm_get_device(ti, cow_path, 0, 0,
452                           FMODE_READ | FMODE_WRITE, &s->cow);
453         if (r) {
454                 dm_put_device(ti, s->origin);
455                 ti->error = "Cannot get COW device";
456                 goto bad2;
457         }
458
459         /*
460          * Chunk size must be multiple of page size.  Silently
461          * round up if it's not.
462          */
463         chunk_size = round_up(chunk_size, PAGE_SIZE >> 9);
464
465         /* Validate the chunk size against the device block size */
466         blocksize = s->cow->bdev->bd_disk->queue->hardsect_size;
467         if (chunk_size % (blocksize >> 9)) {
468                 ti->error = "Chunk size is not a multiple of device blocksize";
469                 r = -EINVAL;
470                 goto bad3;
471         }
472
473         /* Check chunk_size is a power of 2 */
474         if (chunk_size & (chunk_size - 1)) {
475                 ti->error = "Chunk size is not a power of 2";
476                 r = -EINVAL;
477                 goto bad3;
478         }
479
480         s->chunk_size = chunk_size;
481         s->chunk_mask = chunk_size - 1;
482         s->type = persistent;
483         s->chunk_shift = ffs(chunk_size) - 1;
484
485         s->valid = 1;
486         s->active = 0;
487         s->last_percent = 0;
488         init_rwsem(&s->lock);
489         s->table = ti->table;
490
491         /* Allocate hash table for COW data */
492         if (init_hash_tables(s)) {
493                 ti->error = "Unable to allocate hash table space";
494                 r = -ENOMEM;
495                 goto bad3;
496         }
497
498         /*
499          * Check the persistent flag - done here because we need the iobuf
500          * to check the LV header
501          */
502         s->store.snap = s;
503
504         if (persistent == 'P')
505                 r = dm_create_persistent(&s->store, chunk_size);
506         else
507                 r = dm_create_transient(&s->store, s, blocksize);
508
509         if (r) {
510                 ti->error = "Couldn't create exception store";
511                 r = -EINVAL;
512                 goto bad4;
513         }
514
515         r = kcopyd_client_create(SNAPSHOT_PAGES, &s->kcopyd_client);
516         if (r) {
517                 ti->error = "Could not create kcopyd client";
518                 goto bad5;
519         }
520
521         /* Metadata must only be loaded into one table at once */
522         read_snapshot_metadata(s);
523
524         /* Add snapshot to the list of snapshots for this origin */
525         /* Exceptions aren't triggered till snapshot_resume() is called */
526         if (register_snapshot(s)) {
527                 r = -EINVAL;
528                 ti->error = "Cannot register snapshot origin";
529                 goto bad6;
530         }
531
532         ti->private = s;
533         ti->split_io = chunk_size;
534
535         return 0;
536
537  bad6:
538         kcopyd_client_destroy(s->kcopyd_client);
539
540  bad5:
541         s->store.destroy(&s->store);
542
543  bad4:
544         exit_exception_table(&s->pending, pending_cache);
545         exit_exception_table(&s->complete, exception_cache);
546
547  bad3:
548         dm_put_device(ti, s->cow);
549         dm_put_device(ti, s->origin);
550
551  bad2:
552         kfree(s);
553
554  bad1:
555         return r;
556 }
557
558 static void snapshot_dtr(struct dm_target *ti)
559 {
560         struct dm_snapshot *s = (struct dm_snapshot *) ti->private;
561
562         unregister_snapshot(s);
563
564         exit_exception_table(&s->pending, pending_cache);
565         exit_exception_table(&s->complete, exception_cache);
566
567         /* Deallocate memory used */
568         s->store.destroy(&s->store);
569
570         dm_put_device(ti, s->origin);
571         dm_put_device(ti, s->cow);
572         kcopyd_client_destroy(s->kcopyd_client);
573         kfree(s);
574 }
575
576 /*
577  * Flush a list of buffers.
578  */
579 static void flush_bios(struct bio *bio)
580 {
581         struct bio *n;
582
583         while (bio) {
584                 n = bio->bi_next;
585                 bio->bi_next = NULL;
586                 generic_make_request(bio);
587                 bio = n;
588         }
589 }
590
591 /*
592  * Error a list of buffers.
593  */
594 static void error_bios(struct bio *bio)
595 {
596         struct bio *n;
597
598         while (bio) {
599                 n = bio->bi_next;
600                 bio->bi_next = NULL;
601                 bio_io_error(bio, bio->bi_size);
602                 bio = n;
603         }
604 }
605
606 static inline void error_snapshot_bios(struct pending_exception *pe)
607 {
608         error_bios(bio_list_get(&pe->snapshot_bios));
609 }
610
611 static struct bio *__flush_bios(struct pending_exception *pe)
612 {
613         /*
614          * If this pe is involved in a write to the origin and
615          * it is the last sibling to complete then release
616          * the bios for the original write to the origin.
617          */
618
619         if (pe->primary_pe &&
620             atomic_dec_and_test(&pe->primary_pe->sibling_count))
621                 return bio_list_get(&pe->primary_pe->origin_bios);
622
623         return NULL;
624 }
625
626 static void __invalidate_snapshot(struct dm_snapshot *s,
627                                 struct pending_exception *pe, int err)
628 {
629         if (!s->valid)
630                 return;
631
632         if (err == -EIO)
633                 DMERR("Invalidating snapshot: Error reading/writing.");
634         else if (err == -ENOMEM)
635                 DMERR("Invalidating snapshot: Unable to allocate exception.");
636
637         if (pe)
638                 remove_exception(&pe->e);
639
640         if (s->store.drop_snapshot)
641                 s->store.drop_snapshot(&s->store);
642
643         s->valid = 0;
644
645         dm_table_event(s->table);
646 }
647
648 static void pending_complete(struct pending_exception *pe, int success)
649 {
650         struct exception *e;
651         struct pending_exception *primary_pe;
652         struct dm_snapshot *s = pe->snap;
653         struct bio *flush = NULL;
654
655         if (!success) {
656                 /* Read/write error - snapshot is unusable */
657                 down_write(&s->lock);
658                 __invalidate_snapshot(s, pe, -EIO);
659                 flush = __flush_bios(pe);
660                 up_write(&s->lock);
661
662                 error_snapshot_bios(pe);
663                 goto out;
664         }
665
666         e = alloc_exception();
667         if (!e) {
668                 down_write(&s->lock);
669                 __invalidate_snapshot(s, pe, -ENOMEM);
670                 flush = __flush_bios(pe);
671                 up_write(&s->lock);
672
673                 error_snapshot_bios(pe);
674                 goto out;
675         }
676         *e = pe->e;
677
678         /*
679          * Add a proper exception, and remove the
680          * in-flight exception from the list.
681          */
682         down_write(&s->lock);
683         if (!s->valid) {
684                 flush = __flush_bios(pe);
685                 up_write(&s->lock);
686
687                 free_exception(e);
688
689                 error_snapshot_bios(pe);
690                 goto out;
691         }
692
693         insert_exception(&s->complete, e);
694         remove_exception(&pe->e);
695         flush = __flush_bios(pe);
696
697         up_write(&s->lock);
698
699         /* Submit any pending write bios */
700         flush_bios(bio_list_get(&pe->snapshot_bios));
701
702  out:
703         primary_pe = pe->primary_pe;
704
705         /*
706          * Free the pe if it's not linked to an origin write or if
707          * it's not itself a primary pe.
708          */
709         if (!primary_pe || primary_pe != pe)
710                 free_pending_exception(pe);
711
712         /*
713          * Free the primary pe if nothing references it.
714          */
715         if (primary_pe && !atomic_read(&primary_pe->sibling_count))
716                 free_pending_exception(primary_pe);
717
718         if (flush)
719                 flush_bios(flush);
720 }
721
722 static void commit_callback(void *context, int success)
723 {
724         struct pending_exception *pe = (struct pending_exception *) context;
725         pending_complete(pe, success);
726 }
727
728 /*
729  * Called when the copy I/O has finished.  kcopyd actually runs
730  * this code so don't block.
731  */
732 static void copy_callback(int read_err, unsigned int write_err, void *context)
733 {
734         struct pending_exception *pe = (struct pending_exception *) context;
735         struct dm_snapshot *s = pe->snap;
736
737         if (read_err || write_err)
738                 pending_complete(pe, 0);
739
740         else
741                 /* Update the metadata if we are persistent */
742                 s->store.commit_exception(&s->store, &pe->e, commit_callback,
743                                           pe);
744 }
745
746 /*
747  * Dispatches the copy operation to kcopyd.
748  */
749 static void start_copy(struct pending_exception *pe)
750 {
751         struct dm_snapshot *s = pe->snap;
752         struct io_region src, dest;
753         struct block_device *bdev = s->origin->bdev;
754         sector_t dev_size;
755
756         dev_size = get_dev_size(bdev);
757
758         src.bdev = bdev;
759         src.sector = chunk_to_sector(s, pe->e.old_chunk);
760         src.count = min(s->chunk_size, dev_size - src.sector);
761
762         dest.bdev = s->cow->bdev;
763         dest.sector = chunk_to_sector(s, pe->e.new_chunk);
764         dest.count = src.count;
765
766         /* Hand over to kcopyd */
767         kcopyd_copy(s->kcopyd_client,
768                     &src, 1, &dest, 0, copy_callback, pe);
769 }
770
771 /*
772  * Looks to see if this snapshot already has a pending exception
773  * for this chunk, otherwise it allocates a new one and inserts
774  * it into the pending table.
775  *
776  * NOTE: a write lock must be held on snap->lock before calling
777  * this.
778  */
779 static struct pending_exception *
780 __find_pending_exception(struct dm_snapshot *s, struct bio *bio)
781 {
782         struct exception *e;
783         struct pending_exception *pe;
784         chunk_t chunk = sector_to_chunk(s, bio->bi_sector);
785
786         /*
787          * Is there a pending exception for this already ?
788          */
789         e = lookup_exception(&s->pending, chunk);
790         if (e) {
791                 /* cast the exception to a pending exception */
792                 pe = container_of(e, struct pending_exception, e);
793                 goto out;
794         }
795
796         /*
797          * Create a new pending exception, we don't want
798          * to hold the lock while we do this.
799          */
800         up_write(&s->lock);
801         pe = alloc_pending_exception();
802         down_write(&s->lock);
803
804         if (!s->valid) {
805                 free_pending_exception(pe);
806                 return NULL;
807         }
808
809         e = lookup_exception(&s->pending, chunk);
810         if (e) {
811                 free_pending_exception(pe);
812                 pe = container_of(e, struct pending_exception, e);
813                 goto out;
814         }
815
816         pe->e.old_chunk = chunk;
817         bio_list_init(&pe->origin_bios);
818         bio_list_init(&pe->snapshot_bios);
819         pe->primary_pe = NULL;
820         atomic_set(&pe->sibling_count, 1);
821         pe->snap = s;
822         pe->started = 0;
823
824         if (s->store.prepare_exception(&s->store, &pe->e)) {
825                 free_pending_exception(pe);
826                 return NULL;
827         }
828
829         insert_exception(&s->pending, &pe->e);
830
831  out:
832         return pe;
833 }
834
835 static inline void remap_exception(struct dm_snapshot *s, struct exception *e,
836                                    struct bio *bio)
837 {
838         bio->bi_bdev = s->cow->bdev;
839         bio->bi_sector = chunk_to_sector(s, e->new_chunk) +
840                 (bio->bi_sector & s->chunk_mask);
841 }
842
843 static int snapshot_map(struct dm_target *ti, struct bio *bio,
844                         union map_info *map_context)
845 {
846         struct exception *e;
847         struct dm_snapshot *s = (struct dm_snapshot *) ti->private;
848         int copy_needed = 0;
849         int r = 1;
850         chunk_t chunk;
851         struct pending_exception *pe = NULL;
852
853         chunk = sector_to_chunk(s, bio->bi_sector);
854
855         /* Full snapshots are not usable */
856         /* To get here the table must be live so s->active is always set. */
857         if (!s->valid)
858                 return -EIO;
859
860         if (unlikely(bio_barrier(bio)))
861                 return -EOPNOTSUPP;
862
863         /*
864          * Write to snapshot - higher level takes care of RW/RO
865          * flags so we should only get this if we are
866          * writeable.
867          */
868         if (bio_rw(bio) == WRITE) {
869
870                 /* FIXME: should only take write lock if we need
871                  * to copy an exception */
872                 down_write(&s->lock);
873
874                 if (!s->valid) {
875                         r = -EIO;
876                         goto out_unlock;
877                 }
878
879                 /* If the block is already remapped - use that, else remap it */
880                 e = lookup_exception(&s->complete, chunk);
881                 if (e) {
882                         remap_exception(s, e, bio);
883                         goto out_unlock;
884                 }
885
886                 pe = __find_pending_exception(s, bio);
887                 if (!pe) {
888                         __invalidate_snapshot(s, pe, -ENOMEM);
889                         r = -EIO;
890                         goto out_unlock;
891                 }
892
893                 remap_exception(s, &pe->e, bio);
894                 bio_list_add(&pe->snapshot_bios, bio);
895
896                 if (!pe->started) {
897                         /* this is protected by snap->lock */
898                         pe->started = 1;
899                         copy_needed = 1;
900                 }
901
902                 r = 0;
903
904  out_unlock:
905                 up_write(&s->lock);
906
907                 if (copy_needed)
908                         start_copy(pe);
909         } else {
910                 /*
911                  * FIXME: this read path scares me because we
912                  * always use the origin when we have a pending
913                  * exception.  However I can't think of a
914                  * situation where this is wrong - ejt.
915                  */
916
917                 /* Do reads */
918                 down_read(&s->lock);
919
920                 if (!s->valid) {
921                         up_read(&s->lock);
922                         return -EIO;
923                 }
924
925                 /* See if it it has been remapped */
926                 e = lookup_exception(&s->complete, chunk);
927                 if (e)
928                         remap_exception(s, e, bio);
929                 else
930                         bio->bi_bdev = s->origin->bdev;
931
932                 up_read(&s->lock);
933         }
934
935         return r;
936 }
937
938 static void snapshot_resume(struct dm_target *ti)
939 {
940         struct dm_snapshot *s = (struct dm_snapshot *) ti->private;
941
942         down_write(&s->lock);
943         s->active = 1;
944         up_write(&s->lock);
945 }
946
947 static int snapshot_status(struct dm_target *ti, status_type_t type,
948                            char *result, unsigned int maxlen)
949 {
950         struct dm_snapshot *snap = (struct dm_snapshot *) ti->private;
951
952         switch (type) {
953         case STATUSTYPE_INFO:
954                 if (!snap->valid)
955                         snprintf(result, maxlen, "Invalid");
956                 else {
957                         if (snap->store.fraction_full) {
958                                 sector_t numerator, denominator;
959                                 snap->store.fraction_full(&snap->store,
960                                                           &numerator,
961                                                           &denominator);
962                                 snprintf(result, maxlen, "%llu/%llu",
963                                         (unsigned long long)numerator,
964                                         (unsigned long long)denominator);
965                         }
966                         else
967                                 snprintf(result, maxlen, "Unknown");
968                 }
969                 break;
970
971         case STATUSTYPE_TABLE:
972                 /*
973                  * kdevname returns a static pointer so we need
974                  * to make private copies if the output is to
975                  * make sense.
976                  */
977                 snprintf(result, maxlen, "%s %s %c %llu",
978                          snap->origin->name, snap->cow->name,
979                          snap->type,
980                          (unsigned long long)snap->chunk_size);
981                 break;
982         }
983
984         return 0;
985 }
986
987 /*-----------------------------------------------------------------
988  * Origin methods
989  *---------------------------------------------------------------*/
990 static int __origin_write(struct list_head *snapshots, struct bio *bio)
991 {
992         int r = 1, first = 0;
993         struct dm_snapshot *snap;
994         struct exception *e;
995         struct pending_exception *pe, *next_pe, *primary_pe = NULL;
996         chunk_t chunk;
997         LIST_HEAD(pe_queue);
998
999         /* Do all the snapshots on this origin */
1000         list_for_each_entry (snap, snapshots, list) {
1001
1002                 down_write(&snap->lock);
1003
1004                 /* Only deal with valid and active snapshots */
1005                 if (!snap->valid || !snap->active)
1006                         goto next_snapshot;
1007
1008                 /* Nothing to do if writing beyond end of snapshot */
1009                 if (bio->bi_sector >= dm_table_get_size(snap->table))
1010                         goto next_snapshot;
1011
1012                 /*
1013                  * Remember, different snapshots can have
1014                  * different chunk sizes.
1015                  */
1016                 chunk = sector_to_chunk(snap, bio->bi_sector);
1017
1018                 /*
1019                  * Check exception table to see if block
1020                  * is already remapped in this snapshot
1021                  * and trigger an exception if not.
1022                  *
1023                  * sibling_count is initialised to 1 so pending_complete()
1024                  * won't destroy the primary_pe while we're inside this loop.
1025                  */
1026                 e = lookup_exception(&snap->complete, chunk);
1027                 if (e)
1028                         goto next_snapshot;
1029
1030                 pe = __find_pending_exception(snap, bio);
1031                 if (!pe) {
1032                         __invalidate_snapshot(snap, pe, ENOMEM);
1033                         goto next_snapshot;
1034                 }
1035
1036                 if (!primary_pe) {
1037                         /*
1038                          * Either every pe here has same
1039                          * primary_pe or none has one yet.
1040                          */
1041                         if (pe->primary_pe)
1042                                 primary_pe = pe->primary_pe;
1043                         else {
1044                                 primary_pe = pe;
1045                                 first = 1;
1046                         }
1047
1048                         bio_list_add(&primary_pe->origin_bios, bio);
1049
1050                         r = 0;
1051                 }
1052
1053                 if (!pe->primary_pe) {
1054                         atomic_inc(&primary_pe->sibling_count);
1055                         pe->primary_pe = primary_pe;
1056                 }
1057
1058                 if (!pe->started) {
1059                         pe->started = 1;
1060                         list_add_tail(&pe->list, &pe_queue);
1061                 }
1062
1063  next_snapshot:
1064                 up_write(&snap->lock);
1065         }
1066
1067         if (!primary_pe)
1068                 goto out;
1069
1070         /*
1071          * If this is the first time we're processing this chunk and
1072          * sibling_count is now 1 it means all the pending exceptions
1073          * got completed while we were in the loop above, so it falls to
1074          * us here to remove the primary_pe and submit any origin_bios.
1075          */
1076
1077         if (first && atomic_dec_and_test(&primary_pe->sibling_count)) {
1078                 flush_bios(bio_list_get(&primary_pe->origin_bios));
1079                 free_pending_exception(primary_pe);
1080                 /* If we got here, pe_queue is necessarily empty. */
1081                 goto out;
1082         }
1083
1084         /*
1085          * Now that we have a complete pe list we can start the copying.
1086          */
1087         list_for_each_entry_safe(pe, next_pe, &pe_queue, list)
1088                 start_copy(pe);
1089
1090  out:
1091         return r;
1092 }
1093
1094 /*
1095  * Called on a write from the origin driver.
1096  */
1097 static int do_origin(struct dm_dev *origin, struct bio *bio)
1098 {
1099         struct origin *o;
1100         int r = 1;
1101
1102         down_read(&_origins_lock);
1103         o = __lookup_origin(origin->bdev);
1104         if (o)
1105                 r = __origin_write(&o->snapshots, bio);
1106         up_read(&_origins_lock);
1107
1108         return r;
1109 }
1110
1111 /*
1112  * Origin: maps a linear range of a device, with hooks for snapshotting.
1113  */
1114
1115 /*
1116  * Construct an origin mapping: <dev_path>
1117  * The context for an origin is merely a 'struct dm_dev *'
1118  * pointing to the real device.
1119  */
1120 static int origin_ctr(struct dm_target *ti, unsigned int argc, char **argv)
1121 {
1122         int r;
1123         struct dm_dev *dev;
1124
1125         if (argc != 1) {
1126                 ti->error = "dm-origin: incorrect number of arguments";
1127                 return -EINVAL;
1128         }
1129
1130         r = dm_get_device(ti, argv[0], 0, ti->len,
1131                           dm_table_get_mode(ti->table), &dev);
1132         if (r) {
1133                 ti->error = "Cannot get target device";
1134                 return r;
1135         }
1136
1137         ti->private = dev;
1138         return 0;
1139 }
1140
1141 static void origin_dtr(struct dm_target *ti)
1142 {
1143         struct dm_dev *dev = (struct dm_dev *) ti->private;
1144         dm_put_device(ti, dev);
1145 }
1146
1147 static int origin_map(struct dm_target *ti, struct bio *bio,
1148                       union map_info *map_context)
1149 {
1150         struct dm_dev *dev = (struct dm_dev *) ti->private;
1151         bio->bi_bdev = dev->bdev;
1152
1153         if (unlikely(bio_barrier(bio)))
1154                 return -EOPNOTSUPP;
1155
1156         /* Only tell snapshots if this is a write */
1157         return (bio_rw(bio) == WRITE) ? do_origin(dev, bio) : 1;
1158 }
1159
1160 #define min_not_zero(l, r) (l == 0) ? r : ((r == 0) ? l : min(l, r))
1161
1162 /*
1163  * Set the target "split_io" field to the minimum of all the snapshots'
1164  * chunk sizes.
1165  */
1166 static void origin_resume(struct dm_target *ti)
1167 {
1168         struct dm_dev *dev = (struct dm_dev *) ti->private;
1169         struct dm_snapshot *snap;
1170         struct origin *o;
1171         chunk_t chunk_size = 0;
1172
1173         down_read(&_origins_lock);
1174         o = __lookup_origin(dev->bdev);
1175         if (o)
1176                 list_for_each_entry (snap, &o->snapshots, list)
1177                         chunk_size = min_not_zero(chunk_size, snap->chunk_size);
1178         up_read(&_origins_lock);
1179
1180         ti->split_io = chunk_size;
1181 }
1182
1183 static int origin_status(struct dm_target *ti, status_type_t type, char *result,
1184                          unsigned int maxlen)
1185 {
1186         struct dm_dev *dev = (struct dm_dev *) ti->private;
1187
1188         switch (type) {
1189         case STATUSTYPE_INFO:
1190                 result[0] = '\0';
1191                 break;
1192
1193         case STATUSTYPE_TABLE:
1194                 snprintf(result, maxlen, "%s", dev->name);
1195                 break;
1196         }
1197
1198         return 0;
1199 }
1200
1201 static struct target_type origin_target = {
1202         .name    = "snapshot-origin",
1203         .version = {1, 1, 0},
1204         .module  = THIS_MODULE,
1205         .ctr     = origin_ctr,
1206         .dtr     = origin_dtr,
1207         .map     = origin_map,
1208         .resume  = origin_resume,
1209         .status  = origin_status,
1210 };
1211
1212 static struct target_type snapshot_target = {
1213         .name    = "snapshot",
1214         .version = {1, 1, 0},
1215         .module  = THIS_MODULE,
1216         .ctr     = snapshot_ctr,
1217         .dtr     = snapshot_dtr,
1218         .map     = snapshot_map,
1219         .resume  = snapshot_resume,
1220         .status  = snapshot_status,
1221 };
1222
1223 static int __init dm_snapshot_init(void)
1224 {
1225         int r;
1226
1227         r = dm_register_target(&snapshot_target);
1228         if (r) {
1229                 DMERR("snapshot target register failed %d", r);
1230                 return r;
1231         }
1232
1233         r = dm_register_target(&origin_target);
1234         if (r < 0) {
1235                 DMERR("Device mapper: Origin: register failed %d\n", r);
1236                 goto bad1;
1237         }
1238
1239         r = init_origin_hash();
1240         if (r) {
1241                 DMERR("init_origin_hash failed.");
1242                 goto bad2;
1243         }
1244
1245         exception_cache = kmem_cache_create("dm-snapshot-ex",
1246                                             sizeof(struct exception),
1247                                             __alignof__(struct exception),
1248                                             0, NULL, NULL);
1249         if (!exception_cache) {
1250                 DMERR("Couldn't create exception cache.");
1251                 r = -ENOMEM;
1252                 goto bad3;
1253         }
1254
1255         pending_cache =
1256             kmem_cache_create("dm-snapshot-in",
1257                               sizeof(struct pending_exception),
1258                               __alignof__(struct pending_exception),
1259                               0, NULL, NULL);
1260         if (!pending_cache) {
1261                 DMERR("Couldn't create pending cache.");
1262                 r = -ENOMEM;
1263                 goto bad4;
1264         }
1265
1266         pending_pool = mempool_create_slab_pool(128, pending_cache);
1267         if (!pending_pool) {
1268                 DMERR("Couldn't create pending pool.");
1269                 r = -ENOMEM;
1270                 goto bad5;
1271         }
1272
1273         return 0;
1274
1275       bad5:
1276         kmem_cache_destroy(pending_cache);
1277       bad4:
1278         kmem_cache_destroy(exception_cache);
1279       bad3:
1280         exit_origin_hash();
1281       bad2:
1282         dm_unregister_target(&origin_target);
1283       bad1:
1284         dm_unregister_target(&snapshot_target);
1285         return r;
1286 }
1287
1288 static void __exit dm_snapshot_exit(void)
1289 {
1290         int r;
1291
1292         r = dm_unregister_target(&snapshot_target);
1293         if (r)
1294                 DMERR("snapshot unregister failed %d", r);
1295
1296         r = dm_unregister_target(&origin_target);
1297         if (r)
1298                 DMERR("origin unregister failed %d", r);
1299
1300         exit_origin_hash();
1301         mempool_destroy(pending_pool);
1302         kmem_cache_destroy(pending_cache);
1303         kmem_cache_destroy(exception_cache);
1304 }
1305
1306 /* Module hooks */
1307 module_init(dm_snapshot_init);
1308 module_exit(dm_snapshot_exit);
1309
1310 MODULE_DESCRIPTION(DM_NAME " snapshot target");
1311 MODULE_AUTHOR("Joe Thornber");
1312 MODULE_LICENSE("GPL");