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