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