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