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