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