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