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