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