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