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