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