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