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