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