xref: /linux/drivers/md/raid1.c (revision 601d3c21b2e26b676cc67ae8804e991bbbcd4507)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * raid1.c : Multiple Devices driver for Linux
4  *
5  * Copyright (C) 1999, 2000, 2001 Ingo Molnar, Red Hat
6  *
7  * Copyright (C) 1996, 1997, 1998 Ingo Molnar, Miguel de Icaza, Gadi Oxman
8  *
9  * RAID-1 management functions.
10  *
11  * Better read-balancing code written by Mika Kuoppala <miku@iki.fi>, 2000
12  *
13  * Fixes to reconstruction by Jakob Østergaard" <jakob@ostenfeld.dk>
14  * Various fixes by Neil Brown <neilb@cse.unsw.edu.au>
15  *
16  * Changes by Peter T. Breuer <ptb@it.uc3m.es> 31/1/2003 to support
17  * bitmapped intelligence in resync:
18  *
19  *      - bitmap marked during normal i/o
20  *      - bitmap used to skip nondirty blocks during sync
21  *
22  * Additions to bitmap code, (C) 2003-2004 Paul Clements, SteelEye Technology:
23  * - persistent bitmap code
24  */
25 
26 #include <linux/slab.h>
27 #include <linux/delay.h>
28 #include <linux/blkdev.h>
29 #include <linux/module.h>
30 #include <linux/seq_file.h>
31 #include <linux/ratelimit.h>
32 #include <linux/interval_tree_generic.h>
33 
34 #include <trace/events/block.h>
35 
36 #include "md.h"
37 #include "raid1.h"
38 #include "md-bitmap.h"
39 #include "md-cluster.h"
40 
41 #define UNSUPPORTED_MDDEV_FLAGS		\
42 	((1L << MD_HAS_JOURNAL) |	\
43 	 (1L << MD_JOURNAL_CLEAN) |	\
44 	 (1L << MD_HAS_PPL) |		\
45 	 (1L << MD_HAS_MULTIPLE_PPLS))
46 
47 static void allow_barrier(struct r1conf *conf, sector_t sector_nr);
48 static void lower_barrier(struct r1conf *conf, sector_t sector_nr);
49 static void raid1_free(struct mddev *mddev, void *priv);
50 
51 #define RAID_1_10_NAME "raid1"
52 #include "raid1-10.c"
53 
54 #define START(node) ((node)->start)
55 #define LAST(node) ((node)->last)
56 INTERVAL_TREE_DEFINE(struct serial_info, node, sector_t, _subtree_last,
57 		     START, LAST, static inline, raid1_rb);
58 
59 static int check_and_add_serial(struct md_rdev *rdev, struct r1bio *r1_bio,
60 				struct serial_info *si)
61 {
62 	unsigned long flags;
63 	int ret = 0;
64 	sector_t lo = r1_bio->sector;
65 	sector_t hi = lo + r1_bio->sectors - 1;
66 	int idx = sector_to_idx(r1_bio->sector);
67 	struct serial_in_rdev *serial = &rdev->serial[idx];
68 	struct serial_info *head_si;
69 
70 	spin_lock_irqsave(&serial->serial_lock, flags);
71 	/* collision happened */
72 	head_si = raid1_rb_iter_first(&serial->serial_rb, lo, hi);
73 	if (head_si && head_si != si) {
74 		si->start = lo;
75 		si->last = hi;
76 		si->wnode_start = head_si->wnode_start;
77 		list_add_tail(&si->list_node, &head_si->waiters);
78 		ret = -EBUSY;
79 	} else if (!head_si) {
80 		si->start = lo;
81 		si->last = hi;
82 		si->wnode_start = si->start;
83 		raid1_rb_insert(si, &serial->serial_rb);
84 	}
85 	spin_unlock_irqrestore(&serial->serial_lock, flags);
86 
87 	return ret;
88 }
89 
90 static void wait_for_serialization(struct md_rdev *rdev, struct r1bio *r1_bio)
91 {
92 	struct mddev *mddev = rdev->mddev;
93 	struct serial_info *si;
94 
95 	if (WARN_ON(!mddev->serial_info_pool))
96 		return;
97 	si = mempool_alloc(mddev->serial_info_pool, GFP_NOIO);
98 	INIT_LIST_HEAD(&si->waiters);
99 	INIT_LIST_HEAD(&si->list_node);
100 	init_completion(&si->ready);
101 	while (check_and_add_serial(rdev, r1_bio, si)) {
102 		wait_for_completion(&si->ready);
103 		reinit_completion(&si->ready);
104 	}
105 }
106 
107 static void remove_serial(struct md_rdev *rdev, sector_t lo, sector_t hi)
108 {
109 	struct serial_info *si, *iter_si;
110 	unsigned long flags;
111 	int found = 0;
112 	struct mddev *mddev = rdev->mddev;
113 	int idx = sector_to_idx(lo);
114 	struct serial_in_rdev *serial = &rdev->serial[idx];
115 
116 	spin_lock_irqsave(&serial->serial_lock, flags);
117 	for (si = raid1_rb_iter_first(&serial->serial_rb, lo, hi);
118 	     si; si = raid1_rb_iter_next(si, lo, hi)) {
119 		if (si->start == lo && si->last == hi) {
120 			found = 1;
121 			break;
122 		}
123 	}
124 	if (found) {
125 		raid1_rb_remove(si, &serial->serial_rb);
126 		if (!list_empty(&si->waiters)) {
127 			list_for_each_entry(iter_si, &si->waiters, list_node) {
128 				if (iter_si->wnode_start == si->wnode_start) {
129 					list_del_init(&iter_si->list_node);
130 					list_splice_init(&si->waiters, &iter_si->waiters);
131 					raid1_rb_insert(iter_si, &serial->serial_rb);
132 					complete(&iter_si->ready);
133 					break;
134 				}
135 			}
136 		}
137 		mempool_free(si, mddev->serial_info_pool);
138 	} else {
139 		WARN(1, "The write IO is not recorded for serialization\n");
140 	}
141 	spin_unlock_irqrestore(&serial->serial_lock, flags);
142 }
143 
144 /*
145  * for resync bio, r1bio pointer can be retrieved from the per-bio
146  * 'struct resync_pages'.
147  */
148 static inline struct r1bio *get_resync_r1bio(struct bio *bio)
149 {
150 	return get_resync_pages(bio)->raid_bio;
151 }
152 
153 static void *r1bio_pool_alloc(gfp_t gfp_flags, struct r1conf *conf)
154 {
155 	int size = offsetof(struct r1bio, bios[conf->raid_disks * 2]);
156 
157 	/* allocate a r1bio with room for raid_disks entries in the bios array */
158 	return kzalloc(size, gfp_flags);
159 }
160 
161 #define RESYNC_DEPTH 32
162 #define RESYNC_SECTORS (RESYNC_BLOCK_SIZE >> 9)
163 #define RESYNC_WINDOW (RESYNC_BLOCK_SIZE * RESYNC_DEPTH)
164 #define RESYNC_WINDOW_SECTORS (RESYNC_WINDOW >> 9)
165 #define CLUSTER_RESYNC_WINDOW (16 * RESYNC_WINDOW)
166 #define CLUSTER_RESYNC_WINDOW_SECTORS (CLUSTER_RESYNC_WINDOW >> 9)
167 
168 static void * r1buf_pool_alloc(gfp_t gfp_flags, void *data)
169 {
170 	struct r1conf *conf = data;
171 	struct r1bio *r1_bio;
172 	struct bio *bio;
173 	int need_pages;
174 	int j;
175 	struct resync_pages *rps;
176 
177 	r1_bio = r1bio_pool_alloc(gfp_flags, conf);
178 	if (!r1_bio)
179 		return NULL;
180 
181 	rps = kmalloc_objs(struct resync_pages, conf->raid_disks * 2, gfp_flags);
182 	if (!rps)
183 		goto out_free_r1bio;
184 
185 	/*
186 	 * Allocate bios : 1 for reading, n-1 for writing
187 	 */
188 	for (j = conf->raid_disks * 2; j-- ; ) {
189 		bio = bio_kmalloc(RESYNC_PAGES, gfp_flags);
190 		if (!bio)
191 			goto out_free_bio;
192 		bio_init_inline(bio, NULL, RESYNC_PAGES, 0);
193 		r1_bio->bios[j] = bio;
194 	}
195 	/*
196 	 * Allocate RESYNC_PAGES data pages and attach them to
197 	 * the first bio.
198 	 * If this is a user-requested check/repair, allocate
199 	 * RESYNC_PAGES for each bio.
200 	 */
201 	if (test_bit(MD_RECOVERY_REQUESTED, &conf->mddev->recovery))
202 		need_pages = conf->raid_disks * 2;
203 	else
204 		need_pages = 1;
205 	for (j = 0; j < conf->raid_disks * 2; j++) {
206 		struct resync_pages *rp = &rps[j];
207 
208 		bio = r1_bio->bios[j];
209 
210 		if (j < need_pages) {
211 			if (resync_alloc_pages(rp, gfp_flags))
212 				goto out_free_pages;
213 		} else {
214 			memcpy(rp, &rps[0], sizeof(*rp));
215 			resync_get_all_pages(rp);
216 		}
217 
218 		rp->raid_bio = r1_bio;
219 		bio->bi_private = rp;
220 	}
221 
222 	r1_bio->master_bio = NULL;
223 
224 	return r1_bio;
225 
226 out_free_pages:
227 	while (--j >= 0)
228 		resync_free_pages(&rps[j]);
229 
230 out_free_bio:
231 	while (++j < conf->raid_disks * 2) {
232 		bio_uninit(r1_bio->bios[j]);
233 		kfree(r1_bio->bios[j]);
234 	}
235 	kfree(rps);
236 
237 out_free_r1bio:
238 	rbio_pool_free(r1_bio, data);
239 	return NULL;
240 }
241 
242 static void r1buf_pool_free(void *__r1_bio, void *data)
243 {
244 	struct r1conf *conf = data;
245 	int i;
246 	struct r1bio *r1bio = __r1_bio;
247 	struct resync_pages *rp = NULL;
248 
249 	for (i = conf->raid_disks * 2; i--; ) {
250 		rp = get_resync_pages(r1bio->bios[i]);
251 		resync_free_pages(rp);
252 		bio_uninit(r1bio->bios[i]);
253 		kfree(r1bio->bios[i]);
254 	}
255 
256 	/* resync pages array stored in the 1st bio's .bi_private */
257 	kfree(rp);
258 
259 	rbio_pool_free(r1bio, data);
260 }
261 
262 static void put_all_bios(struct r1conf *conf, struct r1bio *r1_bio)
263 {
264 	int i;
265 
266 	for (i = 0; i < conf->raid_disks * 2; i++) {
267 		struct bio **bio = r1_bio->bios + i;
268 		if (!BIO_SPECIAL(*bio))
269 			bio_put(*bio);
270 		*bio = NULL;
271 	}
272 }
273 
274 static void free_r1bio(struct r1bio *r1_bio)
275 {
276 	struct r1conf *conf = r1_bio->mddev->private;
277 
278 	put_all_bios(conf, r1_bio);
279 	mempool_free(r1_bio, conf->r1bio_pool);
280 }
281 
282 static void put_buf(struct r1bio *r1_bio)
283 {
284 	struct r1conf *conf = r1_bio->mddev->private;
285 	sector_t sect = r1_bio->sector;
286 	int i;
287 
288 	for (i = 0; i < conf->raid_disks * 2; i++) {
289 		struct bio *bio = r1_bio->bios[i];
290 		if (bio->bi_end_io)
291 			rdev_dec_pending(conf->mirrors[i].rdev, r1_bio->mddev);
292 	}
293 
294 	mempool_free(r1_bio, &conf->r1buf_pool);
295 
296 	lower_barrier(conf, sect);
297 }
298 
299 static void reschedule_retry(struct r1bio *r1_bio)
300 {
301 	unsigned long flags;
302 	struct mddev *mddev = r1_bio->mddev;
303 	struct r1conf *conf = mddev->private;
304 	int idx;
305 
306 	idx = sector_to_idx(r1_bio->sector);
307 	spin_lock_irqsave(&conf->device_lock, flags);
308 	list_add(&r1_bio->retry_list, &conf->retry_list);
309 	atomic_inc(&conf->nr_queued[idx]);
310 	spin_unlock_irqrestore(&conf->device_lock, flags);
311 
312 	wake_up(&conf->wait_barrier);
313 	md_wakeup_thread(mddev->thread);
314 }
315 
316 /*
317  * raid_end_bio_io() is called when we have finished servicing a mirrored
318  * operation and are ready to return a success/failure code to the buffer
319  * cache layer.
320  */
321 static void call_bio_endio(struct r1bio *r1_bio)
322 {
323 	struct bio *bio = r1_bio->master_bio;
324 
325 	if (!test_bit(R1BIO_Uptodate, &r1_bio->state))
326 		bio->bi_status = BLK_STS_IOERR;
327 
328 	bio_endio(bio);
329 }
330 
331 static void raid_end_bio_io(struct r1bio *r1_bio)
332 {
333 	struct bio *bio = r1_bio->master_bio;
334 	struct r1conf *conf = r1_bio->mddev->private;
335 	sector_t sector = r1_bio->sector;
336 
337 	/* if nobody has done the final endio yet, do it now */
338 	if (!test_and_set_bit(R1BIO_Returned, &r1_bio->state)) {
339 		pr_debug("raid1: sync end %s on sectors %llu-%llu\n",
340 			 (bio_data_dir(bio) == WRITE) ? "write" : "read",
341 			 (unsigned long long) bio->bi_iter.bi_sector,
342 			 (unsigned long long) bio_end_sector(bio) - 1);
343 
344 		call_bio_endio(r1_bio);
345 	}
346 
347 	free_r1bio(r1_bio);
348 	/*
349 	 * Wake up any possible resync thread that waits for the device
350 	 * to go idle.  All I/Os, even write-behind writes, are done.
351 	 */
352 	allow_barrier(conf, sector);
353 }
354 
355 /*
356  * Update disk head position estimator based on IRQ completion info.
357  */
358 static inline void update_head_pos(int disk, struct r1bio *r1_bio)
359 {
360 	struct r1conf *conf = r1_bio->mddev->private;
361 
362 	WRITE_ONCE(conf->mirrors[disk].head_position,
363 		   r1_bio->sector + r1_bio->sectors);
364 }
365 
366 /*
367  * Find the disk number which triggered given bio
368  */
369 static int find_bio_disk(struct r1bio *r1_bio, struct bio *bio)
370 {
371 	int mirror;
372 	struct r1conf *conf = r1_bio->mddev->private;
373 	int raid_disks = conf->raid_disks;
374 
375 	for (mirror = 0; mirror < raid_disks * 2; mirror++)
376 		if (r1_bio->bios[mirror] == bio)
377 			break;
378 
379 	BUG_ON(mirror == raid_disks * 2);
380 	update_head_pos(mirror, r1_bio);
381 
382 	return mirror;
383 }
384 
385 static void raid1_end_read_request(struct bio *bio)
386 {
387 	int uptodate = !bio->bi_status;
388 	struct r1bio *r1_bio = bio->bi_private;
389 	struct r1conf *conf = r1_bio->mddev->private;
390 	struct md_rdev *rdev = conf->mirrors[r1_bio->read_disk].rdev;
391 
392 	/*
393 	 * this branch is our 'one mirror IO has finished' event handler:
394 	 */
395 	update_head_pos(r1_bio->read_disk, r1_bio);
396 
397 	if (uptodate) {
398 		set_bit(R1BIO_Uptodate, &r1_bio->state);
399 	} else if (test_bit(FailFast, &rdev->flags) &&
400 		 test_bit(R1BIO_FailFast, &r1_bio->state)) {
401 		/* This was a fail-fast read so we definitely
402 		 * want to retry */
403 		;
404 	} else if (!raid1_should_handle_error(bio)) {
405 		uptodate = 1;
406 	} else {
407 		/* If all other devices have failed, we want to return
408 		 * the error upwards rather than fail the last device.
409 		 * Here we redefine "uptodate" to mean "Don't want to retry"
410 		 */
411 		unsigned long flags;
412 		spin_lock_irqsave(&conf->device_lock, flags);
413 		if (r1_bio->mddev->degraded == conf->raid_disks ||
414 		    (r1_bio->mddev->degraded == conf->raid_disks-1 &&
415 		     test_bit(In_sync, &rdev->flags)))
416 			uptodate = 1;
417 		spin_unlock_irqrestore(&conf->device_lock, flags);
418 	}
419 
420 	if (uptodate) {
421 		raid_end_bio_io(r1_bio);
422 		rdev_dec_pending(rdev, conf->mddev);
423 	} else {
424 		/*
425 		 * oops, read error:
426 		 */
427 		pr_err_ratelimited("md/raid1:%s: %pg: rescheduling sector %llu\n",
428 				   mdname(conf->mddev),
429 				   rdev->bdev,
430 				   (unsigned long long)r1_bio->sector);
431 		set_bit(R1BIO_ReadError, &r1_bio->state);
432 		reschedule_retry(r1_bio);
433 		/* don't drop the reference on read_disk yet */
434 	}
435 }
436 
437 static void close_write(struct r1bio *r1_bio)
438 {
439 	struct mddev *mddev = r1_bio->mddev;
440 
441 	/* it really is the end of this request */
442 	if (test_bit(R1BIO_BehindIO, &r1_bio->state)) {
443 		bio_free_pages(r1_bio->behind_master_bio);
444 		bio_put(r1_bio->behind_master_bio);
445 		r1_bio->behind_master_bio = NULL;
446 	}
447 
448 	if (test_bit(R1BIO_BehindIO, &r1_bio->state))
449 		mddev->bitmap_ops->end_behind_write(mddev);
450 	md_write_end(mddev);
451 }
452 
453 static void r1_bio_write_done(struct r1bio *r1_bio)
454 {
455 	if (!atomic_dec_and_test(&r1_bio->remaining))
456 		return;
457 
458 	if (test_bit(R1BIO_WriteError, &r1_bio->state))
459 		reschedule_retry(r1_bio);
460 	else {
461 		close_write(r1_bio);
462 		if (test_bit(R1BIO_MadeGood, &r1_bio->state))
463 			reschedule_retry(r1_bio);
464 		else
465 			raid_end_bio_io(r1_bio);
466 	}
467 }
468 
469 static void raid1_end_write_request(struct bio *bio)
470 {
471 	struct r1bio *r1_bio = bio->bi_private;
472 	int behind = test_bit(R1BIO_BehindIO, &r1_bio->state);
473 	struct r1conf *conf = r1_bio->mddev->private;
474 	struct bio *to_put = NULL;
475 	int mirror = find_bio_disk(r1_bio, bio);
476 	struct md_rdev *rdev = conf->mirrors[mirror].rdev;
477 	sector_t lo = r1_bio->sector;
478 	sector_t hi = r1_bio->sector + r1_bio->sectors - 1;
479 	bool ignore_error = !raid1_should_handle_error(bio) ||
480 		(bio->bi_status && bio_op(bio) == REQ_OP_DISCARD);
481 
482 	/*
483 	 * 'one mirror IO has finished' event handler:
484 	 */
485 	if (bio->bi_status && !ignore_error) {
486 		set_bit(WriteErrorSeen,	&rdev->flags);
487 		if (!test_and_set_bit(WantReplacement, &rdev->flags))
488 			set_bit(MD_RECOVERY_NEEDED, &
489 				conf->mddev->recovery);
490 
491 		if (test_bit(FailFast, &rdev->flags) &&
492 		    (bio->bi_opf & MD_FAILFAST) &&
493 		    /* We never try FailFast to WriteMostly devices */
494 		    !test_bit(WriteMostly, &rdev->flags)) {
495 			md_error(r1_bio->mddev, rdev);
496 		}
497 
498 		/*
499 		 * When the device is faulty, it is not necessary to
500 		 * handle write error.
501 		 */
502 		if (!test_bit(Faulty, &rdev->flags))
503 			set_bit(R1BIO_WriteError, &r1_bio->state);
504 		else {
505 			/* Finished with this branch */
506 			r1_bio->bios[mirror] = NULL;
507 			to_put = bio;
508 		}
509 	} else {
510 		/*
511 		 * Set R1BIO_Uptodate in our master bio, so that we
512 		 * will return a good error code for to the higher
513 		 * levels even if IO on some other mirrored buffer
514 		 * fails.
515 		 *
516 		 * The 'master' represents the composite IO operation
517 		 * to user-side. So if something waits for IO, then it
518 		 * will wait for the 'master' bio.
519 		 */
520 		r1_bio->bios[mirror] = NULL;
521 		to_put = bio;
522 		/*
523 		 * Do not set R1BIO_Uptodate if the current device is
524 		 * rebuilding or Faulty. This is because we cannot use
525 		 * such device for properly reading the data back (we could
526 		 * potentially use it, if the current write would have felt
527 		 * before rdev->recovery_offset, but for simplicity we don't
528 		 * check this here.
529 		 */
530 		if (test_bit(In_sync, &rdev->flags) &&
531 		    !test_bit(Faulty, &rdev->flags))
532 			set_bit(R1BIO_Uptodate, &r1_bio->state);
533 
534 		/* Maybe we can clear some bad blocks. */
535 		if (rdev_has_badblock(rdev, r1_bio->sector, r1_bio->sectors) &&
536 		    !ignore_error) {
537 			r1_bio->bios[mirror] = IO_MADE_GOOD;
538 			set_bit(R1BIO_MadeGood, &r1_bio->state);
539 		}
540 	}
541 
542 	if (behind) {
543 		if (test_bit(CollisionCheck, &rdev->flags))
544 			remove_serial(rdev, lo, hi);
545 		if (test_bit(WriteMostly, &rdev->flags))
546 			atomic_dec(&r1_bio->behind_remaining);
547 
548 		/*
549 		 * In behind mode, we ACK the master bio once the I/O
550 		 * has safely reached all non-writemostly
551 		 * disks. Setting the Returned bit ensures that this
552 		 * gets done only once -- we don't ever want to return
553 		 * -EIO here, instead we'll wait
554 		 */
555 		if (atomic_read(&r1_bio->behind_remaining) >= (atomic_read(&r1_bio->remaining)-1) &&
556 		    test_bit(R1BIO_Uptodate, &r1_bio->state)) {
557 			/* Maybe we can return now */
558 			if (!test_and_set_bit(R1BIO_Returned, &r1_bio->state)) {
559 				struct bio *mbio = r1_bio->master_bio;
560 				pr_debug("raid1: behind end write sectors"
561 					 " %llu-%llu\n",
562 					 (unsigned long long) mbio->bi_iter.bi_sector,
563 					 (unsigned long long) bio_end_sector(mbio) - 1);
564 				call_bio_endio(r1_bio);
565 			}
566 		}
567 	} else if (test_bit(MD_SERIALIZE_POLICY, &rdev->mddev->flags))
568 		remove_serial(rdev, lo, hi);
569 	if (r1_bio->bios[mirror] == NULL)
570 		rdev_dec_pending(rdev, conf->mddev);
571 
572 	/*
573 	 * Let's see if all mirrored write operations have finished
574 	 * already.
575 	 */
576 	r1_bio_write_done(r1_bio);
577 
578 	if (to_put)
579 		bio_put(to_put);
580 }
581 
582 static sector_t align_to_barrier_unit_end(sector_t start_sector,
583 					  sector_t sectors)
584 {
585 	sector_t len;
586 
587 	WARN_ON(sectors == 0);
588 	/*
589 	 * len is the number of sectors from start_sector to end of the
590 	 * barrier unit which start_sector belongs to.
591 	 */
592 	len = round_up(start_sector + 1, BARRIER_UNIT_SECTOR_SIZE) -
593 	      start_sector;
594 
595 	if (len > sectors)
596 		len = sectors;
597 
598 	return len;
599 }
600 
601 static void update_read_sectors(struct r1conf *conf, int disk,
602 				sector_t this_sector, int len)
603 {
604 	struct raid1_info *info = &conf->mirrors[disk];
605 
606 	atomic_inc(&info->rdev->nr_pending);
607 	if (info->next_seq_sect != this_sector)
608 		info->seq_start = this_sector;
609 	info->next_seq_sect = this_sector + len;
610 }
611 
612 static int choose_first_rdev(struct r1conf *conf, struct r1bio *r1_bio,
613 			     int *max_sectors)
614 {
615 	sector_t this_sector = r1_bio->sector;
616 	int len = r1_bio->sectors;
617 	int disk;
618 
619 	for (disk = 0 ; disk < conf->raid_disks * 2 ; disk++) {
620 		struct md_rdev *rdev;
621 		int read_len;
622 
623 		if (r1_bio->bios[disk] == IO_BLOCKED)
624 			continue;
625 
626 		rdev = conf->mirrors[disk].rdev;
627 		if (!rdev || test_bit(Faulty, &rdev->flags))
628 			continue;
629 
630 		/* choose the first disk even if it has some bad blocks. */
631 		read_len = raid1_check_read_range(rdev, this_sector, &len);
632 		if (read_len > 0) {
633 			update_read_sectors(conf, disk, this_sector, read_len);
634 			*max_sectors = read_len;
635 			return disk;
636 		}
637 	}
638 
639 	return -1;
640 }
641 
642 static bool rdev_in_recovery(struct md_rdev *rdev, struct r1bio *r1_bio)
643 {
644 	return !test_bit(In_sync, &rdev->flags) &&
645 	       rdev->recovery_offset < r1_bio->sector + r1_bio->sectors;
646 }
647 
648 static int choose_bb_rdev(struct r1conf *conf, struct r1bio *r1_bio,
649 			  int *max_sectors)
650 {
651 	sector_t this_sector = r1_bio->sector;
652 	int best_disk = -1;
653 	int best_len = 0;
654 	int disk;
655 
656 	for (disk = 0 ; disk < conf->raid_disks * 2 ; disk++) {
657 		struct md_rdev *rdev;
658 		int len;
659 		int read_len;
660 
661 		if (r1_bio->bios[disk] == IO_BLOCKED)
662 			continue;
663 
664 		rdev = conf->mirrors[disk].rdev;
665 		if (!rdev || test_bit(Faulty, &rdev->flags) ||
666 		    rdev_in_recovery(rdev, r1_bio) ||
667 		    test_bit(WriteMostly, &rdev->flags))
668 			continue;
669 
670 		/* keep track of the disk with the most readable sectors. */
671 		len = r1_bio->sectors;
672 		read_len = raid1_check_read_range(rdev, this_sector, &len);
673 		if (read_len > best_len) {
674 			best_disk = disk;
675 			best_len = read_len;
676 		}
677 	}
678 
679 	if (best_disk != -1) {
680 		*max_sectors = best_len;
681 		update_read_sectors(conf, best_disk, this_sector, best_len);
682 	}
683 
684 	return best_disk;
685 }
686 
687 static int choose_slow_rdev(struct r1conf *conf, struct r1bio *r1_bio,
688 			    int *max_sectors)
689 {
690 	sector_t this_sector = r1_bio->sector;
691 	int bb_disk = -1;
692 	int bb_read_len = 0;
693 	int disk;
694 
695 	for (disk = 0 ; disk < conf->raid_disks * 2 ; disk++) {
696 		struct md_rdev *rdev;
697 		int len;
698 		int read_len;
699 
700 		if (r1_bio->bios[disk] == IO_BLOCKED)
701 			continue;
702 
703 		rdev = conf->mirrors[disk].rdev;
704 		if (!rdev || test_bit(Faulty, &rdev->flags) ||
705 		    !test_bit(WriteMostly, &rdev->flags) ||
706 		    rdev_in_recovery(rdev, r1_bio))
707 			continue;
708 
709 		/* there are no bad blocks, we can use this disk */
710 		len = r1_bio->sectors;
711 		read_len = raid1_check_read_range(rdev, this_sector, &len);
712 		if (read_len == r1_bio->sectors) {
713 			*max_sectors = read_len;
714 			update_read_sectors(conf, disk, this_sector, read_len);
715 			return disk;
716 		}
717 
718 		/*
719 		 * there are partial bad blocks, choose the rdev with largest
720 		 * read length.
721 		 */
722 		if (read_len > bb_read_len) {
723 			bb_disk = disk;
724 			bb_read_len = read_len;
725 		}
726 	}
727 
728 	if (bb_disk != -1) {
729 		*max_sectors = bb_read_len;
730 		update_read_sectors(conf, bb_disk, this_sector, bb_read_len);
731 	}
732 
733 	return bb_disk;
734 }
735 
736 static bool is_sequential(struct r1conf *conf, int disk, struct r1bio *r1_bio)
737 {
738 	/* TODO: address issues with this check and concurrency. */
739 	return conf->mirrors[disk].next_seq_sect == r1_bio->sector ||
740 	       READ_ONCE(conf->mirrors[disk].head_position) == r1_bio->sector;
741 }
742 
743 /*
744  * If buffered sequential IO size exceeds optimal iosize, check if there is idle
745  * disk. If yes, choose the idle disk.
746  */
747 static bool should_choose_next(struct r1conf *conf, int disk)
748 {
749 	struct raid1_info *mirror = &conf->mirrors[disk];
750 	int opt_iosize;
751 
752 	if (!test_bit(Nonrot, &mirror->rdev->flags))
753 		return false;
754 
755 	opt_iosize = bdev_io_opt(mirror->rdev->bdev) >> 9;
756 	return opt_iosize > 0 && mirror->seq_start != MaxSector &&
757 	       mirror->next_seq_sect > opt_iosize &&
758 	       mirror->next_seq_sect - opt_iosize >= mirror->seq_start;
759 }
760 
761 static bool rdev_readable(struct md_rdev *rdev, struct r1bio *r1_bio)
762 {
763 	if (!rdev || test_bit(Faulty, &rdev->flags))
764 		return false;
765 
766 	if (rdev_in_recovery(rdev, r1_bio))
767 		return false;
768 
769 	/* don't read from slow disk unless have to */
770 	if (test_bit(WriteMostly, &rdev->flags))
771 		return false;
772 
773 	/* don't split IO for bad blocks unless have to */
774 	if (rdev_has_badblock(rdev, r1_bio->sector, r1_bio->sectors))
775 		return false;
776 
777 	return true;
778 }
779 
780 struct read_balance_ctl {
781 	sector_t closest_dist;
782 	int closest_dist_disk;
783 	int min_pending;
784 	int min_pending_disk;
785 	int sequential_disk;
786 	int readable_disks;
787 };
788 
789 static int choose_best_rdev(struct r1conf *conf, struct r1bio *r1_bio)
790 {
791 	int disk;
792 	struct read_balance_ctl ctl = {
793 		.closest_dist_disk      = -1,
794 		.closest_dist           = MaxSector,
795 		.min_pending_disk       = -1,
796 		.min_pending            = UINT_MAX,
797 		.sequential_disk	= -1,
798 	};
799 
800 	for (disk = 0 ; disk < conf->raid_disks * 2 ; disk++) {
801 		struct md_rdev *rdev;
802 		sector_t dist;
803 		unsigned int pending;
804 
805 		if (r1_bio->bios[disk] == IO_BLOCKED)
806 			continue;
807 
808 		rdev = conf->mirrors[disk].rdev;
809 		if (!rdev_readable(rdev, r1_bio))
810 			continue;
811 
812 		/* At least two disks to choose from so failfast is OK */
813 		if (ctl.readable_disks++ == 1)
814 			set_bit(R1BIO_FailFast, &r1_bio->state);
815 
816 		pending = atomic_read(&rdev->nr_pending);
817 		dist = abs(r1_bio->sector -
818 			   READ_ONCE(conf->mirrors[disk].head_position));
819 
820 		/* Don't change to another disk for sequential reads */
821 		if (is_sequential(conf, disk, r1_bio)) {
822 			if (!should_choose_next(conf, disk))
823 				return disk;
824 
825 			/*
826 			 * Add 'pending' to avoid choosing this disk if
827 			 * there is other idle disk.
828 			 */
829 			pending++;
830 			/*
831 			 * If there is no other idle disk, this disk
832 			 * will be chosen.
833 			 */
834 			ctl.sequential_disk = disk;
835 		}
836 
837 		if (ctl.min_pending > pending) {
838 			ctl.min_pending = pending;
839 			ctl.min_pending_disk = disk;
840 		}
841 
842 		if (ctl.closest_dist > dist) {
843 			ctl.closest_dist = dist;
844 			ctl.closest_dist_disk = disk;
845 		}
846 	}
847 
848 	/*
849 	 * sequential IO size exceeds optimal iosize, however, there is no other
850 	 * idle disk, so choose the sequential disk.
851 	 */
852 	if (ctl.sequential_disk != -1 && ctl.min_pending != 0)
853 		return ctl.sequential_disk;
854 
855 	/*
856 	 * If all disks are rotational, choose the closest disk. If any disk is
857 	 * non-rotational, choose the disk with less pending request even the
858 	 * disk is rotational, which might/might not be optimal for raids with
859 	 * mixed ratation/non-rotational disks depending on workload.
860 	 */
861 	if (ctl.min_pending_disk != -1 &&
862 	    (READ_ONCE(conf->nonrot_disks) || ctl.min_pending == 0))
863 		return ctl.min_pending_disk;
864 	else
865 		return ctl.closest_dist_disk;
866 }
867 
868 /*
869  * This routine returns the disk from which the requested read should be done.
870  *
871  * 1) If resync is in progress, find the first usable disk and use it even if it
872  * has some bad blocks.
873  *
874  * 2) Now that there is no resync, loop through all disks and skipping slow
875  * disks and disks with bad blocks for now. Only pay attention to key disk
876  * choice.
877  *
878  * 3) If we've made it this far, now look for disks with bad blocks and choose
879  * the one with most number of sectors.
880  *
881  * 4) If we are all the way at the end, we have no choice but to use a disk even
882  * if it is write mostly.
883  *
884  * The rdev for the device selected will have nr_pending incremented.
885  */
886 static int read_balance(struct r1conf *conf, struct r1bio *r1_bio,
887 			int *max_sectors)
888 {
889 	int disk;
890 
891 	clear_bit(R1BIO_FailFast, &r1_bio->state);
892 
893 	if (raid1_should_read_first(conf->mddev, r1_bio->sector,
894 				    r1_bio->sectors))
895 		return choose_first_rdev(conf, r1_bio, max_sectors);
896 
897 	disk = choose_best_rdev(conf, r1_bio);
898 	if (disk >= 0) {
899 		*max_sectors = r1_bio->sectors;
900 		update_read_sectors(conf, disk, r1_bio->sector,
901 				    r1_bio->sectors);
902 		return disk;
903 	}
904 
905 	/*
906 	 * If we are here it means we didn't find a perfectly good disk so
907 	 * now spend a bit more time trying to find one with the most good
908 	 * sectors.
909 	 */
910 	disk = choose_bb_rdev(conf, r1_bio, max_sectors);
911 	if (disk >= 0)
912 		return disk;
913 
914 	return choose_slow_rdev(conf, r1_bio, max_sectors);
915 }
916 
917 static void wake_up_barrier(struct r1conf *conf)
918 {
919 	if (wq_has_sleeper(&conf->wait_barrier))
920 		wake_up(&conf->wait_barrier);
921 }
922 
923 static void flush_bio_list(struct r1conf *conf, struct bio *bio)
924 {
925 	/* flush any pending bitmap writes to disk before proceeding w/ I/O */
926 	raid1_prepare_flush_writes(conf->mddev);
927 	wake_up_barrier(conf);
928 
929 	while (bio) { /* submit pending writes */
930 		struct bio *next = bio->bi_next;
931 
932 		raid1_submit_write(bio);
933 		bio = next;
934 		cond_resched();
935 	}
936 }
937 
938 static void flush_pending_writes(struct r1conf *conf)
939 {
940 	/* Any writes that have been queued but are awaiting
941 	 * bitmap updates get flushed here.
942 	 */
943 	spin_lock_irq(&conf->device_lock);
944 
945 	if (conf->pending_bio_list.head) {
946 		struct blk_plug plug;
947 		struct bio *bio;
948 
949 		bio = bio_list_get(&conf->pending_bio_list);
950 		spin_unlock_irq(&conf->device_lock);
951 
952 		/*
953 		 * As this is called in a wait_event() loop (see freeze_array),
954 		 * current->state might be TASK_UNINTERRUPTIBLE which will
955 		 * cause a warning when we prepare to wait again.  As it is
956 		 * rare that this path is taken, it is perfectly safe to force
957 		 * us to go around the wait_event() loop again, so the warning
958 		 * is a false-positive.  Silence the warning by resetting
959 		 * thread state
960 		 */
961 		__set_current_state(TASK_RUNNING);
962 		blk_start_plug(&plug);
963 		flush_bio_list(conf, bio);
964 		blk_finish_plug(&plug);
965 	} else
966 		spin_unlock_irq(&conf->device_lock);
967 }
968 
969 /* Barriers....
970  * Sometimes we need to suspend IO while we do something else,
971  * either some resync/recovery, or reconfigure the array.
972  * To do this we raise a 'barrier'.
973  * The 'barrier' is a counter that can be raised multiple times
974  * to count how many activities are happening which preclude
975  * normal IO.
976  * We can only raise the barrier if there is no pending IO.
977  * i.e. if nr_pending == 0.
978  * We choose only to raise the barrier if no-one is waiting for the
979  * barrier to go down.  This means that as soon as an IO request
980  * is ready, no other operations which require a barrier will start
981  * until the IO request has had a chance.
982  *
983  * So: regular IO calls 'wait_barrier'.  When that returns there
984  *    is no backgroup IO happening,  It must arrange to call
985  *    allow_barrier when it has finished its IO.
986  * backgroup IO calls must call raise_barrier.  Once that returns
987  *    there is no normal IO happeing.  It must arrange to call
988  *    lower_barrier when the particular background IO completes.
989  *
990  * If resync/recovery is interrupted, returns -EINTR;
991  * Otherwise, returns 0.
992  */
993 static int raise_barrier(struct r1conf *conf, sector_t sector_nr)
994 {
995 	int idx = sector_to_idx(sector_nr);
996 
997 	spin_lock_irq(&conf->resync_lock);
998 
999 	/* Wait until no block IO is waiting */
1000 	wait_event_lock_irq(conf->wait_barrier,
1001 			    !atomic_read(&conf->nr_waiting[idx]),
1002 			    conf->resync_lock);
1003 
1004 	/* block any new IO from starting */
1005 	atomic_inc(&conf->barrier[idx]);
1006 	/*
1007 	 * In raise_barrier() we firstly increase conf->barrier[idx] then
1008 	 * check conf->nr_pending[idx]. In _wait_barrier() we firstly
1009 	 * increase conf->nr_pending[idx] then check conf->barrier[idx].
1010 	 * A memory barrier here to make sure conf->nr_pending[idx] won't
1011 	 * be fetched before conf->barrier[idx] is increased. Otherwise
1012 	 * there will be a race between raise_barrier() and _wait_barrier().
1013 	 */
1014 	smp_mb__after_atomic();
1015 
1016 	/* For these conditions we must wait:
1017 	 * A: while the array is in frozen state
1018 	 * B: while conf->nr_pending[idx] is not 0, meaning regular I/O
1019 	 *    existing in corresponding I/O barrier bucket.
1020 	 * C: while conf->barrier[idx] >= RESYNC_DEPTH, meaning reaches
1021 	 *    max resync count which allowed on current I/O barrier bucket.
1022 	 */
1023 	wait_event_lock_irq(conf->wait_barrier,
1024 			    (!conf->array_frozen &&
1025 			     !atomic_read(&conf->nr_pending[idx]) &&
1026 			     atomic_read(&conf->barrier[idx]) < RESYNC_DEPTH) ||
1027 				test_bit(MD_RECOVERY_INTR, &conf->mddev->recovery),
1028 			    conf->resync_lock);
1029 
1030 	if (test_bit(MD_RECOVERY_INTR, &conf->mddev->recovery)) {
1031 		atomic_dec(&conf->barrier[idx]);
1032 		spin_unlock_irq(&conf->resync_lock);
1033 		wake_up(&conf->wait_barrier);
1034 		return -EINTR;
1035 	}
1036 
1037 	atomic_inc(&conf->nr_sync_pending);
1038 	spin_unlock_irq(&conf->resync_lock);
1039 
1040 	return 0;
1041 }
1042 
1043 static void lower_barrier(struct r1conf *conf, sector_t sector_nr)
1044 {
1045 	int idx = sector_to_idx(sector_nr);
1046 
1047 	BUG_ON(atomic_read(&conf->barrier[idx]) <= 0);
1048 
1049 	atomic_dec(&conf->barrier[idx]);
1050 	atomic_dec(&conf->nr_sync_pending);
1051 	wake_up(&conf->wait_barrier);
1052 }
1053 
1054 static bool _wait_barrier(struct r1conf *conf, int idx, bool nowait)
1055 {
1056 	bool ret = true;
1057 
1058 	/*
1059 	 * We need to increase conf->nr_pending[idx] very early here,
1060 	 * then raise_barrier() can be blocked when it waits for
1061 	 * conf->nr_pending[idx] to be 0. Then we can avoid holding
1062 	 * conf->resync_lock when there is no barrier raised in same
1063 	 * barrier unit bucket. Also if the array is frozen, I/O
1064 	 * should be blocked until array is unfrozen.
1065 	 */
1066 	atomic_inc(&conf->nr_pending[idx]);
1067 	/*
1068 	 * In _wait_barrier() we firstly increase conf->nr_pending[idx], then
1069 	 * check conf->barrier[idx]. In raise_barrier() we firstly increase
1070 	 * conf->barrier[idx], then check conf->nr_pending[idx]. A memory
1071 	 * barrier is necessary here to make sure conf->barrier[idx] won't be
1072 	 * fetched before conf->nr_pending[idx] is increased. Otherwise there
1073 	 * will be a race between _wait_barrier() and raise_barrier().
1074 	 */
1075 	smp_mb__after_atomic();
1076 
1077 	/*
1078 	 * Don't worry about checking two atomic_t variables at same time
1079 	 * here. If during we check conf->barrier[idx], the array is
1080 	 * frozen (conf->array_frozen is 1), and chonf->barrier[idx] is
1081 	 * 0, it is safe to return and make the I/O continue. Because the
1082 	 * array is frozen, all I/O returned here will eventually complete
1083 	 * or be queued, no race will happen. See code comment in
1084 	 * frozen_array().
1085 	 */
1086 	if (!READ_ONCE(conf->array_frozen) &&
1087 	    !atomic_read(&conf->barrier[idx]))
1088 		return ret;
1089 
1090 	/*
1091 	 * After holding conf->resync_lock, conf->nr_pending[idx]
1092 	 * should be decreased before waiting for barrier to drop.
1093 	 * Otherwise, we may encounter a race condition because
1094 	 * raise_barrer() might be waiting for conf->nr_pending[idx]
1095 	 * to be 0 at same time.
1096 	 */
1097 	spin_lock_irq(&conf->resync_lock);
1098 	atomic_inc(&conf->nr_waiting[idx]);
1099 	atomic_dec(&conf->nr_pending[idx]);
1100 	/*
1101 	 * In case freeze_array() is waiting for
1102 	 * get_unqueued_pending() == extra
1103 	 */
1104 	wake_up_barrier(conf);
1105 	/* Wait for the barrier in same barrier unit bucket to drop. */
1106 
1107 	/* Return false when nowait flag is set */
1108 	if (nowait) {
1109 		ret = false;
1110 	} else {
1111 		wait_event_lock_irq(conf->wait_barrier,
1112 				!conf->array_frozen &&
1113 				!atomic_read(&conf->barrier[idx]),
1114 				conf->resync_lock);
1115 		atomic_inc(&conf->nr_pending[idx]);
1116 	}
1117 
1118 	atomic_dec(&conf->nr_waiting[idx]);
1119 	spin_unlock_irq(&conf->resync_lock);
1120 	return ret;
1121 }
1122 
1123 static bool wait_read_barrier(struct r1conf *conf, sector_t sector_nr, bool nowait)
1124 {
1125 	int idx = sector_to_idx(sector_nr);
1126 	bool ret = true;
1127 
1128 	/*
1129 	 * Very similar to _wait_barrier(). The difference is, for read
1130 	 * I/O we don't need wait for sync I/O, but if the whole array
1131 	 * is frozen, the read I/O still has to wait until the array is
1132 	 * unfrozen. Since there is no ordering requirement with
1133 	 * conf->barrier[idx] here, memory barrier is unnecessary as well.
1134 	 */
1135 	atomic_inc(&conf->nr_pending[idx]);
1136 
1137 	if (!READ_ONCE(conf->array_frozen))
1138 		return ret;
1139 
1140 	spin_lock_irq(&conf->resync_lock);
1141 	atomic_inc(&conf->nr_waiting[idx]);
1142 	atomic_dec(&conf->nr_pending[idx]);
1143 	/*
1144 	 * In case freeze_array() is waiting for
1145 	 * get_unqueued_pending() == extra
1146 	 */
1147 	wake_up_barrier(conf);
1148 	/* Wait for array to be unfrozen */
1149 
1150 	/* Return false when nowait flag is set */
1151 	if (nowait) {
1152 		/* Return false when nowait flag is set */
1153 		ret = false;
1154 	} else {
1155 		wait_event_lock_irq(conf->wait_barrier,
1156 				!conf->array_frozen,
1157 				conf->resync_lock);
1158 		atomic_inc(&conf->nr_pending[idx]);
1159 	}
1160 
1161 	atomic_dec(&conf->nr_waiting[idx]);
1162 	spin_unlock_irq(&conf->resync_lock);
1163 	return ret;
1164 }
1165 
1166 static bool wait_barrier(struct r1conf *conf, sector_t sector_nr, bool nowait)
1167 {
1168 	int idx = sector_to_idx(sector_nr);
1169 
1170 	return _wait_barrier(conf, idx, nowait);
1171 }
1172 
1173 static void _allow_barrier(struct r1conf *conf, int idx)
1174 {
1175 	atomic_dec(&conf->nr_pending[idx]);
1176 	wake_up_barrier(conf);
1177 }
1178 
1179 static void allow_barrier(struct r1conf *conf, sector_t sector_nr)
1180 {
1181 	int idx = sector_to_idx(sector_nr);
1182 
1183 	_allow_barrier(conf, idx);
1184 }
1185 
1186 /* conf->resync_lock should be held */
1187 static int get_unqueued_pending(struct r1conf *conf)
1188 {
1189 	int idx, ret;
1190 
1191 	ret = atomic_read(&conf->nr_sync_pending);
1192 	for (idx = 0; idx < BARRIER_BUCKETS_NR; idx++)
1193 		ret += atomic_read(&conf->nr_pending[idx]) -
1194 			atomic_read(&conf->nr_queued[idx]);
1195 
1196 	return ret;
1197 }
1198 
1199 static void freeze_array(struct r1conf *conf, int extra)
1200 {
1201 	/* Stop sync I/O and normal I/O and wait for everything to
1202 	 * go quiet.
1203 	 * This is called in two situations:
1204 	 * 1) management command handlers (reshape, remove disk, quiesce).
1205 	 * 2) one normal I/O request failed.
1206 
1207 	 * After array_frozen is set to 1, new sync IO will be blocked at
1208 	 * raise_barrier(), and new normal I/O will blocked at _wait_barrier()
1209 	 * or wait_read_barrier(). The flying I/Os will either complete or be
1210 	 * queued. When everything goes quite, there are only queued I/Os left.
1211 
1212 	 * Every flying I/O contributes to a conf->nr_pending[idx], idx is the
1213 	 * barrier bucket index which this I/O request hits. When all sync and
1214 	 * normal I/O are queued, sum of all conf->nr_pending[] will match sum
1215 	 * of all conf->nr_queued[]. But normal I/O failure is an exception,
1216 	 * in handle_read_error(), we may call freeze_array() before trying to
1217 	 * fix the read error. In this case, the error read I/O is not queued,
1218 	 * so get_unqueued_pending() == 1.
1219 	 *
1220 	 * Therefore before this function returns, we need to wait until
1221 	 * get_unqueued_pendings(conf) gets equal to extra. For
1222 	 * normal I/O context, extra is 1, in rested situations extra is 0.
1223 	 */
1224 	spin_lock_irq(&conf->resync_lock);
1225 	conf->array_frozen = 1;
1226 	mddev_add_trace_msg(conf->mddev, "raid1 wait freeze");
1227 	wait_event_lock_irq_cmd(
1228 		conf->wait_barrier,
1229 		get_unqueued_pending(conf) == extra,
1230 		conf->resync_lock,
1231 		flush_pending_writes(conf));
1232 	spin_unlock_irq(&conf->resync_lock);
1233 }
1234 static void unfreeze_array(struct r1conf *conf)
1235 {
1236 	/* reverse the effect of the freeze */
1237 	spin_lock_irq(&conf->resync_lock);
1238 	conf->array_frozen = 0;
1239 	spin_unlock_irq(&conf->resync_lock);
1240 	wake_up(&conf->wait_barrier);
1241 }
1242 
1243 static void alloc_behind_master_bio(struct r1bio *r1_bio,
1244 					   struct bio *bio)
1245 {
1246 	int size = bio->bi_iter.bi_size;
1247 	unsigned vcnt = (size + PAGE_SIZE - 1) >> PAGE_SHIFT;
1248 	int i = 0;
1249 	struct bio *behind_bio = NULL;
1250 
1251 	behind_bio = bio_alloc_bioset(NULL, vcnt, bio->bi_opf, GFP_NOIO,
1252 				      &r1_bio->mddev->bio_set);
1253 
1254 	/* discard op, we don't support writezero/writesame yet */
1255 	if (!bio_has_data(bio)) {
1256 		behind_bio->bi_iter.bi_size = size;
1257 		goto skip_copy;
1258 	}
1259 
1260 	while (i < vcnt && size) {
1261 		struct page *page;
1262 		int len = min_t(int, PAGE_SIZE, size);
1263 
1264 		page = alloc_page(GFP_NOIO);
1265 		if (unlikely(!page))
1266 			goto free_pages;
1267 
1268 		if (!bio_add_page(behind_bio, page, len, 0)) {
1269 			put_page(page);
1270 			goto free_pages;
1271 		}
1272 
1273 		size -= len;
1274 		i++;
1275 	}
1276 
1277 	bio_copy_data(behind_bio, bio);
1278 skip_copy:
1279 	r1_bio->behind_master_bio = behind_bio;
1280 	set_bit(R1BIO_BehindIO, &r1_bio->state);
1281 
1282 	return;
1283 
1284 free_pages:
1285 	pr_debug("%dB behind alloc failed, doing sync I/O\n",
1286 		 bio->bi_iter.bi_size);
1287 	bio_free_pages(behind_bio);
1288 	bio_put(behind_bio);
1289 }
1290 
1291 static void raid1_unplug(struct blk_plug_cb *cb, bool from_schedule)
1292 {
1293 	struct raid1_plug_cb *plug = container_of(cb, struct raid1_plug_cb,
1294 						  cb);
1295 	struct mddev *mddev = plug->cb.data;
1296 	struct r1conf *conf = mddev->private;
1297 	struct bio *bio;
1298 
1299 	if (from_schedule) {
1300 		spin_lock_irq(&conf->device_lock);
1301 		bio_list_merge(&conf->pending_bio_list, &plug->pending);
1302 		spin_unlock_irq(&conf->device_lock);
1303 		wake_up_barrier(conf);
1304 		md_wakeup_thread(mddev->thread);
1305 		kfree(plug);
1306 		return;
1307 	}
1308 
1309 	/* we aren't scheduling, so we can do the write-out directly. */
1310 	bio = bio_list_get(&plug->pending);
1311 	flush_bio_list(conf, bio);
1312 	kfree(plug);
1313 }
1314 
1315 static void init_r1bio(struct r1bio *r1_bio, struct mddev *mddev, struct bio *bio)
1316 {
1317 	r1_bio->master_bio = bio;
1318 	r1_bio->sectors = bio_sectors(bio);
1319 	r1_bio->state = 0;
1320 	r1_bio->mddev = mddev;
1321 	r1_bio->sector = bio->bi_iter.bi_sector;
1322 }
1323 
1324 static inline struct r1bio *
1325 alloc_r1bio(struct mddev *mddev, struct bio *bio)
1326 {
1327 	struct r1conf *conf = mddev->private;
1328 	struct r1bio *r1_bio;
1329 
1330 	r1_bio = mempool_alloc(conf->r1bio_pool, GFP_NOIO);
1331 	memset(r1_bio, 0, offsetof(struct r1bio, bios[conf->raid_disks * 2]));
1332 	init_r1bio(r1_bio, mddev, bio);
1333 	return r1_bio;
1334 }
1335 
1336 static void raid1_read_request(struct mddev *mddev, struct bio *bio,
1337 			       int max_read_sectors, struct r1bio *r1_bio)
1338 {
1339 	struct r1conf *conf = mddev->private;
1340 	struct raid1_info *mirror;
1341 	struct bio *read_bio;
1342 	int max_sectors;
1343 	int rdisk;
1344 	bool r1bio_existed = !!r1_bio;
1345 	bool nowait = bio->bi_opf & REQ_NOWAIT;
1346 
1347 	/*
1348 	 * An md cloned bio indicates we are in the error path.
1349 	 * This is more reliable than checking r1_bio, which might
1350 	 * be NULL even in the error path if a failed bio was split.
1351 	 */
1352 	bool err_path = md_cloned_bio(mddev, bio);
1353 
1354 	/*
1355 	 * If we are in the error path, we are blocking the raid1d
1356 	 * thread so there is a tiny risk of deadlock.  So ask for
1357 	 * emergency memory if needed.
1358 	 */
1359 	gfp_t gfp = err_path ? (GFP_NOIO | __GFP_HIGH) : GFP_NOIO;
1360 
1361 	/*
1362 	 * Still need barrier for READ in case that whole
1363 	 * array is frozen.
1364 	 */
1365 	if (!wait_read_barrier(conf, bio->bi_iter.bi_sector, nowait)) {
1366 		bio_wouldblock_error(bio);
1367 
1368 		if (r1bio_existed) {
1369 			set_bit(R1BIO_Returned, &r1_bio->state);
1370 			raid_end_bio_io(r1_bio);
1371 		}
1372 
1373 		return;
1374 	}
1375 
1376 	if (!r1_bio)
1377 		r1_bio = alloc_r1bio(mddev, bio);
1378 	else
1379 		init_r1bio(r1_bio, mddev, bio);
1380 	r1_bio->sectors = max_read_sectors;
1381 
1382 	/*
1383 	 * make_request() can abort the operation when read-ahead is being
1384 	 * used and no empty request is available.
1385 	 */
1386 	rdisk = read_balance(conf, r1_bio, &max_sectors);
1387 	if (rdisk < 0) {
1388 		/* couldn't find anywhere to read from */
1389 		if (r1bio_existed)
1390 			pr_crit_ratelimited("md/raid1:%s: %pg: unrecoverable I/O read error for block %llu\n",
1391 					    mdname(mddev),
1392 					    conf->mirrors[r1_bio->read_disk].rdev->bdev,
1393 					    r1_bio->sector);
1394 		raid_end_bio_io(r1_bio);
1395 		return;
1396 	}
1397 	mirror = conf->mirrors + rdisk;
1398 
1399 	if (r1bio_existed)
1400 		pr_info_ratelimited("md/raid1:%s: redirecting sector %llu to other mirror: %pg\n",
1401 				    mdname(mddev),
1402 				    (unsigned long long)r1_bio->sector,
1403 				    mirror->rdev->bdev);
1404 
1405 	if (test_bit(WriteMostly, &mirror->rdev->flags) &&
1406 	    md_bitmap_enabled(mddev, false)) {
1407 		/*
1408 		 * Reading from a write-mostly device must take care not to
1409 		 * over-take any writes that are 'behind'
1410 		 */
1411 		mddev_add_trace_msg(mddev, "raid1 wait behind writes");
1412 		if (!mddev->bitmap_ops->wait_behind_writes(mddev, nowait)) {
1413 			bio_wouldblock_error(bio);
1414 			set_bit(R1BIO_Returned, &r1_bio->state);
1415 			goto err_handle;
1416 		}
1417 	}
1418 
1419 	if (max_sectors < bio_sectors(bio)) {
1420 		bio = bio_submit_split_bioset(bio, max_sectors,
1421 					      &conf->bio_split);
1422 		if (!bio) {
1423 			set_bit(R1BIO_Returned, &r1_bio->state);
1424 			goto err_handle;
1425 		}
1426 
1427 		r1_bio->master_bio = bio;
1428 		r1_bio->sectors = max_sectors;
1429 	}
1430 
1431 	r1_bio->read_disk = rdisk;
1432 	if (likely(!md_cloned_bio(mddev, bio))) {
1433 		md_account_bio(mddev, &bio);
1434 		r1_bio->master_bio = bio;
1435 	}
1436 	read_bio = bio_alloc_clone(mirror->rdev->bdev, bio, gfp,
1437 				   &mddev->bio_set);
1438 	read_bio->bi_opf &= ~REQ_NOWAIT;
1439 	r1_bio->bios[rdisk] = read_bio;
1440 
1441 	read_bio->bi_iter.bi_sector = r1_bio->sector +
1442 		mirror->rdev->data_offset;
1443 	read_bio->bi_end_io = raid1_end_read_request;
1444 	if (test_bit(FailFast, &mirror->rdev->flags) &&
1445 	    test_bit(R1BIO_FailFast, &r1_bio->state))
1446 	        read_bio->bi_opf |= MD_FAILFAST;
1447 	read_bio->bi_private = r1_bio;
1448 	mddev_trace_remap(mddev, read_bio, r1_bio->sector);
1449 	submit_bio_noacct(read_bio);
1450 	return;
1451 
1452 err_handle:
1453 	atomic_dec(&mirror->rdev->nr_pending);
1454 	raid_end_bio_io(r1_bio);
1455 }
1456 
1457 static bool wait_blocked_rdev(struct mddev *mddev, struct bio *bio)
1458 {
1459 	struct r1conf *conf = mddev->private;
1460 	int disks = conf->raid_disks * 2;
1461 	int i;
1462 
1463 retry:
1464 	for (i = 0; i < disks; i++) {
1465 		struct md_rdev *rdev = conf->mirrors[i].rdev;
1466 
1467 		if (!rdev)
1468 			continue;
1469 
1470 		/* don't write here until the bad block is acknowledged */
1471 		if (test_bit(WriteErrorSeen, &rdev->flags) &&
1472 		    rdev_has_badblock(rdev, bio->bi_iter.bi_sector,
1473 				      bio_sectors(bio)) < 0)
1474 			set_bit(BlockedBadBlocks, &rdev->flags);
1475 
1476 		if (rdev_blocked(rdev)) {
1477 			if (bio->bi_opf & REQ_NOWAIT)
1478 				return false;
1479 
1480 			mddev_add_trace_msg(rdev->mddev, "raid1 wait rdev %d blocked",
1481 					    rdev->raid_disk);
1482 			atomic_inc(&rdev->nr_pending);
1483 			md_wait_for_blocked_rdev(rdev, rdev->mddev);
1484 			goto retry;
1485 		}
1486 	}
1487 
1488 	return true;
1489 }
1490 
1491 static void raid1_start_write_behind(struct mddev *mddev, struct r1bio *r1_bio,
1492 				     struct bio *bio)
1493 {
1494 	unsigned long max_write_behind = mddev->bitmap_info.max_write_behind;
1495 	struct md_bitmap_stats stats;
1496 	int err;
1497 
1498 	/* behind write rely on bitmap, see bitmap_operations */
1499 	if (!md_bitmap_enabled(mddev, false))
1500 		return;
1501 
1502 	err = mddev->bitmap_ops->get_stats(mddev->bitmap, &stats);
1503 	if (err)
1504 		return;
1505 
1506 	/* Don't do behind IO if reader is waiting, or there are too many. */
1507 	if (!stats.behind_wait && stats.behind_writes < max_write_behind)
1508 		alloc_behind_master_bio(r1_bio, bio);
1509 
1510 	if (test_bit(R1BIO_BehindIO, &r1_bio->state))
1511 		mddev->bitmap_ops->start_behind_write(mddev);
1512 
1513 }
1514 
1515 static bool raid1_write_request(struct mddev *mddev, struct bio *bio,
1516 				int max_sectors)
1517 {
1518 	struct r1conf *conf = mddev->private;
1519 	struct r1bio *r1_bio;
1520 	int i, disks, k;
1521 	unsigned long flags;
1522 	int first_clone;
1523 	bool write_behind = false;
1524 	bool nowait = bio->bi_opf & REQ_NOWAIT;
1525 	bool is_discard = op_is_discard(bio->bi_opf);
1526 	sector_t sector = bio->bi_iter.bi_sector;
1527 
1528 	if (mddev_is_clustered(mddev) &&
1529 	    mddev->cluster_ops->area_resyncing(mddev, WRITE, sector,
1530 					       bio_end_sector(bio))) {
1531 
1532 		if (nowait) {
1533 			bio_wouldblock_error(bio);
1534 			return false;
1535 		}
1536 		wait_event_idle(conf->wait_barrier,
1537 				!mddev->cluster_ops->area_resyncing(mddev, WRITE,
1538 								    sector,
1539 								    bio_end_sector(bio)));
1540 	}
1541 
1542 	/*
1543 	 * Register the new request and wait if the reconstruction
1544 	 * thread has put up a bar for new requests.
1545 	 * Continue immediately if no resync is active currently.
1546 	 */
1547 	if (!wait_barrier(conf, sector, nowait)) {
1548 		bio_wouldblock_error(bio);
1549 		return false;
1550 	}
1551 
1552 	if (!wait_blocked_rdev(mddev, bio)) {
1553 		bio_wouldblock_error(bio);
1554 		goto err_allow_barrier;
1555 	}
1556 
1557 	r1_bio = alloc_r1bio(mddev, bio);
1558 	r1_bio->sectors = max_sectors;
1559 
1560 	/* first select target devices under rcu_lock and
1561 	 * inc refcount on their rdev.  Record them by setting
1562 	 * bios[x] to bio
1563 	 * If there are known/acknowledged bad blocks on any device on
1564 	 * which we have seen a write error, we want to avoid writing those
1565 	 * blocks.
1566 	 * This potentially requires several writes to write around
1567 	 * the bad blocks.  Each set of writes gets it's own r1bio
1568 	 * with a set of bios attached.
1569 	 */
1570 
1571 	disks = conf->raid_disks * 2;
1572 	for (i = 0;  i < disks; i++) {
1573 		struct md_rdev *rdev = conf->mirrors[i].rdev;
1574 
1575 		/*
1576 		 * The write-behind io is only attempted on drives marked as
1577 		 * write-mostly, which means we could allocate write behind
1578 		 * bio later.
1579 		 */
1580 		if (!is_discard && rdev && test_bit(WriteMostly, &rdev->flags))
1581 			write_behind = true;
1582 
1583 		r1_bio->bios[i] = NULL;
1584 		if (!rdev || test_bit(Faulty, &rdev->flags))
1585 			continue;
1586 
1587 		if (test_bit(WriteErrorSeen, &rdev->flags)) {
1588 			sector_t first_bad;
1589 			sector_t bad_sectors;
1590 			int is_bad;
1591 
1592 			is_bad = is_badblock(rdev, sector, max_sectors,
1593 					     &first_bad, &bad_sectors);
1594 			if (is_bad && first_bad <= sector) {
1595 				/* Cannot write here at all */
1596 				bad_sectors -= (sector - first_bad);
1597 				if (bad_sectors < max_sectors)
1598 					/* mustn't write more than bad_sectors
1599 					 * to other devices yet
1600 					 */
1601 					max_sectors = bad_sectors;
1602 				continue;
1603 			}
1604 			if (is_bad) {
1605 				int good_sectors;
1606 
1607 				/*
1608 				 * We cannot atomically write this, so just
1609 				 * error in that case. It could be possible to
1610 				 * atomically write other mirrors, but the
1611 				 * complexity of supporting that is not worth
1612 				 * the benefit.
1613 				 */
1614 				if (bio->bi_opf & REQ_ATOMIC) {
1615 					bio->bi_status = BLK_STS_NOTSUPP;
1616 					bio_endio(bio);
1617 					goto err_dec_pending;
1618 				}
1619 
1620 				good_sectors = first_bad - sector;
1621 				if (good_sectors < max_sectors)
1622 					max_sectors = good_sectors;
1623 			}
1624 		}
1625 
1626 		atomic_inc(&rdev->nr_pending);
1627 		r1_bio->bios[i] = bio;
1628 	}
1629 
1630 	/*
1631 	 * When using a bitmap, we may call alloc_behind_master_bio below.
1632 	 * alloc_behind_master_bio allocates a copy of the data payload a page
1633 	 * at a time and thus needs a new bio that can fit the whole payload
1634 	 * this bio in page sized chunks.
1635 	 */
1636 	if (write_behind && mddev->bitmap)
1637 		max_sectors = min_t(int, max_sectors,
1638 				    BIO_MAX_VECS * (PAGE_SIZE >> 9));
1639 	if (max_sectors < bio_sectors(bio)) {
1640 		bio = bio_submit_split_bioset(bio, max_sectors,
1641 					      &conf->bio_split);
1642 		if (!bio)
1643 			goto err_dec_pending;
1644 
1645 		r1_bio->master_bio = bio;
1646 		r1_bio->sectors = max_sectors;
1647 	}
1648 
1649 	md_account_bio(mddev, &bio);
1650 	r1_bio->master_bio = bio;
1651 	atomic_set(&r1_bio->remaining, 1);
1652 	atomic_set(&r1_bio->behind_remaining, 0);
1653 
1654 	first_clone = 1;
1655 
1656 	for (i = 0; i < disks; i++) {
1657 		struct bio *mbio = NULL;
1658 		struct md_rdev *rdev = conf->mirrors[i].rdev;
1659 		if (!r1_bio->bios[i])
1660 			continue;
1661 
1662 		if (first_clone) {
1663 			if (write_behind)
1664 				raid1_start_write_behind(mddev, r1_bio, bio);
1665 			first_clone = 0;
1666 		}
1667 
1668 		if (r1_bio->behind_master_bio) {
1669 			mbio = bio_alloc_clone(rdev->bdev,
1670 					       r1_bio->behind_master_bio,
1671 					       GFP_NOIO, &mddev->bio_set);
1672 			if (test_bit(CollisionCheck, &rdev->flags))
1673 				wait_for_serialization(rdev, r1_bio);
1674 			if (test_bit(WriteMostly, &rdev->flags))
1675 				atomic_inc(&r1_bio->behind_remaining);
1676 		} else {
1677 			mbio = bio_alloc_clone(rdev->bdev, bio, GFP_NOIO,
1678 					       &mddev->bio_set);
1679 
1680 			if (test_bit(MD_SERIALIZE_POLICY, &mddev->flags))
1681 				wait_for_serialization(rdev, r1_bio);
1682 		}
1683 
1684 		mbio->bi_opf &= ~REQ_NOWAIT;
1685 		r1_bio->bios[i] = mbio;
1686 
1687 		mbio->bi_iter.bi_sector	= sector + rdev->data_offset;
1688 		mbio->bi_end_io	= raid1_end_write_request;
1689 		if (test_bit(FailFast, &rdev->flags) &&
1690 		    !test_bit(WriteMostly, &rdev->flags) &&
1691 		    conf->raid_disks - mddev->degraded > 1)
1692 			mbio->bi_opf |= MD_FAILFAST;
1693 		mbio->bi_private = r1_bio;
1694 
1695 		atomic_inc(&r1_bio->remaining);
1696 		mddev_trace_remap(mddev, mbio, sector);
1697 		/* flush_pending_writes() needs access to the rdev so...*/
1698 		mbio->bi_bdev = (void *)rdev;
1699 		if (!raid1_add_bio_to_plug(mddev, mbio, raid1_unplug, disks)) {
1700 			spin_lock_irqsave(&conf->device_lock, flags);
1701 			bio_list_add(&conf->pending_bio_list, mbio);
1702 			spin_unlock_irqrestore(&conf->device_lock, flags);
1703 			md_wakeup_thread(mddev->thread);
1704 		}
1705 	}
1706 
1707 	r1_bio_write_done(r1_bio);
1708 
1709 	/* In case raid1d snuck in to freeze_array */
1710 	wake_up_barrier(conf);
1711 
1712 	return true;
1713 
1714 err_dec_pending:
1715 	for (k = 0; k < i; k++) {
1716 		if (r1_bio->bios[k]) {
1717 			rdev_dec_pending(conf->mirrors[k].rdev, mddev);
1718 			r1_bio->bios[k] = NULL;
1719 		}
1720 	}
1721 
1722 	free_r1bio(r1_bio);
1723 
1724 err_allow_barrier:
1725 	allow_barrier(conf, sector);
1726 
1727 	return false;
1728 }
1729 
1730 static bool raid1_make_request(struct mddev *mddev, struct bio *bio)
1731 {
1732 	sector_t sectors;
1733 
1734 	if (unlikely(bio->bi_opf & REQ_PREFLUSH)
1735 	    && md_flush_request(mddev, bio))
1736 		return true;
1737 
1738 	/*
1739 	 * There is a limit to the maximum size, but
1740 	 * the read/write handler might find a lower limit
1741 	 * due to bad blocks.  To avoid multiple splits,
1742 	 * we pass the maximum number of sectors down
1743 	 * and let the lower level perform the split.
1744 	 */
1745 	sectors = align_to_barrier_unit_end(
1746 		bio->bi_iter.bi_sector, bio_sectors(bio));
1747 
1748 	if (bio_data_dir(bio) == READ)
1749 		raid1_read_request(mddev, bio, sectors, NULL);
1750 	else {
1751 		md_write_start(mddev, bio);
1752 		if (!raid1_write_request(mddev, bio, sectors))
1753 			md_write_end(mddev);
1754 	}
1755 	return true;
1756 }
1757 
1758 static void raid1_status(struct seq_file *seq, struct mddev *mddev)
1759 {
1760 	struct r1conf *conf = mddev->private;
1761 	int i;
1762 
1763 	lockdep_assert_held(&mddev->lock);
1764 
1765 	seq_printf(seq, " [%d/%d] [", conf->raid_disks,
1766 		   conf->raid_disks - mddev->degraded);
1767 	for (i = 0; i < conf->raid_disks; i++) {
1768 		struct md_rdev *rdev = READ_ONCE(conf->mirrors[i].rdev);
1769 
1770 		seq_printf(seq, "%s",
1771 			   rdev && test_bit(In_sync, &rdev->flags) ? "U" : "_");
1772 	}
1773 	seq_printf(seq, "]");
1774 }
1775 
1776 /**
1777  * raid1_error() - RAID1 error handler.
1778  * @mddev: affected md device.
1779  * @rdev: member device to fail.
1780  *
1781  * The routine acknowledges &rdev failure and determines new @mddev state.
1782  * If it failed, then:
1783  *	- &MD_BROKEN flag is set in &mddev->flags.
1784  *	- recovery is disabled.
1785  * Otherwise, it must be degraded:
1786  *	- recovery is interrupted.
1787  *	- &mddev->degraded is bumped.
1788  *
1789  * @rdev is marked as &Faulty excluding case when array is failed and
1790  * MD_FAILLAST_DEV is not set.
1791  */
1792 static void raid1_error(struct mddev *mddev, struct md_rdev *rdev)
1793 {
1794 	struct r1conf *conf = mddev->private;
1795 	unsigned long flags;
1796 
1797 	spin_lock_irqsave(&conf->device_lock, flags);
1798 
1799 	if (test_bit(In_sync, &rdev->flags) &&
1800 	    (conf->raid_disks - mddev->degraded) == 1) {
1801 		set_bit(MD_BROKEN, &mddev->flags);
1802 
1803 		if (!test_bit(MD_FAILLAST_DEV, &mddev->flags)) {
1804 			spin_unlock_irqrestore(&conf->device_lock, flags);
1805 			return;
1806 		}
1807 	}
1808 	set_bit(Blocked, &rdev->flags);
1809 	if (test_and_clear_bit(In_sync, &rdev->flags))
1810 		mddev->degraded++;
1811 	set_bit(Faulty, &rdev->flags);
1812 	spin_unlock_irqrestore(&conf->device_lock, flags);
1813 	/*
1814 	 * if recovery is running, make sure it aborts.
1815 	 */
1816 	set_bit(MD_RECOVERY_INTR, &mddev->recovery);
1817 	set_mask_bits(&mddev->sb_flags, 0,
1818 		      BIT(MD_SB_CHANGE_DEVS) | BIT(MD_SB_CHANGE_PENDING));
1819 	pr_crit("md/raid1:%s: Disk failure on %pg, disabling device.\n"
1820 		"md/raid1:%s: Operation continuing on %d devices.\n",
1821 		mdname(mddev), rdev->bdev,
1822 		mdname(mddev), conf->raid_disks - mddev->degraded);
1823 }
1824 
1825 static void print_conf(struct r1conf *conf)
1826 {
1827 	int i;
1828 
1829 	pr_debug("RAID1 conf printout:\n");
1830 	if (!conf) {
1831 		pr_debug("(!conf)\n");
1832 		return;
1833 	}
1834 	pr_debug(" --- wd:%d rd:%d\n", conf->raid_disks - conf->mddev->degraded,
1835 		 conf->raid_disks);
1836 
1837 	lockdep_assert_held(&conf->mddev->reconfig_mutex);
1838 	for (i = 0; i < conf->raid_disks; i++) {
1839 		struct md_rdev *rdev = conf->mirrors[i].rdev;
1840 		if (rdev)
1841 			pr_debug(" disk %d, wo:%d, o:%d, dev:%pg\n",
1842 				 i, !test_bit(In_sync, &rdev->flags),
1843 				 !test_bit(Faulty, &rdev->flags),
1844 				 rdev->bdev);
1845 	}
1846 }
1847 
1848 static void close_sync(struct r1conf *conf)
1849 {
1850 	int idx;
1851 
1852 	for (idx = 0; idx < BARRIER_BUCKETS_NR; idx++) {
1853 		_wait_barrier(conf, idx, false);
1854 		_allow_barrier(conf, idx);
1855 	}
1856 
1857 	mempool_exit(&conf->r1buf_pool);
1858 }
1859 
1860 static int raid1_spare_active(struct mddev *mddev)
1861 {
1862 	int i;
1863 	struct r1conf *conf = mddev->private;
1864 	int count = 0;
1865 	unsigned long flags;
1866 
1867 	/*
1868 	 * Find all failed disks within the RAID1 configuration
1869 	 * and mark them readable.
1870 	 * Called under mddev lock, so rcu protection not needed.
1871 	 * device_lock used to avoid races with raid1_end_read_request
1872 	 * which expects 'In_sync' flags and ->degraded to be consistent.
1873 	 */
1874 	spin_lock_irqsave(&conf->device_lock, flags);
1875 	for (i = 0; i < conf->raid_disks; i++) {
1876 		struct md_rdev *rdev = conf->mirrors[i].rdev;
1877 		struct md_rdev *repl = conf->mirrors[conf->raid_disks + i].rdev;
1878 		if (repl
1879 		    && !test_bit(Candidate, &repl->flags)
1880 		    && repl->recovery_offset == MaxSector
1881 		    && !test_bit(Faulty, &repl->flags)
1882 		    && !test_and_set_bit(In_sync, &repl->flags)) {
1883 			/* replacement has just become active */
1884 			if (!rdev ||
1885 			    !test_and_clear_bit(In_sync, &rdev->flags))
1886 				count++;
1887 			if (rdev) {
1888 				/* Replaced device not technically
1889 				 * faulty, but we need to be sure
1890 				 * it gets removed and never re-added
1891 				 */
1892 				set_bit(Faulty, &rdev->flags);
1893 				sysfs_notify_dirent_safe(
1894 					rdev->sysfs_state);
1895 			}
1896 		}
1897 		if (rdev
1898 		    && rdev->recovery_offset == MaxSector
1899 		    && !test_bit(Faulty, &rdev->flags)
1900 		    && !test_and_set_bit(In_sync, &rdev->flags)) {
1901 			count++;
1902 			sysfs_notify_dirent_safe(rdev->sysfs_state);
1903 		}
1904 	}
1905 	mddev->degraded -= count;
1906 	spin_unlock_irqrestore(&conf->device_lock, flags);
1907 
1908 	print_conf(conf);
1909 	return count;
1910 }
1911 
1912 static bool raid1_add_conf(struct r1conf *conf, struct md_rdev *rdev, int disk,
1913 			   bool replacement)
1914 {
1915 	struct raid1_info *info = conf->mirrors + disk;
1916 
1917 	if (replacement)
1918 		info += conf->raid_disks;
1919 
1920 	if (info->rdev)
1921 		return false;
1922 
1923 	if (!bdev_rot(rdev->bdev)) {
1924 		set_bit(Nonrot, &rdev->flags);
1925 		WRITE_ONCE(conf->nonrot_disks, conf->nonrot_disks + 1);
1926 	}
1927 
1928 	rdev->raid_disk = disk;
1929 	info->head_position = 0;
1930 	info->seq_start = MaxSector;
1931 	WRITE_ONCE(info->rdev, rdev);
1932 
1933 	return true;
1934 }
1935 
1936 static bool raid1_remove_conf(struct r1conf *conf, int disk)
1937 {
1938 	struct raid1_info *info = conf->mirrors + disk;
1939 	struct md_rdev *rdev = info->rdev;
1940 
1941 	if (!rdev || test_bit(In_sync, &rdev->flags) ||
1942 	    atomic_read(&rdev->nr_pending))
1943 		return false;
1944 
1945 	/* Only remove non-faulty devices if recovery is not possible. */
1946 	if (!test_bit(Faulty, &rdev->flags) &&
1947 	    rdev->mddev->degraded < conf->raid_disks)
1948 		return false;
1949 
1950 	if (test_and_clear_bit(Nonrot, &rdev->flags))
1951 		WRITE_ONCE(conf->nonrot_disks, conf->nonrot_disks - 1);
1952 
1953 	WRITE_ONCE(info->rdev, NULL);
1954 	return true;
1955 }
1956 
1957 static int raid1_add_disk(struct mddev *mddev, struct md_rdev *rdev)
1958 {
1959 	struct r1conf *conf = mddev->private;
1960 	int err = -EEXIST;
1961 	int mirror = 0, repl_slot = -1;
1962 	struct raid1_info *p;
1963 	int first = 0;
1964 	int last = conf->raid_disks - 1;
1965 
1966 	if (rdev->raid_disk >= 0)
1967 		first = last = rdev->raid_disk;
1968 
1969 	/*
1970 	 * find the disk ... but prefer rdev->saved_raid_disk
1971 	 * if possible.
1972 	 */
1973 	if (rdev->saved_raid_disk >= 0 &&
1974 	    rdev->saved_raid_disk >= first &&
1975 	    rdev->saved_raid_disk < conf->raid_disks &&
1976 	    conf->mirrors[rdev->saved_raid_disk].rdev == NULL)
1977 		first = last = rdev->saved_raid_disk;
1978 
1979 	for (mirror = first; mirror <= last; mirror++) {
1980 		p = conf->mirrors + mirror;
1981 		if (!p->rdev) {
1982 			err = mddev_stack_new_rdev(mddev, rdev);
1983 			if (err)
1984 				return err;
1985 
1986 			raid1_add_conf(conf, rdev, mirror, false);
1987 			/* As all devices are equivalent, we don't need a full recovery
1988 			 * if this was recently any drive of the array
1989 			 */
1990 			if (rdev->saved_raid_disk < 0)
1991 				conf->fullsync = 1;
1992 			break;
1993 		}
1994 		if (test_bit(WantReplacement, &p->rdev->flags) &&
1995 		    p[conf->raid_disks].rdev == NULL && repl_slot < 0)
1996 			repl_slot = mirror;
1997 	}
1998 
1999 	if (err && repl_slot >= 0) {
2000 		/* Add this device as a replacement */
2001 		clear_bit(In_sync, &rdev->flags);
2002 		set_bit(Replacement, &rdev->flags);
2003 		raid1_add_conf(conf, rdev, repl_slot, true);
2004 		err = 0;
2005 		conf->fullsync = 1;
2006 	}
2007 
2008 	print_conf(conf);
2009 	return err;
2010 }
2011 
2012 static int raid1_remove_disk(struct mddev *mddev, struct md_rdev *rdev)
2013 {
2014 	struct r1conf *conf = mddev->private;
2015 	int err = 0;
2016 	int number = rdev->raid_disk;
2017 	struct raid1_info *p = conf->mirrors + number;
2018 
2019 	if (unlikely(number >= conf->raid_disks))
2020 		goto abort;
2021 
2022 	if (rdev != p->rdev) {
2023 		number += conf->raid_disks;
2024 		p = conf->mirrors + number;
2025 	}
2026 
2027 	print_conf(conf);
2028 	if (rdev == p->rdev) {
2029 		if (!raid1_remove_conf(conf, number)) {
2030 			err = -EBUSY;
2031 			goto abort;
2032 		}
2033 
2034 		if (number < conf->raid_disks &&
2035 		    conf->mirrors[conf->raid_disks + number].rdev) {
2036 			/* We just removed a device that is being replaced.
2037 			 * Move down the replacement.  We drain all IO before
2038 			 * doing this to avoid confusion.
2039 			 */
2040 			struct md_rdev *repl =
2041 				conf->mirrors[conf->raid_disks + number].rdev;
2042 			freeze_array(conf, 0);
2043 			if (atomic_read(&repl->nr_pending)) {
2044 				/* It means that some queued IO of retry_list
2045 				 * hold repl. Thus, we cannot set replacement
2046 				 * as NULL, avoiding rdev NULL pointer
2047 				 * dereference in sync_request_write and
2048 				 * handle_write_finished.
2049 				 */
2050 				err = -EBUSY;
2051 				unfreeze_array(conf);
2052 				goto abort;
2053 			}
2054 			clear_bit(Replacement, &repl->flags);
2055 			WRITE_ONCE(p->rdev, repl);
2056 			conf->mirrors[conf->raid_disks + number].rdev = NULL;
2057 			unfreeze_array(conf);
2058 		}
2059 
2060 		clear_bit(WantReplacement, &rdev->flags);
2061 		err = md_integrity_register(mddev);
2062 	}
2063 abort:
2064 
2065 	print_conf(conf);
2066 	return err;
2067 }
2068 
2069 static void end_sync_read(struct bio *bio)
2070 {
2071 	struct r1bio *r1_bio = get_resync_r1bio(bio);
2072 
2073 	update_head_pos(r1_bio->read_disk, r1_bio);
2074 
2075 	/*
2076 	 * we have read a block, now it needs to be re-written,
2077 	 * or re-read if the read failed.
2078 	 * We don't do much here, just schedule handling by raid1d
2079 	 */
2080 	if (!bio->bi_status)
2081 		set_bit(R1BIO_Uptodate, &r1_bio->state);
2082 
2083 	if (atomic_dec_and_test(&r1_bio->remaining))
2084 		reschedule_retry(r1_bio);
2085 }
2086 
2087 static void abort_sync_write(struct mddev *mddev, struct r1bio *r1_bio)
2088 {
2089 	sector_t sync_blocks = 0;
2090 	sector_t s = r1_bio->sector;
2091 	long sectors_to_go = r1_bio->sectors;
2092 
2093 	/* make sure these bits don't get cleared. */
2094 	do {
2095 		md_bitmap_end_sync(mddev, s, &sync_blocks);
2096 		s += sync_blocks;
2097 		sectors_to_go -= sync_blocks;
2098 	} while (sectors_to_go > 0);
2099 }
2100 
2101 static void put_sync_write_buf(struct r1bio *r1_bio)
2102 {
2103 	if (atomic_dec_and_test(&r1_bio->remaining)) {
2104 		struct mddev *mddev = r1_bio->mddev;
2105 		int s = r1_bio->sectors;
2106 
2107 		if (test_bit(R1BIO_MadeGood, &r1_bio->state) ||
2108 		    test_bit(R1BIO_WriteError, &r1_bio->state))
2109 			reschedule_retry(r1_bio);
2110 		else {
2111 			put_buf(r1_bio);
2112 			md_done_sync(mddev, s);
2113 		}
2114 	}
2115 }
2116 
2117 static void end_sync_write(struct bio *bio)
2118 {
2119 	struct r1bio *r1_bio = get_resync_r1bio(bio);
2120 	struct mddev *mddev = r1_bio->mddev;
2121 	struct r1conf *conf = mddev->private;
2122 	struct md_rdev *rdev = conf->mirrors[find_bio_disk(r1_bio, bio)].rdev;
2123 
2124 	if (bio->bi_status) {
2125 		abort_sync_write(mddev, r1_bio);
2126 		set_bit(WriteErrorSeen, &rdev->flags);
2127 		if (!test_and_set_bit(WantReplacement, &rdev->flags))
2128 			set_bit(MD_RECOVERY_NEEDED, &
2129 				mddev->recovery);
2130 		set_bit(R1BIO_WriteError, &r1_bio->state);
2131 	} else if (rdev_has_badblock(rdev, r1_bio->sector, r1_bio->sectors) &&
2132 		   !rdev_has_badblock(conf->mirrors[r1_bio->read_disk].rdev,
2133 				      r1_bio->sector, r1_bio->sectors)) {
2134 		set_bit(R1BIO_MadeGood, &r1_bio->state);
2135 	}
2136 
2137 	put_sync_write_buf(r1_bio);
2138 }
2139 
2140 static int r1_sync_page_io(struct md_rdev *rdev, sector_t sector,
2141 			   int sectors, struct page *page, blk_opf_t rw)
2142 {
2143 	if (sync_page_io(rdev, sector, sectors << 9, page, rw, false))
2144 		/* success */
2145 		return 1;
2146 	if (rw == REQ_OP_WRITE) {
2147 		set_bit(WriteErrorSeen, &rdev->flags);
2148 		if (!test_and_set_bit(WantReplacement,
2149 				      &rdev->flags))
2150 			set_bit(MD_RECOVERY_NEEDED, &
2151 				rdev->mddev->recovery);
2152 	}
2153 	/* need to record an error - either for the block or the device */
2154 	rdev_set_badblocks(rdev, sector, sectors, 0);
2155 	return 0;
2156 }
2157 
2158 static int fix_sync_read_error(struct r1bio *r1_bio)
2159 {
2160 	/* Try some synchronous reads of other devices to get
2161 	 * good data, much like with normal read errors.  Only
2162 	 * read into the pages we already have so we don't
2163 	 * need to re-issue the read request.
2164 	 * We don't need to freeze the array, because being in an
2165 	 * active sync request, there is no normal IO, and
2166 	 * no overlapping syncs.
2167 	 * We don't need to check is_badblock() again as we
2168 	 * made sure that anything with a bad block in range
2169 	 * will have bi_end_io clear.
2170 	 */
2171 	struct mddev *mddev = r1_bio->mddev;
2172 	struct r1conf *conf = mddev->private;
2173 	struct bio *bio = r1_bio->bios[r1_bio->read_disk];
2174 	struct page **pages = get_resync_pages(bio)->pages;
2175 	sector_t sect = r1_bio->sector;
2176 	int sectors = r1_bio->sectors;
2177 	int idx = 0;
2178 	struct md_rdev *rdev;
2179 
2180 	rdev = conf->mirrors[r1_bio->read_disk].rdev;
2181 	if (test_bit(FailFast, &rdev->flags)) {
2182 		/* Don't try recovering from here - just fail it
2183 		 * ... unless it is the last working device of course */
2184 		md_error(mddev, rdev);
2185 		if (test_bit(Faulty, &rdev->flags))
2186 			/* Don't try to read from here, but make sure
2187 			 * put_buf does it's thing
2188 			 */
2189 			bio->bi_end_io = end_sync_write;
2190 	}
2191 
2192 	while(sectors) {
2193 		int s = sectors;
2194 		int d = r1_bio->read_disk;
2195 		int success = 0;
2196 		int start;
2197 
2198 		if (s > (PAGE_SIZE>>9))
2199 			s = PAGE_SIZE >> 9;
2200 		do {
2201 			if (r1_bio->bios[d]->bi_end_io == end_sync_read) {
2202 				/* No rcu protection needed here devices
2203 				 * can only be removed when no resync is
2204 				 * active, and resync is currently active
2205 				 */
2206 				rdev = conf->mirrors[d].rdev;
2207 				if (sync_page_io(rdev, sect, s<<9,
2208 						 pages[idx],
2209 						 REQ_OP_READ, false)) {
2210 					success = 1;
2211 					break;
2212 				}
2213 			}
2214 			d++;
2215 			if (d == conf->raid_disks * 2)
2216 				d = 0;
2217 		} while (!success && d != r1_bio->read_disk);
2218 
2219 		if (!success) {
2220 			int abort = 0;
2221 			/* Cannot read from anywhere, this block is lost.
2222 			 * Record a bad block on each device.  If that doesn't
2223 			 * work just disable and interrupt the recovery.
2224 			 * Don't fail devices as that won't really help.
2225 			 */
2226 			pr_crit_ratelimited("md/raid1:%s: %pg: unrecoverable I/O read error for block %llu\n",
2227 					    mdname(mddev), bio->bi_bdev,
2228 					    (unsigned long long)r1_bio->sector);
2229 			for (d = 0; d < conf->raid_disks * 2; d++) {
2230 				rdev = conf->mirrors[d].rdev;
2231 				if (!rdev || test_bit(Faulty, &rdev->flags))
2232 					continue;
2233 				if (!rdev_set_badblocks(rdev, sect, s, 0))
2234 					abort = 1;
2235 			}
2236 			if (abort)
2237 				return 0;
2238 
2239 			/* Try next page */
2240 			sectors -= s;
2241 			sect += s;
2242 			idx++;
2243 			continue;
2244 		}
2245 
2246 		start = d;
2247 		/* write it back and re-read */
2248 		while (d != r1_bio->read_disk) {
2249 			if (d == 0)
2250 				d = conf->raid_disks * 2;
2251 			d--;
2252 			if (r1_bio->bios[d]->bi_end_io != end_sync_read)
2253 				continue;
2254 			rdev = conf->mirrors[d].rdev;
2255 			if (r1_sync_page_io(rdev, sect, s,
2256 					    pages[idx],
2257 					    REQ_OP_WRITE) == 0) {
2258 				r1_bio->bios[d]->bi_end_io = NULL;
2259 				rdev_dec_pending(rdev, mddev);
2260 			}
2261 		}
2262 		d = start;
2263 		while (d != r1_bio->read_disk) {
2264 			if (d == 0)
2265 				d = conf->raid_disks * 2;
2266 			d--;
2267 			if (r1_bio->bios[d]->bi_end_io != end_sync_read)
2268 				continue;
2269 			rdev = conf->mirrors[d].rdev;
2270 			if (r1_sync_page_io(rdev, sect, s,
2271 					    pages[idx],
2272 					    REQ_OP_READ) != 0)
2273 				atomic_add(s, &rdev->corrected_errors);
2274 		}
2275 		sectors -= s;
2276 		sect += s;
2277 		idx ++;
2278 	}
2279 	set_bit(R1BIO_Uptodate, &r1_bio->state);
2280 	bio->bi_status = 0;
2281 	return 1;
2282 }
2283 
2284 static void process_checks(struct r1bio *r1_bio)
2285 {
2286 	/* We have read all readable devices.  If we haven't
2287 	 * got the block, then there is no hope left.
2288 	 * If we have, then we want to do a comparison
2289 	 * and skip the write if everything is the same.
2290 	 * If any blocks failed to read, then we need to
2291 	 * attempt an over-write
2292 	 */
2293 	struct mddev *mddev = r1_bio->mddev;
2294 	struct r1conf *conf = mddev->private;
2295 	int primary;
2296 	int i;
2297 	int vcnt;
2298 
2299 	/* Fix variable parts of all bios */
2300 	vcnt = (r1_bio->sectors + PAGE_SIZE / 512 - 1) >> (PAGE_SHIFT - 9);
2301 	for (i = 0; i < conf->raid_disks * 2; i++) {
2302 		blk_status_t status;
2303 		struct bio *b = r1_bio->bios[i];
2304 		struct resync_pages *rp = get_resync_pages(b);
2305 		if (b->bi_end_io != end_sync_read)
2306 			continue;
2307 		/* fixup the bio for reuse, but preserve errno */
2308 		status = b->bi_status;
2309 		bio_reset(b, conf->mirrors[i].rdev->bdev, REQ_OP_READ);
2310 		b->bi_status = status;
2311 		b->bi_iter.bi_sector = r1_bio->sector +
2312 			conf->mirrors[i].rdev->data_offset;
2313 		b->bi_end_io = end_sync_read;
2314 		rp->raid_bio = r1_bio;
2315 		b->bi_private = rp;
2316 
2317 		/* initialize bvec table again */
2318 		md_bio_reset_resync_pages(b, rp, r1_bio->sectors << 9);
2319 	}
2320 	for (primary = 0; primary < conf->raid_disks * 2; primary++)
2321 		if (r1_bio->bios[primary]->bi_end_io == end_sync_read &&
2322 		    !r1_bio->bios[primary]->bi_status) {
2323 			r1_bio->bios[primary]->bi_end_io = NULL;
2324 			rdev_dec_pending(conf->mirrors[primary].rdev, mddev);
2325 			break;
2326 		}
2327 	r1_bio->read_disk = primary;
2328 	for (i = 0; i < conf->raid_disks * 2; i++) {
2329 		int j = 0;
2330 		struct bio *pbio = r1_bio->bios[primary];
2331 		struct bio *sbio = r1_bio->bios[i];
2332 		blk_status_t status = sbio->bi_status;
2333 		struct page **ppages = get_resync_pages(pbio)->pages;
2334 		struct page **spages = get_resync_pages(sbio)->pages;
2335 		struct bio_vec *bi;
2336 		int page_len[RESYNC_PAGES] = { 0 };
2337 		struct bvec_iter_all iter_all;
2338 
2339 		if (sbio->bi_end_io != end_sync_read)
2340 			continue;
2341 		/* Now we can 'fixup' the error value */
2342 		sbio->bi_status = 0;
2343 
2344 		bio_for_each_segment_all(bi, sbio, iter_all)
2345 			page_len[j++] = bi->bv_len;
2346 
2347 		if (!status) {
2348 			for (j = vcnt; j-- ; ) {
2349 				if (memcmp(page_address(ppages[j]),
2350 					   page_address(spages[j]),
2351 					   page_len[j]))
2352 					break;
2353 			}
2354 		} else
2355 			j = 0;
2356 		if (j >= 0)
2357 			atomic64_add(r1_bio->sectors, &mddev->resync_mismatches);
2358 		if (j < 0 || (test_bit(MD_RECOVERY_CHECK, &mddev->recovery)
2359 			      && !status)) {
2360 			/* No need to write to this device. */
2361 			sbio->bi_end_io = NULL;
2362 			rdev_dec_pending(conf->mirrors[i].rdev, mddev);
2363 			continue;
2364 		}
2365 
2366 		bio_copy_data(sbio, pbio);
2367 	}
2368 }
2369 
2370 static void sync_request_write(struct mddev *mddev, struct r1bio *r1_bio)
2371 {
2372 	struct r1conf *conf = mddev->private;
2373 	int i;
2374 	int disks = conf->raid_disks * 2;
2375 	struct bio *wbio;
2376 
2377 	if (!test_bit(R1BIO_Uptodate, &r1_bio->state)) {
2378 		/*
2379 		 * ouch - failed to read all of that.
2380 		 * No need to fix read error for check/repair
2381 		 * because all member disks are read.
2382 		 */
2383 		if (test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery) ||
2384 		    !fix_sync_read_error(r1_bio)) {
2385 			md_done_sync(mddev, r1_bio->sectors);
2386 			md_sync_error(mddev);
2387 			put_buf(r1_bio);
2388 			return;
2389 		}
2390 	}
2391 
2392 	if (test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery))
2393 		process_checks(r1_bio);
2394 
2395 	/*
2396 	 * schedule writes
2397 	 */
2398 	atomic_set(&r1_bio->remaining, 1);
2399 	for (i = 0; i < disks ; i++) {
2400 		wbio = r1_bio->bios[i];
2401 		if (wbio->bi_end_io == NULL ||
2402 		    (wbio->bi_end_io == end_sync_read &&
2403 		     (i == r1_bio->read_disk ||
2404 		      !test_bit(MD_RECOVERY_SYNC, &mddev->recovery))))
2405 			continue;
2406 		if (test_bit(Faulty, &conf->mirrors[i].rdev->flags)) {
2407 			abort_sync_write(mddev, r1_bio);
2408 			continue;
2409 		}
2410 
2411 		wbio->bi_opf = REQ_OP_WRITE;
2412 		if (test_bit(FailFast, &conf->mirrors[i].rdev->flags))
2413 			wbio->bi_opf |= MD_FAILFAST;
2414 
2415 		wbio->bi_end_io = end_sync_write;
2416 		atomic_inc(&r1_bio->remaining);
2417 
2418 		submit_bio_noacct(wbio);
2419 	}
2420 
2421 	put_sync_write_buf(r1_bio);
2422 }
2423 
2424 /*
2425  * This is a kernel thread which:
2426  *
2427  *	1.	Retries failed read operations on working mirrors.
2428  *	2.	Updates the raid superblock when problems encounter.
2429  *	3.	Performs writes following reads for array synchronising.
2430  */
2431 
2432 static void fix_read_error(struct r1conf *conf, struct r1bio *r1_bio)
2433 {
2434 	sector_t sect = r1_bio->sector;
2435 	int sectors = r1_bio->sectors;
2436 	int read_disk = r1_bio->read_disk;
2437 	struct mddev *mddev = conf->mddev;
2438 	struct md_rdev *rdev = conf->mirrors[read_disk].rdev;
2439 
2440 	while(sectors) {
2441 		int s = sectors;
2442 		int d = read_disk;
2443 		int success = 0;
2444 		int start;
2445 
2446 		if (s > (PAGE_SIZE>>9))
2447 			s = PAGE_SIZE >> 9;
2448 
2449 		do {
2450 			rdev = conf->mirrors[d].rdev;
2451 			if (rdev &&
2452 			    (test_bit(In_sync, &rdev->flags) ||
2453 			     (!test_bit(Faulty, &rdev->flags) &&
2454 			      rdev->recovery_offset >= sect + s)) &&
2455 			    rdev_has_badblock(rdev, sect, s) == 0) {
2456 				atomic_inc(&rdev->nr_pending);
2457 				if (sync_page_io(rdev, sect, s<<9,
2458 					 conf->tmppage, REQ_OP_READ, false))
2459 					success = 1;
2460 				rdev_dec_pending(rdev, mddev);
2461 				if (success)
2462 					break;
2463 			}
2464 
2465 			d++;
2466 			if (d == conf->raid_disks * 2)
2467 				d = 0;
2468 		} while (d != read_disk);
2469 
2470 		if (!success) {
2471 			/* Cannot read from anywhere - mark it bad */
2472 			struct md_rdev *rdev = conf->mirrors[read_disk].rdev;
2473 			rdev_set_badblocks(rdev, sect, s, 0);
2474 			break;
2475 		}
2476 		/* write it back and re-read */
2477 		start = d;
2478 		while (d != read_disk) {
2479 			if (d==0)
2480 				d = conf->raid_disks * 2;
2481 			d--;
2482 			rdev = conf->mirrors[d].rdev;
2483 			if (rdev &&
2484 			    !test_bit(Faulty, &rdev->flags)) {
2485 				atomic_inc(&rdev->nr_pending);
2486 				r1_sync_page_io(rdev, sect, s,
2487 						conf->tmppage, REQ_OP_WRITE);
2488 				rdev_dec_pending(rdev, mddev);
2489 			}
2490 		}
2491 		d = start;
2492 		while (d != read_disk) {
2493 			if (d==0)
2494 				d = conf->raid_disks * 2;
2495 			d--;
2496 			rdev = conf->mirrors[d].rdev;
2497 			if (rdev &&
2498 			    !test_bit(Faulty, &rdev->flags)) {
2499 				atomic_inc(&rdev->nr_pending);
2500 				if (r1_sync_page_io(rdev, sect, s,
2501 						conf->tmppage, REQ_OP_READ)) {
2502 					atomic_add(s, &rdev->corrected_errors);
2503 					pr_info("md/raid1:%s: read error corrected (%d sectors at %llu on %pg)\n",
2504 						mdname(mddev), s,
2505 						(unsigned long long)(sect +
2506 								     rdev->data_offset),
2507 						rdev->bdev);
2508 				}
2509 				rdev_dec_pending(rdev, mddev);
2510 			}
2511 		}
2512 		sectors -= s;
2513 		sect += s;
2514 	}
2515 }
2516 
2517 static void narrow_write_error(struct r1bio *r1_bio, int i)
2518 {
2519 	struct mddev *mddev = r1_bio->mddev;
2520 	struct r1conf *conf = mddev->private;
2521 	struct md_rdev *rdev = conf->mirrors[i].rdev;
2522 
2523 	/* bio has the data to be written to device 'i' where
2524 	 * we just recently had a write error.
2525 	 * We repeatedly clone the bio and trim down to one block,
2526 	 * then try the write.  Where the write fails we record
2527 	 * a bad block.
2528 	 * It is conceivable that the bio doesn't exactly align with
2529 	 * blocks.  We must handle this somehow.
2530 	 *
2531 	 * We currently own a reference on the rdev.
2532 	 */
2533 
2534 	int block_sectors, lbs = bdev_logical_block_size(rdev->bdev) >> 9;
2535 	sector_t sector;
2536 	int sectors;
2537 	int sect_to_write = r1_bio->sectors;
2538 
2539 	if (rdev->badblocks.shift < 0)
2540 		block_sectors = lbs;
2541 	else
2542 		block_sectors = roundup(1 << rdev->badblocks.shift, lbs);
2543 
2544 	sector = r1_bio->sector;
2545 	sectors = ((sector + block_sectors)
2546 		   & ~(sector_t)(block_sectors - 1))
2547 		- sector;
2548 
2549 	while (sect_to_write) {
2550 		struct bio *wbio;
2551 		if (sectors > sect_to_write)
2552 			sectors = sect_to_write;
2553 		/* Write at 'sector' for 'sectors'*/
2554 
2555 		if (test_bit(R1BIO_BehindIO, &r1_bio->state)) {
2556 			wbio = bio_alloc_clone(rdev->bdev,
2557 					       r1_bio->behind_master_bio,
2558 					       GFP_NOIO, &mddev->bio_set);
2559 		} else {
2560 			wbio = bio_alloc_clone(rdev->bdev, r1_bio->master_bio,
2561 					       GFP_NOIO, &mddev->bio_set);
2562 		}
2563 
2564 		wbio->bi_opf = REQ_OP_WRITE;
2565 		wbio->bi_iter.bi_sector = r1_bio->sector;
2566 		wbio->bi_iter.bi_size = r1_bio->sectors << 9;
2567 
2568 		bio_trim(wbio, sector - r1_bio->sector, sectors);
2569 		wbio->bi_iter.bi_sector += rdev->data_offset;
2570 
2571 		if (submit_bio_wait(wbio) &&
2572 		    !rdev_set_badblocks(rdev, sector, sectors, 0)) {
2573 			/*
2574 			 * Badblocks set failed, disk marked Faulty.
2575 			 * No further operations needed.
2576 			 */
2577 			bio_put(wbio);
2578 			break;
2579 		}
2580 
2581 		bio_put(wbio);
2582 		sect_to_write -= sectors;
2583 		sector += sectors;
2584 		sectors = block_sectors;
2585 	}
2586 }
2587 
2588 static void handle_sync_write_finished(struct r1conf *conf, struct r1bio *r1_bio)
2589 {
2590 	int m;
2591 	int s = r1_bio->sectors;
2592 	for (m = 0; m < conf->raid_disks * 2 ; m++) {
2593 		struct md_rdev *rdev = conf->mirrors[m].rdev;
2594 		struct bio *bio = r1_bio->bios[m];
2595 		if (bio->bi_end_io == NULL)
2596 			continue;
2597 		if (!bio->bi_status &&
2598 		    test_bit(R1BIO_MadeGood, &r1_bio->state))
2599 			rdev_clear_badblocks(rdev, r1_bio->sector, s, 0);
2600 		if (bio->bi_status &&
2601 		    test_bit(R1BIO_WriteError, &r1_bio->state))
2602 			rdev_set_badblocks(rdev, r1_bio->sector, s, 0);
2603 	}
2604 	put_buf(r1_bio);
2605 	md_done_sync(conf->mddev, s);
2606 }
2607 
2608 static void handle_write_finished(struct r1conf *conf, struct r1bio *r1_bio)
2609 {
2610 	int m, idx;
2611 	bool fail = false;
2612 
2613 	for (m = 0; m < conf->raid_disks * 2 ; m++)
2614 		if (r1_bio->bios[m] == IO_MADE_GOOD) {
2615 			struct md_rdev *rdev = conf->mirrors[m].rdev;
2616 			rdev_clear_badblocks(rdev,
2617 					     r1_bio->sector,
2618 					     r1_bio->sectors, 0);
2619 			rdev_dec_pending(rdev, conf->mddev);
2620 		} else if (r1_bio->bios[m] != NULL) {
2621 			/* This drive got a write error.  We need to
2622 			 * narrow down and record precise write
2623 			 * errors.
2624 			 */
2625 			fail = true;
2626 			narrow_write_error(r1_bio, m);
2627 			rdev_dec_pending(conf->mirrors[m].rdev,
2628 					 conf->mddev);
2629 		}
2630 	if (fail) {
2631 		spin_lock_irq(&conf->device_lock);
2632 		list_add(&r1_bio->retry_list, &conf->bio_end_io_list);
2633 		idx = sector_to_idx(r1_bio->sector);
2634 		atomic_inc(&conf->nr_queued[idx]);
2635 		spin_unlock_irq(&conf->device_lock);
2636 		/*
2637 		 * In case freeze_array() is waiting for condition
2638 		 * get_unqueued_pending() == extra to be true.
2639 		 */
2640 		wake_up(&conf->wait_barrier);
2641 		md_wakeup_thread(conf->mddev->thread);
2642 	} else {
2643 		if (test_bit(R1BIO_WriteError, &r1_bio->state))
2644 			close_write(r1_bio);
2645 		raid_end_bio_io(r1_bio);
2646 	}
2647 }
2648 
2649 static void handle_read_error(struct r1conf *conf, struct r1bio *r1_bio)
2650 {
2651 	struct md_rdev *rdev = conf->mirrors[r1_bio->read_disk].rdev;
2652 	struct bio *bio = r1_bio->bios[r1_bio->read_disk];
2653 	struct mddev *mddev = conf->mddev;
2654 	sector_t sector;
2655 
2656 	clear_bit(R1BIO_ReadError, &r1_bio->state);
2657 
2658 	bio_put(bio);
2659 	r1_bio->bios[r1_bio->read_disk] = NULL;
2660 
2661 	/*
2662 	 * We got a read error. Maybe the drive is bad.  Maybe just the block
2663 	 * and we can fix it.
2664 	 *
2665 	 * If allowed, freeze all other IO, and try reading the block from other
2666 	 * devices.  If we find one, we re-write and check it that fixes the
2667 	 * read error.  This is all done synchronously while the array is
2668 	 * frozen.
2669 	 */
2670 	if (mddev->ro) {
2671 		r1_bio->bios[r1_bio->read_disk] = IO_BLOCKED;
2672 	} else if (test_bit(FailFast, &rdev->flags)) {
2673 		md_error(mddev, rdev);
2674 	} else {
2675 		freeze_array(conf, 1);
2676 		if (exceed_read_errors(mddev, rdev))
2677 			r1_bio->bios[r1_bio->read_disk] = IO_BLOCKED;
2678 		else
2679 			fix_read_error(conf, r1_bio);
2680 		unfreeze_array(conf);
2681 	}
2682 
2683 	rdev_dec_pending(rdev, conf->mddev);
2684 	sector = r1_bio->sector;
2685 	bio = r1_bio->master_bio;
2686 
2687 	/* Reuse the old r1_bio so that the IO_BLOCKED settings are preserved */
2688 	r1_bio->state = 0;
2689 	raid1_read_request(mddev, bio, r1_bio->sectors, r1_bio);
2690 	allow_barrier(conf, sector);
2691 }
2692 
2693 static void raid1d(struct md_thread *thread)
2694 {
2695 	struct mddev *mddev = thread->mddev;
2696 	struct r1bio *r1_bio;
2697 	unsigned long flags;
2698 	struct r1conf *conf = mddev->private;
2699 	struct list_head *head = &conf->retry_list;
2700 	struct blk_plug plug;
2701 	int idx;
2702 
2703 	md_check_recovery(mddev);
2704 
2705 	if (!list_empty_careful(&conf->bio_end_io_list) &&
2706 	    !test_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags)) {
2707 		LIST_HEAD(tmp);
2708 		spin_lock_irqsave(&conf->device_lock, flags);
2709 		if (!test_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags))
2710 			list_splice_init(&conf->bio_end_io_list, &tmp);
2711 		spin_unlock_irqrestore(&conf->device_lock, flags);
2712 		while (!list_empty(&tmp)) {
2713 			r1_bio = list_first_entry(&tmp, struct r1bio,
2714 						  retry_list);
2715 			list_del(&r1_bio->retry_list);
2716 			idx = sector_to_idx(r1_bio->sector);
2717 			atomic_dec(&conf->nr_queued[idx]);
2718 			if (test_bit(R1BIO_WriteError, &r1_bio->state))
2719 				close_write(r1_bio);
2720 			raid_end_bio_io(r1_bio);
2721 		}
2722 	}
2723 
2724 	blk_start_plug(&plug);
2725 	for (;;) {
2726 
2727 		flush_pending_writes(conf);
2728 
2729 		spin_lock_irqsave(&conf->device_lock, flags);
2730 		if (list_empty(head)) {
2731 			spin_unlock_irqrestore(&conf->device_lock, flags);
2732 			break;
2733 		}
2734 		r1_bio = list_entry(head->prev, struct r1bio, retry_list);
2735 		list_del(head->prev);
2736 		idx = sector_to_idx(r1_bio->sector);
2737 		atomic_dec(&conf->nr_queued[idx]);
2738 		spin_unlock_irqrestore(&conf->device_lock, flags);
2739 
2740 		mddev = r1_bio->mddev;
2741 		conf = mddev->private;
2742 		if (test_bit(R1BIO_IsSync, &r1_bio->state)) {
2743 			if (test_bit(R1BIO_MadeGood, &r1_bio->state) ||
2744 			    test_bit(R1BIO_WriteError, &r1_bio->state))
2745 				handle_sync_write_finished(conf, r1_bio);
2746 			else
2747 				sync_request_write(mddev, r1_bio);
2748 		} else if (test_bit(R1BIO_MadeGood, &r1_bio->state) ||
2749 			   test_bit(R1BIO_WriteError, &r1_bio->state))
2750 			handle_write_finished(conf, r1_bio);
2751 		else if (test_bit(R1BIO_ReadError, &r1_bio->state))
2752 			handle_read_error(conf, r1_bio);
2753 		else
2754 			WARN_ON_ONCE(1);
2755 
2756 		cond_resched();
2757 		if (mddev->sb_flags & ~(1<<MD_SB_CHANGE_PENDING))
2758 			md_check_recovery(mddev);
2759 	}
2760 	blk_finish_plug(&plug);
2761 }
2762 
2763 static int init_resync(struct r1conf *conf)
2764 {
2765 	int buffs;
2766 
2767 	buffs = RESYNC_WINDOW / RESYNC_BLOCK_SIZE;
2768 	BUG_ON(mempool_initialized(&conf->r1buf_pool));
2769 
2770 	return mempool_init(&conf->r1buf_pool, buffs, r1buf_pool_alloc,
2771 			    r1buf_pool_free, conf);
2772 }
2773 
2774 static struct r1bio *raid1_alloc_init_r1buf(struct r1conf *conf)
2775 {
2776 	struct r1bio *r1bio = mempool_alloc(&conf->r1buf_pool, GFP_NOIO);
2777 	struct resync_pages *rps;
2778 	struct bio *bio;
2779 	int i;
2780 
2781 	for (i = conf->raid_disks * 2; i--; ) {
2782 		bio = r1bio->bios[i];
2783 		rps = bio->bi_private;
2784 		bio_reset(bio, NULL, 0);
2785 		bio->bi_private = rps;
2786 	}
2787 	r1bio->master_bio = NULL;
2788 	return r1bio;
2789 }
2790 
2791 /*
2792  * perform a "sync" on one "block"
2793  *
2794  * We need to make sure that no normal I/O request - particularly write
2795  * requests - conflict with active sync requests.
2796  *
2797  * This is achieved by tracking pending requests and a 'barrier' concept
2798  * that can be installed to exclude normal IO requests.
2799  */
2800 
2801 static sector_t raid1_sync_request(struct mddev *mddev, sector_t sector_nr,
2802 				   sector_t max_sector, int *skipped)
2803 {
2804 	struct r1conf *conf = mddev->private;
2805 	struct r1bio *r1_bio;
2806 	struct bio *bio;
2807 	sector_t nr_sectors;
2808 	int disk = -1;
2809 	int i;
2810 	int wonly = -1;
2811 	int write_targets = 0, read_targets = 0;
2812 	sector_t sync_blocks;
2813 	bool still_degraded = false;
2814 	int good_sectors = RESYNC_SECTORS;
2815 	int min_bad = 0; /* number of sectors that are bad in all devices */
2816 	int idx = sector_to_idx(sector_nr);
2817 	int page_idx = 0;
2818 
2819 	if (!mempool_initialized(&conf->r1buf_pool))
2820 		if (init_resync(conf))
2821 			return 0;
2822 
2823 	if (sector_nr >= max_sector) {
2824 		/* If we aborted, we need to abort the
2825 		 * sync on the 'current' bitmap chunk (there will
2826 		 * only be one in raid1 resync.
2827 		 * We can find the current addess in mddev->curr_resync
2828 		 */
2829 		if (mddev->curr_resync < max_sector) /* aborted */
2830 			md_bitmap_end_sync(mddev, mddev->curr_resync,
2831 					   &sync_blocks);
2832 		else /* completed sync */
2833 			conf->fullsync = 0;
2834 
2835 		if (md_bitmap_enabled(mddev, false))
2836 			mddev->bitmap_ops->close_sync(mddev);
2837 		close_sync(conf);
2838 
2839 		if (mddev_is_clustered(mddev)) {
2840 			conf->cluster_sync_low = 0;
2841 			conf->cluster_sync_high = 0;
2842 		}
2843 		return 0;
2844 	}
2845 
2846 	if (mddev->bitmap == NULL &&
2847 	    mddev->resync_offset == MaxSector &&
2848 	    !test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery) &&
2849 	    conf->fullsync == 0) {
2850 		*skipped = 1;
2851 		return max_sector - sector_nr;
2852 	}
2853 	/* before building a request, check if we can skip these blocks..
2854 	 * This call the bitmap_start_sync doesn't actually record anything
2855 	 */
2856 	if (!md_bitmap_start_sync(mddev, sector_nr, &sync_blocks, true) &&
2857 	    !conf->fullsync && !test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery)) {
2858 		/* We can skip this block, and probably several more */
2859 		*skipped = 1;
2860 		return sync_blocks;
2861 	}
2862 
2863 	/*
2864 	 * If there is non-resync activity waiting for a turn, then let it
2865 	 * though before starting on this new sync request.
2866 	 */
2867 	if (atomic_read(&conf->nr_waiting[idx]))
2868 		schedule_timeout_uninterruptible(1);
2869 
2870 	/* we are incrementing sector_nr below. To be safe, we check against
2871 	 * sector_nr + two times RESYNC_SECTORS
2872 	 */
2873 	if (md_bitmap_enabled(mddev, false))
2874 		mddev->bitmap_ops->cond_end_sync(mddev, sector_nr,
2875 			mddev_is_clustered(mddev) &&
2876 			(sector_nr + 2 * RESYNC_SECTORS >
2877 			 conf->cluster_sync_high));
2878 
2879 	if (raise_barrier(conf, sector_nr))
2880 		return 0;
2881 
2882 	r1_bio = raid1_alloc_init_r1buf(conf);
2883 
2884 	/*
2885 	 * If we get a correctably read error during resync or recovery,
2886 	 * we might want to read from a different device.  So we
2887 	 * flag all drives that could conceivably be read from for READ,
2888 	 * and any others (which will be non-In_sync devices) for WRITE.
2889 	 * If a read fails, we try reading from something else for which READ
2890 	 * is OK.
2891 	 */
2892 
2893 	r1_bio->mddev = mddev;
2894 	r1_bio->sector = sector_nr;
2895 	r1_bio->state = 0;
2896 	set_bit(R1BIO_IsSync, &r1_bio->state);
2897 	/* make sure good_sectors won't go across barrier unit boundary */
2898 	good_sectors = align_to_barrier_unit_end(sector_nr, good_sectors);
2899 
2900 	for (i = 0; i < conf->raid_disks * 2; i++) {
2901 		struct md_rdev *rdev;
2902 		bio = r1_bio->bios[i];
2903 
2904 		rdev = conf->mirrors[i].rdev;
2905 		if (rdev == NULL ||
2906 		    test_bit(Faulty, &rdev->flags)) {
2907 			if (i < conf->raid_disks)
2908 				still_degraded = true;
2909 		} else if (!test_bit(In_sync, &rdev->flags)) {
2910 			bio->bi_opf = REQ_OP_WRITE;
2911 			bio->bi_end_io = end_sync_write;
2912 			write_targets ++;
2913 		} else {
2914 			/* may need to read from here */
2915 			sector_t first_bad = MaxSector;
2916 			sector_t bad_sectors;
2917 
2918 			if (is_badblock(rdev, sector_nr, good_sectors,
2919 					&first_bad, &bad_sectors)) {
2920 				if (first_bad > sector_nr)
2921 					good_sectors = first_bad - sector_nr;
2922 				else {
2923 					bad_sectors -= (sector_nr - first_bad);
2924 					if (min_bad == 0 ||
2925 					    min_bad > bad_sectors)
2926 						min_bad = bad_sectors;
2927 				}
2928 			}
2929 			if (sector_nr < first_bad) {
2930 				if (test_bit(WriteMostly, &rdev->flags)) {
2931 					if (wonly < 0)
2932 						wonly = i;
2933 				} else {
2934 					if (disk < 0)
2935 						disk = i;
2936 				}
2937 				bio->bi_opf = REQ_OP_READ;
2938 				bio->bi_end_io = end_sync_read;
2939 				read_targets++;
2940 			} else if (!test_bit(WriteErrorSeen, &rdev->flags) &&
2941 				test_bit(MD_RECOVERY_SYNC, &mddev->recovery) &&
2942 				!test_bit(MD_RECOVERY_CHECK, &mddev->recovery)) {
2943 				/*
2944 				 * The device is suitable for reading (InSync),
2945 				 * but has bad block(s) here. Let's try to correct them,
2946 				 * if we are doing resync or repair. Otherwise, leave
2947 				 * this device alone for this sync request.
2948 				 */
2949 				bio->bi_opf = REQ_OP_WRITE;
2950 				bio->bi_end_io = end_sync_write;
2951 				write_targets++;
2952 			}
2953 		}
2954 		if (rdev && bio->bi_end_io) {
2955 			atomic_inc(&rdev->nr_pending);
2956 			bio->bi_iter.bi_sector = sector_nr + rdev->data_offset;
2957 			bio_set_dev(bio, rdev->bdev);
2958 			if (test_bit(FailFast, &rdev->flags))
2959 				bio->bi_opf |= MD_FAILFAST;
2960 		}
2961 	}
2962 	if (disk < 0)
2963 		disk = wonly;
2964 	r1_bio->read_disk = disk;
2965 
2966 	if (read_targets == 0 && min_bad > 0) {
2967 		/* These sectors are bad on all InSync devices, so we
2968 		 * need to mark them bad on all write targets
2969 		 */
2970 		int ok = 1;
2971 		for (i = 0 ; i < conf->raid_disks * 2 ; i++)
2972 			if (r1_bio->bios[i]->bi_end_io == end_sync_write) {
2973 				struct md_rdev *rdev = conf->mirrors[i].rdev;
2974 				ok = rdev_set_badblocks(rdev, sector_nr,
2975 							min_bad, 0
2976 					) && ok;
2977 			}
2978 		set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
2979 		*skipped = 1;
2980 		put_buf(r1_bio);
2981 
2982 		if (!ok)
2983 			/* Cannot record the badblocks, md_error has set INTR,
2984 			 * abort the resync.
2985 			 */
2986 			return 0;
2987 		else
2988 			return min_bad;
2989 
2990 	}
2991 	if (min_bad > 0 && min_bad < good_sectors) {
2992 		/* only resync enough to reach the next bad->good
2993 		 * transition */
2994 		good_sectors = min_bad;
2995 	}
2996 
2997 	if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery) && read_targets > 0)
2998 		/* extra read targets are also write targets */
2999 		write_targets += read_targets-1;
3000 
3001 	if (write_targets == 0 || read_targets == 0) {
3002 		/* There is nowhere to write, so all non-sync
3003 		 * drives must be failed - so we are finished
3004 		 */
3005 		sector_t rv;
3006 		if (min_bad > 0)
3007 			max_sector = sector_nr + min_bad;
3008 		rv = max_sector - sector_nr;
3009 		*skipped = 1;
3010 		put_buf(r1_bio);
3011 		return rv;
3012 	}
3013 
3014 	if (max_sector > mddev->resync_max)
3015 		max_sector = mddev->resync_max; /* Don't do IO beyond here */
3016 	if (max_sector > sector_nr + good_sectors)
3017 		max_sector = sector_nr + good_sectors;
3018 	nr_sectors = 0;
3019 	sync_blocks = 0;
3020 	do {
3021 		struct page *page;
3022 		int len = PAGE_SIZE;
3023 		if (sector_nr + (len>>9) > max_sector)
3024 			len = (max_sector - sector_nr) << 9;
3025 		if (len == 0)
3026 			break;
3027 		if (sync_blocks == 0) {
3028 			if (!md_bitmap_start_sync(mddev, sector_nr,
3029 						  &sync_blocks, still_degraded) &&
3030 			    !conf->fullsync &&
3031 			    !test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery))
3032 				break;
3033 			if ((len >> 9) > sync_blocks)
3034 				len = sync_blocks<<9;
3035 		}
3036 
3037 		for (i = 0 ; i < conf->raid_disks * 2; i++) {
3038 			struct resync_pages *rp;
3039 
3040 			bio = r1_bio->bios[i];
3041 			rp = get_resync_pages(bio);
3042 			if (bio->bi_end_io) {
3043 				page = resync_fetch_page(rp, page_idx);
3044 
3045 				/*
3046 				 * won't fail because the vec table is big
3047 				 * enough to hold all these pages
3048 				 */
3049 				__bio_add_page(bio, page, len, 0);
3050 			}
3051 		}
3052 		nr_sectors += len>>9;
3053 		sector_nr += len>>9;
3054 		sync_blocks -= (len>>9);
3055 	} while (++page_idx < RESYNC_PAGES);
3056 
3057 	r1_bio->sectors = nr_sectors;
3058 
3059 	if (mddev_is_clustered(mddev) &&
3060 			conf->cluster_sync_high < sector_nr + nr_sectors) {
3061 		conf->cluster_sync_low = mddev->curr_resync_completed;
3062 		conf->cluster_sync_high = conf->cluster_sync_low + CLUSTER_RESYNC_WINDOW_SECTORS;
3063 		/* Send resync message */
3064 		mddev->cluster_ops->resync_info_update(mddev,
3065 						       conf->cluster_sync_low,
3066 						       conf->cluster_sync_high);
3067 	}
3068 
3069 	/* For a user-requested sync, we read all readable devices and do a
3070 	 * compare
3071 	 */
3072 	if (test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery)) {
3073 		atomic_set(&r1_bio->remaining, read_targets);
3074 		for (i = 0; i < conf->raid_disks * 2 && read_targets; i++) {
3075 			bio = r1_bio->bios[i];
3076 			if (bio->bi_end_io == end_sync_read) {
3077 				read_targets--;
3078 				if (read_targets == 1)
3079 					bio->bi_opf &= ~MD_FAILFAST;
3080 				submit_bio_noacct(bio);
3081 			}
3082 		}
3083 	} else {
3084 		atomic_set(&r1_bio->remaining, 1);
3085 		bio = r1_bio->bios[r1_bio->read_disk];
3086 		if (read_targets == 1)
3087 			bio->bi_opf &= ~MD_FAILFAST;
3088 		submit_bio_noacct(bio);
3089 	}
3090 	return nr_sectors;
3091 }
3092 
3093 static sector_t raid1_size(struct mddev *mddev, sector_t sectors, int raid_disks)
3094 {
3095 	if (sectors)
3096 		return sectors;
3097 
3098 	return mddev->dev_sectors;
3099 }
3100 
3101 static struct r1conf *setup_conf(struct mddev *mddev)
3102 {
3103 	struct r1conf *conf;
3104 	int i;
3105 	struct raid1_info *disk;
3106 	struct md_rdev *rdev;
3107 	size_t r1bio_size;
3108 	int err = -ENOMEM;
3109 
3110 	conf = kzalloc_obj(struct r1conf);
3111 	if (!conf)
3112 		goto abort;
3113 
3114 	conf->nr_pending = kzalloc_objs(atomic_t, BARRIER_BUCKETS_NR);
3115 	if (!conf->nr_pending)
3116 		goto abort;
3117 
3118 	conf->nr_waiting = kzalloc_objs(atomic_t, BARRIER_BUCKETS_NR);
3119 	if (!conf->nr_waiting)
3120 		goto abort;
3121 
3122 	conf->nr_queued = kzalloc_objs(atomic_t, BARRIER_BUCKETS_NR);
3123 	if (!conf->nr_queued)
3124 		goto abort;
3125 
3126 	conf->barrier = kzalloc_objs(atomic_t, BARRIER_BUCKETS_NR);
3127 	if (!conf->barrier)
3128 		goto abort;
3129 
3130 	conf->mirrors = kzalloc(array3_size(sizeof(struct raid1_info),
3131 					    mddev->raid_disks, 2),
3132 				GFP_KERNEL);
3133 	if (!conf->mirrors)
3134 		goto abort;
3135 
3136 	conf->tmppage = alloc_page(GFP_KERNEL);
3137 	if (!conf->tmppage)
3138 		goto abort;
3139 
3140 	r1bio_size = offsetof(struct r1bio, bios[mddev->raid_disks * 2]);
3141 	conf->r1bio_pool = mempool_create_kmalloc_pool(NR_RAID_BIOS, r1bio_size);
3142 	if (!conf->r1bio_pool)
3143 		goto abort;
3144 
3145 	err = bioset_init(&conf->bio_split, BIO_POOL_SIZE, 0, 0);
3146 	if (err)
3147 		goto abort;
3148 
3149 	err = -EINVAL;
3150 	spin_lock_init(&conf->device_lock);
3151 	conf->raid_disks = mddev->raid_disks;
3152 	rdev_for_each(rdev, mddev) {
3153 		int disk_idx = rdev->raid_disk;
3154 
3155 		if (disk_idx >= conf->raid_disks || disk_idx < 0)
3156 			continue;
3157 
3158 		if (!raid1_add_conf(conf, rdev, disk_idx,
3159 				    test_bit(Replacement, &rdev->flags)))
3160 			goto abort;
3161 	}
3162 	conf->mddev = mddev;
3163 	INIT_LIST_HEAD(&conf->retry_list);
3164 	INIT_LIST_HEAD(&conf->bio_end_io_list);
3165 
3166 	spin_lock_init(&conf->resync_lock);
3167 	init_waitqueue_head(&conf->wait_barrier);
3168 
3169 	bio_list_init(&conf->pending_bio_list);
3170 
3171 	err = -EIO;
3172 	for (i = 0; i < conf->raid_disks * 2; i++) {
3173 
3174 		disk = conf->mirrors + i;
3175 
3176 		if (i < conf->raid_disks &&
3177 		    disk[conf->raid_disks].rdev) {
3178 			/* This slot has a replacement. */
3179 			if (!disk->rdev) {
3180 				/* No original, just make the replacement
3181 				 * a recovering spare
3182 				 */
3183 				disk->rdev =
3184 					disk[conf->raid_disks].rdev;
3185 				disk[conf->raid_disks].rdev = NULL;
3186 			} else if (!test_bit(In_sync, &disk->rdev->flags))
3187 				/* Original is not in_sync - bad */
3188 				goto abort;
3189 		}
3190 
3191 		if (!disk->rdev ||
3192 		    !test_bit(In_sync, &disk->rdev->flags)) {
3193 			disk->head_position = 0;
3194 			if (disk->rdev &&
3195 			    (disk->rdev->saved_raid_disk < 0))
3196 				conf->fullsync = 1;
3197 		}
3198 	}
3199 
3200 	err = -ENOMEM;
3201 	rcu_assign_pointer(conf->thread,
3202 			   md_register_thread(raid1d, mddev, "raid1"));
3203 	if (!conf->thread)
3204 		goto abort;
3205 
3206 	return conf;
3207 
3208  abort:
3209 	if (conf) {
3210 		mempool_destroy(conf->r1bio_pool);
3211 		kfree(conf->mirrors);
3212 		safe_put_page(conf->tmppage);
3213 		kfree(conf->nr_pending);
3214 		kfree(conf->nr_waiting);
3215 		kfree(conf->nr_queued);
3216 		kfree(conf->barrier);
3217 		bioset_exit(&conf->bio_split);
3218 		kfree(conf);
3219 	}
3220 	return ERR_PTR(err);
3221 }
3222 
3223 static int raid1_set_limits(struct mddev *mddev)
3224 {
3225 	struct queue_limits lim;
3226 	int err;
3227 
3228 	md_init_stacking_limits(&lim);
3229 	lim.max_write_zeroes_sectors = 0;
3230 	lim.max_hw_wzeroes_unmap_sectors = 0;
3231 	lim.logical_block_size = mddev->logical_block_size;
3232 	lim.features |= BLK_FEAT_ATOMIC_WRITES;
3233 	lim.features |= BLK_FEAT_PCI_P2PDMA;
3234 	err = mddev_stack_rdev_limits(mddev, &lim, MDDEV_STACK_INTEGRITY);
3235 	if (err)
3236 		return err;
3237 	return queue_limits_set(mddev->gendisk->queue, &lim);
3238 }
3239 
3240 static int raid1_run(struct mddev *mddev)
3241 {
3242 	struct r1conf *conf;
3243 	int i;
3244 	int ret;
3245 
3246 	if (mddev->level != 1) {
3247 		pr_warn("md/raid1:%s: raid level not set to mirroring (%d)\n",
3248 			mdname(mddev), mddev->level);
3249 		return -EIO;
3250 	}
3251 	if (mddev->reshape_position != MaxSector) {
3252 		pr_warn("md/raid1:%s: reshape_position set but not supported\n",
3253 			mdname(mddev));
3254 		return -EIO;
3255 	}
3256 
3257 	/*
3258 	 * copy the already verified devices into our private RAID1
3259 	 * bookkeeping area. [whatever we allocate in run(),
3260 	 * should be freed in raid1_free()]
3261 	 */
3262 	if (mddev->private == NULL)
3263 		conf = setup_conf(mddev);
3264 	else
3265 		conf = mddev->private;
3266 
3267 	if (IS_ERR(conf))
3268 		return PTR_ERR(conf);
3269 
3270 	if (!mddev_is_dm(mddev)) {
3271 		ret = raid1_set_limits(mddev);
3272 		if (ret) {
3273 			md_unregister_thread(mddev, &conf->thread);
3274 			if (!mddev->private)
3275 				raid1_free(mddev, conf);
3276 			return ret;
3277 		}
3278 	}
3279 
3280 	mddev->degraded = 0;
3281 	for (i = 0; i < conf->raid_disks; i++)
3282 		if (conf->mirrors[i].rdev == NULL ||
3283 		    !test_bit(In_sync, &conf->mirrors[i].rdev->flags) ||
3284 		    test_bit(Faulty, &conf->mirrors[i].rdev->flags))
3285 			mddev->degraded++;
3286 	/*
3287 	 * RAID1 needs at least one disk in active
3288 	 */
3289 	if (conf->raid_disks - mddev->degraded < 1) {
3290 		md_unregister_thread(mddev, &conf->thread);
3291 		if (!mddev->private)
3292 			raid1_free(mddev, conf);
3293 		return -EINVAL;
3294 	}
3295 
3296 	if (conf->raid_disks - mddev->degraded == 1)
3297 		mddev->resync_offset = MaxSector;
3298 
3299 	if (mddev->resync_offset != MaxSector)
3300 		pr_info("md/raid1:%s: not clean -- starting background reconstruction\n",
3301 			mdname(mddev));
3302 	pr_info("md/raid1:%s: active with %d out of %d mirrors\n",
3303 		mdname(mddev), mddev->raid_disks - mddev->degraded,
3304 		mddev->raid_disks);
3305 
3306 	/*
3307 	 * Ok, everything is just fine now
3308 	 */
3309 	rcu_assign_pointer(mddev->thread, conf->thread);
3310 	rcu_assign_pointer(conf->thread, NULL);
3311 	mddev->private = conf;
3312 	set_bit(MD_FAILFAST_SUPPORTED, &mddev->flags);
3313 
3314 	md_set_array_sectors(mddev, raid1_size(mddev, 0, 0));
3315 
3316 	ret = md_integrity_register(mddev);
3317 	if (ret)
3318 		md_unregister_thread(mddev, &mddev->thread);
3319 	return ret;
3320 }
3321 
3322 static void raid1_free(struct mddev *mddev, void *priv)
3323 {
3324 	struct r1conf *conf = priv;
3325 
3326 	mempool_destroy(conf->r1bio_pool);
3327 	kfree(conf->mirrors);
3328 	safe_put_page(conf->tmppage);
3329 	kfree(conf->nr_pending);
3330 	kfree(conf->nr_waiting);
3331 	kfree(conf->nr_queued);
3332 	kfree(conf->barrier);
3333 	bioset_exit(&conf->bio_split);
3334 	kfree(conf);
3335 }
3336 
3337 static int raid1_resize(struct mddev *mddev, sector_t sectors)
3338 {
3339 	/* no resync is happening, and there is enough space
3340 	 * on all devices, so we can resize.
3341 	 * We need to make sure resync covers any new space.
3342 	 * If the array is shrinking we should possibly wait until
3343 	 * any io in the removed space completes, but it hardly seems
3344 	 * worth it.
3345 	 */
3346 	sector_t newsize = raid1_size(mddev, sectors, 0);
3347 
3348 	if (mddev->external_size &&
3349 	    mddev->array_sectors > newsize)
3350 		return -EINVAL;
3351 
3352 	if (md_bitmap_enabled(mddev, false)) {
3353 		int ret = mddev->bitmap_ops->resize(mddev, newsize, 0);
3354 
3355 		if (ret)
3356 			return ret;
3357 	}
3358 
3359 	md_set_array_sectors(mddev, newsize);
3360 	if (sectors > mddev->dev_sectors &&
3361 	    mddev->resync_offset > mddev->dev_sectors) {
3362 		mddev->resync_offset = mddev->dev_sectors;
3363 		set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
3364 	}
3365 	mddev->dev_sectors = sectors;
3366 	mddev->resync_max_sectors = sectors;
3367 	return 0;
3368 }
3369 
3370 static int raid1_reshape(struct mddev *mddev)
3371 {
3372 	/* We need to:
3373 	 * 1/ resize the r1bio_pool
3374 	 * 2/ resize conf->mirrors
3375 	 *
3376 	 * We allocate a new r1bio_pool if we can.
3377 	 * Then raise a device barrier and wait until all IO stops.
3378 	 * Then resize conf->mirrors and swap in the new r1bio pool.
3379 	 *
3380 	 * At the same time, we "pack" the devices so that all the missing
3381 	 * devices have the higher raid_disk numbers.
3382 	 */
3383 	mempool_t *newpool, *oldpool;
3384 	size_t new_r1bio_size;
3385 	struct raid1_info *newmirrors;
3386 	struct r1conf *conf = mddev->private;
3387 	int cnt, raid_disks;
3388 	unsigned long flags;
3389 	int d, d2;
3390 
3391 	/* Cannot change chunk_size, layout, or level */
3392 	if (mddev->chunk_sectors != mddev->new_chunk_sectors ||
3393 	    mddev->layout != mddev->new_layout ||
3394 	    mddev->level != mddev->new_level) {
3395 		mddev->new_chunk_sectors = mddev->chunk_sectors;
3396 		mddev->new_layout = mddev->layout;
3397 		mddev->new_level = mddev->level;
3398 		return -EINVAL;
3399 	}
3400 
3401 	if (!mddev_is_clustered(mddev))
3402 		md_allow_write(mddev);
3403 
3404 	raid_disks = mddev->raid_disks + mddev->delta_disks;
3405 
3406 	if (raid_disks < conf->raid_disks) {
3407 		cnt=0;
3408 		for (d= 0; d < conf->raid_disks; d++)
3409 			if (conf->mirrors[d].rdev)
3410 				cnt++;
3411 		if (cnt > raid_disks)
3412 			return -EBUSY;
3413 	}
3414 
3415 	new_r1bio_size = offsetof(struct r1bio, bios[raid_disks * 2]);
3416 	newpool = mempool_create_kmalloc_pool(NR_RAID_BIOS, new_r1bio_size);
3417 	if (!newpool) {
3418 		return -ENOMEM;
3419 	}
3420 	newmirrors = kzalloc(array3_size(sizeof(struct raid1_info),
3421 					 raid_disks, 2),
3422 			     GFP_KERNEL);
3423 	if (!newmirrors) {
3424 		mempool_destroy(newpool);
3425 		return -ENOMEM;
3426 	}
3427 
3428 	freeze_array(conf, 0);
3429 
3430 	/* ok, everything is stopped */
3431 	oldpool = conf->r1bio_pool;
3432 	conf->r1bio_pool = newpool;
3433 
3434 	for (d = d2 = 0; d < conf->raid_disks; d++) {
3435 		struct md_rdev *rdev = conf->mirrors[d].rdev;
3436 		if (rdev && rdev->raid_disk != d2) {
3437 			sysfs_unlink_rdev(mddev, rdev);
3438 			rdev->raid_disk = d2;
3439 			sysfs_unlink_rdev(mddev, rdev);
3440 			if (sysfs_link_rdev(mddev, rdev))
3441 				pr_warn("md/raid1:%s: cannot register rd%d\n",
3442 					mdname(mddev), rdev->raid_disk);
3443 		}
3444 		if (rdev)
3445 			newmirrors[d2++].rdev = rdev;
3446 	}
3447 	kfree(conf->mirrors);
3448 	conf->mirrors = newmirrors;
3449 
3450 	spin_lock_irqsave(&conf->device_lock, flags);
3451 	mddev->degraded += (raid_disks - conf->raid_disks);
3452 	spin_unlock_irqrestore(&conf->device_lock, flags);
3453 	conf->raid_disks = mddev->raid_disks = raid_disks;
3454 	mddev->delta_disks = 0;
3455 
3456 	unfreeze_array(conf);
3457 
3458 	set_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
3459 	set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
3460 	md_wakeup_thread(mddev->thread);
3461 
3462 	mempool_destroy(oldpool);
3463 	return 0;
3464 }
3465 
3466 static void raid1_quiesce(struct mddev *mddev, int quiesce)
3467 {
3468 	struct r1conf *conf = mddev->private;
3469 
3470 	if (quiesce)
3471 		freeze_array(conf, 0);
3472 	else
3473 		unfreeze_array(conf);
3474 }
3475 
3476 static void *raid1_takeover(struct mddev *mddev)
3477 {
3478 	/* raid1 can take over:
3479 	 *  raid5 with 2 devices, any layout or chunk size
3480 	 */
3481 	if (mddev->level == 5 && mddev->raid_disks == 2) {
3482 		struct r1conf *conf;
3483 		mddev->new_level = 1;
3484 		mddev->new_layout = 0;
3485 		mddev->new_chunk_sectors = 0;
3486 		conf = setup_conf(mddev);
3487 		if (!IS_ERR(conf)) {
3488 			/* Array must appear to be quiesced */
3489 			conf->array_frozen = 1;
3490 			mddev_clear_unsupported_flags(mddev,
3491 				UNSUPPORTED_MDDEV_FLAGS);
3492 		}
3493 		return conf;
3494 	}
3495 	return ERR_PTR(-EINVAL);
3496 }
3497 
3498 static struct md_personality raid1_personality =
3499 {
3500 	.head = {
3501 		.type	= MD_PERSONALITY,
3502 		.id	= ID_RAID1,
3503 		.name	= "raid1",
3504 		.owner	= THIS_MODULE,
3505 	},
3506 
3507 	.make_request	= raid1_make_request,
3508 	.run		= raid1_run,
3509 	.free		= raid1_free,
3510 	.status		= raid1_status,
3511 	.error_handler	= raid1_error,
3512 	.hot_add_disk	= raid1_add_disk,
3513 	.hot_remove_disk= raid1_remove_disk,
3514 	.spare_active	= raid1_spare_active,
3515 	.sync_request	= raid1_sync_request,
3516 	.resize		= raid1_resize,
3517 	.size		= raid1_size,
3518 	.check_reshape	= raid1_reshape,
3519 	.quiesce	= raid1_quiesce,
3520 	.takeover	= raid1_takeover,
3521 };
3522 
3523 static int __init raid1_init(void)
3524 {
3525 	return register_md_submodule(&raid1_personality.head);
3526 }
3527 
3528 static void __exit raid1_exit(void)
3529 {
3530 	unregister_md_submodule(&raid1_personality.head);
3531 }
3532 
3533 module_init(raid1_init);
3534 module_exit(raid1_exit);
3535 MODULE_LICENSE("GPL");
3536 MODULE_DESCRIPTION("RAID1 (mirroring) personality for MD");
3537 MODULE_ALIAS("md-personality-3"); /* RAID1 */
3538 MODULE_ALIAS("md-raid1");
3539 MODULE_ALIAS("md-level-1");
3540