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