xref: /linux/drivers/md/raid1.c (revision b30288887c06772667b2b3133ac88d1b5bbcfa74)
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 	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 	       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 - conf->mirrors[disk].head_position);
818 
819 		/* Don't change to another disk for sequential reads */
820 		if (is_sequential(conf, disk, r1_bio)) {
821 			if (!should_choose_next(conf, disk))
822 				return disk;
823 
824 			/*
825 			 * Add 'pending' to avoid choosing this disk if
826 			 * there is other idle disk.
827 			 */
828 			pending++;
829 			/*
830 			 * If there is no other idle disk, this disk
831 			 * will be chosen.
832 			 */
833 			ctl.sequential_disk = disk;
834 		}
835 
836 		if (ctl.min_pending > pending) {
837 			ctl.min_pending = pending;
838 			ctl.min_pending_disk = disk;
839 		}
840 
841 		if (ctl.closest_dist > dist) {
842 			ctl.closest_dist = dist;
843 			ctl.closest_dist_disk = disk;
844 		}
845 	}
846 
847 	/*
848 	 * sequential IO size exceeds optimal iosize, however, there is no other
849 	 * idle disk, so choose the sequential disk.
850 	 */
851 	if (ctl.sequential_disk != -1 && ctl.min_pending != 0)
852 		return ctl.sequential_disk;
853 
854 	/*
855 	 * If all disks are rotational, choose the closest disk. If any disk is
856 	 * non-rotational, choose the disk with less pending request even the
857 	 * disk is rotational, which might/might not be optimal for raids with
858 	 * mixed ratation/non-rotational disks depending on workload.
859 	 */
860 	if (ctl.min_pending_disk != -1 &&
861 	    (READ_ONCE(conf->nonrot_disks) || ctl.min_pending == 0))
862 		return ctl.min_pending_disk;
863 	else
864 		return ctl.closest_dist_disk;
865 }
866 
867 /*
868  * This routine returns the disk from which the requested read should be done.
869  *
870  * 1) If resync is in progress, find the first usable disk and use it even if it
871  * has some bad blocks.
872  *
873  * 2) Now that there is no resync, loop through all disks and skipping slow
874  * disks and disks with bad blocks for now. Only pay attention to key disk
875  * choice.
876  *
877  * 3) If we've made it this far, now look for disks with bad blocks and choose
878  * the one with most number of sectors.
879  *
880  * 4) If we are all the way at the end, we have no choice but to use a disk even
881  * if it is write mostly.
882  *
883  * The rdev for the device selected will have nr_pending incremented.
884  */
885 static int read_balance(struct r1conf *conf, struct r1bio *r1_bio,
886 			int *max_sectors)
887 {
888 	int disk;
889 
890 	clear_bit(R1BIO_FailFast, &r1_bio->state);
891 
892 	if (raid1_should_read_first(conf->mddev, r1_bio->sector,
893 				    r1_bio->sectors))
894 		return choose_first_rdev(conf, r1_bio, max_sectors);
895 
896 	disk = choose_best_rdev(conf, r1_bio);
897 	if (disk >= 0) {
898 		*max_sectors = r1_bio->sectors;
899 		update_read_sectors(conf, disk, r1_bio->sector,
900 				    r1_bio->sectors);
901 		return disk;
902 	}
903 
904 	/*
905 	 * If we are here it means we didn't find a perfectly good disk so
906 	 * now spend a bit more time trying to find one with the most good
907 	 * sectors.
908 	 */
909 	disk = choose_bb_rdev(conf, r1_bio, max_sectors);
910 	if (disk >= 0)
911 		return disk;
912 
913 	return choose_slow_rdev(conf, r1_bio, max_sectors);
914 }
915 
916 static void wake_up_barrier(struct r1conf *conf)
917 {
918 	if (wq_has_sleeper(&conf->wait_barrier))
919 		wake_up(&conf->wait_barrier);
920 }
921 
922 static void flush_bio_list(struct r1conf *conf, struct bio *bio)
923 {
924 	/* flush any pending bitmap writes to disk before proceeding w/ I/O */
925 	raid1_prepare_flush_writes(conf->mddev);
926 	wake_up_barrier(conf);
927 
928 	while (bio) { /* submit pending writes */
929 		struct bio *next = bio->bi_next;
930 
931 		raid1_submit_write(bio);
932 		bio = next;
933 		cond_resched();
934 	}
935 }
936 
937 static void flush_pending_writes(struct r1conf *conf)
938 {
939 	/* Any writes that have been queued but are awaiting
940 	 * bitmap updates get flushed here.
941 	 */
942 	spin_lock_irq(&conf->device_lock);
943 
944 	if (conf->pending_bio_list.head) {
945 		struct blk_plug plug;
946 		struct bio *bio;
947 
948 		bio = bio_list_get(&conf->pending_bio_list);
949 		spin_unlock_irq(&conf->device_lock);
950 
951 		/*
952 		 * As this is called in a wait_event() loop (see freeze_array),
953 		 * current->state might be TASK_UNINTERRUPTIBLE which will
954 		 * cause a warning when we prepare to wait again.  As it is
955 		 * rare that this path is taken, it is perfectly safe to force
956 		 * us to go around the wait_event() loop again, so the warning
957 		 * is a false-positive.  Silence the warning by resetting
958 		 * thread state
959 		 */
960 		__set_current_state(TASK_RUNNING);
961 		blk_start_plug(&plug);
962 		flush_bio_list(conf, bio);
963 		blk_finish_plug(&plug);
964 	} else
965 		spin_unlock_irq(&conf->device_lock);
966 }
967 
968 /* Barriers....
969  * Sometimes we need to suspend IO while we do something else,
970  * either some resync/recovery, or reconfigure the array.
971  * To do this we raise a 'barrier'.
972  * The 'barrier' is a counter that can be raised multiple times
973  * to count how many activities are happening which preclude
974  * normal IO.
975  * We can only raise the barrier if there is no pending IO.
976  * i.e. if nr_pending == 0.
977  * We choose only to raise the barrier if no-one is waiting for the
978  * barrier to go down.  This means that as soon as an IO request
979  * is ready, no other operations which require a barrier will start
980  * until the IO request has had a chance.
981  *
982  * So: regular IO calls 'wait_barrier'.  When that returns there
983  *    is no backgroup IO happening,  It must arrange to call
984  *    allow_barrier when it has finished its IO.
985  * backgroup IO calls must call raise_barrier.  Once that returns
986  *    there is no normal IO happeing.  It must arrange to call
987  *    lower_barrier when the particular background IO completes.
988  *
989  * If resync/recovery is interrupted, returns -EINTR;
990  * Otherwise, returns 0.
991  */
992 static int raise_barrier(struct r1conf *conf, sector_t sector_nr)
993 {
994 	int idx = sector_to_idx(sector_nr);
995 
996 	spin_lock_irq(&conf->resync_lock);
997 
998 	/* Wait until no block IO is waiting */
999 	wait_event_lock_irq(conf->wait_barrier,
1000 			    !atomic_read(&conf->nr_waiting[idx]),
1001 			    conf->resync_lock);
1002 
1003 	/* block any new IO from starting */
1004 	atomic_inc(&conf->barrier[idx]);
1005 	/*
1006 	 * In raise_barrier() we firstly increase conf->barrier[idx] then
1007 	 * check conf->nr_pending[idx]. In _wait_barrier() we firstly
1008 	 * increase conf->nr_pending[idx] then check conf->barrier[idx].
1009 	 * A memory barrier here to make sure conf->nr_pending[idx] won't
1010 	 * be fetched before conf->barrier[idx] is increased. Otherwise
1011 	 * there will be a race between raise_barrier() and _wait_barrier().
1012 	 */
1013 	smp_mb__after_atomic();
1014 
1015 	/* For these conditions we must wait:
1016 	 * A: while the array is in frozen state
1017 	 * B: while conf->nr_pending[idx] is not 0, meaning regular I/O
1018 	 *    existing in corresponding I/O barrier bucket.
1019 	 * C: while conf->barrier[idx] >= RESYNC_DEPTH, meaning reaches
1020 	 *    max resync count which allowed on current I/O barrier bucket.
1021 	 */
1022 	wait_event_lock_irq(conf->wait_barrier,
1023 			    (!conf->array_frozen &&
1024 			     !atomic_read(&conf->nr_pending[idx]) &&
1025 			     atomic_read(&conf->barrier[idx]) < RESYNC_DEPTH) ||
1026 				test_bit(MD_RECOVERY_INTR, &conf->mddev->recovery),
1027 			    conf->resync_lock);
1028 
1029 	if (test_bit(MD_RECOVERY_INTR, &conf->mddev->recovery)) {
1030 		atomic_dec(&conf->barrier[idx]);
1031 		spin_unlock_irq(&conf->resync_lock);
1032 		wake_up(&conf->wait_barrier);
1033 		return -EINTR;
1034 	}
1035 
1036 	atomic_inc(&conf->nr_sync_pending);
1037 	spin_unlock_irq(&conf->resync_lock);
1038 
1039 	return 0;
1040 }
1041 
1042 static void lower_barrier(struct r1conf *conf, sector_t sector_nr)
1043 {
1044 	int idx = sector_to_idx(sector_nr);
1045 
1046 	BUG_ON(atomic_read(&conf->barrier[idx]) <= 0);
1047 
1048 	atomic_dec(&conf->barrier[idx]);
1049 	atomic_dec(&conf->nr_sync_pending);
1050 	wake_up(&conf->wait_barrier);
1051 }
1052 
1053 static bool _wait_barrier(struct r1conf *conf, int idx, bool nowait)
1054 {
1055 	bool ret = true;
1056 
1057 	/*
1058 	 * We need to increase conf->nr_pending[idx] very early here,
1059 	 * then raise_barrier() can be blocked when it waits for
1060 	 * conf->nr_pending[idx] to be 0. Then we can avoid holding
1061 	 * conf->resync_lock when there is no barrier raised in same
1062 	 * barrier unit bucket. Also if the array is frozen, I/O
1063 	 * should be blocked until array is unfrozen.
1064 	 */
1065 	atomic_inc(&conf->nr_pending[idx]);
1066 	/*
1067 	 * In _wait_barrier() we firstly increase conf->nr_pending[idx], then
1068 	 * check conf->barrier[idx]. In raise_barrier() we firstly increase
1069 	 * conf->barrier[idx], then check conf->nr_pending[idx]. A memory
1070 	 * barrier is necessary here to make sure conf->barrier[idx] won't be
1071 	 * fetched before conf->nr_pending[idx] is increased. Otherwise there
1072 	 * will be a race between _wait_barrier() and raise_barrier().
1073 	 */
1074 	smp_mb__after_atomic();
1075 
1076 	/*
1077 	 * Don't worry about checking two atomic_t variables at same time
1078 	 * here. If during we check conf->barrier[idx], the array is
1079 	 * frozen (conf->array_frozen is 1), and chonf->barrier[idx] is
1080 	 * 0, it is safe to return and make the I/O continue. Because the
1081 	 * array is frozen, all I/O returned here will eventually complete
1082 	 * or be queued, no race will happen. See code comment in
1083 	 * frozen_array().
1084 	 */
1085 	if (!READ_ONCE(conf->array_frozen) &&
1086 	    !atomic_read(&conf->barrier[idx]))
1087 		return ret;
1088 
1089 	/*
1090 	 * After holding conf->resync_lock, conf->nr_pending[idx]
1091 	 * should be decreased before waiting for barrier to drop.
1092 	 * Otherwise, we may encounter a race condition because
1093 	 * raise_barrer() might be waiting for conf->nr_pending[idx]
1094 	 * to be 0 at same time.
1095 	 */
1096 	spin_lock_irq(&conf->resync_lock);
1097 	atomic_inc(&conf->nr_waiting[idx]);
1098 	atomic_dec(&conf->nr_pending[idx]);
1099 	/*
1100 	 * In case freeze_array() is waiting for
1101 	 * get_unqueued_pending() == extra
1102 	 */
1103 	wake_up_barrier(conf);
1104 	/* Wait for the barrier in same barrier unit bucket to drop. */
1105 
1106 	/* Return false when nowait flag is set */
1107 	if (nowait) {
1108 		ret = false;
1109 	} else {
1110 		wait_event_lock_irq(conf->wait_barrier,
1111 				!conf->array_frozen &&
1112 				!atomic_read(&conf->barrier[idx]),
1113 				conf->resync_lock);
1114 		atomic_inc(&conf->nr_pending[idx]);
1115 	}
1116 
1117 	atomic_dec(&conf->nr_waiting[idx]);
1118 	spin_unlock_irq(&conf->resync_lock);
1119 	return ret;
1120 }
1121 
1122 static bool wait_read_barrier(struct r1conf *conf, sector_t sector_nr, bool nowait)
1123 {
1124 	int idx = sector_to_idx(sector_nr);
1125 	bool ret = true;
1126 
1127 	/*
1128 	 * Very similar to _wait_barrier(). The difference is, for read
1129 	 * I/O we don't need wait for sync I/O, but if the whole array
1130 	 * is frozen, the read I/O still has to wait until the array is
1131 	 * unfrozen. Since there is no ordering requirement with
1132 	 * conf->barrier[idx] here, memory barrier is unnecessary as well.
1133 	 */
1134 	atomic_inc(&conf->nr_pending[idx]);
1135 
1136 	if (!READ_ONCE(conf->array_frozen))
1137 		return ret;
1138 
1139 	spin_lock_irq(&conf->resync_lock);
1140 	atomic_inc(&conf->nr_waiting[idx]);
1141 	atomic_dec(&conf->nr_pending[idx]);
1142 	/*
1143 	 * In case freeze_array() is waiting for
1144 	 * get_unqueued_pending() == extra
1145 	 */
1146 	wake_up_barrier(conf);
1147 	/* Wait for array to be unfrozen */
1148 
1149 	/* Return false when nowait flag is set */
1150 	if (nowait) {
1151 		/* Return false when nowait flag is set */
1152 		ret = false;
1153 	} else {
1154 		wait_event_lock_irq(conf->wait_barrier,
1155 				!conf->array_frozen,
1156 				conf->resync_lock);
1157 		atomic_inc(&conf->nr_pending[idx]);
1158 	}
1159 
1160 	atomic_dec(&conf->nr_waiting[idx]);
1161 	spin_unlock_irq(&conf->resync_lock);
1162 	return ret;
1163 }
1164 
1165 static bool wait_barrier(struct r1conf *conf, sector_t sector_nr, bool nowait)
1166 {
1167 	int idx = sector_to_idx(sector_nr);
1168 
1169 	return _wait_barrier(conf, idx, nowait);
1170 }
1171 
1172 static void _allow_barrier(struct r1conf *conf, int idx)
1173 {
1174 	atomic_dec(&conf->nr_pending[idx]);
1175 	wake_up_barrier(conf);
1176 }
1177 
1178 static void allow_barrier(struct r1conf *conf, sector_t sector_nr)
1179 {
1180 	int idx = sector_to_idx(sector_nr);
1181 
1182 	_allow_barrier(conf, idx);
1183 }
1184 
1185 /* conf->resync_lock should be held */
1186 static int get_unqueued_pending(struct r1conf *conf)
1187 {
1188 	int idx, ret;
1189 
1190 	ret = atomic_read(&conf->nr_sync_pending);
1191 	for (idx = 0; idx < BARRIER_BUCKETS_NR; idx++)
1192 		ret += atomic_read(&conf->nr_pending[idx]) -
1193 			atomic_read(&conf->nr_queued[idx]);
1194 
1195 	return ret;
1196 }
1197 
1198 static void freeze_array(struct r1conf *conf, int extra)
1199 {
1200 	/* Stop sync I/O and normal I/O and wait for everything to
1201 	 * go quiet.
1202 	 * This is called in two situations:
1203 	 * 1) management command handlers (reshape, remove disk, quiesce).
1204 	 * 2) one normal I/O request failed.
1205 
1206 	 * After array_frozen is set to 1, new sync IO will be blocked at
1207 	 * raise_barrier(), and new normal I/O will blocked at _wait_barrier()
1208 	 * or wait_read_barrier(). The flying I/Os will either complete or be
1209 	 * queued. When everything goes quite, there are only queued I/Os left.
1210 
1211 	 * Every flying I/O contributes to a conf->nr_pending[idx], idx is the
1212 	 * barrier bucket index which this I/O request hits. When all sync and
1213 	 * normal I/O are queued, sum of all conf->nr_pending[] will match sum
1214 	 * of all conf->nr_queued[]. But normal I/O failure is an exception,
1215 	 * in handle_read_error(), we may call freeze_array() before trying to
1216 	 * fix the read error. In this case, the error read I/O is not queued,
1217 	 * so get_unqueued_pending() == 1.
1218 	 *
1219 	 * Therefore before this function returns, we need to wait until
1220 	 * get_unqueued_pendings(conf) gets equal to extra. For
1221 	 * normal I/O context, extra is 1, in rested situations extra is 0.
1222 	 */
1223 	spin_lock_irq(&conf->resync_lock);
1224 	conf->array_frozen = 1;
1225 	mddev_add_trace_msg(conf->mddev, "raid1 wait freeze");
1226 	wait_event_lock_irq_cmd(
1227 		conf->wait_barrier,
1228 		get_unqueued_pending(conf) == extra,
1229 		conf->resync_lock,
1230 		flush_pending_writes(conf));
1231 	spin_unlock_irq(&conf->resync_lock);
1232 }
1233 static void unfreeze_array(struct r1conf *conf)
1234 {
1235 	/* reverse the effect of the freeze */
1236 	spin_lock_irq(&conf->resync_lock);
1237 	conf->array_frozen = 0;
1238 	spin_unlock_irq(&conf->resync_lock);
1239 	wake_up(&conf->wait_barrier);
1240 }
1241 
1242 static void alloc_behind_master_bio(struct r1bio *r1_bio,
1243 					   struct bio *bio)
1244 {
1245 	int size = bio->bi_iter.bi_size;
1246 	unsigned vcnt = (size + PAGE_SIZE - 1) >> PAGE_SHIFT;
1247 	int i = 0;
1248 	struct bio *behind_bio = NULL;
1249 
1250 	behind_bio = bio_alloc_bioset(NULL, vcnt, bio->bi_opf, GFP_NOIO,
1251 				      &r1_bio->mddev->bio_set);
1252 
1253 	/* discard op, we don't support writezero/writesame yet */
1254 	if (!bio_has_data(bio)) {
1255 		behind_bio->bi_iter.bi_size = size;
1256 		goto skip_copy;
1257 	}
1258 
1259 	while (i < vcnt && size) {
1260 		struct page *page;
1261 		int len = min_t(int, PAGE_SIZE, size);
1262 
1263 		page = alloc_page(GFP_NOIO);
1264 		if (unlikely(!page))
1265 			goto free_pages;
1266 
1267 		if (!bio_add_page(behind_bio, page, len, 0)) {
1268 			put_page(page);
1269 			goto free_pages;
1270 		}
1271 
1272 		size -= len;
1273 		i++;
1274 	}
1275 
1276 	bio_copy_data(behind_bio, bio);
1277 skip_copy:
1278 	r1_bio->behind_master_bio = behind_bio;
1279 	set_bit(R1BIO_BehindIO, &r1_bio->state);
1280 
1281 	return;
1282 
1283 free_pages:
1284 	pr_debug("%dB behind alloc failed, doing sync I/O\n",
1285 		 bio->bi_iter.bi_size);
1286 	bio_free_pages(behind_bio);
1287 	bio_put(behind_bio);
1288 }
1289 
1290 static void raid1_unplug(struct blk_plug_cb *cb, bool from_schedule)
1291 {
1292 	struct raid1_plug_cb *plug = container_of(cb, struct raid1_plug_cb,
1293 						  cb);
1294 	struct mddev *mddev = plug->cb.data;
1295 	struct r1conf *conf = mddev->private;
1296 	struct bio *bio;
1297 
1298 	if (from_schedule) {
1299 		spin_lock_irq(&conf->device_lock);
1300 		bio_list_merge(&conf->pending_bio_list, &plug->pending);
1301 		spin_unlock_irq(&conf->device_lock);
1302 		wake_up_barrier(conf);
1303 		md_wakeup_thread(mddev->thread);
1304 		kfree(plug);
1305 		return;
1306 	}
1307 
1308 	/* we aren't scheduling, so we can do the write-out directly. */
1309 	bio = bio_list_get(&plug->pending);
1310 	flush_bio_list(conf, bio);
1311 	kfree(plug);
1312 }
1313 
1314 static void init_r1bio(struct r1bio *r1_bio, struct mddev *mddev, struct bio *bio)
1315 {
1316 	r1_bio->master_bio = bio;
1317 	r1_bio->sectors = bio_sectors(bio);
1318 	r1_bio->state = 0;
1319 	r1_bio->mddev = mddev;
1320 	r1_bio->sector = bio->bi_iter.bi_sector;
1321 }
1322 
1323 static inline struct r1bio *
1324 alloc_r1bio(struct mddev *mddev, struct bio *bio)
1325 {
1326 	struct r1conf *conf = mddev->private;
1327 	struct r1bio *r1_bio;
1328 
1329 	r1_bio = mempool_alloc(conf->r1bio_pool, GFP_NOIO);
1330 	memset(r1_bio, 0, offsetof(struct r1bio, bios[conf->raid_disks * 2]));
1331 	init_r1bio(r1_bio, mddev, bio);
1332 	return r1_bio;
1333 }
1334 
1335 static void raid1_read_request(struct mddev *mddev, struct bio *bio,
1336 			       int max_read_sectors, struct r1bio *r1_bio)
1337 {
1338 	struct r1conf *conf = mddev->private;
1339 	struct raid1_info *mirror;
1340 	struct bio *read_bio;
1341 	int max_sectors;
1342 	int rdisk;
1343 	bool r1bio_existed = !!r1_bio;
1344 
1345 	/*
1346 	 * An md cloned bio indicates we are in the error path.
1347 	 * This is more reliable than checking r1_bio, which might
1348 	 * be NULL even in the error path if a failed bio was split.
1349 	 */
1350 	bool err_path = md_cloned_bio(mddev, bio);
1351 
1352 	/*
1353 	 * If we are in the error path, we are blocking the raid1d
1354 	 * thread so there is a tiny risk of deadlock.  So ask for
1355 	 * emergency memory if needed.
1356 	 */
1357 	gfp_t gfp = err_path ? (GFP_NOIO | __GFP_HIGH) : GFP_NOIO;
1358 
1359 	/*
1360 	 * Still need barrier for READ in case that whole
1361 	 * array is frozen.
1362 	 */
1363 	if (!wait_read_barrier(conf, bio->bi_iter.bi_sector,
1364 				bio->bi_opf & REQ_NOWAIT)) {
1365 		bio_wouldblock_error(bio);
1366 		return;
1367 	}
1368 
1369 	if (!r1_bio)
1370 		r1_bio = alloc_r1bio(mddev, bio);
1371 	else
1372 		init_r1bio(r1_bio, mddev, bio);
1373 	r1_bio->sectors = max_read_sectors;
1374 
1375 	/*
1376 	 * make_request() can abort the operation when read-ahead is being
1377 	 * used and no empty request is available.
1378 	 */
1379 	rdisk = read_balance(conf, r1_bio, &max_sectors);
1380 	if (rdisk < 0) {
1381 		/* couldn't find anywhere to read from */
1382 		if (r1bio_existed)
1383 			pr_crit_ratelimited("md/raid1:%s: %pg: unrecoverable I/O read error for block %llu\n",
1384 					    mdname(mddev),
1385 					    conf->mirrors[r1_bio->read_disk].rdev->bdev,
1386 					    r1_bio->sector);
1387 		raid_end_bio_io(r1_bio);
1388 		return;
1389 	}
1390 	mirror = conf->mirrors + rdisk;
1391 
1392 	if (r1bio_existed)
1393 		pr_info_ratelimited("md/raid1:%s: redirecting sector %llu to other mirror: %pg\n",
1394 				    mdname(mddev),
1395 				    (unsigned long long)r1_bio->sector,
1396 				    mirror->rdev->bdev);
1397 
1398 	if (test_bit(WriteMostly, &mirror->rdev->flags) &&
1399 	    md_bitmap_enabled(mddev, false)) {
1400 		/*
1401 		 * Reading from a write-mostly device must take care not to
1402 		 * over-take any writes that are 'behind'
1403 		 */
1404 		mddev_add_trace_msg(mddev, "raid1 wait behind writes");
1405 		mddev->bitmap_ops->wait_behind_writes(mddev);
1406 	}
1407 
1408 	if (max_sectors < bio_sectors(bio)) {
1409 		bio = bio_submit_split_bioset(bio, max_sectors,
1410 					      &conf->bio_split);
1411 		if (!bio) {
1412 			set_bit(R1BIO_Returned, &r1_bio->state);
1413 			goto err_handle;
1414 		}
1415 
1416 		r1_bio->master_bio = bio;
1417 		r1_bio->sectors = max_sectors;
1418 	}
1419 
1420 	r1_bio->read_disk = rdisk;
1421 	if (likely(!md_cloned_bio(mddev, bio))) {
1422 		md_account_bio(mddev, &bio);
1423 		r1_bio->master_bio = bio;
1424 	}
1425 	read_bio = bio_alloc_clone(mirror->rdev->bdev, bio, gfp,
1426 				   &mddev->bio_set);
1427 	read_bio->bi_opf &= ~REQ_NOWAIT;
1428 	r1_bio->bios[rdisk] = read_bio;
1429 
1430 	read_bio->bi_iter.bi_sector = r1_bio->sector +
1431 		mirror->rdev->data_offset;
1432 	read_bio->bi_end_io = raid1_end_read_request;
1433 	if (test_bit(FailFast, &mirror->rdev->flags) &&
1434 	    test_bit(R1BIO_FailFast, &r1_bio->state))
1435 	        read_bio->bi_opf |= MD_FAILFAST;
1436 	read_bio->bi_private = r1_bio;
1437 	mddev_trace_remap(mddev, read_bio, r1_bio->sector);
1438 	submit_bio_noacct(read_bio);
1439 	return;
1440 
1441 err_handle:
1442 	atomic_dec(&mirror->rdev->nr_pending);
1443 	raid_end_bio_io(r1_bio);
1444 }
1445 
1446 static bool wait_blocked_rdev(struct mddev *mddev, struct bio *bio)
1447 {
1448 	struct r1conf *conf = mddev->private;
1449 	int disks = conf->raid_disks * 2;
1450 	int i;
1451 
1452 retry:
1453 	for (i = 0; i < disks; i++) {
1454 		struct md_rdev *rdev = conf->mirrors[i].rdev;
1455 
1456 		if (!rdev)
1457 			continue;
1458 
1459 		/* don't write here until the bad block is acknowledged */
1460 		if (test_bit(WriteErrorSeen, &rdev->flags) &&
1461 		    rdev_has_badblock(rdev, bio->bi_iter.bi_sector,
1462 				      bio_sectors(bio)) < 0)
1463 			set_bit(BlockedBadBlocks, &rdev->flags);
1464 
1465 		if (rdev_blocked(rdev)) {
1466 			if (bio->bi_opf & REQ_NOWAIT)
1467 				return false;
1468 
1469 			mddev_add_trace_msg(rdev->mddev, "raid1 wait rdev %d blocked",
1470 					    rdev->raid_disk);
1471 			atomic_inc(&rdev->nr_pending);
1472 			md_wait_for_blocked_rdev(rdev, rdev->mddev);
1473 			goto retry;
1474 		}
1475 	}
1476 
1477 	return true;
1478 }
1479 
1480 static void raid1_start_write_behind(struct mddev *mddev, struct r1bio *r1_bio,
1481 				     struct bio *bio)
1482 {
1483 	unsigned long max_write_behind = mddev->bitmap_info.max_write_behind;
1484 	struct md_bitmap_stats stats;
1485 	int err;
1486 
1487 	/* behind write rely on bitmap, see bitmap_operations */
1488 	if (!md_bitmap_enabled(mddev, false))
1489 		return;
1490 
1491 	err = mddev->bitmap_ops->get_stats(mddev->bitmap, &stats);
1492 	if (err)
1493 		return;
1494 
1495 	/* Don't do behind IO if reader is waiting, or there are too many. */
1496 	if (!stats.behind_wait && stats.behind_writes < max_write_behind)
1497 		alloc_behind_master_bio(r1_bio, bio);
1498 
1499 	if (test_bit(R1BIO_BehindIO, &r1_bio->state))
1500 		mddev->bitmap_ops->start_behind_write(mddev);
1501 
1502 }
1503 
1504 static void raid1_write_request(struct mddev *mddev, struct bio *bio,
1505 				int max_write_sectors)
1506 {
1507 	struct r1conf *conf = mddev->private;
1508 	struct r1bio *r1_bio;
1509 	int i, disks, k;
1510 	unsigned long flags;
1511 	int first_clone;
1512 	int max_sectors;
1513 	bool write_behind = false;
1514 	bool is_discard = (bio_op(bio) == REQ_OP_DISCARD);
1515 
1516 	if (mddev_is_clustered(mddev) &&
1517 	    mddev->cluster_ops->area_resyncing(mddev, WRITE,
1518 		     bio->bi_iter.bi_sector, bio_end_sector(bio))) {
1519 
1520 		if (bio->bi_opf & REQ_NOWAIT) {
1521 			bio_wouldblock_error(bio);
1522 			return;
1523 		}
1524 		wait_event_idle(conf->wait_barrier,
1525 				!mddev->cluster_ops->area_resyncing(mddev, WRITE,
1526 								    bio->bi_iter.bi_sector,
1527 								    bio_end_sector(bio)));
1528 	}
1529 
1530 	/*
1531 	 * Register the new request and wait if the reconstruction
1532 	 * thread has put up a bar for new requests.
1533 	 * Continue immediately if no resync is active currently.
1534 	 */
1535 	if (!wait_barrier(conf, bio->bi_iter.bi_sector,
1536 				bio->bi_opf & REQ_NOWAIT)) {
1537 		bio_wouldblock_error(bio);
1538 		return;
1539 	}
1540 
1541 	if (!wait_blocked_rdev(mddev, bio)) {
1542 		bio_wouldblock_error(bio);
1543 		return;
1544 	}
1545 
1546 	r1_bio = alloc_r1bio(mddev, bio);
1547 	r1_bio->sectors = max_write_sectors;
1548 
1549 	/* first select target devices under rcu_lock and
1550 	 * inc refcount on their rdev.  Record them by setting
1551 	 * bios[x] to bio
1552 	 * If there are known/acknowledged bad blocks on any device on
1553 	 * which we have seen a write error, we want to avoid writing those
1554 	 * blocks.
1555 	 * This potentially requires several writes to write around
1556 	 * the bad blocks.  Each set of writes gets it's own r1bio
1557 	 * with a set of bios attached.
1558 	 */
1559 
1560 	disks = conf->raid_disks * 2;
1561 	max_sectors = r1_bio->sectors;
1562 	for (i = 0;  i < disks; i++) {
1563 		struct md_rdev *rdev = conf->mirrors[i].rdev;
1564 
1565 		/*
1566 		 * The write-behind io is only attempted on drives marked as
1567 		 * write-mostly, which means we could allocate write behind
1568 		 * bio later.
1569 		 */
1570 		if (!is_discard && rdev && test_bit(WriteMostly, &rdev->flags))
1571 			write_behind = true;
1572 
1573 		r1_bio->bios[i] = NULL;
1574 		if (!rdev || test_bit(Faulty, &rdev->flags))
1575 			continue;
1576 
1577 		atomic_inc(&rdev->nr_pending);
1578 		if (test_bit(WriteErrorSeen, &rdev->flags)) {
1579 			sector_t first_bad;
1580 			sector_t bad_sectors;
1581 			int is_bad;
1582 
1583 			is_bad = is_badblock(rdev, r1_bio->sector, max_sectors,
1584 					     &first_bad, &bad_sectors);
1585 			if (is_bad && first_bad <= r1_bio->sector) {
1586 				/* Cannot write here at all */
1587 				bad_sectors -= (r1_bio->sector - first_bad);
1588 				if (bad_sectors < max_sectors)
1589 					/* mustn't write more than bad_sectors
1590 					 * to other devices yet
1591 					 */
1592 					max_sectors = bad_sectors;
1593 				rdev_dec_pending(rdev, mddev);
1594 				continue;
1595 			}
1596 			if (is_bad) {
1597 				int good_sectors;
1598 
1599 				/*
1600 				 * We cannot atomically write this, so just
1601 				 * error in that case. It could be possible to
1602 				 * atomically write other mirrors, but the
1603 				 * complexity of supporting that is not worth
1604 				 * the benefit.
1605 				 */
1606 				if (bio->bi_opf & REQ_ATOMIC) {
1607 					rdev_dec_pending(rdev, mddev);
1608 					goto err_handle;
1609 				}
1610 
1611 				good_sectors = first_bad - r1_bio->sector;
1612 				if (good_sectors < max_sectors)
1613 					max_sectors = good_sectors;
1614 			}
1615 		}
1616 		r1_bio->bios[i] = bio;
1617 	}
1618 
1619 	/*
1620 	 * When using a bitmap, we may call alloc_behind_master_bio below.
1621 	 * alloc_behind_master_bio allocates a copy of the data payload a page
1622 	 * at a time and thus needs a new bio that can fit the whole payload
1623 	 * this bio in page sized chunks.
1624 	 */
1625 	if (write_behind && mddev->bitmap)
1626 		max_sectors = min_t(int, max_sectors,
1627 				    BIO_MAX_VECS * (PAGE_SIZE >> 9));
1628 	if (max_sectors < bio_sectors(bio)) {
1629 		bio = bio_submit_split_bioset(bio, max_sectors,
1630 					      &conf->bio_split);
1631 		if (!bio) {
1632 			set_bit(R1BIO_Returned, &r1_bio->state);
1633 			goto err_handle;
1634 		}
1635 
1636 		r1_bio->master_bio = bio;
1637 		r1_bio->sectors = max_sectors;
1638 	}
1639 
1640 	md_account_bio(mddev, &bio);
1641 	r1_bio->master_bio = bio;
1642 	atomic_set(&r1_bio->remaining, 1);
1643 	atomic_set(&r1_bio->behind_remaining, 0);
1644 
1645 	first_clone = 1;
1646 
1647 	for (i = 0; i < disks; i++) {
1648 		struct bio *mbio = NULL;
1649 		struct md_rdev *rdev = conf->mirrors[i].rdev;
1650 		if (!r1_bio->bios[i])
1651 			continue;
1652 
1653 		if (first_clone) {
1654 			if (write_behind)
1655 				raid1_start_write_behind(mddev, r1_bio, bio);
1656 			first_clone = 0;
1657 		}
1658 
1659 		if (r1_bio->behind_master_bio) {
1660 			mbio = bio_alloc_clone(rdev->bdev,
1661 					       r1_bio->behind_master_bio,
1662 					       GFP_NOIO, &mddev->bio_set);
1663 			if (test_bit(CollisionCheck, &rdev->flags))
1664 				wait_for_serialization(rdev, r1_bio);
1665 			if (test_bit(WriteMostly, &rdev->flags))
1666 				atomic_inc(&r1_bio->behind_remaining);
1667 		} else {
1668 			mbio = bio_alloc_clone(rdev->bdev, bio, GFP_NOIO,
1669 					       &mddev->bio_set);
1670 
1671 			if (test_bit(MD_SERIALIZE_POLICY, &mddev->flags))
1672 				wait_for_serialization(rdev, r1_bio);
1673 		}
1674 
1675 		mbio->bi_opf &= ~REQ_NOWAIT;
1676 		r1_bio->bios[i] = mbio;
1677 
1678 		mbio->bi_iter.bi_sector	= (r1_bio->sector + rdev->data_offset);
1679 		mbio->bi_end_io	= raid1_end_write_request;
1680 		if (test_bit(FailFast, &rdev->flags) &&
1681 		    !test_bit(WriteMostly, &rdev->flags) &&
1682 		    conf->raid_disks - mddev->degraded > 1)
1683 			mbio->bi_opf |= MD_FAILFAST;
1684 		mbio->bi_private = r1_bio;
1685 
1686 		atomic_inc(&r1_bio->remaining);
1687 		mddev_trace_remap(mddev, mbio, r1_bio->sector);
1688 		/* flush_pending_writes() needs access to the rdev so...*/
1689 		mbio->bi_bdev = (void *)rdev;
1690 		if (!raid1_add_bio_to_plug(mddev, mbio, raid1_unplug, disks)) {
1691 			spin_lock_irqsave(&conf->device_lock, flags);
1692 			bio_list_add(&conf->pending_bio_list, mbio);
1693 			spin_unlock_irqrestore(&conf->device_lock, flags);
1694 			md_wakeup_thread(mddev->thread);
1695 		}
1696 	}
1697 
1698 	r1_bio_write_done(r1_bio);
1699 
1700 	/* In case raid1d snuck in to freeze_array */
1701 	wake_up_barrier(conf);
1702 	return;
1703 err_handle:
1704 	for (k = 0; k < i; k++) {
1705 		if (r1_bio->bios[k]) {
1706 			rdev_dec_pending(conf->mirrors[k].rdev, mddev);
1707 			r1_bio->bios[k] = NULL;
1708 		}
1709 	}
1710 
1711 	raid_end_bio_io(r1_bio);
1712 }
1713 
1714 static bool raid1_make_request(struct mddev *mddev, struct bio *bio)
1715 {
1716 	sector_t sectors;
1717 
1718 	if (unlikely(bio->bi_opf & REQ_PREFLUSH)
1719 	    && md_flush_request(mddev, bio))
1720 		return true;
1721 
1722 	/*
1723 	 * There is a limit to the maximum size, but
1724 	 * the read/write handler might find a lower limit
1725 	 * due to bad blocks.  To avoid multiple splits,
1726 	 * we pass the maximum number of sectors down
1727 	 * and let the lower level perform the split.
1728 	 */
1729 	sectors = align_to_barrier_unit_end(
1730 		bio->bi_iter.bi_sector, bio_sectors(bio));
1731 
1732 	if (bio_data_dir(bio) == READ)
1733 		raid1_read_request(mddev, bio, sectors, NULL);
1734 	else {
1735 		md_write_start(mddev,bio);
1736 		raid1_write_request(mddev, bio, sectors);
1737 	}
1738 	return true;
1739 }
1740 
1741 static void raid1_status(struct seq_file *seq, struct mddev *mddev)
1742 {
1743 	struct r1conf *conf = mddev->private;
1744 	int i;
1745 
1746 	lockdep_assert_held(&mddev->lock);
1747 
1748 	seq_printf(seq, " [%d/%d] [", conf->raid_disks,
1749 		   conf->raid_disks - mddev->degraded);
1750 	for (i = 0; i < conf->raid_disks; i++) {
1751 		struct md_rdev *rdev = READ_ONCE(conf->mirrors[i].rdev);
1752 
1753 		seq_printf(seq, "%s",
1754 			   rdev && test_bit(In_sync, &rdev->flags) ? "U" : "_");
1755 	}
1756 	seq_printf(seq, "]");
1757 }
1758 
1759 /**
1760  * raid1_error() - RAID1 error handler.
1761  * @mddev: affected md device.
1762  * @rdev: member device to fail.
1763  *
1764  * The routine acknowledges &rdev failure and determines new @mddev state.
1765  * If it failed, then:
1766  *	- &MD_BROKEN flag is set in &mddev->flags.
1767  *	- recovery is disabled.
1768  * Otherwise, it must be degraded:
1769  *	- recovery is interrupted.
1770  *	- &mddev->degraded is bumped.
1771  *
1772  * @rdev is marked as &Faulty excluding case when array is failed and
1773  * MD_FAILLAST_DEV is not set.
1774  */
1775 static void raid1_error(struct mddev *mddev, struct md_rdev *rdev)
1776 {
1777 	struct r1conf *conf = mddev->private;
1778 	unsigned long flags;
1779 
1780 	spin_lock_irqsave(&conf->device_lock, flags);
1781 
1782 	if (test_bit(In_sync, &rdev->flags) &&
1783 	    (conf->raid_disks - mddev->degraded) == 1) {
1784 		set_bit(MD_BROKEN, &mddev->flags);
1785 
1786 		if (!test_bit(MD_FAILLAST_DEV, &mddev->flags)) {
1787 			spin_unlock_irqrestore(&conf->device_lock, flags);
1788 			return;
1789 		}
1790 	}
1791 	set_bit(Blocked, &rdev->flags);
1792 	if (test_and_clear_bit(In_sync, &rdev->flags))
1793 		mddev->degraded++;
1794 	set_bit(Faulty, &rdev->flags);
1795 	spin_unlock_irqrestore(&conf->device_lock, flags);
1796 	/*
1797 	 * if recovery is running, make sure it aborts.
1798 	 */
1799 	set_bit(MD_RECOVERY_INTR, &mddev->recovery);
1800 	set_mask_bits(&mddev->sb_flags, 0,
1801 		      BIT(MD_SB_CHANGE_DEVS) | BIT(MD_SB_CHANGE_PENDING));
1802 	pr_crit("md/raid1:%s: Disk failure on %pg, disabling device.\n"
1803 		"md/raid1:%s: Operation continuing on %d devices.\n",
1804 		mdname(mddev), rdev->bdev,
1805 		mdname(mddev), conf->raid_disks - mddev->degraded);
1806 }
1807 
1808 static void print_conf(struct r1conf *conf)
1809 {
1810 	int i;
1811 
1812 	pr_debug("RAID1 conf printout:\n");
1813 	if (!conf) {
1814 		pr_debug("(!conf)\n");
1815 		return;
1816 	}
1817 	pr_debug(" --- wd:%d rd:%d\n", conf->raid_disks - conf->mddev->degraded,
1818 		 conf->raid_disks);
1819 
1820 	lockdep_assert_held(&conf->mddev->reconfig_mutex);
1821 	for (i = 0; i < conf->raid_disks; i++) {
1822 		struct md_rdev *rdev = conf->mirrors[i].rdev;
1823 		if (rdev)
1824 			pr_debug(" disk %d, wo:%d, o:%d, dev:%pg\n",
1825 				 i, !test_bit(In_sync, &rdev->flags),
1826 				 !test_bit(Faulty, &rdev->flags),
1827 				 rdev->bdev);
1828 	}
1829 }
1830 
1831 static void close_sync(struct r1conf *conf)
1832 {
1833 	int idx;
1834 
1835 	for (idx = 0; idx < BARRIER_BUCKETS_NR; idx++) {
1836 		_wait_barrier(conf, idx, false);
1837 		_allow_barrier(conf, idx);
1838 	}
1839 
1840 	mempool_exit(&conf->r1buf_pool);
1841 }
1842 
1843 static int raid1_spare_active(struct mddev *mddev)
1844 {
1845 	int i;
1846 	struct r1conf *conf = mddev->private;
1847 	int count = 0;
1848 	unsigned long flags;
1849 
1850 	/*
1851 	 * Find all failed disks within the RAID1 configuration
1852 	 * and mark them readable.
1853 	 * Called under mddev lock, so rcu protection not needed.
1854 	 * device_lock used to avoid races with raid1_end_read_request
1855 	 * which expects 'In_sync' flags and ->degraded to be consistent.
1856 	 */
1857 	spin_lock_irqsave(&conf->device_lock, flags);
1858 	for (i = 0; i < conf->raid_disks; i++) {
1859 		struct md_rdev *rdev = conf->mirrors[i].rdev;
1860 		struct md_rdev *repl = conf->mirrors[conf->raid_disks + i].rdev;
1861 		if (repl
1862 		    && !test_bit(Candidate, &repl->flags)
1863 		    && repl->recovery_offset == MaxSector
1864 		    && !test_bit(Faulty, &repl->flags)
1865 		    && !test_and_set_bit(In_sync, &repl->flags)) {
1866 			/* replacement has just become active */
1867 			if (!rdev ||
1868 			    !test_and_clear_bit(In_sync, &rdev->flags))
1869 				count++;
1870 			if (rdev) {
1871 				/* Replaced device not technically
1872 				 * faulty, but we need to be sure
1873 				 * it gets removed and never re-added
1874 				 */
1875 				set_bit(Faulty, &rdev->flags);
1876 				sysfs_notify_dirent_safe(
1877 					rdev->sysfs_state);
1878 			}
1879 		}
1880 		if (rdev
1881 		    && rdev->recovery_offset == MaxSector
1882 		    && !test_bit(Faulty, &rdev->flags)
1883 		    && !test_and_set_bit(In_sync, &rdev->flags)) {
1884 			count++;
1885 			sysfs_notify_dirent_safe(rdev->sysfs_state);
1886 		}
1887 	}
1888 	mddev->degraded -= count;
1889 	spin_unlock_irqrestore(&conf->device_lock, flags);
1890 
1891 	print_conf(conf);
1892 	return count;
1893 }
1894 
1895 static bool raid1_add_conf(struct r1conf *conf, struct md_rdev *rdev, int disk,
1896 			   bool replacement)
1897 {
1898 	struct raid1_info *info = conf->mirrors + disk;
1899 
1900 	if (replacement)
1901 		info += conf->raid_disks;
1902 
1903 	if (info->rdev)
1904 		return false;
1905 
1906 	if (!bdev_rot(rdev->bdev)) {
1907 		set_bit(Nonrot, &rdev->flags);
1908 		WRITE_ONCE(conf->nonrot_disks, conf->nonrot_disks + 1);
1909 	}
1910 
1911 	rdev->raid_disk = disk;
1912 	info->head_position = 0;
1913 	info->seq_start = MaxSector;
1914 	WRITE_ONCE(info->rdev, rdev);
1915 
1916 	return true;
1917 }
1918 
1919 static bool raid1_remove_conf(struct r1conf *conf, int disk)
1920 {
1921 	struct raid1_info *info = conf->mirrors + disk;
1922 	struct md_rdev *rdev = info->rdev;
1923 
1924 	if (!rdev || test_bit(In_sync, &rdev->flags) ||
1925 	    atomic_read(&rdev->nr_pending))
1926 		return false;
1927 
1928 	/* Only remove non-faulty devices if recovery is not possible. */
1929 	if (!test_bit(Faulty, &rdev->flags) &&
1930 	    rdev->mddev->degraded < conf->raid_disks)
1931 		return false;
1932 
1933 	if (test_and_clear_bit(Nonrot, &rdev->flags))
1934 		WRITE_ONCE(conf->nonrot_disks, conf->nonrot_disks - 1);
1935 
1936 	WRITE_ONCE(info->rdev, NULL);
1937 	return true;
1938 }
1939 
1940 static int raid1_add_disk(struct mddev *mddev, struct md_rdev *rdev)
1941 {
1942 	struct r1conf *conf = mddev->private;
1943 	int err = -EEXIST;
1944 	int mirror = 0, repl_slot = -1;
1945 	struct raid1_info *p;
1946 	int first = 0;
1947 	int last = conf->raid_disks - 1;
1948 
1949 	if (rdev->raid_disk >= 0)
1950 		first = last = rdev->raid_disk;
1951 
1952 	/*
1953 	 * find the disk ... but prefer rdev->saved_raid_disk
1954 	 * if possible.
1955 	 */
1956 	if (rdev->saved_raid_disk >= 0 &&
1957 	    rdev->saved_raid_disk >= first &&
1958 	    rdev->saved_raid_disk < conf->raid_disks &&
1959 	    conf->mirrors[rdev->saved_raid_disk].rdev == NULL)
1960 		first = last = rdev->saved_raid_disk;
1961 
1962 	for (mirror = first; mirror <= last; mirror++) {
1963 		p = conf->mirrors + mirror;
1964 		if (!p->rdev) {
1965 			err = mddev_stack_new_rdev(mddev, rdev);
1966 			if (err)
1967 				return err;
1968 
1969 			raid1_add_conf(conf, rdev, mirror, false);
1970 			/* As all devices are equivalent, we don't need a full recovery
1971 			 * if this was recently any drive of the array
1972 			 */
1973 			if (rdev->saved_raid_disk < 0)
1974 				conf->fullsync = 1;
1975 			break;
1976 		}
1977 		if (test_bit(WantReplacement, &p->rdev->flags) &&
1978 		    p[conf->raid_disks].rdev == NULL && repl_slot < 0)
1979 			repl_slot = mirror;
1980 	}
1981 
1982 	if (err && repl_slot >= 0) {
1983 		/* Add this device as a replacement */
1984 		clear_bit(In_sync, &rdev->flags);
1985 		set_bit(Replacement, &rdev->flags);
1986 		raid1_add_conf(conf, rdev, repl_slot, true);
1987 		err = 0;
1988 		conf->fullsync = 1;
1989 	}
1990 
1991 	print_conf(conf);
1992 	return err;
1993 }
1994 
1995 static int raid1_remove_disk(struct mddev *mddev, struct md_rdev *rdev)
1996 {
1997 	struct r1conf *conf = mddev->private;
1998 	int err = 0;
1999 	int number = rdev->raid_disk;
2000 	struct raid1_info *p = conf->mirrors + number;
2001 
2002 	if (unlikely(number >= conf->raid_disks))
2003 		goto abort;
2004 
2005 	if (rdev != p->rdev) {
2006 		number += conf->raid_disks;
2007 		p = conf->mirrors + number;
2008 	}
2009 
2010 	print_conf(conf);
2011 	if (rdev == p->rdev) {
2012 		if (!raid1_remove_conf(conf, number)) {
2013 			err = -EBUSY;
2014 			goto abort;
2015 		}
2016 
2017 		if (number < conf->raid_disks &&
2018 		    conf->mirrors[conf->raid_disks + number].rdev) {
2019 			/* We just removed a device that is being replaced.
2020 			 * Move down the replacement.  We drain all IO before
2021 			 * doing this to avoid confusion.
2022 			 */
2023 			struct md_rdev *repl =
2024 				conf->mirrors[conf->raid_disks + number].rdev;
2025 			freeze_array(conf, 0);
2026 			if (atomic_read(&repl->nr_pending)) {
2027 				/* It means that some queued IO of retry_list
2028 				 * hold repl. Thus, we cannot set replacement
2029 				 * as NULL, avoiding rdev NULL pointer
2030 				 * dereference in sync_request_write and
2031 				 * handle_write_finished.
2032 				 */
2033 				err = -EBUSY;
2034 				unfreeze_array(conf);
2035 				goto abort;
2036 			}
2037 			clear_bit(Replacement, &repl->flags);
2038 			WRITE_ONCE(p->rdev, repl);
2039 			conf->mirrors[conf->raid_disks + number].rdev = NULL;
2040 			unfreeze_array(conf);
2041 		}
2042 
2043 		clear_bit(WantReplacement, &rdev->flags);
2044 		err = md_integrity_register(mddev);
2045 	}
2046 abort:
2047 
2048 	print_conf(conf);
2049 	return err;
2050 }
2051 
2052 static void end_sync_read(struct bio *bio)
2053 {
2054 	struct r1bio *r1_bio = get_resync_r1bio(bio);
2055 
2056 	update_head_pos(r1_bio->read_disk, r1_bio);
2057 
2058 	/*
2059 	 * we have read a block, now it needs to be re-written,
2060 	 * or re-read if the read failed.
2061 	 * We don't do much here, just schedule handling by raid1d
2062 	 */
2063 	if (!bio->bi_status)
2064 		set_bit(R1BIO_Uptodate, &r1_bio->state);
2065 
2066 	if (atomic_dec_and_test(&r1_bio->remaining))
2067 		reschedule_retry(r1_bio);
2068 }
2069 
2070 static void abort_sync_write(struct mddev *mddev, struct r1bio *r1_bio)
2071 {
2072 	sector_t sync_blocks = 0;
2073 	sector_t s = r1_bio->sector;
2074 	long sectors_to_go = r1_bio->sectors;
2075 
2076 	/* make sure these bits don't get cleared. */
2077 	do {
2078 		md_bitmap_end_sync(mddev, s, &sync_blocks);
2079 		s += sync_blocks;
2080 		sectors_to_go -= sync_blocks;
2081 	} while (sectors_to_go > 0);
2082 }
2083 
2084 static void put_sync_write_buf(struct r1bio *r1_bio)
2085 {
2086 	if (atomic_dec_and_test(&r1_bio->remaining)) {
2087 		struct mddev *mddev = r1_bio->mddev;
2088 		int s = r1_bio->sectors;
2089 
2090 		if (test_bit(R1BIO_MadeGood, &r1_bio->state) ||
2091 		    test_bit(R1BIO_WriteError, &r1_bio->state))
2092 			reschedule_retry(r1_bio);
2093 		else {
2094 			put_buf(r1_bio);
2095 			md_done_sync(mddev, s);
2096 		}
2097 	}
2098 }
2099 
2100 static void end_sync_write(struct bio *bio)
2101 {
2102 	struct r1bio *r1_bio = get_resync_r1bio(bio);
2103 	struct mddev *mddev = r1_bio->mddev;
2104 	struct r1conf *conf = mddev->private;
2105 	struct md_rdev *rdev = conf->mirrors[find_bio_disk(r1_bio, bio)].rdev;
2106 
2107 	if (bio->bi_status) {
2108 		abort_sync_write(mddev, r1_bio);
2109 		set_bit(WriteErrorSeen, &rdev->flags);
2110 		if (!test_and_set_bit(WantReplacement, &rdev->flags))
2111 			set_bit(MD_RECOVERY_NEEDED, &
2112 				mddev->recovery);
2113 		set_bit(R1BIO_WriteError, &r1_bio->state);
2114 	} else if (rdev_has_badblock(rdev, r1_bio->sector, r1_bio->sectors) &&
2115 		   !rdev_has_badblock(conf->mirrors[r1_bio->read_disk].rdev,
2116 				      r1_bio->sector, r1_bio->sectors)) {
2117 		set_bit(R1BIO_MadeGood, &r1_bio->state);
2118 	}
2119 
2120 	put_sync_write_buf(r1_bio);
2121 }
2122 
2123 static int r1_sync_page_io(struct md_rdev *rdev, sector_t sector,
2124 			   int sectors, struct page *page, blk_opf_t rw)
2125 {
2126 	if (sync_page_io(rdev, sector, sectors << 9, page, rw, false))
2127 		/* success */
2128 		return 1;
2129 	if (rw == REQ_OP_WRITE) {
2130 		set_bit(WriteErrorSeen, &rdev->flags);
2131 		if (!test_and_set_bit(WantReplacement,
2132 				      &rdev->flags))
2133 			set_bit(MD_RECOVERY_NEEDED, &
2134 				rdev->mddev->recovery);
2135 	}
2136 	/* need to record an error - either for the block or the device */
2137 	rdev_set_badblocks(rdev, sector, sectors, 0);
2138 	return 0;
2139 }
2140 
2141 static int fix_sync_read_error(struct r1bio *r1_bio)
2142 {
2143 	/* Try some synchronous reads of other devices to get
2144 	 * good data, much like with normal read errors.  Only
2145 	 * read into the pages we already have so we don't
2146 	 * need to re-issue the read request.
2147 	 * We don't need to freeze the array, because being in an
2148 	 * active sync request, there is no normal IO, and
2149 	 * no overlapping syncs.
2150 	 * We don't need to check is_badblock() again as we
2151 	 * made sure that anything with a bad block in range
2152 	 * will have bi_end_io clear.
2153 	 */
2154 	struct mddev *mddev = r1_bio->mddev;
2155 	struct r1conf *conf = mddev->private;
2156 	struct bio *bio = r1_bio->bios[r1_bio->read_disk];
2157 	struct page **pages = get_resync_pages(bio)->pages;
2158 	sector_t sect = r1_bio->sector;
2159 	int sectors = r1_bio->sectors;
2160 	int idx = 0;
2161 	struct md_rdev *rdev;
2162 
2163 	rdev = conf->mirrors[r1_bio->read_disk].rdev;
2164 	if (test_bit(FailFast, &rdev->flags)) {
2165 		/* Don't try recovering from here - just fail it
2166 		 * ... unless it is the last working device of course */
2167 		md_error(mddev, rdev);
2168 		if (test_bit(Faulty, &rdev->flags))
2169 			/* Don't try to read from here, but make sure
2170 			 * put_buf does it's thing
2171 			 */
2172 			bio->bi_end_io = end_sync_write;
2173 	}
2174 
2175 	while(sectors) {
2176 		int s = sectors;
2177 		int d = r1_bio->read_disk;
2178 		int success = 0;
2179 		int start;
2180 
2181 		if (s > (PAGE_SIZE>>9))
2182 			s = PAGE_SIZE >> 9;
2183 		do {
2184 			if (r1_bio->bios[d]->bi_end_io == end_sync_read) {
2185 				/* No rcu protection needed here devices
2186 				 * can only be removed when no resync is
2187 				 * active, and resync is currently active
2188 				 */
2189 				rdev = conf->mirrors[d].rdev;
2190 				if (sync_page_io(rdev, sect, s<<9,
2191 						 pages[idx],
2192 						 REQ_OP_READ, false)) {
2193 					success = 1;
2194 					break;
2195 				}
2196 			}
2197 			d++;
2198 			if (d == conf->raid_disks * 2)
2199 				d = 0;
2200 		} while (!success && d != r1_bio->read_disk);
2201 
2202 		if (!success) {
2203 			int abort = 0;
2204 			/* Cannot read from anywhere, this block is lost.
2205 			 * Record a bad block on each device.  If that doesn't
2206 			 * work just disable and interrupt the recovery.
2207 			 * Don't fail devices as that won't really help.
2208 			 */
2209 			pr_crit_ratelimited("md/raid1:%s: %pg: unrecoverable I/O read error for block %llu\n",
2210 					    mdname(mddev), bio->bi_bdev,
2211 					    (unsigned long long)r1_bio->sector);
2212 			for (d = 0; d < conf->raid_disks * 2; d++) {
2213 				rdev = conf->mirrors[d].rdev;
2214 				if (!rdev || test_bit(Faulty, &rdev->flags))
2215 					continue;
2216 				if (!rdev_set_badblocks(rdev, sect, s, 0))
2217 					abort = 1;
2218 			}
2219 			if (abort)
2220 				return 0;
2221 
2222 			/* Try next page */
2223 			sectors -= s;
2224 			sect += s;
2225 			idx++;
2226 			continue;
2227 		}
2228 
2229 		start = d;
2230 		/* write it back and re-read */
2231 		while (d != r1_bio->read_disk) {
2232 			if (d == 0)
2233 				d = conf->raid_disks * 2;
2234 			d--;
2235 			if (r1_bio->bios[d]->bi_end_io != end_sync_read)
2236 				continue;
2237 			rdev = conf->mirrors[d].rdev;
2238 			if (r1_sync_page_io(rdev, sect, s,
2239 					    pages[idx],
2240 					    REQ_OP_WRITE) == 0) {
2241 				r1_bio->bios[d]->bi_end_io = NULL;
2242 				rdev_dec_pending(rdev, mddev);
2243 			}
2244 		}
2245 		d = start;
2246 		while (d != r1_bio->read_disk) {
2247 			if (d == 0)
2248 				d = conf->raid_disks * 2;
2249 			d--;
2250 			if (r1_bio->bios[d]->bi_end_io != end_sync_read)
2251 				continue;
2252 			rdev = conf->mirrors[d].rdev;
2253 			if (r1_sync_page_io(rdev, sect, s,
2254 					    pages[idx],
2255 					    REQ_OP_READ) != 0)
2256 				atomic_add(s, &rdev->corrected_errors);
2257 		}
2258 		sectors -= s;
2259 		sect += s;
2260 		idx ++;
2261 	}
2262 	set_bit(R1BIO_Uptodate, &r1_bio->state);
2263 	bio->bi_status = 0;
2264 	return 1;
2265 }
2266 
2267 static void process_checks(struct r1bio *r1_bio)
2268 {
2269 	/* We have read all readable devices.  If we haven't
2270 	 * got the block, then there is no hope left.
2271 	 * If we have, then we want to do a comparison
2272 	 * and skip the write if everything is the same.
2273 	 * If any blocks failed to read, then we need to
2274 	 * attempt an over-write
2275 	 */
2276 	struct mddev *mddev = r1_bio->mddev;
2277 	struct r1conf *conf = mddev->private;
2278 	int primary;
2279 	int i;
2280 	int vcnt;
2281 
2282 	/* Fix variable parts of all bios */
2283 	vcnt = (r1_bio->sectors + PAGE_SIZE / 512 - 1) >> (PAGE_SHIFT - 9);
2284 	for (i = 0; i < conf->raid_disks * 2; i++) {
2285 		blk_status_t status;
2286 		struct bio *b = r1_bio->bios[i];
2287 		struct resync_pages *rp = get_resync_pages(b);
2288 		if (b->bi_end_io != end_sync_read)
2289 			continue;
2290 		/* fixup the bio for reuse, but preserve errno */
2291 		status = b->bi_status;
2292 		bio_reset(b, conf->mirrors[i].rdev->bdev, REQ_OP_READ);
2293 		b->bi_status = status;
2294 		b->bi_iter.bi_sector = r1_bio->sector +
2295 			conf->mirrors[i].rdev->data_offset;
2296 		b->bi_end_io = end_sync_read;
2297 		rp->raid_bio = r1_bio;
2298 		b->bi_private = rp;
2299 
2300 		/* initialize bvec table again */
2301 		md_bio_reset_resync_pages(b, rp, r1_bio->sectors << 9);
2302 	}
2303 	for (primary = 0; primary < conf->raid_disks * 2; primary++)
2304 		if (r1_bio->bios[primary]->bi_end_io == end_sync_read &&
2305 		    !r1_bio->bios[primary]->bi_status) {
2306 			r1_bio->bios[primary]->bi_end_io = NULL;
2307 			rdev_dec_pending(conf->mirrors[primary].rdev, mddev);
2308 			break;
2309 		}
2310 	r1_bio->read_disk = primary;
2311 	for (i = 0; i < conf->raid_disks * 2; i++) {
2312 		int j = 0;
2313 		struct bio *pbio = r1_bio->bios[primary];
2314 		struct bio *sbio = r1_bio->bios[i];
2315 		blk_status_t status = sbio->bi_status;
2316 		struct page **ppages = get_resync_pages(pbio)->pages;
2317 		struct page **spages = get_resync_pages(sbio)->pages;
2318 		struct bio_vec *bi;
2319 		int page_len[RESYNC_PAGES] = { 0 };
2320 		struct bvec_iter_all iter_all;
2321 
2322 		if (sbio->bi_end_io != end_sync_read)
2323 			continue;
2324 		/* Now we can 'fixup' the error value */
2325 		sbio->bi_status = 0;
2326 
2327 		bio_for_each_segment_all(bi, sbio, iter_all)
2328 			page_len[j++] = bi->bv_len;
2329 
2330 		if (!status) {
2331 			for (j = vcnt; j-- ; ) {
2332 				if (memcmp(page_address(ppages[j]),
2333 					   page_address(spages[j]),
2334 					   page_len[j]))
2335 					break;
2336 			}
2337 		} else
2338 			j = 0;
2339 		if (j >= 0)
2340 			atomic64_add(r1_bio->sectors, &mddev->resync_mismatches);
2341 		if (j < 0 || (test_bit(MD_RECOVERY_CHECK, &mddev->recovery)
2342 			      && !status)) {
2343 			/* No need to write to this device. */
2344 			sbio->bi_end_io = NULL;
2345 			rdev_dec_pending(conf->mirrors[i].rdev, mddev);
2346 			continue;
2347 		}
2348 
2349 		bio_copy_data(sbio, pbio);
2350 	}
2351 }
2352 
2353 static void sync_request_write(struct mddev *mddev, struct r1bio *r1_bio)
2354 {
2355 	struct r1conf *conf = mddev->private;
2356 	int i;
2357 	int disks = conf->raid_disks * 2;
2358 	struct bio *wbio;
2359 
2360 	if (!test_bit(R1BIO_Uptodate, &r1_bio->state)) {
2361 		/*
2362 		 * ouch - failed to read all of that.
2363 		 * No need to fix read error for check/repair
2364 		 * because all member disks are read.
2365 		 */
2366 		if (test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery) ||
2367 		    !fix_sync_read_error(r1_bio)) {
2368 			md_done_sync(mddev, r1_bio->sectors);
2369 			md_sync_error(mddev);
2370 			put_buf(r1_bio);
2371 			return;
2372 		}
2373 	}
2374 
2375 	if (test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery))
2376 		process_checks(r1_bio);
2377 
2378 	/*
2379 	 * schedule writes
2380 	 */
2381 	atomic_set(&r1_bio->remaining, 1);
2382 	for (i = 0; i < disks ; i++) {
2383 		wbio = r1_bio->bios[i];
2384 		if (wbio->bi_end_io == NULL ||
2385 		    (wbio->bi_end_io == end_sync_read &&
2386 		     (i == r1_bio->read_disk ||
2387 		      !test_bit(MD_RECOVERY_SYNC, &mddev->recovery))))
2388 			continue;
2389 		if (test_bit(Faulty, &conf->mirrors[i].rdev->flags)) {
2390 			abort_sync_write(mddev, r1_bio);
2391 			continue;
2392 		}
2393 
2394 		wbio->bi_opf = REQ_OP_WRITE;
2395 		if (test_bit(FailFast, &conf->mirrors[i].rdev->flags))
2396 			wbio->bi_opf |= MD_FAILFAST;
2397 
2398 		wbio->bi_end_io = end_sync_write;
2399 		atomic_inc(&r1_bio->remaining);
2400 
2401 		submit_bio_noacct(wbio);
2402 	}
2403 
2404 	put_sync_write_buf(r1_bio);
2405 }
2406 
2407 /*
2408  * This is a kernel thread which:
2409  *
2410  *	1.	Retries failed read operations on working mirrors.
2411  *	2.	Updates the raid superblock when problems encounter.
2412  *	3.	Performs writes following reads for array synchronising.
2413  */
2414 
2415 static void fix_read_error(struct r1conf *conf, struct r1bio *r1_bio)
2416 {
2417 	sector_t sect = r1_bio->sector;
2418 	int sectors = r1_bio->sectors;
2419 	int read_disk = r1_bio->read_disk;
2420 	struct mddev *mddev = conf->mddev;
2421 	struct md_rdev *rdev = conf->mirrors[read_disk].rdev;
2422 
2423 	while(sectors) {
2424 		int s = sectors;
2425 		int d = read_disk;
2426 		int success = 0;
2427 		int start;
2428 
2429 		if (s > (PAGE_SIZE>>9))
2430 			s = PAGE_SIZE >> 9;
2431 
2432 		do {
2433 			rdev = conf->mirrors[d].rdev;
2434 			if (rdev &&
2435 			    (test_bit(In_sync, &rdev->flags) ||
2436 			     (!test_bit(Faulty, &rdev->flags) &&
2437 			      rdev->recovery_offset >= sect + s)) &&
2438 			    rdev_has_badblock(rdev, sect, s) == 0) {
2439 				atomic_inc(&rdev->nr_pending);
2440 				if (sync_page_io(rdev, sect, s<<9,
2441 					 conf->tmppage, REQ_OP_READ, false))
2442 					success = 1;
2443 				rdev_dec_pending(rdev, mddev);
2444 				if (success)
2445 					break;
2446 			}
2447 
2448 			d++;
2449 			if (d == conf->raid_disks * 2)
2450 				d = 0;
2451 		} while (d != read_disk);
2452 
2453 		if (!success) {
2454 			/* Cannot read from anywhere - mark it bad */
2455 			struct md_rdev *rdev = conf->mirrors[read_disk].rdev;
2456 			rdev_set_badblocks(rdev, sect, s, 0);
2457 			break;
2458 		}
2459 		/* write it back and re-read */
2460 		start = d;
2461 		while (d != read_disk) {
2462 			if (d==0)
2463 				d = conf->raid_disks * 2;
2464 			d--;
2465 			rdev = conf->mirrors[d].rdev;
2466 			if (rdev &&
2467 			    !test_bit(Faulty, &rdev->flags)) {
2468 				atomic_inc(&rdev->nr_pending);
2469 				r1_sync_page_io(rdev, sect, s,
2470 						conf->tmppage, REQ_OP_WRITE);
2471 				rdev_dec_pending(rdev, mddev);
2472 			}
2473 		}
2474 		d = start;
2475 		while (d != read_disk) {
2476 			if (d==0)
2477 				d = conf->raid_disks * 2;
2478 			d--;
2479 			rdev = conf->mirrors[d].rdev;
2480 			if (rdev &&
2481 			    !test_bit(Faulty, &rdev->flags)) {
2482 				atomic_inc(&rdev->nr_pending);
2483 				if (r1_sync_page_io(rdev, sect, s,
2484 						conf->tmppage, REQ_OP_READ)) {
2485 					atomic_add(s, &rdev->corrected_errors);
2486 					pr_info("md/raid1:%s: read error corrected (%d sectors at %llu on %pg)\n",
2487 						mdname(mddev), s,
2488 						(unsigned long long)(sect +
2489 								     rdev->data_offset),
2490 						rdev->bdev);
2491 				}
2492 				rdev_dec_pending(rdev, mddev);
2493 			}
2494 		}
2495 		sectors -= s;
2496 		sect += s;
2497 	}
2498 }
2499 
2500 static void narrow_write_error(struct r1bio *r1_bio, int i)
2501 {
2502 	struct mddev *mddev = r1_bio->mddev;
2503 	struct r1conf *conf = mddev->private;
2504 	struct md_rdev *rdev = conf->mirrors[i].rdev;
2505 
2506 	/* bio has the data to be written to device 'i' where
2507 	 * we just recently had a write error.
2508 	 * We repeatedly clone the bio and trim down to one block,
2509 	 * then try the write.  Where the write fails we record
2510 	 * a bad block.
2511 	 * It is conceivable that the bio doesn't exactly align with
2512 	 * blocks.  We must handle this somehow.
2513 	 *
2514 	 * We currently own a reference on the rdev.
2515 	 */
2516 
2517 	int block_sectors, lbs = bdev_logical_block_size(rdev->bdev) >> 9;
2518 	sector_t sector;
2519 	int sectors;
2520 	int sect_to_write = r1_bio->sectors;
2521 
2522 	if (rdev->badblocks.shift < 0)
2523 		block_sectors = lbs;
2524 	else
2525 		block_sectors = roundup(1 << rdev->badblocks.shift, lbs);
2526 
2527 	sector = r1_bio->sector;
2528 	sectors = ((sector + block_sectors)
2529 		   & ~(sector_t)(block_sectors - 1))
2530 		- sector;
2531 
2532 	while (sect_to_write) {
2533 		struct bio *wbio;
2534 		if (sectors > sect_to_write)
2535 			sectors = sect_to_write;
2536 		/* Write at 'sector' for 'sectors'*/
2537 
2538 		if (test_bit(R1BIO_BehindIO, &r1_bio->state)) {
2539 			wbio = bio_alloc_clone(rdev->bdev,
2540 					       r1_bio->behind_master_bio,
2541 					       GFP_NOIO, &mddev->bio_set);
2542 		} else {
2543 			wbio = bio_alloc_clone(rdev->bdev, r1_bio->master_bio,
2544 					       GFP_NOIO, &mddev->bio_set);
2545 		}
2546 
2547 		wbio->bi_opf = REQ_OP_WRITE;
2548 		wbio->bi_iter.bi_sector = r1_bio->sector;
2549 		wbio->bi_iter.bi_size = r1_bio->sectors << 9;
2550 
2551 		bio_trim(wbio, sector - r1_bio->sector, sectors);
2552 		wbio->bi_iter.bi_sector += rdev->data_offset;
2553 
2554 		if (submit_bio_wait(wbio) &&
2555 		    !rdev_set_badblocks(rdev, sector, sectors, 0)) {
2556 			/*
2557 			 * Badblocks set failed, disk marked Faulty.
2558 			 * No further operations needed.
2559 			 */
2560 			bio_put(wbio);
2561 			break;
2562 		}
2563 
2564 		bio_put(wbio);
2565 		sect_to_write -= sectors;
2566 		sector += sectors;
2567 		sectors = block_sectors;
2568 	}
2569 }
2570 
2571 static void handle_sync_write_finished(struct r1conf *conf, struct r1bio *r1_bio)
2572 {
2573 	int m;
2574 	int s = r1_bio->sectors;
2575 	for (m = 0; m < conf->raid_disks * 2 ; m++) {
2576 		struct md_rdev *rdev = conf->mirrors[m].rdev;
2577 		struct bio *bio = r1_bio->bios[m];
2578 		if (bio->bi_end_io == NULL)
2579 			continue;
2580 		if (!bio->bi_status &&
2581 		    test_bit(R1BIO_MadeGood, &r1_bio->state))
2582 			rdev_clear_badblocks(rdev, r1_bio->sector, s, 0);
2583 		if (bio->bi_status &&
2584 		    test_bit(R1BIO_WriteError, &r1_bio->state))
2585 			rdev_set_badblocks(rdev, r1_bio->sector, s, 0);
2586 	}
2587 	put_buf(r1_bio);
2588 	md_done_sync(conf->mddev, s);
2589 }
2590 
2591 static void handle_write_finished(struct r1conf *conf, struct r1bio *r1_bio)
2592 {
2593 	int m, idx;
2594 	bool fail = false;
2595 
2596 	for (m = 0; m < conf->raid_disks * 2 ; m++)
2597 		if (r1_bio->bios[m] == IO_MADE_GOOD) {
2598 			struct md_rdev *rdev = conf->mirrors[m].rdev;
2599 			rdev_clear_badblocks(rdev,
2600 					     r1_bio->sector,
2601 					     r1_bio->sectors, 0);
2602 			rdev_dec_pending(rdev, conf->mddev);
2603 		} else if (r1_bio->bios[m] != NULL) {
2604 			/* This drive got a write error.  We need to
2605 			 * narrow down and record precise write
2606 			 * errors.
2607 			 */
2608 			fail = true;
2609 			narrow_write_error(r1_bio, m);
2610 			rdev_dec_pending(conf->mirrors[m].rdev,
2611 					 conf->mddev);
2612 		}
2613 	if (fail) {
2614 		spin_lock_irq(&conf->device_lock);
2615 		list_add(&r1_bio->retry_list, &conf->bio_end_io_list);
2616 		idx = sector_to_idx(r1_bio->sector);
2617 		atomic_inc(&conf->nr_queued[idx]);
2618 		spin_unlock_irq(&conf->device_lock);
2619 		/*
2620 		 * In case freeze_array() is waiting for condition
2621 		 * get_unqueued_pending() == extra to be true.
2622 		 */
2623 		wake_up(&conf->wait_barrier);
2624 		md_wakeup_thread(conf->mddev->thread);
2625 	} else {
2626 		if (test_bit(R1BIO_WriteError, &r1_bio->state))
2627 			close_write(r1_bio);
2628 		raid_end_bio_io(r1_bio);
2629 	}
2630 }
2631 
2632 static void handle_read_error(struct r1conf *conf, struct r1bio *r1_bio)
2633 {
2634 	struct md_rdev *rdev = conf->mirrors[r1_bio->read_disk].rdev;
2635 	struct bio *bio = r1_bio->bios[r1_bio->read_disk];
2636 	struct mddev *mddev = conf->mddev;
2637 	sector_t sector;
2638 
2639 	clear_bit(R1BIO_ReadError, &r1_bio->state);
2640 
2641 	bio_put(bio);
2642 	r1_bio->bios[r1_bio->read_disk] = NULL;
2643 
2644 	/*
2645 	 * We got a read error. Maybe the drive is bad.  Maybe just the block
2646 	 * and we can fix it.
2647 	 *
2648 	 * If allowed, freeze all other IO, and try reading the block from other
2649 	 * devices.  If we find one, we re-write and check it that fixes the
2650 	 * read error.  This is all done synchronously while the array is
2651 	 * frozen.
2652 	 */
2653 	if (mddev->ro) {
2654 		r1_bio->bios[r1_bio->read_disk] = IO_BLOCKED;
2655 	} else if (test_bit(FailFast, &rdev->flags)) {
2656 		md_error(mddev, rdev);
2657 	} else {
2658 		freeze_array(conf, 1);
2659 		if (exceed_read_errors(mddev, rdev))
2660 			r1_bio->bios[r1_bio->read_disk] = IO_BLOCKED;
2661 		else
2662 			fix_read_error(conf, r1_bio);
2663 		unfreeze_array(conf);
2664 	}
2665 
2666 	rdev_dec_pending(rdev, conf->mddev);
2667 	sector = r1_bio->sector;
2668 	bio = r1_bio->master_bio;
2669 
2670 	/* Reuse the old r1_bio so that the IO_BLOCKED settings are preserved */
2671 	r1_bio->state = 0;
2672 	raid1_read_request(mddev, bio, r1_bio->sectors, r1_bio);
2673 	allow_barrier(conf, sector);
2674 }
2675 
2676 static void raid1d(struct md_thread *thread)
2677 {
2678 	struct mddev *mddev = thread->mddev;
2679 	struct r1bio *r1_bio;
2680 	unsigned long flags;
2681 	struct r1conf *conf = mddev->private;
2682 	struct list_head *head = &conf->retry_list;
2683 	struct blk_plug plug;
2684 	int idx;
2685 
2686 	md_check_recovery(mddev);
2687 
2688 	if (!list_empty_careful(&conf->bio_end_io_list) &&
2689 	    !test_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags)) {
2690 		LIST_HEAD(tmp);
2691 		spin_lock_irqsave(&conf->device_lock, flags);
2692 		if (!test_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags))
2693 			list_splice_init(&conf->bio_end_io_list, &tmp);
2694 		spin_unlock_irqrestore(&conf->device_lock, flags);
2695 		while (!list_empty(&tmp)) {
2696 			r1_bio = list_first_entry(&tmp, struct r1bio,
2697 						  retry_list);
2698 			list_del(&r1_bio->retry_list);
2699 			idx = sector_to_idx(r1_bio->sector);
2700 			atomic_dec(&conf->nr_queued[idx]);
2701 			if (test_bit(R1BIO_WriteError, &r1_bio->state))
2702 				close_write(r1_bio);
2703 			raid_end_bio_io(r1_bio);
2704 		}
2705 	}
2706 
2707 	blk_start_plug(&plug);
2708 	for (;;) {
2709 
2710 		flush_pending_writes(conf);
2711 
2712 		spin_lock_irqsave(&conf->device_lock, flags);
2713 		if (list_empty(head)) {
2714 			spin_unlock_irqrestore(&conf->device_lock, flags);
2715 			break;
2716 		}
2717 		r1_bio = list_entry(head->prev, struct r1bio, retry_list);
2718 		list_del(head->prev);
2719 		idx = sector_to_idx(r1_bio->sector);
2720 		atomic_dec(&conf->nr_queued[idx]);
2721 		spin_unlock_irqrestore(&conf->device_lock, flags);
2722 
2723 		mddev = r1_bio->mddev;
2724 		conf = mddev->private;
2725 		if (test_bit(R1BIO_IsSync, &r1_bio->state)) {
2726 			if (test_bit(R1BIO_MadeGood, &r1_bio->state) ||
2727 			    test_bit(R1BIO_WriteError, &r1_bio->state))
2728 				handle_sync_write_finished(conf, r1_bio);
2729 			else
2730 				sync_request_write(mddev, r1_bio);
2731 		} else if (test_bit(R1BIO_MadeGood, &r1_bio->state) ||
2732 			   test_bit(R1BIO_WriteError, &r1_bio->state))
2733 			handle_write_finished(conf, r1_bio);
2734 		else if (test_bit(R1BIO_ReadError, &r1_bio->state))
2735 			handle_read_error(conf, r1_bio);
2736 		else
2737 			WARN_ON_ONCE(1);
2738 
2739 		cond_resched();
2740 		if (mddev->sb_flags & ~(1<<MD_SB_CHANGE_PENDING))
2741 			md_check_recovery(mddev);
2742 	}
2743 	blk_finish_plug(&plug);
2744 }
2745 
2746 static int init_resync(struct r1conf *conf)
2747 {
2748 	int buffs;
2749 
2750 	buffs = RESYNC_WINDOW / RESYNC_BLOCK_SIZE;
2751 	BUG_ON(mempool_initialized(&conf->r1buf_pool));
2752 
2753 	return mempool_init(&conf->r1buf_pool, buffs, r1buf_pool_alloc,
2754 			    r1buf_pool_free, conf);
2755 }
2756 
2757 static struct r1bio *raid1_alloc_init_r1buf(struct r1conf *conf)
2758 {
2759 	struct r1bio *r1bio = mempool_alloc(&conf->r1buf_pool, GFP_NOIO);
2760 	struct resync_pages *rps;
2761 	struct bio *bio;
2762 	int i;
2763 
2764 	for (i = conf->raid_disks * 2; i--; ) {
2765 		bio = r1bio->bios[i];
2766 		rps = bio->bi_private;
2767 		bio_reset(bio, NULL, 0);
2768 		bio->bi_private = rps;
2769 	}
2770 	r1bio->master_bio = NULL;
2771 	return r1bio;
2772 }
2773 
2774 /*
2775  * perform a "sync" on one "block"
2776  *
2777  * We need to make sure that no normal I/O request - particularly write
2778  * requests - conflict with active sync requests.
2779  *
2780  * This is achieved by tracking pending requests and a 'barrier' concept
2781  * that can be installed to exclude normal IO requests.
2782  */
2783 
2784 static sector_t raid1_sync_request(struct mddev *mddev, sector_t sector_nr,
2785 				   sector_t max_sector, int *skipped)
2786 {
2787 	struct r1conf *conf = mddev->private;
2788 	struct r1bio *r1_bio;
2789 	struct bio *bio;
2790 	sector_t nr_sectors;
2791 	int disk = -1;
2792 	int i;
2793 	int wonly = -1;
2794 	int write_targets = 0, read_targets = 0;
2795 	sector_t sync_blocks;
2796 	bool still_degraded = false;
2797 	int good_sectors = RESYNC_SECTORS;
2798 	int min_bad = 0; /* number of sectors that are bad in all devices */
2799 	int idx = sector_to_idx(sector_nr);
2800 	int page_idx = 0;
2801 
2802 	if (!mempool_initialized(&conf->r1buf_pool))
2803 		if (init_resync(conf))
2804 			return 0;
2805 
2806 	if (sector_nr >= max_sector) {
2807 		/* If we aborted, we need to abort the
2808 		 * sync on the 'current' bitmap chunk (there will
2809 		 * only be one in raid1 resync.
2810 		 * We can find the current addess in mddev->curr_resync
2811 		 */
2812 		if (mddev->curr_resync < max_sector) /* aborted */
2813 			md_bitmap_end_sync(mddev, mddev->curr_resync,
2814 					   &sync_blocks);
2815 		else /* completed sync */
2816 			conf->fullsync = 0;
2817 
2818 		if (md_bitmap_enabled(mddev, false))
2819 			mddev->bitmap_ops->close_sync(mddev);
2820 		close_sync(conf);
2821 
2822 		if (mddev_is_clustered(mddev)) {
2823 			conf->cluster_sync_low = 0;
2824 			conf->cluster_sync_high = 0;
2825 		}
2826 		return 0;
2827 	}
2828 
2829 	if (mddev->bitmap == NULL &&
2830 	    mddev->resync_offset == MaxSector &&
2831 	    !test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery) &&
2832 	    conf->fullsync == 0) {
2833 		*skipped = 1;
2834 		return max_sector - sector_nr;
2835 	}
2836 	/* before building a request, check if we can skip these blocks..
2837 	 * This call the bitmap_start_sync doesn't actually record anything
2838 	 */
2839 	if (!md_bitmap_start_sync(mddev, sector_nr, &sync_blocks, true) &&
2840 	    !conf->fullsync && !test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery)) {
2841 		/* We can skip this block, and probably several more */
2842 		*skipped = 1;
2843 		return sync_blocks;
2844 	}
2845 
2846 	/*
2847 	 * If there is non-resync activity waiting for a turn, then let it
2848 	 * though before starting on this new sync request.
2849 	 */
2850 	if (atomic_read(&conf->nr_waiting[idx]))
2851 		schedule_timeout_uninterruptible(1);
2852 
2853 	/* we are incrementing sector_nr below. To be safe, we check against
2854 	 * sector_nr + two times RESYNC_SECTORS
2855 	 */
2856 	if (md_bitmap_enabled(mddev, false))
2857 		mddev->bitmap_ops->cond_end_sync(mddev, sector_nr,
2858 			mddev_is_clustered(mddev) &&
2859 			(sector_nr + 2 * RESYNC_SECTORS >
2860 			 conf->cluster_sync_high));
2861 
2862 	if (raise_barrier(conf, sector_nr))
2863 		return 0;
2864 
2865 	r1_bio = raid1_alloc_init_r1buf(conf);
2866 
2867 	/*
2868 	 * If we get a correctably read error during resync or recovery,
2869 	 * we might want to read from a different device.  So we
2870 	 * flag all drives that could conceivably be read from for READ,
2871 	 * and any others (which will be non-In_sync devices) for WRITE.
2872 	 * If a read fails, we try reading from something else for which READ
2873 	 * is OK.
2874 	 */
2875 
2876 	r1_bio->mddev = mddev;
2877 	r1_bio->sector = sector_nr;
2878 	r1_bio->state = 0;
2879 	set_bit(R1BIO_IsSync, &r1_bio->state);
2880 	/* make sure good_sectors won't go across barrier unit boundary */
2881 	good_sectors = align_to_barrier_unit_end(sector_nr, good_sectors);
2882 
2883 	for (i = 0; i < conf->raid_disks * 2; i++) {
2884 		struct md_rdev *rdev;
2885 		bio = r1_bio->bios[i];
2886 
2887 		rdev = conf->mirrors[i].rdev;
2888 		if (rdev == NULL ||
2889 		    test_bit(Faulty, &rdev->flags)) {
2890 			if (i < conf->raid_disks)
2891 				still_degraded = true;
2892 		} else if (!test_bit(In_sync, &rdev->flags)) {
2893 			bio->bi_opf = REQ_OP_WRITE;
2894 			bio->bi_end_io = end_sync_write;
2895 			write_targets ++;
2896 		} else {
2897 			/* may need to read from here */
2898 			sector_t first_bad = MaxSector;
2899 			sector_t bad_sectors;
2900 
2901 			if (is_badblock(rdev, sector_nr, good_sectors,
2902 					&first_bad, &bad_sectors)) {
2903 				if (first_bad > sector_nr)
2904 					good_sectors = first_bad - sector_nr;
2905 				else {
2906 					bad_sectors -= (sector_nr - first_bad);
2907 					if (min_bad == 0 ||
2908 					    min_bad > bad_sectors)
2909 						min_bad = bad_sectors;
2910 				}
2911 			}
2912 			if (sector_nr < first_bad) {
2913 				if (test_bit(WriteMostly, &rdev->flags)) {
2914 					if (wonly < 0)
2915 						wonly = i;
2916 				} else {
2917 					if (disk < 0)
2918 						disk = i;
2919 				}
2920 				bio->bi_opf = REQ_OP_READ;
2921 				bio->bi_end_io = end_sync_read;
2922 				read_targets++;
2923 			} else if (!test_bit(WriteErrorSeen, &rdev->flags) &&
2924 				test_bit(MD_RECOVERY_SYNC, &mddev->recovery) &&
2925 				!test_bit(MD_RECOVERY_CHECK, &mddev->recovery)) {
2926 				/*
2927 				 * The device is suitable for reading (InSync),
2928 				 * but has bad block(s) here. Let's try to correct them,
2929 				 * if we are doing resync or repair. Otherwise, leave
2930 				 * this device alone for this sync request.
2931 				 */
2932 				bio->bi_opf = REQ_OP_WRITE;
2933 				bio->bi_end_io = end_sync_write;
2934 				write_targets++;
2935 			}
2936 		}
2937 		if (rdev && bio->bi_end_io) {
2938 			atomic_inc(&rdev->nr_pending);
2939 			bio->bi_iter.bi_sector = sector_nr + rdev->data_offset;
2940 			bio_set_dev(bio, rdev->bdev);
2941 			if (test_bit(FailFast, &rdev->flags))
2942 				bio->bi_opf |= MD_FAILFAST;
2943 		}
2944 	}
2945 	if (disk < 0)
2946 		disk = wonly;
2947 	r1_bio->read_disk = disk;
2948 
2949 	if (read_targets == 0 && min_bad > 0) {
2950 		/* These sectors are bad on all InSync devices, so we
2951 		 * need to mark them bad on all write targets
2952 		 */
2953 		int ok = 1;
2954 		for (i = 0 ; i < conf->raid_disks * 2 ; i++)
2955 			if (r1_bio->bios[i]->bi_end_io == end_sync_write) {
2956 				struct md_rdev *rdev = conf->mirrors[i].rdev;
2957 				ok = rdev_set_badblocks(rdev, sector_nr,
2958 							min_bad, 0
2959 					) && ok;
2960 			}
2961 		set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
2962 		*skipped = 1;
2963 		put_buf(r1_bio);
2964 
2965 		if (!ok)
2966 			/* Cannot record the badblocks, md_error has set INTR,
2967 			 * abort the resync.
2968 			 */
2969 			return 0;
2970 		else
2971 			return min_bad;
2972 
2973 	}
2974 	if (min_bad > 0 && min_bad < good_sectors) {
2975 		/* only resync enough to reach the next bad->good
2976 		 * transition */
2977 		good_sectors = min_bad;
2978 	}
2979 
2980 	if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery) && read_targets > 0)
2981 		/* extra read targets are also write targets */
2982 		write_targets += read_targets-1;
2983 
2984 	if (write_targets == 0 || read_targets == 0) {
2985 		/* There is nowhere to write, so all non-sync
2986 		 * drives must be failed - so we are finished
2987 		 */
2988 		sector_t rv;
2989 		if (min_bad > 0)
2990 			max_sector = sector_nr + min_bad;
2991 		rv = max_sector - sector_nr;
2992 		*skipped = 1;
2993 		put_buf(r1_bio);
2994 		return rv;
2995 	}
2996 
2997 	if (max_sector > mddev->resync_max)
2998 		max_sector = mddev->resync_max; /* Don't do IO beyond here */
2999 	if (max_sector > sector_nr + good_sectors)
3000 		max_sector = sector_nr + good_sectors;
3001 	nr_sectors = 0;
3002 	sync_blocks = 0;
3003 	do {
3004 		struct page *page;
3005 		int len = PAGE_SIZE;
3006 		if (sector_nr + (len>>9) > max_sector)
3007 			len = (max_sector - sector_nr) << 9;
3008 		if (len == 0)
3009 			break;
3010 		if (sync_blocks == 0) {
3011 			if (!md_bitmap_start_sync(mddev, sector_nr,
3012 						  &sync_blocks, still_degraded) &&
3013 			    !conf->fullsync &&
3014 			    !test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery))
3015 				break;
3016 			if ((len >> 9) > sync_blocks)
3017 				len = sync_blocks<<9;
3018 		}
3019 
3020 		for (i = 0 ; i < conf->raid_disks * 2; i++) {
3021 			struct resync_pages *rp;
3022 
3023 			bio = r1_bio->bios[i];
3024 			rp = get_resync_pages(bio);
3025 			if (bio->bi_end_io) {
3026 				page = resync_fetch_page(rp, page_idx);
3027 
3028 				/*
3029 				 * won't fail because the vec table is big
3030 				 * enough to hold all these pages
3031 				 */
3032 				__bio_add_page(bio, page, len, 0);
3033 			}
3034 		}
3035 		nr_sectors += len>>9;
3036 		sector_nr += len>>9;
3037 		sync_blocks -= (len>>9);
3038 	} while (++page_idx < RESYNC_PAGES);
3039 
3040 	r1_bio->sectors = nr_sectors;
3041 
3042 	if (mddev_is_clustered(mddev) &&
3043 			conf->cluster_sync_high < sector_nr + nr_sectors) {
3044 		conf->cluster_sync_low = mddev->curr_resync_completed;
3045 		conf->cluster_sync_high = conf->cluster_sync_low + CLUSTER_RESYNC_WINDOW_SECTORS;
3046 		/* Send resync message */
3047 		mddev->cluster_ops->resync_info_update(mddev,
3048 						       conf->cluster_sync_low,
3049 						       conf->cluster_sync_high);
3050 	}
3051 
3052 	/* For a user-requested sync, we read all readable devices and do a
3053 	 * compare
3054 	 */
3055 	if (test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery)) {
3056 		atomic_set(&r1_bio->remaining, read_targets);
3057 		for (i = 0; i < conf->raid_disks * 2 && read_targets; i++) {
3058 			bio = r1_bio->bios[i];
3059 			if (bio->bi_end_io == end_sync_read) {
3060 				read_targets--;
3061 				if (read_targets == 1)
3062 					bio->bi_opf &= ~MD_FAILFAST;
3063 				submit_bio_noacct(bio);
3064 			}
3065 		}
3066 	} else {
3067 		atomic_set(&r1_bio->remaining, 1);
3068 		bio = r1_bio->bios[r1_bio->read_disk];
3069 		if (read_targets == 1)
3070 			bio->bi_opf &= ~MD_FAILFAST;
3071 		submit_bio_noacct(bio);
3072 	}
3073 	return nr_sectors;
3074 }
3075 
3076 static sector_t raid1_size(struct mddev *mddev, sector_t sectors, int raid_disks)
3077 {
3078 	if (sectors)
3079 		return sectors;
3080 
3081 	return mddev->dev_sectors;
3082 }
3083 
3084 static struct r1conf *setup_conf(struct mddev *mddev)
3085 {
3086 	struct r1conf *conf;
3087 	int i;
3088 	struct raid1_info *disk;
3089 	struct md_rdev *rdev;
3090 	size_t r1bio_size;
3091 	int err = -ENOMEM;
3092 
3093 	conf = kzalloc_obj(struct r1conf);
3094 	if (!conf)
3095 		goto abort;
3096 
3097 	conf->nr_pending = kzalloc_objs(atomic_t, BARRIER_BUCKETS_NR);
3098 	if (!conf->nr_pending)
3099 		goto abort;
3100 
3101 	conf->nr_waiting = kzalloc_objs(atomic_t, BARRIER_BUCKETS_NR);
3102 	if (!conf->nr_waiting)
3103 		goto abort;
3104 
3105 	conf->nr_queued = kzalloc_objs(atomic_t, BARRIER_BUCKETS_NR);
3106 	if (!conf->nr_queued)
3107 		goto abort;
3108 
3109 	conf->barrier = kzalloc_objs(atomic_t, BARRIER_BUCKETS_NR);
3110 	if (!conf->barrier)
3111 		goto abort;
3112 
3113 	conf->mirrors = kzalloc(array3_size(sizeof(struct raid1_info),
3114 					    mddev->raid_disks, 2),
3115 				GFP_KERNEL);
3116 	if (!conf->mirrors)
3117 		goto abort;
3118 
3119 	conf->tmppage = alloc_page(GFP_KERNEL);
3120 	if (!conf->tmppage)
3121 		goto abort;
3122 
3123 	r1bio_size = offsetof(struct r1bio, bios[mddev->raid_disks * 2]);
3124 	conf->r1bio_pool = mempool_create_kmalloc_pool(NR_RAID_BIOS, r1bio_size);
3125 	if (!conf->r1bio_pool)
3126 		goto abort;
3127 
3128 	err = bioset_init(&conf->bio_split, BIO_POOL_SIZE, 0, 0);
3129 	if (err)
3130 		goto abort;
3131 
3132 	err = -EINVAL;
3133 	spin_lock_init(&conf->device_lock);
3134 	conf->raid_disks = mddev->raid_disks;
3135 	rdev_for_each(rdev, mddev) {
3136 		int disk_idx = rdev->raid_disk;
3137 
3138 		if (disk_idx >= conf->raid_disks || disk_idx < 0)
3139 			continue;
3140 
3141 		if (!raid1_add_conf(conf, rdev, disk_idx,
3142 				    test_bit(Replacement, &rdev->flags)))
3143 			goto abort;
3144 	}
3145 	conf->mddev = mddev;
3146 	INIT_LIST_HEAD(&conf->retry_list);
3147 	INIT_LIST_HEAD(&conf->bio_end_io_list);
3148 
3149 	spin_lock_init(&conf->resync_lock);
3150 	init_waitqueue_head(&conf->wait_barrier);
3151 
3152 	bio_list_init(&conf->pending_bio_list);
3153 
3154 	err = -EIO;
3155 	for (i = 0; i < conf->raid_disks * 2; i++) {
3156 
3157 		disk = conf->mirrors + i;
3158 
3159 		if (i < conf->raid_disks &&
3160 		    disk[conf->raid_disks].rdev) {
3161 			/* This slot has a replacement. */
3162 			if (!disk->rdev) {
3163 				/* No original, just make the replacement
3164 				 * a recovering spare
3165 				 */
3166 				disk->rdev =
3167 					disk[conf->raid_disks].rdev;
3168 				disk[conf->raid_disks].rdev = NULL;
3169 			} else if (!test_bit(In_sync, &disk->rdev->flags))
3170 				/* Original is not in_sync - bad */
3171 				goto abort;
3172 		}
3173 
3174 		if (!disk->rdev ||
3175 		    !test_bit(In_sync, &disk->rdev->flags)) {
3176 			disk->head_position = 0;
3177 			if (disk->rdev &&
3178 			    (disk->rdev->saved_raid_disk < 0))
3179 				conf->fullsync = 1;
3180 		}
3181 	}
3182 
3183 	err = -ENOMEM;
3184 	rcu_assign_pointer(conf->thread,
3185 			   md_register_thread(raid1d, mddev, "raid1"));
3186 	if (!conf->thread)
3187 		goto abort;
3188 
3189 	return conf;
3190 
3191  abort:
3192 	if (conf) {
3193 		mempool_destroy(conf->r1bio_pool);
3194 		kfree(conf->mirrors);
3195 		safe_put_page(conf->tmppage);
3196 		kfree(conf->nr_pending);
3197 		kfree(conf->nr_waiting);
3198 		kfree(conf->nr_queued);
3199 		kfree(conf->barrier);
3200 		bioset_exit(&conf->bio_split);
3201 		kfree(conf);
3202 	}
3203 	return ERR_PTR(err);
3204 }
3205 
3206 static int raid1_set_limits(struct mddev *mddev)
3207 {
3208 	struct queue_limits lim;
3209 	int err;
3210 
3211 	md_init_stacking_limits(&lim);
3212 	lim.max_write_zeroes_sectors = 0;
3213 	lim.max_hw_wzeroes_unmap_sectors = 0;
3214 	lim.logical_block_size = mddev->logical_block_size;
3215 	lim.features |= BLK_FEAT_ATOMIC_WRITES;
3216 	lim.features |= BLK_FEAT_PCI_P2PDMA;
3217 	err = mddev_stack_rdev_limits(mddev, &lim, MDDEV_STACK_INTEGRITY);
3218 	if (err)
3219 		return err;
3220 	return queue_limits_set(mddev->gendisk->queue, &lim);
3221 }
3222 
3223 static int raid1_run(struct mddev *mddev)
3224 {
3225 	struct r1conf *conf;
3226 	int i;
3227 	int ret;
3228 
3229 	if (mddev->level != 1) {
3230 		pr_warn("md/raid1:%s: raid level not set to mirroring (%d)\n",
3231 			mdname(mddev), mddev->level);
3232 		return -EIO;
3233 	}
3234 	if (mddev->reshape_position != MaxSector) {
3235 		pr_warn("md/raid1:%s: reshape_position set but not supported\n",
3236 			mdname(mddev));
3237 		return -EIO;
3238 	}
3239 
3240 	/*
3241 	 * copy the already verified devices into our private RAID1
3242 	 * bookkeeping area. [whatever we allocate in run(),
3243 	 * should be freed in raid1_free()]
3244 	 */
3245 	if (mddev->private == NULL)
3246 		conf = setup_conf(mddev);
3247 	else
3248 		conf = mddev->private;
3249 
3250 	if (IS_ERR(conf))
3251 		return PTR_ERR(conf);
3252 
3253 	if (!mddev_is_dm(mddev)) {
3254 		ret = raid1_set_limits(mddev);
3255 		if (ret) {
3256 			md_unregister_thread(mddev, &conf->thread);
3257 			if (!mddev->private)
3258 				raid1_free(mddev, conf);
3259 			return ret;
3260 		}
3261 	}
3262 
3263 	mddev->degraded = 0;
3264 	for (i = 0; i < conf->raid_disks; i++)
3265 		if (conf->mirrors[i].rdev == NULL ||
3266 		    !test_bit(In_sync, &conf->mirrors[i].rdev->flags) ||
3267 		    test_bit(Faulty, &conf->mirrors[i].rdev->flags))
3268 			mddev->degraded++;
3269 	/*
3270 	 * RAID1 needs at least one disk in active
3271 	 */
3272 	if (conf->raid_disks - mddev->degraded < 1) {
3273 		md_unregister_thread(mddev, &conf->thread);
3274 		if (!mddev->private)
3275 			raid1_free(mddev, conf);
3276 		return -EINVAL;
3277 	}
3278 
3279 	if (conf->raid_disks - mddev->degraded == 1)
3280 		mddev->resync_offset = MaxSector;
3281 
3282 	if (mddev->resync_offset != MaxSector)
3283 		pr_info("md/raid1:%s: not clean -- starting background reconstruction\n",
3284 			mdname(mddev));
3285 	pr_info("md/raid1:%s: active with %d out of %d mirrors\n",
3286 		mdname(mddev), mddev->raid_disks - mddev->degraded,
3287 		mddev->raid_disks);
3288 
3289 	/*
3290 	 * Ok, everything is just fine now
3291 	 */
3292 	rcu_assign_pointer(mddev->thread, conf->thread);
3293 	rcu_assign_pointer(conf->thread, NULL);
3294 	mddev->private = conf;
3295 	set_bit(MD_FAILFAST_SUPPORTED, &mddev->flags);
3296 
3297 	md_set_array_sectors(mddev, raid1_size(mddev, 0, 0));
3298 
3299 	ret = md_integrity_register(mddev);
3300 	if (ret)
3301 		md_unregister_thread(mddev, &mddev->thread);
3302 	return ret;
3303 }
3304 
3305 static void raid1_free(struct mddev *mddev, void *priv)
3306 {
3307 	struct r1conf *conf = priv;
3308 
3309 	mempool_destroy(conf->r1bio_pool);
3310 	kfree(conf->mirrors);
3311 	safe_put_page(conf->tmppage);
3312 	kfree(conf->nr_pending);
3313 	kfree(conf->nr_waiting);
3314 	kfree(conf->nr_queued);
3315 	kfree(conf->barrier);
3316 	bioset_exit(&conf->bio_split);
3317 	kfree(conf);
3318 }
3319 
3320 static int raid1_resize(struct mddev *mddev, sector_t sectors)
3321 {
3322 	/* no resync is happening, and there is enough space
3323 	 * on all devices, so we can resize.
3324 	 * We need to make sure resync covers any new space.
3325 	 * If the array is shrinking we should possibly wait until
3326 	 * any io in the removed space completes, but it hardly seems
3327 	 * worth it.
3328 	 */
3329 	sector_t newsize = raid1_size(mddev, sectors, 0);
3330 
3331 	if (mddev->external_size &&
3332 	    mddev->array_sectors > newsize)
3333 		return -EINVAL;
3334 
3335 	if (md_bitmap_enabled(mddev, false)) {
3336 		int ret = mddev->bitmap_ops->resize(mddev, newsize, 0);
3337 
3338 		if (ret)
3339 			return ret;
3340 	}
3341 
3342 	md_set_array_sectors(mddev, newsize);
3343 	if (sectors > mddev->dev_sectors &&
3344 	    mddev->resync_offset > mddev->dev_sectors) {
3345 		mddev->resync_offset = mddev->dev_sectors;
3346 		set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
3347 	}
3348 	mddev->dev_sectors = sectors;
3349 	mddev->resync_max_sectors = sectors;
3350 	return 0;
3351 }
3352 
3353 static int raid1_reshape(struct mddev *mddev)
3354 {
3355 	/* We need to:
3356 	 * 1/ resize the r1bio_pool
3357 	 * 2/ resize conf->mirrors
3358 	 *
3359 	 * We allocate a new r1bio_pool if we can.
3360 	 * Then raise a device barrier and wait until all IO stops.
3361 	 * Then resize conf->mirrors and swap in the new r1bio pool.
3362 	 *
3363 	 * At the same time, we "pack" the devices so that all the missing
3364 	 * devices have the higher raid_disk numbers.
3365 	 */
3366 	mempool_t *newpool, *oldpool;
3367 	size_t new_r1bio_size;
3368 	struct raid1_info *newmirrors;
3369 	struct r1conf *conf = mddev->private;
3370 	int cnt, raid_disks;
3371 	unsigned long flags;
3372 	int d, d2;
3373 
3374 	/* Cannot change chunk_size, layout, or level */
3375 	if (mddev->chunk_sectors != mddev->new_chunk_sectors ||
3376 	    mddev->layout != mddev->new_layout ||
3377 	    mddev->level != mddev->new_level) {
3378 		mddev->new_chunk_sectors = mddev->chunk_sectors;
3379 		mddev->new_layout = mddev->layout;
3380 		mddev->new_level = mddev->level;
3381 		return -EINVAL;
3382 	}
3383 
3384 	if (!mddev_is_clustered(mddev))
3385 		md_allow_write(mddev);
3386 
3387 	raid_disks = mddev->raid_disks + mddev->delta_disks;
3388 
3389 	if (raid_disks < conf->raid_disks) {
3390 		cnt=0;
3391 		for (d= 0; d < conf->raid_disks; d++)
3392 			if (conf->mirrors[d].rdev)
3393 				cnt++;
3394 		if (cnt > raid_disks)
3395 			return -EBUSY;
3396 	}
3397 
3398 	new_r1bio_size = offsetof(struct r1bio, bios[raid_disks * 2]);
3399 	newpool = mempool_create_kmalloc_pool(NR_RAID_BIOS, new_r1bio_size);
3400 	if (!newpool) {
3401 		return -ENOMEM;
3402 	}
3403 	newmirrors = kzalloc(array3_size(sizeof(struct raid1_info),
3404 					 raid_disks, 2),
3405 			     GFP_KERNEL);
3406 	if (!newmirrors) {
3407 		mempool_destroy(newpool);
3408 		return -ENOMEM;
3409 	}
3410 
3411 	freeze_array(conf, 0);
3412 
3413 	/* ok, everything is stopped */
3414 	oldpool = conf->r1bio_pool;
3415 	conf->r1bio_pool = newpool;
3416 
3417 	for (d = d2 = 0; d < conf->raid_disks; d++) {
3418 		struct md_rdev *rdev = conf->mirrors[d].rdev;
3419 		if (rdev && rdev->raid_disk != d2) {
3420 			sysfs_unlink_rdev(mddev, rdev);
3421 			rdev->raid_disk = d2;
3422 			sysfs_unlink_rdev(mddev, rdev);
3423 			if (sysfs_link_rdev(mddev, rdev))
3424 				pr_warn("md/raid1:%s: cannot register rd%d\n",
3425 					mdname(mddev), rdev->raid_disk);
3426 		}
3427 		if (rdev)
3428 			newmirrors[d2++].rdev = rdev;
3429 	}
3430 	kfree(conf->mirrors);
3431 	conf->mirrors = newmirrors;
3432 
3433 	spin_lock_irqsave(&conf->device_lock, flags);
3434 	mddev->degraded += (raid_disks - conf->raid_disks);
3435 	spin_unlock_irqrestore(&conf->device_lock, flags);
3436 	conf->raid_disks = mddev->raid_disks = raid_disks;
3437 	mddev->delta_disks = 0;
3438 
3439 	unfreeze_array(conf);
3440 
3441 	set_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
3442 	set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
3443 	md_wakeup_thread(mddev->thread);
3444 
3445 	mempool_destroy(oldpool);
3446 	return 0;
3447 }
3448 
3449 static void raid1_quiesce(struct mddev *mddev, int quiesce)
3450 {
3451 	struct r1conf *conf = mddev->private;
3452 
3453 	if (quiesce)
3454 		freeze_array(conf, 0);
3455 	else
3456 		unfreeze_array(conf);
3457 }
3458 
3459 static void *raid1_takeover(struct mddev *mddev)
3460 {
3461 	/* raid1 can take over:
3462 	 *  raid5 with 2 devices, any layout or chunk size
3463 	 */
3464 	if (mddev->level == 5 && mddev->raid_disks == 2) {
3465 		struct r1conf *conf;
3466 		mddev->new_level = 1;
3467 		mddev->new_layout = 0;
3468 		mddev->new_chunk_sectors = 0;
3469 		conf = setup_conf(mddev);
3470 		if (!IS_ERR(conf)) {
3471 			/* Array must appear to be quiesced */
3472 			conf->array_frozen = 1;
3473 			mddev_clear_unsupported_flags(mddev,
3474 				UNSUPPORTED_MDDEV_FLAGS);
3475 		}
3476 		return conf;
3477 	}
3478 	return ERR_PTR(-EINVAL);
3479 }
3480 
3481 static struct md_personality raid1_personality =
3482 {
3483 	.head = {
3484 		.type	= MD_PERSONALITY,
3485 		.id	= ID_RAID1,
3486 		.name	= "raid1",
3487 		.owner	= THIS_MODULE,
3488 	},
3489 
3490 	.make_request	= raid1_make_request,
3491 	.run		= raid1_run,
3492 	.free		= raid1_free,
3493 	.status		= raid1_status,
3494 	.error_handler	= raid1_error,
3495 	.hot_add_disk	= raid1_add_disk,
3496 	.hot_remove_disk= raid1_remove_disk,
3497 	.spare_active	= raid1_spare_active,
3498 	.sync_request	= raid1_sync_request,
3499 	.resize		= raid1_resize,
3500 	.size		= raid1_size,
3501 	.check_reshape	= raid1_reshape,
3502 	.quiesce	= raid1_quiesce,
3503 	.takeover	= raid1_takeover,
3504 };
3505 
3506 static int __init raid1_init(void)
3507 {
3508 	return register_md_submodule(&raid1_personality.head);
3509 }
3510 
3511 static void __exit raid1_exit(void)
3512 {
3513 	unregister_md_submodule(&raid1_personality.head);
3514 }
3515 
3516 module_init(raid1_init);
3517 module_exit(raid1_exit);
3518 MODULE_LICENSE("GPL");
3519 MODULE_DESCRIPTION("RAID1 (mirroring) personality for MD");
3520 MODULE_ALIAS("md-personality-3"); /* RAID1 */
3521 MODULE_ALIAS("md-raid1");
3522 MODULE_ALIAS("md-level-1");
3523