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