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