dm raid1: remove bio_endio from dm_rh_mark_nosync
[safe/jmp/linux-2.6] / drivers / md / dm-raid1.c
1 /*
2  * Copyright (C) 2003 Sistina Software Limited.
3  * Copyright (C) 2005-2008 Red Hat, Inc. All rights reserved.
4  *
5  * This file is released under the GPL.
6  */
7
8 #include "dm-bio-record.h"
9
10 #include <linux/init.h>
11 #include <linux/mempool.h>
12 #include <linux/module.h>
13 #include <linux/pagemap.h>
14 #include <linux/slab.h>
15 #include <linux/workqueue.h>
16 #include <linux/device-mapper.h>
17 #include <linux/dm-io.h>
18 #include <linux/dm-dirty-log.h>
19 #include <linux/dm-kcopyd.h>
20 #include <linux/dm-region-hash.h>
21
22 #define DM_MSG_PREFIX "raid1"
23
24 #define MAX_RECOVERY 1  /* Maximum number of regions recovered in parallel. */
25 #define DM_IO_PAGES 64
26 #define DM_KCOPYD_PAGES 64
27
28 #define DM_RAID1_HANDLE_ERRORS 0x01
29 #define errors_handled(p)       ((p)->features & DM_RAID1_HANDLE_ERRORS)
30
31 static DECLARE_WAIT_QUEUE_HEAD(_kmirrord_recovery_stopped);
32
33 /*-----------------------------------------------------------------
34  * Mirror set structures.
35  *---------------------------------------------------------------*/
36 enum dm_raid1_error {
37         DM_RAID1_WRITE_ERROR,
38         DM_RAID1_FLUSH_ERROR,
39         DM_RAID1_SYNC_ERROR,
40         DM_RAID1_READ_ERROR
41 };
42
43 struct mirror {
44         struct mirror_set *ms;
45         atomic_t error_count;
46         unsigned long error_type;
47         struct dm_dev *dev;
48         sector_t offset;
49 };
50
51 struct mirror_set {
52         struct dm_target *ti;
53         struct list_head list;
54
55         uint64_t features;
56
57         spinlock_t lock;        /* protects the lists */
58         struct bio_list reads;
59         struct bio_list writes;
60         struct bio_list failures;
61         struct bio_list holds;  /* bios are waiting until suspend */
62
63         struct dm_region_hash *rh;
64         struct dm_kcopyd_client *kcopyd_client;
65         struct dm_io_client *io_client;
66         mempool_t *read_record_pool;
67
68         /* recovery */
69         region_t nr_regions;
70         int in_sync;
71         int log_failure;
72         atomic_t suspend;
73
74         atomic_t default_mirror;        /* Default mirror */
75
76         struct workqueue_struct *kmirrord_wq;
77         struct work_struct kmirrord_work;
78         struct timer_list timer;
79         unsigned long timer_pending;
80
81         struct work_struct trigger_event;
82
83         unsigned nr_mirrors;
84         struct mirror mirror[0];
85 };
86
87 static void wakeup_mirrord(void *context)
88 {
89         struct mirror_set *ms = context;
90
91         queue_work(ms->kmirrord_wq, &ms->kmirrord_work);
92 }
93
94 static void delayed_wake_fn(unsigned long data)
95 {
96         struct mirror_set *ms = (struct mirror_set *) data;
97
98         clear_bit(0, &ms->timer_pending);
99         wakeup_mirrord(ms);
100 }
101
102 static void delayed_wake(struct mirror_set *ms)
103 {
104         if (test_and_set_bit(0, &ms->timer_pending))
105                 return;
106
107         ms->timer.expires = jiffies + HZ / 5;
108         ms->timer.data = (unsigned long) ms;
109         ms->timer.function = delayed_wake_fn;
110         add_timer(&ms->timer);
111 }
112
113 static void wakeup_all_recovery_waiters(void *context)
114 {
115         wake_up_all(&_kmirrord_recovery_stopped);
116 }
117
118 static void queue_bio(struct mirror_set *ms, struct bio *bio, int rw)
119 {
120         unsigned long flags;
121         int should_wake = 0;
122         struct bio_list *bl;
123
124         bl = (rw == WRITE) ? &ms->writes : &ms->reads;
125         spin_lock_irqsave(&ms->lock, flags);
126         should_wake = !(bl->head);
127         bio_list_add(bl, bio);
128         spin_unlock_irqrestore(&ms->lock, flags);
129
130         if (should_wake)
131                 wakeup_mirrord(ms);
132 }
133
134 static void dispatch_bios(void *context, struct bio_list *bio_list)
135 {
136         struct mirror_set *ms = context;
137         struct bio *bio;
138
139         while ((bio = bio_list_pop(bio_list)))
140                 queue_bio(ms, bio, WRITE);
141 }
142
143 #define MIN_READ_RECORDS 20
144 struct dm_raid1_read_record {
145         struct mirror *m;
146         struct dm_bio_details details;
147 };
148
149 static struct kmem_cache *_dm_raid1_read_record_cache;
150
151 /*
152  * Every mirror should look like this one.
153  */
154 #define DEFAULT_MIRROR 0
155
156 /*
157  * This is yucky.  We squirrel the mirror struct away inside
158  * bi_next for read/write buffers.  This is safe since the bh
159  * doesn't get submitted to the lower levels of block layer.
160  */
161 static struct mirror *bio_get_m(struct bio *bio)
162 {
163         return (struct mirror *) bio->bi_next;
164 }
165
166 static void bio_set_m(struct bio *bio, struct mirror *m)
167 {
168         bio->bi_next = (struct bio *) m;
169 }
170
171 static struct mirror *get_default_mirror(struct mirror_set *ms)
172 {
173         return &ms->mirror[atomic_read(&ms->default_mirror)];
174 }
175
176 static void set_default_mirror(struct mirror *m)
177 {
178         struct mirror_set *ms = m->ms;
179         struct mirror *m0 = &(ms->mirror[0]);
180
181         atomic_set(&ms->default_mirror, m - m0);
182 }
183
184 static struct mirror *get_valid_mirror(struct mirror_set *ms)
185 {
186         struct mirror *m;
187
188         for (m = ms->mirror; m < ms->mirror + ms->nr_mirrors; m++)
189                 if (!atomic_read(&m->error_count))
190                         return m;
191
192         return NULL;
193 }
194
195 /* fail_mirror
196  * @m: mirror device to fail
197  * @error_type: one of the enum's, DM_RAID1_*_ERROR
198  *
199  * If errors are being handled, record the type of
200  * error encountered for this device.  If this type
201  * of error has already been recorded, we can return;
202  * otherwise, we must signal userspace by triggering
203  * an event.  Additionally, if the device is the
204  * primary device, we must choose a new primary, but
205  * only if the mirror is in-sync.
206  *
207  * This function must not block.
208  */
209 static void fail_mirror(struct mirror *m, enum dm_raid1_error error_type)
210 {
211         struct mirror_set *ms = m->ms;
212         struct mirror *new;
213
214         /*
215          * error_count is used for nothing more than a
216          * simple way to tell if a device has encountered
217          * errors.
218          */
219         atomic_inc(&m->error_count);
220
221         if (test_and_set_bit(error_type, &m->error_type))
222                 return;
223
224         if (!errors_handled(ms))
225                 return;
226
227         if (m != get_default_mirror(ms))
228                 goto out;
229
230         if (!ms->in_sync) {
231                 /*
232                  * Better to issue requests to same failing device
233                  * than to risk returning corrupt data.
234                  */
235                 DMERR("Primary mirror (%s) failed while out-of-sync: "
236                       "Reads may fail.", m->dev->name);
237                 goto out;
238         }
239
240         new = get_valid_mirror(ms);
241         if (new)
242                 set_default_mirror(new);
243         else
244                 DMWARN("All sides of mirror have failed.");
245
246 out:
247         schedule_work(&ms->trigger_event);
248 }
249
250 static int mirror_flush(struct dm_target *ti)
251 {
252         struct mirror_set *ms = ti->private;
253         unsigned long error_bits;
254
255         unsigned int i;
256         struct dm_io_region io[ms->nr_mirrors];
257         struct mirror *m;
258         struct dm_io_request io_req = {
259                 .bi_rw = WRITE_BARRIER,
260                 .mem.type = DM_IO_KMEM,
261                 .mem.ptr.bvec = NULL,
262                 .client = ms->io_client,
263         };
264
265         for (i = 0, m = ms->mirror; i < ms->nr_mirrors; i++, m++) {
266                 io[i].bdev = m->dev->bdev;
267                 io[i].sector = 0;
268                 io[i].count = 0;
269         }
270
271         error_bits = -1;
272         dm_io(&io_req, ms->nr_mirrors, io, &error_bits);
273         if (unlikely(error_bits != 0)) {
274                 for (i = 0; i < ms->nr_mirrors; i++)
275                         if (test_bit(i, &error_bits))
276                                 fail_mirror(ms->mirror + i,
277                                             DM_RAID1_FLUSH_ERROR);
278                 return -EIO;
279         }
280
281         return 0;
282 }
283
284 /*-----------------------------------------------------------------
285  * Recovery.
286  *
287  * When a mirror is first activated we may find that some regions
288  * are in the no-sync state.  We have to recover these by
289  * recopying from the default mirror to all the others.
290  *---------------------------------------------------------------*/
291 static void recovery_complete(int read_err, unsigned long write_err,
292                               void *context)
293 {
294         struct dm_region *reg = context;
295         struct mirror_set *ms = dm_rh_region_context(reg);
296         int m, bit = 0;
297
298         if (read_err) {
299                 /* Read error means the failure of default mirror. */
300                 DMERR_LIMIT("Unable to read primary mirror during recovery");
301                 fail_mirror(get_default_mirror(ms), DM_RAID1_SYNC_ERROR);
302         }
303
304         if (write_err) {
305                 DMERR_LIMIT("Write error during recovery (error = 0x%lx)",
306                             write_err);
307                 /*
308                  * Bits correspond to devices (excluding default mirror).
309                  * The default mirror cannot change during recovery.
310                  */
311                 for (m = 0; m < ms->nr_mirrors; m++) {
312                         if (&ms->mirror[m] == get_default_mirror(ms))
313                                 continue;
314                         if (test_bit(bit, &write_err))
315                                 fail_mirror(ms->mirror + m,
316                                             DM_RAID1_SYNC_ERROR);
317                         bit++;
318                 }
319         }
320
321         dm_rh_recovery_end(reg, !(read_err || write_err));
322 }
323
324 static int recover(struct mirror_set *ms, struct dm_region *reg)
325 {
326         int r;
327         unsigned i;
328         struct dm_io_region from, to[DM_KCOPYD_MAX_REGIONS], *dest;
329         struct mirror *m;
330         unsigned long flags = 0;
331         region_t key = dm_rh_get_region_key(reg);
332         sector_t region_size = dm_rh_get_region_size(ms->rh);
333
334         /* fill in the source */
335         m = get_default_mirror(ms);
336         from.bdev = m->dev->bdev;
337         from.sector = m->offset + dm_rh_region_to_sector(ms->rh, key);
338         if (key == (ms->nr_regions - 1)) {
339                 /*
340                  * The final region may be smaller than
341                  * region_size.
342                  */
343                 from.count = ms->ti->len & (region_size - 1);
344                 if (!from.count)
345                         from.count = region_size;
346         } else
347                 from.count = region_size;
348
349         /* fill in the destinations */
350         for (i = 0, dest = to; i < ms->nr_mirrors; i++) {
351                 if (&ms->mirror[i] == get_default_mirror(ms))
352                         continue;
353
354                 m = ms->mirror + i;
355                 dest->bdev = m->dev->bdev;
356                 dest->sector = m->offset + dm_rh_region_to_sector(ms->rh, key);
357                 dest->count = from.count;
358                 dest++;
359         }
360
361         /* hand to kcopyd */
362         if (!errors_handled(ms))
363                 set_bit(DM_KCOPYD_IGNORE_ERROR, &flags);
364
365         r = dm_kcopyd_copy(ms->kcopyd_client, &from, ms->nr_mirrors - 1, to,
366                            flags, recovery_complete, reg);
367
368         return r;
369 }
370
371 static void do_recovery(struct mirror_set *ms)
372 {
373         struct dm_region *reg;
374         struct dm_dirty_log *log = dm_rh_dirty_log(ms->rh);
375         int r;
376
377         /*
378          * Start quiescing some regions.
379          */
380         dm_rh_recovery_prepare(ms->rh);
381
382         /*
383          * Copy any already quiesced regions.
384          */
385         while ((reg = dm_rh_recovery_start(ms->rh))) {
386                 r = recover(ms, reg);
387                 if (r)
388                         dm_rh_recovery_end(reg, 0);
389         }
390
391         /*
392          * Update the in sync flag.
393          */
394         if (!ms->in_sync &&
395             (log->type->get_sync_count(log) == ms->nr_regions)) {
396                 /* the sync is complete */
397                 dm_table_event(ms->ti->table);
398                 ms->in_sync = 1;
399         }
400 }
401
402 /*-----------------------------------------------------------------
403  * Reads
404  *---------------------------------------------------------------*/
405 static struct mirror *choose_mirror(struct mirror_set *ms, sector_t sector)
406 {
407         struct mirror *m = get_default_mirror(ms);
408
409         do {
410                 if (likely(!atomic_read(&m->error_count)))
411                         return m;
412
413                 if (m-- == ms->mirror)
414                         m += ms->nr_mirrors;
415         } while (m != get_default_mirror(ms));
416
417         return NULL;
418 }
419
420 static int default_ok(struct mirror *m)
421 {
422         struct mirror *default_mirror = get_default_mirror(m->ms);
423
424         return !atomic_read(&default_mirror->error_count);
425 }
426
427 static int mirror_available(struct mirror_set *ms, struct bio *bio)
428 {
429         struct dm_dirty_log *log = dm_rh_dirty_log(ms->rh);
430         region_t region = dm_rh_bio_to_region(ms->rh, bio);
431
432         if (log->type->in_sync(log, region, 0))
433                 return choose_mirror(ms,  bio->bi_sector) ? 1 : 0;
434
435         return 0;
436 }
437
438 /*
439  * remap a buffer to a particular mirror.
440  */
441 static sector_t map_sector(struct mirror *m, struct bio *bio)
442 {
443         if (unlikely(!bio->bi_size))
444                 return 0;
445         return m->offset + (bio->bi_sector - m->ms->ti->begin);
446 }
447
448 static void map_bio(struct mirror *m, struct bio *bio)
449 {
450         bio->bi_bdev = m->dev->bdev;
451         bio->bi_sector = map_sector(m, bio);
452 }
453
454 static void map_region(struct dm_io_region *io, struct mirror *m,
455                        struct bio *bio)
456 {
457         io->bdev = m->dev->bdev;
458         io->sector = map_sector(m, bio);
459         io->count = bio->bi_size >> 9;
460 }
461
462 static void hold_bio(struct mirror_set *ms, struct bio *bio)
463 {
464         /*
465          * If device is suspended, complete the bio.
466          */
467         if (atomic_read(&ms->suspend)) {
468                 if (dm_noflush_suspending(ms->ti))
469                         bio_endio(bio, DM_ENDIO_REQUEUE);
470                 else
471                         bio_endio(bio, -EIO);
472                 return;
473         }
474
475         /*
476          * Hold bio until the suspend is complete.
477          */
478         spin_lock_irq(&ms->lock);
479         bio_list_add(&ms->holds, bio);
480         spin_unlock_irq(&ms->lock);
481 }
482
483 /*-----------------------------------------------------------------
484  * Reads
485  *---------------------------------------------------------------*/
486 static void read_callback(unsigned long error, void *context)
487 {
488         struct bio *bio = context;
489         struct mirror *m;
490
491         m = bio_get_m(bio);
492         bio_set_m(bio, NULL);
493
494         if (likely(!error)) {
495                 bio_endio(bio, 0);
496                 return;
497         }
498
499         fail_mirror(m, DM_RAID1_READ_ERROR);
500
501         if (likely(default_ok(m)) || mirror_available(m->ms, bio)) {
502                 DMWARN_LIMIT("Read failure on mirror device %s.  "
503                              "Trying alternative device.",
504                              m->dev->name);
505                 queue_bio(m->ms, bio, bio_rw(bio));
506                 return;
507         }
508
509         DMERR_LIMIT("Read failure on mirror device %s.  Failing I/O.",
510                     m->dev->name);
511         bio_endio(bio, -EIO);
512 }
513
514 /* Asynchronous read. */
515 static void read_async_bio(struct mirror *m, struct bio *bio)
516 {
517         struct dm_io_region io;
518         struct dm_io_request io_req = {
519                 .bi_rw = READ,
520                 .mem.type = DM_IO_BVEC,
521                 .mem.ptr.bvec = bio->bi_io_vec + bio->bi_idx,
522                 .notify.fn = read_callback,
523                 .notify.context = bio,
524                 .client = m->ms->io_client,
525         };
526
527         map_region(&io, m, bio);
528         bio_set_m(bio, m);
529         BUG_ON(dm_io(&io_req, 1, &io, NULL));
530 }
531
532 static inline int region_in_sync(struct mirror_set *ms, region_t region,
533                                  int may_block)
534 {
535         int state = dm_rh_get_state(ms->rh, region, may_block);
536         return state == DM_RH_CLEAN || state == DM_RH_DIRTY;
537 }
538
539 static void do_reads(struct mirror_set *ms, struct bio_list *reads)
540 {
541         region_t region;
542         struct bio *bio;
543         struct mirror *m;
544
545         while ((bio = bio_list_pop(reads))) {
546                 region = dm_rh_bio_to_region(ms->rh, bio);
547                 m = get_default_mirror(ms);
548
549                 /*
550                  * We can only read balance if the region is in sync.
551                  */
552                 if (likely(region_in_sync(ms, region, 1)))
553                         m = choose_mirror(ms, bio->bi_sector);
554                 else if (m && atomic_read(&m->error_count))
555                         m = NULL;
556
557                 if (likely(m))
558                         read_async_bio(m, bio);
559                 else
560                         bio_endio(bio, -EIO);
561         }
562 }
563
564 /*-----------------------------------------------------------------
565  * Writes.
566  *
567  * We do different things with the write io depending on the
568  * state of the region that it's in:
569  *
570  * SYNC:        increment pending, use kcopyd to write to *all* mirrors
571  * RECOVERING:  delay the io until recovery completes
572  * NOSYNC:      increment pending, just write to the default mirror
573  *---------------------------------------------------------------*/
574
575
576 static void write_callback(unsigned long error, void *context)
577 {
578         unsigned i, ret = 0;
579         struct bio *bio = (struct bio *) context;
580         struct mirror_set *ms;
581         int uptodate = 0;
582         int should_wake = 0;
583         unsigned long flags;
584
585         ms = bio_get_m(bio)->ms;
586         bio_set_m(bio, NULL);
587
588         /*
589          * NOTE: We don't decrement the pending count here,
590          * instead it is done by the targets endio function.
591          * This way we handle both writes to SYNC and NOSYNC
592          * regions with the same code.
593          */
594         if (likely(!error))
595                 goto out;
596
597         for (i = 0; i < ms->nr_mirrors; i++)
598                 if (test_bit(i, &error))
599                         fail_mirror(ms->mirror + i, DM_RAID1_WRITE_ERROR);
600                 else
601                         uptodate = 1;
602
603         if (unlikely(!uptodate)) {
604                 DMERR("All replicated volumes dead, failing I/O");
605                 /* None of the writes succeeded, fail the I/O. */
606                 ret = -EIO;
607         } else if (errors_handled(ms)) {
608                 /*
609                  * Need to raise event.  Since raising
610                  * events can block, we need to do it in
611                  * the main thread.
612                  */
613                 spin_lock_irqsave(&ms->lock, flags);
614                 if (!ms->failures.head)
615                         should_wake = 1;
616                 bio_list_add(&ms->failures, bio);
617                 spin_unlock_irqrestore(&ms->lock, flags);
618                 if (should_wake)
619                         wakeup_mirrord(ms);
620                 return;
621         }
622 out:
623         bio_endio(bio, ret);
624 }
625
626 static void do_write(struct mirror_set *ms, struct bio *bio)
627 {
628         unsigned int i;
629         struct dm_io_region io[ms->nr_mirrors], *dest = io;
630         struct mirror *m;
631         struct dm_io_request io_req = {
632                 .bi_rw = WRITE | (bio->bi_rw & WRITE_BARRIER),
633                 .mem.type = DM_IO_BVEC,
634                 .mem.ptr.bvec = bio->bi_io_vec + bio->bi_idx,
635                 .notify.fn = write_callback,
636                 .notify.context = bio,
637                 .client = ms->io_client,
638         };
639
640         for (i = 0, m = ms->mirror; i < ms->nr_mirrors; i++, m++)
641                 map_region(dest++, m, bio);
642
643         /*
644          * Use default mirror because we only need it to retrieve the reference
645          * to the mirror set in write_callback().
646          */
647         bio_set_m(bio, get_default_mirror(ms));
648
649         BUG_ON(dm_io(&io_req, ms->nr_mirrors, io, NULL));
650 }
651
652 static void do_writes(struct mirror_set *ms, struct bio_list *writes)
653 {
654         int state;
655         struct bio *bio;
656         struct bio_list sync, nosync, recover, *this_list = NULL;
657         struct bio_list requeue;
658         struct dm_dirty_log *log = dm_rh_dirty_log(ms->rh);
659         region_t region;
660
661         if (!writes->head)
662                 return;
663
664         /*
665          * Classify each write.
666          */
667         bio_list_init(&sync);
668         bio_list_init(&nosync);
669         bio_list_init(&recover);
670         bio_list_init(&requeue);
671
672         while ((bio = bio_list_pop(writes))) {
673                 if (unlikely(bio_empty_barrier(bio))) {
674                         bio_list_add(&sync, bio);
675                         continue;
676                 }
677
678                 region = dm_rh_bio_to_region(ms->rh, bio);
679
680                 if (log->type->is_remote_recovering &&
681                     log->type->is_remote_recovering(log, region)) {
682                         bio_list_add(&requeue, bio);
683                         continue;
684                 }
685
686                 state = dm_rh_get_state(ms->rh, region, 1);
687                 switch (state) {
688                 case DM_RH_CLEAN:
689                 case DM_RH_DIRTY:
690                         this_list = &sync;
691                         break;
692
693                 case DM_RH_NOSYNC:
694                         this_list = &nosync;
695                         break;
696
697                 case DM_RH_RECOVERING:
698                         this_list = &recover;
699                         break;
700                 }
701
702                 bio_list_add(this_list, bio);
703         }
704
705         /*
706          * Add bios that are delayed due to remote recovery
707          * back on to the write queue
708          */
709         if (unlikely(requeue.head)) {
710                 spin_lock_irq(&ms->lock);
711                 bio_list_merge(&ms->writes, &requeue);
712                 spin_unlock_irq(&ms->lock);
713                 delayed_wake(ms);
714         }
715
716         /*
717          * Increment the pending counts for any regions that will
718          * be written to (writes to recover regions are going to
719          * be delayed).
720          */
721         dm_rh_inc_pending(ms->rh, &sync);
722         dm_rh_inc_pending(ms->rh, &nosync);
723
724         /*
725          * If the flush fails on a previous call and succeeds here,
726          * we must not reset the log_failure variable.  We need
727          * userspace interaction to do that.
728          */
729         ms->log_failure = dm_rh_flush(ms->rh) ? 1 : ms->log_failure;
730
731         /*
732          * Dispatch io.
733          */
734         if (unlikely(ms->log_failure)) {
735                 spin_lock_irq(&ms->lock);
736                 bio_list_merge(&ms->failures, &sync);
737                 spin_unlock_irq(&ms->lock);
738                 wakeup_mirrord(ms);
739         } else
740                 while ((bio = bio_list_pop(&sync)))
741                         do_write(ms, bio);
742
743         while ((bio = bio_list_pop(&recover)))
744                 dm_rh_delay(ms->rh, bio);
745
746         while ((bio = bio_list_pop(&nosync))) {
747                 map_bio(get_default_mirror(ms), bio);
748                 generic_make_request(bio);
749         }
750 }
751
752 static void do_failures(struct mirror_set *ms, struct bio_list *failures)
753 {
754         struct bio *bio;
755
756         if (likely(!failures->head))
757                 return;
758
759         /*
760          * If the log has failed, unattempted writes are being
761          * put on the holds list.  We can't issue those writes
762          * until a log has been marked, so we must store them.
763          *
764          * If a 'noflush' suspend is in progress, we can requeue
765          * the I/O's to the core.  This give userspace a chance
766          * to reconfigure the mirror, at which point the core
767          * will reissue the writes.  If the 'noflush' flag is
768          * not set, we have no choice but to return errors.
769          *
770          * Some writes on the failures list may have been
771          * submitted before the log failure and represent a
772          * failure to write to one of the devices.  It is ok
773          * for us to treat them the same and requeue them
774          * as well.
775          */
776
777         while ((bio = bio_list_pop(failures))) {
778                 if (ms->log_failure)
779                         hold_bio(ms, bio);
780                 else {
781                         ms->in_sync = 0;
782                         dm_rh_mark_nosync(ms->rh, bio);
783                         bio_endio(bio, 0);
784                 }
785         }
786 }
787
788 static void trigger_event(struct work_struct *work)
789 {
790         struct mirror_set *ms =
791                 container_of(work, struct mirror_set, trigger_event);
792
793         dm_table_event(ms->ti->table);
794 }
795
796 /*-----------------------------------------------------------------
797  * kmirrord
798  *---------------------------------------------------------------*/
799 static void do_mirror(struct work_struct *work)
800 {
801         struct mirror_set *ms = container_of(work, struct mirror_set,
802                                              kmirrord_work);
803         struct bio_list reads, writes, failures;
804         unsigned long flags;
805
806         spin_lock_irqsave(&ms->lock, flags);
807         reads = ms->reads;
808         writes = ms->writes;
809         failures = ms->failures;
810         bio_list_init(&ms->reads);
811         bio_list_init(&ms->writes);
812         bio_list_init(&ms->failures);
813         spin_unlock_irqrestore(&ms->lock, flags);
814
815         dm_rh_update_states(ms->rh, errors_handled(ms));
816         do_recovery(ms);
817         do_reads(ms, &reads);
818         do_writes(ms, &writes);
819         do_failures(ms, &failures);
820
821         dm_table_unplug_all(ms->ti->table);
822 }
823
824 /*-----------------------------------------------------------------
825  * Target functions
826  *---------------------------------------------------------------*/
827 static struct mirror_set *alloc_context(unsigned int nr_mirrors,
828                                         uint32_t region_size,
829                                         struct dm_target *ti,
830                                         struct dm_dirty_log *dl)
831 {
832         size_t len;
833         struct mirror_set *ms = NULL;
834
835         len = sizeof(*ms) + (sizeof(ms->mirror[0]) * nr_mirrors);
836
837         ms = kzalloc(len, GFP_KERNEL);
838         if (!ms) {
839                 ti->error = "Cannot allocate mirror context";
840                 return NULL;
841         }
842
843         spin_lock_init(&ms->lock);
844
845         ms->ti = ti;
846         ms->nr_mirrors = nr_mirrors;
847         ms->nr_regions = dm_sector_div_up(ti->len, region_size);
848         ms->in_sync = 0;
849         ms->log_failure = 0;
850         atomic_set(&ms->suspend, 0);
851         atomic_set(&ms->default_mirror, DEFAULT_MIRROR);
852
853         ms->read_record_pool = mempool_create_slab_pool(MIN_READ_RECORDS,
854                                                 _dm_raid1_read_record_cache);
855
856         if (!ms->read_record_pool) {
857                 ti->error = "Error creating mirror read_record_pool";
858                 kfree(ms);
859                 return NULL;
860         }
861
862         ms->io_client = dm_io_client_create(DM_IO_PAGES);
863         if (IS_ERR(ms->io_client)) {
864                 ti->error = "Error creating dm_io client";
865                 mempool_destroy(ms->read_record_pool);
866                 kfree(ms);
867                 return NULL;
868         }
869
870         ms->rh = dm_region_hash_create(ms, dispatch_bios, wakeup_mirrord,
871                                        wakeup_all_recovery_waiters,
872                                        ms->ti->begin, MAX_RECOVERY,
873                                        dl, region_size, ms->nr_regions);
874         if (IS_ERR(ms->rh)) {
875                 ti->error = "Error creating dirty region hash";
876                 dm_io_client_destroy(ms->io_client);
877                 mempool_destroy(ms->read_record_pool);
878                 kfree(ms);
879                 return NULL;
880         }
881
882         return ms;
883 }
884
885 static void free_context(struct mirror_set *ms, struct dm_target *ti,
886                          unsigned int m)
887 {
888         while (m--)
889                 dm_put_device(ti, ms->mirror[m].dev);
890
891         dm_io_client_destroy(ms->io_client);
892         dm_region_hash_destroy(ms->rh);
893         mempool_destroy(ms->read_record_pool);
894         kfree(ms);
895 }
896
897 static int get_mirror(struct mirror_set *ms, struct dm_target *ti,
898                       unsigned int mirror, char **argv)
899 {
900         unsigned long long offset;
901
902         if (sscanf(argv[1], "%llu", &offset) != 1) {
903                 ti->error = "Invalid offset";
904                 return -EINVAL;
905         }
906
907         if (dm_get_device(ti, argv[0], offset, ti->len,
908                           dm_table_get_mode(ti->table),
909                           &ms->mirror[mirror].dev)) {
910                 ti->error = "Device lookup failure";
911                 return -ENXIO;
912         }
913
914         ms->mirror[mirror].ms = ms;
915         atomic_set(&(ms->mirror[mirror].error_count), 0);
916         ms->mirror[mirror].error_type = 0;
917         ms->mirror[mirror].offset = offset;
918
919         return 0;
920 }
921
922 /*
923  * Create dirty log: log_type #log_params <log_params>
924  */
925 static struct dm_dirty_log *create_dirty_log(struct dm_target *ti,
926                                              unsigned argc, char **argv,
927                                              unsigned *args_used)
928 {
929         unsigned param_count;
930         struct dm_dirty_log *dl;
931
932         if (argc < 2) {
933                 ti->error = "Insufficient mirror log arguments";
934                 return NULL;
935         }
936
937         if (sscanf(argv[1], "%u", &param_count) != 1) {
938                 ti->error = "Invalid mirror log argument count";
939                 return NULL;
940         }
941
942         *args_used = 2 + param_count;
943
944         if (argc < *args_used) {
945                 ti->error = "Insufficient mirror log arguments";
946                 return NULL;
947         }
948
949         dl = dm_dirty_log_create(argv[0], ti, mirror_flush, param_count,
950                                  argv + 2);
951         if (!dl) {
952                 ti->error = "Error creating mirror dirty log";
953                 return NULL;
954         }
955
956         return dl;
957 }
958
959 static int parse_features(struct mirror_set *ms, unsigned argc, char **argv,
960                           unsigned *args_used)
961 {
962         unsigned num_features;
963         struct dm_target *ti = ms->ti;
964
965         *args_used = 0;
966
967         if (!argc)
968                 return 0;
969
970         if (sscanf(argv[0], "%u", &num_features) != 1) {
971                 ti->error = "Invalid number of features";
972                 return -EINVAL;
973         }
974
975         argc--;
976         argv++;
977         (*args_used)++;
978
979         if (num_features > argc) {
980                 ti->error = "Not enough arguments to support feature count";
981                 return -EINVAL;
982         }
983
984         if (!strcmp("handle_errors", argv[0]))
985                 ms->features |= DM_RAID1_HANDLE_ERRORS;
986         else {
987                 ti->error = "Unrecognised feature requested";
988                 return -EINVAL;
989         }
990
991         (*args_used)++;
992
993         return 0;
994 }
995
996 /*
997  * Construct a mirror mapping:
998  *
999  * log_type #log_params <log_params>
1000  * #mirrors [mirror_path offset]{2,}
1001  * [#features <features>]
1002  *
1003  * log_type is "core" or "disk"
1004  * #log_params is between 1 and 3
1005  *
1006  * If present, features must be "handle_errors".
1007  */
1008 static int mirror_ctr(struct dm_target *ti, unsigned int argc, char **argv)
1009 {
1010         int r;
1011         unsigned int nr_mirrors, m, args_used;
1012         struct mirror_set *ms;
1013         struct dm_dirty_log *dl;
1014
1015         dl = create_dirty_log(ti, argc, argv, &args_used);
1016         if (!dl)
1017                 return -EINVAL;
1018
1019         argv += args_used;
1020         argc -= args_used;
1021
1022         if (!argc || sscanf(argv[0], "%u", &nr_mirrors) != 1 ||
1023             nr_mirrors < 2 || nr_mirrors > DM_KCOPYD_MAX_REGIONS + 1) {
1024                 ti->error = "Invalid number of mirrors";
1025                 dm_dirty_log_destroy(dl);
1026                 return -EINVAL;
1027         }
1028
1029         argv++, argc--;
1030
1031         if (argc < nr_mirrors * 2) {
1032                 ti->error = "Too few mirror arguments";
1033                 dm_dirty_log_destroy(dl);
1034                 return -EINVAL;
1035         }
1036
1037         ms = alloc_context(nr_mirrors, dl->type->get_region_size(dl), ti, dl);
1038         if (!ms) {
1039                 dm_dirty_log_destroy(dl);
1040                 return -ENOMEM;
1041         }
1042
1043         /* Get the mirror parameter sets */
1044         for (m = 0; m < nr_mirrors; m++) {
1045                 r = get_mirror(ms, ti, m, argv);
1046                 if (r) {
1047                         free_context(ms, ti, m);
1048                         return r;
1049                 }
1050                 argv += 2;
1051                 argc -= 2;
1052         }
1053
1054         ti->private = ms;
1055         ti->split_io = dm_rh_get_region_size(ms->rh);
1056         ti->num_flush_requests = 1;
1057
1058         ms->kmirrord_wq = create_singlethread_workqueue("kmirrord");
1059         if (!ms->kmirrord_wq) {
1060                 DMERR("couldn't start kmirrord");
1061                 r = -ENOMEM;
1062                 goto err_free_context;
1063         }
1064         INIT_WORK(&ms->kmirrord_work, do_mirror);
1065         init_timer(&ms->timer);
1066         ms->timer_pending = 0;
1067         INIT_WORK(&ms->trigger_event, trigger_event);
1068
1069         r = parse_features(ms, argc, argv, &args_used);
1070         if (r)
1071                 goto err_destroy_wq;
1072
1073         argv += args_used;
1074         argc -= args_used;
1075
1076         /*
1077          * Any read-balancing addition depends on the
1078          * DM_RAID1_HANDLE_ERRORS flag being present.
1079          * This is because the decision to balance depends
1080          * on the sync state of a region.  If the above
1081          * flag is not present, we ignore errors; and
1082          * the sync state may be inaccurate.
1083          */
1084
1085         if (argc) {
1086                 ti->error = "Too many mirror arguments";
1087                 r = -EINVAL;
1088                 goto err_destroy_wq;
1089         }
1090
1091         r = dm_kcopyd_client_create(DM_KCOPYD_PAGES, &ms->kcopyd_client);
1092         if (r)
1093                 goto err_destroy_wq;
1094
1095         wakeup_mirrord(ms);
1096         return 0;
1097
1098 err_destroy_wq:
1099         destroy_workqueue(ms->kmirrord_wq);
1100 err_free_context:
1101         free_context(ms, ti, ms->nr_mirrors);
1102         return r;
1103 }
1104
1105 static void mirror_dtr(struct dm_target *ti)
1106 {
1107         struct mirror_set *ms = (struct mirror_set *) ti->private;
1108
1109         del_timer_sync(&ms->timer);
1110         flush_workqueue(ms->kmirrord_wq);
1111         flush_scheduled_work();
1112         dm_kcopyd_client_destroy(ms->kcopyd_client);
1113         destroy_workqueue(ms->kmirrord_wq);
1114         free_context(ms, ti, ms->nr_mirrors);
1115 }
1116
1117 /*
1118  * Mirror mapping function
1119  */
1120 static int mirror_map(struct dm_target *ti, struct bio *bio,
1121                       union map_info *map_context)
1122 {
1123         int r, rw = bio_rw(bio);
1124         struct mirror *m;
1125         struct mirror_set *ms = ti->private;
1126         struct dm_raid1_read_record *read_record = NULL;
1127         struct dm_dirty_log *log = dm_rh_dirty_log(ms->rh);
1128
1129         if (rw == WRITE) {
1130                 /* Save region for mirror_end_io() handler */
1131                 map_context->ll = dm_rh_bio_to_region(ms->rh, bio);
1132                 queue_bio(ms, bio, rw);
1133                 return DM_MAPIO_SUBMITTED;
1134         }
1135
1136         r = log->type->in_sync(log, dm_rh_bio_to_region(ms->rh, bio), 0);
1137         if (r < 0 && r != -EWOULDBLOCK)
1138                 return r;
1139
1140         /*
1141          * If region is not in-sync queue the bio.
1142          */
1143         if (!r || (r == -EWOULDBLOCK)) {
1144                 if (rw == READA)
1145                         return -EWOULDBLOCK;
1146
1147                 queue_bio(ms, bio, rw);
1148                 return DM_MAPIO_SUBMITTED;
1149         }
1150
1151         /*
1152          * The region is in-sync and we can perform reads directly.
1153          * Store enough information so we can retry if it fails.
1154          */
1155         m = choose_mirror(ms, bio->bi_sector);
1156         if (unlikely(!m))
1157                 return -EIO;
1158
1159         read_record = mempool_alloc(ms->read_record_pool, GFP_NOIO);
1160         if (likely(read_record)) {
1161                 dm_bio_record(&read_record->details, bio);
1162                 map_context->ptr = read_record;
1163                 read_record->m = m;
1164         }
1165
1166         map_bio(m, bio);
1167
1168         return DM_MAPIO_REMAPPED;
1169 }
1170
1171 static int mirror_end_io(struct dm_target *ti, struct bio *bio,
1172                          int error, union map_info *map_context)
1173 {
1174         int rw = bio_rw(bio);
1175         struct mirror_set *ms = (struct mirror_set *) ti->private;
1176         struct mirror *m = NULL;
1177         struct dm_bio_details *bd = NULL;
1178         struct dm_raid1_read_record *read_record = map_context->ptr;
1179
1180         /*
1181          * We need to dec pending if this was a write.
1182          */
1183         if (rw == WRITE) {
1184                 if (likely(!bio_empty_barrier(bio)))
1185                         dm_rh_dec(ms->rh, map_context->ll);
1186                 return error;
1187         }
1188
1189         if (error == -EOPNOTSUPP)
1190                 goto out;
1191
1192         if ((error == -EWOULDBLOCK) && bio_rw_flagged(bio, BIO_RW_AHEAD))
1193                 goto out;
1194
1195         if (unlikely(error)) {
1196                 if (!read_record) {
1197                         /*
1198                          * There wasn't enough memory to record necessary
1199                          * information for a retry or there was no other
1200                          * mirror in-sync.
1201                          */
1202                         DMERR_LIMIT("Mirror read failed.");
1203                         return -EIO;
1204                 }
1205
1206                 m = read_record->m;
1207
1208                 DMERR("Mirror read failed from %s. Trying alternative device.",
1209                       m->dev->name);
1210
1211                 fail_mirror(m, DM_RAID1_READ_ERROR);
1212
1213                 /*
1214                  * A failed read is requeued for another attempt using an intact
1215                  * mirror.
1216                  */
1217                 if (default_ok(m) || mirror_available(ms, bio)) {
1218                         bd = &read_record->details;
1219
1220                         dm_bio_restore(bd, bio);
1221                         mempool_free(read_record, ms->read_record_pool);
1222                         map_context->ptr = NULL;
1223                         queue_bio(ms, bio, rw);
1224                         return 1;
1225                 }
1226                 DMERR("All replicated volumes dead, failing I/O");
1227         }
1228
1229 out:
1230         if (read_record) {
1231                 mempool_free(read_record, ms->read_record_pool);
1232                 map_context->ptr = NULL;
1233         }
1234
1235         return error;
1236 }
1237
1238 static void mirror_presuspend(struct dm_target *ti)
1239 {
1240         struct mirror_set *ms = (struct mirror_set *) ti->private;
1241         struct dm_dirty_log *log = dm_rh_dirty_log(ms->rh);
1242
1243         struct bio_list holds;
1244         struct bio *bio;
1245
1246         atomic_set(&ms->suspend, 1);
1247
1248         /*
1249          * We must finish up all the work that we've
1250          * generated (i.e. recovery work).
1251          */
1252         dm_rh_stop_recovery(ms->rh);
1253
1254         wait_event(_kmirrord_recovery_stopped,
1255                    !dm_rh_recovery_in_flight(ms->rh));
1256
1257         if (log->type->presuspend && log->type->presuspend(log))
1258                 /* FIXME: need better error handling */
1259                 DMWARN("log presuspend failed");
1260
1261         /*
1262          * Now that recovery is complete/stopped and the
1263          * delayed bios are queued, we need to wait for
1264          * the worker thread to complete.  This way,
1265          * we know that all of our I/O has been pushed.
1266          */
1267         flush_workqueue(ms->kmirrord_wq);
1268
1269         /*
1270          * Now set ms->suspend is set and the workqueue flushed, no more
1271          * entries can be added to ms->hold list, so process it.
1272          *
1273          * Bios can still arrive concurrently with or after this
1274          * presuspend function, but they cannot join the hold list
1275          * because ms->suspend is set.
1276          */
1277         spin_lock_irq(&ms->lock);
1278         holds = ms->holds;
1279         bio_list_init(&ms->holds);
1280         spin_unlock_irq(&ms->lock);
1281
1282         while ((bio = bio_list_pop(&holds)))
1283                 hold_bio(ms, bio);
1284 }
1285
1286 static void mirror_postsuspend(struct dm_target *ti)
1287 {
1288         struct mirror_set *ms = ti->private;
1289         struct dm_dirty_log *log = dm_rh_dirty_log(ms->rh);
1290
1291         if (log->type->postsuspend && log->type->postsuspend(log))
1292                 /* FIXME: need better error handling */
1293                 DMWARN("log postsuspend failed");
1294 }
1295
1296 static void mirror_resume(struct dm_target *ti)
1297 {
1298         struct mirror_set *ms = ti->private;
1299         struct dm_dirty_log *log = dm_rh_dirty_log(ms->rh);
1300
1301         atomic_set(&ms->suspend, 0);
1302         if (log->type->resume && log->type->resume(log))
1303                 /* FIXME: need better error handling */
1304                 DMWARN("log resume failed");
1305         dm_rh_start_recovery(ms->rh);
1306 }
1307
1308 /*
1309  * device_status_char
1310  * @m: mirror device/leg we want the status of
1311  *
1312  * We return one character representing the most severe error
1313  * we have encountered.
1314  *    A => Alive - No failures
1315  *    D => Dead - A write failure occurred leaving mirror out-of-sync
1316  *    S => Sync - A sychronization failure occurred, mirror out-of-sync
1317  *    R => Read - A read failure occurred, mirror data unaffected
1318  *
1319  * Returns: <char>
1320  */
1321 static char device_status_char(struct mirror *m)
1322 {
1323         if (!atomic_read(&(m->error_count)))
1324                 return 'A';
1325
1326         return (test_bit(DM_RAID1_FLUSH_ERROR, &(m->error_type))) ? 'F' :
1327                 (test_bit(DM_RAID1_WRITE_ERROR, &(m->error_type))) ? 'D' :
1328                 (test_bit(DM_RAID1_SYNC_ERROR, &(m->error_type))) ? 'S' :
1329                 (test_bit(DM_RAID1_READ_ERROR, &(m->error_type))) ? 'R' : 'U';
1330 }
1331
1332
1333 static int mirror_status(struct dm_target *ti, status_type_t type,
1334                          char *result, unsigned int maxlen)
1335 {
1336         unsigned int m, sz = 0;
1337         struct mirror_set *ms = (struct mirror_set *) ti->private;
1338         struct dm_dirty_log *log = dm_rh_dirty_log(ms->rh);
1339         char buffer[ms->nr_mirrors + 1];
1340
1341         switch (type) {
1342         case STATUSTYPE_INFO:
1343                 DMEMIT("%d ", ms->nr_mirrors);
1344                 for (m = 0; m < ms->nr_mirrors; m++) {
1345                         DMEMIT("%s ", ms->mirror[m].dev->name);
1346                         buffer[m] = device_status_char(&(ms->mirror[m]));
1347                 }
1348                 buffer[m] = '\0';
1349
1350                 DMEMIT("%llu/%llu 1 %s ",
1351                       (unsigned long long)log->type->get_sync_count(log),
1352                       (unsigned long long)ms->nr_regions, buffer);
1353
1354                 sz += log->type->status(log, type, result+sz, maxlen-sz);
1355
1356                 break;
1357
1358         case STATUSTYPE_TABLE:
1359                 sz = log->type->status(log, type, result, maxlen);
1360
1361                 DMEMIT("%d", ms->nr_mirrors);
1362                 for (m = 0; m < ms->nr_mirrors; m++)
1363                         DMEMIT(" %s %llu", ms->mirror[m].dev->name,
1364                                (unsigned long long)ms->mirror[m].offset);
1365
1366                 if (ms->features & DM_RAID1_HANDLE_ERRORS)
1367                         DMEMIT(" 1 handle_errors");
1368         }
1369
1370         return 0;
1371 }
1372
1373 static int mirror_iterate_devices(struct dm_target *ti,
1374                                   iterate_devices_callout_fn fn, void *data)
1375 {
1376         struct mirror_set *ms = ti->private;
1377         int ret = 0;
1378         unsigned i;
1379
1380         for (i = 0; !ret && i < ms->nr_mirrors; i++)
1381                 ret = fn(ti, ms->mirror[i].dev,
1382                          ms->mirror[i].offset, ti->len, data);
1383
1384         return ret;
1385 }
1386
1387 static struct target_type mirror_target = {
1388         .name    = "mirror",
1389         .version = {1, 12, 0},
1390         .module  = THIS_MODULE,
1391         .ctr     = mirror_ctr,
1392         .dtr     = mirror_dtr,
1393         .map     = mirror_map,
1394         .end_io  = mirror_end_io,
1395         .presuspend = mirror_presuspend,
1396         .postsuspend = mirror_postsuspend,
1397         .resume  = mirror_resume,
1398         .status  = mirror_status,
1399         .iterate_devices = mirror_iterate_devices,
1400 };
1401
1402 static int __init dm_mirror_init(void)
1403 {
1404         int r;
1405
1406         _dm_raid1_read_record_cache = KMEM_CACHE(dm_raid1_read_record, 0);
1407         if (!_dm_raid1_read_record_cache) {
1408                 DMERR("Can't allocate dm_raid1_read_record cache");
1409                 r = -ENOMEM;
1410                 goto bad_cache;
1411         }
1412
1413         r = dm_register_target(&mirror_target);
1414         if (r < 0) {
1415                 DMERR("Failed to register mirror target");
1416                 goto bad_target;
1417         }
1418
1419         return 0;
1420
1421 bad_target:
1422         kmem_cache_destroy(_dm_raid1_read_record_cache);
1423 bad_cache:
1424         return r;
1425 }
1426
1427 static void __exit dm_mirror_exit(void)
1428 {
1429         dm_unregister_target(&mirror_target);
1430         kmem_cache_destroy(_dm_raid1_read_record_cache);
1431 }
1432
1433 /* Module hooks */
1434 module_init(dm_mirror_init);
1435 module_exit(dm_mirror_exit);
1436
1437 MODULE_DESCRIPTION(DM_NAME " mirror target");
1438 MODULE_AUTHOR("Joe Thornber");
1439 MODULE_LICENSE("GPL");