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