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