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