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