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