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