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