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