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