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