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