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