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