raid1.c 93.3 KB
Newer Older
1
// SPDX-License-Identifier: GPL-2.0-or-later
Linus Torvalds's avatar
Linus Torvalds committed
2 3 4 5 6 7 8 9 10 11 12
/*
 * raid1.c : Multiple Devices driver for Linux
 *
 * Copyright (C) 1999, 2000, 2001 Ingo Molnar, Red Hat
 *
 * Copyright (C) 1996, 1997, 1998 Ingo Molnar, Miguel de Icaza, Gadi Oxman
 *
 * RAID-1 management functions.
 *
 * Better read-balancing code written by Mika Kuoppala <miku@iki.fi>, 2000
 *
13
 * Fixes to reconstruction by Jakob Østergaard" <jakob@ostenfeld.dk>
Linus Torvalds's avatar
Linus Torvalds committed
14 15
 * Various fixes by Neil Brown <neilb@cse.unsw.edu.au>
 *
16 17 18 19 20 21 22 23
 * Changes by Peter T. Breuer <ptb@it.uc3m.es> 31/1/2003 to support
 * bitmapped intelligence in resync:
 *
 *      - bitmap marked during normal i/o
 *      - bitmap used to skip nondirty blocks during sync
 *
 * Additions to bitmap code, (C) 2003-2004 Paul Clements, SteelEye Technology:
 * - persistent bitmap code
Linus Torvalds's avatar
Linus Torvalds committed
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 41
#define UNSUPPORTED_MDDEV_FLAGS		\
	((1L << MD_HAS_JOURNAL) |	\
42
	 (1L << MD_JOURNAL_CLEAN) |	\
43 44
	 (1L << MD_HAS_PPL) |		\
	 (1L << MD_HAS_MULTIPLE_PPLS))
45

46 47
static void allow_barrier(struct r1conf *conf, sector_t sector_nr);
static void lower_barrier(struct r1conf *conf, sector_t sector_nr);
Linus Torvalds's avatar
Linus Torvalds committed
48

49
#define RAID_1_10_NAME "raid1"
50 51
#include "raid1-10.c"

52 53 54 55 56
#define START(node) ((node)->start)
#define LAST(node) ((node)->last)
INTERVAL_TREE_DEFINE(struct serial_info, node, sector_t, _subtree_last,
		     START, LAST, static inline, raid1_rb);

57 58
static int check_and_add_serial(struct md_rdev *rdev, struct r1bio *r1_bio,
				struct serial_info *si, int idx)
59 60 61
{
	unsigned long flags;
	int ret = 0;
62 63
	sector_t lo = r1_bio->sector;
	sector_t hi = lo + r1_bio->sectors;
64
	struct serial_in_rdev *serial = &rdev->serial[idx];
65

66 67 68 69
	spin_lock_irqsave(&serial->serial_lock, flags);
	/* collision happened */
	if (raid1_rb_iter_first(&serial->serial_rb, lo, hi))
		ret = -EBUSY;
70
	else {
71 72 73
		si->start = lo;
		si->last = hi;
		raid1_rb_insert(si, &serial->serial_rb);
74
	}
75
	spin_unlock_irqrestore(&serial->serial_lock, flags);
76 77 78 79

	return ret;
}

80 81 82 83 84 85 86 87 88 89 90 91 92 93
static void wait_for_serialization(struct md_rdev *rdev, struct r1bio *r1_bio)
{
	struct mddev *mddev = rdev->mddev;
	struct serial_info *si;
	int idx = sector_to_idx(r1_bio->sector);
	struct serial_in_rdev *serial = &rdev->serial[idx];

	if (WARN_ON(!mddev->serial_info_pool))
		return;
	si = mempool_alloc(mddev->serial_info_pool, GFP_NOIO);
	wait_event(serial->serial_io_wait,
		   check_and_add_serial(rdev, r1_bio, si, idx) == 0);
}

Guoqing Jiang's avatar
Guoqing Jiang committed
94
static void remove_serial(struct md_rdev *rdev, sector_t lo, sector_t hi)
95
{
96
	struct serial_info *si;
97 98 99
	unsigned long flags;
	int found = 0;
	struct mddev *mddev = rdev->mddev;
100 101
	int idx = sector_to_idx(lo);
	struct serial_in_rdev *serial = &rdev->serial[idx];
102 103 104 105 106 107 108

	spin_lock_irqsave(&serial->serial_lock, flags);
	for (si = raid1_rb_iter_first(&serial->serial_rb, lo, hi);
	     si; si = raid1_rb_iter_next(si, lo, hi)) {
		if (si->start == lo && si->last == hi) {
			raid1_rb_remove(si, &serial->serial_rb);
			mempool_free(si, mddev->serial_info_pool);
109 110 111
			found = 1;
			break;
		}
112
	}
113
	if (!found)
Guoqing Jiang's avatar
Guoqing Jiang committed
114
		WARN(1, "The write IO is not recorded for serialization\n");
115 116
	spin_unlock_irqrestore(&serial->serial_lock, flags);
	wake_up(&serial->serial_io_wait);
117 118
}

119 120 121 122 123 124 125 126 127
/*
 * for resync bio, r1bio pointer can be retrieved from the per-bio
 * 'struct resync_pages'.
 */
static inline struct r1bio *get_resync_r1bio(struct bio *bio)
{
	return get_resync_pages(bio)->raid_bio;
}

128
static void * r1bio_pool_alloc(gfp_t gfp_flags, void *data)
Linus Torvalds's avatar
Linus Torvalds committed
129 130
{
	struct pool_info *pi = data;
131
	int size = offsetof(struct r1bio, bios[pi->raid_disks]);
Linus Torvalds's avatar
Linus Torvalds committed
132 133

	/* allocate a r1bio with room for raid_disks entries in the bios array */
134
	return kzalloc(size, gfp_flags);
Linus Torvalds's avatar
Linus Torvalds committed
135 136
}

137
#define RESYNC_DEPTH 32
Linus Torvalds's avatar
Linus Torvalds committed
138
#define RESYNC_SECTORS (RESYNC_BLOCK_SIZE >> 9)
139 140
#define RESYNC_WINDOW (RESYNC_BLOCK_SIZE * RESYNC_DEPTH)
#define RESYNC_WINDOW_SECTORS (RESYNC_WINDOW >> 9)
141 142
#define CLUSTER_RESYNC_WINDOW (16 * RESYNC_WINDOW)
#define CLUSTER_RESYNC_WINDOW_SECTORS (CLUSTER_RESYNC_WINDOW >> 9)
Linus Torvalds's avatar
Linus Torvalds committed
143

144
static void * r1buf_pool_alloc(gfp_t gfp_flags, void *data)
Linus Torvalds's avatar
Linus Torvalds committed
145 146
{
	struct pool_info *pi = data;
147
	struct r1bio *r1_bio;
Linus Torvalds's avatar
Linus Torvalds committed
148
	struct bio *bio;
149
	int need_pages;
150 151
	int j;
	struct resync_pages *rps;
Linus Torvalds's avatar
Linus Torvalds committed
152 153

	r1_bio = r1bio_pool_alloc(gfp_flags, pi);
154
	if (!r1_bio)
Linus Torvalds's avatar
Linus Torvalds committed
155 156
		return NULL;

157 158
	rps = kmalloc_array(pi->raid_disks, sizeof(struct resync_pages),
			    gfp_flags);
159 160 161
	if (!rps)
		goto out_free_r1bio;

Linus Torvalds's avatar
Linus Torvalds committed
162 163 164 165
	/*
	 * Allocate bios : 1 for reading, n-1 for writing
	 */
	for (j = pi->raid_disks ; j-- ; ) {
166
		bio = bio_kmalloc(RESYNC_PAGES, gfp_flags);
Linus Torvalds's avatar
Linus Torvalds committed
167 168
		if (!bio)
			goto out_free_bio;
169
		bio_init(bio, NULL, bio->bi_inline_vecs, RESYNC_PAGES, 0);
Linus Torvalds's avatar
Linus Torvalds committed
170 171 172 173
		r1_bio->bios[j] = bio;
	}
	/*
	 * Allocate RESYNC_PAGES data pages and attach them to
174 175 176
	 * the first bio.
	 * If this is a user-requested check/repair, allocate
	 * RESYNC_PAGES for each bio.
Linus Torvalds's avatar
Linus Torvalds committed
177
	 */
178
	if (test_bit(MD_RECOVERY_REQUESTED, &pi->mddev->recovery))
179
		need_pages = pi->raid_disks;
180
	else
181
		need_pages = 1;
182 183 184
	for (j = 0; j < pi->raid_disks; j++) {
		struct resync_pages *rp = &rps[j];

185 186
		bio = r1_bio->bios[j];

187 188 189 190 191 192 193 194 195 196
		if (j < need_pages) {
			if (resync_alloc_pages(rp, gfp_flags))
				goto out_free_pages;
		} else {
			memcpy(rp, &rps[0], sizeof(*rp));
			resync_get_all_pages(rp);
		}

		rp->raid_bio = r1_bio;
		bio->bi_private = rp;
Linus Torvalds's avatar
Linus Torvalds committed
197 198 199 200 201 202
	}

	r1_bio->master_bio = NULL;

	return r1_bio;

203
out_free_pages:
204
	while (--j >= 0)
205
		resync_free_pages(&rps[j]);
206

Linus Torvalds's avatar
Linus Torvalds committed
207
out_free_bio:
208 209 210 211
	while (++j < pi->raid_disks) {
		bio_uninit(r1_bio->bios[j]);
		kfree(r1_bio->bios[j]);
	}
212 213 214
	kfree(rps);

out_free_r1bio:
215
	rbio_pool_free(r1_bio, data);
Linus Torvalds's avatar
Linus Torvalds committed
216 217 218 219 220 221
	return NULL;
}

static void r1buf_pool_free(void *__r1_bio, void *data)
{
	struct pool_info *pi = data;
222
	int i;
223
	struct r1bio *r1bio = __r1_bio;
224
	struct resync_pages *rp = NULL;
Linus Torvalds's avatar
Linus Torvalds committed
225

226 227 228
	for (i = pi->raid_disks; i--; ) {
		rp = get_resync_pages(r1bio->bios[i]);
		resync_free_pages(rp);
229 230
		bio_uninit(r1bio->bios[i]);
		kfree(r1bio->bios[i]);
231 232 233 234
	}

	/* resync pages array stored in the 1st bio's .bi_private */
	kfree(rp);
Linus Torvalds's avatar
Linus Torvalds committed
235

236
	rbio_pool_free(r1bio, data);
Linus Torvalds's avatar
Linus Torvalds committed
237 238
}

239
static void put_all_bios(struct r1conf *conf, struct r1bio *r1_bio)
Linus Torvalds's avatar
Linus Torvalds committed
240 241 242
{
	int i;

243
	for (i = 0; i < conf->raid_disks * 2; i++) {
Linus Torvalds's avatar
Linus Torvalds committed
244
		struct bio **bio = r1_bio->bios + i;
245
		if (!BIO_SPECIAL(*bio))
Linus Torvalds's avatar
Linus Torvalds committed
246 247 248 249 250
			bio_put(*bio);
		*bio = NULL;
	}
}

251
static void free_r1bio(struct r1bio *r1_bio)
Linus Torvalds's avatar
Linus Torvalds committed
252
{
253
	struct r1conf *conf = r1_bio->mddev->private;
Linus Torvalds's avatar
Linus Torvalds committed
254 255

	put_all_bios(conf, r1_bio);
256
	mempool_free(r1_bio, &conf->r1bio_pool);
Linus Torvalds's avatar
Linus Torvalds committed
257 258
}

259
static void put_buf(struct r1bio *r1_bio)
Linus Torvalds's avatar
Linus Torvalds committed
260
{
261
	struct r1conf *conf = r1_bio->mddev->private;
262
	sector_t sect = r1_bio->sector;
263 264
	int i;

265
	for (i = 0; i < conf->raid_disks * 2; i++) {
266 267 268 269
		struct bio *bio = r1_bio->bios[i];
		if (bio->bi_end_io)
			rdev_dec_pending(conf->mirrors[i].rdev, r1_bio->mddev);
	}
Linus Torvalds's avatar
Linus Torvalds committed
270

271
	mempool_free(r1_bio, &conf->r1buf_pool);
Linus Torvalds's avatar
Linus Torvalds committed
272

273
	lower_barrier(conf, sect);
Linus Torvalds's avatar
Linus Torvalds committed
274 275
}

276
static void reschedule_retry(struct r1bio *r1_bio)
Linus Torvalds's avatar
Linus Torvalds committed
277 278
{
	unsigned long flags;
279
	struct mddev *mddev = r1_bio->mddev;
280
	struct r1conf *conf = mddev->private;
281
	int idx;
Linus Torvalds's avatar
Linus Torvalds committed
282

283
	idx = sector_to_idx(r1_bio->sector);
Linus Torvalds's avatar
Linus Torvalds committed
284 285
	spin_lock_irqsave(&conf->device_lock, flags);
	list_add(&r1_bio->retry_list, &conf->retry_list);
286
	atomic_inc(&conf->nr_queued[idx]);
Linus Torvalds's avatar
Linus Torvalds committed
287 288
	spin_unlock_irqrestore(&conf->device_lock, flags);

289
	wake_up(&conf->wait_barrier);
Linus Torvalds's avatar
Linus Torvalds committed
290 291 292 293 294 295 296 297
	md_wakeup_thread(mddev->thread);
}

/*
 * raid_end_bio_io() is called when we have finished servicing a mirrored
 * operation and are ready to return a success/failure code to the buffer
 * cache layer.
 */
298
static void call_bio_endio(struct r1bio *r1_bio)
299 300 301 302
{
	struct bio *bio = r1_bio->master_bio;

	if (!test_bit(R1BIO_Uptodate, &r1_bio->state))
303
		bio->bi_status = BLK_STS_IOERR;
304

305
	bio_endio(bio);
306 307
}

308
static void raid_end_bio_io(struct r1bio *r1_bio)
Linus Torvalds's avatar
Linus Torvalds committed
309 310
{
	struct bio *bio = r1_bio->master_bio;
311
	struct r1conf *conf = r1_bio->mddev->private;
312
	sector_t sector = r1_bio->sector;
Linus Torvalds's avatar
Linus Torvalds committed
313

314 315
	/* if nobody has done the final endio yet, do it now */
	if (!test_and_set_bit(R1BIO_Returned, &r1_bio->state)) {
316 317
		pr_debug("raid1: sync end %s on sectors %llu-%llu\n",
			 (bio_data_dir(bio) == WRITE) ? "write" : "read",
318 319
			 (unsigned long long) bio->bi_iter.bi_sector,
			 (unsigned long long) bio_end_sector(bio) - 1);
320

321
		call_bio_endio(r1_bio);
322
	}
323 324

	free_r1bio(r1_bio);
325 326 327 328
	/*
	 * Wake up any possible resync thread that waits for the device
	 * to go idle.  All I/Os, even write-behind writes, are done.
	 */
329
	allow_barrier(conf, sector);
Linus Torvalds's avatar
Linus Torvalds committed
330 331 332 333 334
}

/*
 * Update disk head position estimator based on IRQ completion info.
 */
335
static inline void update_head_pos(int disk, struct r1bio *r1_bio)
Linus Torvalds's avatar
Linus Torvalds committed
336
{
337
	struct r1conf *conf = r1_bio->mddev->private;
Linus Torvalds's avatar
Linus Torvalds committed
338 339 340 341 342

	conf->mirrors[disk].head_position =
		r1_bio->sector + (r1_bio->sectors);
}

343 344 345
/*
 * Find the disk number which triggered given bio
 */
346
static int find_bio_disk(struct r1bio *r1_bio, struct bio *bio)
347 348
{
	int mirror;
349 350
	struct r1conf *conf = r1_bio->mddev->private;
	int raid_disks = conf->raid_disks;
351

352
	for (mirror = 0; mirror < raid_disks * 2; mirror++)
353 354 355
		if (r1_bio->bios[mirror] == bio)
			break;

356
	BUG_ON(mirror == raid_disks * 2);
357 358 359 360 361
	update_head_pos(mirror, r1_bio);

	return mirror;
}

362
static void raid1_end_read_request(struct bio *bio)
Linus Torvalds's avatar
Linus Torvalds committed
363
{
364
	int uptodate = !bio->bi_status;
365
	struct r1bio *r1_bio = bio->bi_private;
366
	struct r1conf *conf = r1_bio->mddev->private;
367
	struct md_rdev *rdev = conf->mirrors[r1_bio->read_disk].rdev;
Linus Torvalds's avatar
Linus Torvalds committed
368 369 370 371

	/*
	 * this branch is our 'one mirror IO has finished' event handler:
	 */
372
	update_head_pos(r1_bio->read_disk, r1_bio);
373

374 375
	if (uptodate)
		set_bit(R1BIO_Uptodate, &r1_bio->state);
376 377 378 379 380
	else if (test_bit(FailFast, &rdev->flags) &&
		 test_bit(R1BIO_FailFast, &r1_bio->state))
		/* This was a fail-fast read so we definitely
		 * want to retry */
		;
381 382 383 384
	else {
		/* If all other devices have failed, we want to return
		 * the error upwards rather than fail the last device.
		 * Here we redefine "uptodate" to mean "Don't want to retry"
Linus Torvalds's avatar
Linus Torvalds committed
385
		 */
386 387 388 389
		unsigned long flags;
		spin_lock_irqsave(&conf->device_lock, flags);
		if (r1_bio->mddev->degraded == conf->raid_disks ||
		    (r1_bio->mddev->degraded == conf->raid_disks-1 &&
390
		     test_bit(In_sync, &rdev->flags)))
391 392 393
			uptodate = 1;
		spin_unlock_irqrestore(&conf->device_lock, flags);
	}
Linus Torvalds's avatar
Linus Torvalds committed
394

395
	if (uptodate) {
Linus Torvalds's avatar
Linus Torvalds committed
396
		raid_end_bio_io(r1_bio);
397
		rdev_dec_pending(rdev, conf->mddev);
398
	} else {
Linus Torvalds's avatar
Linus Torvalds committed
399 400 401
		/*
		 * oops, read error:
		 */
402
		pr_err_ratelimited("md/raid1:%s: %pg: rescheduling sector %llu\n",
403
				   mdname(conf->mddev),
404
				   rdev->bdev,
405
				   (unsigned long long)r1_bio->sector);
406
		set_bit(R1BIO_ReadError, &r1_bio->state);
Linus Torvalds's avatar
Linus Torvalds committed
407
		reschedule_retry(r1_bio);
408
		/* don't drop the reference on read_disk yet */
Linus Torvalds's avatar
Linus Torvalds committed
409 410 411
	}
}

412
static void close_write(struct r1bio *r1_bio)
413
{
414 415
	struct mddev *mddev = r1_bio->mddev;

416 417
	/* it really is the end of this request */
	if (test_bit(R1BIO_BehindIO, &r1_bio->state)) {
Ming Lei's avatar
Ming Lei committed
418 419 420
		bio_free_pages(r1_bio->behind_master_bio);
		bio_put(r1_bio->behind_master_bio);
		r1_bio->behind_master_bio = NULL;
421
	}
422

423
	/* clear the bitmap if all writes complete successfully */
424 425 426 427
	mddev->bitmap_ops->endwrite(mddev, r1_bio->sector, r1_bio->sectors,
				    !test_bit(R1BIO_Degraded, &r1_bio->state),
				    test_bit(R1BIO_BehindIO, &r1_bio->state));
	md_write_end(mddev);
428 429
}

430
static void r1_bio_write_done(struct r1bio *r1_bio)
431
{
432 433 434 435 436 437 438
	if (!atomic_dec_and_test(&r1_bio->remaining))
		return;

	if (test_bit(R1BIO_WriteError, &r1_bio->state))
		reschedule_retry(r1_bio);
	else {
		close_write(r1_bio);
439 440 441 442
		if (test_bit(R1BIO_MadeGood, &r1_bio->state))
			reschedule_retry(r1_bio);
		else
			raid_end_bio_io(r1_bio);
443 444 445
	}
}

446
static void raid1_end_write_request(struct bio *bio)
Linus Torvalds's avatar
Linus Torvalds committed
447
{
448
	struct r1bio *r1_bio = bio->bi_private;
449
	int behind = test_bit(R1BIO_BehindIO, &r1_bio->state);
450
	struct r1conf *conf = r1_bio->mddev->private;
451
	struct bio *to_put = NULL;
452 453
	int mirror = find_bio_disk(r1_bio, bio);
	struct md_rdev *rdev = conf->mirrors[mirror].rdev;
Shaohua Li's avatar
Shaohua Li committed
454
	bool discard_error;
455 456
	sector_t lo = r1_bio->sector;
	sector_t hi = r1_bio->sector + r1_bio->sectors;
Shaohua Li's avatar
Shaohua Li committed
457

458
	discard_error = bio->bi_status && bio_op(bio) == REQ_OP_DISCARD;
Linus Torvalds's avatar
Linus Torvalds committed
459

460 461 462
	/*
	 * 'one mirror IO has finished' event handler:
	 */
463
	if (bio->bi_status && !discard_error) {
464 465
		set_bit(WriteErrorSeen,	&rdev->flags);
		if (!test_and_set_bit(WantReplacement, &rdev->flags))
466 467 468
			set_bit(MD_RECOVERY_NEEDED, &
				conf->mddev->recovery);

469 470 471 472 473
		if (test_bit(FailFast, &rdev->flags) &&
		    (bio->bi_opf & MD_FAILFAST) &&
		    /* We never try FailFast to WriteMostly devices */
		    !test_bit(WriteMostly, &rdev->flags)) {
			md_error(r1_bio->mddev, rdev);
474 475 476 477 478 479 480
		}

		/*
		 * When the device is faulty, it is not necessary to
		 * handle write error.
		 */
		if (!test_bit(Faulty, &rdev->flags))
481
			set_bit(R1BIO_WriteError, &r1_bio->state);
482
		else {
483 484
			/* Fail the request */
			set_bit(R1BIO_Degraded, &r1_bio->state);
485 486 487 488
			/* Finished with this branch */
			r1_bio->bios[mirror] = NULL;
			to_put = bio;
		}
489
	} else {
Linus Torvalds's avatar
Linus Torvalds committed
490
		/*
491 492 493 494 495 496 497 498
		 * Set R1BIO_Uptodate in our master bio, so that we
		 * will return a good error code for to the higher
		 * levels even if IO on some other mirrored buffer
		 * fails.
		 *
		 * The 'master' represents the composite IO operation
		 * to user-side. So if something waits for IO, then it
		 * will wait for the 'master' bio.
Linus Torvalds's avatar
Linus Torvalds committed
499
		 */
500 501
		r1_bio->bios[mirror] = NULL;
		to_put = bio;
502 503 504 505 506 507 508 509
		/*
		 * Do not set R1BIO_Uptodate if the current device is
		 * rebuilding or Faulty. This is because we cannot use
		 * such device for properly reading the data back (we could
		 * potentially use it, if the current write would have felt
		 * before rdev->recovery_offset, but for simplicity we don't
		 * check this here.
		 */
510 511
		if (test_bit(In_sync, &rdev->flags) &&
		    !test_bit(Faulty, &rdev->flags))
512
			set_bit(R1BIO_Uptodate, &r1_bio->state);
513

514
		/* Maybe we can clear some bad blocks. */
515 516
		if (rdev_has_badblock(rdev, r1_bio->sector, r1_bio->sectors) &&
		    !discard_error) {
517 518 519 520 521
			r1_bio->bios[mirror] = IO_MADE_GOOD;
			set_bit(R1BIO_MadeGood, &r1_bio->state);
		}
	}

522
	if (behind) {
523
		if (test_bit(CollisionCheck, &rdev->flags))
Guoqing Jiang's avatar
Guoqing Jiang committed
524
			remove_serial(rdev, lo, hi);
525
		if (test_bit(WriteMostly, &rdev->flags))
526 527 528 529 530 531 532 533 534 535 536 537 538 539
			atomic_dec(&r1_bio->behind_remaining);

		/*
		 * In behind mode, we ACK the master bio once the I/O
		 * has safely reached all non-writemostly
		 * disks. Setting the Returned bit ensures that this
		 * gets done only once -- we don't ever want to return
		 * -EIO here, instead we'll wait
		 */
		if (atomic_read(&r1_bio->behind_remaining) >= (atomic_read(&r1_bio->remaining)-1) &&
		    test_bit(R1BIO_Uptodate, &r1_bio->state)) {
			/* Maybe we can return now */
			if (!test_and_set_bit(R1BIO_Returned, &r1_bio->state)) {
				struct bio *mbio = r1_bio->master_bio;
540 541
				pr_debug("raid1: behind end write sectors"
					 " %llu-%llu\n",
542 543
					 (unsigned long long) mbio->bi_iter.bi_sector,
					 (unsigned long long) bio_end_sector(mbio) - 1);
544
				call_bio_endio(r1_bio);
545 546
			}
		}
547 548
	} else if (rdev->mddev->serialize_policy)
		remove_serial(rdev, lo, hi);
549
	if (r1_bio->bios[mirror] == NULL)
550
		rdev_dec_pending(rdev, conf->mddev);
551

Linus Torvalds's avatar
Linus Torvalds committed
552 553 554 555
	/*
	 * Let's see if all mirrored write operations have finished
	 * already.
	 */
556
	r1_bio_write_done(r1_bio);
557

558 559
	if (to_put)
		bio_put(to_put);
Linus Torvalds's avatar
Linus Torvalds committed
560 561
}

562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580
static sector_t align_to_barrier_unit_end(sector_t start_sector,
					  sector_t sectors)
{
	sector_t len;

	WARN_ON(sectors == 0);
	/*
	 * len is the number of sectors from start_sector to end of the
	 * barrier unit which start_sector belongs to.
	 */
	len = round_up(start_sector + 1, BARRIER_UNIT_SECTOR_SIZE) -
	      start_sector;

	if (len > sectors)
		len = sectors;

	return len;
}

581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621
static void update_read_sectors(struct r1conf *conf, int disk,
				sector_t this_sector, int len)
{
	struct raid1_info *info = &conf->mirrors[disk];

	atomic_inc(&info->rdev->nr_pending);
	if (info->next_seq_sect != this_sector)
		info->seq_start = this_sector;
	info->next_seq_sect = this_sector + len;
}

static int choose_first_rdev(struct r1conf *conf, struct r1bio *r1_bio,
			     int *max_sectors)
{
	sector_t this_sector = r1_bio->sector;
	int len = r1_bio->sectors;
	int disk;

	for (disk = 0 ; disk < conf->raid_disks * 2 ; disk++) {
		struct md_rdev *rdev;
		int read_len;

		if (r1_bio->bios[disk] == IO_BLOCKED)
			continue;

		rdev = conf->mirrors[disk].rdev;
		if (!rdev || test_bit(Faulty, &rdev->flags))
			continue;

		/* choose the first disk even if it has some bad blocks. */
		read_len = raid1_check_read_range(rdev, this_sector, &len);
		if (read_len > 0) {
			update_read_sectors(conf, disk, this_sector, read_len);
			*max_sectors = read_len;
			return disk;
		}
	}

	return -1;
}

622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659
static int choose_bb_rdev(struct r1conf *conf, struct r1bio *r1_bio,
			  int *max_sectors)
{
	sector_t this_sector = r1_bio->sector;
	int best_disk = -1;
	int best_len = 0;
	int disk;

	for (disk = 0 ; disk < conf->raid_disks * 2 ; disk++) {
		struct md_rdev *rdev;
		int len;
		int read_len;

		if (r1_bio->bios[disk] == IO_BLOCKED)
			continue;

		rdev = conf->mirrors[disk].rdev;
		if (!rdev || test_bit(Faulty, &rdev->flags) ||
		    test_bit(WriteMostly, &rdev->flags))
			continue;

		/* keep track of the disk with the most readable sectors. */
		len = r1_bio->sectors;
		read_len = raid1_check_read_range(rdev, this_sector, &len);
		if (read_len > best_len) {
			best_disk = disk;
			best_len = read_len;
		}
	}

	if (best_disk != -1) {
		*max_sectors = best_len;
		update_read_sectors(conf, best_disk, this_sector, best_len);
	}

	return best_disk;
}

660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684
static int choose_slow_rdev(struct r1conf *conf, struct r1bio *r1_bio,
			    int *max_sectors)
{
	sector_t this_sector = r1_bio->sector;
	int bb_disk = -1;
	int bb_read_len = 0;
	int disk;

	for (disk = 0 ; disk < conf->raid_disks * 2 ; disk++) {
		struct md_rdev *rdev;
		int len;
		int read_len;

		if (r1_bio->bios[disk] == IO_BLOCKED)
			continue;

		rdev = conf->mirrors[disk].rdev;
		if (!rdev || test_bit(Faulty, &rdev->flags) ||
		    !test_bit(WriteMostly, &rdev->flags))
			continue;

		/* there are no bad blocks, we can use this disk */
		len = r1_bio->sectors;
		read_len = raid1_check_read_range(rdev, this_sector, &len);
		if (read_len == r1_bio->sectors) {
685
			*max_sectors = read_len;
686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707
			update_read_sectors(conf, disk, this_sector, read_len);
			return disk;
		}

		/*
		 * there are partial bad blocks, choose the rdev with largest
		 * read length.
		 */
		if (read_len > bb_read_len) {
			bb_disk = disk;
			bb_read_len = read_len;
		}
	}

	if (bb_disk != -1) {
		*max_sectors = bb_read_len;
		update_read_sectors(conf, bb_disk, this_sector, bb_read_len);
	}

	return bb_disk;
}

708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732
static bool is_sequential(struct r1conf *conf, int disk, struct r1bio *r1_bio)
{
	/* TODO: address issues with this check and concurrency. */
	return conf->mirrors[disk].next_seq_sect == r1_bio->sector ||
	       conf->mirrors[disk].head_position == r1_bio->sector;
}

/*
 * If buffered sequential IO size exceeds optimal iosize, check if there is idle
 * disk. If yes, choose the idle disk.
 */
static bool should_choose_next(struct r1conf *conf, int disk)
{
	struct raid1_info *mirror = &conf->mirrors[disk];
	int opt_iosize;

	if (!test_bit(Nonrot, &mirror->rdev->flags))
		return false;

	opt_iosize = bdev_io_opt(mirror->rdev->bdev) >> 9;
	return opt_iosize > 0 && mirror->seq_start != MaxSector &&
	       mirror->next_seq_sect > opt_iosize &&
	       mirror->next_seq_sect - opt_iosize >= mirror->seq_start;
}

733
static bool rdev_readable(struct md_rdev *rdev, struct r1bio *r1_bio)
Linus Torvalds's avatar
Linus Torvalds committed
734
{
735 736
	if (!rdev || test_bit(Faulty, &rdev->flags))
		return false;
737

738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772
	/* still in recovery */
	if (!test_bit(In_sync, &rdev->flags) &&
	    rdev->recovery_offset < r1_bio->sector + r1_bio->sectors)
		return false;

	/* don't read from slow disk unless have to */
	if (test_bit(WriteMostly, &rdev->flags))
		return false;

	/* don't split IO for bad blocks unless have to */
	if (rdev_has_badblock(rdev, r1_bio->sector, r1_bio->sectors))
		return false;

	return true;
}

struct read_balance_ctl {
	sector_t closest_dist;
	int closest_dist_disk;
	int min_pending;
	int min_pending_disk;
	int sequential_disk;
	int readable_disks;
};

static int choose_best_rdev(struct r1conf *conf, struct r1bio *r1_bio)
{
	int disk;
	struct read_balance_ctl ctl = {
		.closest_dist_disk      = -1,
		.closest_dist           = MaxSector,
		.min_pending_disk       = -1,
		.min_pending            = UINT_MAX,
		.sequential_disk	= -1,
	};
773

774
	for (disk = 0 ; disk < conf->raid_disks * 2 ; disk++) {
775
		struct md_rdev *rdev;
NeilBrown's avatar
NeilBrown committed
776
		sector_t dist;
777
		unsigned int pending;
778

779
		if (r1_bio->bios[disk] == IO_BLOCKED)
NeilBrown's avatar
NeilBrown committed
780
			continue;
781 782 783

		rdev = conf->mirrors[disk].rdev;
		if (!rdev_readable(rdev, r1_bio))
784 785
			continue;

786 787
		/* At least two disks to choose from so failfast is OK */
		if (ctl.readable_disks++ == 1)
788 789
			set_bit(R1BIO_FailFast, &r1_bio->state);

790
		pending = atomic_read(&rdev->nr_pending);
791 792
		dist = abs(r1_bio->sector - conf->mirrors[disk].head_position);

793
		/* Don't change to another disk for sequential reads */
794
		if (is_sequential(conf, disk, r1_bio)) {
795 796 797
			if (!should_choose_next(conf, disk))
				return disk;

798 799 800 801 802 803 804 805 806
			/*
			 * Add 'pending' to avoid choosing this disk if
			 * there is other idle disk.
			 */
			pending++;
			/*
			 * If there is no other idle disk, this disk
			 * will be chosen.
			 */
807
			ctl.sequential_disk = disk;
808 809
		}

810 811 812
		if (ctl.min_pending > pending) {
			ctl.min_pending = pending;
			ctl.min_pending_disk = disk;
813 814
		}

815 816 817
		if (ctl.closest_dist > dist) {
			ctl.closest_dist = dist;
			ctl.closest_dist_disk = disk;
Linus Torvalds's avatar
Linus Torvalds committed
818
		}
819
	}
Linus Torvalds's avatar
Linus Torvalds committed
820

821 822 823 824
	/*
	 * sequential IO size exceeds optimal iosize, however, there is no other
	 * idle disk, so choose the sequential disk.
	 */
825 826
	if (ctl.sequential_disk != -1 && ctl.min_pending != 0)
		return ctl.sequential_disk;
827

828 829 830 831 832 833
	/*
	 * If all disks are rotational, choose the closest disk. If any disk is
	 * non-rotational, choose the disk with less pending request even the
	 * disk is rotational, which might/might not be optimal for raids with
	 * mixed ratation/non-rotational disks depending on workload.
	 */
834 835 836 837 838 839
	if (ctl.min_pending_disk != -1 &&
	    (READ_ONCE(conf->nonrot_disks) || ctl.min_pending == 0))
		return ctl.min_pending_disk;
	else
		return ctl.closest_dist_disk;
}
840

841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862
/*
 * This routine returns the disk from which the requested read should be done.
 *
 * 1) If resync is in progress, find the first usable disk and use it even if it
 * has some bad blocks.
 *
 * 2) Now that there is no resync, loop through all disks and skipping slow
 * disks and disks with bad blocks for now. Only pay attention to key disk
 * choice.
 *
 * 3) If we've made it this far, now look for disks with bad blocks and choose
 * the one with most number of sectors.
 *
 * 4) If we are all the way at the end, we have no choice but to use a disk even
 * if it is write mostly.
 *
 * The rdev for the device selected will have nr_pending incremented.
 */
static int read_balance(struct r1conf *conf, struct r1bio *r1_bio,
			int *max_sectors)
{
	int disk;
863

864
	clear_bit(R1BIO_FailFast, &r1_bio->state);
Linus Torvalds's avatar
Linus Torvalds committed
865

866 867 868 869 870 871 872 873 874 875 876
	if (raid1_should_read_first(conf->mddev, r1_bio->sector,
				    r1_bio->sectors))
		return choose_first_rdev(conf, r1_bio, max_sectors);

	disk = choose_best_rdev(conf, r1_bio);
	if (disk >= 0) {
		*max_sectors = r1_bio->sectors;
		update_read_sectors(conf, disk, r1_bio->sector,
				    r1_bio->sectors);
		return disk;
	}
877

878 879 880 881 882 883 884 885 886
	/*
	 * If we are here it means we didn't find a perfectly good disk so
	 * now spend a bit more time trying to find one with the most good
	 * sectors.
	 */
	disk = choose_bb_rdev(conf, r1_bio, max_sectors);
	if (disk >= 0)
		return disk;

887
	return choose_slow_rdev(conf, r1_bio, max_sectors);
Linus Torvalds's avatar
Linus Torvalds committed
888 889
}

890 891 892 893 894 895
static void wake_up_barrier(struct r1conf *conf)
{
	if (wq_has_sleeper(&conf->wait_barrier))
		wake_up(&conf->wait_barrier);
}

896 897 898
static void flush_bio_list(struct r1conf *conf, struct bio *bio)
{
	/* flush any pending bitmap writes to disk before proceeding w/ I/O */
899
	raid1_prepare_flush_writes(conf->mddev);
900
	wake_up_barrier(conf);
901 902 903

	while (bio) { /* submit pending writes */
		struct bio *next = bio->bi_next;
904 905

		raid1_submit_write(bio);
906
		bio = next;
907
		cond_resched();
908 909 910
	}
}

911
static void flush_pending_writes(struct r1conf *conf)
912 913 914 915 916 917 918
{
	/* Any writes that have been queued but are awaiting
	 * bitmap updates get flushed here.
	 */
	spin_lock_irq(&conf->device_lock);

	if (conf->pending_bio_list.head) {
919
		struct blk_plug plug;
920
		struct bio *bio;
921

922 923
		bio = bio_list_get(&conf->pending_bio_list);
		spin_unlock_irq(&conf->device_lock);
924 925 926 927 928 929 930 931 932 933 934

		/*
		 * As this is called in a wait_event() loop (see freeze_array),
		 * current->state might be TASK_UNINTERRUPTIBLE which will
		 * cause a warning when we prepare to wait again.  As it is
		 * rare that this path is taken, it is perfectly safe to force
		 * us to go around the wait_event() loop again, so the warning
		 * is a false-positive.  Silence the warning by resetting
		 * thread state
		 */
		__set_current_state(TASK_RUNNING);
935
		blk_start_plug(&plug);
936
		flush_bio_list(conf, bio);
937
		blk_finish_plug(&plug);
938 939
	} else
		spin_unlock_irq(&conf->device_lock);
940 941
}

942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961
/* Barriers....
 * Sometimes we need to suspend IO while we do something else,
 * either some resync/recovery, or reconfigure the array.
 * To do this we raise a 'barrier'.
 * The 'barrier' is a counter that can be raised multiple times
 * to count how many activities are happening which preclude
 * normal IO.
 * We can only raise the barrier if there is no pending IO.
 * i.e. if nr_pending == 0.
 * We choose only to raise the barrier if no-one is waiting for the
 * barrier to go down.  This means that as soon as an IO request
 * is ready, no other operations which require a barrier will start
 * until the IO request has had a chance.
 *
 * So: regular IO calls 'wait_barrier'.  When that returns there
 *    is no backgroup IO happening,  It must arrange to call
 *    allow_barrier when it has finished its IO.
 * backgroup IO calls must call raise_barrier.  Once that returns
 *    there is no normal IO happeing.  It must arrange to call
 *    lower_barrier when the particular background IO completes.
962 963 964
 *
 * If resync/recovery is interrupted, returns -EINTR;
 * Otherwise, returns 0.
Linus Torvalds's avatar
Linus Torvalds committed
965
 */
966
static int raise_barrier(struct r1conf *conf, sector_t sector_nr)
Linus Torvalds's avatar
Linus Torvalds committed
967
{
968 969
	int idx = sector_to_idx(sector_nr);

Linus Torvalds's avatar
Linus Torvalds committed
970
	spin_lock_irq(&conf->resync_lock);
971 972

	/* Wait until no block IO is waiting */
973 974
	wait_event_lock_irq(conf->wait_barrier,
			    !atomic_read(&conf->nr_waiting[idx]),
975
			    conf->resync_lock);
976 977

	/* block any new IO from starting */
978 979 980 981 982 983 984 985 986 987
	atomic_inc(&conf->barrier[idx]);
	/*
	 * In raise_barrier() we firstly increase conf->barrier[idx] then
	 * check conf->nr_pending[idx]. In _wait_barrier() we firstly
	 * increase conf->nr_pending[idx] then check conf->barrier[idx].
	 * A memory barrier here to make sure conf->nr_pending[idx] won't
	 * be fetched before conf->barrier[idx] is increased. Otherwise
	 * there will be a race between raise_barrier() and _wait_barrier().
	 */
	smp_mb__after_atomic();
988

989 990
	/* For these conditions we must wait:
	 * A: while the array is in frozen state
991 992 993 994
	 * B: while conf->nr_pending[idx] is not 0, meaning regular I/O
	 *    existing in corresponding I/O barrier bucket.
	 * C: while conf->barrier[idx] >= RESYNC_DEPTH, meaning reaches
	 *    max resync count which allowed on current I/O barrier bucket.
995
	 */
996
	wait_event_lock_irq(conf->wait_barrier,
997
			    (!conf->array_frozen &&
998
			     !atomic_read(&conf->nr_pending[idx]) &&
999 1000
			     atomic_read(&conf->barrier[idx]) < RESYNC_DEPTH) ||
				test_bit(MD_RECOVERY_INTR, &conf->mddev->recovery),
1001
			    conf->resync_lock);
1002

1003 1004 1005 1006 1007 1008 1009
	if (test_bit(MD_RECOVERY_INTR, &conf->mddev->recovery)) {
		atomic_dec(&conf->barrier[idx]);
		spin_unlock_irq(&conf->resync_lock);
		wake_up(&conf->wait_barrier);
		return -EINTR;
	}

1010
	atomic_inc(&conf->nr_sync_pending);
1011
	spin_unlock_irq(&conf->resync_lock);
1012 1013

	return 0;
1014 1015
}

1016
static void lower_barrier(struct r1conf *conf, sector_t sector_nr)
1017
{
1018 1019
	int idx = sector_to_idx(sector_nr);

1020
	BUG_ON(atomic_read(&conf->barrier[idx]) <= 0);
1021

1022
	atomic_dec(&conf->barrier[idx]);
1023
	atomic_dec(&conf->nr_sync_pending);
1024 1025 1026
	wake_up(&conf->wait_barrier);
}

1027
static bool _wait_barrier(struct r1conf *conf, int idx, bool nowait)
1028
{
1029 1030
	bool ret = true;

1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048
	/*
	 * We need to increase conf->nr_pending[idx] very early here,
	 * then raise_barrier() can be blocked when it waits for
	 * conf->nr_pending[idx] to be 0. Then we can avoid holding
	 * conf->resync_lock when there is no barrier raised in same
	 * barrier unit bucket. Also if the array is frozen, I/O
	 * should be blocked until array is unfrozen.
	 */
	atomic_inc(&conf->nr_pending[idx]);
	/*
	 * In _wait_barrier() we firstly increase conf->nr_pending[idx], then
	 * check conf->barrier[idx]. In raise_barrier() we firstly increase
	 * conf->barrier[idx], then check conf->nr_pending[idx]. A memory
	 * barrier is necessary here to make sure conf->barrier[idx] won't be
	 * fetched before conf->nr_pending[idx] is increased. Otherwise there
	 * will be a race between _wait_barrier() and raise_barrier().
	 */
	smp_mb__after_atomic();
1049

1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060
	/*
	 * Don't worry about checking two atomic_t variables at same time
	 * here. If during we check conf->barrier[idx], the array is
	 * frozen (conf->array_frozen is 1), and chonf->barrier[idx] is
	 * 0, it is safe to return and make the I/O continue. Because the
	 * array is frozen, all I/O returned here will eventually complete
	 * or be queued, no race will happen. See code comment in
	 * frozen_array().
	 */
	if (!READ_ONCE(conf->array_frozen) &&
	    !atomic_read(&conf->barrier[idx]))
1061
		return ret;
1062

1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076
	/*
	 * After holding conf->resync_lock, conf->nr_pending[idx]
	 * should be decreased before waiting for barrier to drop.
	 * Otherwise, we may encounter a race condition because
	 * raise_barrer() might be waiting for conf->nr_pending[idx]
	 * to be 0 at same time.
	 */
	spin_lock_irq(&conf->resync_lock);
	atomic_inc(&conf->nr_waiting[idx]);
	atomic_dec(&conf->nr_pending[idx]);
	/*
	 * In case freeze_array() is waiting for
	 * get_unqueued_pending() == extra
	 */
1077
	wake_up_barrier(conf);
1078
	/* Wait for the barrier in same barrier unit bucket to drop. */
1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090

	/* Return false when nowait flag is set */
	if (nowait) {
		ret = false;
	} else {
		wait_event_lock_irq(conf->wait_barrier,
				!conf->array_frozen &&
				!atomic_read(&conf->barrier[idx]),
				conf->resync_lock);
		atomic_inc(&conf->nr_pending[idx]);
	}

1091
	atomic_dec(&conf->nr_waiting[idx]);
1092
	spin_unlock_irq(&conf->resync_lock);
1093
	return ret;
1094 1095
}

1096
static bool wait_read_barrier(struct r1conf *conf, sector_t sector_nr, bool nowait)
1097
{
1098
	int idx = sector_to_idx(sector_nr);
1099
	bool ret = true;
1100

1101 1102 1103 1104 1105 1106 1107 1108
	/*
	 * Very similar to _wait_barrier(). The difference is, for read
	 * I/O we don't need wait for sync I/O, but if the whole array
	 * is frozen, the read I/O still has to wait until the array is
	 * unfrozen. Since there is no ordering requirement with
	 * conf->barrier[idx] here, memory barrier is unnecessary as well.
	 */
	atomic_inc(&conf->nr_pending[idx]);
1109

1110
	if (!READ_ONCE(conf->array_frozen))
1111
		return ret;
1112 1113 1114 1115 1116 1117 1118 1119

	spin_lock_irq(&conf->resync_lock);
	atomic_inc(&conf->nr_waiting[idx]);
	atomic_dec(&conf->nr_pending[idx]);
	/*
	 * In case freeze_array() is waiting for
	 * get_unqueued_pending() == extra
	 */
1120
	wake_up_barrier(conf);
1121
	/* Wait for array to be unfrozen */
1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133

	/* Return false when nowait flag is set */
	if (nowait) {
		/* Return false when nowait flag is set */
		ret = false;
	} else {
		wait_event_lock_irq(conf->wait_barrier,
				!conf->array_frozen,
				conf->resync_lock);
		atomic_inc(&conf->nr_pending[idx]);
	}

1134
	atomic_dec(&conf->nr_waiting[idx]);
Linus Torvalds's avatar
Linus Torvalds committed
1135
	spin_unlock_irq(&conf->resync_lock);
1136
	return ret;
Linus Torvalds's avatar
Linus Torvalds committed
1137 1138
}

1139
static bool wait_barrier(struct r1conf *conf, sector_t sector_nr, bool nowait)
1140
{
1141
	int idx = sector_to_idx(sector_nr);
1142

1143
	return _wait_barrier(conf, idx, nowait);
1144 1145 1146
}

static void _allow_barrier(struct r1conf *conf, int idx)
1147
{
1148
	atomic_dec(&conf->nr_pending[idx]);
1149
	wake_up_barrier(conf);
1150 1151
}

1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163
static void allow_barrier(struct r1conf *conf, sector_t sector_nr)
{
	int idx = sector_to_idx(sector_nr);

	_allow_barrier(conf, idx);
}

/* conf->resync_lock should be held */
static int get_unqueued_pending(struct r1conf *conf)
{
	int idx, ret;

1164 1165
	ret = atomic_read(&conf->nr_sync_pending);
	for (idx = 0; idx < BARRIER_BUCKETS_NR; idx++)
1166 1167
		ret += atomic_read(&conf->nr_pending[idx]) -
			atomic_read(&conf->nr_queued[idx]);
1168 1169 1170 1171

	return ret;
}

1172
static void freeze_array(struct r1conf *conf, int extra)
1173
{
1174
	/* Stop sync I/O and normal I/O and wait for everything to
1175
	 * go quiet.
1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195
	 * This is called in two situations:
	 * 1) management command handlers (reshape, remove disk, quiesce).
	 * 2) one normal I/O request failed.

	 * After array_frozen is set to 1, new sync IO will be blocked at
	 * raise_barrier(), and new normal I/O will blocked at _wait_barrier()
	 * or wait_read_barrier(). The flying I/Os will either complete or be
	 * queued. When everything goes quite, there are only queued I/Os left.

	 * Every flying I/O contributes to a conf->nr_pending[idx], idx is the
	 * barrier bucket index which this I/O request hits. When all sync and
	 * normal I/O are queued, sum of all conf->nr_pending[] will match sum
	 * of all conf->nr_queued[]. But normal I/O failure is an exception,
	 * in handle_read_error(), we may call freeze_array() before trying to
	 * fix the read error. In this case, the error read I/O is not queued,
	 * so get_unqueued_pending() == 1.
	 *
	 * Therefore before this function returns, we need to wait until
	 * get_unqueued_pendings(conf) gets equal to extra. For
	 * normal I/O context, extra is 1, in rested situations extra is 0.
1196 1197
	 */
	spin_lock_irq(&conf->resync_lock);
1198
	conf->array_frozen = 1;
1199
	mddev_add_trace_msg(conf->mddev, "raid1 wait freeze");
1200 1201 1202 1203 1204
	wait_event_lock_irq_cmd(
		conf->wait_barrier,
		get_unqueued_pending(conf) == extra,
		conf->resync_lock,
		flush_pending_writes(conf));
1205 1206
	spin_unlock_irq(&conf->resync_lock);
}
1207
static void unfreeze_array(struct r1conf *conf)
1208 1209 1210
{
	/* reverse the effect of the freeze */
	spin_lock_irq(&conf->resync_lock);
1211
	conf->array_frozen = 0;
1212
	spin_unlock_irq(&conf->resync_lock);
1213
	wake_up(&conf->wait_barrier);
1214 1215
}

1216
static void alloc_behind_master_bio(struct r1bio *r1_bio,
1217
					   struct bio *bio)
1218
{
1219
	int size = bio->bi_iter.bi_size;
Ming Lei's avatar
Ming Lei committed
1220 1221 1222 1223
	unsigned vcnt = (size + PAGE_SIZE - 1) >> PAGE_SHIFT;
	int i = 0;
	struct bio *behind_bio = NULL;

1224 1225
	behind_bio = bio_alloc_bioset(NULL, vcnt, 0, GFP_NOIO,
				      &r1_bio->mddev->bio_set);
1226

1227
	/* discard op, we don't support writezero/writesame yet */
1228 1229
	if (!bio_has_data(bio)) {
		behind_bio->bi_iter.bi_size = size;
1230
		goto skip_copy;
1231
	}
1232

Ming Lei's avatar
Ming Lei committed
1233 1234 1235 1236 1237 1238 1239 1240
	while (i < vcnt && size) {
		struct page *page;
		int len = min_t(int, PAGE_SIZE, size);

		page = alloc_page(GFP_NOIO);
		if (unlikely(!page))
			goto free_pages;

1241 1242 1243 1244
		if (!bio_add_page(behind_bio, page, len, 0)) {
			put_page(page);
			goto free_pages;
		}
Ming Lei's avatar
Ming Lei committed
1245 1246 1247

		size -= len;
		i++;
1248
	}
Ming Lei's avatar
Ming Lei committed
1249

1250
	bio_copy_data(behind_bio, bio);
1251
skip_copy:
1252
	r1_bio->behind_master_bio = behind_bio;
1253
	set_bit(R1BIO_BehindIO, &r1_bio->state);
1254

1255
	return;
Ming Lei's avatar
Ming Lei committed
1256 1257

free_pages:
1258 1259
	pr_debug("%dB behind alloc failed, doing sync I/O\n",
		 bio->bi_iter.bi_size);
Ming Lei's avatar
Ming Lei committed
1260
	bio_free_pages(behind_bio);
1261
	bio_put(behind_bio);
1262 1263
}

1264 1265 1266 1267 1268 1269 1270 1271
static void raid1_unplug(struct blk_plug_cb *cb, bool from_schedule)
{
	struct raid1_plug_cb *plug = container_of(cb, struct raid1_plug_cb,
						  cb);
	struct mddev *mddev = plug->cb.data;
	struct r1conf *conf = mddev->private;
	struct bio *bio;

1272
	if (from_schedule) {
1273 1274 1275
		spin_lock_irq(&conf->device_lock);
		bio_list_merge(&conf->pending_bio_list, &plug->pending);
		spin_unlock_irq(&conf->device_lock);
1276
		wake_up_barrier(conf);
1277 1278 1279 1280 1281 1282 1283
		md_wakeup_thread(mddev->thread);
		kfree(plug);
		return;
	}

	/* we aren't scheduling, so we can do the write-out directly. */
	bio = bio_list_get(&plug->pending);
1284
	flush_bio_list(conf, bio);
1285 1286 1287
	kfree(plug);
}

1288 1289 1290 1291 1292 1293 1294 1295 1296
static void init_r1bio(struct r1bio *r1_bio, struct mddev *mddev, struct bio *bio)
{
	r1_bio->master_bio = bio;
	r1_bio->sectors = bio_sectors(bio);
	r1_bio->state = 0;
	r1_bio->mddev = mddev;
	r1_bio->sector = bio->bi_iter.bi_sector;
}

1297
static inline struct r1bio *
1298
alloc_r1bio(struct mddev *mddev, struct bio *bio)
1299 1300 1301 1302
{
	struct r1conf *conf = mddev->private;
	struct r1bio *r1_bio;

1303
	r1_bio = mempool_alloc(&conf->r1bio_pool, GFP_NOIO);
1304 1305 1306
	/* Ensure no bio records IO_BLOCKED */
	memset(r1_bio->bios, 0, conf->raid_disks * sizeof(r1_bio->bios[0]));
	init_r1bio(r1_bio, mddev, bio);
1307 1308 1309
	return r1_bio;
}

1310
static void raid1_read_request(struct mddev *mddev, struct bio *bio,
1311
			       int max_read_sectors, struct r1bio *r1_bio)
Linus Torvalds's avatar
Linus Torvalds committed
1312
{
1313
	struct r1conf *conf = mddev->private;
1314
	struct raid1_info *mirror;
Linus Torvalds's avatar
Linus Torvalds committed
1315
	struct bio *read_bio;
1316 1317
	const enum req_op op = bio_op(bio);
	const blk_opf_t do_sync = bio->bi_opf & REQ_SYNC;
1318 1319
	int max_sectors;
	int rdisk;
1320
	bool r1bio_existed = !!r1_bio;
1321

1322
	/*
1323 1324 1325
	 * If r1_bio is set, we are blocking the raid1d thread
	 * so there is a tiny risk of deadlock.  So ask for
	 * emergency memory if needed.
1326
	 */
1327
	gfp_t gfp = r1_bio ? (GFP_NOIO | __GFP_HIGH) : GFP_NOIO;
1328 1329 1330 1331 1332

	/*
	 * Still need barrier for READ in case that whole
	 * array is frozen.
	 */
1333 1334 1335 1336 1337
	if (!wait_read_barrier(conf, bio->bi_iter.bi_sector,
				bio->bi_opf & REQ_NOWAIT)) {
		bio_wouldblock_error(bio);
		return;
	}
1338

1339 1340 1341 1342
	if (!r1_bio)
		r1_bio = alloc_r1bio(mddev, bio);
	else
		init_r1bio(r1_bio, mddev, bio);
1343
	r1_bio->sectors = max_read_sectors;
1344 1345 1346 1347 1348

	/*
	 * make_request() can abort the operation when read-ahead is being
	 * used and no empty request is available.
	 */
1349 1350 1351
	rdisk = read_balance(conf, r1_bio, &max_sectors);
	if (rdisk < 0) {
		/* couldn't find anywhere to read from */
1352 1353
		if (r1bio_existed)
			pr_crit_ratelimited("md/raid1:%s: %pg: unrecoverable I/O read error for block %llu\n",
1354
					    mdname(mddev),
1355 1356
					    conf->mirrors[r1_bio->read_disk].rdev->bdev,
					    r1_bio->sector);
1357 1358 1359 1360 1361
		raid_end_bio_io(r1_bio);
		return;
	}
	mirror = conf->mirrors + rdisk;

1362
	if (r1bio_existed)
1363
		pr_info_ratelimited("md/raid1:%s: redirecting sector %llu to other mirror: %pg\n",
1364 1365
				    mdname(mddev),
				    (unsigned long long)r1_bio->sector,
1366
				    mirror->rdev->bdev);
1367

1368
	if (test_bit(WriteMostly, &mirror->rdev->flags)) {
1369 1370 1371 1372
		/*
		 * Reading from a write-mostly device must take care not to
		 * over-take any writes that are 'behind'
		 */
1373
		mddev_add_trace_msg(mddev, "raid1 wait behind writes");
1374
		mddev->bitmap_ops->wait_behind_writes(mddev);
1375
	}
1376 1377 1378

	if (max_sectors < bio_sectors(bio)) {
		struct bio *split = bio_split(bio, max_sectors,
1379
					      gfp, &conf->bio_split);
1380
		bio_chain(split, bio);
1381
		submit_bio_noacct(bio);
1382 1383 1384 1385 1386
		bio = split;
		r1_bio->master_bio = bio;
		r1_bio->sectors = max_sectors;
	}

1387
	r1_bio->read_disk = rdisk;
1388 1389 1390 1391
	if (!r1bio_existed) {
		md_account_bio(mddev, &bio);
		r1_bio->master_bio = bio;
	}
1392 1393
	read_bio = bio_alloc_clone(mirror->rdev->bdev, bio, gfp,
				   &mddev->bio_set);
1394 1395 1396 1397 1398 1399

	r1_bio->bios[rdisk] = read_bio;

	read_bio->bi_iter.bi_sector = r1_bio->sector +
		mirror->rdev->data_offset;
	read_bio->bi_end_io = raid1_end_read_request;
1400
	read_bio->bi_opf = op | do_sync;
1401 1402 1403 1404
	if (test_bit(FailFast, &mirror->rdev->flags) &&
	    test_bit(R1BIO_FailFast, &r1_bio->state))
	        read_bio->bi_opf |= MD_FAILFAST;
	read_bio->bi_private = r1_bio;
1405
	mddev_trace_remap(mddev, read_bio, r1_bio->sector);
1406
	submit_bio_noacct(read_bio);
1407 1408
}

1409 1410
static void raid1_write_request(struct mddev *mddev, struct bio *bio,
				int max_write_sectors)
1411 1412
{
	struct r1conf *conf = mddev->private;
1413
	struct r1bio *r1_bio;
1414
	int i, disks;
1415
	unsigned long flags;
1416
	struct md_rdev *blocked_rdev;
1417 1418
	int first_clone;
	int max_sectors;
1419
	bool write_behind = false;
1420
	bool is_discard = (bio_op(bio) == REQ_OP_DISCARD);
1421

1422
	if (mddev_is_clustered(mddev) &&
1423
	     md_cluster_ops->area_resyncing(mddev, WRITE,
1424
		     bio->bi_iter.bi_sector, bio_end_sector(bio))) {
1425

1426
		DEFINE_WAIT(w);
1427 1428 1429 1430
		if (bio->bi_opf & REQ_NOWAIT) {
			bio_wouldblock_error(bio);
			return;
		}
1431 1432
		for (;;) {
			prepare_to_wait(&conf->wait_barrier,
1433
					&w, TASK_IDLE);
1434
			if (!md_cluster_ops->area_resyncing(mddev, WRITE,
1435
							bio->bi_iter.bi_sector,
1436
							bio_end_sector(bio)))
1437 1438 1439 1440 1441
				break;
			schedule();
		}
		finish_wait(&conf->wait_barrier, &w);
	}
1442 1443 1444 1445 1446 1447

	/*
	 * Register the new request and wait if the reconstruction
	 * thread has put up a bar for new requests.
	 * Continue immediately if no resync is active currently.
	 */
1448 1449 1450 1451 1452
	if (!wait_barrier(conf, bio->bi_iter.bi_sector,
				bio->bi_opf & REQ_NOWAIT)) {
		bio_wouldblock_error(bio);
		return;
	}
1453

1454
 retry_write:
1455
	r1_bio = alloc_r1bio(mddev, bio);
1456
	r1_bio->sectors = max_write_sectors;
Linus Torvalds's avatar
Linus Torvalds committed
1457

1458
	/* first select target devices under rcu_lock and
Linus Torvalds's avatar
Linus Torvalds committed
1459 1460
	 * inc refcount on their rdev.  Record them by setting
	 * bios[x] to bio
1461 1462 1463 1464 1465 1466
	 * If there are known/acknowledged bad blocks on any device on
	 * which we have seen a write error, we want to avoid writing those
	 * blocks.
	 * This potentially requires several writes to write around
	 * the bad blocks.  Each set of writes gets it's own r1bio
	 * with a set of bios attached.
Linus Torvalds's avatar
Linus Torvalds committed
1467
	 */
1468

1469
	disks = conf->raid_disks * 2;
1470
	blocked_rdev = NULL;
1471
	max_sectors = r1_bio->sectors;
Linus Torvalds's avatar
Linus Torvalds committed
1472
	for (i = 0;  i < disks; i++) {
1473
		struct md_rdev *rdev = conf->mirrors[i].rdev;
1474 1475 1476 1477 1478 1479

		/*
		 * The write-behind io is only attempted on drives marked as
		 * write-mostly, which means we could allocate write behind
		 * bio later.
		 */
1480
		if (!is_discard && rdev && test_bit(WriteMostly, &rdev->flags))
1481 1482
			write_behind = true;

1483 1484 1485 1486 1487
		if (rdev && unlikely(test_bit(Blocked, &rdev->flags))) {
			atomic_inc(&rdev->nr_pending);
			blocked_rdev = rdev;
			break;
		}
1488
		r1_bio->bios[i] = NULL;
1489
		if (!rdev || test_bit(Faulty, &rdev->flags)) {
1490 1491
			if (i < conf->raid_disks)
				set_bit(R1BIO_Degraded, &r1_bio->state);
1492 1493 1494 1495 1496 1497 1498 1499 1500
			continue;
		}

		atomic_inc(&rdev->nr_pending);
		if (test_bit(WriteErrorSeen, &rdev->flags)) {
			sector_t first_bad;
			int bad_sectors;
			int is_bad;

1501
			is_bad = is_badblock(rdev, r1_bio->sector, max_sectors,
1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517
					     &first_bad, &bad_sectors);
			if (is_bad < 0) {
				/* mustn't write here until the bad block is
				 * acknowledged*/
				set_bit(BlockedBadBlocks, &rdev->flags);
				blocked_rdev = rdev;
				break;
			}
			if (is_bad && first_bad <= r1_bio->sector) {
				/* Cannot write here at all */
				bad_sectors -= (r1_bio->sector - first_bad);
				if (bad_sectors < max_sectors)
					/* mustn't write more than bad_sectors
					 * to other devices yet
					 */
					max_sectors = bad_sectors;
1518
				rdev_dec_pending(rdev, mddev);
1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529
				/* We don't set R1BIO_Degraded as that
				 * only applies if the disk is
				 * missing, so it might be re-added,
				 * and we want to know to recover this
				 * chunk.
				 * In this case the device is here,
				 * and the fact that this chunk is not
				 * in-sync is recorded in the bad
				 * block log
				 */
				continue;
1530
			}
1531 1532 1533 1534 1535 1536 1537
			if (is_bad) {
				int good_sectors = first_bad - r1_bio->sector;
				if (good_sectors < max_sectors)
					max_sectors = good_sectors;
			}
		}
		r1_bio->bios[i] = bio;
Linus Torvalds's avatar
Linus Torvalds committed
1538 1539
	}

1540 1541 1542 1543 1544 1545 1546
	if (unlikely(blocked_rdev)) {
		/* Wait for this device to become unblocked */
		int j;

		for (j = 0; j < i; j++)
			if (r1_bio->bios[j])
				rdev_dec_pending(conf->mirrors[j].rdev, mddev);
1547
		mempool_free(r1_bio, &conf->r1bio_pool);
1548
		allow_barrier(conf, bio->bi_iter.bi_sector);
1549 1550 1551 1552 1553

		if (bio->bi_opf & REQ_NOWAIT) {
			bio_wouldblock_error(bio);
			return;
		}
1554 1555
		mddev_add_trace_msg(mddev, "raid1 wait rdev %d blocked",
				blocked_rdev->raid_disk);
1556
		md_wait_for_blocked_rdev(blocked_rdev, mddev);
1557
		wait_barrier(conf, bio->bi_iter.bi_sector, false);
1558 1559 1560
		goto retry_write;
	}

1561 1562 1563 1564 1565 1566
	/*
	 * When using a bitmap, we may call alloc_behind_master_bio below.
	 * alloc_behind_master_bio allocates a copy of the data payload a page
	 * at a time and thus needs a new bio that can fit the whole payload
	 * this bio in page sized chunks.
	 */
1567
	if (write_behind && mddev->bitmap)
1568 1569
		max_sectors = min_t(int, max_sectors,
				    BIO_MAX_VECS * (PAGE_SIZE >> 9));
1570 1571
	if (max_sectors < bio_sectors(bio)) {
		struct bio *split = bio_split(bio, max_sectors,
1572
					      GFP_NOIO, &conf->bio_split);
1573
		bio_chain(split, bio);
1574
		submit_bio_noacct(bio);
1575 1576
		bio = split;
		r1_bio->master_bio = bio;
1577
		r1_bio->sectors = max_sectors;
1578
	}
1579

1580 1581
	md_account_bio(mddev, &bio);
	r1_bio->master_bio = bio;
1582
	atomic_set(&r1_bio->remaining, 1);
1583
	atomic_set(&r1_bio->behind_remaining, 0);
1584

1585
	first_clone = 1;
1586

Linus Torvalds's avatar
Linus Torvalds committed
1587
	for (i = 0; i < disks; i++) {
1588
		struct bio *mbio = NULL;
1589
		struct md_rdev *rdev = conf->mirrors[i].rdev;
Linus Torvalds's avatar
Linus Torvalds committed
1590 1591 1592
		if (!r1_bio->bios[i])
			continue;

1593
		if (first_clone) {
1594 1595 1596 1597 1598
			unsigned long max_write_behind =
				mddev->bitmap_info.max_write_behind;
			struct md_bitmap_stats stats;
			int err;

1599 1600 1601 1602
			/* do behind I/O ?
			 * Not if there are too many, or cannot
			 * allocate memory, or a reader on WriteMostly
			 * is waiting for behind writes to flush */
1603
			err = mddev->bitmap_ops->get_stats(mddev->bitmap, &stats);
1604 1605
			if (!err && write_behind && !stats.behind_wait &&
			    stats.behind_writes < max_write_behind)
1606
				alloc_behind_master_bio(r1_bio, bio);
1607

1608 1609 1610
			mddev->bitmap_ops->startwrite(
				mddev, r1_bio->sector, r1_bio->sectors,
				test_bit(R1BIO_BehindIO, &r1_bio->state));
1611 1612
			first_clone = 0;
		}
1613

Ming Lei's avatar
Ming Lei committed
1614
		if (r1_bio->behind_master_bio) {
1615 1616 1617
			mbio = bio_alloc_clone(rdev->bdev,
					       r1_bio->behind_master_bio,
					       GFP_NOIO, &mddev->bio_set);
1618
			if (test_bit(CollisionCheck, &rdev->flags))
1619
				wait_for_serialization(rdev, r1_bio);
1620
			if (test_bit(WriteMostly, &rdev->flags))
1621
				atomic_inc(&r1_bio->behind_remaining);
1622 1623 1624 1625 1626 1627 1628
		} else {
			mbio = bio_alloc_clone(rdev->bdev, bio, GFP_NOIO,
					       &mddev->bio_set);

			if (mddev->serialize_policy)
				wait_for_serialization(rdev, r1_bio);
		}
1629

1630 1631
		r1_bio->bios[i] = mbio;

1632
		mbio->bi_iter.bi_sector	= (r1_bio->sector + rdev->data_offset);
1633
		mbio->bi_end_io	= raid1_end_write_request;
1634
		mbio->bi_opf = bio_op(bio) | (bio->bi_opf & (REQ_SYNC | REQ_FUA));
1635 1636
		if (test_bit(FailFast, &rdev->flags) &&
		    !test_bit(WriteMostly, &rdev->flags) &&
1637 1638
		    conf->raid_disks - mddev->degraded > 1)
			mbio->bi_opf |= MD_FAILFAST;
1639 1640
		mbio->bi_private = r1_bio;

Linus Torvalds's avatar
Linus Torvalds committed
1641
		atomic_inc(&r1_bio->remaining);
1642
		mddev_trace_remap(mddev, mbio, r1_bio->sector);
1643
		/* flush_pending_writes() needs access to the rdev so...*/
1644
		mbio->bi_bdev = (void *)rdev;
1645
		if (!raid1_add_bio_to_plug(mddev, mbio, raid1_unplug, disks)) {
1646
			spin_lock_irqsave(&conf->device_lock, flags);
1647
			bio_list_add(&conf->pending_bio_list, mbio);
1648
			spin_unlock_irqrestore(&conf->device_lock, flags);
NeilBrown's avatar
NeilBrown committed
1649
			md_wakeup_thread(mddev->thread);
1650
		}
Linus Torvalds's avatar
Linus Torvalds committed
1651
	}
1652

1653 1654 1655
	r1_bio_write_done(r1_bio);

	/* In case raid1d snuck in to freeze_array */
1656
	wake_up_barrier(conf);
Linus Torvalds's avatar
Linus Torvalds committed
1657 1658
}

1659
static bool raid1_make_request(struct mddev *mddev, struct bio *bio)
1660
{
1661
	sector_t sectors;
1662

1663 1664
	if (unlikely(bio->bi_opf & REQ_PREFLUSH)
	    && md_flush_request(mddev, bio))
1665
		return true;
1666

1667 1668 1669 1670 1671 1672 1673 1674 1675
	/*
	 * There is a limit to the maximum size, but
	 * the read/write handler might find a lower limit
	 * due to bad blocks.  To avoid multiple splits,
	 * we pass the maximum number of sectors down
	 * and let the lower level perform the split.
	 */
	sectors = align_to_barrier_unit_end(
		bio->bi_iter.bi_sector, bio_sectors(bio));
1676

1677
	if (bio_data_dir(bio) == READ)
1678
		raid1_read_request(mddev, bio, sectors, NULL);
1679
	else {
1680
		md_write_start(mddev,bio);
1681
		raid1_write_request(mddev, bio, sectors);
1682 1683
	}
	return true;
1684 1685
}

Shaohua Li's avatar
Shaohua Li committed
1686
static void raid1_status(struct seq_file *seq, struct mddev *mddev)
Linus Torvalds's avatar
Linus Torvalds committed
1687
{
1688
	struct r1conf *conf = mddev->private;
Linus Torvalds's avatar
Linus Torvalds committed
1689 1690
	int i;

1691 1692
	lockdep_assert_held(&mddev->lock);

Linus Torvalds's avatar
Linus Torvalds committed
1693
	seq_printf(seq, " [%d/%d] [", conf->raid_disks,
1694
		   conf->raid_disks - mddev->degraded);
1695
	for (i = 0; i < conf->raid_disks; i++) {
1696 1697
		struct md_rdev *rdev = READ_ONCE(conf->mirrors[i].rdev);

Linus Torvalds's avatar
Linus Torvalds committed
1698
		seq_printf(seq, "%s",
1699 1700
			   rdev && test_bit(In_sync, &rdev->flags) ? "U" : "_");
	}
Linus Torvalds's avatar
Linus Torvalds committed
1701 1702 1703
	seq_printf(seq, "]");
}

1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719
/**
 * raid1_error() - RAID1 error handler.
 * @mddev: affected md device.
 * @rdev: member device to fail.
 *
 * The routine acknowledges &rdev failure and determines new @mddev state.
 * If it failed, then:
 *	- &MD_BROKEN flag is set in &mddev->flags.
 *	- recovery is disabled.
 * Otherwise, it must be degraded:
 *	- recovery is interrupted.
 *	- &mddev->degraded is bumped.
 *
 * @rdev is marked as &Faulty excluding case when array is failed and
 * &mddev->fail_last_dev is off.
 */
Shaohua Li's avatar
Shaohua Li committed
1720
static void raid1_error(struct mddev *mddev, struct md_rdev *rdev)
Linus Torvalds's avatar
Linus Torvalds committed
1721
{
1722
	struct r1conf *conf = mddev->private;
1723
	unsigned long flags;
Linus Torvalds's avatar
Linus Torvalds committed
1724

1725
	spin_lock_irqsave(&conf->device_lock, flags);
1726 1727 1728 1729 1730 1731 1732 1733 1734 1735

	if (test_bit(In_sync, &rdev->flags) &&
	    (conf->raid_disks - mddev->degraded) == 1) {
		set_bit(MD_BROKEN, &mddev->flags);

		if (!mddev->fail_last_dev) {
			conf->recovery_disabled = mddev->recovery_disabled;
			spin_unlock_irqrestore(&conf->device_lock, flags);
			return;
		}
1736
	}
1737
	set_bit(Blocked, &rdev->flags);
1738
	if (test_and_clear_bit(In_sync, &rdev->flags))
Linus Torvalds's avatar
Linus Torvalds committed
1739
		mddev->degraded++;
1740
	set_bit(Faulty, &rdev->flags);
1741
	spin_unlock_irqrestore(&conf->device_lock, flags);
1742 1743 1744 1745
	/*
	 * if recovery is running, make sure it aborts.
	 */
	set_bit(MD_RECOVERY_INTR, &mddev->recovery);
1746 1747
	set_mask_bits(&mddev->sb_flags, 0,
		      BIT(MD_SB_CHANGE_DEVS) | BIT(MD_SB_CHANGE_PENDING));
1748
	pr_crit("md/raid1:%s: Disk failure on %pg, disabling device.\n"
1749
		"md/raid1:%s: Operation continuing on %d devices.\n",
1750
		mdname(mddev), rdev->bdev,
1751
		mdname(mddev), conf->raid_disks - mddev->degraded);
Linus Torvalds's avatar
Linus Torvalds committed
1752 1753
}

1754
static void print_conf(struct r1conf *conf)
Linus Torvalds's avatar
Linus Torvalds committed
1755 1756 1757
{
	int i;

1758
	pr_debug("RAID1 conf printout:\n");
Linus Torvalds's avatar
Linus Torvalds committed
1759
	if (!conf) {
1760
		pr_debug("(!conf)\n");
Linus Torvalds's avatar
Linus Torvalds committed
1761 1762
		return;
	}
1763 1764
	pr_debug(" --- wd:%d rd:%d\n", conf->raid_disks - conf->mddev->degraded,
		 conf->raid_disks);
Linus Torvalds's avatar
Linus Torvalds committed
1765

1766
	lockdep_assert_held(&conf->mddev->reconfig_mutex);
Linus Torvalds's avatar
Linus Torvalds committed
1767
	for (i = 0; i < conf->raid_disks; i++) {
1768
		struct md_rdev *rdev = conf->mirrors[i].rdev;
1769
		if (rdev)
1770
			pr_debug(" disk %d, wo:%d, o:%d, dev:%pg\n",
1771 1772
				 i, !test_bit(In_sync, &rdev->flags),
				 !test_bit(Faulty, &rdev->flags),
1773
				 rdev->bdev);
Linus Torvalds's avatar
Linus Torvalds committed
1774 1775 1776
	}
}

1777
static void close_sync(struct r1conf *conf)
Linus Torvalds's avatar
Linus Torvalds committed
1778
{
1779 1780 1781
	int idx;

	for (idx = 0; idx < BARRIER_BUCKETS_NR; idx++) {
1782
		_wait_barrier(conf, idx, false);
1783 1784
		_allow_barrier(conf, idx);
	}
Linus Torvalds's avatar
Linus Torvalds committed
1785

1786
	mempool_exit(&conf->r1buf_pool);
Linus Torvalds's avatar
Linus Torvalds committed
1787 1788
}

1789
static int raid1_spare_active(struct mddev *mddev)
Linus Torvalds's avatar
Linus Torvalds committed
1790 1791
{
	int i;
1792
	struct r1conf *conf = mddev->private;
1793 1794
	int count = 0;
	unsigned long flags;
Linus Torvalds's avatar
Linus Torvalds committed
1795 1796

	/*
1797
	 * Find all failed disks within the RAID1 configuration
1798 1799
	 * and mark them readable.
	 * Called under mddev lock, so rcu protection not needed.
1800 1801
	 * device_lock used to avoid races with raid1_end_read_request
	 * which expects 'In_sync' flags and ->degraded to be consistent.
Linus Torvalds's avatar
Linus Torvalds committed
1802
	 */
1803
	spin_lock_irqsave(&conf->device_lock, flags);
Linus Torvalds's avatar
Linus Torvalds committed
1804
	for (i = 0; i < conf->raid_disks; i++) {
1805
		struct md_rdev *rdev = conf->mirrors[i].rdev;
1806 1807
		struct md_rdev *repl = conf->mirrors[conf->raid_disks + i].rdev;
		if (repl
1808
		    && !test_bit(Candidate, &repl->flags)
1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825
		    && repl->recovery_offset == MaxSector
		    && !test_bit(Faulty, &repl->flags)
		    && !test_and_set_bit(In_sync, &repl->flags)) {
			/* replacement has just become active */
			if (!rdev ||
			    !test_and_clear_bit(In_sync, &rdev->flags))
				count++;
			if (rdev) {
				/* Replaced device not technically
				 * faulty, but we need to be sure
				 * it gets removed and never re-added
				 */
				set_bit(Faulty, &rdev->flags);
				sysfs_notify_dirent_safe(
					rdev->sysfs_state);
			}
		}
1826
		if (rdev
1827
		    && rdev->recovery_offset == MaxSector
1828
		    && !test_bit(Faulty, &rdev->flags)
1829
		    && !test_and_set_bit(In_sync, &rdev->flags)) {
1830
			count++;
1831
			sysfs_notify_dirent_safe(rdev->sysfs_state);
Linus Torvalds's avatar
Linus Torvalds committed
1832 1833
		}
	}
1834 1835
	mddev->degraded -= count;
	spin_unlock_irqrestore(&conf->device_lock, flags);
Linus Torvalds's avatar
Linus Torvalds committed
1836 1837

	print_conf(conf);
1838
	return count;
Linus Torvalds's avatar
Linus Torvalds committed
1839 1840
}

1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851
static bool raid1_add_conf(struct r1conf *conf, struct md_rdev *rdev, int disk,
			   bool replacement)
{
	struct raid1_info *info = conf->mirrors + disk;

	if (replacement)
		info += conf->raid_disks;

	if (info->rdev)
		return false;

1852 1853 1854 1855 1856
	if (bdev_nonrot(rdev->bdev)) {
		set_bit(Nonrot, &rdev->flags);
		WRITE_ONCE(conf->nonrot_disks, conf->nonrot_disks + 1);
	}

1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879
	rdev->raid_disk = disk;
	info->head_position = 0;
	info->seq_start = MaxSector;
	WRITE_ONCE(info->rdev, rdev);

	return true;
}

static bool raid1_remove_conf(struct r1conf *conf, int disk)
{
	struct raid1_info *info = conf->mirrors + disk;
	struct md_rdev *rdev = info->rdev;

	if (!rdev || test_bit(In_sync, &rdev->flags) ||
	    atomic_read(&rdev->nr_pending))
		return false;

	/* Only remove non-faulty devices if recovery is not possible. */
	if (!test_bit(Faulty, &rdev->flags) &&
	    rdev->mddev->recovery_disabled != conf->recovery_disabled &&
	    rdev->mddev->degraded < conf->raid_disks)
		return false;

1880 1881 1882
	if (test_and_clear_bit(Nonrot, &rdev->flags))
		WRITE_ONCE(conf->nonrot_disks, conf->nonrot_disks - 1);

1883 1884 1885 1886
	WRITE_ONCE(info->rdev, NULL);
	return true;
}

1887
static int raid1_add_disk(struct mddev *mddev, struct md_rdev *rdev)
Linus Torvalds's avatar
Linus Torvalds committed
1888
{
1889
	struct r1conf *conf = mddev->private;
1890
	int err = -EEXIST;
1891
	int mirror = 0, repl_slot = -1;
1892
	struct raid1_info *p;
1893
	int first = 0;
1894
	int last = conf->raid_disks - 1;
Linus Torvalds's avatar
Linus Torvalds committed
1895

1896 1897 1898
	if (mddev->recovery_disabled == conf->recovery_disabled)
		return -EBUSY;

1899 1900 1901
	if (rdev->raid_disk >= 0)
		first = last = rdev->raid_disk;

1902 1903 1904 1905 1906 1907
	/*
	 * find the disk ... but prefer rdev->saved_raid_disk
	 * if possible.
	 */
	if (rdev->saved_raid_disk >= 0 &&
	    rdev->saved_raid_disk >= first &&
1908
	    rdev->saved_raid_disk < conf->raid_disks &&
1909 1910 1911
	    conf->mirrors[rdev->saved_raid_disk].rdev == NULL)
		first = last = rdev->saved_raid_disk;

1912
	for (mirror = first; mirror <= last; mirror++) {
1913
		p = conf->mirrors + mirror;
1914
		if (!p->rdev) {
1915 1916 1917
			err = mddev_stack_new_rdev(mddev, rdev);
			if (err)
				return err;
Linus Torvalds's avatar
Linus Torvalds committed
1918

1919
			raid1_add_conf(conf, rdev, mirror, false);
1920 1921 1922 1923
			/* As all devices are equivalent, we don't need a full recovery
			 * if this was recently any drive of the array
			 */
			if (rdev->saved_raid_disk < 0)
1924
				conf->fullsync = 1;
Linus Torvalds's avatar
Linus Torvalds committed
1925 1926
			break;
		}
1927
		if (test_bit(WantReplacement, &p->rdev->flags) &&
1928 1929
		    p[conf->raid_disks].rdev == NULL && repl_slot < 0)
			repl_slot = mirror;
1930
	}
1931 1932 1933 1934 1935

	if (err && repl_slot >= 0) {
		/* Add this device as a replacement */
		clear_bit(In_sync, &rdev->flags);
		set_bit(Replacement, &rdev->flags);
1936
		raid1_add_conf(conf, rdev, repl_slot, true);
1937 1938 1939 1940
		err = 0;
		conf->fullsync = 1;
	}

Linus Torvalds's avatar
Linus Torvalds committed
1941
	print_conf(conf);
1942
	return err;
Linus Torvalds's avatar
Linus Torvalds committed
1943 1944
}

1945
static int raid1_remove_disk(struct mddev *mddev, struct md_rdev *rdev)
Linus Torvalds's avatar
Linus Torvalds committed
1946
{
1947
	struct r1conf *conf = mddev->private;
Linus Torvalds's avatar
Linus Torvalds committed
1948
	int err = 0;
1949
	int number = rdev->raid_disk;
1950
	struct raid1_info *p = conf->mirrors + number;
1951 1952 1953 1954

	if (unlikely(number >= conf->raid_disks))
		goto abort;

1955 1956 1957 1958
	if (rdev != p->rdev) {
		number += conf->raid_disks;
		p = conf->mirrors + number;
	}
1959

Linus Torvalds's avatar
Linus Torvalds committed
1960
	print_conf(conf);
1961
	if (rdev == p->rdev) {
1962
		if (!raid1_remove_conf(conf, number)) {
1963 1964 1965
			err = -EBUSY;
			goto abort;
		}
1966 1967 1968

		if (number < conf->raid_disks &&
		    conf->mirrors[conf->raid_disks + number].rdev) {
1969 1970 1971 1972 1973 1974
			/* We just removed a device that is being replaced.
			 * Move down the replacement.  We drain all IO before
			 * doing this to avoid confusion.
			 */
			struct md_rdev *repl =
				conf->mirrors[conf->raid_disks + number].rdev;
1975
			freeze_array(conf, 0);
1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986
			if (atomic_read(&repl->nr_pending)) {
				/* It means that some queued IO of retry_list
				 * hold repl. Thus, we cannot set replacement
				 * as NULL, avoiding rdev NULL pointer
				 * dereference in sync_request_write and
				 * handle_write_finished.
				 */
				err = -EBUSY;
				unfreeze_array(conf);
				goto abort;
			}
1987
			clear_bit(Replacement, &repl->flags);
1988
			WRITE_ONCE(p->rdev, repl);
1989
			conf->mirrors[conf->raid_disks + number].rdev = NULL;
1990
			unfreeze_array(conf);
1991 1992 1993
		}

		clear_bit(WantReplacement, &rdev->flags);
1994
		err = md_integrity_register(mddev);
Linus Torvalds's avatar
Linus Torvalds committed
1995 1996 1997 1998 1999 2000 2001
	}
abort:

	print_conf(conf);
	return err;
}

2002
static void end_sync_read(struct bio *bio)
Linus Torvalds's avatar
Linus Torvalds committed
2003
{
2004
	struct r1bio *r1_bio = get_resync_r1bio(bio);
Linus Torvalds's avatar
Linus Torvalds committed
2005

2006
	update_head_pos(r1_bio->read_disk, r1_bio);
2007

Linus Torvalds's avatar
Linus Torvalds committed
2008 2009 2010 2011 2012
	/*
	 * we have read a block, now it needs to be re-written,
	 * or re-read if the read failed.
	 * We don't do much here, just schedule handling by raid1d
	 */
2013
	if (!bio->bi_status)
Linus Torvalds's avatar
Linus Torvalds committed
2014
		set_bit(R1BIO_Uptodate, &r1_bio->state);
2015 2016 2017

	if (atomic_dec_and_test(&r1_bio->remaining))
		reschedule_retry(r1_bio);
Linus Torvalds's avatar
Linus Torvalds committed
2018 2019
}

2020 2021 2022 2023 2024 2025 2026 2027
static void abort_sync_write(struct mddev *mddev, struct r1bio *r1_bio)
{
	sector_t sync_blocks = 0;
	sector_t s = r1_bio->sector;
	long sectors_to_go = r1_bio->sectors;

	/* make sure these bits don't get cleared. */
	do {
2028
		mddev->bitmap_ops->end_sync(mddev, s, &sync_blocks);
2029 2030 2031 2032 2033
		s += sync_blocks;
		sectors_to_go -= sync_blocks;
	} while (sectors_to_go > 0);
}

2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049
static void put_sync_write_buf(struct r1bio *r1_bio, int uptodate)
{
	if (atomic_dec_and_test(&r1_bio->remaining)) {
		struct mddev *mddev = r1_bio->mddev;
		int s = r1_bio->sectors;

		if (test_bit(R1BIO_MadeGood, &r1_bio->state) ||
		    test_bit(R1BIO_WriteError, &r1_bio->state))
			reschedule_retry(r1_bio);
		else {
			put_buf(r1_bio);
			md_done_sync(mddev, s, uptodate);
		}
	}
}

2050
static void end_sync_write(struct bio *bio)
Linus Torvalds's avatar
Linus Torvalds committed
2051
{
2052
	int uptodate = !bio->bi_status;
2053
	struct r1bio *r1_bio = get_resync_r1bio(bio);
2054
	struct mddev *mddev = r1_bio->mddev;
2055
	struct r1conf *conf = mddev->private;
2056
	struct md_rdev *rdev = conf->mirrors[find_bio_disk(r1_bio, bio)].rdev;
2057

2058
	if (!uptodate) {
2059
		abort_sync_write(mddev, r1_bio);
2060 2061
		set_bit(WriteErrorSeen, &rdev->flags);
		if (!test_and_set_bit(WantReplacement, &rdev->flags))
2062 2063
			set_bit(MD_RECOVERY_NEEDED, &
				mddev->recovery);
2064
		set_bit(R1BIO_WriteError, &r1_bio->state);
2065 2066 2067
	} else if (rdev_has_badblock(rdev, r1_bio->sector, r1_bio->sectors) &&
		   !rdev_has_badblock(conf->mirrors[r1_bio->read_disk].rdev,
				      r1_bio->sector, r1_bio->sectors)) {
2068
		set_bit(R1BIO_MadeGood, &r1_bio->state);
2069
	}
2070

2071
	put_sync_write_buf(r1_bio, uptodate);
Linus Torvalds's avatar
Linus Torvalds committed
2072 2073
}

2074
static int r1_sync_page_io(struct md_rdev *rdev, sector_t sector,
2075
			   int sectors, struct page *page, blk_opf_t rw)
2076
{
2077
	if (sync_page_io(rdev, sector, sectors << 9, page, rw, false))
2078 2079
		/* success */
		return 1;
2080
	if (rw == REQ_OP_WRITE) {
2081
		set_bit(WriteErrorSeen, &rdev->flags);
2082 2083 2084 2085 2086
		if (!test_and_set_bit(WantReplacement,
				      &rdev->flags))
			set_bit(MD_RECOVERY_NEEDED, &
				rdev->mddev->recovery);
	}
2087 2088 2089 2090 2091 2092
	/* need to record an error - either for the block or the device */
	if (!rdev_set_badblocks(rdev, sector, sectors, 0))
		md_error(rdev->mddev, rdev);
	return 0;
}

2093
static int fix_sync_read_error(struct r1bio *r1_bio)
Linus Torvalds's avatar
Linus Torvalds committed
2094
{
2095 2096 2097 2098 2099 2100 2101
	/* Try some synchronous reads of other devices to get
	 * good data, much like with normal read errors.  Only
	 * read into the pages we already have so we don't
	 * need to re-issue the read request.
	 * We don't need to freeze the array, because being in an
	 * active sync request, there is no normal IO, and
	 * no overlapping syncs.
2102 2103 2104
	 * We don't need to check is_badblock() again as we
	 * made sure that anything with a bad block in range
	 * will have bi_end_io clear.
2105
	 */
2106
	struct mddev *mddev = r1_bio->mddev;
2107
	struct r1conf *conf = mddev->private;
2108
	struct bio *bio = r1_bio->bios[r1_bio->read_disk];
2109
	struct page **pages = get_resync_pages(bio)->pages;
2110 2111 2112
	sector_t sect = r1_bio->sector;
	int sectors = r1_bio->sectors;
	int idx = 0;
2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125
	struct md_rdev *rdev;

	rdev = conf->mirrors[r1_bio->read_disk].rdev;
	if (test_bit(FailFast, &rdev->flags)) {
		/* Don't try recovering from here - just fail it
		 * ... unless it is the last working device of course */
		md_error(mddev, rdev);
		if (test_bit(Faulty, &rdev->flags))
			/* Don't try to read from here, but make sure
			 * put_buf does it's thing
			 */
			bio->bi_end_io = end_sync_write;
	}
2126 2127 2128 2129 2130

	while(sectors) {
		int s = sectors;
		int d = r1_bio->read_disk;
		int success = 0;
2131
		int start;
2132 2133 2134 2135 2136 2137 2138 2139 2140 2141

		if (s > (PAGE_SIZE>>9))
			s = PAGE_SIZE >> 9;
		do {
			if (r1_bio->bios[d]->bi_end_io == end_sync_read) {
				/* No rcu protection needed here devices
				 * can only be removed when no resync is
				 * active, and resync is currently active
				 */
				rdev = conf->mirrors[d].rdev;
2142
				if (sync_page_io(rdev, sect, s<<9,
2143
						 pages[idx],
2144
						 REQ_OP_READ, false)) {
2145 2146 2147 2148 2149
					success = 1;
					break;
				}
			}
			d++;
2150
			if (d == conf->raid_disks * 2)
2151 2152 2153
				d = 0;
		} while (!success && d != r1_bio->read_disk);

2154
		if (!success) {
2155 2156 2157 2158 2159 2160
			int abort = 0;
			/* Cannot read from anywhere, this block is lost.
			 * Record a bad block on each device.  If that doesn't
			 * work just disable and interrupt the recovery.
			 * Don't fail devices as that won't really help.
			 */
2161 2162
			pr_crit_ratelimited("md/raid1:%s: %pg: unrecoverable I/O read error for block %llu\n",
					    mdname(mddev), bio->bi_bdev,
2163
					    (unsigned long long)r1_bio->sector);
2164
			for (d = 0; d < conf->raid_disks * 2; d++) {
2165 2166 2167 2168 2169 2170 2171
				rdev = conf->mirrors[d].rdev;
				if (!rdev || test_bit(Faulty, &rdev->flags))
					continue;
				if (!rdev_set_badblocks(rdev, sect, s, 0))
					abort = 1;
			}
			if (abort) {
2172 2173
				conf->recovery_disabled =
					mddev->recovery_disabled;
2174 2175 2176 2177 2178 2179 2180 2181 2182 2183
				set_bit(MD_RECOVERY_INTR, &mddev->recovery);
				md_done_sync(mddev, r1_bio->sectors, 0);
				put_buf(r1_bio);
				return 0;
			}
			/* Try next page */
			sectors -= s;
			sect += s;
			idx++;
			continue;
2184
		}
2185 2186 2187 2188 2189

		start = d;
		/* write it back and re-read */
		while (d != r1_bio->read_disk) {
			if (d == 0)
2190
				d = conf->raid_disks * 2;
2191 2192 2193 2194
			d--;
			if (r1_bio->bios[d]->bi_end_io != end_sync_read)
				continue;
			rdev = conf->mirrors[d].rdev;
2195
			if (r1_sync_page_io(rdev, sect, s,
2196
					    pages[idx],
2197
					    REQ_OP_WRITE) == 0) {
2198 2199
				r1_bio->bios[d]->bi_end_io = NULL;
				rdev_dec_pending(rdev, mddev);
2200
			}
2201 2202 2203 2204
		}
		d = start;
		while (d != r1_bio->read_disk) {
			if (d == 0)
2205
				d = conf->raid_disks * 2;
2206 2207 2208 2209
			d--;
			if (r1_bio->bios[d]->bi_end_io != end_sync_read)
				continue;
			rdev = conf->mirrors[d].rdev;
2210
			if (r1_sync_page_io(rdev, sect, s,
2211
					    pages[idx],
2212
					    REQ_OP_READ) != 0)
2213
				atomic_add(s, &rdev->corrected_errors);
2214
		}
2215 2216 2217 2218
		sectors -= s;
		sect += s;
		idx ++;
	}
2219
	set_bit(R1BIO_Uptodate, &r1_bio->state);
2220
	bio->bi_status = 0;
2221 2222 2223
	return 1;
}

2224
static void process_checks(struct r1bio *r1_bio)
2225 2226 2227 2228 2229 2230 2231 2232
{
	/* We have read all readable devices.  If we haven't
	 * got the block, then there is no hope left.
	 * If we have, then we want to do a comparison
	 * and skip the write if everything is the same.
	 * If any blocks failed to read, then we need to
	 * attempt an over-write
	 */
2233
	struct mddev *mddev = r1_bio->mddev;
2234
	struct r1conf *conf = mddev->private;
2235 2236
	int primary;
	int i;
2237
	int vcnt;
2238

2239 2240 2241
	/* Fix variable parts of all bios */
	vcnt = (r1_bio->sectors + PAGE_SIZE / 512 - 1) >> (PAGE_SHIFT - 9);
	for (i = 0; i < conf->raid_disks * 2; i++) {
2242
		blk_status_t status;
2243
		struct bio *b = r1_bio->bios[i];
2244
		struct resync_pages *rp = get_resync_pages(b);
2245 2246
		if (b->bi_end_io != end_sync_read)
			continue;
2247
		/* fixup the bio for reuse, but preserve errno */
2248
		status = b->bi_status;
2249
		bio_reset(b, conf->mirrors[i].rdev->bdev, REQ_OP_READ);
2250
		b->bi_status = status;
2251
		b->bi_iter.bi_sector = r1_bio->sector +
2252 2253
			conf->mirrors[i].rdev->data_offset;
		b->bi_end_io = end_sync_read;
2254 2255
		rp->raid_bio = r1_bio;
		b->bi_private = rp;
2256

2257 2258
		/* initialize bvec table again */
		md_bio_reset_resync_pages(b, rp, r1_bio->sectors << 9);
2259
	}
2260
	for (primary = 0; primary < conf->raid_disks * 2; primary++)
2261
		if (r1_bio->bios[primary]->bi_end_io == end_sync_read &&
2262
		    !r1_bio->bios[primary]->bi_status) {
2263 2264 2265 2266 2267
			r1_bio->bios[primary]->bi_end_io = NULL;
			rdev_dec_pending(conf->mirrors[primary].rdev, mddev);
			break;
		}
	r1_bio->read_disk = primary;
2268
	for (i = 0; i < conf->raid_disks * 2; i++) {
2269
		int j = 0;
2270 2271
		struct bio *pbio = r1_bio->bios[primary];
		struct bio *sbio = r1_bio->bios[i];
2272
		blk_status_t status = sbio->bi_status;
2273 2274
		struct page **ppages = get_resync_pages(pbio)->pages;
		struct page **spages = get_resync_pages(sbio)->pages;
2275
		struct bio_vec *bi;
2276
		int page_len[RESYNC_PAGES] = { 0 };
2277
		struct bvec_iter_all iter_all;
2278

Kent Overstreet's avatar
Kent Overstreet committed
2279
		if (sbio->bi_end_io != end_sync_read)
2280
			continue;
2281
		/* Now we can 'fixup' the error value */
2282
		sbio->bi_status = 0;
2283

2284 2285
		bio_for_each_segment_all(bi, sbio, iter_all)
			page_len[j++] = bi->bv_len;
2286

2287
		if (!status) {
2288
			for (j = vcnt; j-- ; ) {
2289 2290
				if (memcmp(page_address(ppages[j]),
					   page_address(spages[j]),
2291
					   page_len[j]))
2292
					break;
2293
			}
2294 2295 2296
		} else
			j = 0;
		if (j >= 0)
2297
			atomic64_add(r1_bio->sectors, &mddev->resync_mismatches);
2298
		if (j < 0 || (test_bit(MD_RECOVERY_CHECK, &mddev->recovery)
2299
			      && !status)) {
2300 2301 2302 2303 2304
			/* No need to write to this device. */
			sbio->bi_end_io = NULL;
			rdev_dec_pending(conf->mirrors[i].rdev, mddev);
			continue;
		}
Kent Overstreet's avatar
Kent Overstreet committed
2305 2306

		bio_copy_data(sbio, pbio);
2307
	}
2308 2309
}

2310
static void sync_request_write(struct mddev *mddev, struct r1bio *r1_bio)
2311
{
2312
	struct r1conf *conf = mddev->private;
2313
	int i;
2314
	int disks = conf->raid_disks * 2;
2315
	struct bio *wbio;
2316 2317 2318 2319 2320

	if (!test_bit(R1BIO_Uptodate, &r1_bio->state))
		/* ouch - failed to read all of that. */
		if (!fix_sync_read_error(r1_bio))
			return;
2321 2322

	if (test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery))
2323 2324
		process_checks(r1_bio);

2325 2326 2327
	/*
	 * schedule writes
	 */
Linus Torvalds's avatar
Linus Torvalds committed
2328 2329 2330
	atomic_set(&r1_bio->remaining, 1);
	for (i = 0; i < disks ; i++) {
		wbio = r1_bio->bios[i];
2331 2332 2333 2334
		if (wbio->bi_end_io == NULL ||
		    (wbio->bi_end_io == end_sync_read &&
		     (i == r1_bio->read_disk ||
		      !test_bit(MD_RECOVERY_SYNC, &mddev->recovery))))
Linus Torvalds's avatar
Linus Torvalds committed
2335
			continue;
2336 2337
		if (test_bit(Faulty, &conf->mirrors[i].rdev->flags)) {
			abort_sync_write(mddev, r1_bio);
2338
			continue;
2339
		}
Linus Torvalds's avatar
Linus Torvalds committed
2340

2341
		wbio->bi_opf = REQ_OP_WRITE;
2342 2343 2344
		if (test_bit(FailFast, &conf->mirrors[i].rdev->flags))
			wbio->bi_opf |= MD_FAILFAST;

2345
		wbio->bi_end_io = end_sync_write;
Linus Torvalds's avatar
Linus Torvalds committed
2346
		atomic_inc(&r1_bio->remaining);
2347
		md_sync_acct(conf->mirrors[i].rdev->bdev, bio_sectors(wbio));
2348

2349
		submit_bio_noacct(wbio);
Linus Torvalds's avatar
Linus Torvalds committed
2350 2351
	}

2352
	put_sync_write_buf(r1_bio, 1);
Linus Torvalds's avatar
Linus Torvalds committed
2353 2354 2355 2356 2357 2358 2359
}

/*
 * This is a kernel thread which:
 *
 *	1.	Retries failed read operations on working mirrors.
 *	2.	Updates the raid superblock when problems encounter.
2360
 *	3.	Performs writes following reads for array synchronising.
Linus Torvalds's avatar
Linus Torvalds committed
2361 2362
 */

2363
static void fix_read_error(struct r1conf *conf, struct r1bio *r1_bio)
2364
{
2365 2366 2367
	sector_t sect = r1_bio->sector;
	int sectors = r1_bio->sectors;
	int read_disk = r1_bio->read_disk;
2368
	struct mddev *mddev = conf->mddev;
2369
	struct md_rdev *rdev = conf->mirrors[read_disk].rdev;
2370 2371 2372 2373 2374 2375

	if (exceed_read_errors(mddev, rdev)) {
		r1_bio->bios[r1_bio->read_disk] = IO_BLOCKED;
		return;
	}

2376 2377 2378 2379 2380 2381 2382 2383 2384 2385
	while(sectors) {
		int s = sectors;
		int d = read_disk;
		int success = 0;
		int start;

		if (s > (PAGE_SIZE>>9))
			s = PAGE_SIZE >> 9;

		do {
2386
			rdev = conf->mirrors[d].rdev;
2387
			if (rdev &&
2388 2389 2390
			    (test_bit(In_sync, &rdev->flags) ||
			     (!test_bit(Faulty, &rdev->flags) &&
			      rdev->recovery_offset >= sect + s)) &&
2391
			    rdev_has_badblock(rdev, sect, s) == 0) {
2392 2393
				atomic_inc(&rdev->nr_pending);
				if (sync_page_io(rdev, sect, s<<9,
2394
					 conf->tmppage, REQ_OP_READ, false))
2395 2396 2397 2398
					success = 1;
				rdev_dec_pending(rdev, mddev);
				if (success)
					break;
2399 2400
			}

2401 2402 2403
			d++;
			if (d == conf->raid_disks * 2)
				d = 0;
2404
		} while (d != read_disk);
2405 2406

		if (!success) {
2407
			/* Cannot read from anywhere - mark it bad */
2408
			struct md_rdev *rdev = conf->mirrors[read_disk].rdev;
2409 2410
			if (!rdev_set_badblocks(rdev, sect, s, 0))
				md_error(mddev, rdev);
2411 2412 2413 2414 2415 2416
			break;
		}
		/* write it back and re-read */
		start = d;
		while (d != read_disk) {
			if (d==0)
2417
				d = conf->raid_disks * 2;
2418
			d--;
2419
			rdev = conf->mirrors[d].rdev;
2420
			if (rdev &&
2421 2422
			    !test_bit(Faulty, &rdev->flags)) {
				atomic_inc(&rdev->nr_pending);
2423
				r1_sync_page_io(rdev, sect, s,
2424
						conf->tmppage, REQ_OP_WRITE);
2425
				rdev_dec_pending(rdev, mddev);
2426
			}
2427 2428 2429 2430
		}
		d = start;
		while (d != read_disk) {
			if (d==0)
2431
				d = conf->raid_disks * 2;
2432
			d--;
2433
			rdev = conf->mirrors[d].rdev;
2434
			if (rdev &&
2435
			    !test_bit(Faulty, &rdev->flags)) {
2436
				atomic_inc(&rdev->nr_pending);
2437
				if (r1_sync_page_io(rdev, sect, s,
2438
						conf->tmppage, REQ_OP_READ)) {
2439
					atomic_add(s, &rdev->corrected_errors);
2440
					pr_info("md/raid1:%s: read error corrected (%d sectors at %llu on %pg)\n",
2441 2442 2443
						mdname(mddev), s,
						(unsigned long long)(sect +
								     rdev->data_offset),
2444
						rdev->bdev);
2445
				}
2446
				rdev_dec_pending(rdev, mddev);
2447
			}
2448 2449 2450 2451 2452 2453
		}
		sectors -= s;
		sect += s;
	}
}

2454
static int narrow_write_error(struct r1bio *r1_bio, int i)
2455
{
2456
	struct mddev *mddev = r1_bio->mddev;
2457
	struct r1conf *conf = mddev->private;
2458
	struct md_rdev *rdev = conf->mirrors[i].rdev;
2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479

	/* bio has the data to be written to device 'i' where
	 * we just recently had a write error.
	 * We repeatedly clone the bio and trim down to one block,
	 * then try the write.  Where the write fails we record
	 * a bad block.
	 * It is conceivable that the bio doesn't exactly align with
	 * blocks.  We must handle this somehow.
	 *
	 * We currently own a reference on the rdev.
	 */

	int block_sectors;
	sector_t sector;
	int sectors;
	int sect_to_write = r1_bio->sectors;
	int ok = 1;

	if (rdev->badblocks.shift < 0)
		return 0;

2480 2481
	block_sectors = roundup(1 << rdev->badblocks.shift,
				bdev_logical_block_size(rdev->bdev) >> 9);
2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492
	sector = r1_bio->sector;
	sectors = ((sector + block_sectors)
		   & ~(sector_t)(block_sectors - 1))
		- sector;

	while (sect_to_write) {
		struct bio *wbio;
		if (sectors > sect_to_write)
			sectors = sect_to_write;
		/* Write at 'sector' for 'sectors'*/

2493
		if (test_bit(R1BIO_BehindIO, &r1_bio->state)) {
2494 2495 2496
			wbio = bio_alloc_clone(rdev->bdev,
					       r1_bio->behind_master_bio,
					       GFP_NOIO, &mddev->bio_set);
2497
		} else {
2498 2499
			wbio = bio_alloc_clone(rdev->bdev, r1_bio->master_bio,
					       GFP_NOIO, &mddev->bio_set);
2500 2501
		}

2502
		wbio->bi_opf = REQ_OP_WRITE;
2503 2504
		wbio->bi_iter.bi_sector = r1_bio->sector;
		wbio->bi_iter.bi_size = r1_bio->sectors << 9;
2505

2506
		bio_trim(wbio, sector - r1_bio->sector, sectors);
2507
		wbio->bi_iter.bi_sector += rdev->data_offset;
2508 2509

		if (submit_bio_wait(wbio) < 0)
2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522
			/* failure! */
			ok = rdev_set_badblocks(rdev, sector,
						sectors, 0)
				&& ok;

		bio_put(wbio);
		sect_to_write -= sectors;
		sector += sectors;
		sectors = block_sectors;
	}
	return ok;
}

2523
static void handle_sync_write_finished(struct r1conf *conf, struct r1bio *r1_bio)
2524 2525 2526
{
	int m;
	int s = r1_bio->sectors;
2527
	for (m = 0; m < conf->raid_disks * 2 ; m++) {
2528
		struct md_rdev *rdev = conf->mirrors[m].rdev;
2529 2530 2531
		struct bio *bio = r1_bio->bios[m];
		if (bio->bi_end_io == NULL)
			continue;
2532
		if (!bio->bi_status &&
2533
		    test_bit(R1BIO_MadeGood, &r1_bio->state)) {
2534
			rdev_clear_badblocks(rdev, r1_bio->sector, s, 0);
2535
		}
2536
		if (bio->bi_status &&
2537 2538 2539 2540 2541 2542 2543 2544 2545
		    test_bit(R1BIO_WriteError, &r1_bio->state)) {
			if (!rdev_set_badblocks(rdev, r1_bio->sector, s, 0))
				md_error(conf->mddev, rdev);
		}
	}
	put_buf(r1_bio);
	md_done_sync(conf->mddev, s, 1);
}

2546
static void handle_write_finished(struct r1conf *conf, struct r1bio *r1_bio)
2547
{
2548
	int m, idx;
2549
	bool fail = false;
2550

2551
	for (m = 0; m < conf->raid_disks * 2 ; m++)
2552
		if (r1_bio->bios[m] == IO_MADE_GOOD) {
2553
			struct md_rdev *rdev = conf->mirrors[m].rdev;
2554 2555
			rdev_clear_badblocks(rdev,
					     r1_bio->sector,
2556
					     r1_bio->sectors, 0);
2557 2558 2559 2560 2561 2562
			rdev_dec_pending(rdev, conf->mddev);
		} else if (r1_bio->bios[m] != NULL) {
			/* This drive got a write error.  We need to
			 * narrow down and record precise write
			 * errors.
			 */
2563
			fail = true;
2564 2565 2566 2567 2568 2569 2570 2571 2572
			if (!narrow_write_error(r1_bio, m)) {
				md_error(conf->mddev,
					 conf->mirrors[m].rdev);
				/* an I/O failed, we can't clear the bitmap */
				set_bit(R1BIO_Degraded, &r1_bio->state);
			}
			rdev_dec_pending(conf->mirrors[m].rdev,
					 conf->mddev);
		}
2573 2574 2575
	if (fail) {
		spin_lock_irq(&conf->device_lock);
		list_add(&r1_bio->retry_list, &conf->bio_end_io_list);
2576
		idx = sector_to_idx(r1_bio->sector);
2577
		atomic_inc(&conf->nr_queued[idx]);
2578
		spin_unlock_irq(&conf->device_lock);
2579 2580 2581 2582 2583
		/*
		 * In case freeze_array() is waiting for condition
		 * get_unqueued_pending() == extra to be true.
		 */
		wake_up(&conf->wait_barrier);
2584
		md_wakeup_thread(conf->mddev->thread);
2585 2586 2587
	} else {
		if (test_bit(R1BIO_WriteError, &r1_bio->state))
			close_write(r1_bio);
2588
		raid_end_bio_io(r1_bio);
2589
	}
2590 2591
}

2592
static void handle_read_error(struct r1conf *conf, struct r1bio *r1_bio)
2593
{
2594
	struct mddev *mddev = conf->mddev;
2595
	struct bio *bio;
2596
	struct md_rdev *rdev;
2597
	sector_t sector;
2598 2599 2600 2601 2602 2603 2604 2605 2606 2607

	clear_bit(R1BIO_ReadError, &r1_bio->state);
	/* we got a read error. Maybe the drive is bad.  Maybe just
	 * the block and we can fix it.
	 * We freeze all other IO, and try reading the block from
	 * other devices.  When we find one, we re-write
	 * and check it that fixes the read error.
	 * This is all done synchronously while the array is
	 * frozen
	 */
2608 2609 2610 2611 2612

	bio = r1_bio->bios[r1_bio->read_disk];
	bio_put(bio);
	r1_bio->bios[r1_bio->read_disk] = NULL;

2613 2614 2615
	rdev = conf->mirrors[r1_bio->read_disk].rdev;
	if (mddev->ro == 0
	    && !test_bit(FailFast, &rdev->flags)) {
2616
		freeze_array(conf, 1);
2617
		fix_read_error(conf, r1_bio);
2618
		unfreeze_array(conf);
2619 2620
	} else if (mddev->ro == 0 && test_bit(FailFast, &rdev->flags)) {
		md_error(mddev, rdev);
2621 2622 2623 2624
	} else {
		r1_bio->bios[r1_bio->read_disk] = IO_BLOCKED;
	}

2625
	rdev_dec_pending(rdev, conf->mddev);
2626
	sector = r1_bio->sector;
2627
	bio = r1_bio->master_bio;
2628

2629 2630 2631
	/* Reuse the old r1_bio so that the IO_BLOCKED settings are preserved */
	r1_bio->state = 0;
	raid1_read_request(mddev, bio, r1_bio->sectors, r1_bio);
2632
	allow_barrier(conf, sector);
2633 2634
}

2635
static void raid1d(struct md_thread *thread)
Linus Torvalds's avatar
Linus Torvalds committed
2636
{
2637
	struct mddev *mddev = thread->mddev;
2638
	struct r1bio *r1_bio;
Linus Torvalds's avatar
Linus Torvalds committed
2639
	unsigned long flags;
2640
	struct r1conf *conf = mddev->private;
Linus Torvalds's avatar
Linus Torvalds committed
2641
	struct list_head *head = &conf->retry_list;
2642
	struct blk_plug plug;
2643
	int idx;
Linus Torvalds's avatar
Linus Torvalds committed
2644 2645

	md_check_recovery(mddev);
2646

2647
	if (!list_empty_careful(&conf->bio_end_io_list) &&
2648
	    !test_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags)) {
2649 2650
		LIST_HEAD(tmp);
		spin_lock_irqsave(&conf->device_lock, flags);
2651 2652
		if (!test_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags))
			list_splice_init(&conf->bio_end_io_list, &tmp);
2653 2654
		spin_unlock_irqrestore(&conf->device_lock, flags);
		while (!list_empty(&tmp)) {
2655 2656
			r1_bio = list_first_entry(&tmp, struct r1bio,
						  retry_list);
2657
			list_del(&r1_bio->retry_list);
2658
			idx = sector_to_idx(r1_bio->sector);
2659
			atomic_dec(&conf->nr_queued[idx]);
2660 2661 2662 2663
			if (mddev->degraded)
				set_bit(R1BIO_Degraded, &r1_bio->state);
			if (test_bit(R1BIO_WriteError, &r1_bio->state))
				close_write(r1_bio);
2664 2665 2666 2667
			raid_end_bio_io(r1_bio);
		}
	}

2668
	blk_start_plug(&plug);
Linus Torvalds's avatar
Linus Torvalds committed
2669
	for (;;) {
2670

2671
		flush_pending_writes(conf);
2672

2673 2674 2675
		spin_lock_irqsave(&conf->device_lock, flags);
		if (list_empty(head)) {
			spin_unlock_irqrestore(&conf->device_lock, flags);
Linus Torvalds's avatar
Linus Torvalds committed
2676
			break;
2677
		}
2678
		r1_bio = list_entry(head->prev, struct r1bio, retry_list);
Linus Torvalds's avatar
Linus Torvalds committed
2679
		list_del(head->prev);
2680
		idx = sector_to_idx(r1_bio->sector);
2681
		atomic_dec(&conf->nr_queued[idx]);
Linus Torvalds's avatar
Linus Torvalds committed
2682 2683 2684
		spin_unlock_irqrestore(&conf->device_lock, flags);

		mddev = r1_bio->mddev;
2685
		conf = mddev->private;
2686
		if (test_bit(R1BIO_IsSync, &r1_bio->state)) {
2687
			if (test_bit(R1BIO_MadeGood, &r1_bio->state) ||
2688 2689 2690
			    test_bit(R1BIO_WriteError, &r1_bio->state))
				handle_sync_write_finished(conf, r1_bio);
			else
2691
				sync_request_write(mddev, r1_bio);
2692
		} else if (test_bit(R1BIO_MadeGood, &r1_bio->state) ||
2693 2694 2695 2696 2697
			   test_bit(R1BIO_WriteError, &r1_bio->state))
			handle_write_finished(conf, r1_bio);
		else if (test_bit(R1BIO_ReadError, &r1_bio->state))
			handle_read_error(conf, r1_bio);
		else
2698
			WARN_ON_ONCE(1);
2699

2700
		cond_resched();
2701
		if (mddev->sb_flags & ~(1<<MD_SB_CHANGE_PENDING))
2702
			md_check_recovery(mddev);
Linus Torvalds's avatar
Linus Torvalds committed
2703
	}
2704
	blk_finish_plug(&plug);
Linus Torvalds's avatar
Linus Torvalds committed
2705 2706
}

2707
static int init_resync(struct r1conf *conf)
Linus Torvalds's avatar
Linus Torvalds committed
2708 2709 2710 2711
{
	int buffs;

	buffs = RESYNC_WINDOW / RESYNC_BLOCK_SIZE;
2712 2713 2714 2715
	BUG_ON(mempool_initialized(&conf->r1buf_pool));

	return mempool_init(&conf->r1buf_pool, buffs, r1buf_pool_alloc,
			    r1buf_pool_free, conf->poolinfo);
Linus Torvalds's avatar
Linus Torvalds committed
2716 2717
}

2718 2719
static struct r1bio *raid1_alloc_init_r1buf(struct r1conf *conf)
{
2720
	struct r1bio *r1bio = mempool_alloc(&conf->r1buf_pool, GFP_NOIO);
2721 2722 2723 2724 2725 2726 2727
	struct resync_pages *rps;
	struct bio *bio;
	int i;

	for (i = conf->poolinfo->raid_disks; i--; ) {
		bio = r1bio->bios[i];
		rps = bio->bi_private;
2728
		bio_reset(bio, NULL, 0);
2729 2730 2731 2732 2733 2734
		bio->bi_private = rps;
	}
	r1bio->master_bio = NULL;
	return r1bio;
}

Linus Torvalds's avatar
Linus Torvalds committed
2735 2736 2737 2738 2739 2740 2741 2742 2743 2744
/*
 * perform a "sync" on one "block"
 *
 * We need to make sure that no normal I/O request - particularly write
 * requests - conflict with active sync requests.
 *
 * This is achieved by tracking pending requests and a 'barrier' concept
 * that can be installed to exclude normal IO requests.
 */

Shaohua Li's avatar
Shaohua Li committed
2745
static sector_t raid1_sync_request(struct mddev *mddev, sector_t sector_nr,
2746
				   sector_t max_sector, int *skipped)
Linus Torvalds's avatar
Linus Torvalds committed
2747
{
2748
	struct r1conf *conf = mddev->private;
2749
	struct r1bio *r1_bio;
Linus Torvalds's avatar
Linus Torvalds committed
2750
	struct bio *bio;
2751
	sector_t nr_sectors;
2752
	int disk = -1;
Linus Torvalds's avatar
Linus Torvalds committed
2753
	int i;
2754 2755
	int wonly = -1;
	int write_targets = 0, read_targets = 0;
2756
	sector_t sync_blocks;
2757
	bool still_degraded = false;
2758 2759
	int good_sectors = RESYNC_SECTORS;
	int min_bad = 0; /* number of sectors that are bad in all devices */
2760
	int idx = sector_to_idx(sector_nr);
2761
	int page_idx = 0;
Linus Torvalds's avatar
Linus Torvalds committed
2762

2763
	if (!mempool_initialized(&conf->r1buf_pool))
Linus Torvalds's avatar
Linus Torvalds committed
2764
		if (init_resync(conf))
2765
			return 0;
Linus Torvalds's avatar
Linus Torvalds committed
2766 2767

	if (sector_nr >= max_sector) {
2768 2769 2770 2771 2772
		/* If we aborted, we need to abort the
		 * sync on the 'current' bitmap chunk (there will
		 * only be one in raid1 resync.
		 * We can find the current addess in mddev->curr_resync
		 */
2773
		if (mddev->curr_resync < max_sector) /* aborted */
2774 2775
			mddev->bitmap_ops->end_sync(mddev, mddev->curr_resync,
						    &sync_blocks);
2776
		else /* completed sync */
2777
			conf->fullsync = 0;
2778

2779
		mddev->bitmap_ops->close_sync(mddev);
Linus Torvalds's avatar
Linus Torvalds committed
2780
		close_sync(conf);
2781 2782 2783 2784 2785

		if (mddev_is_clustered(mddev)) {
			conf->cluster_sync_low = 0;
			conf->cluster_sync_high = 0;
		}
Linus Torvalds's avatar
Linus Torvalds committed
2786 2787 2788
		return 0;
	}

2789 2790
	if (mddev->bitmap == NULL &&
	    mddev->recovery_cp == MaxSector &&
2791
	    !test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery) &&
2792 2793 2794 2795
	    conf->fullsync == 0) {
		*skipped = 1;
		return max_sector - sector_nr;
	}
2796 2797 2798
	/* before building a request, check if we can skip these blocks..
	 * This call the bitmap_start_sync doesn't actually record anything
	 */
2799
	if (!mddev->bitmap_ops->start_sync(mddev, sector_nr, &sync_blocks, true) &&
2800
	    !conf->fullsync && !test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery)) {
2801 2802 2803 2804
		/* We can skip this block, and probably several more */
		*skipped = 1;
		return sync_blocks;
	}
2805

2806 2807 2808 2809
	/*
	 * If there is non-resync activity waiting for a turn, then let it
	 * though before starting on this new sync request.
	 */
2810
	if (atomic_read(&conf->nr_waiting[idx]))
2811 2812
		schedule_timeout_uninterruptible(1);

2813 2814 2815 2816
	/* we are incrementing sector_nr below. To be safe, we check against
	 * sector_nr + two times RESYNC_SECTORS
	 */

2817 2818 2819
	mddev->bitmap_ops->cond_end_sync(mddev, sector_nr,
		mddev_is_clustered(mddev) &&
		(sector_nr + 2 * RESYNC_SECTORS > conf->cluster_sync_high));
2820 2821 2822 2823 2824

	if (raise_barrier(conf, sector_nr))
		return 0;

	r1_bio = raid1_alloc_init_r1buf(conf);
Linus Torvalds's avatar
Linus Torvalds committed
2825 2826

	/*
2827 2828 2829 2830 2831 2832
	 * If we get a correctably read error during resync or recovery,
	 * we might want to read from a different device.  So we
	 * flag all drives that could conceivably be read from for READ,
	 * and any others (which will be non-In_sync devices) for WRITE.
	 * If a read fails, we try reading from something else for which READ
	 * is OK.
Linus Torvalds's avatar
Linus Torvalds committed
2833 2834 2835 2836
	 */

	r1_bio->mddev = mddev;
	r1_bio->sector = sector_nr;
2837
	r1_bio->state = 0;
Linus Torvalds's avatar
Linus Torvalds committed
2838
	set_bit(R1BIO_IsSync, &r1_bio->state);
2839 2840
	/* make sure good_sectors won't go across barrier unit boundary */
	good_sectors = align_to_barrier_unit_end(sector_nr, good_sectors);
Linus Torvalds's avatar
Linus Torvalds committed
2841

2842
	for (i = 0; i < conf->raid_disks * 2; i++) {
2843
		struct md_rdev *rdev;
Linus Torvalds's avatar
Linus Torvalds committed
2844 2845
		bio = r1_bio->bios[i];

2846
		rdev = conf->mirrors[i].rdev;
2847
		if (rdev == NULL ||
2848
		    test_bit(Faulty, &rdev->flags)) {
2849
			if (i < conf->raid_disks)
2850
				still_degraded = true;
2851
		} else if (!test_bit(In_sync, &rdev->flags)) {
2852
			bio->bi_opf = REQ_OP_WRITE;
Linus Torvalds's avatar
Linus Torvalds committed
2853 2854
			bio->bi_end_io = end_sync_write;
			write_targets ++;
2855 2856
		} else {
			/* may need to read from here */
2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878
			sector_t first_bad = MaxSector;
			int bad_sectors;

			if (is_badblock(rdev, sector_nr, good_sectors,
					&first_bad, &bad_sectors)) {
				if (first_bad > sector_nr)
					good_sectors = first_bad - sector_nr;
				else {
					bad_sectors -= (sector_nr - first_bad);
					if (min_bad == 0 ||
					    min_bad > bad_sectors)
						min_bad = bad_sectors;
				}
			}
			if (sector_nr < first_bad) {
				if (test_bit(WriteMostly, &rdev->flags)) {
					if (wonly < 0)
						wonly = i;
				} else {
					if (disk < 0)
						disk = i;
				}
2879
				bio->bi_opf = REQ_OP_READ;
2880 2881
				bio->bi_end_io = end_sync_read;
				read_targets++;
2882 2883 2884 2885 2886 2887 2888 2889 2890
			} else if (!test_bit(WriteErrorSeen, &rdev->flags) &&
				test_bit(MD_RECOVERY_SYNC, &mddev->recovery) &&
				!test_bit(MD_RECOVERY_CHECK, &mddev->recovery)) {
				/*
				 * The device is suitable for reading (InSync),
				 * but has bad block(s) here. Let's try to correct them,
				 * if we are doing resync or repair. Otherwise, leave
				 * this device alone for this sync request.
				 */
2891
				bio->bi_opf = REQ_OP_WRITE;
2892 2893
				bio->bi_end_io = end_sync_write;
				write_targets++;
2894 2895
			}
		}
2896
		if (rdev && bio->bi_end_io) {
2897
			atomic_inc(&rdev->nr_pending);
2898
			bio->bi_iter.bi_sector = sector_nr + rdev->data_offset;
2899
			bio_set_dev(bio, rdev->bdev);
2900 2901
			if (test_bit(FailFast, &rdev->flags))
				bio->bi_opf |= MD_FAILFAST;
2902
		}
Linus Torvalds's avatar
Linus Torvalds committed
2903
	}
2904 2905 2906
	if (disk < 0)
		disk = wonly;
	r1_bio->read_disk = disk;
2907

2908 2909 2910 2911 2912
	if (read_targets == 0 && min_bad > 0) {
		/* These sectors are bad on all InSync devices, so we
		 * need to mark them bad on all write targets
		 */
		int ok = 1;
2913
		for (i = 0 ; i < conf->raid_disks * 2 ; i++)
2914
			if (r1_bio->bios[i]->bi_end_io == end_sync_write) {
2915
				struct md_rdev *rdev = conf->mirrors[i].rdev;
2916 2917 2918 2919
				ok = rdev_set_badblocks(rdev, sector_nr,
							min_bad, 0
					) && ok;
			}
2920
		set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942
		*skipped = 1;
		put_buf(r1_bio);

		if (!ok) {
			/* Cannot record the badblocks, so need to
			 * abort the resync.
			 * If there are multiple read targets, could just
			 * fail the really bad ones ???
			 */
			conf->recovery_disabled = mddev->recovery_disabled;
			set_bit(MD_RECOVERY_INTR, &mddev->recovery);
			return 0;
		} else
			return min_bad;

	}
	if (min_bad > 0 && min_bad < good_sectors) {
		/* only resync enough to reach the next bad->good
		 * transition */
		good_sectors = min_bad;
	}

2943 2944 2945 2946 2947
	if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery) && read_targets > 0)
		/* extra read targets are also write targets */
		write_targets += read_targets-1;

	if (write_targets == 0 || read_targets == 0) {
Linus Torvalds's avatar
Linus Torvalds committed
2948 2949 2950
		/* There is nowhere to write, so all non-sync
		 * drives must be failed - so we are finished
		 */
2951 2952 2953 2954
		sector_t rv;
		if (min_bad > 0)
			max_sector = sector_nr + min_bad;
		rv = max_sector - sector_nr;
2955
		*skipped = 1;
Linus Torvalds's avatar
Linus Torvalds committed
2956 2957 2958 2959
		put_buf(r1_bio);
		return rv;
	}

2960 2961
	if (max_sector > mddev->resync_max)
		max_sector = mddev->resync_max; /* Don't do IO beyond here */
2962 2963
	if (max_sector > sector_nr + good_sectors)
		max_sector = sector_nr + good_sectors;
Linus Torvalds's avatar
Linus Torvalds committed
2964
	nr_sectors = 0;
2965
	sync_blocks = 0;
Linus Torvalds's avatar
Linus Torvalds committed
2966 2967 2968 2969 2970 2971 2972
	do {
		struct page *page;
		int len = PAGE_SIZE;
		if (sector_nr + (len>>9) > max_sector)
			len = (max_sector - sector_nr) << 9;
		if (len == 0)
			break;
2973
		if (sync_blocks == 0) {
2974 2975
			if (!mddev->bitmap_ops->start_sync(mddev, sector_nr,
						&sync_blocks, still_degraded) &&
2976 2977
			    !conf->fullsync &&
			    !test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery))
2978
				break;
2979
			if ((len >> 9) > sync_blocks)
2980
				len = sync_blocks<<9;
2981
		}
2982

2983
		for (i = 0 ; i < conf->raid_disks * 2; i++) {
2984 2985
			struct resync_pages *rp;

Linus Torvalds's avatar
Linus Torvalds committed
2986
			bio = r1_bio->bios[i];
2987
			rp = get_resync_pages(bio);
Linus Torvalds's avatar
Linus Torvalds committed
2988
			if (bio->bi_end_io) {
2989
				page = resync_fetch_page(rp, page_idx);
2990 2991 2992 2993 2994

				/*
				 * won't fail because the vec table is big
				 * enough to hold all these pages
				 */
2995
				__bio_add_page(bio, page, len, 0);
Linus Torvalds's avatar
Linus Torvalds committed
2996 2997 2998 2999
			}
		}
		nr_sectors += len>>9;
		sector_nr += len>>9;
3000
		sync_blocks -= (len>>9);
3001
	} while (++page_idx < RESYNC_PAGES);
3002

Linus Torvalds's avatar
Linus Torvalds committed
3003 3004
	r1_bio->sectors = nr_sectors;

3005 3006 3007 3008 3009 3010 3011 3012 3013 3014
	if (mddev_is_clustered(mddev) &&
			conf->cluster_sync_high < sector_nr + nr_sectors) {
		conf->cluster_sync_low = mddev->curr_resync_completed;
		conf->cluster_sync_high = conf->cluster_sync_low + CLUSTER_RESYNC_WINDOW_SECTORS;
		/* Send resync message */
		md_cluster_ops->resync_info_update(mddev,
				conf->cluster_sync_low,
				conf->cluster_sync_high);
	}

3015 3016 3017 3018 3019
	/* For a user-requested sync, we read all readable devices and do a
	 * compare
	 */
	if (test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery)) {
		atomic_set(&r1_bio->remaining, read_targets);
3020
		for (i = 0; i < conf->raid_disks * 2 && read_targets; i++) {
3021 3022
			bio = r1_bio->bios[i];
			if (bio->bi_end_io == end_sync_read) {
3023
				read_targets--;
3024
				md_sync_acct_bio(bio, nr_sectors);
3025 3026
				if (read_targets == 1)
					bio->bi_opf &= ~MD_FAILFAST;
3027
				submit_bio_noacct(bio);
3028 3029 3030 3031 3032
			}
		}
	} else {
		atomic_set(&r1_bio->remaining, 1);
		bio = r1_bio->bios[r1_bio->read_disk];
3033
		md_sync_acct_bio(bio, nr_sectors);
3034 3035
		if (read_targets == 1)
			bio->bi_opf &= ~MD_FAILFAST;
3036
		submit_bio_noacct(bio);
3037
	}
Linus Torvalds's avatar
Linus Torvalds committed
3038 3039 3040
	return nr_sectors;
}

3041
static sector_t raid1_size(struct mddev *mddev, sector_t sectors, int raid_disks)
3042 3043 3044 3045 3046 3047 3048
{
	if (sectors)
		return sectors;

	return mddev->dev_sectors;
}

3049
static struct r1conf *setup_conf(struct mddev *mddev)
Linus Torvalds's avatar
Linus Torvalds committed
3050
{
3051
	struct r1conf *conf;
3052
	int i;
3053
	struct raid1_info *disk;
3054
	struct md_rdev *rdev;
3055
	int err = -ENOMEM;
Linus Torvalds's avatar
Linus Torvalds committed
3056

3057
	conf = kzalloc(sizeof(struct r1conf), GFP_KERNEL);
Linus Torvalds's avatar
Linus Torvalds committed
3058
	if (!conf)
3059
		goto abort;
Linus Torvalds's avatar
Linus Torvalds committed
3060

3061
	conf->nr_pending = kcalloc(BARRIER_BUCKETS_NR,
3062
				   sizeof(atomic_t), GFP_KERNEL);
3063 3064 3065 3066
	if (!conf->nr_pending)
		goto abort;

	conf->nr_waiting = kcalloc(BARRIER_BUCKETS_NR,
3067
				   sizeof(atomic_t), GFP_KERNEL);
3068 3069 3070 3071
	if (!conf->nr_waiting)
		goto abort;

	conf->nr_queued = kcalloc(BARRIER_BUCKETS_NR,
3072
				  sizeof(atomic_t), GFP_KERNEL);
3073 3074 3075 3076
	if (!conf->nr_queued)
		goto abort;

	conf->barrier = kcalloc(BARRIER_BUCKETS_NR,
3077
				sizeof(atomic_t), GFP_KERNEL);
3078 3079 3080
	if (!conf->barrier)
		goto abort;

3081 3082 3083
	conf->mirrors = kzalloc(array3_size(sizeof(struct raid1_info),
					    mddev->raid_disks, 2),
				GFP_KERNEL);
Linus Torvalds's avatar
Linus Torvalds committed
3084
	if (!conf->mirrors)
3085
		goto abort;
Linus Torvalds's avatar
Linus Torvalds committed
3086

3087 3088
	conf->tmppage = alloc_page(GFP_KERNEL);
	if (!conf->tmppage)
3089
		goto abort;
3090

3091
	conf->poolinfo = kzalloc(sizeof(*conf->poolinfo), GFP_KERNEL);
Linus Torvalds's avatar
Linus Torvalds committed
3092
	if (!conf->poolinfo)
3093
		goto abort;
3094
	conf->poolinfo->raid_disks = mddev->raid_disks * 2;
3095
	err = mempool_init(&conf->r1bio_pool, NR_RAID_BIOS, r1bio_pool_alloc,
3096
			   rbio_pool_free, conf->poolinfo);
3097
	if (err)
3098 3099
		goto abort;

3100 3101
	err = bioset_init(&conf->bio_split, BIO_POOL_SIZE, 0, 0);
	if (err)
3102 3103
		goto abort;

3104
	conf->poolinfo->mddev = mddev;
Linus Torvalds's avatar
Linus Torvalds committed
3105

3106
	err = -EINVAL;
3107
	spin_lock_init(&conf->device_lock);
3108
	conf->raid_disks = mddev->raid_disks;
NeilBrown's avatar
NeilBrown committed
3109
	rdev_for_each(rdev, mddev) {
3110
		int disk_idx = rdev->raid_disk;
3111 3112

		if (disk_idx >= conf->raid_disks || disk_idx < 0)
Linus Torvalds's avatar
Linus Torvalds committed
3113 3114
			continue;

3115 3116
		if (!raid1_add_conf(conf, rdev, disk_idx,
				    test_bit(Replacement, &rdev->flags)))
3117
			goto abort;
Linus Torvalds's avatar
Linus Torvalds committed
3118 3119 3120
	}
	conf->mddev = mddev;
	INIT_LIST_HEAD(&conf->retry_list);
3121
	INIT_LIST_HEAD(&conf->bio_end_io_list);
Linus Torvalds's avatar
Linus Torvalds committed
3122 3123

	spin_lock_init(&conf->resync_lock);
3124
	init_waitqueue_head(&conf->wait_barrier);
Linus Torvalds's avatar
Linus Torvalds committed
3125

3126
	bio_list_init(&conf->pending_bio_list);
3127
	conf->recovery_disabled = mddev->recovery_disabled - 1;
3128

3129
	err = -EIO;
3130
	for (i = 0; i < conf->raid_disks * 2; i++) {
Linus Torvalds's avatar
Linus Torvalds committed
3131 3132 3133

		disk = conf->mirrors + i;

3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148
		if (i < conf->raid_disks &&
		    disk[conf->raid_disks].rdev) {
			/* This slot has a replacement. */
			if (!disk->rdev) {
				/* No original, just make the replacement
				 * a recovering spare
				 */
				disk->rdev =
					disk[conf->raid_disks].rdev;
				disk[conf->raid_disks].rdev = NULL;
			} else if (!test_bit(In_sync, &disk->rdev->flags))
				/* Original is not in_sync - bad */
				goto abort;
		}

3149 3150
		if (!disk->rdev ||
		    !test_bit(In_sync, &disk->rdev->flags)) {
Linus Torvalds's avatar
Linus Torvalds committed
3151
			disk->head_position = 0;
3152 3153
			if (disk->rdev &&
			    (disk->rdev->saved_raid_disk < 0))
3154
				conf->fullsync = 1;
3155
		}
Linus Torvalds's avatar
Linus Torvalds committed
3156
	}
3157 3158

	err = -ENOMEM;
Yu Kuai's avatar
Yu Kuai committed
3159 3160
	rcu_assign_pointer(conf->thread,
			   md_register_thread(raid1d, mddev, "raid1"));
3161
	if (!conf->thread)
3162
		goto abort;
Linus Torvalds's avatar
Linus Torvalds committed
3163

3164 3165 3166 3167
	return conf;

 abort:
	if (conf) {
3168
		mempool_exit(&conf->r1bio_pool);
3169 3170 3171
		kfree(conf->mirrors);
		safe_put_page(conf->tmppage);
		kfree(conf->poolinfo);
3172 3173 3174 3175
		kfree(conf->nr_pending);
		kfree(conf->nr_waiting);
		kfree(conf->nr_queued);
		kfree(conf->barrier);
3176
		bioset_exit(&conf->bio_split);
3177 3178 3179 3180 3181
		kfree(conf);
	}
	return ERR_PTR(err);
}

3182 3183 3184
static int raid1_set_limits(struct mddev *mddev)
{
	struct queue_limits lim;
3185
	int err;
3186

3187
	md_init_stacking_limits(&lim);
3188
	lim.max_write_zeroes_sectors = 0;
3189 3190 3191 3192 3193
	err = mddev_stack_rdev_limits(mddev, &lim, MDDEV_STACK_INTEGRITY);
	if (err) {
		queue_limits_cancel_update(mddev->gendisk->queue);
		return err;
	}
3194
	return queue_limits_set(mddev->gendisk->queue, &lim);
3195 3196
}

Shaohua Li's avatar
Shaohua Li committed
3197
static int raid1_run(struct mddev *mddev)
3198
{
3199
	struct r1conf *conf;
3200
	int i;
3201
	int ret;
3202 3203

	if (mddev->level != 1) {
3204 3205
		pr_warn("md/raid1:%s: raid level not set to mirroring (%d)\n",
			mdname(mddev), mddev->level);
3206 3207 3208
		return -EIO;
	}
	if (mddev->reshape_position != MaxSector) {
3209 3210
		pr_warn("md/raid1:%s: reshape_position set but not supported\n",
			mdname(mddev));
3211 3212
		return -EIO;
	}
3213

Linus Torvalds's avatar
Linus Torvalds committed
3214
	/*
3215 3216
	 * copy the already verified devices into our private RAID1
	 * bookkeeping area. [whatever we allocate in run(),
NeilBrown's avatar
NeilBrown committed
3217
	 * should be freed in raid1_free()]
Linus Torvalds's avatar
Linus Torvalds committed
3218
	 */
3219 3220 3221 3222
	if (mddev->private == NULL)
		conf = setup_conf(mddev);
	else
		conf = mddev->private;
Linus Torvalds's avatar
Linus Torvalds committed
3223

3224 3225
	if (IS_ERR(conf))
		return PTR_ERR(conf);
Linus Torvalds's avatar
Linus Torvalds committed
3226

3227
	if (!mddev_is_dm(mddev)) {
3228 3229
		ret = raid1_set_limits(mddev);
		if (ret)
3230
			return ret;
Linus Torvalds's avatar
Linus Torvalds committed
3231
	}
3232

3233
	mddev->degraded = 0;
3234
	for (i = 0; i < conf->raid_disks; i++)
3235 3236 3237 3238
		if (conf->mirrors[i].rdev == NULL ||
		    !test_bit(In_sync, &conf->mirrors[i].rdev->flags) ||
		    test_bit(Faulty, &conf->mirrors[i].rdev->flags))
			mddev->degraded++;
3239 3240 3241 3242
	/*
	 * RAID1 needs at least one disk in active
	 */
	if (conf->raid_disks - mddev->degraded < 1) {
3243
		md_unregister_thread(mddev, &conf->thread);
3244
		return -EINVAL;
3245
	}
3246 3247 3248 3249

	if (conf->raid_disks - mddev->degraded == 1)
		mddev->recovery_cp = MaxSector;

3250
	if (mddev->recovery_cp != MaxSector)
3251 3252 3253
		pr_info("md/raid1:%s: not clean -- starting background reconstruction\n",
			mdname(mddev));
	pr_info("md/raid1:%s: active with %d out of %d mirrors\n",
3254
		mdname(mddev), mddev->raid_disks - mddev->degraded,
Linus Torvalds's avatar
Linus Torvalds committed
3255
		mddev->raid_disks);
3256

Linus Torvalds's avatar
Linus Torvalds committed
3257 3258 3259
	/*
	 * Ok, everything is just fine now
	 */
Yu Kuai's avatar
Yu Kuai committed
3260 3261
	rcu_assign_pointer(mddev->thread, conf->thread);
	rcu_assign_pointer(conf->thread, NULL);
3262
	mddev->private = conf;
3263
	set_bit(MD_FAILFAST_SUPPORTED, &mddev->flags);
3264

3265
	md_set_array_sectors(mddev, raid1_size(mddev, 0, 0));
Linus Torvalds's avatar
Linus Torvalds committed
3266

3267
	ret = md_integrity_register(mddev);
3268
	if (ret)
3269
		md_unregister_thread(mddev, &mddev->thread);
3270
	return ret;
Linus Torvalds's avatar
Linus Torvalds committed
3271 3272
}

NeilBrown's avatar
NeilBrown committed
3273
static void raid1_free(struct mddev *mddev, void *priv)
Linus Torvalds's avatar
Linus Torvalds committed
3274
{
NeilBrown's avatar
NeilBrown committed
3275
	struct r1conf *conf = priv;
3276

3277
	mempool_exit(&conf->r1bio_pool);
3278
	kfree(conf->mirrors);
3279
	safe_put_page(conf->tmppage);
3280
	kfree(conf->poolinfo);
3281 3282 3283 3284
	kfree(conf->nr_pending);
	kfree(conf->nr_waiting);
	kfree(conf->nr_queued);
	kfree(conf->barrier);
3285
	bioset_exit(&conf->bio_split);
Linus Torvalds's avatar
Linus Torvalds committed
3286 3287 3288
	kfree(conf);
}

3289
static int raid1_resize(struct mddev *mddev, sector_t sectors)
Linus Torvalds's avatar
Linus Torvalds committed
3290 3291 3292 3293 3294 3295 3296 3297
{
	/* no resync is happening, and there is enough space
	 * on all devices, so we can resize.
	 * We need to make sure resync covers any new space.
	 * If the array is shrinking we should possibly wait until
	 * any io in the removed space completes, but it hardly seems
	 * worth it.
	 */
3298
	sector_t newsize = raid1_size(mddev, sectors, 0);
3299 3300
	int ret;

3301 3302
	if (mddev->external_size &&
	    mddev->array_sectors > newsize)
3303
		return -EINVAL;
3304

3305
	ret = mddev->bitmap_ops->resize(mddev, newsize, 0, false);
3306 3307 3308
	if (ret)
		return ret;

3309
	md_set_array_sectors(mddev, newsize);
3310
	if (sectors > mddev->dev_sectors &&
3311
	    mddev->recovery_cp > mddev->dev_sectors) {
3312
		mddev->recovery_cp = mddev->dev_sectors;
Linus Torvalds's avatar
Linus Torvalds committed
3313 3314
		set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
	}
3315
	mddev->dev_sectors = sectors;
3316
	mddev->resync_max_sectors = sectors;
Linus Torvalds's avatar
Linus Torvalds committed
3317 3318 3319
	return 0;
}

3320
static int raid1_reshape(struct mddev *mddev)
Linus Torvalds's avatar
Linus Torvalds committed
3321 3322 3323 3324 3325 3326 3327 3328
{
	/* We need to:
	 * 1/ resize the r1bio_pool
	 * 2/ resize conf->mirrors
	 *
	 * We allocate a new r1bio_pool if we can.
	 * Then raise a device barrier and wait until all IO stops.
	 * Then resize conf->mirrors and swap in the new r1bio pool.
3329 3330 3331
	 *
	 * At the same time, we "pack" the devices so that all the missing
	 * devices have the higher raid_disk numbers.
Linus Torvalds's avatar
Linus Torvalds committed
3332
	 */
3333
	mempool_t newpool, oldpool;
Linus Torvalds's avatar
Linus Torvalds committed
3334
	struct pool_info *newpoolinfo;
3335
	struct raid1_info *newmirrors;
3336
	struct r1conf *conf = mddev->private;
3337
	int cnt, raid_disks;
3338
	unsigned long flags;
3339
	int d, d2;
3340 3341 3342 3343
	int ret;

	memset(&newpool, 0, sizeof(newpool));
	memset(&oldpool, 0, sizeof(oldpool));
Linus Torvalds's avatar
Linus Torvalds committed
3344

3345
	/* Cannot change chunk_size, layout, or level */
3346
	if (mddev->chunk_sectors != mddev->new_chunk_sectors ||
3347 3348
	    mddev->layout != mddev->new_layout ||
	    mddev->level != mddev->new_level) {
3349
		mddev->new_chunk_sectors = mddev->chunk_sectors;
3350 3351 3352 3353 3354
		mddev->new_layout = mddev->layout;
		mddev->new_level = mddev->level;
		return -EINVAL;
	}

3355 3356
	if (!mddev_is_clustered(mddev))
		md_allow_write(mddev);
3357

3358 3359
	raid_disks = mddev->raid_disks + mddev->delta_disks;

3360 3361 3362 3363 3364 3365
	if (raid_disks < conf->raid_disks) {
		cnt=0;
		for (d= 0; d < conf->raid_disks; d++)
			if (conf->mirrors[d].rdev)
				cnt++;
		if (cnt > raid_disks)
Linus Torvalds's avatar
Linus Torvalds committed
3366
			return -EBUSY;
3367
	}
Linus Torvalds's avatar
Linus Torvalds committed
3368 3369 3370 3371 3372

	newpoolinfo = kmalloc(sizeof(*newpoolinfo), GFP_KERNEL);
	if (!newpoolinfo)
		return -ENOMEM;
	newpoolinfo->mddev = mddev;
3373
	newpoolinfo->raid_disks = raid_disks * 2;
Linus Torvalds's avatar
Linus Torvalds committed
3374

3375
	ret = mempool_init(&newpool, NR_RAID_BIOS, r1bio_pool_alloc,
3376
			   rbio_pool_free, newpoolinfo);
3377
	if (ret) {
Linus Torvalds's avatar
Linus Torvalds committed
3378
		kfree(newpoolinfo);
3379
		return ret;
Linus Torvalds's avatar
Linus Torvalds committed
3380
	}
3381 3382
	newmirrors = kzalloc(array3_size(sizeof(struct raid1_info),
					 raid_disks, 2),
3383
			     GFP_KERNEL);
Linus Torvalds's avatar
Linus Torvalds committed
3384 3385
	if (!newmirrors) {
		kfree(newpoolinfo);
3386
		mempool_exit(&newpool);
Linus Torvalds's avatar
Linus Torvalds committed
3387 3388 3389
		return -ENOMEM;
	}

3390
	freeze_array(conf, 0);
Linus Torvalds's avatar
Linus Torvalds committed
3391 3392 3393 3394

	/* ok, everything is stopped */
	oldpool = conf->r1bio_pool;
	conf->r1bio_pool = newpool;
3395

3396
	for (d = d2 = 0; d < conf->raid_disks; d++) {
3397
		struct md_rdev *rdev = conf->mirrors[d].rdev;
3398
		if (rdev && rdev->raid_disk != d2) {
3399
			sysfs_unlink_rdev(mddev, rdev);
3400
			rdev->raid_disk = d2;
3401 3402
			sysfs_unlink_rdev(mddev, rdev);
			if (sysfs_link_rdev(mddev, rdev))
3403 3404
				pr_warn("md/raid1:%s: cannot register rd%d\n",
					mdname(mddev), rdev->raid_disk);
3405
		}
3406 3407 3408
		if (rdev)
			newmirrors[d2++].rdev = rdev;
	}
Linus Torvalds's avatar
Linus Torvalds committed
3409 3410 3411 3412 3413
	kfree(conf->mirrors);
	conf->mirrors = newmirrors;
	kfree(conf->poolinfo);
	conf->poolinfo = newpoolinfo;

3414
	spin_lock_irqsave(&conf->device_lock, flags);
Linus Torvalds's avatar
Linus Torvalds committed
3415
	mddev->degraded += (raid_disks - conf->raid_disks);
3416
	spin_unlock_irqrestore(&conf->device_lock, flags);
Linus Torvalds's avatar
Linus Torvalds committed
3417
	conf->raid_disks = mddev->raid_disks = raid_disks;
3418
	mddev->delta_disks = 0;
Linus Torvalds's avatar
Linus Torvalds committed
3419

3420
	unfreeze_array(conf);
Linus Torvalds's avatar
Linus Torvalds committed
3421

3422
	set_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
Linus Torvalds's avatar
Linus Torvalds committed
3423 3424 3425
	set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
	md_wakeup_thread(mddev->thread);

3426
	mempool_exit(&oldpool);
Linus Torvalds's avatar
Linus Torvalds committed
3427 3428 3429
	return 0;
}

3430
static void raid1_quiesce(struct mddev *mddev, int quiesce)
3431
{
3432
	struct r1conf *conf = mddev->private;
3433

3434
	if (quiesce)
3435
		freeze_array(conf, 0);
3436
	else
3437
		unfreeze_array(conf);
3438 3439
}

3440
static void *raid1_takeover(struct mddev *mddev)
3441 3442 3443 3444 3445
{
	/* raid1 can take over:
	 *  raid5 with 2 devices, any layout or chunk size
	 */
	if (mddev->level == 5 && mddev->raid_disks == 2) {
3446
		struct r1conf *conf;
3447 3448 3449 3450
		mddev->new_level = 1;
		mddev->new_layout = 0;
		mddev->new_chunk_sectors = 0;
		conf = setup_conf(mddev);
3451
		if (!IS_ERR(conf)) {
3452 3453
			/* Array must appear to be quiesced */
			conf->array_frozen = 1;
3454 3455
			mddev_clear_unsupported_flags(mddev,
				UNSUPPORTED_MDDEV_FLAGS);
3456
		}
3457 3458 3459 3460
		return conf;
	}
	return ERR_PTR(-EINVAL);
}
Linus Torvalds's avatar
Linus Torvalds committed
3461

3462
static struct md_personality raid1_personality =
Linus Torvalds's avatar
Linus Torvalds committed
3463 3464
{
	.name		= "raid1",
3465
	.level		= 1,
Linus Torvalds's avatar
Linus Torvalds committed
3466
	.owner		= THIS_MODULE,
Shaohua Li's avatar
Shaohua Li committed
3467 3468
	.make_request	= raid1_make_request,
	.run		= raid1_run,
NeilBrown's avatar
NeilBrown committed
3469
	.free		= raid1_free,
Shaohua Li's avatar
Shaohua Li committed
3470 3471
	.status		= raid1_status,
	.error_handler	= raid1_error,
Linus Torvalds's avatar
Linus Torvalds committed
3472 3473 3474
	.hot_add_disk	= raid1_add_disk,
	.hot_remove_disk= raid1_remove_disk,
	.spare_active	= raid1_spare_active,
Shaohua Li's avatar
Shaohua Li committed
3475
	.sync_request	= raid1_sync_request,
Linus Torvalds's avatar
Linus Torvalds committed
3476
	.resize		= raid1_resize,
3477
	.size		= raid1_size,
3478
	.check_reshape	= raid1_reshape,
3479
	.quiesce	= raid1_quiesce,
3480
	.takeover	= raid1_takeover,
Linus Torvalds's avatar
Linus Torvalds committed
3481 3482 3483 3484
};

static int __init raid_init(void)
{
3485
	return register_md_personality(&raid1_personality);
Linus Torvalds's avatar
Linus Torvalds committed
3486 3487 3488 3489
}

static void raid_exit(void)
{
3490
	unregister_md_personality(&raid1_personality);
Linus Torvalds's avatar
Linus Torvalds committed
3491 3492 3493 3494 3495
}

module_init(raid_init);
module_exit(raid_exit);
MODULE_LICENSE("GPL");
3496
MODULE_DESCRIPTION("RAID1 (mirroring) personality for MD");
Linus Torvalds's avatar
Linus Torvalds committed
3497
MODULE_ALIAS("md-personality-3"); /* RAID1 */
3498
MODULE_ALIAS("md-raid1");
3499
MODULE_ALIAS("md-level-1");