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