- patches.fixes/md-raid1-dont-release-reference.patch: md/raid1:
[opensuse:kernel.git] / drivers / md / raid1.c
1 /*
2  * raid1.c : Multiple Devices driver for Linux
3  *
4  * Copyright (C) 1999, 2000, 2001 Ingo Molnar, Red Hat
5  *
6  * Copyright (C) 1996, 1997, 1998 Ingo Molnar, Miguel de Icaza, Gadi Oxman
7  *
8  * RAID-1 management functions.
9  *
10  * Better read-balancing code written by Mika Kuoppala <miku@iki.fi>, 2000
11  *
12  * Fixes to reconstruction by Jakob Ć˜stergaard" <jakob@ostenfeld.dk>
13  * Various fixes by Neil Brown <neilb@cse.unsw.edu.au>
14  *
15  * Changes by Peter T. Breuer <ptb@it.uc3m.es> 31/1/2003 to support
16  * bitmapped intelligence in resync:
17  *
18  *      - bitmap marked during normal i/o
19  *      - bitmap used to skip nondirty blocks during sync
20  *
21  * Additions to bitmap code, (C) 2003-2004 Paul Clements, SteelEye Technology:
22  * - persistent bitmap code
23  *
24  * This program is free software; you can redistribute it and/or modify
25  * it under the terms of the GNU General Public License as published by
26  * the Free Software Foundation; either version 2, or (at your option)
27  * any later version.
28  *
29  * You should have received a copy of the GNU General Public License
30  * (for example /usr/src/linux/COPYING); if not, write to the Free
31  * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
32  */
33
34 #include <linux/slab.h>
35 #include <linux/delay.h>
36 #include <linux/blkdev.h>
37 #include <linux/seq_file.h>
38 #include "md.h"
39 #include "raid1.h"
40 #include "bitmap.h"
41
42 #define DEBUG 0
43 #if DEBUG
44 #define PRINTK(x...) printk(x)
45 #else
46 #define PRINTK(x...)
47 #endif
48
49 /*
50  * Number of guaranteed r1bios in case of extreme VM load:
51  */
52 #define NR_RAID1_BIOS 256
53
54
55 static void allow_barrier(conf_t *conf);
56 static void lower_barrier(conf_t *conf);
57
58 static void * r1bio_pool_alloc(gfp_t gfp_flags, void *data)
59 {
60         struct pool_info *pi = data;
61         int size = offsetof(r1bio_t, bios[pi->raid_disks]);
62
63         /* allocate a r1bio with room for raid_disks entries in the bios array */
64         return kzalloc(size, gfp_flags);
65 }
66
67 static void r1bio_pool_free(void *r1_bio, void *data)
68 {
69         kfree(r1_bio);
70 }
71
72 #define RESYNC_BLOCK_SIZE (64*1024)
73 //#define RESYNC_BLOCK_SIZE PAGE_SIZE
74 #define RESYNC_SECTORS (RESYNC_BLOCK_SIZE >> 9)
75 #define RESYNC_PAGES ((RESYNC_BLOCK_SIZE + PAGE_SIZE-1) / PAGE_SIZE)
76 #define RESYNC_WINDOW (2048*1024)
77
78 static void * r1buf_pool_alloc(gfp_t gfp_flags, void *data)
79 {
80         struct pool_info *pi = data;
81         struct page *page;
82         r1bio_t *r1_bio;
83         struct bio *bio;
84         int i, j;
85
86         r1_bio = r1bio_pool_alloc(gfp_flags, pi);
87         if (!r1_bio)
88                 return NULL;
89
90         /*
91          * Allocate bios : 1 for reading, n-1 for writing
92          */
93         for (j = pi->raid_disks ; j-- ; ) {
94                 bio = bio_kmalloc(gfp_flags, RESYNC_PAGES);
95                 if (!bio)
96                         goto out_free_bio;
97                 r1_bio->bios[j] = bio;
98         }
99         /*
100          * Allocate RESYNC_PAGES data pages and attach them to
101          * the first bio.
102          * If this is a user-requested check/repair, allocate
103          * RESYNC_PAGES for each bio.
104          */
105         if (test_bit(MD_RECOVERY_REQUESTED, &pi->mddev->recovery))
106                 j = pi->raid_disks;
107         else
108                 j = 1;
109         while(j--) {
110                 bio = r1_bio->bios[j];
111                 for (i = 0; i < RESYNC_PAGES; i++) {
112                         page = alloc_page(gfp_flags);
113                         if (unlikely(!page))
114                                 goto out_free_pages;
115
116                         bio->bi_io_vec[i].bv_page = page;
117                         bio->bi_vcnt = i+1;
118                 }
119         }
120         /* If not user-requests, copy the page pointers to all bios */
121         if (!test_bit(MD_RECOVERY_REQUESTED, &pi->mddev->recovery)) {
122                 for (i=0; i<RESYNC_PAGES ; i++)
123                         for (j=1; j<pi->raid_disks; j++)
124                                 r1_bio->bios[j]->bi_io_vec[i].bv_page =
125                                         r1_bio->bios[0]->bi_io_vec[i].bv_page;
126         }
127
128         r1_bio->master_bio = NULL;
129
130         return r1_bio;
131
132 out_free_pages:
133         for (j=0 ; j < pi->raid_disks; j++)
134                 for (i=0; i < r1_bio->bios[j]->bi_vcnt ; i++)
135                         put_page(r1_bio->bios[j]->bi_io_vec[i].bv_page);
136         j = -1;
137 out_free_bio:
138         while ( ++j < pi->raid_disks )
139                 bio_put(r1_bio->bios[j]);
140         r1bio_pool_free(r1_bio, data);
141         return NULL;
142 }
143
144 static void r1buf_pool_free(void *__r1_bio, void *data)
145 {
146         struct pool_info *pi = data;
147         int i,j;
148         r1bio_t *r1bio = __r1_bio;
149
150         for (i = 0; i < RESYNC_PAGES; i++)
151                 for (j = pi->raid_disks; j-- ;) {
152                         if (j == 0 ||
153                             r1bio->bios[j]->bi_io_vec[i].bv_page !=
154                             r1bio->bios[0]->bi_io_vec[i].bv_page)
155                                 safe_put_page(r1bio->bios[j]->bi_io_vec[i].bv_page);
156                 }
157         for (i=0 ; i < pi->raid_disks; i++)
158                 bio_put(r1bio->bios[i]);
159
160         r1bio_pool_free(r1bio, data);
161 }
162
163 static void put_all_bios(conf_t *conf, r1bio_t *r1_bio)
164 {
165         int i;
166
167         for (i = 0; i < conf->raid_disks; i++) {
168                 struct bio **bio = r1_bio->bios + i;
169                 if (*bio && *bio != IO_BLOCKED)
170                         bio_put(*bio);
171                 *bio = NULL;
172         }
173 }
174
175 static void free_r1bio(r1bio_t *r1_bio)
176 {
177         conf_t *conf = r1_bio->mddev->private;
178
179         /*
180          * Wake up any possible resync thread that waits for the device
181          * to go idle.
182          */
183         allow_barrier(conf);
184
185         put_all_bios(conf, r1_bio);
186         mempool_free(r1_bio, conf->r1bio_pool);
187 }
188
189 static void put_buf(r1bio_t *r1_bio)
190 {
191         conf_t *conf = r1_bio->mddev->private;
192         int i;
193
194         for (i=0; i<conf->raid_disks; i++) {
195                 struct bio *bio = r1_bio->bios[i];
196                 if (bio->bi_end_io)
197                         rdev_dec_pending(conf->mirrors[i].rdev, r1_bio->mddev);
198         }
199
200         mempool_free(r1_bio, conf->r1buf_pool);
201
202         lower_barrier(conf);
203 }
204
205 static void reschedule_retry(r1bio_t *r1_bio)
206 {
207         unsigned long flags;
208         mddev_t *mddev = r1_bio->mddev;
209         conf_t *conf = mddev->private;
210
211         spin_lock_irqsave(&conf->device_lock, flags);
212         list_add(&r1_bio->retry_list, &conf->retry_list);
213         conf->nr_queued ++;
214         spin_unlock_irqrestore(&conf->device_lock, flags);
215
216         wake_up(&conf->wait_barrier);
217         md_wakeup_thread(mddev->thread);
218 }
219
220 /*
221  * raid_end_bio_io() is called when we have finished servicing a mirrored
222  * operation and are ready to return a success/failure code to the buffer
223  * cache layer.
224  */
225 static void raid_end_bio_io(r1bio_t *r1_bio)
226 {
227         struct bio *bio = r1_bio->master_bio;
228
229         /* if nobody has done the final endio yet, do it now */
230         if (!test_and_set_bit(R1BIO_Returned, &r1_bio->state)) {
231                 PRINTK(KERN_DEBUG "raid1: sync end %s on sectors %llu-%llu\n",
232                         (bio_data_dir(bio) == WRITE) ? "write" : "read",
233                         (unsigned long long) bio->bi_sector,
234                         (unsigned long long) bio->bi_sector +
235                                 (bio->bi_size >> 9) - 1);
236
237                 bio_endio(bio,
238                         test_bit(R1BIO_Uptodate, &r1_bio->state) ? 0 : -EIO);
239         }
240         free_r1bio(r1_bio);
241 }
242
243 /*
244  * Update disk head position estimator based on IRQ completion info.
245  */
246 static inline void update_head_pos(int disk, r1bio_t *r1_bio)
247 {
248         conf_t *conf = r1_bio->mddev->private;
249
250         conf->mirrors[disk].head_position =
251                 r1_bio->sector + (r1_bio->sectors);
252 }
253
254 static void raid1_end_read_request(struct bio *bio, int error)
255 {
256         int uptodate = test_bit(BIO_UPTODATE, &bio->bi_flags);
257         r1bio_t *r1_bio = bio->bi_private;
258         int mirror;
259         conf_t *conf = r1_bio->mddev->private;
260         mdk_rdev_t *rdev;
261
262         mirror = r1_bio->read_disk;
263         rdev = conf->mirrors[mirror].rdev;
264         /*
265          * this branch is our 'one mirror IO has finished' event handler:
266          */
267         update_head_pos(mirror, r1_bio);
268
269         if (uptodate)
270                 set_bit(R1BIO_Uptodate, &r1_bio->state);
271         else if (test_bit(FailFast, &rdev->flags) &&
272                  test_bit(R1BIO_FailFast, &r1_bio->state))
273                 /* This was a fail-fast read so we definitely
274                  * want to retry */
275                 ;
276         else {
277                 /* If all other devices have failed, we want to return
278                  * the error upwards rather than fail the last device.
279                  * Here we redefine "uptodate" to mean "Don't want to retry"
280                  */
281                 unsigned long flags;
282                 spin_lock_irqsave(&conf->device_lock, flags);
283                 if (r1_bio->mddev->degraded == conf->raid_disks ||
284                     (r1_bio->mddev->degraded == conf->raid_disks-1 &&
285                      !test_bit(Faulty, &conf->mirrors[mirror].rdev->flags)))
286                         uptodate = 1;
287                 spin_unlock_irqrestore(&conf->device_lock, flags);
288         }
289
290         if (uptodate) {
291                 raid_end_bio_io(r1_bio);
292                 rdev_dec_pending(conf->mirrors[mirror].rdev, conf->mddev);
293         } else {
294                 /*
295                  * oops, read error:
296                  */
297                 char b[BDEVNAME_SIZE];
298                 if (printk_ratelimit())
299                         printk(KERN_ERR "md/raid1:%s: %s: rescheduling sector %llu\n",
300                                mdname(conf->mddev),
301                                bdevname(conf->mirrors[mirror].rdev->bdev,b), (unsigned long long)r1_bio->sector);
302                 reschedule_retry(r1_bio);
303                 /* don't drop the reference on read_disk yet */
304         }
305 }
306
307 static void r1_bio_write_done(r1bio_t *r1_bio)
308 {
309         if (atomic_dec_and_test(&r1_bio->remaining))
310         {
311                 if (test_bit(R1BIO_WriteError, &r1_bio->state)) {
312                         reschedule_retry(r1_bio);
313                         return;
314                 }
315                 /* it really is the end of this request */
316                 if (test_bit(R1BIO_BehindIO, &r1_bio->state)) {
317                         /* free extra copy of the data pages */
318                         int i = r1_bio->behind_page_count;
319                         while (i--)
320                                 safe_put_page(r1_bio->behind_pages[i]);
321                         kfree(r1_bio->behind_pages);
322                         r1_bio->behind_pages = NULL;
323                 }
324                 /* clear the bitmap if all writes complete successfully */
325                 bitmap_endwrite(r1_bio->mddev->bitmap, r1_bio->sector,
326                                 r1_bio->sectors,
327                                 !test_bit(R1BIO_Degraded, &r1_bio->state),
328                                 test_bit(R1BIO_BehindIO, &r1_bio->state));
329                 md_write_end(r1_bio->mddev);
330                 raid_end_bio_io(r1_bio);
331         }
332 }
333
334 static void raid1_end_write_request(struct bio *bio, int error)
335 {
336         int uptodate = test_bit(BIO_UPTODATE, &bio->bi_flags);
337         r1bio_t *r1_bio = bio->bi_private;
338         int mirror, behind = test_bit(R1BIO_BehindIO, &r1_bio->state);
339         conf_t *conf = r1_bio->mddev->private;
340         struct bio *to_put = NULL;
341         mdk_rdev_t *rdev;
342
343
344         for (mirror = 0; mirror < conf->raid_disks; mirror++)
345                 if (r1_bio->bios[mirror] == bio)
346                         break;
347         rdev = conf->mirrors[mirror].rdev;
348
349         /*
350          * 'one mirror IO has finished' event handler:
351          */
352         r1_bio->bios[mirror] = NULL;
353         to_put = bio;
354         if (!uptodate) {
355                 md_error(r1_bio->mddev, conf->mirrors[mirror].rdev);
356                 /* an I/O failed, we can't clear the bitmap */
357
358                 if (test_bit(FailFast, &rdev->flags) &&
359                     /* We never try FailFast to WriteMostly devices */
360                     !test_bit(WriteMostly, &rdev->flags) &&
361                     !test_bit(Faulty, &rdev->flags)) {
362                         /* This is the only remaining device,
363                          * We need to retry the write without
364                          * FailFast
365                          */
366                         set_bit(R1BIO_WriteError, &r1_bio->state);
367                         r1_bio->bios[mirror] = to_put;
368                         to_put = NULL;
369                 } else
370                         set_bit(R1BIO_Degraded, &r1_bio->state);
371         } else
372                 /*
373                  * Set R1BIO_Uptodate in our master bio, so that we
374                  * will return a good error code for to the higher
375                  * levels even if IO on some other mirrored buffer
376                  * fails.
377                  *
378                  * The 'master' represents the composite IO operation
379                  * to user-side. So if something waits for IO, then it
380                  * will wait for the 'master' bio.
381                  */
382                 set_bit(R1BIO_Uptodate, &r1_bio->state);
383
384         update_head_pos(mirror, r1_bio);
385
386         if (behind) {
387                 if (test_bit(WriteMostly, &conf->mirrors[mirror].rdev->flags))
388                         atomic_dec(&r1_bio->behind_remaining);
389
390                 /*
391                  * In behind mode, we ACK the master bio once the I/O
392                  * has safely reached all non-writemostly
393                  * disks. Setting the Returned bit ensures that this
394                  * gets done only once -- we don't ever want to return
395                  * -EIO here, instead we'll wait
396                  */
397                 if (atomic_read(&r1_bio->behind_remaining) >= (atomic_read(&r1_bio->remaining)-1) &&
398                     test_bit(R1BIO_Uptodate, &r1_bio->state)) {
399                         /* Maybe we can return now */
400                         if (!test_and_set_bit(R1BIO_Returned, &r1_bio->state)) {
401                                 struct bio *mbio = r1_bio->master_bio;
402                                 PRINTK(KERN_DEBUG "raid1: behind end write sectors %llu-%llu\n",
403                                        (unsigned long long) mbio->bi_sector,
404                                        (unsigned long long) mbio->bi_sector +
405                                        (mbio->bi_size >> 9) - 1);
406                                 bio_endio(mbio, 0);
407                         }
408                 }
409         }
410         if (r1_bio->bios[mirror] == NULL)
411                 rdev_dec_pending(conf->mirrors[mirror].rdev, conf->mddev);
412
413         /*
414          * Let's see if all mirrored write operations have finished
415          * already.
416          */
417         r1_bio_write_done(r1_bio);
418
419         if (to_put)
420                 bio_put(to_put);
421 }
422
423
424 /*
425  * This routine returns the disk from which the requested read should
426  * be done. There is a per-array 'next expected sequential IO' sector
427  * number - if this matches on the next IO then we use the last disk.
428  * There is also a per-disk 'last know head position' sector that is
429  * maintained from IRQ contexts, both the normal and the resync IO
430  * completion handlers update this position correctly. If there is no
431  * perfect sequential match then we pick the disk whose head is closest.
432  *
433  * If there are 2 mirrors in the same 2 devices, performance degrades
434  * because position is mirror, not device based.
435  *
436  * The rdev for the device selected will have nr_pending incremented.
437  */
438 static int read_balance(conf_t *conf, r1bio_t *r1_bio)
439 {
440         const sector_t this_sector = r1_bio->sector;
441         const int sectors = r1_bio->sectors;
442         int start_disk;
443         int best_disk;
444         int i;
445         sector_t best_dist;
446         mdk_rdev_t *rdev;
447         int choose_first;
448
449         rcu_read_lock();
450         /*
451          * Check if we can balance. We can balance on the whole
452          * device if no resync is going on, or below the resync window.
453          * We take the first readable disk when above the resync window.
454          */
455  retry:
456         best_disk = -1;
457         best_dist = MaxSector;
458         clear_bit(R1BIO_FailFast, &r1_bio->state);
459
460         if (conf->mddev->recovery_cp < MaxSector &&
461             (this_sector + sectors >= conf->next_resync)) {
462                 choose_first = 1;
463                 start_disk = 0;
464         } else {
465                 choose_first = 0;
466                 start_disk = conf->last_used;
467         }
468
469         for (i = 0 ; i < conf->raid_disks ; i++) {
470                 sector_t dist;
471                 int disk = start_disk + i;
472                 if (disk >= conf->raid_disks)
473                         disk -= conf->raid_disks;
474
475                 rdev = rcu_dereference(conf->mirrors[disk].rdev);
476                 if (r1_bio->bios[disk] == IO_BLOCKED
477                     || rdev == NULL
478                     || test_bit(Faulty, &rdev->flags))
479                         continue;
480                 if (!test_bit(In_sync, &rdev->flags) &&
481                     rdev->recovery_offset < this_sector + sectors)
482                         continue;
483                 if (test_bit(WriteMostly, &rdev->flags)) {
484                         /* Don't balance among write-mostly, just
485                          * use the first as a last resort */
486                         if (best_disk < 0)
487                                 best_disk = disk;
488                         continue;
489                 }
490                 /* This is a reasonable device to use.  It might
491                  * even be best.
492                  */
493                 dist = abs(this_sector - conf->mirrors[disk].head_position);
494                 if (choose_first) {
495                         best_disk = disk;
496                         break;
497                 }
498                 if (
499                     /* Don't change to another disk for sequential reads */
500                     conf->next_seq_sect == this_sector
501                     /* If device is idle, use it */
502                     || atomic_read(&rdev->nr_pending) == 0)
503                         dist = 0;
504
505                 if (best_disk >= 0)
506                         /* At least two disks to choose from so failfast is OK */
507                         set_bit(R1BIO_FailFast, &r1_bio->state);
508
509                 if (dist < best_dist) {
510                         best_dist = dist;
511                         best_disk = disk;
512                 }
513         }
514
515         if (best_disk >= 0) {
516                 rdev = rcu_dereference(conf->mirrors[best_disk].rdev);
517                 if (!rdev)
518                         goto retry;
519                 atomic_inc(&rdev->nr_pending);
520                 if (test_bit(Faulty, &rdev->flags)) {
521                         /* cannot risk returning a device that failed
522                          * before we inc'ed nr_pending
523                          */
524                         rdev_dec_pending(rdev, conf->mddev);
525                         goto retry;
526                 }
527                 conf->next_seq_sect = this_sector + sectors;
528                 conf->last_used = best_disk;
529         }
530         rcu_read_unlock();
531
532         return best_disk;
533 }
534
535 static int max_queued = INT_MAX;
536
537 int md_raid1_congested(mddev_t *mddev, int bits)
538 {
539         conf_t *conf = mddev->private;
540         int i, ret = 0;
541
542         if ((bits & (1 << BDI_async_congested)) &&
543             conf->pending_count >= max_queued)
544                 return 1;
545
546         rcu_read_lock();
547         for (i = 0; i < mddev->raid_disks; i++) {
548                 mdk_rdev_t *rdev = rcu_dereference(conf->mirrors[i].rdev);
549                 if (rdev && !test_bit(Faulty, &rdev->flags)) {
550                         struct request_queue *q = bdev_get_queue(rdev->bdev);
551
552                         BUG_ON(!q);
553
554                         /* Note the '|| 1' - when read_balance prefers
555                          * non-congested targets, it can be removed
556                          */
557                         if ((bits & (1<<BDI_async_congested)) || 1)
558                                 ret |= bdi_congested(&q->backing_dev_info, bits);
559                         else
560                                 ret &= bdi_congested(&q->backing_dev_info, bits);
561                 }
562         }
563         rcu_read_unlock();
564         return ret;
565 }
566 EXPORT_SYMBOL_GPL(md_raid1_congested);
567
568 static int raid1_congested(void *data, int bits)
569 {
570         mddev_t *mddev = data;
571
572         return mddev_congested(mddev, bits) ||
573                 md_raid1_congested(mddev, bits);
574 }
575
576 static void flush_pending_writes(conf_t *conf)
577 {
578         /* Any writes that have been queued but are awaiting
579          * bitmap updates get flushed here.
580          */
581         spin_lock_irq(&conf->device_lock);
582
583         if (conf->pending_bio_list.head) {
584                 struct bio *bio;
585                 bio = bio_list_get(&conf->pending_bio_list);
586                 conf->pending_count = 0;
587                 spin_unlock_irq(&conf->device_lock);
588                 wake_up(&conf->wait_barrier);
589                 /* flush any pending bitmap writes to
590                  * disk before proceeding w/ I/O */
591                 bitmap_unplug(conf->mddev->bitmap);
592
593                 while (bio) { /* submit pending writes */
594                         struct bio *next = bio->bi_next;
595                         bio->bi_next = NULL;
596                         generic_make_request(bio);
597                         bio = next;
598                 }
599         } else
600                 spin_unlock_irq(&conf->device_lock);
601 }
602
603 /* Barriers....
604  * Sometimes we need to suspend IO while we do something else,
605  * either some resync/recovery, or reconfigure the array.
606  * To do this we raise a 'barrier'.
607  * The 'barrier' is a counter that can be raised multiple times
608  * to count how many activities are happening which preclude
609  * normal IO.
610  * We can only raise the barrier if there is no pending IO.
611  * i.e. if nr_pending == 0.
612  * We choose only to raise the barrier if no-one is waiting for the
613  * barrier to go down.  This means that as soon as an IO request
614  * is ready, no other operations which require a barrier will start
615  * until the IO request has had a chance.
616  *
617  * So: regular IO calls 'wait_barrier'.  When that returns there
618  *    is no backgroup IO happening,  It must arrange to call
619  *    allow_barrier when it has finished its IO.
620  * backgroup IO calls must call raise_barrier.  Once that returns
621  *    there is no normal IO happeing.  It must arrange to call
622  *    lower_barrier when the particular background IO completes.
623  */
624 #define RESYNC_DEPTH 32
625
626 static void raise_barrier(conf_t *conf)
627 {
628         spin_lock_irq(&conf->resync_lock);
629
630         /* Wait until no block IO is waiting */
631         wait_event_lock_irq(conf->wait_barrier, !conf->nr_waiting,
632                             conf->resync_lock, );
633
634         /* block any new IO from starting */
635         conf->barrier++;
636
637         /* Now wait for all pending IO to complete */
638         wait_event_lock_irq(conf->wait_barrier,
639                             !conf->nr_pending && conf->barrier < RESYNC_DEPTH,
640                             conf->resync_lock, );
641
642         spin_unlock_irq(&conf->resync_lock);
643 }
644
645 static void lower_barrier(conf_t *conf)
646 {
647         unsigned long flags;
648         BUG_ON(conf->barrier <= 0);
649         spin_lock_irqsave(&conf->resync_lock, flags);
650         conf->barrier--;
651         spin_unlock_irqrestore(&conf->resync_lock, flags);
652         wake_up(&conf->wait_barrier);
653 }
654
655 static void wait_barrier(conf_t *conf)
656 {
657         spin_lock_irq(&conf->resync_lock);
658         if (conf->barrier) {
659                 conf->nr_waiting++;
660                 /* Wait for the barrier to drop.
661                  * However if there are already pending
662                  * requests (preventing the barrier from
663                  * rising completely), and the
664                  * pre-process bio queue isn't empty,
665                  * then don't wait, as we need to empty
666                  * that queue to get the nr_pending
667                  * count down.
668                  */
669                 wait_event_lock_irq(conf->wait_barrier,
670                                     !conf->barrier ||
671                                     (conf->nr_pending &&
672                                      current->bio_list &&
673                                      !bio_list_empty(current->bio_list)),
674                                     conf->resync_lock,
675                         );
676                 conf->nr_waiting--;
677         }
678         conf->nr_pending++;
679         spin_unlock_irq(&conf->resync_lock);
680 }
681
682 static void allow_barrier(conf_t *conf)
683 {
684         unsigned long flags;
685         spin_lock_irqsave(&conf->resync_lock, flags);
686         conf->nr_pending--;
687         spin_unlock_irqrestore(&conf->resync_lock, flags);
688         wake_up(&conf->wait_barrier);
689 }
690
691 static void freeze_array(conf_t *conf)
692 {
693         /* stop syncio and normal IO and wait for everything to
694          * go quite.
695          * We increment barrier and nr_waiting, and then
696          * wait until nr_pending match nr_queued+1
697          * This is called in the context of one normal IO request
698          * that has failed. Thus any sync request that might be pending
699          * will be blocked by nr_pending, and we need to wait for
700          * pending IO requests to complete or be queued for re-try.
701          * Thus the number queued (nr_queued) plus this request (1)
702          * must match the number of pending IOs (nr_pending) before
703          * we continue.
704          */
705         spin_lock_irq(&conf->resync_lock);
706         conf->barrier++;
707         conf->nr_waiting++;
708         wait_event_lock_irq(conf->wait_barrier,
709                             conf->nr_pending == conf->nr_queued+1,
710                             conf->resync_lock,
711                             flush_pending_writes(conf));
712         spin_unlock_irq(&conf->resync_lock);
713 }
714 static void unfreeze_array(conf_t *conf)
715 {
716         /* reverse the effect of the freeze */
717         spin_lock_irq(&conf->resync_lock);
718         conf->barrier--;
719         conf->nr_waiting--;
720         wake_up(&conf->wait_barrier);
721         spin_unlock_irq(&conf->resync_lock);
722 }
723
724
725 /* duplicate the data pages for behind I/O 
726  */
727 static void alloc_behind_pages(struct bio *bio, r1bio_t *r1_bio)
728 {
729         int i;
730         struct bio_vec *bvec;
731         struct page **pages = kzalloc(bio->bi_vcnt * sizeof(struct page*),
732                                         GFP_NOIO);
733         if (unlikely(!pages))
734                 return;
735
736         bio_for_each_segment(bvec, bio, i) {
737                 pages[i] = alloc_page(GFP_NOIO);
738                 if (unlikely(!pages[i]))
739                         goto do_sync_io;
740                 memcpy(kmap(pages[i]) + bvec->bv_offset,
741                         kmap(bvec->bv_page) + bvec->bv_offset, bvec->bv_len);
742                 kunmap(pages[i]);
743                 kunmap(bvec->bv_page);
744         }
745         r1_bio->behind_pages = pages;
746         r1_bio->behind_page_count = bio->bi_vcnt;
747         set_bit(R1BIO_BehindIO, &r1_bio->state);
748         return;
749
750 do_sync_io:
751         for (i = 0; i < bio->bi_vcnt; i++)
752                 if (pages[i])
753                         put_page(pages[i]);
754         kfree(pages);
755         PRINTK("%dB behind alloc failed, doing sync I/O\n", bio->bi_size);
756 }
757
758 static int make_request(mddev_t *mddev, struct bio * bio)
759 {
760         conf_t *conf = mddev->private;
761         mirror_info_t *mirror;
762         r1bio_t *r1_bio;
763         struct bio *read_bio;
764         int i, targets = 0, disks;
765         struct bitmap *bitmap;
766         unsigned long flags;
767         const int rw = bio_data_dir(bio);
768         const unsigned long do_sync = (bio->bi_rw & REQ_SYNC);
769         const unsigned long do_flush_fua = (bio->bi_rw & (REQ_FLUSH | REQ_FUA));
770         mdk_rdev_t *blocked_rdev;
771         int plugged;
772
773         /*
774          * Register the new request and wait if the reconstruction
775          * thread has put up a bar for new requests.
776          * Continue immediately if no resync is active currently.
777          */
778
779         md_write_start(mddev, bio); /* wait on superblock update early */
780
781         if (bio_data_dir(bio) == WRITE &&
782             bio->bi_sector + bio->bi_size/512 > mddev->suspend_lo &&
783             bio->bi_sector < mddev->suspend_hi) {
784                 /* As the suspend_* range is controlled by
785                  * userspace, we want an interruptible
786                  * wait.
787                  */
788                 DEFINE_WAIT(w);
789                 for (;;) {
790                         flush_signals(current);
791                         prepare_to_wait(&conf->wait_barrier,
792                                         &w, TASK_INTERRUPTIBLE);
793                         if (bio->bi_sector + bio->bi_size/512 <= mddev->suspend_lo ||
794                             bio->bi_sector >= mddev->suspend_hi)
795                                 break;
796                         schedule();
797                 }
798                 finish_wait(&conf->wait_barrier, &w);
799         }
800
801         wait_barrier(conf);
802
803         bitmap = mddev->bitmap;
804
805         /*
806          * make_request() can abort the operation when READA is being
807          * used and no empty request is available.
808          *
809          */
810         r1_bio = mempool_alloc(conf->r1bio_pool, GFP_NOIO);
811
812         r1_bio->master_bio = bio;
813         r1_bio->sectors = bio->bi_size >> 9;
814         r1_bio->state = 0;
815         r1_bio->mddev = mddev;
816         r1_bio->sector = bio->bi_sector;
817
818         if (rw == READ) {
819                 /*
820                  * read balancing logic:
821                  */
822                 int rdisk = read_balance(conf, r1_bio);
823
824                 if (rdisk < 0) {
825                         /* couldn't find anywhere to read from */
826                         raid_end_bio_io(r1_bio);
827                         return 0;
828                 }
829                 mirror = conf->mirrors + rdisk;
830
831                 if (test_bit(WriteMostly, &mirror->rdev->flags) &&
832                     bitmap) {
833                         /* Reading from a write-mostly device must
834                          * take care not to over-take any writes
835                          * that are 'behind'
836                          */
837                         wait_event(bitmap->behind_wait,
838                                    atomic_read(&bitmap->behind_writes) == 0);
839                 }
840                 r1_bio->read_disk = rdisk;
841
842                 read_bio = bio_clone_mddev(bio, GFP_NOIO, mddev);
843
844                 r1_bio->bios[rdisk] = read_bio;
845
846                 read_bio->bi_sector = r1_bio->sector + mirror->rdev->data_offset;
847                 read_bio->bi_bdev = mirror->rdev->bdev;
848                 read_bio->bi_end_io = raid1_end_read_request;
849                 read_bio->bi_rw = READ | do_sync;
850                 if (test_bit(FailFast, &mirror->rdev->flags) &&
851                     test_bit(R1BIO_FailFast, &r1_bio->state))
852                         read_bio->bi_rw |= REQ_FAILFAST_DEV;
853                 read_bio->bi_private = r1_bio;
854
855                 generic_make_request(read_bio);
856                 return 0;
857         }
858
859         /*
860          * WRITE:
861          */
862         if (conf->pending_count >= max_queued) {
863                 md_wakeup_thread(mddev->thread);
864                 wait_event(conf->wait_barrier,
865                            conf->pending_count < max_queued);
866         }
867         /* first select target devices under spinlock and
868          * inc refcount on their rdev.  Record them by setting
869          * bios[x] to bio
870          */
871         plugged = mddev_check_plugged(mddev);
872
873         disks = conf->raid_disks;
874  retry_write:
875         blocked_rdev = NULL;
876         rcu_read_lock();
877         for (i = 0;  i < disks; i++) {
878                 mdk_rdev_t *rdev = rcu_dereference(conf->mirrors[i].rdev);
879                 if (rdev && unlikely(test_bit(Blocked, &rdev->flags))) {
880                         atomic_inc(&rdev->nr_pending);
881                         blocked_rdev = rdev;
882                         break;
883                 }
884                 if (rdev && !test_bit(Faulty, &rdev->flags)) {
885                         atomic_inc(&rdev->nr_pending);
886                         if (test_bit(Faulty, &rdev->flags)) {
887                                 rdev_dec_pending(rdev, mddev);
888                                 r1_bio->bios[i] = NULL;
889                         } else {
890                                 r1_bio->bios[i] = bio;
891                                 targets++;
892                         }
893                 } else
894                         r1_bio->bios[i] = NULL;
895         }
896         rcu_read_unlock();
897
898         if (unlikely(blocked_rdev)) {
899                 /* Wait for this device to become unblocked */
900                 int j;
901
902                 for (j = 0; j < i; j++)
903                         if (r1_bio->bios[j])
904                                 rdev_dec_pending(conf->mirrors[j].rdev, mddev);
905
906                 allow_barrier(conf);
907                 md_wait_for_blocked_rdev(blocked_rdev, mddev);
908                 wait_barrier(conf);
909                 goto retry_write;
910         }
911
912         BUG_ON(targets == 0); /* we never fail the last device */
913
914         if (targets < conf->raid_disks) {
915                 /* array is degraded, we will not clear the bitmap
916                  * on I/O completion (see raid1_end_write_request) */
917                 set_bit(R1BIO_Degraded, &r1_bio->state);
918         }
919
920         /* do behind I/O ?
921          * Not if there are too many, or cannot allocate memory,
922          * or a reader on WriteMostly is waiting for behind writes 
923          * to flush */
924         if (bitmap &&
925             (atomic_read(&bitmap->behind_writes)
926              < mddev->bitmap_info.max_write_behind) &&
927             !waitqueue_active(&bitmap->behind_wait))
928                 alloc_behind_pages(bio, r1_bio);
929
930         atomic_set(&r1_bio->remaining, 1);
931         atomic_set(&r1_bio->behind_remaining, 0);
932
933         bitmap_startwrite(bitmap, bio->bi_sector, r1_bio->sectors,
934                                 test_bit(R1BIO_BehindIO, &r1_bio->state));
935         for (i = 0; i < disks; i++) {
936                 struct bio *mbio;
937                 if (!r1_bio->bios[i])
938                         continue;
939
940                 mbio = bio_clone_mddev(bio, GFP_NOIO, mddev);
941                 r1_bio->bios[i] = mbio;
942
943                 mbio->bi_sector = r1_bio->sector + conf->mirrors[i].rdev->data_offset;
944                 mbio->bi_bdev = conf->mirrors[i].rdev->bdev;
945                 mbio->bi_end_io = raid1_end_write_request;
946                 mbio->bi_rw = WRITE | do_flush_fua | do_sync;
947                 if (test_bit(FailFast, &conf->mirrors[i].rdev->flags) &&
948                     !test_bit(WriteMostly, &conf->mirrors[i].rdev->flags) &&
949                     conf->raid_disks - mddev->degraded > 1)
950                         mbio->bi_rw |= REQ_FAILFAST_DEV;
951                 mbio->bi_private = r1_bio;
952
953                 if (r1_bio->behind_pages) {
954                         struct bio_vec *bvec;
955                         int j;
956
957                         /* Yes, I really want the '__' version so that
958                          * we clear any unused pointer in the io_vec, rather
959                          * than leave them unchanged.  This is important
960                          * because when we come to free the pages, we won't
961                          * know the original bi_idx, so we just free
962                          * them all
963                          */
964                         __bio_for_each_segment(bvec, mbio, j, 0)
965                                 bvec->bv_page = r1_bio->behind_pages[j];
966                         if (test_bit(WriteMostly, &conf->mirrors[i].rdev->flags))
967                                 atomic_inc(&r1_bio->behind_remaining);
968                 }
969
970                 atomic_inc(&r1_bio->remaining);
971                 spin_lock_irqsave(&conf->device_lock, flags);
972                 bio_list_add(&conf->pending_bio_list, mbio);
973                 conf->pending_count++;
974                 spin_unlock_irqrestore(&conf->device_lock, flags);
975         }
976         r1_bio_write_done(r1_bio);
977
978         /* In case raid1d snuck in to freeze_array */
979         wake_up(&conf->wait_barrier);
980
981         if (do_sync || !bitmap || !plugged)
982                 md_wakeup_thread(mddev->thread);
983
984         return 0;
985 }
986
987 static void status(struct seq_file *seq, mddev_t *mddev)
988 {
989         conf_t *conf = mddev->private;
990         int i;
991
992         seq_printf(seq, " [%d/%d] [", conf->raid_disks,
993                    conf->raid_disks - mddev->degraded);
994         rcu_read_lock();
995         for (i = 0; i < conf->raid_disks; i++) {
996                 mdk_rdev_t *rdev = rcu_dereference(conf->mirrors[i].rdev);
997                 seq_printf(seq, "%s",
998                            rdev && test_bit(In_sync, &rdev->flags) ? "U" : "_");
999         }
1000         rcu_read_unlock();
1001         seq_printf(seq, "]");
1002 }
1003
1004
1005 static void error(mddev_t *mddev, mdk_rdev_t *rdev)
1006 {
1007         char b[BDEVNAME_SIZE];
1008         conf_t *conf = mddev->private;
1009         unsigned long flags;
1010
1011         /*
1012          * If it is not operational, then we have already marked it as dead
1013          * else if it is the last working disks, ignore the error, let the
1014          * next level up know.
1015          * else mark the drive as failed
1016          */
1017         spin_lock_irqsave(&conf->device_lock, flags);
1018         if (test_bit(In_sync, &rdev->flags)
1019             && (conf->raid_disks - mddev->degraded) == 1) {
1020                 /*
1021                  * Don't fail the drive, act as though we were just a
1022                  * normal single drive.
1023                  * However don't try a recovery from this drive as
1024                  * it is very likely to fail.
1025                  */
1026                 mddev->recovery_disabled = 1;
1027                 spin_unlock_irqrestore(&conf->device_lock, flags);
1028                 return;
1029         }
1030         if (test_and_clear_bit(In_sync, &rdev->flags)) {
1031                 mddev->degraded++;
1032                 set_bit(Faulty, &rdev->flags);
1033                 /*
1034                  * if recovery is running, make sure it aborts.
1035                  */
1036                 set_bit(MD_RECOVERY_INTR, &mddev->recovery);
1037         } else
1038                 set_bit(Faulty, &rdev->flags);
1039         spin_unlock_irqrestore(&conf->device_lock, flags);
1040         set_bit(MD_CHANGE_DEVS, &mddev->flags);
1041         printk(KERN_ALERT
1042                "md/raid1:%s: Disk failure on %s, disabling device.\n"
1043                "md/raid1:%s: Operation continuing on %d devices.\n",
1044                mdname(mddev), bdevname(rdev->bdev, b),
1045                mdname(mddev), conf->raid_disks - mddev->degraded);
1046 }
1047
1048 static void print_conf(conf_t *conf)
1049 {
1050         int i;
1051
1052         printk(KERN_DEBUG "RAID1 conf printout:\n");
1053         if (!conf) {
1054                 printk(KERN_DEBUG "(!conf)\n");
1055                 return;
1056         }
1057         printk(KERN_DEBUG " --- wd:%d rd:%d\n", conf->raid_disks - conf->mddev->degraded,
1058                 conf->raid_disks);
1059
1060         rcu_read_lock();
1061         for (i = 0; i < conf->raid_disks; i++) {
1062                 char b[BDEVNAME_SIZE];
1063                 mdk_rdev_t *rdev = rcu_dereference(conf->mirrors[i].rdev);
1064                 if (rdev)
1065                         printk(KERN_DEBUG " disk %d, wo:%d, o:%d, dev:%s\n",
1066                                i, !test_bit(In_sync, &rdev->flags),
1067                                !test_bit(Faulty, &rdev->flags),
1068                                bdevname(rdev->bdev,b));
1069         }
1070         rcu_read_unlock();
1071 }
1072
1073 static void close_sync(conf_t *conf)
1074 {
1075         wait_barrier(conf);
1076         allow_barrier(conf);
1077
1078         mempool_destroy(conf->r1buf_pool);
1079         conf->r1buf_pool = NULL;
1080 }
1081
1082 static int raid1_spare_active(mddev_t *mddev)
1083 {
1084         int i;
1085         conf_t *conf = mddev->private;
1086         int count = 0;
1087         unsigned long flags;
1088
1089         /*
1090          * Find all failed disks within the RAID1 configuration 
1091          * and mark them readable.
1092          * Called under mddev lock, so rcu protection not needed.
1093          */
1094         for (i = 0; i < conf->raid_disks; i++) {
1095                 mdk_rdev_t *rdev = conf->mirrors[i].rdev;
1096                 if (rdev
1097                     && !test_bit(Faulty, &rdev->flags)
1098                     && !test_and_set_bit(In_sync, &rdev->flags)) {
1099                         count++;
1100                         sysfs_notify_dirent(rdev->sysfs_state);
1101                 }
1102         }
1103         spin_lock_irqsave(&conf->device_lock, flags);
1104         mddev->degraded -= count;
1105         spin_unlock_irqrestore(&conf->device_lock, flags);
1106
1107         print_conf(conf);
1108         return count;
1109 }
1110
1111
1112 static int raid1_add_disk(mddev_t *mddev, mdk_rdev_t *rdev)
1113 {
1114         conf_t *conf = mddev->private;
1115         int err = -EEXIST;
1116         int mirror = 0;
1117         mirror_info_t *p;
1118         int first = 0;
1119         int last = mddev->raid_disks - 1;
1120
1121         if (rdev->raid_disk >= 0)
1122                 first = last = rdev->raid_disk;
1123
1124         for (mirror = first; mirror <= last; mirror++)
1125                 if ( !(p=conf->mirrors+mirror)->rdev) {
1126
1127                         disk_stack_limits(mddev->gendisk, rdev->bdev,
1128                                           rdev->data_offset << 9);
1129                         /* as we don't honour merge_bvec_fn, we must
1130                          * never risk violating it, so limit
1131                          * ->max_segments to one lying with a single
1132                          * page, as a one page request is never in
1133                          * violation.
1134                          */
1135                         if (rdev->bdev->bd_disk->queue->merge_bvec_fn) {
1136                                 blk_queue_max_segments(mddev->queue, 1);
1137                                 blk_queue_segment_boundary(mddev->queue,
1138                                                            PAGE_CACHE_SIZE - 1);
1139                         }
1140
1141                         p->head_position = 0;
1142                         rdev->raid_disk = mirror;
1143                         err = 0;
1144                         /* As all devices are equivalent, we don't need a full recovery
1145                          * if this was recently any drive of the array
1146                          */
1147                         if (rdev->saved_raid_disk < 0)
1148                                 conf->fullsync = 1;
1149                         rcu_assign_pointer(p->rdev, rdev);
1150                         break;
1151                 }
1152         md_integrity_add_rdev(rdev, mddev);
1153         print_conf(conf);
1154         return err;
1155 }
1156
1157 static int raid1_remove_disk(mddev_t *mddev, int number)
1158 {
1159         conf_t *conf = mddev->private;
1160         int err = 0;
1161         mdk_rdev_t *rdev;
1162         mirror_info_t *p = conf->mirrors+ number;
1163
1164         print_conf(conf);
1165         rdev = p->rdev;
1166         if (rdev) {
1167                 if (test_bit(In_sync, &rdev->flags) ||
1168                     atomic_read(&rdev->nr_pending)) {
1169                         err = -EBUSY;
1170                         goto abort;
1171                 }
1172                 /* Only remove non-faulty devices if recovery
1173                  * is not possible.
1174                  */
1175                 if (!test_bit(Faulty, &rdev->flags) &&
1176                     !mddev->recovery_disabled &&
1177                     mddev->degraded < conf->raid_disks) {
1178                         err = -EBUSY;
1179                         goto abort;
1180                 }
1181                 p->rdev = NULL;
1182                 synchronize_rcu();
1183                 if (atomic_read(&rdev->nr_pending)) {
1184                         /* lost the race, try later */
1185                         err = -EBUSY;
1186                         p->rdev = rdev;
1187                         goto abort;
1188                 }
1189                 err = md_integrity_register(mddev);
1190         }
1191 abort:
1192
1193         print_conf(conf);
1194         return err;
1195 }
1196
1197
1198 static void end_sync_read(struct bio *bio, int error)
1199 {
1200         r1bio_t *r1_bio = bio->bi_private;
1201         int i;
1202
1203         for (i=r1_bio->mddev->raid_disks; i--; )
1204                 if (r1_bio->bios[i] == bio)
1205                         break;
1206         BUG_ON(i < 0);
1207         update_head_pos(i, r1_bio);
1208         /*
1209          * we have read a block, now it needs to be re-written,
1210          * or re-read if the read failed.
1211          * We don't do much here, just schedule handling by raid1d
1212          */
1213         if (test_bit(BIO_UPTODATE, &bio->bi_flags))
1214                 set_bit(R1BIO_Uptodate, &r1_bio->state);
1215
1216         if (atomic_dec_and_test(&r1_bio->remaining))
1217                 reschedule_retry(r1_bio);
1218 }
1219
1220 static void end_sync_write(struct bio *bio, int error)
1221 {
1222         int uptodate = test_bit(BIO_UPTODATE, &bio->bi_flags);
1223         r1bio_t *r1_bio = bio->bi_private;
1224         mddev_t *mddev = r1_bio->mddev;
1225         conf_t *conf = mddev->private;
1226         int i;
1227         int mirror=0;
1228
1229         for (i = 0; i < conf->raid_disks; i++)
1230                 if (r1_bio->bios[i] == bio) {
1231                         mirror = i;
1232                         break;
1233                 }
1234         if (!uptodate) {
1235                 sector_t sync_blocks = 0;
1236                 sector_t s = r1_bio->sector;
1237                 long sectors_to_go = r1_bio->sectors;
1238                 /* make sure these bits doesn't get cleared. */
1239                 do {
1240                         bitmap_end_sync(mddev->bitmap, s,
1241                                         &sync_blocks, 1);
1242                         s += sync_blocks;
1243                         sectors_to_go -= sync_blocks;
1244                 } while (sectors_to_go > 0);
1245                 md_error(mddev, conf->mirrors[mirror].rdev);
1246         }
1247
1248         update_head_pos(mirror, r1_bio);
1249
1250         if (atomic_dec_and_test(&r1_bio->remaining)) {
1251                 sector_t s = r1_bio->sectors;
1252                 put_buf(r1_bio);
1253                 md_done_sync(mddev, s, uptodate);
1254         }
1255 }
1256
1257 static int fix_sync_read_error(r1bio_t *r1_bio)
1258 {
1259         /* Try some synchronous reads of other devices to get
1260          * good data, much like with normal read errors.  Only
1261          * read into the pages we already have so we don't
1262          * need to re-issue the read request.
1263          * We don't need to freeze the array, because being in an
1264          * active sync request, there is no normal IO, and
1265          * no overlapping syncs.
1266          */
1267         mddev_t *mddev = r1_bio->mddev;
1268         conf_t *conf = mddev->private;
1269         struct bio *bio = r1_bio->bios[r1_bio->read_disk];
1270         sector_t sect = r1_bio->sector;
1271         int sectors = r1_bio->sectors;
1272         int idx = 0;
1273         mdk_rdev_t *rdev;
1274
1275         rdev = conf->mirrors[r1_bio->read_disk].rdev;
1276         if (test_bit(FailFast, &rdev->flags)) {
1277                 /* Don't try recovering from here - just fail it
1278                  * ... unless it is the last working device of course */
1279                 md_error(mddev, rdev);
1280                 if (test_bit(Faulty, &rdev->flags))
1281                         /* Don't try to read from here, but make sure
1282                          * put_buf does it's thing
1283                          */
1284                         r1_bio->bios[r1_bio->read_disk]->bi_end_io = end_sync_write;
1285         }
1286
1287         while(sectors) {
1288                 int s = sectors;
1289                 int d = r1_bio->read_disk;
1290                 int success = 0;
1291                 int start;
1292
1293                 if (s > (PAGE_SIZE>>9))
1294                         s = PAGE_SIZE >> 9;
1295                 do {
1296                         if (r1_bio->bios[d]->bi_end_io == end_sync_read) {
1297                                 /* No rcu protection needed here devices
1298                                  * can only be removed when no resync is
1299                                  * active, and resync is currently active
1300                                  */
1301                                 rdev = conf->mirrors[d].rdev;
1302                                 if (sync_page_io(rdev,
1303                                                  sect,
1304                                                  s<<9,
1305                                                  bio->bi_io_vec[idx].bv_page,
1306                                                  READ, false)) {
1307                                         success = 1;
1308                                         break;
1309                                 }
1310                         }
1311                         d++;
1312                         if (d == conf->raid_disks)
1313                                 d = 0;
1314                 } while (!success && d != r1_bio->read_disk);
1315
1316                 if (!success) {
1317                         char b[BDEVNAME_SIZE];
1318                         /* Cannot read from anywhere, array is toast */
1319                         md_error(mddev, conf->mirrors[r1_bio->read_disk].rdev);
1320                         printk(KERN_ALERT "md/raid1:%s: %s: unrecoverable I/O read error"
1321                                " for block %llu\n",
1322                                mdname(mddev),
1323                                bdevname(bio->bi_bdev, b),
1324                                (unsigned long long)r1_bio->sector);
1325                         md_done_sync(mddev, r1_bio->sectors, 0);
1326                         put_buf(r1_bio);
1327                         return 0;
1328                 }
1329
1330                 start = d;
1331                 /* write it back and re-read */
1332                 while (d != r1_bio->read_disk) {
1333                         if (d == 0)
1334                                 d = conf->raid_disks;
1335                         d--;
1336                         if (r1_bio->bios[d]->bi_end_io != end_sync_read)
1337                                 continue;
1338                         rdev = conf->mirrors[d].rdev;
1339                         if (sync_page_io(rdev,
1340                                          sect,
1341                                          s<<9,
1342                                          bio->bi_io_vec[idx].bv_page,
1343                                          WRITE, false) == 0) {
1344                                 r1_bio->bios[d]->bi_end_io = NULL;
1345                                 rdev_dec_pending(rdev, mddev);
1346                                 md_error(mddev, rdev);
1347                         } else
1348                                 atomic_add(s, &rdev->corrected_errors);
1349                 }
1350                 d = start;
1351                 while (d != r1_bio->read_disk) {
1352                         if (d == 0)
1353                                 d = conf->raid_disks;
1354                         d--;
1355                         if (r1_bio->bios[d]->bi_end_io != end_sync_read)
1356                                 continue;
1357                         rdev = conf->mirrors[d].rdev;
1358                         if (sync_page_io(rdev,
1359                                          sect,
1360                                          s<<9,
1361                                          bio->bi_io_vec[idx].bv_page,
1362                                          READ, false) == 0)
1363                                 md_error(mddev, rdev);
1364                 }
1365                 sectors -= s;
1366                 sect += s;
1367                 idx ++;
1368         }
1369         set_bit(R1BIO_Uptodate, &r1_bio->state);
1370         set_bit(BIO_UPTODATE, &bio->bi_flags);
1371         return 1;
1372 }
1373
1374 static int process_checks(r1bio_t *r1_bio)
1375 {
1376         /* We have read all readable devices.  If we haven't
1377          * got the block, then there is no hope left.
1378          * If we have, then we want to do a comparison
1379          * and skip the write if everything is the same.
1380          * If any blocks failed to read, then we need to
1381          * attempt an over-write
1382          */
1383         mddev_t *mddev = r1_bio->mddev;
1384         conf_t *conf = mddev->private;
1385         int primary;
1386         int i;
1387
1388         for (primary = 0; primary < conf->raid_disks; primary++)
1389                 if (r1_bio->bios[primary]->bi_end_io == end_sync_read &&
1390                     test_bit(BIO_UPTODATE, &r1_bio->bios[primary]->bi_flags)) {
1391                         r1_bio->bios[primary]->bi_end_io = NULL;
1392                         rdev_dec_pending(conf->mirrors[primary].rdev, mddev);
1393                         break;
1394                 }
1395         r1_bio->read_disk = primary;
1396         for (i = 0; i < conf->raid_disks; i++) {
1397                 int j;
1398                 int vcnt = r1_bio->sectors >> (PAGE_SHIFT- 9);
1399                 struct bio *pbio = r1_bio->bios[primary];
1400                 struct bio *sbio = r1_bio->bios[i];
1401                 int size;
1402
1403                 if (r1_bio->bios[i]->bi_end_io != end_sync_read)
1404                         continue;
1405
1406                 if (test_bit(BIO_UPTODATE, &sbio->bi_flags)) {
1407                         for (j = vcnt; j-- ; ) {
1408                                 struct page *p, *s;
1409                                 p = pbio->bi_io_vec[j].bv_page;
1410                                 s = sbio->bi_io_vec[j].bv_page;
1411                                 if (memcmp(page_address(p),
1412                                            page_address(s),
1413                                            PAGE_SIZE))
1414                                         break;
1415                         }
1416                 } else
1417                         j = 0;
1418                 if (j >= 0)
1419                         mddev->resync_mismatches += r1_bio->sectors;
1420                 if (j < 0 || (test_bit(MD_RECOVERY_CHECK, &mddev->recovery)
1421                               && test_bit(BIO_UPTODATE, &sbio->bi_flags))) {
1422                         /* No need to write to this device. */
1423                         sbio->bi_end_io = NULL;
1424                         rdev_dec_pending(conf->mirrors[i].rdev, mddev);
1425                         continue;
1426                 }
1427                 /* fixup the bio for reuse */
1428                 sbio->bi_vcnt = vcnt;
1429                 sbio->bi_size = r1_bio->sectors << 9;
1430                 sbio->bi_idx = 0;
1431                 sbio->bi_phys_segments = 0;
1432                 sbio->bi_flags &= ~(BIO_POOL_MASK - 1);
1433                 sbio->bi_flags |= 1 << BIO_UPTODATE;
1434                 sbio->bi_next = NULL;
1435                 sbio->bi_sector = r1_bio->sector +
1436                         conf->mirrors[i].rdev->data_offset;
1437                 sbio->bi_bdev = conf->mirrors[i].rdev->bdev;
1438                 size = sbio->bi_size;
1439                 for (j = 0; j < vcnt ; j++) {
1440                         struct bio_vec *bi;
1441                         bi = &sbio->bi_io_vec[j];
1442                         bi->bv_offset = 0;
1443                         if (size > PAGE_SIZE)
1444                                 bi->bv_len = PAGE_SIZE;
1445                         else
1446                                 bi->bv_len = size;
1447                         size -= PAGE_SIZE;
1448                         memcpy(page_address(bi->bv_page),
1449                                page_address(pbio->bi_io_vec[j].bv_page),
1450                                PAGE_SIZE);
1451                 }
1452         }
1453         return 0;
1454 }
1455
1456 static void sync_request_write(mddev_t *mddev, r1bio_t *r1_bio)
1457 {
1458         conf_t *conf = mddev->private;
1459         int i;
1460         int disks = conf->raid_disks;
1461         struct bio *bio, *wbio;
1462
1463         bio = r1_bio->bios[r1_bio->read_disk];
1464
1465         if (!test_bit(R1BIO_Uptodate, &r1_bio->state))
1466                 /* ouch - failed to read all of that. */
1467                 if (!fix_sync_read_error(r1_bio))
1468                         return;
1469
1470         if (test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery))
1471                 if (process_checks(r1_bio) < 0)
1472                         return;
1473         /*
1474          * schedule writes
1475          */
1476         atomic_set(&r1_bio->remaining, 1);
1477         for (i = 0; i < disks ; i++) {
1478                 wbio = r1_bio->bios[i];
1479                 if (wbio->bi_end_io == NULL ||
1480                     (wbio->bi_end_io == end_sync_read &&
1481                      (i == r1_bio->read_disk ||
1482                       !test_bit(MD_RECOVERY_SYNC, &mddev->recovery))))
1483                         continue;
1484
1485                 wbio->bi_rw = WRITE;
1486                 if (test_bit(FailFast, &conf->mirrors[i].rdev->flags))
1487                         wbio->bi_rw |= REQ_FAILFAST_DEV;
1488
1489                 wbio->bi_end_io = end_sync_write;
1490                 atomic_inc(&r1_bio->remaining);
1491                 md_sync_acct(conf->mirrors[i].rdev->bdev, wbio->bi_size >> 9);
1492
1493                 generic_make_request(wbio);
1494         }
1495
1496         if (atomic_dec_and_test(&r1_bio->remaining)) {
1497                 /* if we're here, all write(s) have completed, so clean up */
1498                 md_done_sync(mddev, r1_bio->sectors, 1);
1499                 put_buf(r1_bio);
1500         }
1501 }
1502
1503 /*
1504  * This is a kernel thread which:
1505  *
1506  *      1.      Retries failed read operations on working mirrors.
1507  *      2.      Updates the raid superblock when problems encounter.
1508  *      3.      Performs writes following reads for array syncronising.
1509  */
1510
1511 static void fix_read_error(conf_t *conf, int read_disk,
1512                            sector_t sect, int sectors)
1513 {
1514         mddev_t *mddev = conf->mddev;
1515         while(sectors) {
1516                 int s = sectors;
1517                 int d = read_disk;
1518                 int success = 0;
1519                 int start;
1520                 mdk_rdev_t *rdev;
1521
1522                 if (s > (PAGE_SIZE>>9))
1523                         s = PAGE_SIZE >> 9;
1524
1525                 do {
1526                         /* Note: no rcu protection needed here
1527                          * as this is synchronous in the raid1d thread
1528                          * which is the thread that might remove
1529                          * a device.  If raid1d ever becomes multi-threaded....
1530                          */
1531                         rdev = conf->mirrors[d].rdev;
1532                         if (rdev &&
1533                             test_bit(In_sync, &rdev->flags) &&
1534                             sync_page_io(rdev, sect, s<<9,
1535                                          conf->tmppage, READ, false))
1536                                 success = 1;
1537                         else {
1538                                 d++;
1539                                 if (d == conf->raid_disks)
1540                                         d = 0;
1541                         }
1542                 } while (!success && d != read_disk);
1543
1544                 if (!success) {
1545                         /* Cannot read from anywhere -- bye bye array */
1546                         md_error(mddev, conf->mirrors[read_disk].rdev);
1547                         break;
1548                 }
1549                 /* write it back and re-read */
1550                 start = d;
1551                 while (d != read_disk) {
1552                         if (d==0)
1553                                 d = conf->raid_disks;
1554                         d--;
1555                         rdev = conf->mirrors[d].rdev;
1556                         if (rdev &&
1557                             test_bit(In_sync, &rdev->flags)) {
1558                                 if (sync_page_io(rdev, sect, s<<9,
1559                                                  conf->tmppage, WRITE, false)
1560                                     == 0)
1561                                         /* Well, this device is dead */
1562                                         md_error(mddev, rdev);
1563                         }
1564                 }
1565                 d = start;
1566                 while (d != read_disk) {
1567                         char b[BDEVNAME_SIZE];
1568                         if (d==0)
1569                                 d = conf->raid_disks;
1570                         d--;
1571                         rdev = conf->mirrors[d].rdev;
1572                         if (rdev &&
1573                             test_bit(In_sync, &rdev->flags)) {
1574                                 if (sync_page_io(rdev, sect, s<<9,
1575                                                  conf->tmppage, READ, false)
1576                                     == 0)
1577                                         /* Well, this device is dead */
1578                                         md_error(mddev, rdev);
1579                                 else {
1580                                         atomic_add(s, &rdev->corrected_errors);
1581                                         printk(KERN_INFO
1582                                                "md/raid1:%s: read error corrected "
1583                                                "(%d sectors at %llu on %s)\n",
1584                                                mdname(mddev), s,
1585                                                (unsigned long long)(sect +
1586                                                    rdev->data_offset),
1587                                                bdevname(rdev->bdev, b));
1588                                 }
1589                         }
1590                 }
1591                 sectors -= s;
1592                 sect += s;
1593         }
1594 }
1595
1596 static void bi_complete(struct bio *bio, int error)
1597 {
1598         complete((struct completion *)bio->bi_private);
1599 }
1600
1601 static int submit_bio_wait(int rw, struct bio *bio)
1602 {
1603         struct completion event;
1604         rw |= REQ_SYNC;
1605
1606         init_completion(&event);
1607         bio->bi_private = &event;
1608         bio->bi_end_io = bi_complete;
1609         submit_bio(rw, bio);
1610         wait_for_completion(&event);
1611
1612         return test_bit(BIO_UPTODATE, &bio->bi_flags);
1613 }
1614
1615 static void handle_write_error(conf_t *conf, r1bio_t *r1_bio)
1616 {
1617         int m;
1618
1619         for (m = 0; m < conf->raid_disks; m++) {
1620                 struct bio *wbio = r1_bio->bios[m];
1621                 mdk_rdev_t *rdev;
1622                 if (!wbio)
1623                         continue;
1624                 /* We got a write error on this FailFast
1625                  * device.  Need to try again without
1626                  * FailFast as it is only device remaining
1627                  */
1628                 wbio->bi_sector = r1_bio->sector;
1629                 wbio->bi_flags &= ~(BIO_POOL_MASK-1);
1630                 wbio->bi_flags |= 1 << BIO_UPTODATE;
1631                 wbio->bi_rw = WRITE;
1632                 wbio->bi_vcnt = r1_bio->master_bio->bi_vcnt;
1633                 memcpy(wbio->bi_io_vec,
1634                        r1_bio->master_bio->bi_io_vec,
1635                        wbio->bi_vcnt *sizeof(struct bio_vec));
1636                 wbio->bi_idx = r1_bio->master_bio->bi_idx;
1637
1638                 wbio->bi_size = r1_bio->sectors << 9;
1639                 wbio->bi_next = NULL;
1640
1641                 rdev = conf->mirrors[m].rdev;
1642                 wbio->bi_sector += rdev->data_offset;
1643                 wbio->bi_bdev = rdev->bdev;
1644                 if (submit_bio_wait(WRITE, wbio) != 0)
1645                         set_bit(R1BIO_Uptodate, &r1_bio->state);
1646                 else
1647                         set_bit(R1BIO_Degraded, &r1_bio->state);
1648                 rdev_dec_pending(rdev, conf->mddev);
1649         }
1650         /* Now we can really finish the request */
1651         atomic_inc(&r1_bio->remaining);
1652         clear_bit(R1BIO_WriteError, &r1_bio->state);
1653         r1_bio_write_done(r1_bio);
1654 }
1655
1656 static void raid1d(mddev_t *mddev)
1657 {
1658         r1bio_t *r1_bio;
1659         struct bio *bio;
1660         unsigned long flags;
1661         conf_t *conf = mddev->private;
1662         struct list_head *head = &conf->retry_list;
1663         mdk_rdev_t *rdev;
1664         struct blk_plug plug;
1665
1666         md_check_recovery(mddev);
1667
1668         blk_start_plug(&plug);
1669         for (;;) {
1670                 char b[BDEVNAME_SIZE];
1671
1672                 if (atomic_read(&mddev->plug_cnt) == 0)
1673                         flush_pending_writes(conf);
1674
1675                 spin_lock_irqsave(&conf->device_lock, flags);
1676                 if (list_empty(head)) {
1677                         spin_unlock_irqrestore(&conf->device_lock, flags);
1678                         break;
1679                 }
1680                 r1_bio = list_entry(head->prev, r1bio_t, retry_list);
1681                 list_del(head->prev);
1682                 conf->nr_queued--;
1683                 spin_unlock_irqrestore(&conf->device_lock, flags);
1684
1685                 mddev = r1_bio->mddev;
1686                 conf = mddev->private;
1687                 if (test_bit(R1BIO_WriteError, &r1_bio->state))
1688                         handle_write_error(conf, r1_bio);
1689                 else if (test_bit(R1BIO_IsSync, &r1_bio->state))
1690                         sync_request_write(mddev, r1_bio);
1691                 else {
1692                         int disk;
1693
1694                         /* we got a read error. Maybe the drive is bad.  Maybe just
1695                          * the block and we can fix it.
1696                          * We freeze all other IO, and try reading the block from
1697                          * other devices.  When we find one, we re-write
1698                          * and check it that fixes the read error.
1699                          * This is all done synchronously while the array is
1700                          * frozen
1701                          */
1702                         rdev = conf->mirrors[r1_bio->read_disk].rdev;
1703                         if (mddev->ro == 0
1704                             && !test_bit(FailFast, &rdev->flags)) {
1705                                 freeze_array(conf);
1706                                 fix_read_error(conf, r1_bio->read_disk,
1707                                                r1_bio->sector,
1708                                                r1_bio->sectors);
1709                                 unfreeze_array(conf);
1710                         } else
1711                                 md_error(mddev,
1712                                          conf->mirrors[r1_bio->read_disk].rdev);
1713                         rdev_dec_pending(conf->mirrors[r1_bio->read_disk].rdev, conf->mddev);
1714
1715                         bio = r1_bio->bios[r1_bio->read_disk];
1716                         r1_bio->bios[r1_bio->read_disk] =
1717                                 mddev->ro ? IO_BLOCKED : NULL;
1718                         if ((disk=read_balance(conf, r1_bio)) == -1) {
1719                                 printk(KERN_ALERT "md/raid1:%s: %s: unrecoverable I/O"
1720                                        " read error for block %llu\n",
1721                                        mdname(mddev),
1722                                        bdevname(bio->bi_bdev,b),
1723                                        (unsigned long long)r1_bio->sector);
1724                                 bio_put(bio);
1725                                 raid_end_bio_io(r1_bio);
1726                         } else {
1727                                 const unsigned long do_sync = r1_bio->master_bio->bi_rw & REQ_SYNC;
1728                                 r1_bio->read_disk = disk;
1729                                 bio_put(bio);
1730                                 bio = bio_clone_mddev(r1_bio->master_bio,
1731                                                       GFP_NOIO, mddev);
1732                                 r1_bio->bios[r1_bio->read_disk] = bio;
1733                                 rdev = conf->mirrors[disk].rdev;
1734                                 if (printk_ratelimit())
1735                                         printk(KERN_ERR "md/raid1:%s: redirecting sector %llu to"
1736                                                " other mirror: %s\n",
1737                                                mdname(mddev),
1738                                                (unsigned long long)r1_bio->sector,
1739                                                bdevname(rdev->bdev,b));
1740                                 bio->bi_sector = r1_bio->sector + rdev->data_offset;
1741                                 bio->bi_bdev = rdev->bdev;
1742                                 bio->bi_end_io = raid1_end_read_request;
1743                                 bio->bi_rw = READ | do_sync;
1744                                 if (test_bit(FailFast, &rdev->flags) &&
1745                                     test_bit(R1BIO_FailFast, &r1_bio->state))
1746                                         bio->bi_rw |= REQ_FAILFAST_DEV;
1747                                 bio->bi_private = r1_bio;
1748                                 generic_make_request(bio);
1749                         }
1750                 }
1751                 cond_resched();
1752         }
1753         blk_finish_plug(&plug);
1754 }
1755
1756
1757 static int init_resync(conf_t *conf)
1758 {
1759         int buffs;
1760
1761         buffs = RESYNC_WINDOW / RESYNC_BLOCK_SIZE;
1762         BUG_ON(conf->r1buf_pool);
1763         conf->r1buf_pool = mempool_create(buffs, r1buf_pool_alloc, r1buf_pool_free,
1764                                           conf->poolinfo);
1765         if (!conf->r1buf_pool)
1766                 return -ENOMEM;
1767         conf->next_resync = 0;
1768         return 0;
1769 }
1770
1771 /*
1772  * perform a "sync" on one "block"
1773  *
1774  * We need to make sure that no normal I/O request - particularly write
1775  * requests - conflict with active sync requests.
1776  *
1777  * This is achieved by tracking pending requests and a 'barrier' concept
1778  * that can be installed to exclude normal IO requests.
1779  */
1780
1781 static sector_t sync_request(mddev_t *mddev, sector_t sector_nr, int *skipped, int go_faster)
1782 {
1783         conf_t *conf = mddev->private;
1784         r1bio_t *r1_bio;
1785         struct bio *bio;
1786         sector_t max_sector, nr_sectors;
1787         int disk = -1;
1788         int i;
1789         int wonly = -1;
1790         int write_targets = 0, read_targets = 0;
1791         sector_t sync_blocks;
1792         int still_degraded = 0;
1793
1794         if (!conf->r1buf_pool)
1795                 if (init_resync(conf))
1796                         return 0;
1797
1798         max_sector = mddev->dev_sectors;
1799         if (sector_nr >= max_sector) {
1800                 /* If we aborted, we need to abort the
1801                  * sync on the 'current' bitmap chunk (there will
1802                  * only be one in raid1 resync.
1803                  * We can find the current addess in mddev->curr_resync
1804                  */
1805                 if (mddev->curr_resync < max_sector) /* aborted */
1806                         bitmap_end_sync(mddev->bitmap, mddev->curr_resync,
1807                                                 &sync_blocks, 1);
1808                 else /* completed sync */
1809                         conf->fullsync = 0;
1810
1811                 bitmap_close_sync(mddev->bitmap);
1812                 close_sync(conf);
1813                 return 0;
1814         }
1815
1816         if (mddev->bitmap == NULL &&
1817             mddev->recovery_cp == MaxSector &&
1818             !test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery) &&
1819             conf->fullsync == 0) {
1820                 *skipped = 1;
1821                 return max_sector - sector_nr;
1822         }
1823         /* before building a request, check if we can skip these blocks..
1824          * This call the bitmap_start_sync doesn't actually record anything
1825          */
1826         if (!bitmap_start_sync(mddev->bitmap, sector_nr, &sync_blocks, 1) &&
1827             !conf->fullsync && !test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery)) {
1828                 /* We can skip this block, and probably several more */
1829                 *skipped = 1;
1830                 return sync_blocks;
1831         }
1832         /*
1833          * If there is non-resync activity waiting for a turn,
1834          * and resync is going fast enough,
1835          * then let it though before starting on this new sync request.
1836          */
1837         if (!go_faster && conf->nr_waiting)
1838                 msleep_interruptible(1000);
1839
1840         bitmap_cond_end_sync(mddev->bitmap, sector_nr);
1841         r1_bio = mempool_alloc(conf->r1buf_pool, GFP_NOIO);
1842         raise_barrier(conf);
1843
1844         conf->next_resync = sector_nr;
1845
1846         rcu_read_lock();
1847         /*
1848          * If we get a correctably read error during resync or recovery,
1849          * we might want to read from a different device.  So we
1850          * flag all drives that could conceivably be read from for READ,
1851          * and any others (which will be non-In_sync devices) for WRITE.
1852          * If a read fails, we try reading from something else for which READ
1853          * is OK.
1854          */
1855
1856         r1_bio->mddev = mddev;
1857         r1_bio->sector = sector_nr;
1858         r1_bio->state = 0;
1859         set_bit(R1BIO_IsSync, &r1_bio->state);
1860
1861         for (i=0; i < conf->raid_disks; i++) {
1862                 mdk_rdev_t *rdev;
1863                 bio = r1_bio->bios[i];
1864
1865                 /* take from bio_init */
1866                 bio->bi_next = NULL;
1867                 bio->bi_flags &= ~(BIO_POOL_MASK-1);
1868                 bio->bi_flags |= 1 << BIO_UPTODATE;
1869                 bio->bi_comp_cpu = -1;
1870                 bio->bi_rw = READ;
1871                 bio->bi_vcnt = 0;
1872                 bio->bi_idx = 0;
1873                 bio->bi_phys_segments = 0;
1874                 bio->bi_size = 0;
1875                 bio->bi_end_io = NULL;
1876                 bio->bi_private = NULL;
1877
1878                 rdev = rcu_dereference(conf->mirrors[i].rdev);
1879                 if (rdev == NULL ||
1880                            test_bit(Faulty, &rdev->flags)) {
1881                         still_degraded = 1;
1882                         continue;
1883                 } else if (!test_bit(In_sync, &rdev->flags)) {
1884                         bio->bi_rw = WRITE;
1885                         bio->bi_end_io = end_sync_write;
1886                         write_targets ++;
1887                 } else {
1888                         /* may need to read from here */
1889                         bio->bi_rw = READ;
1890                         bio->bi_end_io = end_sync_read;
1891                         if (test_bit(WriteMostly, &rdev->flags)) {
1892                                 if (wonly < 0)
1893                                         wonly = i;
1894                         } else {
1895                                 if (disk < 0)
1896                                         disk = i;
1897                         }
1898                         read_targets++;
1899                 }
1900                 atomic_inc(&rdev->nr_pending);
1901                 bio->bi_sector = sector_nr + rdev->data_offset;
1902                 bio->bi_bdev = rdev->bdev;
1903                 bio->bi_private = r1_bio;
1904                 if (test_bit(FailFast, &rdev->flags))
1905                         bio->bi_rw |= REQ_FAILFAST_DEV;
1906         }
1907         rcu_read_unlock();
1908         if (disk < 0)
1909                 disk = wonly;
1910         r1_bio->read_disk = disk;
1911
1912         if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery) && read_targets > 0)
1913                 /* extra read targets are also write targets */
1914                 write_targets += read_targets-1;
1915
1916         if (write_targets == 0 || read_targets == 0) {
1917                 /* There is nowhere to write, so all non-sync
1918                  * drives must be failed - so we are finished
1919                  */
1920                 sector_t rv = max_sector - sector_nr;
1921                 *skipped = 1;
1922                 put_buf(r1_bio);
1923                 return rv;
1924         }
1925
1926         if (max_sector > mddev->resync_max)
1927                 max_sector = mddev->resync_max; /* Don't do IO beyond here */
1928         nr_sectors = 0;
1929         sync_blocks = 0;
1930         do {
1931                 struct page *page;
1932                 int len = PAGE_SIZE;
1933                 if (sector_nr + (len>>9) > max_sector)
1934                         len = (max_sector - sector_nr) << 9;
1935                 if (len == 0)
1936                         break;
1937                 if (sync_blocks == 0) {
1938                         if (!bitmap_start_sync(mddev->bitmap, sector_nr,
1939                                                &sync_blocks, still_degraded) &&
1940                             !conf->fullsync &&
1941                             !test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery))
1942                                 break;
1943                         BUG_ON(sync_blocks < (PAGE_SIZE>>9));
1944                         if ((len >> 9) > sync_blocks)
1945                                 len = sync_blocks<<9;
1946                 }
1947
1948                 for (i=0 ; i < conf->raid_disks; i++) {
1949                         bio = r1_bio->bios[i];
1950                         if (bio->bi_end_io) {
1951                                 page = bio->bi_io_vec[bio->bi_vcnt].bv_page;
1952                                 if (bio_add_page(bio, page, len, 0) == 0) {
1953                                         /* stop here */
1954                                         bio->bi_io_vec[bio->bi_vcnt].bv_page = page;
1955                                         while (i > 0) {
1956                                                 i--;
1957                                                 bio = r1_bio->bios[i];
1958                                                 if (bio->bi_end_io==NULL)
1959                                                         continue;
1960                                                 /* remove last page from this bio */
1961                                                 bio->bi_vcnt--;
1962                                                 bio->bi_size -= len;
1963                                                 bio->bi_flags &= ~(1<< BIO_SEG_VALID);
1964                                         }
1965                                         goto bio_full;
1966                                 }
1967                         }
1968                 }
1969                 nr_sectors += len>>9;
1970                 sector_nr += len>>9;
1971                 sync_blocks -= (len>>9);
1972         } while (r1_bio->bios[disk]->bi_vcnt < RESYNC_PAGES);
1973  bio_full:
1974         r1_bio->sectors = nr_sectors;
1975
1976         /* For a user-requested sync, we read all readable devices and do a
1977          * compare
1978          */
1979         if (test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery)) {
1980                 atomic_set(&r1_bio->remaining, read_targets);
1981                 for (i=0; i<conf->raid_disks; i++) {
1982                         bio = r1_bio->bios[i];
1983                         if (bio->bi_end_io == end_sync_read) {
1984                                 md_sync_acct(bio->bi_bdev, nr_sectors);
1985                                 if (read_targets == 1)
1986                                         bio->bi_rw &= ~REQ_FAILFAST_MASK;
1987                                 generic_make_request(bio);
1988                         }
1989                 }
1990         } else {
1991                 atomic_set(&r1_bio->remaining, 1);
1992                 bio = r1_bio->bios[r1_bio->read_disk];
1993                 md_sync_acct(bio->bi_bdev, nr_sectors);
1994                 if (read_targets == 1)
1995                         bio->bi_rw &= ~REQ_FAILFAST_MASK;
1996                 generic_make_request(bio);
1997
1998         }
1999         return nr_sectors;
2000 }
2001
2002 static sector_t raid1_size(mddev_t *mddev, sector_t sectors, int raid_disks)
2003 {
2004         if (sectors)
2005                 return sectors;
2006
2007         return mddev->dev_sectors;
2008 }
2009
2010 static conf_t *setup_conf(mddev_t *mddev)
2011 {
2012         conf_t *conf;
2013         int i;
2014         mirror_info_t *disk;
2015         mdk_rdev_t *rdev;
2016         int err = -ENOMEM;
2017
2018         conf = kzalloc(sizeof(conf_t), GFP_KERNEL);
2019         if (!conf)
2020                 goto abort;
2021
2022         conf->mirrors = kzalloc(sizeof(struct mirror_info)*mddev->raid_disks,
2023                                  GFP_KERNEL);
2024         if (!conf->mirrors)
2025                 goto abort;
2026
2027         conf->tmppage = alloc_page(GFP_KERNEL);
2028         if (!conf->tmppage)
2029                 goto abort;
2030
2031         conf->poolinfo = kzalloc(sizeof(*conf->poolinfo), GFP_KERNEL);
2032         if (!conf->poolinfo)
2033                 goto abort;
2034         conf->poolinfo->raid_disks = mddev->raid_disks;
2035         conf->r1bio_pool = mempool_create(NR_RAID1_BIOS, r1bio_pool_alloc,
2036                                           r1bio_pool_free,
2037                                           conf->poolinfo);
2038         if (!conf->r1bio_pool)
2039                 goto abort;
2040
2041         conf->poolinfo->mddev = mddev;
2042
2043         spin_lock_init(&conf->device_lock);
2044         list_for_each_entry(rdev, &mddev->disks, same_set) {
2045                 int disk_idx = rdev->raid_disk;
2046                 if (disk_idx >= mddev->raid_disks
2047                     || disk_idx < 0)
2048                         continue;
2049                 disk = conf->mirrors + disk_idx;
2050
2051                 disk->rdev = rdev;
2052
2053                 disk->head_position = 0;
2054         }
2055         conf->raid_disks = mddev->raid_disks;
2056         conf->mddev = mddev;
2057         INIT_LIST_HEAD(&conf->retry_list);
2058
2059         spin_lock_init(&conf->resync_lock);
2060         init_waitqueue_head(&conf->wait_barrier);
2061
2062         bio_list_init(&conf->pending_bio_list);
2063         conf->pending_count = 0;
2064
2065         conf->last_used = -1;
2066         for (i = 0; i < conf->raid_disks; i++) {
2067
2068                 disk = conf->mirrors + i;
2069
2070                 if (!disk->rdev ||
2071                     !test_bit(In_sync, &disk->rdev->flags)) {
2072                         disk->head_position = 0;
2073                         if (disk->rdev)
2074                                 conf->fullsync = 1;
2075                 } else if (conf->last_used < 0)
2076                         /*
2077                          * The first working device is used as a
2078                          * starting point to read balancing.
2079                          */
2080                         conf->last_used = i;
2081         }
2082
2083         err = -EIO;
2084         if (conf->last_used < 0) {
2085                 printk(KERN_ERR "md/raid1:%s: no operational mirrors\n",
2086                        mdname(mddev));
2087                 goto abort;
2088         }
2089         err = -ENOMEM;
2090         conf->thread = md_register_thread(raid1d, mddev, NULL);
2091         if (!conf->thread) {
2092                 printk(KERN_ERR
2093                        "md/raid1:%s: couldn't allocate thread\n",
2094                        mdname(mddev));
2095                 goto abort;
2096         }
2097
2098         return conf;
2099
2100  abort:
2101         if (conf) {
2102                 if (conf->r1bio_pool)
2103                         mempool_destroy(conf->r1bio_pool);
2104                 kfree(conf->mirrors);
2105                 safe_put_page(conf->tmppage);
2106                 kfree(conf->poolinfo);
2107                 kfree(conf);
2108         }
2109         return ERR_PTR(err);
2110 }
2111
2112 static int run(mddev_t *mddev)
2113 {
2114         conf_t *conf;
2115         int i;
2116         mdk_rdev_t *rdev;
2117
2118         if (mddev->level != 1) {
2119                 printk(KERN_ERR "md/raid1:%s: raid level not set to mirroring (%d)\n",
2120                        mdname(mddev), mddev->level);
2121                 return -EIO;
2122         }
2123         if (mddev->reshape_position != MaxSector) {
2124                 printk(KERN_ERR "md/raid1:%s: reshape_position set but not supported\n",
2125                        mdname(mddev));
2126                 return -EIO;
2127         }
2128         /*
2129          * copy the already verified devices into our private RAID1
2130          * bookkeeping area. [whatever we allocate in run(),
2131          * should be freed in stop()]
2132          */
2133         if (mddev->private == NULL)
2134                 conf = setup_conf(mddev);
2135         else
2136                 conf = mddev->private;
2137
2138         if (IS_ERR(conf))
2139                 return PTR_ERR(conf);
2140
2141         list_for_each_entry(rdev, &mddev->disks, same_set) {
2142                 if (!mddev->gendisk)
2143                         continue;
2144                 disk_stack_limits(mddev->gendisk, rdev->bdev,
2145                                   rdev->data_offset << 9);
2146                 /* as we don't honour merge_bvec_fn, we must never risk
2147                  * violating it, so limit ->max_segments to 1 lying within
2148                  * a single page, as a one page request is never in violation.
2149                  */
2150                 if (rdev->bdev->bd_disk->queue->merge_bvec_fn) {
2151                         blk_queue_max_segments(mddev->queue, 1);
2152                         blk_queue_segment_boundary(mddev->queue,
2153                                                    PAGE_CACHE_SIZE - 1);
2154                 }
2155         }
2156
2157         mddev->degraded = 0;
2158         for (i=0; i < conf->raid_disks; i++)
2159                 if (conf->mirrors[i].rdev == NULL ||
2160                     !test_bit(In_sync, &conf->mirrors[i].rdev->flags) ||
2161                     test_bit(Faulty, &conf->mirrors[i].rdev->flags))
2162                         mddev->degraded++;
2163
2164         if (conf->raid_disks - mddev->degraded == 1)
2165                 mddev->recovery_cp = MaxSector;
2166
2167         if (mddev->recovery_cp != MaxSector)
2168                 printk(KERN_NOTICE "md/raid1:%s: not clean"
2169                        " -- starting background reconstruction\n",
2170                        mdname(mddev));
2171         printk(KERN_INFO 
2172                 "md/raid1:%s: active with %d out of %d mirrors\n",
2173                 mdname(mddev), mddev->raid_disks - mddev->degraded, 
2174                 mddev->raid_disks);
2175
2176         /*
2177          * Ok, everything is just fine now
2178          */
2179         mddev->thread = conf->thread;
2180         conf->thread = NULL;
2181         rcu_assign_pointer(mddev->private, conf);
2182
2183         md_set_array_sectors(mddev, raid1_size(mddev, 0, 0));
2184
2185         if (mddev->queue) {
2186                 mddev->queue->backing_dev_info.congested_fn = raid1_congested;
2187                 mddev->queue->backing_dev_info.congested_data = mddev;
2188         }
2189         return md_integrity_register(mddev);
2190 }
2191
2192 static int stop(mddev_t *mddev)
2193 {
2194         conf_t *conf = mddev->private;
2195         struct bitmap *bitmap = mddev->bitmap;
2196
2197         /* wait for behind writes to complete */
2198         if (bitmap && atomic_read(&bitmap->behind_writes) > 0) {
2199                 printk(KERN_INFO "md/raid1:%s: behind writes in progress - waiting to stop.\n",
2200                        mdname(mddev));
2201                 /* need to kick something here to make sure I/O goes? */
2202                 wait_event(bitmap->behind_wait,
2203                            atomic_read(&bitmap->behind_writes) == 0);
2204         }
2205
2206         raise_barrier(conf);
2207         lower_barrier(conf);
2208
2209         md_unregister_thread(&mddev->thread);
2210         if (conf->r1bio_pool)
2211                 mempool_destroy(conf->r1bio_pool);
2212         kfree(conf->mirrors);
2213         kfree(conf->poolinfo);
2214         kfree(conf);
2215         mddev->private = NULL;
2216         return 0;
2217 }
2218
2219 static int raid1_resize(mddev_t *mddev, sector_t sectors)
2220 {
2221         /* no resync is happening, and there is enough space
2222          * on all devices, so we can resize.
2223          * We need to make sure resync covers any new space.
2224          * If the array is shrinking we should possibly wait until
2225          * any io in the removed space completes, but it hardly seems
2226          * worth it.
2227          */
2228         sector_t newsize = raid1_size(mddev, sectors, 0);
2229         if (mddev->external_size &&
2230             mddev->array_sectors > newsize)
2231                 return -EINVAL;
2232         if (mddev->bitmap) {
2233                 int ret = bitmap_resize(mddev->bitmap, newsize, 0, 0);
2234                 if (ret)
2235                         return ret;
2236         }
2237         md_set_array_sectors(mddev, newsize);
2238         set_capacity(mddev->gendisk, mddev->array_sectors);
2239         revalidate_disk(mddev->gendisk);
2240         if (sectors > mddev->dev_sectors &&
2241             mddev->recovery_cp > mddev->dev_sectors) {
2242                 mddev->recovery_cp = mddev->dev_sectors;
2243                 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
2244         }
2245         mddev->dev_sectors = sectors;
2246         mddev->resync_max_sectors = sectors;
2247         return 0;
2248 }
2249
2250 static int raid1_reshape(mddev_t *mddev)
2251 {
2252         /* We need to:
2253          * 1/ resize the r1bio_pool
2254          * 2/ resize conf->mirrors
2255          *
2256          * We allocate a new r1bio_pool if we can.
2257          * Then raise a device barrier and wait until all IO stops.
2258          * Then resize conf->mirrors and swap in the new r1bio pool.
2259          *
2260          * At the same time, we "pack" the devices so that all the missing
2261          * devices have the higher raid_disk numbers.
2262          */
2263         mempool_t *newpool, *oldpool;
2264         struct pool_info *newpoolinfo;
2265         mirror_info_t *newmirrors;
2266         conf_t *conf = mddev->private;
2267         int cnt, raid_disks;
2268         unsigned long flags;
2269         int d, d2, err;
2270
2271         /* Cannot change chunk_size, layout, or level */
2272         if (mddev->chunk_sectors != mddev->new_chunk_sectors ||
2273             mddev->layout != mddev->new_layout ||
2274             mddev->level != mddev->new_level) {
2275                 mddev->new_chunk_sectors = mddev->chunk_sectors;
2276                 mddev->new_layout = mddev->layout;
2277                 mddev->new_level = mddev->level;
2278                 return -EINVAL;
2279         }
2280
2281         err = md_allow_write(mddev);
2282         if (err)
2283                 return err;
2284
2285         raid_disks = mddev->raid_disks + mddev->delta_disks;
2286
2287         if (raid_disks < conf->raid_disks) {
2288                 cnt=0;
2289                 for (d= 0; d < conf->raid_disks; d++)
2290                         if (conf->mirrors[d].rdev)
2291                                 cnt++;
2292                 if (cnt > raid_disks)
2293                         return -EBUSY;
2294         }
2295
2296         newpoolinfo = kmalloc(sizeof(*newpoolinfo), GFP_KERNEL);
2297         if (!newpoolinfo)
2298                 return -ENOMEM;
2299         newpoolinfo->mddev = mddev;
2300         newpoolinfo->raid_disks = raid_disks;
2301
2302         newpool = mempool_create(NR_RAID1_BIOS, r1bio_pool_alloc,
2303                                  r1bio_pool_free, newpoolinfo);
2304         if (!newpool) {
2305                 kfree(newpoolinfo);
2306                 return -ENOMEM;
2307         }
2308         newmirrors = kzalloc(sizeof(struct mirror_info) * raid_disks, GFP_KERNEL);
2309         if (!newmirrors) {
2310                 kfree(newpoolinfo);
2311                 mempool_destroy(newpool);
2312                 return -ENOMEM;
2313         }
2314
2315         raise_barrier(conf);
2316
2317         /* ok, everything is stopped */
2318         oldpool = conf->r1bio_pool;
2319         conf->r1bio_pool = newpool;
2320
2321         for (d = d2 = 0; d < conf->raid_disks; d++) {
2322                 mdk_rdev_t *rdev = conf->mirrors[d].rdev;
2323                 if (rdev && rdev->raid_disk != d2) {
2324                         char nm[20];
2325                         sprintf(nm, "rd%d", rdev->raid_disk);
2326                         sysfs_remove_link(&mddev->kobj, nm);
2327                         rdev->raid_disk = d2;
2328                         sprintf(nm, "rd%d", rdev->raid_disk);
2329                         sysfs_remove_link(&mddev->kobj, nm);
2330                         if (sysfs_create_link(&mddev->kobj,
2331                                               &rdev->kobj, nm))
2332                                 printk(KERN_WARNING
2333                                        "md/raid1:%s: cannot register "
2334                                        "%s\n",
2335                                        mdname(mddev), nm);
2336                 }
2337                 if (rdev)
2338                         newmirrors[d2++].rdev = rdev;
2339         }
2340         kfree(conf->mirrors);
2341         conf->mirrors = newmirrors;
2342         kfree(conf->poolinfo);
2343         conf->poolinfo = newpoolinfo;
2344
2345         spin_lock_irqsave(&conf->device_lock, flags);
2346         mddev->degraded += (raid_disks - conf->raid_disks);
2347         spin_unlock_irqrestore(&conf->device_lock, flags);
2348         conf->raid_disks = mddev->raid_disks = raid_disks;
2349         mddev->delta_disks = 0;
2350
2351         conf->last_used = 0; /* just make sure it is in-range */
2352         lower_barrier(conf);
2353
2354         set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
2355         md_wakeup_thread(mddev->thread);
2356
2357         mempool_destroy(oldpool);
2358         return 0;
2359 }
2360
2361 static void raid1_quiesce(mddev_t *mddev, int state)
2362 {
2363         conf_t *conf = mddev->private;
2364
2365         switch(state) {
2366         case 2: /* wake for suspend */
2367                 wake_up(&conf->wait_barrier);
2368                 break;
2369         case 1:
2370                 raise_barrier(conf);
2371                 break;
2372         case 0:
2373                 lower_barrier(conf);
2374                 break;
2375         }
2376 }
2377
2378 static void *raid1_takeover(mddev_t *mddev)
2379 {
2380         /* raid1 can take over:
2381          *  raid5 with 2 devices, any layout or chunk size
2382          */
2383         if (mddev->level == 5 && mddev->raid_disks == 2) {
2384                 conf_t *conf;
2385                 mddev->new_level = 1;
2386                 mddev->new_layout = 0;
2387                 mddev->new_chunk_sectors = 0;
2388                 conf = setup_conf(mddev);
2389                 if (!IS_ERR(conf))
2390                         conf->barrier = 1;
2391                 return conf;
2392         }
2393         return ERR_PTR(-EINVAL);
2394 }
2395
2396 static struct mdk_personality raid1_personality =
2397 {
2398         .name           = "raid1",
2399         .level          = 1,
2400         .owner          = THIS_MODULE,
2401         .make_request   = make_request,
2402         .run            = run,
2403         .stop           = stop,
2404         .status         = status,
2405         .error_handler  = error,
2406         .hot_add_disk   = raid1_add_disk,
2407         .hot_remove_disk= raid1_remove_disk,
2408         .spare_active   = raid1_spare_active,
2409         .sync_request   = sync_request,
2410         .resize         = raid1_resize,
2411         .size           = raid1_size,
2412         .check_reshape  = raid1_reshape,
2413         .quiesce        = raid1_quiesce,
2414         .takeover       = raid1_takeover,
2415 };
2416
2417 static int __init raid_init(void)
2418 {
2419         return register_md_personality(&raid1_personality);
2420 }
2421
2422 static void raid_exit(void)
2423 {
2424         unregister_md_personality(&raid1_personality);
2425 }
2426
2427 module_init(raid_init);
2428 module_exit(raid_exit);
2429 MODULE_LICENSE("GPL");
2430 MODULE_DESCRIPTION("RAID1 (mirroring) personality for MD");
2431 MODULE_ALIAS("md-personality-3"); /* RAID1 */
2432 MODULE_ALIAS("md-raid1");
2433 MODULE_ALIAS("md-level-1");
2434
2435 module_param(max_queued, int, S_IRUGO|S_IWUSR);