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