GNU Linux-libre 4.14.313-gnu1
[releases.git] / drivers / md / raid10.c
1 /*
2  * raid10.c : Multiple Devices driver for Linux
3  *
4  * Copyright (C) 2000-2004 Neil Brown
5  *
6  * RAID-10 support for md.
7  *
8  * Base on code in raid1.c.  See raid1.c for further copyright information.
9  *
10  *
11  * This program is free software; you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation; either version 2, or (at your option)
14  * any later version.
15  *
16  * You should have received a copy of the GNU General Public License
17  * (for example /usr/src/linux/COPYING); if not, write to the Free
18  * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19  */
20
21 #include <linux/slab.h>
22 #include <linux/delay.h>
23 #include <linux/blkdev.h>
24 #include <linux/module.h>
25 #include <linux/seq_file.h>
26 #include <linux/ratelimit.h>
27 #include <linux/kthread.h>
28 #include <trace/events/block.h>
29 #include "md.h"
30 #include "raid10.h"
31 #include "raid0.h"
32 #include "bitmap.h"
33
34 /*
35  * RAID10 provides a combination of RAID0 and RAID1 functionality.
36  * The layout of data is defined by
37  *    chunk_size
38  *    raid_disks
39  *    near_copies (stored in low byte of layout)
40  *    far_copies (stored in second byte of layout)
41  *    far_offset (stored in bit 16 of layout )
42  *    use_far_sets (stored in bit 17 of layout )
43  *    use_far_sets_bugfixed (stored in bit 18 of layout )
44  *
45  * The data to be stored is divided into chunks using chunksize.  Each device
46  * is divided into far_copies sections.   In each section, chunks are laid out
47  * in a style similar to raid0, but near_copies copies of each chunk is stored
48  * (each on a different drive).  The starting device for each section is offset
49  * near_copies from the starting device of the previous section.  Thus there
50  * are (near_copies * far_copies) of each chunk, and each is on a different
51  * drive.  near_copies and far_copies must be at least one, and their product
52  * is at most raid_disks.
53  *
54  * If far_offset is true, then the far_copies are handled a bit differently.
55  * The copies are still in different stripes, but instead of being very far
56  * apart on disk, there are adjacent stripes.
57  *
58  * The far and offset algorithms are handled slightly differently if
59  * 'use_far_sets' is true.  In this case, the array's devices are grouped into
60  * sets that are (near_copies * far_copies) in size.  The far copied stripes
61  * are still shifted by 'near_copies' devices, but this shifting stays confined
62  * to the set rather than the entire array.  This is done to improve the number
63  * of device combinations that can fail without causing the array to fail.
64  * Example 'far' algorithm w/o 'use_far_sets' (each letter represents a chunk
65  * on a device):
66  *    A B C D    A B C D E
67  *      ...         ...
68  *    D A B C    E A B C D
69  * Example 'far' algorithm w/ 'use_far_sets' enabled (sets illustrated w/ []'s):
70  *    [A B] [C D]    [A B] [C D E]
71  *    |...| |...|    |...| | ... |
72  *    [B A] [D C]    [B A] [E C D]
73  */
74
75 /*
76  * Number of guaranteed r10bios in case of extreme VM load:
77  */
78 #define NR_RAID10_BIOS 256
79
80 /* when we get a read error on a read-only array, we redirect to another
81  * device without failing the first device, or trying to over-write to
82  * correct the read error.  To keep track of bad blocks on a per-bio
83  * level, we store IO_BLOCKED in the appropriate 'bios' pointer
84  */
85 #define IO_BLOCKED ((struct bio *)1)
86 /* When we successfully write to a known bad-block, we need to remove the
87  * bad-block marking which must be done from process context.  So we record
88  * the success by setting devs[n].bio to IO_MADE_GOOD
89  */
90 #define IO_MADE_GOOD ((struct bio *)2)
91
92 #define BIO_SPECIAL(bio) ((unsigned long)bio <= 2)
93
94 /* When there are this many requests queued to be written by
95  * the raid10 thread, we become 'congested' to provide back-pressure
96  * for writeback.
97  */
98 static int max_queued_requests = 1024;
99
100 static void allow_barrier(struct r10conf *conf);
101 static void lower_barrier(struct r10conf *conf);
102 static int _enough(struct r10conf *conf, int previous, int ignore);
103 static int enough(struct r10conf *conf, int ignore);
104 static sector_t reshape_request(struct mddev *mddev, sector_t sector_nr,
105                                 int *skipped);
106 static void reshape_request_write(struct mddev *mddev, struct r10bio *r10_bio);
107 static void end_reshape_write(struct bio *bio);
108 static void end_reshape(struct r10conf *conf);
109
110 #define raid10_log(md, fmt, args...)                            \
111         do { if ((md)->queue) blk_add_trace_msg((md)->queue, "raid10 " fmt, ##args); } while (0)
112
113 #include "raid1-10.c"
114
115 /*
116  * for resync bio, r10bio pointer can be retrieved from the per-bio
117  * 'struct resync_pages'.
118  */
119 static inline struct r10bio *get_resync_r10bio(struct bio *bio)
120 {
121         return get_resync_pages(bio)->raid_bio;
122 }
123
124 static void * r10bio_pool_alloc(gfp_t gfp_flags, void *data)
125 {
126         struct r10conf *conf = data;
127         int size = offsetof(struct r10bio, devs[conf->copies]);
128
129         /* allocate a r10bio with room for raid_disks entries in the
130          * bios array */
131         return kzalloc(size, gfp_flags);
132 }
133
134 static void r10bio_pool_free(void *r10_bio, void *data)
135 {
136         kfree(r10_bio);
137 }
138
139 /* amount of memory to reserve for resync requests */
140 #define RESYNC_WINDOW (1024*1024)
141 /* maximum number of concurrent requests, memory permitting */
142 #define RESYNC_DEPTH (32*1024*1024/RESYNC_BLOCK_SIZE)
143
144 /*
145  * When performing a resync, we need to read and compare, so
146  * we need as many pages are there are copies.
147  * When performing a recovery, we need 2 bios, one for read,
148  * one for write (we recover only one drive per r10buf)
149  *
150  */
151 static void * r10buf_pool_alloc(gfp_t gfp_flags, void *data)
152 {
153         struct r10conf *conf = data;
154         struct r10bio *r10_bio;
155         struct bio *bio;
156         int j;
157         int nalloc, nalloc_rp;
158         struct resync_pages *rps;
159
160         r10_bio = r10bio_pool_alloc(gfp_flags, conf);
161         if (!r10_bio)
162                 return NULL;
163
164         if (test_bit(MD_RECOVERY_SYNC, &conf->mddev->recovery) ||
165             test_bit(MD_RECOVERY_RESHAPE, &conf->mddev->recovery))
166                 nalloc = conf->copies; /* resync */
167         else
168                 nalloc = 2; /* recovery */
169
170         /* allocate once for all bios */
171         if (!conf->have_replacement)
172                 nalloc_rp = nalloc;
173         else
174                 nalloc_rp = nalloc * 2;
175         rps = kmalloc(sizeof(struct resync_pages) * nalloc_rp, gfp_flags);
176         if (!rps)
177                 goto out_free_r10bio;
178
179         /*
180          * Allocate bios.
181          */
182         for (j = nalloc ; j-- ; ) {
183                 bio = bio_kmalloc(gfp_flags, RESYNC_PAGES);
184                 if (!bio)
185                         goto out_free_bio;
186                 r10_bio->devs[j].bio = bio;
187                 if (!conf->have_replacement)
188                         continue;
189                 bio = bio_kmalloc(gfp_flags, RESYNC_PAGES);
190                 if (!bio)
191                         goto out_free_bio;
192                 r10_bio->devs[j].repl_bio = bio;
193         }
194         /*
195          * Allocate RESYNC_PAGES data pages and attach them
196          * where needed.
197          */
198         for (j = 0; j < nalloc; j++) {
199                 struct bio *rbio = r10_bio->devs[j].repl_bio;
200                 struct resync_pages *rp, *rp_repl;
201
202                 rp = &rps[j];
203                 if (rbio)
204                         rp_repl = &rps[nalloc + j];
205
206                 bio = r10_bio->devs[j].bio;
207
208                 if (!j || test_bit(MD_RECOVERY_SYNC,
209                                    &conf->mddev->recovery)) {
210                         if (resync_alloc_pages(rp, gfp_flags))
211                                 goto out_free_pages;
212                 } else {
213                         memcpy(rp, &rps[0], sizeof(*rp));
214                         resync_get_all_pages(rp);
215                 }
216
217                 rp->raid_bio = r10_bio;
218                 bio->bi_private = rp;
219                 if (rbio) {
220                         memcpy(rp_repl, rp, sizeof(*rp));
221                         rbio->bi_private = rp_repl;
222                 }
223         }
224
225         return r10_bio;
226
227 out_free_pages:
228         while (--j >= 0)
229                 resync_free_pages(&rps[j]);
230
231         j = 0;
232 out_free_bio:
233         for ( ; j < nalloc; j++) {
234                 if (r10_bio->devs[j].bio)
235                         bio_put(r10_bio->devs[j].bio);
236                 if (r10_bio->devs[j].repl_bio)
237                         bio_put(r10_bio->devs[j].repl_bio);
238         }
239         kfree(rps);
240 out_free_r10bio:
241         r10bio_pool_free(r10_bio, conf);
242         return NULL;
243 }
244
245 static void r10buf_pool_free(void *__r10_bio, void *data)
246 {
247         struct r10conf *conf = data;
248         struct r10bio *r10bio = __r10_bio;
249         int j;
250         struct resync_pages *rp = NULL;
251
252         for (j = conf->copies; j--; ) {
253                 struct bio *bio = r10bio->devs[j].bio;
254
255                 rp = get_resync_pages(bio);
256                 resync_free_pages(rp);
257                 bio_put(bio);
258
259                 bio = r10bio->devs[j].repl_bio;
260                 if (bio)
261                         bio_put(bio);
262         }
263
264         /* resync pages array stored in the 1st bio's .bi_private */
265         kfree(rp);
266
267         r10bio_pool_free(r10bio, conf);
268 }
269
270 static void put_all_bios(struct r10conf *conf, struct r10bio *r10_bio)
271 {
272         int i;
273
274         for (i = 0; i < conf->copies; i++) {
275                 struct bio **bio = & r10_bio->devs[i].bio;
276                 if (!BIO_SPECIAL(*bio))
277                         bio_put(*bio);
278                 *bio = NULL;
279                 bio = &r10_bio->devs[i].repl_bio;
280                 if (r10_bio->read_slot < 0 && !BIO_SPECIAL(*bio))
281                         bio_put(*bio);
282                 *bio = NULL;
283         }
284 }
285
286 static void free_r10bio(struct r10bio *r10_bio)
287 {
288         struct r10conf *conf = r10_bio->mddev->private;
289
290         put_all_bios(conf, r10_bio);
291         mempool_free(r10_bio, conf->r10bio_pool);
292 }
293
294 static void put_buf(struct r10bio *r10_bio)
295 {
296         struct r10conf *conf = r10_bio->mddev->private;
297
298         mempool_free(r10_bio, conf->r10buf_pool);
299
300         lower_barrier(conf);
301 }
302
303 static void reschedule_retry(struct r10bio *r10_bio)
304 {
305         unsigned long flags;
306         struct mddev *mddev = r10_bio->mddev;
307         struct r10conf *conf = mddev->private;
308
309         spin_lock_irqsave(&conf->device_lock, flags);
310         list_add(&r10_bio->retry_list, &conf->retry_list);
311         conf->nr_queued ++;
312         spin_unlock_irqrestore(&conf->device_lock, flags);
313
314         /* wake up frozen array... */
315         wake_up(&conf->wait_barrier);
316
317         md_wakeup_thread(mddev->thread);
318 }
319
320 /*
321  * raid_end_bio_io() is called when we have finished servicing a mirrored
322  * operation and are ready to return a success/failure code to the buffer
323  * cache layer.
324  */
325 static void raid_end_bio_io(struct r10bio *r10_bio)
326 {
327         struct bio *bio = r10_bio->master_bio;
328         struct r10conf *conf = r10_bio->mddev->private;
329
330         if (!test_bit(R10BIO_Uptodate, &r10_bio->state))
331                 bio->bi_status = BLK_STS_IOERR;
332
333         bio_endio(bio);
334         /*
335          * Wake up any possible resync thread that waits for the device
336          * to go idle.
337          */
338         allow_barrier(conf);
339
340         free_r10bio(r10_bio);
341 }
342
343 /*
344  * Update disk head position estimator based on IRQ completion info.
345  */
346 static inline void update_head_pos(int slot, struct r10bio *r10_bio)
347 {
348         struct r10conf *conf = r10_bio->mddev->private;
349
350         conf->mirrors[r10_bio->devs[slot].devnum].head_position =
351                 r10_bio->devs[slot].addr + (r10_bio->sectors);
352 }
353
354 /*
355  * Find the disk number which triggered given bio
356  */
357 static int find_bio_disk(struct r10conf *conf, struct r10bio *r10_bio,
358                          struct bio *bio, int *slotp, int *replp)
359 {
360         int slot;
361         int repl = 0;
362
363         for (slot = 0; slot < conf->copies; slot++) {
364                 if (r10_bio->devs[slot].bio == bio)
365                         break;
366                 if (r10_bio->devs[slot].repl_bio == bio) {
367                         repl = 1;
368                         break;
369                 }
370         }
371
372         BUG_ON(slot == conf->copies);
373         update_head_pos(slot, r10_bio);
374
375         if (slotp)
376                 *slotp = slot;
377         if (replp)
378                 *replp = repl;
379         return r10_bio->devs[slot].devnum;
380 }
381
382 static void raid10_end_read_request(struct bio *bio)
383 {
384         int uptodate = !bio->bi_status;
385         struct r10bio *r10_bio = bio->bi_private;
386         int slot, dev;
387         struct md_rdev *rdev;
388         struct r10conf *conf = r10_bio->mddev->private;
389
390         slot = r10_bio->read_slot;
391         dev = r10_bio->devs[slot].devnum;
392         rdev = r10_bio->devs[slot].rdev;
393         /*
394          * this branch is our 'one mirror IO has finished' event handler:
395          */
396         update_head_pos(slot, r10_bio);
397
398         if (uptodate) {
399                 /*
400                  * Set R10BIO_Uptodate in our master bio, so that
401                  * we will return a good error code to the higher
402                  * levels even if IO on some other mirrored buffer fails.
403                  *
404                  * The 'master' represents the composite IO operation to
405                  * user-side. So if something waits for IO, then it will
406                  * wait for the 'master' bio.
407                  */
408                 set_bit(R10BIO_Uptodate, &r10_bio->state);
409         } else {
410                 /* If all other devices that store this block have
411                  * failed, we want to return the error upwards rather
412                  * than fail the last device.  Here we redefine
413                  * "uptodate" to mean "Don't want to retry"
414                  */
415                 if (!_enough(conf, test_bit(R10BIO_Previous, &r10_bio->state),
416                              rdev->raid_disk))
417                         uptodate = 1;
418         }
419         if (uptodate) {
420                 raid_end_bio_io(r10_bio);
421                 rdev_dec_pending(rdev, conf->mddev);
422         } else {
423                 /*
424                  * oops, read error - keep the refcount on the rdev
425                  */
426                 char b[BDEVNAME_SIZE];
427                 pr_err_ratelimited("md/raid10:%s: %s: rescheduling sector %llu\n",
428                                    mdname(conf->mddev),
429                                    bdevname(rdev->bdev, b),
430                                    (unsigned long long)r10_bio->sector);
431                 set_bit(R10BIO_ReadError, &r10_bio->state);
432                 reschedule_retry(r10_bio);
433         }
434 }
435
436 static void close_write(struct r10bio *r10_bio)
437 {
438         /* clear the bitmap if all writes complete successfully */
439         bitmap_endwrite(r10_bio->mddev->bitmap, r10_bio->sector,
440                         r10_bio->sectors,
441                         !test_bit(R10BIO_Degraded, &r10_bio->state),
442                         0);
443         md_write_end(r10_bio->mddev);
444 }
445
446 static void one_write_done(struct r10bio *r10_bio)
447 {
448         if (atomic_dec_and_test(&r10_bio->remaining)) {
449                 if (test_bit(R10BIO_WriteError, &r10_bio->state))
450                         reschedule_retry(r10_bio);
451                 else {
452                         close_write(r10_bio);
453                         if (test_bit(R10BIO_MadeGood, &r10_bio->state))
454                                 reschedule_retry(r10_bio);
455                         else
456                                 raid_end_bio_io(r10_bio);
457                 }
458         }
459 }
460
461 static void raid10_end_write_request(struct bio *bio)
462 {
463         struct r10bio *r10_bio = bio->bi_private;
464         int dev;
465         int dec_rdev = 1;
466         struct r10conf *conf = r10_bio->mddev->private;
467         int slot, repl;
468         struct md_rdev *rdev = NULL;
469         struct bio *to_put = NULL;
470         bool discard_error;
471
472         discard_error = bio->bi_status && bio_op(bio) == REQ_OP_DISCARD;
473
474         dev = find_bio_disk(conf, r10_bio, bio, &slot, &repl);
475
476         if (repl)
477                 rdev = conf->mirrors[dev].replacement;
478         if (!rdev) {
479                 smp_rmb();
480                 repl = 0;
481                 rdev = conf->mirrors[dev].rdev;
482         }
483         /*
484          * this branch is our 'one mirror IO has finished' event handler:
485          */
486         if (bio->bi_status && !discard_error) {
487                 if (repl)
488                         /* Never record new bad blocks to replacement,
489                          * just fail it.
490                          */
491                         md_error(rdev->mddev, rdev);
492                 else {
493                         set_bit(WriteErrorSeen, &rdev->flags);
494                         if (!test_and_set_bit(WantReplacement, &rdev->flags))
495                                 set_bit(MD_RECOVERY_NEEDED,
496                                         &rdev->mddev->recovery);
497
498                         dec_rdev = 0;
499                         if (test_bit(FailFast, &rdev->flags) &&
500                             (bio->bi_opf & MD_FAILFAST)) {
501                                 md_error(rdev->mddev, rdev);
502                                 if (!test_bit(Faulty, &rdev->flags))
503                                         /* This is the only remaining device,
504                                          * We need to retry the write without
505                                          * FailFast
506                                          */
507                                         set_bit(R10BIO_WriteError, &r10_bio->state);
508                                 else {
509                                         r10_bio->devs[slot].bio = NULL;
510                                         to_put = bio;
511                                         dec_rdev = 1;
512                                 }
513                         } else
514                                 set_bit(R10BIO_WriteError, &r10_bio->state);
515                 }
516         } else {
517                 /*
518                  * Set R10BIO_Uptodate in our master bio, so that
519                  * we will return a good error code for to the higher
520                  * levels even if IO on some other mirrored buffer fails.
521                  *
522                  * The 'master' represents the composite IO operation to
523                  * user-side. So if something waits for IO, then it will
524                  * wait for the 'master' bio.
525                  */
526                 sector_t first_bad;
527                 int bad_sectors;
528
529                 /*
530                  * Do not set R10BIO_Uptodate if the current device is
531                  * rebuilding or Faulty. This is because we cannot use
532                  * such device for properly reading the data back (we could
533                  * potentially use it, if the current write would have felt
534                  * before rdev->recovery_offset, but for simplicity we don't
535                  * check this here.
536                  */
537                 if (test_bit(In_sync, &rdev->flags) &&
538                     !test_bit(Faulty, &rdev->flags))
539                         set_bit(R10BIO_Uptodate, &r10_bio->state);
540
541                 /* Maybe we can clear some bad blocks. */
542                 if (is_badblock(rdev,
543                                 r10_bio->devs[slot].addr,
544                                 r10_bio->sectors,
545                                 &first_bad, &bad_sectors) && !discard_error) {
546                         bio_put(bio);
547                         if (repl)
548                                 r10_bio->devs[slot].repl_bio = IO_MADE_GOOD;
549                         else
550                                 r10_bio->devs[slot].bio = IO_MADE_GOOD;
551                         dec_rdev = 0;
552                         set_bit(R10BIO_MadeGood, &r10_bio->state);
553                 }
554         }
555
556         /*
557          *
558          * Let's see if all mirrored write operations have finished
559          * already.
560          */
561         one_write_done(r10_bio);
562         if (dec_rdev)
563                 rdev_dec_pending(rdev, conf->mddev);
564         if (to_put)
565                 bio_put(to_put);
566 }
567
568 /*
569  * RAID10 layout manager
570  * As well as the chunksize and raid_disks count, there are two
571  * parameters: near_copies and far_copies.
572  * near_copies * far_copies must be <= raid_disks.
573  * Normally one of these will be 1.
574  * If both are 1, we get raid0.
575  * If near_copies == raid_disks, we get raid1.
576  *
577  * Chunks are laid out in raid0 style with near_copies copies of the
578  * first chunk, followed by near_copies copies of the next chunk and
579  * so on.
580  * If far_copies > 1, then after 1/far_copies of the array has been assigned
581  * as described above, we start again with a device offset of near_copies.
582  * So we effectively have another copy of the whole array further down all
583  * the drives, but with blocks on different drives.
584  * With this layout, and block is never stored twice on the one device.
585  *
586  * raid10_find_phys finds the sector offset of a given virtual sector
587  * on each device that it is on.
588  *
589  * raid10_find_virt does the reverse mapping, from a device and a
590  * sector offset to a virtual address
591  */
592
593 static void __raid10_find_phys(struct geom *geo, struct r10bio *r10bio)
594 {
595         int n,f;
596         sector_t sector;
597         sector_t chunk;
598         sector_t stripe;
599         int dev;
600         int slot = 0;
601         int last_far_set_start, last_far_set_size;
602
603         last_far_set_start = (geo->raid_disks / geo->far_set_size) - 1;
604         last_far_set_start *= geo->far_set_size;
605
606         last_far_set_size = geo->far_set_size;
607         last_far_set_size += (geo->raid_disks % geo->far_set_size);
608
609         /* now calculate first sector/dev */
610         chunk = r10bio->sector >> geo->chunk_shift;
611         sector = r10bio->sector & geo->chunk_mask;
612
613         chunk *= geo->near_copies;
614         stripe = chunk;
615         dev = sector_div(stripe, geo->raid_disks);
616         if (geo->far_offset)
617                 stripe *= geo->far_copies;
618
619         sector += stripe << geo->chunk_shift;
620
621         /* and calculate all the others */
622         for (n = 0; n < geo->near_copies; n++) {
623                 int d = dev;
624                 int set;
625                 sector_t s = sector;
626                 r10bio->devs[slot].devnum = d;
627                 r10bio->devs[slot].addr = s;
628                 slot++;
629
630                 for (f = 1; f < geo->far_copies; f++) {
631                         set = d / geo->far_set_size;
632                         d += geo->near_copies;
633
634                         if ((geo->raid_disks % geo->far_set_size) &&
635                             (d > last_far_set_start)) {
636                                 d -= last_far_set_start;
637                                 d %= last_far_set_size;
638                                 d += last_far_set_start;
639                         } else {
640                                 d %= geo->far_set_size;
641                                 d += geo->far_set_size * set;
642                         }
643                         s += geo->stride;
644                         r10bio->devs[slot].devnum = d;
645                         r10bio->devs[slot].addr = s;
646                         slot++;
647                 }
648                 dev++;
649                 if (dev >= geo->raid_disks) {
650                         dev = 0;
651                         sector += (geo->chunk_mask + 1);
652                 }
653         }
654 }
655
656 static void raid10_find_phys(struct r10conf *conf, struct r10bio *r10bio)
657 {
658         struct geom *geo = &conf->geo;
659
660         if (conf->reshape_progress != MaxSector &&
661             ((r10bio->sector >= conf->reshape_progress) !=
662              conf->mddev->reshape_backwards)) {
663                 set_bit(R10BIO_Previous, &r10bio->state);
664                 geo = &conf->prev;
665         } else
666                 clear_bit(R10BIO_Previous, &r10bio->state);
667
668         __raid10_find_phys(geo, r10bio);
669 }
670
671 static sector_t raid10_find_virt(struct r10conf *conf, sector_t sector, int dev)
672 {
673         sector_t offset, chunk, vchunk;
674         /* Never use conf->prev as this is only called during resync
675          * or recovery, so reshape isn't happening
676          */
677         struct geom *geo = &conf->geo;
678         int far_set_start = (dev / geo->far_set_size) * geo->far_set_size;
679         int far_set_size = geo->far_set_size;
680         int last_far_set_start;
681
682         if (geo->raid_disks % geo->far_set_size) {
683                 last_far_set_start = (geo->raid_disks / geo->far_set_size) - 1;
684                 last_far_set_start *= geo->far_set_size;
685
686                 if (dev >= last_far_set_start) {
687                         far_set_size = geo->far_set_size;
688                         far_set_size += (geo->raid_disks % geo->far_set_size);
689                         far_set_start = last_far_set_start;
690                 }
691         }
692
693         offset = sector & geo->chunk_mask;
694         if (geo->far_offset) {
695                 int fc;
696                 chunk = sector >> geo->chunk_shift;
697                 fc = sector_div(chunk, geo->far_copies);
698                 dev -= fc * geo->near_copies;
699                 if (dev < far_set_start)
700                         dev += far_set_size;
701         } else {
702                 while (sector >= geo->stride) {
703                         sector -= geo->stride;
704                         if (dev < (geo->near_copies + far_set_start))
705                                 dev += far_set_size - geo->near_copies;
706                         else
707                                 dev -= geo->near_copies;
708                 }
709                 chunk = sector >> geo->chunk_shift;
710         }
711         vchunk = chunk * geo->raid_disks + dev;
712         sector_div(vchunk, geo->near_copies);
713         return (vchunk << geo->chunk_shift) + offset;
714 }
715
716 /*
717  * This routine returns the disk from which the requested read should
718  * be done. There is a per-array 'next expected sequential IO' sector
719  * number - if this matches on the next IO then we use the last disk.
720  * There is also a per-disk 'last know head position' sector that is
721  * maintained from IRQ contexts, both the normal and the resync IO
722  * completion handlers update this position correctly. If there is no
723  * perfect sequential match then we pick the disk whose head is closest.
724  *
725  * If there are 2 mirrors in the same 2 devices, performance degrades
726  * because position is mirror, not device based.
727  *
728  * The rdev for the device selected will have nr_pending incremented.
729  */
730
731 /*
732  * FIXME: possibly should rethink readbalancing and do it differently
733  * depending on near_copies / far_copies geometry.
734  */
735 static struct md_rdev *read_balance(struct r10conf *conf,
736                                     struct r10bio *r10_bio,
737                                     int *max_sectors)
738 {
739         const sector_t this_sector = r10_bio->sector;
740         int disk, slot;
741         int sectors = r10_bio->sectors;
742         int best_good_sectors;
743         sector_t new_distance, best_dist;
744         struct md_rdev *best_rdev, *rdev = NULL;
745         int do_balance;
746         int best_slot;
747         struct geom *geo = &conf->geo;
748
749         raid10_find_phys(conf, r10_bio);
750         rcu_read_lock();
751         sectors = r10_bio->sectors;
752         best_slot = -1;
753         best_rdev = NULL;
754         best_dist = MaxSector;
755         best_good_sectors = 0;
756         do_balance = 1;
757         clear_bit(R10BIO_FailFast, &r10_bio->state);
758         /*
759          * Check if we can balance. We can balance on the whole
760          * device if no resync is going on (recovery is ok), or below
761          * the resync window. We take the first readable disk when
762          * above the resync window.
763          */
764         if (conf->mddev->recovery_cp < MaxSector
765             && (this_sector + sectors >= conf->next_resync))
766                 do_balance = 0;
767
768         for (slot = 0; slot < conf->copies ; slot++) {
769                 sector_t first_bad;
770                 int bad_sectors;
771                 sector_t dev_sector;
772
773                 if (r10_bio->devs[slot].bio == IO_BLOCKED)
774                         continue;
775                 disk = r10_bio->devs[slot].devnum;
776                 rdev = rcu_dereference(conf->mirrors[disk].replacement);
777                 if (rdev == NULL || test_bit(Faulty, &rdev->flags) ||
778                     r10_bio->devs[slot].addr + sectors > rdev->recovery_offset)
779                         rdev = rcu_dereference(conf->mirrors[disk].rdev);
780                 if (rdev == NULL ||
781                     test_bit(Faulty, &rdev->flags))
782                         continue;
783                 if (!test_bit(In_sync, &rdev->flags) &&
784                     r10_bio->devs[slot].addr + sectors > rdev->recovery_offset)
785                         continue;
786
787                 dev_sector = r10_bio->devs[slot].addr;
788                 if (is_badblock(rdev, dev_sector, sectors,
789                                 &first_bad, &bad_sectors)) {
790                         if (best_dist < MaxSector)
791                                 /* Already have a better slot */
792                                 continue;
793                         if (first_bad <= dev_sector) {
794                                 /* Cannot read here.  If this is the
795                                  * 'primary' device, then we must not read
796                                  * beyond 'bad_sectors' from another device.
797                                  */
798                                 bad_sectors -= (dev_sector - first_bad);
799                                 if (!do_balance && sectors > bad_sectors)
800                                         sectors = bad_sectors;
801                                 if (best_good_sectors > sectors)
802                                         best_good_sectors = sectors;
803                         } else {
804                                 sector_t good_sectors =
805                                         first_bad - dev_sector;
806                                 if (good_sectors > best_good_sectors) {
807                                         best_good_sectors = good_sectors;
808                                         best_slot = slot;
809                                         best_rdev = rdev;
810                                 }
811                                 if (!do_balance)
812                                         /* Must read from here */
813                                         break;
814                         }
815                         continue;
816                 } else
817                         best_good_sectors = sectors;
818
819                 if (!do_balance)
820                         break;
821
822                 if (best_slot >= 0)
823                         /* At least 2 disks to choose from so failfast is OK */
824                         set_bit(R10BIO_FailFast, &r10_bio->state);
825                 /* This optimisation is debatable, and completely destroys
826                  * sequential read speed for 'far copies' arrays.  So only
827                  * keep it for 'near' arrays, and review those later.
828                  */
829                 if (geo->near_copies > 1 && !atomic_read(&rdev->nr_pending))
830                         new_distance = 0;
831
832                 /* for far > 1 always use the lowest address */
833                 else if (geo->far_copies > 1)
834                         new_distance = r10_bio->devs[slot].addr;
835                 else
836                         new_distance = abs(r10_bio->devs[slot].addr -
837                                            conf->mirrors[disk].head_position);
838                 if (new_distance < best_dist) {
839                         best_dist = new_distance;
840                         best_slot = slot;
841                         best_rdev = rdev;
842                 }
843         }
844         if (slot >= conf->copies) {
845                 slot = best_slot;
846                 rdev = best_rdev;
847         }
848
849         if (slot >= 0) {
850                 atomic_inc(&rdev->nr_pending);
851                 r10_bio->read_slot = slot;
852         } else
853                 rdev = NULL;
854         rcu_read_unlock();
855         *max_sectors = best_good_sectors;
856
857         return rdev;
858 }
859
860 static int raid10_congested(struct mddev *mddev, int bits)
861 {
862         struct r10conf *conf = mddev->private;
863         int i, ret = 0;
864
865         if ((bits & (1 << WB_async_congested)) &&
866             conf->pending_count >= max_queued_requests)
867                 return 1;
868
869         rcu_read_lock();
870         for (i = 0;
871              (i < conf->geo.raid_disks || i < conf->prev.raid_disks)
872                      && ret == 0;
873              i++) {
874                 struct md_rdev *rdev = rcu_dereference(conf->mirrors[i].rdev);
875                 if (rdev && !test_bit(Faulty, &rdev->flags)) {
876                         struct request_queue *q = bdev_get_queue(rdev->bdev);
877
878                         ret |= bdi_congested(q->backing_dev_info, bits);
879                 }
880         }
881         rcu_read_unlock();
882         return ret;
883 }
884
885 static void flush_pending_writes(struct r10conf *conf)
886 {
887         /* Any writes that have been queued but are awaiting
888          * bitmap updates get flushed here.
889          */
890         spin_lock_irq(&conf->device_lock);
891
892         if (conf->pending_bio_list.head) {
893                 struct blk_plug plug;
894                 struct bio *bio;
895
896                 bio = bio_list_get(&conf->pending_bio_list);
897                 conf->pending_count = 0;
898                 spin_unlock_irq(&conf->device_lock);
899                 blk_start_plug(&plug);
900                 /* flush any pending bitmap writes to disk
901                  * before proceeding w/ I/O */
902                 bitmap_unplug(conf->mddev->bitmap);
903                 wake_up(&conf->wait_barrier);
904
905                 while (bio) { /* submit pending writes */
906                         struct bio *next = bio->bi_next;
907                         struct md_rdev *rdev = (void*)bio->bi_disk;
908                         bio->bi_next = NULL;
909                         bio_set_dev(bio, rdev->bdev);
910                         if (test_bit(Faulty, &rdev->flags)) {
911                                 bio_io_error(bio);
912                         } else if (unlikely((bio_op(bio) ==  REQ_OP_DISCARD) &&
913                                             !blk_queue_discard(bio->bi_disk->queue)))
914                                 /* Just ignore it */
915                                 bio_endio(bio);
916                         else
917                                 generic_make_request(bio);
918                         bio = next;
919                 }
920                 blk_finish_plug(&plug);
921         } else
922                 spin_unlock_irq(&conf->device_lock);
923 }
924
925 /* Barriers....
926  * Sometimes we need to suspend IO while we do something else,
927  * either some resync/recovery, or reconfigure the array.
928  * To do this we raise a 'barrier'.
929  * The 'barrier' is a counter that can be raised multiple times
930  * to count how many activities are happening which preclude
931  * normal IO.
932  * We can only raise the barrier if there is no pending IO.
933  * i.e. if nr_pending == 0.
934  * We choose only to raise the barrier if no-one is waiting for the
935  * barrier to go down.  This means that as soon as an IO request
936  * is ready, no other operations which require a barrier will start
937  * until the IO request has had a chance.
938  *
939  * So: regular IO calls 'wait_barrier'.  When that returns there
940  *    is no backgroup IO happening,  It must arrange to call
941  *    allow_barrier when it has finished its IO.
942  * backgroup IO calls must call raise_barrier.  Once that returns
943  *    there is no normal IO happeing.  It must arrange to call
944  *    lower_barrier when the particular background IO completes.
945  */
946
947 static void raise_barrier(struct r10conf *conf, int force)
948 {
949         BUG_ON(force && !conf->barrier);
950         spin_lock_irq(&conf->resync_lock);
951
952         /* Wait until no block IO is waiting (unless 'force') */
953         wait_event_lock_irq(conf->wait_barrier, force || !conf->nr_waiting,
954                             conf->resync_lock);
955
956         /* block any new IO from starting */
957         conf->barrier++;
958
959         /* Now wait for all pending IO to complete */
960         wait_event_lock_irq(conf->wait_barrier,
961                             !atomic_read(&conf->nr_pending) && conf->barrier < RESYNC_DEPTH,
962                             conf->resync_lock);
963
964         spin_unlock_irq(&conf->resync_lock);
965 }
966
967 static void lower_barrier(struct r10conf *conf)
968 {
969         unsigned long flags;
970         spin_lock_irqsave(&conf->resync_lock, flags);
971         conf->barrier--;
972         spin_unlock_irqrestore(&conf->resync_lock, flags);
973         wake_up(&conf->wait_barrier);
974 }
975
976 static void wait_barrier(struct r10conf *conf)
977 {
978         spin_lock_irq(&conf->resync_lock);
979         if (conf->barrier) {
980                 conf->nr_waiting++;
981                 /* Wait for the barrier to drop.
982                  * However if there are already pending
983                  * requests (preventing the barrier from
984                  * rising completely), and the
985                  * pre-process bio queue isn't empty,
986                  * then don't wait, as we need to empty
987                  * that queue to get the nr_pending
988                  * count down.
989                  */
990                 raid10_log(conf->mddev, "wait barrier");
991                 wait_event_lock_irq(conf->wait_barrier,
992                                     !conf->barrier ||
993                                     (atomic_read(&conf->nr_pending) &&
994                                      current->bio_list &&
995                                      (!bio_list_empty(&current->bio_list[0]) ||
996                                       !bio_list_empty(&current->bio_list[1]))),
997                                     conf->resync_lock);
998                 conf->nr_waiting--;
999                 if (!conf->nr_waiting)
1000                         wake_up(&conf->wait_barrier);
1001         }
1002         atomic_inc(&conf->nr_pending);
1003         spin_unlock_irq(&conf->resync_lock);
1004 }
1005
1006 static void allow_barrier(struct r10conf *conf)
1007 {
1008         if ((atomic_dec_and_test(&conf->nr_pending)) ||
1009                         (conf->array_freeze_pending))
1010                 wake_up(&conf->wait_barrier);
1011 }
1012
1013 static void freeze_array(struct r10conf *conf, int extra)
1014 {
1015         /* stop syncio and normal IO and wait for everything to
1016          * go quiet.
1017          * We increment barrier and nr_waiting, and then
1018          * wait until nr_pending match nr_queued+extra
1019          * This is called in the context of one normal IO request
1020          * that has failed. Thus any sync request that might be pending
1021          * will be blocked by nr_pending, and we need to wait for
1022          * pending IO requests to complete or be queued for re-try.
1023          * Thus the number queued (nr_queued) plus this request (extra)
1024          * must match the number of pending IOs (nr_pending) before
1025          * we continue.
1026          */
1027         spin_lock_irq(&conf->resync_lock);
1028         conf->array_freeze_pending++;
1029         conf->barrier++;
1030         conf->nr_waiting++;
1031         wait_event_lock_irq_cmd(conf->wait_barrier,
1032                                 atomic_read(&conf->nr_pending) == conf->nr_queued+extra,
1033                                 conf->resync_lock,
1034                                 flush_pending_writes(conf));
1035
1036         conf->array_freeze_pending--;
1037         spin_unlock_irq(&conf->resync_lock);
1038 }
1039
1040 static void unfreeze_array(struct r10conf *conf)
1041 {
1042         /* reverse the effect of the freeze */
1043         spin_lock_irq(&conf->resync_lock);
1044         conf->barrier--;
1045         conf->nr_waiting--;
1046         wake_up(&conf->wait_barrier);
1047         spin_unlock_irq(&conf->resync_lock);
1048 }
1049
1050 static sector_t choose_data_offset(struct r10bio *r10_bio,
1051                                    struct md_rdev *rdev)
1052 {
1053         if (!test_bit(MD_RECOVERY_RESHAPE, &rdev->mddev->recovery) ||
1054             test_bit(R10BIO_Previous, &r10_bio->state))
1055                 return rdev->data_offset;
1056         else
1057                 return rdev->new_data_offset;
1058 }
1059
1060 struct raid10_plug_cb {
1061         struct blk_plug_cb      cb;
1062         struct bio_list         pending;
1063         int                     pending_cnt;
1064 };
1065
1066 static void raid10_unplug(struct blk_plug_cb *cb, bool from_schedule)
1067 {
1068         struct raid10_plug_cb *plug = container_of(cb, struct raid10_plug_cb,
1069                                                    cb);
1070         struct mddev *mddev = plug->cb.data;
1071         struct r10conf *conf = mddev->private;
1072         struct bio *bio;
1073
1074         if (from_schedule || current->bio_list) {
1075                 spin_lock_irq(&conf->device_lock);
1076                 bio_list_merge(&conf->pending_bio_list, &plug->pending);
1077                 conf->pending_count += plug->pending_cnt;
1078                 spin_unlock_irq(&conf->device_lock);
1079                 wake_up(&conf->wait_barrier);
1080                 md_wakeup_thread(mddev->thread);
1081                 kfree(plug);
1082                 return;
1083         }
1084
1085         /* we aren't scheduling, so we can do the write-out directly. */
1086         bio = bio_list_get(&plug->pending);
1087         bitmap_unplug(mddev->bitmap);
1088         wake_up(&conf->wait_barrier);
1089
1090         while (bio) { /* submit pending writes */
1091                 struct bio *next = bio->bi_next;
1092                 struct md_rdev *rdev = (void*)bio->bi_disk;
1093                 bio->bi_next = NULL;
1094                 bio_set_dev(bio, rdev->bdev);
1095                 if (test_bit(Faulty, &rdev->flags)) {
1096                         bio_io_error(bio);
1097                 } else if (unlikely((bio_op(bio) ==  REQ_OP_DISCARD) &&
1098                                     !blk_queue_discard(bio->bi_disk->queue)))
1099                         /* Just ignore it */
1100                         bio_endio(bio);
1101                 else
1102                         generic_make_request(bio);
1103                 bio = next;
1104         }
1105         kfree(plug);
1106 }
1107
1108 static void raid10_read_request(struct mddev *mddev, struct bio *bio,
1109                                 struct r10bio *r10_bio)
1110 {
1111         struct r10conf *conf = mddev->private;
1112         struct bio *read_bio;
1113         const int op = bio_op(bio);
1114         const unsigned long do_sync = (bio->bi_opf & REQ_SYNC);
1115         int max_sectors;
1116         sector_t sectors;
1117         struct md_rdev *rdev;
1118         char b[BDEVNAME_SIZE];
1119         int slot = r10_bio->read_slot;
1120         struct md_rdev *err_rdev = NULL;
1121         gfp_t gfp = GFP_NOIO;
1122
1123         if (slot >= 0 && r10_bio->devs[slot].rdev) {
1124                 /*
1125                  * This is an error retry, but we cannot
1126                  * safely dereference the rdev in the r10_bio,
1127                  * we must use the one in conf.
1128                  * If it has already been disconnected (unlikely)
1129                  * we lose the device name in error messages.
1130                  */
1131                 int disk;
1132                 /*
1133                  * As we are blocking raid10, it is a little safer to
1134                  * use __GFP_HIGH.
1135                  */
1136                 gfp = GFP_NOIO | __GFP_HIGH;
1137
1138                 rcu_read_lock();
1139                 disk = r10_bio->devs[slot].devnum;
1140                 err_rdev = rcu_dereference(conf->mirrors[disk].rdev);
1141                 if (err_rdev)
1142                         bdevname(err_rdev->bdev, b);
1143                 else {
1144                         strcpy(b, "???");
1145                         /* This never gets dereferenced */
1146                         err_rdev = r10_bio->devs[slot].rdev;
1147                 }
1148                 rcu_read_unlock();
1149         }
1150         /*
1151          * Register the new request and wait if the reconstruction
1152          * thread has put up a bar for new requests.
1153          * Continue immediately if no resync is active currently.
1154          */
1155         wait_barrier(conf);
1156
1157         sectors = r10_bio->sectors;
1158         while (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery) &&
1159             bio->bi_iter.bi_sector < conf->reshape_progress &&
1160             bio->bi_iter.bi_sector + sectors > conf->reshape_progress) {
1161                 /*
1162                  * IO spans the reshape position.  Need to wait for reshape to
1163                  * pass
1164                  */
1165                 raid10_log(conf->mddev, "wait reshape");
1166                 allow_barrier(conf);
1167                 wait_event(conf->wait_barrier,
1168                            conf->reshape_progress <= bio->bi_iter.bi_sector ||
1169                            conf->reshape_progress >= bio->bi_iter.bi_sector +
1170                            sectors);
1171                 wait_barrier(conf);
1172         }
1173
1174         rdev = read_balance(conf, r10_bio, &max_sectors);
1175         if (!rdev) {
1176                 if (err_rdev) {
1177                         pr_crit_ratelimited("md/raid10:%s: %s: unrecoverable I/O read error for block %llu\n",
1178                                             mdname(mddev), b,
1179                                             (unsigned long long)r10_bio->sector);
1180                 }
1181                 raid_end_bio_io(r10_bio);
1182                 return;
1183         }
1184         if (err_rdev)
1185                 pr_err_ratelimited("md/raid10:%s: %s: redirecting sector %llu to another mirror\n",
1186                                    mdname(mddev),
1187                                    bdevname(rdev->bdev, b),
1188                                    (unsigned long long)r10_bio->sector);
1189         if (max_sectors < bio_sectors(bio)) {
1190                 struct bio *split = bio_split(bio, max_sectors,
1191                                               gfp, conf->bio_split);
1192                 bio_chain(split, bio);
1193                 allow_barrier(conf);
1194                 generic_make_request(bio);
1195                 wait_barrier(conf);
1196                 bio = split;
1197                 r10_bio->master_bio = bio;
1198                 r10_bio->sectors = max_sectors;
1199         }
1200         slot = r10_bio->read_slot;
1201
1202         read_bio = bio_clone_fast(bio, gfp, mddev->bio_set);
1203
1204         r10_bio->devs[slot].bio = read_bio;
1205         r10_bio->devs[slot].rdev = rdev;
1206
1207         read_bio->bi_iter.bi_sector = r10_bio->devs[slot].addr +
1208                 choose_data_offset(r10_bio, rdev);
1209         bio_set_dev(read_bio, rdev->bdev);
1210         read_bio->bi_end_io = raid10_end_read_request;
1211         bio_set_op_attrs(read_bio, op, do_sync);
1212         if (test_bit(FailFast, &rdev->flags) &&
1213             test_bit(R10BIO_FailFast, &r10_bio->state))
1214                 read_bio->bi_opf |= MD_FAILFAST;
1215         read_bio->bi_private = r10_bio;
1216
1217         if (mddev->gendisk)
1218                 trace_block_bio_remap(read_bio->bi_disk->queue,
1219                                       read_bio, disk_devt(mddev->gendisk),
1220                                       r10_bio->sector);
1221         generic_make_request(read_bio);
1222         return;
1223 }
1224
1225 static void raid10_write_one_disk(struct mddev *mddev, struct r10bio *r10_bio,
1226                                   struct bio *bio, bool replacement,
1227                                   int n_copy)
1228 {
1229         const int op = bio_op(bio);
1230         const unsigned long do_sync = (bio->bi_opf & REQ_SYNC);
1231         const unsigned long do_fua = (bio->bi_opf & REQ_FUA);
1232         unsigned long flags;
1233         struct blk_plug_cb *cb;
1234         struct raid10_plug_cb *plug = NULL;
1235         struct r10conf *conf = mddev->private;
1236         struct md_rdev *rdev;
1237         int devnum = r10_bio->devs[n_copy].devnum;
1238         struct bio *mbio;
1239
1240         if (replacement) {
1241                 rdev = conf->mirrors[devnum].replacement;
1242                 if (rdev == NULL) {
1243                         /* Replacement just got moved to main 'rdev' */
1244                         smp_mb();
1245                         rdev = conf->mirrors[devnum].rdev;
1246                 }
1247         } else
1248                 rdev = conf->mirrors[devnum].rdev;
1249
1250         mbio = bio_clone_fast(bio, GFP_NOIO, mddev->bio_set);
1251         if (replacement)
1252                 r10_bio->devs[n_copy].repl_bio = mbio;
1253         else
1254                 r10_bio->devs[n_copy].bio = mbio;
1255
1256         mbio->bi_iter.bi_sector = (r10_bio->devs[n_copy].addr +
1257                                    choose_data_offset(r10_bio, rdev));
1258         bio_set_dev(mbio, rdev->bdev);
1259         mbio->bi_end_io = raid10_end_write_request;
1260         bio_set_op_attrs(mbio, op, do_sync | do_fua);
1261         if (!replacement && test_bit(FailFast,
1262                                      &conf->mirrors[devnum].rdev->flags)
1263                          && enough(conf, devnum))
1264                 mbio->bi_opf |= MD_FAILFAST;
1265         mbio->bi_private = r10_bio;
1266
1267         if (conf->mddev->gendisk)
1268                 trace_block_bio_remap(mbio->bi_disk->queue,
1269                                       mbio, disk_devt(conf->mddev->gendisk),
1270                                       r10_bio->sector);
1271         /* flush_pending_writes() needs access to the rdev so...*/
1272         mbio->bi_disk = (void *)rdev;
1273
1274         atomic_inc(&r10_bio->remaining);
1275
1276         cb = blk_check_plugged(raid10_unplug, mddev, sizeof(*plug));
1277         if (cb)
1278                 plug = container_of(cb, struct raid10_plug_cb, cb);
1279         else
1280                 plug = NULL;
1281         if (plug) {
1282                 bio_list_add(&plug->pending, mbio);
1283                 plug->pending_cnt++;
1284         } else {
1285                 spin_lock_irqsave(&conf->device_lock, flags);
1286                 bio_list_add(&conf->pending_bio_list, mbio);
1287                 conf->pending_count++;
1288                 spin_unlock_irqrestore(&conf->device_lock, flags);
1289                 md_wakeup_thread(mddev->thread);
1290         }
1291 }
1292
1293 static void raid10_write_request(struct mddev *mddev, struct bio *bio,
1294                                  struct r10bio *r10_bio)
1295 {
1296         struct r10conf *conf = mddev->private;
1297         int i;
1298         struct md_rdev *blocked_rdev;
1299         sector_t sectors;
1300         int max_sectors;
1301
1302         /*
1303          * Register the new request and wait if the reconstruction
1304          * thread has put up a bar for new requests.
1305          * Continue immediately if no resync is active currently.
1306          */
1307         wait_barrier(conf);
1308
1309         sectors = r10_bio->sectors;
1310         while (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery) &&
1311             bio->bi_iter.bi_sector < conf->reshape_progress &&
1312             bio->bi_iter.bi_sector + sectors > conf->reshape_progress) {
1313                 /*
1314                  * IO spans the reshape position.  Need to wait for reshape to
1315                  * pass
1316                  */
1317                 raid10_log(conf->mddev, "wait reshape");
1318                 allow_barrier(conf);
1319                 wait_event(conf->wait_barrier,
1320                            conf->reshape_progress <= bio->bi_iter.bi_sector ||
1321                            conf->reshape_progress >= bio->bi_iter.bi_sector +
1322                            sectors);
1323                 wait_barrier(conf);
1324         }
1325
1326         if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery) &&
1327             (mddev->reshape_backwards
1328              ? (bio->bi_iter.bi_sector < conf->reshape_safe &&
1329                 bio->bi_iter.bi_sector + sectors > conf->reshape_progress)
1330              : (bio->bi_iter.bi_sector + sectors > conf->reshape_safe &&
1331                 bio->bi_iter.bi_sector < conf->reshape_progress))) {
1332                 /* Need to update reshape_position in metadata */
1333                 mddev->reshape_position = conf->reshape_progress;
1334                 set_mask_bits(&mddev->sb_flags, 0,
1335                               BIT(MD_SB_CHANGE_DEVS) | BIT(MD_SB_CHANGE_PENDING));
1336                 md_wakeup_thread(mddev->thread);
1337                 raid10_log(conf->mddev, "wait reshape metadata");
1338                 wait_event(mddev->sb_wait,
1339                            !test_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags));
1340
1341                 conf->reshape_safe = mddev->reshape_position;
1342         }
1343
1344         if (conf->pending_count >= max_queued_requests) {
1345                 md_wakeup_thread(mddev->thread);
1346                 raid10_log(mddev, "wait queued");
1347                 wait_event(conf->wait_barrier,
1348                            conf->pending_count < max_queued_requests);
1349         }
1350         /* first select target devices under rcu_lock and
1351          * inc refcount on their rdev.  Record them by setting
1352          * bios[x] to bio
1353          * If there are known/acknowledged bad blocks on any device
1354          * on which we have seen a write error, we want to avoid
1355          * writing to those blocks.  This potentially requires several
1356          * writes to write around the bad blocks.  Each set of writes
1357          * gets its own r10_bio with a set of bios attached.
1358          */
1359
1360         r10_bio->read_slot = -1; /* make sure repl_bio gets freed */
1361         raid10_find_phys(conf, r10_bio);
1362 retry_write:
1363         blocked_rdev = NULL;
1364         rcu_read_lock();
1365         max_sectors = r10_bio->sectors;
1366
1367         for (i = 0;  i < conf->copies; i++) {
1368                 int d = r10_bio->devs[i].devnum;
1369                 struct md_rdev *rdev = rcu_dereference(conf->mirrors[d].rdev);
1370                 struct md_rdev *rrdev = rcu_dereference(
1371                         conf->mirrors[d].replacement);
1372                 if (rdev == rrdev)
1373                         rrdev = NULL;
1374                 if (rdev && unlikely(test_bit(Blocked, &rdev->flags))) {
1375                         atomic_inc(&rdev->nr_pending);
1376                         blocked_rdev = rdev;
1377                         break;
1378                 }
1379                 if (rrdev && unlikely(test_bit(Blocked, &rrdev->flags))) {
1380                         atomic_inc(&rrdev->nr_pending);
1381                         blocked_rdev = rrdev;
1382                         break;
1383                 }
1384                 if (rdev && (test_bit(Faulty, &rdev->flags)))
1385                         rdev = NULL;
1386                 if (rrdev && (test_bit(Faulty, &rrdev->flags)))
1387                         rrdev = NULL;
1388
1389                 r10_bio->devs[i].bio = NULL;
1390                 r10_bio->devs[i].repl_bio = NULL;
1391
1392                 if (!rdev && !rrdev) {
1393                         set_bit(R10BIO_Degraded, &r10_bio->state);
1394                         continue;
1395                 }
1396                 if (rdev && test_bit(WriteErrorSeen, &rdev->flags)) {
1397                         sector_t first_bad;
1398                         sector_t dev_sector = r10_bio->devs[i].addr;
1399                         int bad_sectors;
1400                         int is_bad;
1401
1402                         is_bad = is_badblock(rdev, dev_sector, max_sectors,
1403                                              &first_bad, &bad_sectors);
1404                         if (is_bad < 0) {
1405                                 /* Mustn't write here until the bad block
1406                                  * is acknowledged
1407                                  */
1408                                 atomic_inc(&rdev->nr_pending);
1409                                 set_bit(BlockedBadBlocks, &rdev->flags);
1410                                 blocked_rdev = rdev;
1411                                 break;
1412                         }
1413                         if (is_bad && first_bad <= dev_sector) {
1414                                 /* Cannot write here at all */
1415                                 bad_sectors -= (dev_sector - first_bad);
1416                                 if (bad_sectors < max_sectors)
1417                                         /* Mustn't write more than bad_sectors
1418                                          * to other devices yet
1419                                          */
1420                                         max_sectors = bad_sectors;
1421                                 /* We don't set R10BIO_Degraded as that
1422                                  * only applies if the disk is missing,
1423                                  * so it might be re-added, and we want to
1424                                  * know to recover this chunk.
1425                                  * In this case the device is here, and the
1426                                  * fact that this chunk is not in-sync is
1427                                  * recorded in the bad block log.
1428                                  */
1429                                 continue;
1430                         }
1431                         if (is_bad) {
1432                                 int good_sectors = first_bad - dev_sector;
1433                                 if (good_sectors < max_sectors)
1434                                         max_sectors = good_sectors;
1435                         }
1436                 }
1437                 if (rdev) {
1438                         r10_bio->devs[i].bio = bio;
1439                         atomic_inc(&rdev->nr_pending);
1440                 }
1441                 if (rrdev) {
1442                         r10_bio->devs[i].repl_bio = bio;
1443                         atomic_inc(&rrdev->nr_pending);
1444                 }
1445         }
1446         rcu_read_unlock();
1447
1448         if (unlikely(blocked_rdev)) {
1449                 /* Have to wait for this device to get unblocked, then retry */
1450                 int j;
1451                 int d;
1452
1453                 for (j = 0; j < i; j++) {
1454                         if (r10_bio->devs[j].bio) {
1455                                 d = r10_bio->devs[j].devnum;
1456                                 rdev_dec_pending(conf->mirrors[d].rdev, mddev);
1457                         }
1458                         if (r10_bio->devs[j].repl_bio) {
1459                                 struct md_rdev *rdev;
1460                                 d = r10_bio->devs[j].devnum;
1461                                 rdev = conf->mirrors[d].replacement;
1462                                 if (!rdev) {
1463                                         /* Race with remove_disk */
1464                                         smp_mb();
1465                                         rdev = conf->mirrors[d].rdev;
1466                                 }
1467                                 rdev_dec_pending(rdev, mddev);
1468                         }
1469                 }
1470                 allow_barrier(conf);
1471                 raid10_log(conf->mddev, "wait rdev %d blocked", blocked_rdev->raid_disk);
1472                 md_wait_for_blocked_rdev(blocked_rdev, mddev);
1473                 wait_barrier(conf);
1474                 goto retry_write;
1475         }
1476
1477         if (max_sectors < r10_bio->sectors)
1478                 r10_bio->sectors = max_sectors;
1479
1480         if (r10_bio->sectors < bio_sectors(bio)) {
1481                 struct bio *split = bio_split(bio, r10_bio->sectors,
1482                                               GFP_NOIO, conf->bio_split);
1483                 bio_chain(split, bio);
1484                 allow_barrier(conf);
1485                 generic_make_request(bio);
1486                 wait_barrier(conf);
1487                 bio = split;
1488                 r10_bio->master_bio = bio;
1489         }
1490
1491         atomic_set(&r10_bio->remaining, 1);
1492         bitmap_startwrite(mddev->bitmap, r10_bio->sector, r10_bio->sectors, 0);
1493
1494         for (i = 0; i < conf->copies; i++) {
1495                 if (r10_bio->devs[i].bio)
1496                         raid10_write_one_disk(mddev, r10_bio, bio, false, i);
1497                 if (r10_bio->devs[i].repl_bio)
1498                         raid10_write_one_disk(mddev, r10_bio, bio, true, i);
1499         }
1500         one_write_done(r10_bio);
1501 }
1502
1503 static void __make_request(struct mddev *mddev, struct bio *bio, int sectors)
1504 {
1505         struct r10conf *conf = mddev->private;
1506         struct r10bio *r10_bio;
1507
1508         r10_bio = mempool_alloc(conf->r10bio_pool, GFP_NOIO);
1509
1510         r10_bio->master_bio = bio;
1511         r10_bio->sectors = sectors;
1512
1513         r10_bio->mddev = mddev;
1514         r10_bio->sector = bio->bi_iter.bi_sector;
1515         r10_bio->state = 0;
1516         r10_bio->read_slot = -1;
1517         memset(r10_bio->devs, 0, sizeof(r10_bio->devs[0]) * conf->copies);
1518
1519         if (bio_data_dir(bio) == READ)
1520                 raid10_read_request(mddev, bio, r10_bio);
1521         else
1522                 raid10_write_request(mddev, bio, r10_bio);
1523 }
1524
1525 static bool raid10_make_request(struct mddev *mddev, struct bio *bio)
1526 {
1527         struct r10conf *conf = mddev->private;
1528         sector_t chunk_mask = (conf->geo.chunk_mask & conf->prev.chunk_mask);
1529         int chunk_sects = chunk_mask + 1;
1530         int sectors = bio_sectors(bio);
1531
1532         if (unlikely(bio->bi_opf & REQ_PREFLUSH)) {
1533                 md_flush_request(mddev, bio);
1534                 return true;
1535         }
1536
1537         if (!md_write_start(mddev, bio))
1538                 return false;
1539
1540         /*
1541          * If this request crosses a chunk boundary, we need to split
1542          * it.
1543          */
1544         if (unlikely((bio->bi_iter.bi_sector & chunk_mask) +
1545                      sectors > chunk_sects
1546                      && (conf->geo.near_copies < conf->geo.raid_disks
1547                          || conf->prev.near_copies <
1548                          conf->prev.raid_disks)))
1549                 sectors = chunk_sects -
1550                         (bio->bi_iter.bi_sector &
1551                          (chunk_sects - 1));
1552         __make_request(mddev, bio, sectors);
1553
1554         /* In case raid10d snuck in to freeze_array */
1555         wake_up(&conf->wait_barrier);
1556         return true;
1557 }
1558
1559 static void raid10_status(struct seq_file *seq, struct mddev *mddev)
1560 {
1561         struct r10conf *conf = mddev->private;
1562         int i;
1563
1564         if (conf->geo.near_copies < conf->geo.raid_disks)
1565                 seq_printf(seq, " %dK chunks", mddev->chunk_sectors / 2);
1566         if (conf->geo.near_copies > 1)
1567                 seq_printf(seq, " %d near-copies", conf->geo.near_copies);
1568         if (conf->geo.far_copies > 1) {
1569                 if (conf->geo.far_offset)
1570                         seq_printf(seq, " %d offset-copies", conf->geo.far_copies);
1571                 else
1572                         seq_printf(seq, " %d far-copies", conf->geo.far_copies);
1573                 if (conf->geo.far_set_size != conf->geo.raid_disks)
1574                         seq_printf(seq, " %d devices per set", conf->geo.far_set_size);
1575         }
1576         seq_printf(seq, " [%d/%d] [", conf->geo.raid_disks,
1577                                         conf->geo.raid_disks - mddev->degraded);
1578         rcu_read_lock();
1579         for (i = 0; i < conf->geo.raid_disks; i++) {
1580                 struct md_rdev *rdev = rcu_dereference(conf->mirrors[i].rdev);
1581                 seq_printf(seq, "%s", rdev && test_bit(In_sync, &rdev->flags) ? "U" : "_");
1582         }
1583         rcu_read_unlock();
1584         seq_printf(seq, "]");
1585 }
1586
1587 /* check if there are enough drives for
1588  * every block to appear on atleast one.
1589  * Don't consider the device numbered 'ignore'
1590  * as we might be about to remove it.
1591  */
1592 static int _enough(struct r10conf *conf, int previous, int ignore)
1593 {
1594         int first = 0;
1595         int has_enough = 0;
1596         int disks, ncopies;
1597         if (previous) {
1598                 disks = conf->prev.raid_disks;
1599                 ncopies = conf->prev.near_copies;
1600         } else {
1601                 disks = conf->geo.raid_disks;
1602                 ncopies = conf->geo.near_copies;
1603         }
1604
1605         rcu_read_lock();
1606         do {
1607                 int n = conf->copies;
1608                 int cnt = 0;
1609                 int this = first;
1610                 while (n--) {
1611                         struct md_rdev *rdev;
1612                         if (this != ignore &&
1613                             (rdev = rcu_dereference(conf->mirrors[this].rdev)) &&
1614                             test_bit(In_sync, &rdev->flags))
1615                                 cnt++;
1616                         this = (this+1) % disks;
1617                 }
1618                 if (cnt == 0)
1619                         goto out;
1620                 first = (first + ncopies) % disks;
1621         } while (first != 0);
1622         has_enough = 1;
1623 out:
1624         rcu_read_unlock();
1625         return has_enough;
1626 }
1627
1628 static int enough(struct r10conf *conf, int ignore)
1629 {
1630         /* when calling 'enough', both 'prev' and 'geo' must
1631          * be stable.
1632          * This is ensured if ->reconfig_mutex or ->device_lock
1633          * is held.
1634          */
1635         return _enough(conf, 0, ignore) &&
1636                 _enough(conf, 1, ignore);
1637 }
1638
1639 static void raid10_error(struct mddev *mddev, struct md_rdev *rdev)
1640 {
1641         char b[BDEVNAME_SIZE];
1642         struct r10conf *conf = mddev->private;
1643         unsigned long flags;
1644
1645         /*
1646          * If it is not operational, then we have already marked it as dead
1647          * else if it is the last working disks, ignore the error, let the
1648          * next level up know.
1649          * else mark the drive as failed
1650          */
1651         spin_lock_irqsave(&conf->device_lock, flags);
1652         if (test_bit(In_sync, &rdev->flags)
1653             && !enough(conf, rdev->raid_disk)) {
1654                 /*
1655                  * Don't fail the drive, just return an IO error.
1656                  */
1657                 spin_unlock_irqrestore(&conf->device_lock, flags);
1658                 return;
1659         }
1660         if (test_and_clear_bit(In_sync, &rdev->flags))
1661                 mddev->degraded++;
1662         /*
1663          * If recovery is running, make sure it aborts.
1664          */
1665         set_bit(MD_RECOVERY_INTR, &mddev->recovery);
1666         set_bit(Blocked, &rdev->flags);
1667         set_bit(Faulty, &rdev->flags);
1668         set_mask_bits(&mddev->sb_flags, 0,
1669                       BIT(MD_SB_CHANGE_DEVS) | BIT(MD_SB_CHANGE_PENDING));
1670         spin_unlock_irqrestore(&conf->device_lock, flags);
1671         pr_crit("md/raid10:%s: Disk failure on %s, disabling device.\n"
1672                 "md/raid10:%s: Operation continuing on %d devices.\n",
1673                 mdname(mddev), bdevname(rdev->bdev, b),
1674                 mdname(mddev), conf->geo.raid_disks - mddev->degraded);
1675 }
1676
1677 static void print_conf(struct r10conf *conf)
1678 {
1679         int i;
1680         struct md_rdev *rdev;
1681
1682         pr_debug("RAID10 conf printout:\n");
1683         if (!conf) {
1684                 pr_debug("(!conf)\n");
1685                 return;
1686         }
1687         pr_debug(" --- wd:%d rd:%d\n", conf->geo.raid_disks - conf->mddev->degraded,
1688                  conf->geo.raid_disks);
1689
1690         /* This is only called with ->reconfix_mutex held, so
1691          * rcu protection of rdev is not needed */
1692         for (i = 0; i < conf->geo.raid_disks; i++) {
1693                 char b[BDEVNAME_SIZE];
1694                 rdev = conf->mirrors[i].rdev;
1695                 if (rdev)
1696                         pr_debug(" disk %d, wo:%d, o:%d, dev:%s\n",
1697                                  i, !test_bit(In_sync, &rdev->flags),
1698                                  !test_bit(Faulty, &rdev->flags),
1699                                  bdevname(rdev->bdev,b));
1700         }
1701 }
1702
1703 static void close_sync(struct r10conf *conf)
1704 {
1705         wait_barrier(conf);
1706         allow_barrier(conf);
1707
1708         mempool_destroy(conf->r10buf_pool);
1709         conf->r10buf_pool = NULL;
1710 }
1711
1712 static int raid10_spare_active(struct mddev *mddev)
1713 {
1714         int i;
1715         struct r10conf *conf = mddev->private;
1716         struct raid10_info *tmp;
1717         int count = 0;
1718         unsigned long flags;
1719
1720         /*
1721          * Find all non-in_sync disks within the RAID10 configuration
1722          * and mark them in_sync
1723          */
1724         for (i = 0; i < conf->geo.raid_disks; i++) {
1725                 tmp = conf->mirrors + i;
1726                 if (tmp->replacement
1727                     && tmp->replacement->recovery_offset == MaxSector
1728                     && !test_bit(Faulty, &tmp->replacement->flags)
1729                     && !test_and_set_bit(In_sync, &tmp->replacement->flags)) {
1730                         /* Replacement has just become active */
1731                         if (!tmp->rdev
1732                             || !test_and_clear_bit(In_sync, &tmp->rdev->flags))
1733                                 count++;
1734                         if (tmp->rdev) {
1735                                 /* Replaced device not technically faulty,
1736                                  * but we need to be sure it gets removed
1737                                  * and never re-added.
1738                                  */
1739                                 set_bit(Faulty, &tmp->rdev->flags);
1740                                 sysfs_notify_dirent_safe(
1741                                         tmp->rdev->sysfs_state);
1742                         }
1743                         sysfs_notify_dirent_safe(tmp->replacement->sysfs_state);
1744                 } else if (tmp->rdev
1745                            && tmp->rdev->recovery_offset == MaxSector
1746                            && !test_bit(Faulty, &tmp->rdev->flags)
1747                            && !test_and_set_bit(In_sync, &tmp->rdev->flags)) {
1748                         count++;
1749                         sysfs_notify_dirent_safe(tmp->rdev->sysfs_state);
1750                 }
1751         }
1752         spin_lock_irqsave(&conf->device_lock, flags);
1753         mddev->degraded -= count;
1754         spin_unlock_irqrestore(&conf->device_lock, flags);
1755
1756         print_conf(conf);
1757         return count;
1758 }
1759
1760 static int raid10_add_disk(struct mddev *mddev, struct md_rdev *rdev)
1761 {
1762         struct r10conf *conf = mddev->private;
1763         int err = -EEXIST;
1764         int mirror;
1765         int first = 0;
1766         int last = conf->geo.raid_disks - 1;
1767
1768         if (mddev->recovery_cp < MaxSector)
1769                 /* only hot-add to in-sync arrays, as recovery is
1770                  * very different from resync
1771                  */
1772                 return -EBUSY;
1773         if (rdev->saved_raid_disk < 0 && !_enough(conf, 1, -1))
1774                 return -EINVAL;
1775
1776         if (md_integrity_add_rdev(rdev, mddev))
1777                 return -ENXIO;
1778
1779         if (rdev->raid_disk >= 0)
1780                 first = last = rdev->raid_disk;
1781
1782         if (rdev->saved_raid_disk >= first &&
1783             rdev->saved_raid_disk < conf->geo.raid_disks &&
1784             conf->mirrors[rdev->saved_raid_disk].rdev == NULL)
1785                 mirror = rdev->saved_raid_disk;
1786         else
1787                 mirror = first;
1788         for ( ; mirror <= last ; mirror++) {
1789                 struct raid10_info *p = &conf->mirrors[mirror];
1790                 if (p->recovery_disabled == mddev->recovery_disabled)
1791                         continue;
1792                 if (p->rdev) {
1793                         if (!test_bit(WantReplacement, &p->rdev->flags) ||
1794                             p->replacement != NULL)
1795                                 continue;
1796                         clear_bit(In_sync, &rdev->flags);
1797                         set_bit(Replacement, &rdev->flags);
1798                         rdev->raid_disk = mirror;
1799                         err = 0;
1800                         if (mddev->gendisk)
1801                                 disk_stack_limits(mddev->gendisk, rdev->bdev,
1802                                                   rdev->data_offset << 9);
1803                         conf->fullsync = 1;
1804                         rcu_assign_pointer(p->replacement, rdev);
1805                         break;
1806                 }
1807
1808                 if (mddev->gendisk)
1809                         disk_stack_limits(mddev->gendisk, rdev->bdev,
1810                                           rdev->data_offset << 9);
1811
1812                 p->head_position = 0;
1813                 p->recovery_disabled = mddev->recovery_disabled - 1;
1814                 rdev->raid_disk = mirror;
1815                 err = 0;
1816                 if (rdev->saved_raid_disk != mirror)
1817                         conf->fullsync = 1;
1818                 rcu_assign_pointer(p->rdev, rdev);
1819                 break;
1820         }
1821         if (mddev->queue && blk_queue_discard(bdev_get_queue(rdev->bdev)))
1822                 queue_flag_set_unlocked(QUEUE_FLAG_DISCARD, mddev->queue);
1823
1824         print_conf(conf);
1825         return err;
1826 }
1827
1828 static int raid10_remove_disk(struct mddev *mddev, struct md_rdev *rdev)
1829 {
1830         struct r10conf *conf = mddev->private;
1831         int err = 0;
1832         int number = rdev->raid_disk;
1833         struct md_rdev **rdevp;
1834         struct raid10_info *p;
1835
1836         print_conf(conf);
1837         if (unlikely(number >= mddev->raid_disks))
1838                 return 0;
1839         p = conf->mirrors + number;
1840         if (rdev == p->rdev)
1841                 rdevp = &p->rdev;
1842         else if (rdev == p->replacement)
1843                 rdevp = &p->replacement;
1844         else
1845                 return 0;
1846
1847         if (test_bit(In_sync, &rdev->flags) ||
1848             atomic_read(&rdev->nr_pending)) {
1849                 err = -EBUSY;
1850                 goto abort;
1851         }
1852         /* Only remove non-faulty devices if recovery
1853          * is not possible.
1854          */
1855         if (!test_bit(Faulty, &rdev->flags) &&
1856             mddev->recovery_disabled != p->recovery_disabled &&
1857             (!p->replacement || p->replacement == rdev) &&
1858             number < conf->geo.raid_disks &&
1859             enough(conf, -1)) {
1860                 err = -EBUSY;
1861                 goto abort;
1862         }
1863         *rdevp = NULL;
1864         if (!test_bit(RemoveSynchronized, &rdev->flags)) {
1865                 synchronize_rcu();
1866                 if (atomic_read(&rdev->nr_pending)) {
1867                         /* lost the race, try later */
1868                         err = -EBUSY;
1869                         *rdevp = rdev;
1870                         goto abort;
1871                 }
1872         }
1873         if (p->replacement) {
1874                 /* We must have just cleared 'rdev' */
1875                 p->rdev = p->replacement;
1876                 clear_bit(Replacement, &p->replacement->flags);
1877                 smp_mb(); /* Make sure other CPUs may see both as identical
1878                            * but will never see neither -- if they are careful.
1879                            */
1880                 p->replacement = NULL;
1881         }
1882
1883         clear_bit(WantReplacement, &rdev->flags);
1884         err = md_integrity_register(mddev);
1885
1886 abort:
1887
1888         print_conf(conf);
1889         return err;
1890 }
1891
1892 static void __end_sync_read(struct r10bio *r10_bio, struct bio *bio, int d)
1893 {
1894         struct r10conf *conf = r10_bio->mddev->private;
1895
1896         if (!bio->bi_status)
1897                 set_bit(R10BIO_Uptodate, &r10_bio->state);
1898         else
1899                 /* The write handler will notice the lack of
1900                  * R10BIO_Uptodate and record any errors etc
1901                  */
1902                 atomic_add(r10_bio->sectors,
1903                            &conf->mirrors[d].rdev->corrected_errors);
1904
1905         /* for reconstruct, we always reschedule after a read.
1906          * for resync, only after all reads
1907          */
1908         rdev_dec_pending(conf->mirrors[d].rdev, conf->mddev);
1909         if (test_bit(R10BIO_IsRecover, &r10_bio->state) ||
1910             atomic_dec_and_test(&r10_bio->remaining)) {
1911                 /* we have read all the blocks,
1912                  * do the comparison in process context in raid10d
1913                  */
1914                 reschedule_retry(r10_bio);
1915         }
1916 }
1917
1918 static void end_sync_read(struct bio *bio)
1919 {
1920         struct r10bio *r10_bio = get_resync_r10bio(bio);
1921         struct r10conf *conf = r10_bio->mddev->private;
1922         int d = find_bio_disk(conf, r10_bio, bio, NULL, NULL);
1923
1924         __end_sync_read(r10_bio, bio, d);
1925 }
1926
1927 static void end_reshape_read(struct bio *bio)
1928 {
1929         /* reshape read bio isn't allocated from r10buf_pool */
1930         struct r10bio *r10_bio = bio->bi_private;
1931
1932         __end_sync_read(r10_bio, bio, r10_bio->read_slot);
1933 }
1934
1935 static void end_sync_request(struct r10bio *r10_bio)
1936 {
1937         struct mddev *mddev = r10_bio->mddev;
1938
1939         while (atomic_dec_and_test(&r10_bio->remaining)) {
1940                 if (r10_bio->master_bio == NULL) {
1941                         /* the primary of several recovery bios */
1942                         sector_t s = r10_bio->sectors;
1943                         if (test_bit(R10BIO_MadeGood, &r10_bio->state) ||
1944                             test_bit(R10BIO_WriteError, &r10_bio->state))
1945                                 reschedule_retry(r10_bio);
1946                         else
1947                                 put_buf(r10_bio);
1948                         md_done_sync(mddev, s, 1);
1949                         break;
1950                 } else {
1951                         struct r10bio *r10_bio2 = (struct r10bio *)r10_bio->master_bio;
1952                         if (test_bit(R10BIO_MadeGood, &r10_bio->state) ||
1953                             test_bit(R10BIO_WriteError, &r10_bio->state))
1954                                 reschedule_retry(r10_bio);
1955                         else
1956                                 put_buf(r10_bio);
1957                         r10_bio = r10_bio2;
1958                 }
1959         }
1960 }
1961
1962 static void end_sync_write(struct bio *bio)
1963 {
1964         struct r10bio *r10_bio = get_resync_r10bio(bio);
1965         struct mddev *mddev = r10_bio->mddev;
1966         struct r10conf *conf = mddev->private;
1967         int d;
1968         sector_t first_bad;
1969         int bad_sectors;
1970         int slot;
1971         int repl;
1972         struct md_rdev *rdev = NULL;
1973
1974         d = find_bio_disk(conf, r10_bio, bio, &slot, &repl);
1975         if (repl)
1976                 rdev = conf->mirrors[d].replacement;
1977         else
1978                 rdev = conf->mirrors[d].rdev;
1979
1980         if (bio->bi_status) {
1981                 if (repl)
1982                         md_error(mddev, rdev);
1983                 else {
1984                         set_bit(WriteErrorSeen, &rdev->flags);
1985                         if (!test_and_set_bit(WantReplacement, &rdev->flags))
1986                                 set_bit(MD_RECOVERY_NEEDED,
1987                                         &rdev->mddev->recovery);
1988                         set_bit(R10BIO_WriteError, &r10_bio->state);
1989                 }
1990         } else if (is_badblock(rdev,
1991                              r10_bio->devs[slot].addr,
1992                              r10_bio->sectors,
1993                              &first_bad, &bad_sectors))
1994                 set_bit(R10BIO_MadeGood, &r10_bio->state);
1995
1996         rdev_dec_pending(rdev, mddev);
1997
1998         end_sync_request(r10_bio);
1999 }
2000
2001 /*
2002  * Note: sync and recover and handled very differently for raid10
2003  * This code is for resync.
2004  * For resync, we read through virtual addresses and read all blocks.
2005  * If there is any error, we schedule a write.  The lowest numbered
2006  * drive is authoritative.
2007  * However requests come for physical address, so we need to map.
2008  * For every physical address there are raid_disks/copies virtual addresses,
2009  * which is always are least one, but is not necessarly an integer.
2010  * This means that a physical address can span multiple chunks, so we may
2011  * have to submit multiple io requests for a single sync request.
2012  */
2013 /*
2014  * We check if all blocks are in-sync and only write to blocks that
2015  * aren't in sync
2016  */
2017 static void sync_request_write(struct mddev *mddev, struct r10bio *r10_bio)
2018 {
2019         struct r10conf *conf = mddev->private;
2020         int i, first;
2021         struct bio *tbio, *fbio;
2022         int vcnt;
2023         struct page **tpages, **fpages;
2024
2025         atomic_set(&r10_bio->remaining, 1);
2026
2027         /* find the first device with a block */
2028         for (i=0; i<conf->copies; i++)
2029                 if (!r10_bio->devs[i].bio->bi_status)
2030                         break;
2031
2032         if (i == conf->copies)
2033                 goto done;
2034
2035         first = i;
2036         fbio = r10_bio->devs[i].bio;
2037         fbio->bi_iter.bi_size = r10_bio->sectors << 9;
2038         fbio->bi_iter.bi_idx = 0;
2039         fpages = get_resync_pages(fbio)->pages;
2040
2041         vcnt = (r10_bio->sectors + (PAGE_SIZE >> 9) - 1) >> (PAGE_SHIFT - 9);
2042         /* now find blocks with errors */
2043         for (i=0 ; i < conf->copies ; i++) {
2044                 int  j, d;
2045                 struct md_rdev *rdev;
2046                 struct resync_pages *rp;
2047
2048                 tbio = r10_bio->devs[i].bio;
2049
2050                 if (tbio->bi_end_io != end_sync_read)
2051                         continue;
2052                 if (i == first)
2053                         continue;
2054
2055                 tpages = get_resync_pages(tbio)->pages;
2056                 d = r10_bio->devs[i].devnum;
2057                 rdev = conf->mirrors[d].rdev;
2058                 if (!r10_bio->devs[i].bio->bi_status) {
2059                         /* We know that the bi_io_vec layout is the same for
2060                          * both 'first' and 'i', so we just compare them.
2061                          * All vec entries are PAGE_SIZE;
2062                          */
2063                         int sectors = r10_bio->sectors;
2064                         for (j = 0; j < vcnt; j++) {
2065                                 int len = PAGE_SIZE;
2066                                 if (sectors < (len / 512))
2067                                         len = sectors * 512;
2068                                 if (memcmp(page_address(fpages[j]),
2069                                            page_address(tpages[j]),
2070                                            len))
2071                                         break;
2072                                 sectors -= len/512;
2073                         }
2074                         if (j == vcnt)
2075                                 continue;
2076                         atomic64_add(r10_bio->sectors, &mddev->resync_mismatches);
2077                         if (test_bit(MD_RECOVERY_CHECK, &mddev->recovery))
2078                                 /* Don't fix anything. */
2079                                 continue;
2080                 } else if (test_bit(FailFast, &rdev->flags)) {
2081                         /* Just give up on this device */
2082                         md_error(rdev->mddev, rdev);
2083                         continue;
2084                 }
2085                 /* Ok, we need to write this bio, either to correct an
2086                  * inconsistency or to correct an unreadable block.
2087                  * First we need to fixup bv_offset, bv_len and
2088                  * bi_vecs, as the read request might have corrupted these
2089                  */
2090                 rp = get_resync_pages(tbio);
2091                 bio_reset(tbio);
2092
2093                 md_bio_reset_resync_pages(tbio, rp, fbio->bi_iter.bi_size);
2094
2095                 rp->raid_bio = r10_bio;
2096                 tbio->bi_private = rp;
2097                 tbio->bi_iter.bi_sector = r10_bio->devs[i].addr;
2098                 tbio->bi_end_io = end_sync_write;
2099                 bio_set_op_attrs(tbio, REQ_OP_WRITE, 0);
2100
2101                 bio_copy_data(tbio, fbio);
2102
2103                 atomic_inc(&conf->mirrors[d].rdev->nr_pending);
2104                 atomic_inc(&r10_bio->remaining);
2105                 md_sync_acct(conf->mirrors[d].rdev->bdev, bio_sectors(tbio));
2106
2107                 if (test_bit(FailFast, &conf->mirrors[d].rdev->flags))
2108                         tbio->bi_opf |= MD_FAILFAST;
2109                 tbio->bi_iter.bi_sector += conf->mirrors[d].rdev->data_offset;
2110                 bio_set_dev(tbio, conf->mirrors[d].rdev->bdev);
2111                 generic_make_request(tbio);
2112         }
2113
2114         /* Now write out to any replacement devices
2115          * that are active
2116          */
2117         for (i = 0; i < conf->copies; i++) {
2118                 int d;
2119
2120                 tbio = r10_bio->devs[i].repl_bio;
2121                 if (!tbio || !tbio->bi_end_io)
2122                         continue;
2123                 if (r10_bio->devs[i].bio->bi_end_io != end_sync_write
2124                     && r10_bio->devs[i].bio != fbio)
2125                         bio_copy_data(tbio, fbio);
2126                 d = r10_bio->devs[i].devnum;
2127                 atomic_inc(&r10_bio->remaining);
2128                 md_sync_acct(conf->mirrors[d].replacement->bdev,
2129                              bio_sectors(tbio));
2130                 generic_make_request(tbio);
2131         }
2132
2133 done:
2134         if (atomic_dec_and_test(&r10_bio->remaining)) {
2135                 md_done_sync(mddev, r10_bio->sectors, 1);
2136                 put_buf(r10_bio);
2137         }
2138 }
2139
2140 /*
2141  * Now for the recovery code.
2142  * Recovery happens across physical sectors.
2143  * We recover all non-is_sync drives by finding the virtual address of
2144  * each, and then choose a working drive that also has that virt address.
2145  * There is a separate r10_bio for each non-in_sync drive.
2146  * Only the first two slots are in use. The first for reading,
2147  * The second for writing.
2148  *
2149  */
2150 static void fix_recovery_read_error(struct r10bio *r10_bio)
2151 {
2152         /* We got a read error during recovery.
2153          * We repeat the read in smaller page-sized sections.
2154          * If a read succeeds, write it to the new device or record
2155          * a bad block if we cannot.
2156          * If a read fails, record a bad block on both old and
2157          * new devices.
2158          */
2159         struct mddev *mddev = r10_bio->mddev;
2160         struct r10conf *conf = mddev->private;
2161         struct bio *bio = r10_bio->devs[0].bio;
2162         sector_t sect = 0;
2163         int sectors = r10_bio->sectors;
2164         int idx = 0;
2165         int dr = r10_bio->devs[0].devnum;
2166         int dw = r10_bio->devs[1].devnum;
2167         struct page **pages = get_resync_pages(bio)->pages;
2168
2169         while (sectors) {
2170                 int s = sectors;
2171                 struct md_rdev *rdev;
2172                 sector_t addr;
2173                 int ok;
2174
2175                 if (s > (PAGE_SIZE>>9))
2176                         s = PAGE_SIZE >> 9;
2177
2178                 rdev = conf->mirrors[dr].rdev;
2179                 addr = r10_bio->devs[0].addr + sect,
2180                 ok = sync_page_io(rdev,
2181                                   addr,
2182                                   s << 9,
2183                                   pages[idx],
2184                                   REQ_OP_READ, 0, false);
2185                 if (ok) {
2186                         rdev = conf->mirrors[dw].rdev;
2187                         addr = r10_bio->devs[1].addr + sect;
2188                         ok = sync_page_io(rdev,
2189                                           addr,
2190                                           s << 9,
2191                                           pages[idx],
2192                                           REQ_OP_WRITE, 0, false);
2193                         if (!ok) {
2194                                 set_bit(WriteErrorSeen, &rdev->flags);
2195                                 if (!test_and_set_bit(WantReplacement,
2196                                                       &rdev->flags))
2197                                         set_bit(MD_RECOVERY_NEEDED,
2198                                                 &rdev->mddev->recovery);
2199                         }
2200                 }
2201                 if (!ok) {
2202                         /* We don't worry if we cannot set a bad block -
2203                          * it really is bad so there is no loss in not
2204                          * recording it yet
2205                          */
2206                         rdev_set_badblocks(rdev, addr, s, 0);
2207
2208                         if (rdev != conf->mirrors[dw].rdev) {
2209                                 /* need bad block on destination too */
2210                                 struct md_rdev *rdev2 = conf->mirrors[dw].rdev;
2211                                 addr = r10_bio->devs[1].addr + sect;
2212                                 ok = rdev_set_badblocks(rdev2, addr, s, 0);
2213                                 if (!ok) {
2214                                         /* just abort the recovery */
2215                                         pr_notice("md/raid10:%s: recovery aborted due to read error\n",
2216                                                   mdname(mddev));
2217
2218                                         conf->mirrors[dw].recovery_disabled
2219                                                 = mddev->recovery_disabled;
2220                                         set_bit(MD_RECOVERY_INTR,
2221                                                 &mddev->recovery);
2222                                         break;
2223                                 }
2224                         }
2225                 }
2226
2227                 sectors -= s;
2228                 sect += s;
2229                 idx++;
2230         }
2231 }
2232
2233 static void recovery_request_write(struct mddev *mddev, struct r10bio *r10_bio)
2234 {
2235         struct r10conf *conf = mddev->private;
2236         int d;
2237         struct bio *wbio, *wbio2;
2238
2239         if (!test_bit(R10BIO_Uptodate, &r10_bio->state)) {
2240                 fix_recovery_read_error(r10_bio);
2241                 end_sync_request(r10_bio);
2242                 return;
2243         }
2244
2245         /*
2246          * share the pages with the first bio
2247          * and submit the write request
2248          */
2249         d = r10_bio->devs[1].devnum;
2250         wbio = r10_bio->devs[1].bio;
2251         wbio2 = r10_bio->devs[1].repl_bio;
2252         /* Need to test wbio2->bi_end_io before we call
2253          * generic_make_request as if the former is NULL,
2254          * the latter is free to free wbio2.
2255          */
2256         if (wbio2 && !wbio2->bi_end_io)
2257                 wbio2 = NULL;
2258         if (wbio->bi_end_io) {
2259                 atomic_inc(&conf->mirrors[d].rdev->nr_pending);
2260                 md_sync_acct(conf->mirrors[d].rdev->bdev, bio_sectors(wbio));
2261                 generic_make_request(wbio);
2262         }
2263         if (wbio2) {
2264                 atomic_inc(&conf->mirrors[d].replacement->nr_pending);
2265                 md_sync_acct(conf->mirrors[d].replacement->bdev,
2266                              bio_sectors(wbio2));
2267                 generic_make_request(wbio2);
2268         }
2269 }
2270
2271 /*
2272  * Used by fix_read_error() to decay the per rdev read_errors.
2273  * We halve the read error count for every hour that has elapsed
2274  * since the last recorded read error.
2275  *
2276  */
2277 static void check_decay_read_errors(struct mddev *mddev, struct md_rdev *rdev)
2278 {
2279         long cur_time_mon;
2280         unsigned long hours_since_last;
2281         unsigned int read_errors = atomic_read(&rdev->read_errors);
2282
2283         cur_time_mon = ktime_get_seconds();
2284
2285         if (rdev->last_read_error == 0) {
2286                 /* first time we've seen a read error */
2287                 rdev->last_read_error = cur_time_mon;
2288                 return;
2289         }
2290
2291         hours_since_last = (long)(cur_time_mon -
2292                             rdev->last_read_error) / 3600;
2293
2294         rdev->last_read_error = cur_time_mon;
2295
2296         /*
2297          * if hours_since_last is > the number of bits in read_errors
2298          * just set read errors to 0. We do this to avoid
2299          * overflowing the shift of read_errors by hours_since_last.
2300          */
2301         if (hours_since_last >= 8 * sizeof(read_errors))
2302                 atomic_set(&rdev->read_errors, 0);
2303         else
2304                 atomic_set(&rdev->read_errors, read_errors >> hours_since_last);
2305 }
2306
2307 static int r10_sync_page_io(struct md_rdev *rdev, sector_t sector,
2308                             int sectors, struct page *page, int rw)
2309 {
2310         sector_t first_bad;
2311         int bad_sectors;
2312
2313         if (is_badblock(rdev, sector, sectors, &first_bad, &bad_sectors)
2314             && (rw == READ || test_bit(WriteErrorSeen, &rdev->flags)))
2315                 return -1;
2316         if (sync_page_io(rdev, sector, sectors << 9, page, rw, 0, false))
2317                 /* success */
2318                 return 1;
2319         if (rw == WRITE) {
2320                 set_bit(WriteErrorSeen, &rdev->flags);
2321                 if (!test_and_set_bit(WantReplacement, &rdev->flags))
2322                         set_bit(MD_RECOVERY_NEEDED,
2323                                 &rdev->mddev->recovery);
2324         }
2325         /* need to record an error - either for the block or the device */
2326         if (!rdev_set_badblocks(rdev, sector, sectors, 0))
2327                 md_error(rdev->mddev, rdev);
2328         return 0;
2329 }
2330
2331 /*
2332  * This is a kernel thread which:
2333  *
2334  *      1.      Retries failed read operations on working mirrors.
2335  *      2.      Updates the raid superblock when problems encounter.
2336  *      3.      Performs writes following reads for array synchronising.
2337  */
2338
2339 static void fix_read_error(struct r10conf *conf, struct mddev *mddev, struct r10bio *r10_bio)
2340 {
2341         int sect = 0; /* Offset from r10_bio->sector */
2342         int sectors = r10_bio->sectors;
2343         struct md_rdev*rdev;
2344         int max_read_errors = atomic_read(&mddev->max_corr_read_errors);
2345         int d = r10_bio->devs[r10_bio->read_slot].devnum;
2346
2347         /* still own a reference to this rdev, so it cannot
2348          * have been cleared recently.
2349          */
2350         rdev = conf->mirrors[d].rdev;
2351
2352         if (test_bit(Faulty, &rdev->flags))
2353                 /* drive has already been failed, just ignore any
2354                    more fix_read_error() attempts */
2355                 return;
2356
2357         check_decay_read_errors(mddev, rdev);
2358         atomic_inc(&rdev->read_errors);
2359         if (atomic_read(&rdev->read_errors) > max_read_errors) {
2360                 char b[BDEVNAME_SIZE];
2361                 bdevname(rdev->bdev, b);
2362
2363                 pr_notice("md/raid10:%s: %s: Raid device exceeded read_error threshold [cur %d:max %d]\n",
2364                           mdname(mddev), b,
2365                           atomic_read(&rdev->read_errors), max_read_errors);
2366                 pr_notice("md/raid10:%s: %s: Failing raid device\n",
2367                           mdname(mddev), b);
2368                 md_error(mddev, rdev);
2369                 r10_bio->devs[r10_bio->read_slot].bio = IO_BLOCKED;
2370                 return;
2371         }
2372
2373         while(sectors) {
2374                 int s = sectors;
2375                 int sl = r10_bio->read_slot;
2376                 int success = 0;
2377                 int start;
2378
2379                 if (s > (PAGE_SIZE>>9))
2380                         s = PAGE_SIZE >> 9;
2381
2382                 rcu_read_lock();
2383                 do {
2384                         sector_t first_bad;
2385                         int bad_sectors;
2386
2387                         d = r10_bio->devs[sl].devnum;
2388                         rdev = rcu_dereference(conf->mirrors[d].rdev);
2389                         if (rdev &&
2390                             test_bit(In_sync, &rdev->flags) &&
2391                             !test_bit(Faulty, &rdev->flags) &&
2392                             is_badblock(rdev, r10_bio->devs[sl].addr + sect, s,
2393                                         &first_bad, &bad_sectors) == 0) {
2394                                 atomic_inc(&rdev->nr_pending);
2395                                 rcu_read_unlock();
2396                                 success = sync_page_io(rdev,
2397                                                        r10_bio->devs[sl].addr +
2398                                                        sect,
2399                                                        s<<9,
2400                                                        conf->tmppage,
2401                                                        REQ_OP_READ, 0, false);
2402                                 rdev_dec_pending(rdev, mddev);
2403                                 rcu_read_lock();
2404                                 if (success)
2405                                         break;
2406                         }
2407                         sl++;
2408                         if (sl == conf->copies)
2409                                 sl = 0;
2410                 } while (!success && sl != r10_bio->read_slot);
2411                 rcu_read_unlock();
2412
2413                 if (!success) {
2414                         /* Cannot read from anywhere, just mark the block
2415                          * as bad on the first device to discourage future
2416                          * reads.
2417                          */
2418                         int dn = r10_bio->devs[r10_bio->read_slot].devnum;
2419                         rdev = conf->mirrors[dn].rdev;
2420
2421                         if (!rdev_set_badblocks(
2422                                     rdev,
2423                                     r10_bio->devs[r10_bio->read_slot].addr
2424                                     + sect,
2425                                     s, 0)) {
2426                                 md_error(mddev, rdev);
2427                                 r10_bio->devs[r10_bio->read_slot].bio
2428                                         = IO_BLOCKED;
2429                         }
2430                         break;
2431                 }
2432
2433                 start = sl;
2434                 /* write it back and re-read */
2435                 rcu_read_lock();
2436                 while (sl != r10_bio->read_slot) {
2437                         char b[BDEVNAME_SIZE];
2438
2439                         if (sl==0)
2440                                 sl = conf->copies;
2441                         sl--;
2442                         d = r10_bio->devs[sl].devnum;
2443                         rdev = rcu_dereference(conf->mirrors[d].rdev);
2444                         if (!rdev ||
2445                             test_bit(Faulty, &rdev->flags) ||
2446                             !test_bit(In_sync, &rdev->flags))
2447                                 continue;
2448
2449                         atomic_inc(&rdev->nr_pending);
2450                         rcu_read_unlock();
2451                         if (r10_sync_page_io(rdev,
2452                                              r10_bio->devs[sl].addr +
2453                                              sect,
2454                                              s, conf->tmppage, WRITE)
2455                             == 0) {
2456                                 /* Well, this device is dead */
2457                                 pr_notice("md/raid10:%s: read correction write failed (%d sectors at %llu on %s)\n",
2458                                           mdname(mddev), s,
2459                                           (unsigned long long)(
2460                                                   sect +
2461                                                   choose_data_offset(r10_bio,
2462                                                                      rdev)),
2463                                           bdevname(rdev->bdev, b));
2464                                 pr_notice("md/raid10:%s: %s: failing drive\n",
2465                                           mdname(mddev),
2466                                           bdevname(rdev->bdev, b));
2467                         }
2468                         rdev_dec_pending(rdev, mddev);
2469                         rcu_read_lock();
2470                 }
2471                 sl = start;
2472                 while (sl != r10_bio->read_slot) {
2473                         char b[BDEVNAME_SIZE];
2474
2475                         if (sl==0)
2476                                 sl = conf->copies;
2477                         sl--;
2478                         d = r10_bio->devs[sl].devnum;
2479                         rdev = rcu_dereference(conf->mirrors[d].rdev);
2480                         if (!rdev ||
2481                             test_bit(Faulty, &rdev->flags) ||
2482                             !test_bit(In_sync, &rdev->flags))
2483                                 continue;
2484
2485                         atomic_inc(&rdev->nr_pending);
2486                         rcu_read_unlock();
2487                         switch (r10_sync_page_io(rdev,
2488                                              r10_bio->devs[sl].addr +
2489                                              sect,
2490                                              s, conf->tmppage,
2491                                                  READ)) {
2492                         case 0:
2493                                 /* Well, this device is dead */
2494                                 pr_notice("md/raid10:%s: unable to read back corrected sectors (%d sectors at %llu on %s)\n",
2495                                        mdname(mddev), s,
2496                                        (unsigned long long)(
2497                                                sect +
2498                                                choose_data_offset(r10_bio, rdev)),
2499                                        bdevname(rdev->bdev, b));
2500                                 pr_notice("md/raid10:%s: %s: failing drive\n",
2501                                        mdname(mddev),
2502                                        bdevname(rdev->bdev, b));
2503                                 break;
2504                         case 1:
2505                                 pr_info("md/raid10:%s: read error corrected (%d sectors at %llu on %s)\n",
2506                                        mdname(mddev), s,
2507                                        (unsigned long long)(
2508                                                sect +
2509                                                choose_data_offset(r10_bio, rdev)),
2510                                        bdevname(rdev->bdev, b));
2511                                 atomic_add(s, &rdev->corrected_errors);
2512                         }
2513
2514                         rdev_dec_pending(rdev, mddev);
2515                         rcu_read_lock();
2516                 }
2517                 rcu_read_unlock();
2518
2519                 sectors -= s;
2520                 sect += s;
2521         }
2522 }
2523
2524 static int narrow_write_error(struct r10bio *r10_bio, int i)
2525 {
2526         struct bio *bio = r10_bio->master_bio;
2527         struct mddev *mddev = r10_bio->mddev;
2528         struct r10conf *conf = mddev->private;
2529         struct md_rdev *rdev = conf->mirrors[r10_bio->devs[i].devnum].rdev;
2530         /* bio has the data to be written to slot 'i' where
2531          * we just recently had a write error.
2532          * We repeatedly clone the bio and trim down to one block,
2533          * then try the write.  Where the write fails we record
2534          * a bad block.
2535          * It is conceivable that the bio doesn't exactly align with
2536          * blocks.  We must handle this.
2537          *
2538          * We currently own a reference to the rdev.
2539          */
2540
2541         int block_sectors;
2542         sector_t sector;
2543         int sectors;
2544         int sect_to_write = r10_bio->sectors;
2545         int ok = 1;
2546
2547         if (rdev->badblocks.shift < 0)
2548                 return 0;
2549
2550         block_sectors = roundup(1 << rdev->badblocks.shift,
2551                                 bdev_logical_block_size(rdev->bdev) >> 9);
2552         sector = r10_bio->sector;
2553         sectors = ((r10_bio->sector + block_sectors)
2554                    & ~(sector_t)(block_sectors - 1))
2555                 - sector;
2556
2557         while (sect_to_write) {
2558                 struct bio *wbio;
2559                 sector_t wsector;
2560                 if (sectors > sect_to_write)
2561                         sectors = sect_to_write;
2562                 /* Write at 'sector' for 'sectors' */
2563                 wbio = bio_clone_fast(bio, GFP_NOIO, mddev->bio_set);
2564                 bio_trim(wbio, sector - bio->bi_iter.bi_sector, sectors);
2565                 wsector = r10_bio->devs[i].addr + (sector - r10_bio->sector);
2566                 wbio->bi_iter.bi_sector = wsector +
2567                                    choose_data_offset(r10_bio, rdev);
2568                 bio_set_dev(wbio, rdev->bdev);
2569                 bio_set_op_attrs(wbio, REQ_OP_WRITE, 0);
2570
2571                 if (submit_bio_wait(wbio) < 0)
2572                         /* Failure! */
2573                         ok = rdev_set_badblocks(rdev, wsector,
2574                                                 sectors, 0)
2575                                 && ok;
2576
2577                 bio_put(wbio);
2578                 sect_to_write -= sectors;
2579                 sector += sectors;
2580                 sectors = block_sectors;
2581         }
2582         return ok;
2583 }
2584
2585 static void handle_read_error(struct mddev *mddev, struct r10bio *r10_bio)
2586 {
2587         int slot = r10_bio->read_slot;
2588         struct bio *bio;
2589         struct r10conf *conf = mddev->private;
2590         struct md_rdev *rdev = r10_bio->devs[slot].rdev;
2591         sector_t bio_last_sector;
2592
2593         /* we got a read error. Maybe the drive is bad.  Maybe just
2594          * the block and we can fix it.
2595          * We freeze all other IO, and try reading the block from
2596          * other devices.  When we find one, we re-write
2597          * and check it that fixes the read error.
2598          * This is all done synchronously while the array is
2599          * frozen.
2600          */
2601         bio = r10_bio->devs[slot].bio;
2602         bio_last_sector = r10_bio->devs[slot].addr + rdev->data_offset + r10_bio->sectors;
2603         bio_put(bio);
2604         r10_bio->devs[slot].bio = NULL;
2605
2606         if (mddev->ro)
2607                 r10_bio->devs[slot].bio = IO_BLOCKED;
2608         else if (!test_bit(FailFast, &rdev->flags)) {
2609                 freeze_array(conf, 1);
2610                 fix_read_error(conf, mddev, r10_bio);
2611                 unfreeze_array(conf);
2612         } else
2613                 md_error(mddev, rdev);
2614
2615         rdev_dec_pending(rdev, mddev);
2616         allow_barrier(conf);
2617         r10_bio->state = 0;
2618         raid10_read_request(mddev, r10_bio->master_bio, r10_bio);
2619 }
2620
2621 static void handle_write_completed(struct r10conf *conf, struct r10bio *r10_bio)
2622 {
2623         /* Some sort of write request has finished and it
2624          * succeeded in writing where we thought there was a
2625          * bad block.  So forget the bad block.
2626          * Or possibly if failed and we need to record
2627          * a bad block.
2628          */
2629         int m;
2630         struct md_rdev *rdev;
2631
2632         if (test_bit(R10BIO_IsSync, &r10_bio->state) ||
2633             test_bit(R10BIO_IsRecover, &r10_bio->state)) {
2634                 for (m = 0; m < conf->copies; m++) {
2635                         int dev = r10_bio->devs[m].devnum;
2636                         rdev = conf->mirrors[dev].rdev;
2637                         if (r10_bio->devs[m].bio == NULL ||
2638                                 r10_bio->devs[m].bio->bi_end_io == NULL)
2639                                 continue;
2640                         if (!r10_bio->devs[m].bio->bi_status) {
2641                                 rdev_clear_badblocks(
2642                                         rdev,
2643                                         r10_bio->devs[m].addr,
2644                                         r10_bio->sectors, 0);
2645                         } else {
2646                                 if (!rdev_set_badblocks(
2647                                             rdev,
2648                                             r10_bio->devs[m].addr,
2649                                             r10_bio->sectors, 0))
2650                                         md_error(conf->mddev, rdev);
2651                         }
2652                         rdev = conf->mirrors[dev].replacement;
2653                         if (r10_bio->devs[m].repl_bio == NULL ||
2654                                 r10_bio->devs[m].repl_bio->bi_end_io == NULL)
2655                                 continue;
2656
2657                         if (!r10_bio->devs[m].repl_bio->bi_status) {
2658                                 rdev_clear_badblocks(
2659                                         rdev,
2660                                         r10_bio->devs[m].addr,
2661                                         r10_bio->sectors, 0);
2662                         } else {
2663                                 if (!rdev_set_badblocks(
2664                                             rdev,
2665                                             r10_bio->devs[m].addr,
2666                                             r10_bio->sectors, 0))
2667                                         md_error(conf->mddev, rdev);
2668                         }
2669                 }
2670                 put_buf(r10_bio);
2671         } else {
2672                 bool fail = false;
2673                 for (m = 0; m < conf->copies; m++) {
2674                         int dev = r10_bio->devs[m].devnum;
2675                         struct bio *bio = r10_bio->devs[m].bio;
2676                         rdev = conf->mirrors[dev].rdev;
2677                         if (bio == IO_MADE_GOOD) {
2678                                 rdev_clear_badblocks(
2679                                         rdev,
2680                                         r10_bio->devs[m].addr,
2681                                         r10_bio->sectors, 0);
2682                                 rdev_dec_pending(rdev, conf->mddev);
2683                         } else if (bio != NULL && bio->bi_status) {
2684                                 fail = true;
2685                                 if (!narrow_write_error(r10_bio, m)) {
2686                                         md_error(conf->mddev, rdev);
2687                                         set_bit(R10BIO_Degraded,
2688                                                 &r10_bio->state);
2689                                 }
2690                                 rdev_dec_pending(rdev, conf->mddev);
2691                         }
2692                         bio = r10_bio->devs[m].repl_bio;
2693                         rdev = conf->mirrors[dev].replacement;
2694                         if (rdev && bio == IO_MADE_GOOD) {
2695                                 rdev_clear_badblocks(
2696                                         rdev,
2697                                         r10_bio->devs[m].addr,
2698                                         r10_bio->sectors, 0);
2699                                 rdev_dec_pending(rdev, conf->mddev);
2700                         }
2701                 }
2702                 if (fail) {
2703                         spin_lock_irq(&conf->device_lock);
2704                         list_add(&r10_bio->retry_list, &conf->bio_end_io_list);
2705                         conf->nr_queued++;
2706                         spin_unlock_irq(&conf->device_lock);
2707                         /*
2708                          * In case freeze_array() is waiting for condition
2709                          * nr_pending == nr_queued + extra to be true.
2710                          */
2711                         wake_up(&conf->wait_barrier);
2712                         md_wakeup_thread(conf->mddev->thread);
2713                 } else {
2714                         if (test_bit(R10BIO_WriteError,
2715                                      &r10_bio->state))
2716                                 close_write(r10_bio);
2717                         raid_end_bio_io(r10_bio);
2718                 }
2719         }
2720 }
2721
2722 static void raid10d(struct md_thread *thread)
2723 {
2724         struct mddev *mddev = thread->mddev;
2725         struct r10bio *r10_bio;
2726         unsigned long flags;
2727         struct r10conf *conf = mddev->private;
2728         struct list_head *head = &conf->retry_list;
2729         struct blk_plug plug;
2730
2731         md_check_recovery(mddev);
2732
2733         if (!list_empty_careful(&conf->bio_end_io_list) &&
2734             !test_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags)) {
2735                 LIST_HEAD(tmp);
2736                 spin_lock_irqsave(&conf->device_lock, flags);
2737                 if (!test_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags)) {
2738                         while (!list_empty(&conf->bio_end_io_list)) {
2739                                 list_move(conf->bio_end_io_list.prev, &tmp);
2740                                 conf->nr_queued--;
2741                         }
2742                 }
2743                 spin_unlock_irqrestore(&conf->device_lock, flags);
2744                 while (!list_empty(&tmp)) {
2745                         r10_bio = list_first_entry(&tmp, struct r10bio,
2746                                                    retry_list);
2747                         list_del(&r10_bio->retry_list);
2748                         if (mddev->degraded)
2749                                 set_bit(R10BIO_Degraded, &r10_bio->state);
2750
2751                         if (test_bit(R10BIO_WriteError,
2752                                      &r10_bio->state))
2753                                 close_write(r10_bio);
2754                         raid_end_bio_io(r10_bio);
2755                 }
2756         }
2757
2758         blk_start_plug(&plug);
2759         for (;;) {
2760
2761                 flush_pending_writes(conf);
2762
2763                 spin_lock_irqsave(&conf->device_lock, flags);
2764                 if (list_empty(head)) {
2765                         spin_unlock_irqrestore(&conf->device_lock, flags);
2766                         break;
2767                 }
2768                 r10_bio = list_entry(head->prev, struct r10bio, retry_list);
2769                 list_del(head->prev);
2770                 conf->nr_queued--;
2771                 spin_unlock_irqrestore(&conf->device_lock, flags);
2772
2773                 mddev = r10_bio->mddev;
2774                 conf = mddev->private;
2775                 if (test_bit(R10BIO_MadeGood, &r10_bio->state) ||
2776                     test_bit(R10BIO_WriteError, &r10_bio->state))
2777                         handle_write_completed(conf, r10_bio);
2778                 else if (test_bit(R10BIO_IsReshape, &r10_bio->state))
2779                         reshape_request_write(mddev, r10_bio);
2780                 else if (test_bit(R10BIO_IsSync, &r10_bio->state))
2781                         sync_request_write(mddev, r10_bio);
2782                 else if (test_bit(R10BIO_IsRecover, &r10_bio->state))
2783                         recovery_request_write(mddev, r10_bio);
2784                 else if (test_bit(R10BIO_ReadError, &r10_bio->state))
2785                         handle_read_error(mddev, r10_bio);
2786                 else
2787                         WARN_ON_ONCE(1);
2788
2789                 cond_resched();
2790                 if (mddev->sb_flags & ~(1<<MD_SB_CHANGE_PENDING))
2791                         md_check_recovery(mddev);
2792         }
2793         blk_finish_plug(&plug);
2794 }
2795
2796 static int init_resync(struct r10conf *conf)
2797 {
2798         int buffs;
2799         int i;
2800
2801         buffs = RESYNC_WINDOW / RESYNC_BLOCK_SIZE;
2802         BUG_ON(conf->r10buf_pool);
2803         conf->have_replacement = 0;
2804         for (i = 0; i < conf->geo.raid_disks; i++)
2805                 if (conf->mirrors[i].replacement)
2806                         conf->have_replacement = 1;
2807         conf->r10buf_pool = mempool_create(buffs, r10buf_pool_alloc, r10buf_pool_free, conf);
2808         if (!conf->r10buf_pool)
2809                 return -ENOMEM;
2810         conf->next_resync = 0;
2811         return 0;
2812 }
2813
2814 static struct r10bio *raid10_alloc_init_r10buf(struct r10conf *conf)
2815 {
2816         struct r10bio *r10bio = mempool_alloc(conf->r10buf_pool, GFP_NOIO);
2817         struct rsync_pages *rp;
2818         struct bio *bio;
2819         int nalloc;
2820         int i;
2821
2822         if (test_bit(MD_RECOVERY_SYNC, &conf->mddev->recovery) ||
2823             test_bit(MD_RECOVERY_RESHAPE, &conf->mddev->recovery))
2824                 nalloc = conf->copies; /* resync */
2825         else
2826                 nalloc = 2; /* recovery */
2827
2828         for (i = 0; i < nalloc; i++) {
2829                 bio = r10bio->devs[i].bio;
2830                 rp = bio->bi_private;
2831                 bio_reset(bio);
2832                 bio->bi_private = rp;
2833                 bio = r10bio->devs[i].repl_bio;
2834                 if (bio) {
2835                         rp = bio->bi_private;
2836                         bio_reset(bio);
2837                         bio->bi_private = rp;
2838                 }
2839         }
2840         return r10bio;
2841 }
2842
2843 /*
2844  * perform a "sync" on one "block"
2845  *
2846  * We need to make sure that no normal I/O request - particularly write
2847  * requests - conflict with active sync requests.
2848  *
2849  * This is achieved by tracking pending requests and a 'barrier' concept
2850  * that can be installed to exclude normal IO requests.
2851  *
2852  * Resync and recovery are handled very differently.
2853  * We differentiate by looking at MD_RECOVERY_SYNC in mddev->recovery.
2854  *
2855  * For resync, we iterate over virtual addresses, read all copies,
2856  * and update if there are differences.  If only one copy is live,
2857  * skip it.
2858  * For recovery, we iterate over physical addresses, read a good
2859  * value for each non-in_sync drive, and over-write.
2860  *
2861  * So, for recovery we may have several outstanding complex requests for a
2862  * given address, one for each out-of-sync device.  We model this by allocating
2863  * a number of r10_bio structures, one for each out-of-sync device.
2864  * As we setup these structures, we collect all bio's together into a list
2865  * which we then process collectively to add pages, and then process again
2866  * to pass to generic_make_request.
2867  *
2868  * The r10_bio structures are linked using a borrowed master_bio pointer.
2869  * This link is counted in ->remaining.  When the r10_bio that points to NULL
2870  * has its remaining count decremented to 0, the whole complex operation
2871  * is complete.
2872  *
2873  */
2874
2875 static sector_t raid10_sync_request(struct mddev *mddev, sector_t sector_nr,
2876                              int *skipped)
2877 {
2878         struct r10conf *conf = mddev->private;
2879         struct r10bio *r10_bio;
2880         struct bio *biolist = NULL, *bio;
2881         sector_t max_sector, nr_sectors;
2882         int i;
2883         int max_sync;
2884         sector_t sync_blocks;
2885         sector_t sectors_skipped = 0;
2886         int chunks_skipped = 0;
2887         sector_t chunk_mask = conf->geo.chunk_mask;
2888         int page_idx = 0;
2889
2890         if (!conf->r10buf_pool)
2891                 if (init_resync(conf))
2892                         return 0;
2893
2894         /*
2895          * Allow skipping a full rebuild for incremental assembly
2896          * of a clean array, like RAID1 does.
2897          */
2898         if (mddev->bitmap == NULL &&
2899             mddev->recovery_cp == MaxSector &&
2900             mddev->reshape_position == MaxSector &&
2901             !test_bit(MD_RECOVERY_SYNC, &mddev->recovery) &&
2902             !test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery) &&
2903             !test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery) &&
2904             conf->fullsync == 0) {
2905                 *skipped = 1;
2906                 return mddev->dev_sectors - sector_nr;
2907         }
2908
2909  skipped:
2910         max_sector = mddev->dev_sectors;
2911         if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery) ||
2912             test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery))
2913                 max_sector = mddev->resync_max_sectors;
2914         if (sector_nr >= max_sector) {
2915                 /* If we aborted, we need to abort the
2916                  * sync on the 'current' bitmap chucks (there can
2917                  * be several when recovering multiple devices).
2918                  * as we may have started syncing it but not finished.
2919                  * We can find the current address in
2920                  * mddev->curr_resync, but for recovery,
2921                  * we need to convert that to several
2922                  * virtual addresses.
2923                  */
2924                 if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery)) {
2925                         end_reshape(conf);
2926                         close_sync(conf);
2927                         return 0;
2928                 }
2929
2930                 if (mddev->curr_resync < max_sector) { /* aborted */
2931                         if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery))
2932                                 bitmap_end_sync(mddev->bitmap, mddev->curr_resync,
2933                                                 &sync_blocks, 1);
2934                         else for (i = 0; i < conf->geo.raid_disks; i++) {
2935                                 sector_t sect =
2936                                         raid10_find_virt(conf, mddev->curr_resync, i);
2937                                 bitmap_end_sync(mddev->bitmap, sect,
2938                                                 &sync_blocks, 1);
2939                         }
2940                 } else {
2941                         /* completed sync */
2942                         if ((!mddev->bitmap || conf->fullsync)
2943                             && conf->have_replacement
2944                             && test_bit(MD_RECOVERY_SYNC, &mddev->recovery)) {
2945                                 /* Completed a full sync so the replacements
2946                                  * are now fully recovered.
2947                                  */
2948                                 rcu_read_lock();
2949                                 for (i = 0; i < conf->geo.raid_disks; i++) {
2950                                         struct md_rdev *rdev =
2951                                                 rcu_dereference(conf->mirrors[i].replacement);
2952                                         if (rdev)
2953                                                 rdev->recovery_offset = MaxSector;
2954                                 }
2955                                 rcu_read_unlock();
2956                         }
2957                         conf->fullsync = 0;
2958                 }
2959                 bitmap_close_sync(mddev->bitmap);
2960                 close_sync(conf);
2961                 *skipped = 1;
2962                 return sectors_skipped;
2963         }
2964
2965         if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery))
2966                 return reshape_request(mddev, sector_nr, skipped);
2967
2968         if (chunks_skipped >= conf->geo.raid_disks) {
2969                 /* if there has been nothing to do on any drive,
2970                  * then there is nothing to do at all..
2971                  */
2972                 *skipped = 1;
2973                 return (max_sector - sector_nr) + sectors_skipped;
2974         }
2975
2976         if (max_sector > mddev->resync_max)
2977                 max_sector = mddev->resync_max; /* Don't do IO beyond here */
2978
2979         /* make sure whole request will fit in a chunk - if chunks
2980          * are meaningful
2981          */
2982         if (conf->geo.near_copies < conf->geo.raid_disks &&
2983             max_sector > (sector_nr | chunk_mask))
2984                 max_sector = (sector_nr | chunk_mask) + 1;
2985
2986         /*
2987          * If there is non-resync activity waiting for a turn, then let it
2988          * though before starting on this new sync request.
2989          */
2990         if (conf->nr_waiting)
2991                 schedule_timeout_uninterruptible(1);
2992
2993         /* Again, very different code for resync and recovery.
2994          * Both must result in an r10bio with a list of bios that
2995          * have bi_end_io, bi_sector, bi_disk set,
2996          * and bi_private set to the r10bio.
2997          * For recovery, we may actually create several r10bios
2998          * with 2 bios in each, that correspond to the bios in the main one.
2999          * In this case, the subordinate r10bios link back through a
3000          * borrowed master_bio pointer, and the counter in the master
3001          * includes a ref from each subordinate.
3002          */
3003         /* First, we decide what to do and set ->bi_end_io
3004          * To end_sync_read if we want to read, and
3005          * end_sync_write if we will want to write.
3006          */
3007
3008         max_sync = RESYNC_PAGES << (PAGE_SHIFT-9);
3009         if (!test_bit(MD_RECOVERY_SYNC, &mddev->recovery)) {
3010                 /* recovery... the complicated one */
3011                 int j;
3012                 r10_bio = NULL;
3013
3014                 for (i = 0 ; i < conf->geo.raid_disks; i++) {
3015                         int still_degraded;
3016                         struct r10bio *rb2;
3017                         sector_t sect;
3018                         int must_sync;
3019                         int any_working;
3020                         struct raid10_info *mirror = &conf->mirrors[i];
3021                         struct md_rdev *mrdev, *mreplace;
3022
3023                         rcu_read_lock();
3024                         mrdev = rcu_dereference(mirror->rdev);
3025                         mreplace = rcu_dereference(mirror->replacement);
3026
3027                         if ((mrdev == NULL ||
3028                              test_bit(Faulty, &mrdev->flags) ||
3029                              test_bit(In_sync, &mrdev->flags)) &&
3030                             (mreplace == NULL ||
3031                              test_bit(Faulty, &mreplace->flags))) {
3032                                 rcu_read_unlock();
3033                                 continue;
3034                         }
3035
3036                         still_degraded = 0;
3037                         /* want to reconstruct this device */
3038                         rb2 = r10_bio;
3039                         sect = raid10_find_virt(conf, sector_nr, i);
3040                         if (sect >= mddev->resync_max_sectors) {
3041                                 /* last stripe is not complete - don't
3042                                  * try to recover this sector.
3043                                  */
3044                                 rcu_read_unlock();
3045                                 continue;
3046                         }
3047                         if (mreplace && test_bit(Faulty, &mreplace->flags))
3048                                 mreplace = NULL;
3049                         /* Unless we are doing a full sync, or a replacement
3050                          * we only need to recover the block if it is set in
3051                          * the bitmap
3052                          */
3053                         must_sync = bitmap_start_sync(mddev->bitmap, sect,
3054                                                       &sync_blocks, 1);
3055                         if (sync_blocks < max_sync)
3056                                 max_sync = sync_blocks;
3057                         if (!must_sync &&
3058                             mreplace == NULL &&
3059                             !conf->fullsync) {
3060                                 /* yep, skip the sync_blocks here, but don't assume
3061                                  * that there will never be anything to do here
3062                                  */
3063                                 chunks_skipped = -1;
3064                                 rcu_read_unlock();
3065                                 continue;
3066                         }
3067                         atomic_inc(&mrdev->nr_pending);
3068                         if (mreplace)
3069                                 atomic_inc(&mreplace->nr_pending);
3070                         rcu_read_unlock();
3071
3072                         r10_bio = raid10_alloc_init_r10buf(conf);
3073                         r10_bio->state = 0;
3074                         raise_barrier(conf, rb2 != NULL);
3075                         atomic_set(&r10_bio->remaining, 0);
3076
3077                         r10_bio->master_bio = (struct bio*)rb2;
3078                         if (rb2)
3079                                 atomic_inc(&rb2->remaining);
3080                         r10_bio->mddev = mddev;
3081                         set_bit(R10BIO_IsRecover, &r10_bio->state);
3082                         r10_bio->sector = sect;
3083
3084                         raid10_find_phys(conf, r10_bio);
3085
3086                         /* Need to check if the array will still be
3087                          * degraded
3088                          */
3089                         rcu_read_lock();
3090                         for (j = 0; j < conf->geo.raid_disks; j++) {
3091                                 struct md_rdev *rdev = rcu_dereference(
3092                                         conf->mirrors[j].rdev);
3093                                 if (rdev == NULL || test_bit(Faulty, &rdev->flags)) {
3094                                         still_degraded = 1;
3095                                         break;
3096                                 }
3097                         }
3098
3099                         must_sync = bitmap_start_sync(mddev->bitmap, sect,
3100                                                       &sync_blocks, still_degraded);
3101
3102                         any_working = 0;
3103                         for (j=0; j<conf->copies;j++) {
3104                                 int k;
3105                                 int d = r10_bio->devs[j].devnum;
3106                                 sector_t from_addr, to_addr;
3107                                 struct md_rdev *rdev =
3108                                         rcu_dereference(conf->mirrors[d].rdev);
3109                                 sector_t sector, first_bad;
3110                                 int bad_sectors;
3111                                 if (!rdev ||
3112                                     !test_bit(In_sync, &rdev->flags))
3113                                         continue;
3114                                 /* This is where we read from */
3115                                 any_working = 1;
3116                                 sector = r10_bio->devs[j].addr;
3117
3118                                 if (is_badblock(rdev, sector, max_sync,
3119                                                 &first_bad, &bad_sectors)) {
3120                                         if (first_bad > sector)
3121                                                 max_sync = first_bad - sector;
3122                                         else {
3123                                                 bad_sectors -= (sector
3124                                                                 - first_bad);
3125                                                 if (max_sync > bad_sectors)
3126                                                         max_sync = bad_sectors;
3127                                                 continue;
3128                                         }
3129                                 }
3130                                 bio = r10_bio->devs[0].bio;
3131                                 bio->bi_next = biolist;
3132                                 biolist = bio;
3133                                 bio->bi_end_io = end_sync_read;
3134                                 bio_set_op_attrs(bio, REQ_OP_READ, 0);
3135                                 if (test_bit(FailFast, &rdev->flags))
3136                                         bio->bi_opf |= MD_FAILFAST;
3137                                 from_addr = r10_bio->devs[j].addr;
3138                                 bio->bi_iter.bi_sector = from_addr +
3139                                         rdev->data_offset;
3140                                 bio_set_dev(bio, rdev->bdev);
3141                                 atomic_inc(&rdev->nr_pending);
3142                                 /* and we write to 'i' (if not in_sync) */
3143
3144                                 for (k=0; k<conf->copies; k++)
3145                                         if (r10_bio->devs[k].devnum == i)
3146                                                 break;
3147                                 BUG_ON(k == conf->copies);
3148                                 to_addr = r10_bio->devs[k].addr;
3149                                 r10_bio->devs[0].devnum = d;
3150                                 r10_bio->devs[0].addr = from_addr;
3151                                 r10_bio->devs[1].devnum = i;
3152                                 r10_bio->devs[1].addr = to_addr;
3153
3154                                 if (!test_bit(In_sync, &mrdev->flags)) {
3155                                         bio = r10_bio->devs[1].bio;
3156                                         bio->bi_next = biolist;
3157                                         biolist = bio;
3158                                         bio->bi_end_io = end_sync_write;
3159                                         bio_set_op_attrs(bio, REQ_OP_WRITE, 0);
3160                                         bio->bi_iter.bi_sector = to_addr
3161                                                 + mrdev->data_offset;
3162                                         bio_set_dev(bio, mrdev->bdev);
3163                                         atomic_inc(&r10_bio->remaining);
3164                                 } else
3165                                         r10_bio->devs[1].bio->bi_end_io = NULL;
3166
3167                                 /* and maybe write to replacement */
3168                                 bio = r10_bio->devs[1].repl_bio;
3169                                 if (bio)
3170                                         bio->bi_end_io = NULL;
3171                                 /* Note: if mreplace != NULL, then bio
3172                                  * cannot be NULL as r10buf_pool_alloc will
3173                                  * have allocated it.
3174                                  * So the second test here is pointless.
3175                                  * But it keeps semantic-checkers happy, and
3176                                  * this comment keeps human reviewers
3177                                  * happy.
3178                                  */
3179                                 if (mreplace == NULL || bio == NULL ||
3180                                     test_bit(Faulty, &mreplace->flags))
3181                                         break;
3182                                 bio->bi_next = biolist;
3183                                 biolist = bio;
3184                                 bio->bi_end_io = end_sync_write;
3185                                 bio_set_op_attrs(bio, REQ_OP_WRITE, 0);
3186                                 bio->bi_iter.bi_sector = to_addr +
3187                                         mreplace->data_offset;
3188                                 bio_set_dev(bio, mreplace->bdev);
3189                                 atomic_inc(&r10_bio->remaining);
3190                                 break;
3191                         }
3192                         rcu_read_unlock();
3193                         if (j == conf->copies) {
3194                                 /* Cannot recover, so abort the recovery or
3195                                  * record a bad block */
3196                                 if (any_working) {
3197                                         /* problem is that there are bad blocks
3198                                          * on other device(s)
3199                                          */
3200                                         int k;
3201                                         for (k = 0; k < conf->copies; k++)
3202                                                 if (r10_bio->devs[k].devnum == i)
3203                                                         break;
3204                                         if (!test_bit(In_sync,
3205                                                       &mrdev->flags)
3206                                             && !rdev_set_badblocks(
3207                                                     mrdev,
3208                                                     r10_bio->devs[k].addr,
3209                                                     max_sync, 0))
3210                                                 any_working = 0;
3211                                         if (mreplace &&
3212                                             !rdev_set_badblocks(
3213                                                     mreplace,
3214                                                     r10_bio->devs[k].addr,
3215                                                     max_sync, 0))
3216                                                 any_working = 0;
3217                                 }
3218                                 if (!any_working)  {
3219                                         if (!test_and_set_bit(MD_RECOVERY_INTR,
3220                                                               &mddev->recovery))
3221                                                 pr_warn("md/raid10:%s: insufficient working devices for recovery.\n",
3222                                                        mdname(mddev));
3223                                         mirror->recovery_disabled
3224                                                 = mddev->recovery_disabled;
3225                                 }
3226                                 put_buf(r10_bio);
3227                                 if (rb2)
3228                                         atomic_dec(&rb2->remaining);
3229                                 r10_bio = rb2;
3230                                 rdev_dec_pending(mrdev, mddev);
3231                                 if (mreplace)
3232                                         rdev_dec_pending(mreplace, mddev);
3233                                 break;
3234                         }
3235                         rdev_dec_pending(mrdev, mddev);
3236                         if (mreplace)
3237                                 rdev_dec_pending(mreplace, mddev);
3238                         if (r10_bio->devs[0].bio->bi_opf & MD_FAILFAST) {
3239                                 /* Only want this if there is elsewhere to
3240                                  * read from. 'j' is currently the first
3241                                  * readable copy.
3242                                  */
3243                                 int targets = 1;
3244                                 for (; j < conf->copies; j++) {
3245                                         int d = r10_bio->devs[j].devnum;
3246                                         if (conf->mirrors[d].rdev &&
3247                                             test_bit(In_sync,
3248                                                       &conf->mirrors[d].rdev->flags))
3249                                                 targets++;
3250                                 }
3251                                 if (targets == 1)
3252                                         r10_bio->devs[0].bio->bi_opf
3253                                                 &= ~MD_FAILFAST;
3254                         }
3255                 }
3256                 if (biolist == NULL) {
3257                         while (r10_bio) {
3258                                 struct r10bio *rb2 = r10_bio;
3259                                 r10_bio = (struct r10bio*) rb2->master_bio;
3260                                 rb2->master_bio = NULL;
3261                                 put_buf(rb2);
3262                         }
3263                         goto giveup;
3264                 }
3265         } else {
3266                 /* resync. Schedule a read for every block at this virt offset */
3267                 int count = 0;
3268
3269                 bitmap_cond_end_sync(mddev->bitmap, sector_nr, 0);
3270
3271                 if (!bitmap_start_sync(mddev->bitmap, sector_nr,
3272                                        &sync_blocks, mddev->degraded) &&
3273                     !conf->fullsync && !test_bit(MD_RECOVERY_REQUESTED,
3274                                                  &mddev->recovery)) {
3275                         /* We can skip this block */
3276                         *skipped = 1;
3277                         return sync_blocks + sectors_skipped;
3278                 }
3279                 if (sync_blocks < max_sync)
3280                         max_sync = sync_blocks;
3281                 r10_bio = raid10_alloc_init_r10buf(conf);
3282                 r10_bio->state = 0;
3283
3284                 r10_bio->mddev = mddev;
3285                 atomic_set(&r10_bio->remaining, 0);
3286                 raise_barrier(conf, 0);
3287                 conf->next_resync = sector_nr;
3288
3289                 r10_bio->master_bio = NULL;
3290                 r10_bio->sector = sector_nr;
3291                 set_bit(R10BIO_IsSync, &r10_bio->state);
3292                 raid10_find_phys(conf, r10_bio);
3293                 r10_bio->sectors = (sector_nr | chunk_mask) - sector_nr + 1;
3294
3295                 for (i = 0; i < conf->copies; i++) {
3296                         int d = r10_bio->devs[i].devnum;
3297                         sector_t first_bad, sector;
3298                         int bad_sectors;
3299                         struct md_rdev *rdev;
3300
3301                         if (r10_bio->devs[i].repl_bio)
3302                                 r10_bio->devs[i].repl_bio->bi_end_io = NULL;
3303
3304                         bio = r10_bio->devs[i].bio;
3305                         bio->bi_status = BLK_STS_IOERR;
3306                         rcu_read_lock();
3307                         rdev = rcu_dereference(conf->mirrors[d].rdev);
3308                         if (rdev == NULL || test_bit(Faulty, &rdev->flags)) {
3309                                 rcu_read_unlock();
3310                                 continue;
3311                         }
3312                         sector = r10_bio->devs[i].addr;
3313                         if (is_badblock(rdev, sector, max_sync,
3314                                         &first_bad, &bad_sectors)) {
3315                                 if (first_bad > sector)
3316                                         max_sync = first_bad - sector;
3317                                 else {
3318                                         bad_sectors -= (sector - first_bad);
3319                                         if (max_sync > bad_sectors)
3320                                                 max_sync = bad_sectors;
3321                                         rcu_read_unlock();
3322                                         continue;
3323                                 }
3324                         }
3325                         atomic_inc(&rdev->nr_pending);
3326                         atomic_inc(&r10_bio->remaining);
3327                         bio->bi_next = biolist;
3328                         biolist = bio;
3329                         bio->bi_end_io = end_sync_read;
3330                         bio_set_op_attrs(bio, REQ_OP_READ, 0);
3331                         if (test_bit(FailFast, &rdev->flags))
3332                                 bio->bi_opf |= MD_FAILFAST;
3333                         bio->bi_iter.bi_sector = sector + rdev->data_offset;
3334                         bio_set_dev(bio, rdev->bdev);
3335                         count++;
3336
3337                         rdev = rcu_dereference(conf->mirrors[d].replacement);
3338                         if (rdev == NULL || test_bit(Faulty, &rdev->flags)) {
3339                                 rcu_read_unlock();
3340                                 continue;
3341                         }
3342                         atomic_inc(&rdev->nr_pending);
3343
3344                         /* Need to set up for writing to the replacement */
3345                         bio = r10_bio->devs[i].repl_bio;
3346                         bio->bi_status = BLK_STS_IOERR;
3347
3348                         sector = r10_bio->devs[i].addr;
3349                         bio->bi_next = biolist;
3350                         biolist = bio;
3351                         bio->bi_end_io = end_sync_write;
3352                         bio_set_op_attrs(bio, REQ_OP_WRITE, 0);
3353                         if (test_bit(FailFast, &rdev->flags))
3354                                 bio->bi_opf |= MD_FAILFAST;
3355                         bio->bi_iter.bi_sector = sector + rdev->data_offset;
3356                         bio_set_dev(bio, rdev->bdev);
3357                         count++;
3358                         rcu_read_unlock();
3359                 }
3360
3361                 if (count < 2) {
3362                         for (i=0; i<conf->copies; i++) {
3363                                 int d = r10_bio->devs[i].devnum;
3364                                 if (r10_bio->devs[i].bio->bi_end_io)
3365                                         rdev_dec_pending(conf->mirrors[d].rdev,
3366                                                          mddev);
3367                                 if (r10_bio->devs[i].repl_bio &&
3368                                     r10_bio->devs[i].repl_bio->bi_end_io)
3369                                         rdev_dec_pending(
3370                                                 conf->mirrors[d].replacement,
3371                                                 mddev);
3372                         }
3373                         put_buf(r10_bio);
3374                         biolist = NULL;
3375                         goto giveup;
3376                 }
3377         }
3378
3379         nr_sectors = 0;
3380         if (sector_nr + max_sync < max_sector)
3381                 max_sector = sector_nr + max_sync;
3382         do {
3383                 struct page *page;
3384                 int len = PAGE_SIZE;
3385                 if (sector_nr + (len>>9) > max_sector)
3386                         len = (max_sector - sector_nr) << 9;
3387                 if (len == 0)
3388                         break;
3389                 for (bio= biolist ; bio ; bio=bio->bi_next) {
3390                         struct resync_pages *rp = get_resync_pages(bio);
3391                         page = resync_fetch_page(rp, page_idx);
3392                         /*
3393                          * won't fail because the vec table is big enough
3394                          * to hold all these pages
3395                          */
3396                         bio_add_page(bio, page, len, 0);
3397                 }
3398                 nr_sectors += len>>9;
3399                 sector_nr += len>>9;
3400         } while (++page_idx < RESYNC_PAGES);
3401         r10_bio->sectors = nr_sectors;
3402
3403         while (biolist) {
3404                 bio = biolist;
3405                 biolist = biolist->bi_next;
3406
3407                 bio->bi_next = NULL;
3408                 r10_bio = get_resync_r10bio(bio);
3409                 r10_bio->sectors = nr_sectors;
3410
3411                 if (bio->bi_end_io == end_sync_read) {
3412                         md_sync_acct_bio(bio, nr_sectors);
3413                         bio->bi_status = 0;
3414                         generic_make_request(bio);
3415                 }
3416         }
3417
3418         if (sectors_skipped)
3419                 /* pretend they weren't skipped, it makes
3420                  * no important difference in this case
3421                  */
3422                 md_done_sync(mddev, sectors_skipped, 1);
3423
3424         return sectors_skipped + nr_sectors;
3425  giveup:
3426         /* There is nowhere to write, so all non-sync
3427          * drives must be failed or in resync, all drives
3428          * have a bad block, so try the next chunk...
3429          */
3430         if (sector_nr + max_sync < max_sector)
3431                 max_sector = sector_nr + max_sync;
3432
3433         sectors_skipped += (max_sector - sector_nr);
3434         chunks_skipped ++;
3435         sector_nr = max_sector;
3436         goto skipped;
3437 }
3438
3439 static sector_t
3440 raid10_size(struct mddev *mddev, sector_t sectors, int raid_disks)
3441 {
3442         sector_t size;
3443         struct r10conf *conf = mddev->private;
3444
3445         if (!raid_disks)
3446                 raid_disks = min(conf->geo.raid_disks,
3447                                  conf->prev.raid_disks);
3448         if (!sectors)
3449                 sectors = conf->dev_sectors;
3450
3451         size = sectors >> conf->geo.chunk_shift;
3452         sector_div(size, conf->geo.far_copies);
3453         size = size * raid_disks;
3454         sector_div(size, conf->geo.near_copies);
3455
3456         return size << conf->geo.chunk_shift;
3457 }
3458
3459 static void calc_sectors(struct r10conf *conf, sector_t size)
3460 {
3461         /* Calculate the number of sectors-per-device that will
3462          * actually be used, and set conf->dev_sectors and
3463          * conf->stride
3464          */
3465
3466         size = size >> conf->geo.chunk_shift;
3467         sector_div(size, conf->geo.far_copies);
3468         size = size * conf->geo.raid_disks;
3469         sector_div(size, conf->geo.near_copies);
3470         /* 'size' is now the number of chunks in the array */
3471         /* calculate "used chunks per device" */
3472         size = size * conf->copies;
3473
3474         /* We need to round up when dividing by raid_disks to
3475          * get the stride size.
3476          */
3477         size = DIV_ROUND_UP_SECTOR_T(size, conf->geo.raid_disks);
3478
3479         conf->dev_sectors = size << conf->geo.chunk_shift;
3480
3481         if (conf->geo.far_offset)
3482                 conf->geo.stride = 1 << conf->geo.chunk_shift;
3483         else {
3484                 sector_div(size, conf->geo.far_copies);
3485                 conf->geo.stride = size << conf->geo.chunk_shift;
3486         }
3487 }
3488
3489 enum geo_type {geo_new, geo_old, geo_start};
3490 static int setup_geo(struct geom *geo, struct mddev *mddev, enum geo_type new)
3491 {
3492         int nc, fc, fo;
3493         int layout, chunk, disks;
3494         switch (new) {
3495         case geo_old:
3496                 layout = mddev->layout;
3497                 chunk = mddev->chunk_sectors;
3498                 disks = mddev->raid_disks - mddev->delta_disks;
3499                 break;
3500         case geo_new:
3501                 layout = mddev->new_layout;
3502                 chunk = mddev->new_chunk_sectors;
3503                 disks = mddev->raid_disks;
3504                 break;
3505         default: /* avoid 'may be unused' warnings */
3506         case geo_start: /* new when starting reshape - raid_disks not
3507                          * updated yet. */
3508                 layout = mddev->new_layout;
3509                 chunk = mddev->new_chunk_sectors;
3510                 disks = mddev->raid_disks + mddev->delta_disks;
3511                 break;
3512         }
3513         if (layout >> 19)
3514                 return -1;
3515         if (chunk < (PAGE_SIZE >> 9) ||
3516             !is_power_of_2(chunk))
3517                 return -2;
3518         nc = layout & 255;
3519         fc = (layout >> 8) & 255;
3520         fo = layout & (1<<16);
3521         geo->raid_disks = disks;
3522         geo->near_copies = nc;
3523         geo->far_copies = fc;
3524         geo->far_offset = fo;
3525         switch (layout >> 17) {
3526         case 0: /* original layout.  simple but not always optimal */
3527                 geo->far_set_size = disks;
3528                 break;
3529         case 1: /* "improved" layout which was buggy.  Hopefully no-one is
3530                  * actually using this, but leave code here just in case.*/
3531                 geo->far_set_size = disks/fc;
3532                 WARN(geo->far_set_size < fc,
3533                      "This RAID10 layout does not provide data safety - please backup and create new array\n");
3534                 break;
3535         case 2: /* "improved" layout fixed to match documentation */
3536                 geo->far_set_size = fc * nc;
3537                 break;
3538         default: /* Not a valid layout */
3539                 return -1;
3540         }
3541         geo->chunk_mask = chunk - 1;
3542         geo->chunk_shift = ffz(~chunk);
3543         return nc*fc;
3544 }
3545
3546 static struct r10conf *setup_conf(struct mddev *mddev)
3547 {
3548         struct r10conf *conf = NULL;
3549         int err = -EINVAL;
3550         struct geom geo;
3551         int copies;
3552
3553         copies = setup_geo(&geo, mddev, geo_new);
3554
3555         if (copies == -2) {
3556                 pr_warn("md/raid10:%s: chunk size must be at least PAGE_SIZE(%ld) and be a power of 2.\n",
3557                         mdname(mddev), PAGE_SIZE);
3558                 goto out;
3559         }
3560
3561         if (copies < 2 || copies > mddev->raid_disks) {
3562                 pr_warn("md/raid10:%s: unsupported raid10 layout: 0x%8x\n",
3563                         mdname(mddev), mddev->new_layout);
3564                 goto out;
3565         }
3566
3567         err = -ENOMEM;
3568         conf = kzalloc(sizeof(struct r10conf), GFP_KERNEL);
3569         if (!conf)
3570                 goto out;
3571
3572         /* FIXME calc properly */
3573         conf->mirrors = kzalloc(sizeof(struct raid10_info)*(mddev->raid_disks +
3574                                                             max(0,-mddev->delta_disks)),
3575                                 GFP_KERNEL);
3576         if (!conf->mirrors)
3577                 goto out;
3578
3579         conf->tmppage = alloc_page(GFP_KERNEL);
3580         if (!conf->tmppage)
3581                 goto out;
3582
3583         conf->geo = geo;
3584         conf->copies = copies;
3585         conf->r10bio_pool = mempool_create(NR_RAID10_BIOS, r10bio_pool_alloc,
3586                                            r10bio_pool_free, conf);
3587         if (!conf->r10bio_pool)
3588                 goto out;
3589
3590         conf->bio_split = bioset_create(BIO_POOL_SIZE, 0, 0);
3591         if (!conf->bio_split)
3592                 goto out;
3593
3594         calc_sectors(conf, mddev->dev_sectors);
3595         if (mddev->reshape_position == MaxSector) {
3596                 conf->prev = conf->geo;
3597                 conf->reshape_progress = MaxSector;
3598         } else {
3599                 if (setup_geo(&conf->prev, mddev, geo_old) != conf->copies) {
3600                         err = -EINVAL;
3601                         goto out;
3602                 }
3603                 conf->reshape_progress = mddev->reshape_position;
3604                 if (conf->prev.far_offset)
3605                         conf->prev.stride = 1 << conf->prev.chunk_shift;
3606                 else
3607                         /* far_copies must be 1 */
3608                         conf->prev.stride = conf->dev_sectors;
3609         }
3610         conf->reshape_safe = conf->reshape_progress;
3611         spin_lock_init(&conf->device_lock);
3612         INIT_LIST_HEAD(&conf->retry_list);
3613         INIT_LIST_HEAD(&conf->bio_end_io_list);
3614
3615         spin_lock_init(&conf->resync_lock);
3616         init_waitqueue_head(&conf->wait_barrier);
3617         atomic_set(&conf->nr_pending, 0);
3618
3619         conf->thread = md_register_thread(raid10d, mddev, "raid10");
3620         if (!conf->thread)
3621                 goto out;
3622
3623         conf->mddev = mddev;
3624         return conf;
3625
3626  out:
3627         if (conf) {
3628                 mempool_destroy(conf->r10bio_pool);
3629                 kfree(conf->mirrors);
3630                 safe_put_page(conf->tmppage);
3631                 if (conf->bio_split)
3632                         bioset_free(conf->bio_split);
3633                 kfree(conf);
3634         }
3635         return ERR_PTR(err);
3636 }
3637
3638 static int raid10_run(struct mddev *mddev)
3639 {
3640         struct r10conf *conf;
3641         int i, disk_idx, chunk_size;
3642         struct raid10_info *disk;
3643         struct md_rdev *rdev;
3644         sector_t size;
3645         sector_t min_offset_diff = 0;
3646         int first = 1;
3647         bool discard_supported = false;
3648
3649         if (mddev_init_writes_pending(mddev) < 0)
3650                 return -ENOMEM;
3651
3652         if (mddev->private == NULL) {
3653                 conf = setup_conf(mddev);
3654                 if (IS_ERR(conf))
3655                         return PTR_ERR(conf);
3656                 mddev->private = conf;
3657         }
3658         conf = mddev->private;
3659         if (!conf)
3660                 goto out;
3661
3662         mddev->thread = conf->thread;
3663         conf->thread = NULL;
3664
3665         chunk_size = mddev->chunk_sectors << 9;
3666         if (mddev->queue) {
3667                 blk_queue_max_discard_sectors(mddev->queue,
3668                                               mddev->chunk_sectors);
3669                 blk_queue_max_write_same_sectors(mddev->queue, 0);
3670                 blk_queue_max_write_zeroes_sectors(mddev->queue, 0);
3671                 blk_queue_io_min(mddev->queue, chunk_size);
3672                 if (conf->geo.raid_disks % conf->geo.near_copies)
3673                         blk_queue_io_opt(mddev->queue, chunk_size * conf->geo.raid_disks);
3674                 else
3675                         blk_queue_io_opt(mddev->queue, chunk_size *
3676                                          (conf->geo.raid_disks / conf->geo.near_copies));
3677         }
3678
3679         rdev_for_each(rdev, mddev) {
3680                 long long diff;
3681
3682                 disk_idx = rdev->raid_disk;
3683                 if (disk_idx < 0)
3684                         continue;
3685                 if (disk_idx >= conf->geo.raid_disks &&
3686                     disk_idx >= conf->prev.raid_disks)
3687                         continue;
3688                 disk = conf->mirrors + disk_idx;
3689
3690                 if (test_bit(Replacement, &rdev->flags)) {
3691                         if (disk->replacement)
3692                                 goto out_free_conf;
3693                         disk->replacement = rdev;
3694                 } else {
3695                         if (disk->rdev)
3696                                 goto out_free_conf;
3697                         disk->rdev = rdev;
3698                 }
3699                 diff = (rdev->new_data_offset - rdev->data_offset);
3700                 if (!mddev->reshape_backwards)
3701                         diff = -diff;
3702                 if (diff < 0)
3703                         diff = 0;
3704                 if (first || diff < min_offset_diff)
3705                         min_offset_diff = diff;
3706
3707                 if (mddev->gendisk)
3708                         disk_stack_limits(mddev->gendisk, rdev->bdev,
3709                                           rdev->data_offset << 9);
3710
3711                 disk->head_position = 0;
3712
3713                 if (blk_queue_discard(bdev_get_queue(rdev->bdev)))
3714                         discard_supported = true;
3715                 first = 0;
3716         }
3717
3718         if (mddev->queue) {
3719                 if (discard_supported)
3720                         queue_flag_set_unlocked(QUEUE_FLAG_DISCARD,
3721                                                 mddev->queue);
3722                 else
3723                         queue_flag_clear_unlocked(QUEUE_FLAG_DISCARD,
3724                                                   mddev->queue);
3725         }
3726         /* need to check that every block has at least one working mirror */
3727         if (!enough(conf, -1)) {
3728                 pr_err("md/raid10:%s: not enough operational mirrors.\n",
3729                        mdname(mddev));
3730                 goto out_free_conf;
3731         }
3732
3733         if (conf->reshape_progress != MaxSector) {
3734                 /* must ensure that shape change is supported */
3735                 if (conf->geo.far_copies != 1 &&
3736                     conf->geo.far_offset == 0)
3737                         goto out_free_conf;
3738                 if (conf->prev.far_copies != 1 &&
3739                     conf->prev.far_offset == 0)
3740                         goto out_free_conf;
3741         }
3742
3743         mddev->degraded = 0;
3744         for (i = 0;
3745              i < conf->geo.raid_disks
3746                      || i < conf->prev.raid_disks;
3747              i++) {
3748
3749                 disk = conf->mirrors + i;
3750
3751                 if (!disk->rdev && disk->replacement) {
3752                         /* The replacement is all we have - use it */
3753                         disk->rdev = disk->replacement;
3754                         disk->replacement = NULL;
3755                         clear_bit(Replacement, &disk->rdev->flags);
3756                 }
3757
3758                 if (!disk->rdev ||
3759                     !test_bit(In_sync, &disk->rdev->flags)) {
3760                         disk->head_position = 0;
3761                         mddev->degraded++;
3762                         if (disk->rdev &&
3763                             disk->rdev->saved_raid_disk < 0)
3764                                 conf->fullsync = 1;
3765                 }
3766
3767                 if (disk->replacement &&
3768                     !test_bit(In_sync, &disk->replacement->flags) &&
3769                     disk->replacement->saved_raid_disk < 0) {
3770                         conf->fullsync = 1;
3771                 }
3772
3773                 disk->recovery_disabled = mddev->recovery_disabled - 1;
3774         }
3775
3776         if (mddev->recovery_cp != MaxSector)
3777                 pr_notice("md/raid10:%s: not clean -- starting background reconstruction\n",
3778                           mdname(mddev));
3779         pr_info("md/raid10:%s: active with %d out of %d devices\n",
3780                 mdname(mddev), conf->geo.raid_disks - mddev->degraded,
3781                 conf->geo.raid_disks);
3782         /*
3783          * Ok, everything is just fine now
3784          */
3785         mddev->dev_sectors = conf->dev_sectors;
3786         size = raid10_size(mddev, 0, 0);
3787         md_set_array_sectors(mddev, size);
3788         mddev->resync_max_sectors = size;
3789         set_bit(MD_FAILFAST_SUPPORTED, &mddev->flags);
3790
3791         if (mddev->queue) {
3792                 int stripe = conf->geo.raid_disks *
3793                         ((mddev->chunk_sectors << 9) / PAGE_SIZE);
3794
3795                 /* Calculate max read-ahead size.
3796                  * We need to readahead at least twice a whole stripe....
3797                  * maybe...
3798                  */
3799                 stripe /= conf->geo.near_copies;
3800                 if (mddev->queue->backing_dev_info->ra_pages < 2 * stripe)
3801                         mddev->queue->backing_dev_info->ra_pages = 2 * stripe;
3802         }
3803
3804         if (md_integrity_register(mddev))
3805                 goto out_free_conf;
3806
3807         if (conf->reshape_progress != MaxSector) {
3808                 unsigned long before_length, after_length;
3809
3810                 before_length = ((1 << conf->prev.chunk_shift) *
3811                                  conf->prev.far_copies);
3812                 after_length = ((1 << conf->geo.chunk_shift) *
3813                                 conf->geo.far_copies);
3814
3815                 if (max(before_length, after_length) > min_offset_diff) {
3816                         /* This cannot work */
3817                         pr_warn("md/raid10: offset difference not enough to continue reshape\n");
3818                         goto out_free_conf;
3819                 }
3820                 conf->offset_diff = min_offset_diff;
3821
3822                 clear_bit(MD_RECOVERY_SYNC, &mddev->recovery);
3823                 clear_bit(MD_RECOVERY_CHECK, &mddev->recovery);
3824                 set_bit(MD_RECOVERY_RESHAPE, &mddev->recovery);
3825                 set_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
3826                 mddev->sync_thread = md_register_thread(md_do_sync, mddev,
3827                                                         "reshape");
3828                 if (!mddev->sync_thread)
3829                         goto out_free_conf;
3830         }
3831
3832         return 0;
3833
3834 out_free_conf:
3835         md_unregister_thread(&mddev->thread);
3836         mempool_destroy(conf->r10bio_pool);
3837         safe_put_page(conf->tmppage);
3838         kfree(conf->mirrors);
3839         kfree(conf);
3840         mddev->private = NULL;
3841 out:
3842         return -EIO;
3843 }
3844
3845 static void raid10_free(struct mddev *mddev, void *priv)
3846 {
3847         struct r10conf *conf = priv;
3848
3849         mempool_destroy(conf->r10bio_pool);
3850         safe_put_page(conf->tmppage);
3851         kfree(conf->mirrors);
3852         kfree(conf->mirrors_old);
3853         kfree(conf->mirrors_new);
3854         if (conf->bio_split)
3855                 bioset_free(conf->bio_split);
3856         kfree(conf);
3857 }
3858
3859 static void raid10_quiesce(struct mddev *mddev, int quiesce)
3860 {
3861         struct r10conf *conf = mddev->private;
3862
3863         if (quiesce)
3864                 raise_barrier(conf, 0);
3865         else
3866                 lower_barrier(conf);
3867 }
3868
3869 static int raid10_resize(struct mddev *mddev, sector_t sectors)
3870 {
3871         /* Resize of 'far' arrays is not supported.
3872          * For 'near' and 'offset' arrays we can set the
3873          * number of sectors used to be an appropriate multiple
3874          * of the chunk size.
3875          * For 'offset', this is far_copies*chunksize.
3876          * For 'near' the multiplier is the LCM of
3877          * near_copies and raid_disks.
3878          * So if far_copies > 1 && !far_offset, fail.
3879          * Else find LCM(raid_disks, near_copy)*far_copies and
3880          * multiply by chunk_size.  Then round to this number.
3881          * This is mostly done by raid10_size()
3882          */
3883         struct r10conf *conf = mddev->private;
3884         sector_t oldsize, size;
3885
3886         if (mddev->reshape_position != MaxSector)
3887                 return -EBUSY;
3888
3889         if (conf->geo.far_copies > 1 && !conf->geo.far_offset)
3890                 return -EINVAL;
3891
3892         oldsize = raid10_size(mddev, 0, 0);
3893         size = raid10_size(mddev, sectors, 0);
3894         if (mddev->external_size &&
3895             mddev->array_sectors > size)
3896                 return -EINVAL;
3897         if (mddev->bitmap) {
3898                 int ret = bitmap_resize(mddev->bitmap, size, 0, 0);
3899                 if (ret)
3900                         return ret;
3901         }
3902         md_set_array_sectors(mddev, size);
3903         if (sectors > mddev->dev_sectors &&
3904             mddev->recovery_cp > oldsize) {
3905                 mddev->recovery_cp = oldsize;
3906                 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
3907         }
3908         calc_sectors(conf, sectors);
3909         mddev->dev_sectors = conf->dev_sectors;
3910         mddev->resync_max_sectors = size;
3911         return 0;
3912 }
3913
3914 static void *raid10_takeover_raid0(struct mddev *mddev, sector_t size, int devs)
3915 {
3916         struct md_rdev *rdev;
3917         struct r10conf *conf;
3918
3919         if (mddev->degraded > 0) {
3920                 pr_warn("md/raid10:%s: Error: degraded raid0!\n",
3921                         mdname(mddev));
3922                 return ERR_PTR(-EINVAL);
3923         }
3924         sector_div(size, devs);
3925
3926         /* Set new parameters */
3927         mddev->new_level = 10;
3928         /* new layout: far_copies = 1, near_copies = 2 */
3929         mddev->new_layout = (1<<8) + 2;
3930         mddev->new_chunk_sectors = mddev->chunk_sectors;
3931         mddev->delta_disks = mddev->raid_disks;
3932         mddev->raid_disks *= 2;
3933         /* make sure it will be not marked as dirty */
3934         mddev->recovery_cp = MaxSector;
3935         mddev->dev_sectors = size;
3936
3937         conf = setup_conf(mddev);
3938         if (!IS_ERR(conf)) {
3939                 rdev_for_each(rdev, mddev)
3940                         if (rdev->raid_disk >= 0) {
3941                                 rdev->new_raid_disk = rdev->raid_disk * 2;
3942                                 rdev->sectors = size;
3943                         }
3944                 conf->barrier = 1;
3945         }
3946
3947         return conf;
3948 }
3949
3950 static void *raid10_takeover(struct mddev *mddev)
3951 {
3952         struct r0conf *raid0_conf;
3953
3954         /* raid10 can take over:
3955          *  raid0 - providing it has only two drives
3956          */
3957         if (mddev->level == 0) {
3958                 /* for raid0 takeover only one zone is supported */
3959                 raid0_conf = mddev->private;
3960                 if (raid0_conf->nr_strip_zones > 1) {
3961                         pr_warn("md/raid10:%s: cannot takeover raid 0 with more than one zone.\n",
3962                                 mdname(mddev));
3963                         return ERR_PTR(-EINVAL);
3964                 }
3965                 return raid10_takeover_raid0(mddev,
3966                         raid0_conf->strip_zone->zone_end,
3967                         raid0_conf->strip_zone->nb_dev);
3968         }
3969         return ERR_PTR(-EINVAL);
3970 }
3971
3972 static int raid10_check_reshape(struct mddev *mddev)
3973 {
3974         /* Called when there is a request to change
3975          * - layout (to ->new_layout)
3976          * - chunk size (to ->new_chunk_sectors)
3977          * - raid_disks (by delta_disks)
3978          * or when trying to restart a reshape that was ongoing.
3979          *
3980          * We need to validate the request and possibly allocate
3981          * space if that might be an issue later.
3982          *
3983          * Currently we reject any reshape of a 'far' mode array,
3984          * allow chunk size to change if new is generally acceptable,
3985          * allow raid_disks to increase, and allow
3986          * a switch between 'near' mode and 'offset' mode.
3987          */
3988         struct r10conf *conf = mddev->private;
3989         struct geom geo;
3990
3991         if (conf->geo.far_copies != 1 && !conf->geo.far_offset)
3992                 return -EINVAL;
3993
3994         if (setup_geo(&geo, mddev, geo_start) != conf->copies)
3995                 /* mustn't change number of copies */
3996                 return -EINVAL;
3997         if (geo.far_copies > 1 && !geo.far_offset)
3998                 /* Cannot switch to 'far' mode */
3999                 return -EINVAL;
4000
4001         if (mddev->array_sectors & geo.chunk_mask)
4002                         /* not factor of array size */
4003                         return -EINVAL;
4004
4005         if (!enough(conf, -1))
4006                 return -EINVAL;
4007
4008         kfree(conf->mirrors_new);
4009         conf->mirrors_new = NULL;
4010         if (mddev->delta_disks > 0) {
4011                 /* allocate new 'mirrors' list */
4012                 conf->mirrors_new = kzalloc(
4013                         sizeof(struct raid10_info)
4014                         *(mddev->raid_disks +
4015                           mddev->delta_disks),
4016                         GFP_KERNEL);
4017                 if (!conf->mirrors_new)
4018                         return -ENOMEM;
4019         }
4020         return 0;
4021 }
4022
4023 /*
4024  * Need to check if array has failed when deciding whether to:
4025  *  - start an array
4026  *  - remove non-faulty devices
4027  *  - add a spare
4028  *  - allow a reshape
4029  * This determination is simple when no reshape is happening.
4030  * However if there is a reshape, we need to carefully check
4031  * both the before and after sections.
4032  * This is because some failed devices may only affect one
4033  * of the two sections, and some non-in_sync devices may
4034  * be insync in the section most affected by failed devices.
4035  */
4036 static int calc_degraded(struct r10conf *conf)
4037 {
4038         int degraded, degraded2;
4039         int i;
4040
4041         rcu_read_lock();
4042         degraded = 0;
4043         /* 'prev' section first */
4044         for (i = 0; i < conf->prev.raid_disks; i++) {
4045                 struct md_rdev *rdev = rcu_dereference(conf->mirrors[i].rdev);
4046                 if (!rdev || test_bit(Faulty, &rdev->flags))
4047                         degraded++;
4048                 else if (!test_bit(In_sync, &rdev->flags))
4049                         /* When we can reduce the number of devices in
4050                          * an array, this might not contribute to
4051                          * 'degraded'.  It does now.
4052                          */
4053                         degraded++;
4054         }
4055         rcu_read_unlock();
4056         if (conf->geo.raid_disks == conf->prev.raid_disks)
4057                 return degraded;
4058         rcu_read_lock();
4059         degraded2 = 0;
4060         for (i = 0; i < conf->geo.raid_disks; i++) {
4061                 struct md_rdev *rdev = rcu_dereference(conf->mirrors[i].rdev);
4062                 if (!rdev || test_bit(Faulty, &rdev->flags))
4063                         degraded2++;
4064                 else if (!test_bit(In_sync, &rdev->flags)) {
4065                         /* If reshape is increasing the number of devices,
4066                          * this section has already been recovered, so
4067                          * it doesn't contribute to degraded.
4068                          * else it does.
4069                          */
4070                         if (conf->geo.raid_disks <= conf->prev.raid_disks)
4071                                 degraded2++;
4072                 }
4073         }
4074         rcu_read_unlock();
4075         if (degraded2 > degraded)
4076                 return degraded2;
4077         return degraded;
4078 }
4079
4080 static int raid10_start_reshape(struct mddev *mddev)
4081 {
4082         /* A 'reshape' has been requested. This commits
4083          * the various 'new' fields and sets MD_RECOVER_RESHAPE
4084          * This also checks if there are enough spares and adds them
4085          * to the array.
4086          * We currently require enough spares to make the final
4087          * array non-degraded.  We also require that the difference
4088          * between old and new data_offset - on each device - is
4089          * enough that we never risk over-writing.
4090          */
4091
4092         unsigned long before_length, after_length;
4093         sector_t min_offset_diff = 0;
4094         int first = 1;
4095         struct geom new;
4096         struct r10conf *conf = mddev->private;
4097         struct md_rdev *rdev;
4098         int spares = 0;
4099         int ret;
4100
4101         if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
4102                 return -EBUSY;
4103
4104         if (setup_geo(&new, mddev, geo_start) != conf->copies)
4105                 return -EINVAL;
4106
4107         before_length = ((1 << conf->prev.chunk_shift) *
4108                          conf->prev.far_copies);
4109         after_length = ((1 << conf->geo.chunk_shift) *
4110                         conf->geo.far_copies);
4111
4112         rdev_for_each(rdev, mddev) {
4113                 if (!test_bit(In_sync, &rdev->flags)
4114                     && !test_bit(Faulty, &rdev->flags))
4115                         spares++;
4116                 if (rdev->raid_disk >= 0) {
4117                         long long diff = (rdev->new_data_offset
4118                                           - rdev->data_offset);
4119                         if (!mddev->reshape_backwards)
4120                                 diff = -diff;
4121                         if (diff < 0)
4122                                 diff = 0;
4123                         if (first || diff < min_offset_diff)
4124                                 min_offset_diff = diff;
4125                         first = 0;
4126                 }
4127         }
4128
4129         if (max(before_length, after_length) > min_offset_diff)
4130                 return -EINVAL;
4131
4132         if (spares < mddev->delta_disks)
4133                 return -EINVAL;
4134
4135         conf->offset_diff = min_offset_diff;
4136         spin_lock_irq(&conf->device_lock);
4137         if (conf->mirrors_new) {
4138                 memcpy(conf->mirrors_new, conf->mirrors,
4139                        sizeof(struct raid10_info)*conf->prev.raid_disks);
4140                 smp_mb();
4141                 kfree(conf->mirrors_old);
4142                 conf->mirrors_old = conf->mirrors;
4143                 conf->mirrors = conf->mirrors_new;
4144                 conf->mirrors_new = NULL;
4145         }
4146         setup_geo(&conf->geo, mddev, geo_start);
4147         smp_mb();
4148         if (mddev->reshape_backwards) {
4149                 sector_t size = raid10_size(mddev, 0, 0);
4150                 if (size < mddev->array_sectors) {
4151                         spin_unlock_irq(&conf->device_lock);
4152                         pr_warn("md/raid10:%s: array size must be reduce before number of disks\n",
4153                                 mdname(mddev));
4154                         return -EINVAL;
4155                 }
4156                 mddev->resync_max_sectors = size;
4157                 conf->reshape_progress = size;
4158         } else
4159                 conf->reshape_progress = 0;
4160         conf->reshape_safe = conf->reshape_progress;
4161         spin_unlock_irq(&conf->device_lock);
4162
4163         if (mddev->delta_disks && mddev->bitmap) {
4164                 ret = bitmap_resize(mddev->bitmap,
4165                                     raid10_size(mddev, 0,
4166                                                 conf->geo.raid_disks),
4167                                     0, 0);
4168                 if (ret)
4169                         goto abort;
4170         }
4171         if (mddev->delta_disks > 0) {
4172                 rdev_for_each(rdev, mddev)
4173                         if (rdev->raid_disk < 0 &&
4174                             !test_bit(Faulty, &rdev->flags)) {
4175                                 if (raid10_add_disk(mddev, rdev) == 0) {
4176                                         if (rdev->raid_disk >=
4177                                             conf->prev.raid_disks)
4178                                                 set_bit(In_sync, &rdev->flags);
4179                                         else
4180                                                 rdev->recovery_offset = 0;
4181
4182                                         if (sysfs_link_rdev(mddev, rdev))
4183                                                 /* Failure here  is OK */;
4184                                 }
4185                         } else if (rdev->raid_disk >= conf->prev.raid_disks
4186                                    && !test_bit(Faulty, &rdev->flags)) {
4187                                 /* This is a spare that was manually added */
4188                                 set_bit(In_sync, &rdev->flags);
4189                         }
4190         }
4191         /* When a reshape changes the number of devices,
4192          * ->degraded is measured against the larger of the
4193          * pre and  post numbers.
4194          */
4195         spin_lock_irq(&conf->device_lock);
4196         mddev->degraded = calc_degraded(conf);
4197         spin_unlock_irq(&conf->device_lock);
4198         mddev->raid_disks = conf->geo.raid_disks;
4199         mddev->reshape_position = conf->reshape_progress;
4200         set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
4201
4202         clear_bit(MD_RECOVERY_SYNC, &mddev->recovery);
4203         clear_bit(MD_RECOVERY_CHECK, &mddev->recovery);
4204         clear_bit(MD_RECOVERY_DONE, &mddev->recovery);
4205         set_bit(MD_RECOVERY_RESHAPE, &mddev->recovery);
4206         set_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
4207
4208         mddev->sync_thread = md_register_thread(md_do_sync, mddev,
4209                                                 "reshape");
4210         if (!mddev->sync_thread) {
4211                 ret = -EAGAIN;
4212                 goto abort;
4213         }
4214         conf->reshape_checkpoint = jiffies;
4215         md_wakeup_thread(mddev->sync_thread);
4216         md_new_event(mddev);
4217         return 0;
4218
4219 abort:
4220         mddev->recovery = 0;
4221         spin_lock_irq(&conf->device_lock);
4222         conf->geo = conf->prev;
4223         mddev->raid_disks = conf->geo.raid_disks;
4224         rdev_for_each(rdev, mddev)
4225                 rdev->new_data_offset = rdev->data_offset;
4226         smp_wmb();
4227         conf->reshape_progress = MaxSector;
4228         conf->reshape_safe = MaxSector;
4229         mddev->reshape_position = MaxSector;
4230         spin_unlock_irq(&conf->device_lock);
4231         return ret;
4232 }
4233
4234 /* Calculate the last device-address that could contain
4235  * any block from the chunk that includes the array-address 's'
4236  * and report the next address.
4237  * i.e. the address returned will be chunk-aligned and after
4238  * any data that is in the chunk containing 's'.
4239  */
4240 static sector_t last_dev_address(sector_t s, struct geom *geo)
4241 {
4242         s = (s | geo->chunk_mask) + 1;
4243         s >>= geo->chunk_shift;
4244         s *= geo->near_copies;
4245         s = DIV_ROUND_UP_SECTOR_T(s, geo->raid_disks);
4246         s *= geo->far_copies;
4247         s <<= geo->chunk_shift;
4248         return s;
4249 }
4250
4251 /* Calculate the first device-address that could contain
4252  * any block from the chunk that includes the array-address 's'.
4253  * This too will be the start of a chunk
4254  */
4255 static sector_t first_dev_address(sector_t s, struct geom *geo)
4256 {
4257         s >>= geo->chunk_shift;
4258         s *= geo->near_copies;
4259         sector_div(s, geo->raid_disks);
4260         s *= geo->far_copies;
4261         s <<= geo->chunk_shift;
4262         return s;
4263 }
4264
4265 static sector_t reshape_request(struct mddev *mddev, sector_t sector_nr,
4266                                 int *skipped)
4267 {
4268         /* We simply copy at most one chunk (smallest of old and new)
4269          * at a time, possibly less if that exceeds RESYNC_PAGES,
4270          * or we hit a bad block or something.
4271          * This might mean we pause for normal IO in the middle of
4272          * a chunk, but that is not a problem as mddev->reshape_position
4273          * can record any location.
4274          *
4275          * If we will want to write to a location that isn't
4276          * yet recorded as 'safe' (i.e. in metadata on disk) then
4277          * we need to flush all reshape requests and update the metadata.
4278          *
4279          * When reshaping forwards (e.g. to more devices), we interpret
4280          * 'safe' as the earliest block which might not have been copied
4281          * down yet.  We divide this by previous stripe size and multiply
4282          * by previous stripe length to get lowest device offset that we
4283          * cannot write to yet.
4284          * We interpret 'sector_nr' as an address that we want to write to.
4285          * From this we use last_device_address() to find where we might
4286          * write to, and first_device_address on the  'safe' position.
4287          * If this 'next' write position is after the 'safe' position,
4288          * we must update the metadata to increase the 'safe' position.
4289          *
4290          * When reshaping backwards, we round in the opposite direction
4291          * and perform the reverse test:  next write position must not be
4292          * less than current safe position.
4293          *
4294          * In all this the minimum difference in data offsets
4295          * (conf->offset_diff - always positive) allows a bit of slack,
4296          * so next can be after 'safe', but not by more than offset_diff
4297          *
4298          * We need to prepare all the bios here before we start any IO
4299          * to ensure the size we choose is acceptable to all devices.
4300          * The means one for each copy for write-out and an extra one for
4301          * read-in.
4302          * We store the read-in bio in ->master_bio and the others in
4303          * ->devs[x].bio and ->devs[x].repl_bio.
4304          */
4305         struct r10conf *conf = mddev->private;
4306         struct r10bio *r10_bio;
4307         sector_t next, safe, last;
4308         int max_sectors;
4309         int nr_sectors;
4310         int s;
4311         struct md_rdev *rdev;
4312         int need_flush = 0;
4313         struct bio *blist;
4314         struct bio *bio, *read_bio;
4315         int sectors_done = 0;
4316         struct page **pages;
4317
4318         if (sector_nr == 0) {
4319                 /* If restarting in the middle, skip the initial sectors */
4320                 if (mddev->reshape_backwards &&
4321                     conf->reshape_progress < raid10_size(mddev, 0, 0)) {
4322                         sector_nr = (raid10_size(mddev, 0, 0)
4323                                      - conf->reshape_progress);
4324                 } else if (!mddev->reshape_backwards &&
4325                            conf->reshape_progress > 0)
4326                         sector_nr = conf->reshape_progress;
4327                 if (sector_nr) {
4328                         mddev->curr_resync_completed = sector_nr;
4329                         sysfs_notify(&mddev->kobj, NULL, "sync_completed");
4330                         *skipped = 1;
4331                         return sector_nr;
4332                 }
4333         }
4334
4335         /* We don't use sector_nr to track where we are up to
4336          * as that doesn't work well for ->reshape_backwards.
4337          * So just use ->reshape_progress.
4338          */
4339         if (mddev->reshape_backwards) {
4340                 /* 'next' is the earliest device address that we might
4341                  * write to for this chunk in the new layout
4342                  */
4343                 next = first_dev_address(conf->reshape_progress - 1,
4344                                          &conf->geo);
4345
4346                 /* 'safe' is the last device address that we might read from
4347                  * in the old layout after a restart
4348                  */
4349                 safe = last_dev_address(conf->reshape_safe - 1,
4350                                         &conf->prev);
4351
4352                 if (next + conf->offset_diff < safe)
4353                         need_flush = 1;
4354
4355                 last = conf->reshape_progress - 1;
4356                 sector_nr = last & ~(sector_t)(conf->geo.chunk_mask
4357                                                & conf->prev.chunk_mask);
4358                 if (sector_nr + RESYNC_BLOCK_SIZE/512 < last)
4359                         sector_nr = last + 1 - RESYNC_BLOCK_SIZE/512;
4360         } else {
4361                 /* 'next' is after the last device address that we
4362                  * might write to for this chunk in the new layout
4363                  */
4364                 next = last_dev_address(conf->reshape_progress, &conf->geo);
4365
4366                 /* 'safe' is the earliest device address that we might
4367                  * read from in the old layout after a restart
4368                  */
4369                 safe = first_dev_address(conf->reshape_safe, &conf->prev);
4370
4371                 /* Need to update metadata if 'next' might be beyond 'safe'
4372                  * as that would possibly corrupt data
4373                  */
4374                 if (next > safe + conf->offset_diff)
4375                         need_flush = 1;
4376
4377                 sector_nr = conf->reshape_progress;
4378                 last  = sector_nr | (conf->geo.chunk_mask
4379                                      & conf->prev.chunk_mask);
4380
4381                 if (sector_nr + RESYNC_BLOCK_SIZE/512 <= last)
4382                         last = sector_nr + RESYNC_BLOCK_SIZE/512 - 1;
4383         }
4384
4385         if (need_flush ||
4386             time_after(jiffies, conf->reshape_checkpoint + 10*HZ)) {
4387                 /* Need to update reshape_position in metadata */
4388                 wait_barrier(conf);
4389                 mddev->reshape_position = conf->reshape_progress;
4390                 if (mddev->reshape_backwards)
4391                         mddev->curr_resync_completed = raid10_size(mddev, 0, 0)
4392                                 - conf->reshape_progress;
4393                 else
4394                         mddev->curr_resync_completed = conf->reshape_progress;
4395                 conf->reshape_checkpoint = jiffies;
4396                 set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
4397                 md_wakeup_thread(mddev->thread);
4398                 wait_event(mddev->sb_wait, mddev->sb_flags == 0 ||
4399                            test_bit(MD_RECOVERY_INTR, &mddev->recovery));
4400                 if (test_bit(MD_RECOVERY_INTR, &mddev->recovery)) {
4401                         allow_barrier(conf);
4402                         return sectors_done;
4403                 }
4404                 conf->reshape_safe = mddev->reshape_position;
4405                 allow_barrier(conf);
4406         }
4407
4408         raise_barrier(conf, 0);
4409 read_more:
4410         /* Now schedule reads for blocks from sector_nr to last */
4411         r10_bio = raid10_alloc_init_r10buf(conf);
4412         r10_bio->state = 0;
4413         raise_barrier(conf, 1);
4414         atomic_set(&r10_bio->remaining, 0);
4415         r10_bio->mddev = mddev;
4416         r10_bio->sector = sector_nr;
4417         set_bit(R10BIO_IsReshape, &r10_bio->state);
4418         r10_bio->sectors = last - sector_nr + 1;
4419         rdev = read_balance(conf, r10_bio, &max_sectors);
4420         BUG_ON(!test_bit(R10BIO_Previous, &r10_bio->state));
4421
4422         if (!rdev) {
4423                 /* Cannot read from here, so need to record bad blocks
4424                  * on all the target devices.
4425                  */
4426                 // FIXME
4427                 mempool_free(r10_bio, conf->r10buf_pool);
4428                 set_bit(MD_RECOVERY_INTR, &mddev->recovery);
4429                 return sectors_done;
4430         }
4431
4432         read_bio = bio_alloc_mddev(GFP_KERNEL, RESYNC_PAGES, mddev);
4433
4434         bio_set_dev(read_bio, rdev->bdev);
4435         read_bio->bi_iter.bi_sector = (r10_bio->devs[r10_bio->read_slot].addr
4436                                + rdev->data_offset);
4437         read_bio->bi_private = r10_bio;
4438         read_bio->bi_end_io = end_reshape_read;
4439         bio_set_op_attrs(read_bio, REQ_OP_READ, 0);
4440         read_bio->bi_flags &= (~0UL << BIO_RESET_BITS);
4441         read_bio->bi_status = 0;
4442         read_bio->bi_vcnt = 0;
4443         read_bio->bi_iter.bi_size = 0;
4444         r10_bio->master_bio = read_bio;
4445         r10_bio->read_slot = r10_bio->devs[r10_bio->read_slot].devnum;
4446
4447         /* Now find the locations in the new layout */
4448         __raid10_find_phys(&conf->geo, r10_bio);
4449
4450         blist = read_bio;
4451         read_bio->bi_next = NULL;
4452
4453         rcu_read_lock();
4454         for (s = 0; s < conf->copies*2; s++) {
4455                 struct bio *b;
4456                 int d = r10_bio->devs[s/2].devnum;
4457                 struct md_rdev *rdev2;
4458                 if (s&1) {
4459                         rdev2 = rcu_dereference(conf->mirrors[d].replacement);
4460                         b = r10_bio->devs[s/2].repl_bio;
4461                 } else {
4462                         rdev2 = rcu_dereference(conf->mirrors[d].rdev);
4463                         b = r10_bio->devs[s/2].bio;
4464                 }
4465                 if (!rdev2 || test_bit(Faulty, &rdev2->flags))
4466                         continue;
4467
4468                 bio_set_dev(b, rdev2->bdev);
4469                 b->bi_iter.bi_sector = r10_bio->devs[s/2].addr +
4470                         rdev2->new_data_offset;
4471                 b->bi_end_io = end_reshape_write;
4472                 bio_set_op_attrs(b, REQ_OP_WRITE, 0);
4473                 b->bi_next = blist;
4474                 blist = b;
4475         }
4476
4477         /* Now add as many pages as possible to all of these bios. */
4478
4479         nr_sectors = 0;
4480         pages = get_resync_pages(r10_bio->devs[0].bio)->pages;
4481         for (s = 0 ; s < max_sectors; s += PAGE_SIZE >> 9) {
4482                 struct page *page = pages[s / (PAGE_SIZE >> 9)];
4483                 int len = (max_sectors - s) << 9;
4484                 if (len > PAGE_SIZE)
4485                         len = PAGE_SIZE;
4486                 for (bio = blist; bio ; bio = bio->bi_next) {
4487                         /*
4488                          * won't fail because the vec table is big enough
4489                          * to hold all these pages
4490                          */
4491                         bio_add_page(bio, page, len, 0);
4492                 }
4493                 sector_nr += len >> 9;
4494                 nr_sectors += len >> 9;
4495         }
4496         rcu_read_unlock();
4497         r10_bio->sectors = nr_sectors;
4498
4499         /* Now submit the read */
4500         md_sync_acct_bio(read_bio, r10_bio->sectors);
4501         atomic_inc(&r10_bio->remaining);
4502         read_bio->bi_next = NULL;
4503         generic_make_request(read_bio);
4504         sectors_done += nr_sectors;
4505         if (sector_nr <= last)
4506                 goto read_more;
4507
4508         lower_barrier(conf);
4509
4510         /* Now that we have done the whole section we can
4511          * update reshape_progress
4512          */
4513         if (mddev->reshape_backwards)
4514                 conf->reshape_progress -= sectors_done;
4515         else
4516                 conf->reshape_progress += sectors_done;
4517
4518         return sectors_done;
4519 }
4520
4521 static void end_reshape_request(struct r10bio *r10_bio);
4522 static int handle_reshape_read_error(struct mddev *mddev,
4523                                      struct r10bio *r10_bio);
4524 static void reshape_request_write(struct mddev *mddev, struct r10bio *r10_bio)
4525 {
4526         /* Reshape read completed.  Hopefully we have a block
4527          * to write out.
4528          * If we got a read error then we do sync 1-page reads from
4529          * elsewhere until we find the data - or give up.
4530          */
4531         struct r10conf *conf = mddev->private;
4532         int s;
4533
4534         if (!test_bit(R10BIO_Uptodate, &r10_bio->state))
4535                 if (handle_reshape_read_error(mddev, r10_bio) < 0) {
4536                         /* Reshape has been aborted */
4537                         md_done_sync(mddev, r10_bio->sectors, 0);
4538                         return;
4539                 }
4540
4541         /* We definitely have the data in the pages, schedule the
4542          * writes.
4543          */
4544         atomic_set(&r10_bio->remaining, 1);
4545         for (s = 0; s < conf->copies*2; s++) {
4546                 struct bio *b;
4547                 int d = r10_bio->devs[s/2].devnum;
4548                 struct md_rdev *rdev;
4549                 rcu_read_lock();
4550                 if (s&1) {
4551                         rdev = rcu_dereference(conf->mirrors[d].replacement);
4552                         b = r10_bio->devs[s/2].repl_bio;
4553                 } else {
4554                         rdev = rcu_dereference(conf->mirrors[d].rdev);
4555                         b = r10_bio->devs[s/2].bio;
4556                 }
4557                 if (!rdev || test_bit(Faulty, &rdev->flags)) {
4558                         rcu_read_unlock();
4559                         continue;
4560                 }
4561                 atomic_inc(&rdev->nr_pending);
4562                 rcu_read_unlock();
4563                 md_sync_acct_bio(b, r10_bio->sectors);
4564                 atomic_inc(&r10_bio->remaining);
4565                 b->bi_next = NULL;
4566                 generic_make_request(b);
4567         }
4568         end_reshape_request(r10_bio);
4569 }
4570
4571 static void end_reshape(struct r10conf *conf)
4572 {
4573         if (test_bit(MD_RECOVERY_INTR, &conf->mddev->recovery))
4574                 return;
4575
4576         spin_lock_irq(&conf->device_lock);
4577         conf->prev = conf->geo;
4578         md_finish_reshape(conf->mddev);
4579         smp_wmb();
4580         conf->reshape_progress = MaxSector;
4581         conf->reshape_safe = MaxSector;
4582         spin_unlock_irq(&conf->device_lock);
4583
4584         /* read-ahead size must cover two whole stripes, which is
4585          * 2 * (datadisks) * chunksize where 'n' is the number of raid devices
4586          */
4587         if (conf->mddev->queue) {
4588                 int stripe = conf->geo.raid_disks *
4589                         ((conf->mddev->chunk_sectors << 9) / PAGE_SIZE);
4590                 stripe /= conf->geo.near_copies;
4591                 if (conf->mddev->queue->backing_dev_info->ra_pages < 2 * stripe)
4592                         conf->mddev->queue->backing_dev_info->ra_pages = 2 * stripe;
4593         }
4594         conf->fullsync = 0;
4595 }
4596
4597 static int handle_reshape_read_error(struct mddev *mddev,
4598                                      struct r10bio *r10_bio)
4599 {
4600         /* Use sync reads to get the blocks from somewhere else */
4601         int sectors = r10_bio->sectors;
4602         struct r10conf *conf = mddev->private;
4603         struct r10bio *r10b;
4604         int slot = 0;
4605         int idx = 0;
4606         struct page **pages;
4607
4608         r10b = kmalloc(sizeof(*r10b) +
4609                sizeof(struct r10dev) * conf->copies, GFP_NOIO);
4610         if (!r10b) {
4611                 set_bit(MD_RECOVERY_INTR, &mddev->recovery);
4612                 return -ENOMEM;
4613         }
4614
4615         /* reshape IOs share pages from .devs[0].bio */
4616         pages = get_resync_pages(r10_bio->devs[0].bio)->pages;
4617
4618         r10b->sector = r10_bio->sector;
4619         __raid10_find_phys(&conf->prev, r10b);
4620
4621         while (sectors) {
4622                 int s = sectors;
4623                 int success = 0;
4624                 int first_slot = slot;
4625
4626                 if (s > (PAGE_SIZE >> 9))
4627                         s = PAGE_SIZE >> 9;
4628
4629                 rcu_read_lock();
4630                 while (!success) {
4631                         int d = r10b->devs[slot].devnum;
4632                         struct md_rdev *rdev = rcu_dereference(conf->mirrors[d].rdev);
4633                         sector_t addr;
4634                         if (rdev == NULL ||
4635                             test_bit(Faulty, &rdev->flags) ||
4636                             !test_bit(In_sync, &rdev->flags))
4637                                 goto failed;
4638
4639                         addr = r10b->devs[slot].addr + idx * PAGE_SIZE;
4640                         atomic_inc(&rdev->nr_pending);
4641                         rcu_read_unlock();
4642                         success = sync_page_io(rdev,
4643                                                addr,
4644                                                s << 9,
4645                                                pages[idx],
4646                                                REQ_OP_READ, 0, false);
4647                         rdev_dec_pending(rdev, mddev);
4648                         rcu_read_lock();
4649                         if (success)
4650                                 break;
4651                 failed:
4652                         slot++;
4653                         if (slot >= conf->copies)
4654                                 slot = 0;
4655                         if (slot == first_slot)
4656                                 break;
4657                 }
4658                 rcu_read_unlock();
4659                 if (!success) {
4660                         /* couldn't read this block, must give up */
4661                         set_bit(MD_RECOVERY_INTR,
4662                                 &mddev->recovery);
4663                         kfree(r10b);
4664                         return -EIO;
4665                 }
4666                 sectors -= s;
4667                 idx++;
4668         }
4669         kfree(r10b);
4670         return 0;
4671 }
4672
4673 static void end_reshape_write(struct bio *bio)
4674 {
4675         struct r10bio *r10_bio = get_resync_r10bio(bio);
4676         struct mddev *mddev = r10_bio->mddev;
4677         struct r10conf *conf = mddev->private;
4678         int d;
4679         int slot;
4680         int repl;
4681         struct md_rdev *rdev = NULL;
4682
4683         d = find_bio_disk(conf, r10_bio, bio, &slot, &repl);
4684         if (repl)
4685                 rdev = conf->mirrors[d].replacement;
4686         if (!rdev) {
4687                 smp_mb();
4688                 rdev = conf->mirrors[d].rdev;
4689         }
4690
4691         if (bio->bi_status) {
4692                 /* FIXME should record badblock */
4693                 md_error(mddev, rdev);
4694         }
4695
4696         rdev_dec_pending(rdev, mddev);
4697         end_reshape_request(r10_bio);
4698 }
4699
4700 static void end_reshape_request(struct r10bio *r10_bio)
4701 {
4702         if (!atomic_dec_and_test(&r10_bio->remaining))
4703                 return;
4704         md_done_sync(r10_bio->mddev, r10_bio->sectors, 1);
4705         bio_put(r10_bio->master_bio);
4706         put_buf(r10_bio);
4707 }
4708
4709 static void raid10_finish_reshape(struct mddev *mddev)
4710 {
4711         struct r10conf *conf = mddev->private;
4712
4713         if (test_bit(MD_RECOVERY_INTR, &mddev->recovery))
4714                 return;
4715
4716         if (mddev->delta_disks > 0) {
4717                 if (mddev->recovery_cp > mddev->resync_max_sectors) {
4718                         mddev->recovery_cp = mddev->resync_max_sectors;
4719                         set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
4720                 }
4721                 mddev->resync_max_sectors = mddev->array_sectors;
4722         } else {
4723                 int d;
4724                 rcu_read_lock();
4725                 for (d = conf->geo.raid_disks ;
4726                      d < conf->geo.raid_disks - mddev->delta_disks;
4727                      d++) {
4728                         struct md_rdev *rdev = rcu_dereference(conf->mirrors[d].rdev);
4729                         if (rdev)
4730                                 clear_bit(In_sync, &rdev->flags);
4731                         rdev = rcu_dereference(conf->mirrors[d].replacement);
4732                         if (rdev)
4733                                 clear_bit(In_sync, &rdev->flags);
4734                 }
4735                 rcu_read_unlock();
4736         }
4737         mddev->layout = mddev->new_layout;
4738         mddev->chunk_sectors = 1 << conf->geo.chunk_shift;
4739         mddev->reshape_position = MaxSector;
4740         mddev->delta_disks = 0;
4741         mddev->reshape_backwards = 0;
4742 }
4743
4744 static struct md_personality raid10_personality =
4745 {
4746         .name           = "raid10",
4747         .level          = 10,
4748         .owner          = THIS_MODULE,
4749         .make_request   = raid10_make_request,
4750         .run            = raid10_run,
4751         .free           = raid10_free,
4752         .status         = raid10_status,
4753         .error_handler  = raid10_error,
4754         .hot_add_disk   = raid10_add_disk,
4755         .hot_remove_disk= raid10_remove_disk,
4756         .spare_active   = raid10_spare_active,
4757         .sync_request   = raid10_sync_request,
4758         .quiesce        = raid10_quiesce,
4759         .size           = raid10_size,
4760         .resize         = raid10_resize,
4761         .takeover       = raid10_takeover,
4762         .check_reshape  = raid10_check_reshape,
4763         .start_reshape  = raid10_start_reshape,
4764         .finish_reshape = raid10_finish_reshape,
4765         .congested      = raid10_congested,
4766 };
4767
4768 static int __init raid_init(void)
4769 {
4770         return register_md_personality(&raid10_personality);
4771 }
4772
4773 static void raid_exit(void)
4774 {
4775         unregister_md_personality(&raid10_personality);
4776 }
4777
4778 module_init(raid_init);
4779 module_exit(raid_exit);
4780 MODULE_LICENSE("GPL");
4781 MODULE_DESCRIPTION("RAID10 (striped mirror) personality for MD");
4782 MODULE_ALIAS("md-personality-9"); /* RAID10 */
4783 MODULE_ALIAS("md-raid10");
4784 MODULE_ALIAS("md-level-10");
4785
4786 module_param(max_queued_requests, int, S_IRUGO|S_IWUSR);