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