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