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