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