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