1 /*
2  * raid10.c : Multiple Devices driver for Linux
3  *
4  * Copyright (C) 2000-2004 Neil Brown
5  *
6  * RAID-10 support for md.
7  *
8  * Base on code in raid1.c.  See raid1.c for further copyright information.
9  *
10  *
11  * This program is free software; you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation; either version 2, or (at your option)
14  * any later version.
15  *
16  * You should have received a copy of the GNU General Public License
17  * (for example /usr/src/linux/COPYING); if not, write to the Free
18  * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19  */
20 
21 #include <linux/slab.h>
22 #include <linux/delay.h>
23 #include <linux/blkdev.h>
24 #include <linux/module.h>
25 #include <linux/seq_file.h>
26 #include <linux/ratelimit.h>
27 #include "md.h"
28 #include "raid10.h"
29 #include "raid0.h"
30 #include "bitmap.h"
31 
32 /*
33  * RAID10 provides a combination of RAID0 and RAID1 functionality.
34  * The layout of data is defined by
35  *    chunk_size
36  *    raid_disks
37  *    near_copies (stored in low byte of layout)
38  *    far_copies (stored in second byte of layout)
39  *    far_offset (stored in bit 16 of layout )
40  *
41  * The data to be stored is divided into chunks using chunksize.
42  * Each device is divided into far_copies sections.
43  * In each section, chunks are laid out in a style similar to raid0, but
44  * near_copies copies of each chunk is stored (each on a different drive).
45  * The starting device for each section is offset near_copies from the starting
46  * device of the previous section.
47  * Thus they are (near_copies*far_copies) of each chunk, and each is on a different
48  * drive.
49  * near_copies and far_copies must be at least one, and their product is at most
50  * raid_disks.
51  *
52  * If far_offset is true, then the far_copies are handled a bit differently.
53  * The copies are still in different stripes, but instead of be very far apart
54  * on disk, there are adjacent stripes.
55  */
56 
57 /*
58  * Number of guaranteed r10bios in case of extreme VM load:
59  */
60 #define	NR_RAID10_BIOS 256
61 
62 /* When there are this many requests queue to be written by
63  * the raid10 thread, we become 'congested' to provide back-pressure
64  * for writeback.
65  */
66 static int max_queued_requests = 1024;
67 
68 static void allow_barrier(struct r10conf *conf);
69 static void lower_barrier(struct r10conf *conf);
70 static int enough(struct r10conf *conf, int ignore);
71 
r10bio_pool_alloc(gfp_t gfp_flags,void * data)72 static void * r10bio_pool_alloc(gfp_t gfp_flags, void *data)
73 {
74 	struct r10conf *conf = data;
75 	int size = offsetof(struct r10bio, devs[conf->copies]);
76 
77 	/* allocate a r10bio with room for raid_disks entries in the
78 	 * bios array */
79 	return kzalloc(size, gfp_flags);
80 }
81 
r10bio_pool_free(void * r10_bio,void * data)82 static void r10bio_pool_free(void *r10_bio, void *data)
83 {
84 	kfree(r10_bio);
85 }
86 
87 /* Maximum size of each resync request */
88 #define RESYNC_BLOCK_SIZE (64*1024)
89 #define RESYNC_PAGES ((RESYNC_BLOCK_SIZE + PAGE_SIZE-1) / PAGE_SIZE)
90 /* amount of memory to reserve for resync requests */
91 #define RESYNC_WINDOW (1024*1024)
92 /* maximum number of concurrent requests, memory permitting */
93 #define RESYNC_DEPTH (32*1024*1024/RESYNC_BLOCK_SIZE)
94 
95 /*
96  * When performing a resync, we need to read and compare, so
97  * we need as many pages are there are copies.
98  * When performing a recovery, we need 2 bios, one for read,
99  * one for write (we recover only one drive per r10buf)
100  *
101  */
r10buf_pool_alloc(gfp_t gfp_flags,void * data)102 static void * r10buf_pool_alloc(gfp_t gfp_flags, void *data)
103 {
104 	struct r10conf *conf = data;
105 	struct page *page;
106 	struct r10bio *r10_bio;
107 	struct bio *bio;
108 	int i, j;
109 	int nalloc;
110 
111 	r10_bio = r10bio_pool_alloc(gfp_flags, conf);
112 	if (!r10_bio)
113 		return NULL;
114 
115 	if (test_bit(MD_RECOVERY_SYNC, &conf->mddev->recovery))
116 		nalloc = conf->copies; /* resync */
117 	else
118 		nalloc = 2; /* recovery */
119 
120 	/*
121 	 * Allocate bios.
122 	 */
123 	for (j = nalloc ; j-- ; ) {
124 		bio = bio_kmalloc(gfp_flags, RESYNC_PAGES);
125 		if (!bio)
126 			goto out_free_bio;
127 		r10_bio->devs[j].bio = bio;
128 		if (!conf->have_replacement)
129 			continue;
130 		bio = bio_kmalloc(gfp_flags, RESYNC_PAGES);
131 		if (!bio)
132 			goto out_free_bio;
133 		r10_bio->devs[j].repl_bio = bio;
134 	}
135 	/*
136 	 * Allocate RESYNC_PAGES data pages and attach them
137 	 * where needed.
138 	 */
139 	for (j = 0 ; j < nalloc; j++) {
140 		struct bio *rbio = r10_bio->devs[j].repl_bio;
141 		bio = r10_bio->devs[j].bio;
142 		for (i = 0; i < RESYNC_PAGES; i++) {
143 			if (j == 1 && !test_bit(MD_RECOVERY_SYNC,
144 						&conf->mddev->recovery)) {
145 				/* we can share bv_page's during recovery */
146 				struct bio *rbio = r10_bio->devs[0].bio;
147 				page = rbio->bi_io_vec[i].bv_page;
148 				get_page(page);
149 			} else
150 				page = alloc_page(gfp_flags);
151 			if (unlikely(!page))
152 				goto out_free_pages;
153 
154 			bio->bi_io_vec[i].bv_page = page;
155 			if (rbio)
156 				rbio->bi_io_vec[i].bv_page = page;
157 		}
158 	}
159 
160 	return r10_bio;
161 
162 out_free_pages:
163 	for ( ; i > 0 ; i--)
164 		safe_put_page(bio->bi_io_vec[i-1].bv_page);
165 	while (j--)
166 		for (i = 0; i < RESYNC_PAGES ; i++)
167 			safe_put_page(r10_bio->devs[j].bio->bi_io_vec[i].bv_page);
168 	j = -1;
169 out_free_bio:
170 	while (++j < nalloc) {
171 		bio_put(r10_bio->devs[j].bio);
172 		if (r10_bio->devs[j].repl_bio)
173 			bio_put(r10_bio->devs[j].repl_bio);
174 	}
175 	r10bio_pool_free(r10_bio, conf);
176 	return NULL;
177 }
178 
r10buf_pool_free(void * __r10_bio,void * data)179 static void r10buf_pool_free(void *__r10_bio, void *data)
180 {
181 	int i;
182 	struct r10conf *conf = data;
183 	struct r10bio *r10bio = __r10_bio;
184 	int j;
185 
186 	for (j=0; j < conf->copies; j++) {
187 		struct bio *bio = r10bio->devs[j].bio;
188 		if (bio) {
189 			for (i = 0; i < RESYNC_PAGES; i++) {
190 				safe_put_page(bio->bi_io_vec[i].bv_page);
191 				bio->bi_io_vec[i].bv_page = NULL;
192 			}
193 			bio_put(bio);
194 		}
195 		bio = r10bio->devs[j].repl_bio;
196 		if (bio)
197 			bio_put(bio);
198 	}
199 	r10bio_pool_free(r10bio, conf);
200 }
201 
put_all_bios(struct r10conf * conf,struct r10bio * r10_bio)202 static void put_all_bios(struct r10conf *conf, struct r10bio *r10_bio)
203 {
204 	int i;
205 
206 	for (i = 0; i < conf->copies; i++) {
207 		struct bio **bio = & r10_bio->devs[i].bio;
208 		if (!BIO_SPECIAL(*bio))
209 			bio_put(*bio);
210 		*bio = NULL;
211 		bio = &r10_bio->devs[i].repl_bio;
212 		if (r10_bio->read_slot < 0 && !BIO_SPECIAL(*bio))
213 			bio_put(*bio);
214 		*bio = NULL;
215 	}
216 }
217 
free_r10bio(struct r10bio * r10_bio)218 static void free_r10bio(struct r10bio *r10_bio)
219 {
220 	struct r10conf *conf = r10_bio->mddev->private;
221 
222 	put_all_bios(conf, r10_bio);
223 	mempool_free(r10_bio, conf->r10bio_pool);
224 }
225 
put_buf(struct r10bio * r10_bio)226 static void put_buf(struct r10bio *r10_bio)
227 {
228 	struct r10conf *conf = r10_bio->mddev->private;
229 
230 	mempool_free(r10_bio, conf->r10buf_pool);
231 
232 	lower_barrier(conf);
233 }
234 
reschedule_retry(struct r10bio * r10_bio)235 static void reschedule_retry(struct r10bio *r10_bio)
236 {
237 	unsigned long flags;
238 	struct mddev *mddev = r10_bio->mddev;
239 	struct r10conf *conf = mddev->private;
240 
241 	spin_lock_irqsave(&conf->device_lock, flags);
242 	list_add(&r10_bio->retry_list, &conf->retry_list);
243 	conf->nr_queued ++;
244 	spin_unlock_irqrestore(&conf->device_lock, flags);
245 
246 	/* wake up frozen array... */
247 	wake_up(&conf->wait_barrier);
248 
249 	md_wakeup_thread(mddev->thread);
250 }
251 
252 /*
253  * raid_end_bio_io() is called when we have finished servicing a mirrored
254  * operation and are ready to return a success/failure code to the buffer
255  * cache layer.
256  */
raid_end_bio_io(struct r10bio * r10_bio)257 static void raid_end_bio_io(struct r10bio *r10_bio)
258 {
259 	struct bio *bio = r10_bio->master_bio;
260 	int done;
261 	struct r10conf *conf = r10_bio->mddev->private;
262 
263 	if (bio->bi_phys_segments) {
264 		unsigned long flags;
265 		spin_lock_irqsave(&conf->device_lock, flags);
266 		bio->bi_phys_segments--;
267 		done = (bio->bi_phys_segments == 0);
268 		spin_unlock_irqrestore(&conf->device_lock, flags);
269 	} else
270 		done = 1;
271 	if (!test_bit(R10BIO_Uptodate, &r10_bio->state))
272 		clear_bit(BIO_UPTODATE, &bio->bi_flags);
273 	if (done) {
274 		bio_endio(bio, 0);
275 		/*
276 		 * Wake up any possible resync thread that waits for the device
277 		 * to go idle.
278 		 */
279 		allow_barrier(conf);
280 	}
281 	free_r10bio(r10_bio);
282 }
283 
284 /*
285  * Update disk head position estimator based on IRQ completion info.
286  */
update_head_pos(int slot,struct r10bio * r10_bio)287 static inline void update_head_pos(int slot, struct r10bio *r10_bio)
288 {
289 	struct r10conf *conf = r10_bio->mddev->private;
290 
291 	conf->mirrors[r10_bio->devs[slot].devnum].head_position =
292 		r10_bio->devs[slot].addr + (r10_bio->sectors);
293 }
294 
295 /*
296  * Find the disk number which triggered given bio
297  */
find_bio_disk(struct r10conf * conf,struct r10bio * r10_bio,struct bio * bio,int * slotp,int * replp)298 static int find_bio_disk(struct r10conf *conf, struct r10bio *r10_bio,
299 			 struct bio *bio, int *slotp, int *replp)
300 {
301 	int slot;
302 	int repl = 0;
303 
304 	for (slot = 0; slot < conf->copies; slot++) {
305 		if (r10_bio->devs[slot].bio == bio)
306 			break;
307 		if (r10_bio->devs[slot].repl_bio == bio) {
308 			repl = 1;
309 			break;
310 		}
311 	}
312 
313 	BUG_ON(slot == conf->copies);
314 	update_head_pos(slot, r10_bio);
315 
316 	if (slotp)
317 		*slotp = slot;
318 	if (replp)
319 		*replp = repl;
320 	return r10_bio->devs[slot].devnum;
321 }
322 
raid10_end_read_request(struct bio * bio,int error)323 static void raid10_end_read_request(struct bio *bio, int error)
324 {
325 	int uptodate = test_bit(BIO_UPTODATE, &bio->bi_flags);
326 	struct r10bio *r10_bio = bio->bi_private;
327 	int slot, dev;
328 	struct md_rdev *rdev;
329 	struct r10conf *conf = r10_bio->mddev->private;
330 
331 
332 	slot = r10_bio->read_slot;
333 	dev = r10_bio->devs[slot].devnum;
334 	rdev = r10_bio->devs[slot].rdev;
335 	/*
336 	 * this branch is our 'one mirror IO has finished' event handler:
337 	 */
338 	update_head_pos(slot, r10_bio);
339 
340 	if (uptodate) {
341 		/*
342 		 * Set R10BIO_Uptodate in our master bio, so that
343 		 * we will return a good error code to the higher
344 		 * levels even if IO on some other mirrored buffer fails.
345 		 *
346 		 * The 'master' represents the composite IO operation to
347 		 * user-side. So if something waits for IO, then it will
348 		 * wait for the 'master' bio.
349 		 */
350 		set_bit(R10BIO_Uptodate, &r10_bio->state);
351 	} else {
352 		/* If all other devices that store this block have
353 		 * failed, we want to return the error upwards rather
354 		 * than fail the last device.  Here we redefine
355 		 * "uptodate" to mean "Don't want to retry"
356 		 */
357 		unsigned long flags;
358 		spin_lock_irqsave(&conf->device_lock, flags);
359 		if (!enough(conf, rdev->raid_disk))
360 			uptodate = 1;
361 		spin_unlock_irqrestore(&conf->device_lock, flags);
362 	}
363 	if (uptodate) {
364 		raid_end_bio_io(r10_bio);
365 		rdev_dec_pending(rdev, conf->mddev);
366 	} else {
367 		/*
368 		 * oops, read error - keep the refcount on the rdev
369 		 */
370 		char b[BDEVNAME_SIZE];
371 		printk_ratelimited(KERN_ERR
372 				   "md/raid10:%s: %s: rescheduling sector %llu\n",
373 				   mdname(conf->mddev),
374 				   bdevname(rdev->bdev, b),
375 				   (unsigned long long)r10_bio->sector);
376 		set_bit(R10BIO_ReadError, &r10_bio->state);
377 		reschedule_retry(r10_bio);
378 	}
379 }
380 
close_write(struct r10bio * r10_bio)381 static void close_write(struct r10bio *r10_bio)
382 {
383 	/* clear the bitmap if all writes complete successfully */
384 	bitmap_endwrite(r10_bio->mddev->bitmap, r10_bio->sector,
385 			r10_bio->sectors,
386 			!test_bit(R10BIO_Degraded, &r10_bio->state),
387 			0);
388 	md_write_end(r10_bio->mddev);
389 }
390 
one_write_done(struct r10bio * r10_bio)391 static void one_write_done(struct r10bio *r10_bio)
392 {
393 	if (atomic_dec_and_test(&r10_bio->remaining)) {
394 		if (test_bit(R10BIO_WriteError, &r10_bio->state))
395 			reschedule_retry(r10_bio);
396 		else {
397 			close_write(r10_bio);
398 			if (test_bit(R10BIO_MadeGood, &r10_bio->state))
399 				reschedule_retry(r10_bio);
400 			else
401 				raid_end_bio_io(r10_bio);
402 		}
403 	}
404 }
405 
raid10_end_write_request(struct bio * bio,int error)406 static void raid10_end_write_request(struct bio *bio, int error)
407 {
408 	int uptodate = test_bit(BIO_UPTODATE, &bio->bi_flags);
409 	struct r10bio *r10_bio = bio->bi_private;
410 	int dev;
411 	int dec_rdev = 1;
412 	struct r10conf *conf = r10_bio->mddev->private;
413 	int slot, repl;
414 	struct md_rdev *rdev = NULL;
415 
416 	dev = find_bio_disk(conf, r10_bio, bio, &slot, &repl);
417 
418 	if (repl)
419 		rdev = conf->mirrors[dev].replacement;
420 	if (!rdev) {
421 		smp_rmb();
422 		repl = 0;
423 		rdev = conf->mirrors[dev].rdev;
424 	}
425 	/*
426 	 * this branch is our 'one mirror IO has finished' event handler:
427 	 */
428 	if (!uptodate) {
429 		if (repl)
430 			/* Never record new bad blocks to replacement,
431 			 * just fail it.
432 			 */
433 			md_error(rdev->mddev, rdev);
434 		else {
435 			set_bit(WriteErrorSeen,	&rdev->flags);
436 			if (!test_and_set_bit(WantReplacement, &rdev->flags))
437 				set_bit(MD_RECOVERY_NEEDED,
438 					&rdev->mddev->recovery);
439 			set_bit(R10BIO_WriteError, &r10_bio->state);
440 			dec_rdev = 0;
441 		}
442 	} else {
443 		/*
444 		 * Set R10BIO_Uptodate in our master bio, so that
445 		 * we will return a good error code for to the higher
446 		 * levels even if IO on some other mirrored buffer fails.
447 		 *
448 		 * The 'master' represents the composite IO operation to
449 		 * user-side. So if something waits for IO, then it will
450 		 * wait for the 'master' bio.
451 		 */
452 		sector_t first_bad;
453 		int bad_sectors;
454 
455 		/*
456 		 * Do not set R10BIO_Uptodate if the current device is
457 		 * rebuilding or Faulty. This is because we cannot use
458 		 * such device for properly reading the data back (we could
459 		 * potentially use it, if the current write would have felt
460 		 * before rdev->recovery_offset, but for simplicity we don't
461 		 * check this here.
462 		 */
463 		if (test_bit(In_sync, &rdev->flags) &&
464 		    !test_bit(Faulty, &rdev->flags))
465 			set_bit(R10BIO_Uptodate, &r10_bio->state);
466 
467 		/* Maybe we can clear some bad blocks. */
468 		if (is_badblock(rdev,
469 				r10_bio->devs[slot].addr,
470 				r10_bio->sectors,
471 				&first_bad, &bad_sectors)) {
472 			bio_put(bio);
473 			if (repl)
474 				r10_bio->devs[slot].repl_bio = IO_MADE_GOOD;
475 			else
476 				r10_bio->devs[slot].bio = IO_MADE_GOOD;
477 			dec_rdev = 0;
478 			set_bit(R10BIO_MadeGood, &r10_bio->state);
479 		}
480 	}
481 
482 	/*
483 	 *
484 	 * Let's see if all mirrored write operations have finished
485 	 * already.
486 	 */
487 	one_write_done(r10_bio);
488 	if (dec_rdev)
489 		rdev_dec_pending(rdev, conf->mddev);
490 }
491 
492 /*
493  * RAID10 layout manager
494  * As well as the chunksize and raid_disks count, there are two
495  * parameters: near_copies and far_copies.
496  * near_copies * far_copies must be <= raid_disks.
497  * Normally one of these will be 1.
498  * If both are 1, we get raid0.
499  * If near_copies == raid_disks, we get raid1.
500  *
501  * Chunks are laid out in raid0 style with near_copies copies of the
502  * first chunk, followed by near_copies copies of the next chunk and
503  * so on.
504  * If far_copies > 1, then after 1/far_copies of the array has been assigned
505  * as described above, we start again with a device offset of near_copies.
506  * So we effectively have another copy of the whole array further down all
507  * the drives, but with blocks on different drives.
508  * With this layout, and block is never stored twice on the one device.
509  *
510  * raid10_find_phys finds the sector offset of a given virtual sector
511  * on each device that it is on.
512  *
513  * raid10_find_virt does the reverse mapping, from a device and a
514  * sector offset to a virtual address
515  */
516 
raid10_find_phys(struct r10conf * conf,struct r10bio * r10bio)517 static void raid10_find_phys(struct r10conf *conf, struct r10bio *r10bio)
518 {
519 	int n,f;
520 	sector_t sector;
521 	sector_t chunk;
522 	sector_t stripe;
523 	int dev;
524 
525 	int slot = 0;
526 
527 	/* now calculate first sector/dev */
528 	chunk = r10bio->sector >> conf->chunk_shift;
529 	sector = r10bio->sector & conf->chunk_mask;
530 
531 	chunk *= conf->near_copies;
532 	stripe = chunk;
533 	dev = sector_div(stripe, conf->raid_disks);
534 	if (conf->far_offset)
535 		stripe *= conf->far_copies;
536 
537 	sector += stripe << conf->chunk_shift;
538 
539 	/* and calculate all the others */
540 	for (n=0; n < conf->near_copies; n++) {
541 		int d = dev;
542 		sector_t s = sector;
543 		r10bio->devs[slot].addr = sector;
544 		r10bio->devs[slot].devnum = d;
545 		slot++;
546 
547 		for (f = 1; f < conf->far_copies; f++) {
548 			d += conf->near_copies;
549 			if (d >= conf->raid_disks)
550 				d -= conf->raid_disks;
551 			s += conf->stride;
552 			r10bio->devs[slot].devnum = d;
553 			r10bio->devs[slot].addr = s;
554 			slot++;
555 		}
556 		dev++;
557 		if (dev >= conf->raid_disks) {
558 			dev = 0;
559 			sector += (conf->chunk_mask + 1);
560 		}
561 	}
562 	BUG_ON(slot != conf->copies);
563 }
564 
raid10_find_virt(struct r10conf * conf,sector_t sector,int dev)565 static sector_t raid10_find_virt(struct r10conf *conf, sector_t sector, int dev)
566 {
567 	sector_t offset, chunk, vchunk;
568 
569 	offset = sector & conf->chunk_mask;
570 	if (conf->far_offset) {
571 		int fc;
572 		chunk = sector >> conf->chunk_shift;
573 		fc = sector_div(chunk, conf->far_copies);
574 		dev -= fc * conf->near_copies;
575 		if (dev < 0)
576 			dev += conf->raid_disks;
577 	} else {
578 		while (sector >= conf->stride) {
579 			sector -= conf->stride;
580 			if (dev < conf->near_copies)
581 				dev += conf->raid_disks - conf->near_copies;
582 			else
583 				dev -= conf->near_copies;
584 		}
585 		chunk = sector >> conf->chunk_shift;
586 	}
587 	vchunk = chunk * conf->raid_disks + dev;
588 	sector_div(vchunk, conf->near_copies);
589 	return (vchunk << conf->chunk_shift) + offset;
590 }
591 
592 /**
593  *	raid10_mergeable_bvec -- tell bio layer if a two requests can be merged
594  *	@q: request queue
595  *	@bvm: properties of new bio
596  *	@biovec: the request that could be merged to it.
597  *
598  *	Return amount of bytes we can accept at this offset
599  *	This requires checking for end-of-chunk if near_copies != raid_disks,
600  *	and for subordinate merge_bvec_fns if merge_check_needed.
601  */
raid10_mergeable_bvec(struct request_queue * q,struct bvec_merge_data * bvm,struct bio_vec * biovec)602 static int raid10_mergeable_bvec(struct request_queue *q,
603 				 struct bvec_merge_data *bvm,
604 				 struct bio_vec *biovec)
605 {
606 	struct mddev *mddev = q->queuedata;
607 	struct r10conf *conf = mddev->private;
608 	sector_t sector = bvm->bi_sector + get_start_sect(bvm->bi_bdev);
609 	int max;
610 	unsigned int chunk_sectors = mddev->chunk_sectors;
611 	unsigned int bio_sectors = bvm->bi_size >> 9;
612 
613 	if (conf->near_copies < conf->raid_disks) {
614 		max = (chunk_sectors - ((sector & (chunk_sectors - 1))
615 					+ bio_sectors)) << 9;
616 		if (max < 0)
617 			/* bio_add cannot handle a negative return */
618 			max = 0;
619 		if (max <= biovec->bv_len && bio_sectors == 0)
620 			return biovec->bv_len;
621 	} else
622 		max = biovec->bv_len;
623 
624 	if (mddev->merge_check_needed) {
625 		struct {
626 			struct r10bio r10_bio;
627 			struct r10dev devs[conf->copies];
628 		} on_stack;
629 		struct r10bio *r10_bio = &on_stack.r10_bio;
630 		int s;
631 		r10_bio->sector = sector;
632 		raid10_find_phys(conf, r10_bio);
633 		rcu_read_lock();
634 		for (s = 0; s < conf->copies; s++) {
635 			int disk = r10_bio->devs[s].devnum;
636 			struct md_rdev *rdev = rcu_dereference(
637 				conf->mirrors[disk].rdev);
638 			if (rdev && !test_bit(Faulty, &rdev->flags)) {
639 				struct request_queue *q =
640 					bdev_get_queue(rdev->bdev);
641 				if (q->merge_bvec_fn) {
642 					bvm->bi_sector = r10_bio->devs[s].addr
643 						+ rdev->data_offset;
644 					bvm->bi_bdev = rdev->bdev;
645 					max = min(max, q->merge_bvec_fn(
646 							  q, bvm, biovec));
647 				}
648 			}
649 			rdev = rcu_dereference(conf->mirrors[disk].replacement);
650 			if (rdev && !test_bit(Faulty, &rdev->flags)) {
651 				struct request_queue *q =
652 					bdev_get_queue(rdev->bdev);
653 				if (q->merge_bvec_fn) {
654 					bvm->bi_sector = r10_bio->devs[s].addr
655 						+ rdev->data_offset;
656 					bvm->bi_bdev = rdev->bdev;
657 					max = min(max, q->merge_bvec_fn(
658 							  q, bvm, biovec));
659 				}
660 			}
661 		}
662 		rcu_read_unlock();
663 	}
664 	return max;
665 }
666 
667 /*
668  * This routine returns the disk from which the requested read should
669  * be done. There is a per-array 'next expected sequential IO' sector
670  * number - if this matches on the next IO then we use the last disk.
671  * There is also a per-disk 'last know head position' sector that is
672  * maintained from IRQ contexts, both the normal and the resync IO
673  * completion handlers update this position correctly. If there is no
674  * perfect sequential match then we pick the disk whose head is closest.
675  *
676  * If there are 2 mirrors in the same 2 devices, performance degrades
677  * because position is mirror, not device based.
678  *
679  * The rdev for the device selected will have nr_pending incremented.
680  */
681 
682 /*
683  * FIXME: possibly should rethink readbalancing and do it differently
684  * depending on near_copies / far_copies geometry.
685  */
read_balance(struct r10conf * conf,struct r10bio * r10_bio,int * max_sectors)686 static struct md_rdev *read_balance(struct r10conf *conf,
687 				    struct r10bio *r10_bio,
688 				    int *max_sectors)
689 {
690 	const sector_t this_sector = r10_bio->sector;
691 	int disk, slot;
692 	int sectors = r10_bio->sectors;
693 	int best_good_sectors;
694 	sector_t new_distance, best_dist;
695 	struct md_rdev *rdev, *best_rdev;
696 	int do_balance;
697 	int best_slot;
698 
699 	raid10_find_phys(conf, r10_bio);
700 	rcu_read_lock();
701 retry:
702 	sectors = r10_bio->sectors;
703 	best_slot = -1;
704 	best_rdev = NULL;
705 	best_dist = MaxSector;
706 	best_good_sectors = 0;
707 	do_balance = 1;
708 	/*
709 	 * Check if we can balance. We can balance on the whole
710 	 * device if no resync is going on (recovery is ok), or below
711 	 * the resync window. We take the first readable disk when
712 	 * above the resync window.
713 	 */
714 	if (conf->mddev->recovery_cp < MaxSector
715 	    && (this_sector + sectors >= conf->next_resync))
716 		do_balance = 0;
717 
718 	for (slot = 0; slot < conf->copies ; slot++) {
719 		sector_t first_bad;
720 		int bad_sectors;
721 		sector_t dev_sector;
722 
723 		if (r10_bio->devs[slot].bio == IO_BLOCKED)
724 			continue;
725 		disk = r10_bio->devs[slot].devnum;
726 		rdev = rcu_dereference(conf->mirrors[disk].replacement);
727 		if (rdev == NULL || test_bit(Faulty, &rdev->flags) ||
728 		    test_bit(Unmerged, &rdev->flags) ||
729 		    r10_bio->devs[slot].addr + sectors > rdev->recovery_offset)
730 			rdev = rcu_dereference(conf->mirrors[disk].rdev);
731 		if (rdev == NULL ||
732 		    test_bit(Faulty, &rdev->flags) ||
733 		    test_bit(Unmerged, &rdev->flags))
734 			continue;
735 		if (!test_bit(In_sync, &rdev->flags) &&
736 		    r10_bio->devs[slot].addr + sectors > rdev->recovery_offset)
737 			continue;
738 
739 		dev_sector = r10_bio->devs[slot].addr;
740 		if (is_badblock(rdev, dev_sector, sectors,
741 				&first_bad, &bad_sectors)) {
742 			if (best_dist < MaxSector)
743 				/* Already have a better slot */
744 				continue;
745 			if (first_bad <= dev_sector) {
746 				/* Cannot read here.  If this is the
747 				 * 'primary' device, then we must not read
748 				 * beyond 'bad_sectors' from another device.
749 				 */
750 				bad_sectors -= (dev_sector - first_bad);
751 				if (!do_balance && sectors > bad_sectors)
752 					sectors = bad_sectors;
753 				if (best_good_sectors > sectors)
754 					best_good_sectors = sectors;
755 			} else {
756 				sector_t good_sectors =
757 					first_bad - dev_sector;
758 				if (good_sectors > best_good_sectors) {
759 					best_good_sectors = good_sectors;
760 					best_slot = slot;
761 					best_rdev = rdev;
762 				}
763 				if (!do_balance)
764 					/* Must read from here */
765 					break;
766 			}
767 			continue;
768 		} else
769 			best_good_sectors = sectors;
770 
771 		if (!do_balance)
772 			break;
773 
774 		/* This optimisation is debatable, and completely destroys
775 		 * sequential read speed for 'far copies' arrays.  So only
776 		 * keep it for 'near' arrays, and review those later.
777 		 */
778 		if (conf->near_copies > 1 && !atomic_read(&rdev->nr_pending))
779 			break;
780 
781 		/* for far > 1 always use the lowest address */
782 		if (conf->far_copies > 1)
783 			new_distance = r10_bio->devs[slot].addr;
784 		else
785 			new_distance = abs(r10_bio->devs[slot].addr -
786 					   conf->mirrors[disk].head_position);
787 		if (new_distance < best_dist) {
788 			best_dist = new_distance;
789 			best_slot = slot;
790 			best_rdev = rdev;
791 		}
792 	}
793 	if (slot >= conf->copies) {
794 		slot = best_slot;
795 		rdev = best_rdev;
796 	}
797 
798 	if (slot >= 0) {
799 		atomic_inc(&rdev->nr_pending);
800 		if (test_bit(Faulty, &rdev->flags)) {
801 			/* Cannot risk returning a device that failed
802 			 * before we inc'ed nr_pending
803 			 */
804 			rdev_dec_pending(rdev, conf->mddev);
805 			goto retry;
806 		}
807 		r10_bio->read_slot = slot;
808 	} else
809 		rdev = NULL;
810 	rcu_read_unlock();
811 	*max_sectors = best_good_sectors;
812 
813 	return rdev;
814 }
815 
raid10_congested(void * data,int bits)816 static int raid10_congested(void *data, int bits)
817 {
818 	struct mddev *mddev = data;
819 	struct r10conf *conf = mddev->private;
820 	int i, ret = 0;
821 
822 	if ((bits & (1 << BDI_async_congested)) &&
823 	    conf->pending_count >= max_queued_requests)
824 		return 1;
825 
826 	if (mddev_congested(mddev, bits))
827 		return 1;
828 	rcu_read_lock();
829 	for (i = 0; i < conf->raid_disks && ret == 0; i++) {
830 		struct md_rdev *rdev = rcu_dereference(conf->mirrors[i].rdev);
831 		if (rdev && !test_bit(Faulty, &rdev->flags)) {
832 			struct request_queue *q = bdev_get_queue(rdev->bdev);
833 
834 			ret |= bdi_congested(&q->backing_dev_info, bits);
835 		}
836 	}
837 	rcu_read_unlock();
838 	return ret;
839 }
840 
flush_pending_writes(struct r10conf * conf)841 static void flush_pending_writes(struct r10conf *conf)
842 {
843 	/* Any writes that have been queued but are awaiting
844 	 * bitmap updates get flushed here.
845 	 */
846 	spin_lock_irq(&conf->device_lock);
847 
848 	if (conf->pending_bio_list.head) {
849 		struct bio *bio;
850 		bio = bio_list_get(&conf->pending_bio_list);
851 		conf->pending_count = 0;
852 		spin_unlock_irq(&conf->device_lock);
853 		/* flush any pending bitmap writes to disk
854 		 * before proceeding w/ I/O */
855 		bitmap_unplug(conf->mddev->bitmap);
856 		wake_up(&conf->wait_barrier);
857 
858 		while (bio) { /* submit pending writes */
859 			struct bio *next = bio->bi_next;
860 			bio->bi_next = NULL;
861 			generic_make_request(bio);
862 			bio = next;
863 		}
864 	} else
865 		spin_unlock_irq(&conf->device_lock);
866 }
867 
868 /* Barriers....
869  * Sometimes we need to suspend IO while we do something else,
870  * either some resync/recovery, or reconfigure the array.
871  * To do this we raise a 'barrier'.
872  * The 'barrier' is a counter that can be raised multiple times
873  * to count how many activities are happening which preclude
874  * normal IO.
875  * We can only raise the barrier if there is no pending IO.
876  * i.e. if nr_pending == 0.
877  * We choose only to raise the barrier if no-one is waiting for the
878  * barrier to go down.  This means that as soon as an IO request
879  * is ready, no other operations which require a barrier will start
880  * until the IO request has had a chance.
881  *
882  * So: regular IO calls 'wait_barrier'.  When that returns there
883  *    is no backgroup IO happening,  It must arrange to call
884  *    allow_barrier when it has finished its IO.
885  * backgroup IO calls must call raise_barrier.  Once that returns
886  *    there is no normal IO happeing.  It must arrange to call
887  *    lower_barrier when the particular background IO completes.
888  */
889 
raise_barrier(struct r10conf * conf,int force)890 static void raise_barrier(struct r10conf *conf, int force)
891 {
892 	BUG_ON(force && !conf->barrier);
893 	spin_lock_irq(&conf->resync_lock);
894 
895 	/* Wait until no block IO is waiting (unless 'force') */
896 	wait_event_lock_irq(conf->wait_barrier, force || !conf->nr_waiting,
897 			    conf->resync_lock, );
898 
899 	/* block any new IO from starting */
900 	conf->barrier++;
901 
902 	/* Now wait for all pending IO to complete */
903 	wait_event_lock_irq(conf->wait_barrier,
904 			    !conf->nr_pending && conf->barrier < RESYNC_DEPTH,
905 			    conf->resync_lock, );
906 
907 	spin_unlock_irq(&conf->resync_lock);
908 }
909 
lower_barrier(struct r10conf * conf)910 static void lower_barrier(struct r10conf *conf)
911 {
912 	unsigned long flags;
913 	spin_lock_irqsave(&conf->resync_lock, flags);
914 	conf->barrier--;
915 	spin_unlock_irqrestore(&conf->resync_lock, flags);
916 	wake_up(&conf->wait_barrier);
917 }
918 
wait_barrier(struct r10conf * conf)919 static void wait_barrier(struct r10conf *conf)
920 {
921 	spin_lock_irq(&conf->resync_lock);
922 	if (conf->barrier) {
923 		conf->nr_waiting++;
924 		/* Wait for the barrier to drop.
925 		 * However if there are already pending
926 		 * requests (preventing the barrier from
927 		 * rising completely), and the
928 		 * pre-process bio queue isn't empty,
929 		 * then don't wait, as we need to empty
930 		 * that queue to get the nr_pending
931 		 * count down.
932 		 */
933 		wait_event_lock_irq(conf->wait_barrier,
934 				    !conf->barrier ||
935 				    (conf->nr_pending &&
936 				     current->bio_list &&
937 				     !bio_list_empty(current->bio_list)),
938 				    conf->resync_lock,
939 			);
940 		conf->nr_waiting--;
941 	}
942 	conf->nr_pending++;
943 	spin_unlock_irq(&conf->resync_lock);
944 }
945 
allow_barrier(struct r10conf * conf)946 static void allow_barrier(struct r10conf *conf)
947 {
948 	unsigned long flags;
949 	spin_lock_irqsave(&conf->resync_lock, flags);
950 	conf->nr_pending--;
951 	spin_unlock_irqrestore(&conf->resync_lock, flags);
952 	wake_up(&conf->wait_barrier);
953 }
954 
freeze_array(struct r10conf * conf,int extra)955 static void freeze_array(struct r10conf *conf, int extra)
956 {
957 	/* stop syncio and normal IO and wait for everything to
958 	 * go quiet.
959 	 * We increment barrier and nr_waiting, and then
960 	 * wait until nr_pending match nr_queued+extra
961 	 * This is called in the context of one normal IO request
962 	 * that has failed. Thus any sync request that might be pending
963 	 * will be blocked by nr_pending, and we need to wait for
964 	 * pending IO requests to complete or be queued for re-try.
965 	 * Thus the number queued (nr_queued) plus this request (extra)
966 	 * must match the number of pending IOs (nr_pending) before
967 	 * we continue.
968 	 */
969 	spin_lock_irq(&conf->resync_lock);
970 	conf->barrier++;
971 	conf->nr_waiting++;
972 	wait_event_lock_irq(conf->wait_barrier,
973 			    conf->nr_pending == conf->nr_queued+extra,
974 			    conf->resync_lock,
975 			    flush_pending_writes(conf));
976 
977 	spin_unlock_irq(&conf->resync_lock);
978 }
979 
unfreeze_array(struct r10conf * conf)980 static void unfreeze_array(struct r10conf *conf)
981 {
982 	/* reverse the effect of the freeze */
983 	spin_lock_irq(&conf->resync_lock);
984 	conf->barrier--;
985 	conf->nr_waiting--;
986 	wake_up(&conf->wait_barrier);
987 	spin_unlock_irq(&conf->resync_lock);
988 }
989 
make_request(struct mddev * mddev,struct bio * bio)990 static void make_request(struct mddev *mddev, struct bio * bio)
991 {
992 	struct r10conf *conf = mddev->private;
993 	struct r10bio *r10_bio;
994 	struct bio *read_bio;
995 	int i;
996 	int chunk_sects = conf->chunk_mask + 1;
997 	const int rw = bio_data_dir(bio);
998 	const unsigned long do_sync = (bio->bi_rw & REQ_SYNC);
999 	const unsigned long do_fua = (bio->bi_rw & REQ_FUA);
1000 	unsigned long flags;
1001 	struct md_rdev *blocked_rdev;
1002 	int plugged;
1003 	int sectors_handled;
1004 	int max_sectors;
1005 
1006 	if (unlikely(bio->bi_rw & REQ_FLUSH)) {
1007 		md_flush_request(mddev, bio);
1008 		return;
1009 	}
1010 
1011 	/* If this request crosses a chunk boundary, we need to
1012 	 * split it.  This will only happen for 1 PAGE (or less) requests.
1013 	 */
1014 	if (unlikely( (bio->bi_sector & conf->chunk_mask) + (bio->bi_size >> 9)
1015 		      > chunk_sects &&
1016 		    conf->near_copies < conf->raid_disks)) {
1017 		struct bio_pair *bp;
1018 		/* Sanity check -- queue functions should prevent this happening */
1019 		if (bio->bi_vcnt != 1 ||
1020 		    bio->bi_idx != 0)
1021 			goto bad_map;
1022 		/* This is a one page bio that upper layers
1023 		 * refuse to split for us, so we need to split it.
1024 		 */
1025 		bp = bio_split(bio,
1026 			       chunk_sects - (bio->bi_sector & (chunk_sects - 1)) );
1027 
1028 		/* Each of these 'make_request' calls will call 'wait_barrier'.
1029 		 * If the first succeeds but the second blocks due to the resync
1030 		 * thread raising the barrier, we will deadlock because the
1031 		 * IO to the underlying device will be queued in generic_make_request
1032 		 * and will never complete, so will never reduce nr_pending.
1033 		 * So increment nr_waiting here so no new raise_barriers will
1034 		 * succeed, and so the second wait_barrier cannot block.
1035 		 */
1036 		spin_lock_irq(&conf->resync_lock);
1037 		conf->nr_waiting++;
1038 		spin_unlock_irq(&conf->resync_lock);
1039 
1040 		make_request(mddev, &bp->bio1);
1041 		make_request(mddev, &bp->bio2);
1042 
1043 		spin_lock_irq(&conf->resync_lock);
1044 		conf->nr_waiting--;
1045 		wake_up(&conf->wait_barrier);
1046 		spin_unlock_irq(&conf->resync_lock);
1047 
1048 		bio_pair_release(bp);
1049 		return;
1050 	bad_map:
1051 		printk("md/raid10:%s: make_request bug: can't convert block across chunks"
1052 		       " or bigger than %dk %llu %d\n", mdname(mddev), chunk_sects/2,
1053 		       (unsigned long long)bio->bi_sector, bio->bi_size >> 10);
1054 
1055 		bio_io_error(bio);
1056 		return;
1057 	}
1058 
1059 	md_write_start(mddev, bio);
1060 
1061 	/*
1062 	 * Register the new request and wait if the reconstruction
1063 	 * thread has put up a bar for new requests.
1064 	 * Continue immediately if no resync is active currently.
1065 	 */
1066 	wait_barrier(conf);
1067 
1068 	r10_bio = mempool_alloc(conf->r10bio_pool, GFP_NOIO);
1069 
1070 	r10_bio->master_bio = bio;
1071 	r10_bio->sectors = bio->bi_size >> 9;
1072 
1073 	r10_bio->mddev = mddev;
1074 	r10_bio->sector = bio->bi_sector;
1075 	r10_bio->state = 0;
1076 
1077 	/* We might need to issue multiple reads to different
1078 	 * devices if there are bad blocks around, so we keep
1079 	 * track of the number of reads in bio->bi_phys_segments.
1080 	 * If this is 0, there is only one r10_bio and no locking
1081 	 * will be needed when the request completes.  If it is
1082 	 * non-zero, then it is the number of not-completed requests.
1083 	 */
1084 	bio->bi_phys_segments = 0;
1085 	clear_bit(BIO_SEG_VALID, &bio->bi_flags);
1086 
1087 	if (rw == READ) {
1088 		/*
1089 		 * read balancing logic:
1090 		 */
1091 		struct md_rdev *rdev;
1092 		int slot;
1093 
1094 read_again:
1095 		rdev = read_balance(conf, r10_bio, &max_sectors);
1096 		if (!rdev) {
1097 			raid_end_bio_io(r10_bio);
1098 			return;
1099 		}
1100 		slot = r10_bio->read_slot;
1101 
1102 		read_bio = bio_clone_mddev(bio, GFP_NOIO, mddev);
1103 		md_trim_bio(read_bio, r10_bio->sector - bio->bi_sector,
1104 			    max_sectors);
1105 
1106 		r10_bio->devs[slot].bio = read_bio;
1107 		r10_bio->devs[slot].rdev = rdev;
1108 
1109 		read_bio->bi_sector = r10_bio->devs[slot].addr +
1110 			rdev->data_offset;
1111 		read_bio->bi_bdev = rdev->bdev;
1112 		read_bio->bi_end_io = raid10_end_read_request;
1113 		read_bio->bi_rw = READ | do_sync;
1114 		read_bio->bi_private = r10_bio;
1115 
1116 		if (max_sectors < r10_bio->sectors) {
1117 			/* Could not read all from this device, so we will
1118 			 * need another r10_bio.
1119 			 */
1120 			sectors_handled = (r10_bio->sector + max_sectors
1121 					   - bio->bi_sector);
1122 			r10_bio->sectors = max_sectors;
1123 			spin_lock_irq(&conf->device_lock);
1124 			if (bio->bi_phys_segments == 0)
1125 				bio->bi_phys_segments = 2;
1126 			else
1127 				bio->bi_phys_segments++;
1128 			spin_unlock_irq(&conf->device_lock);
1129 			/* Cannot call generic_make_request directly
1130 			 * as that will be queued in __generic_make_request
1131 			 * and subsequent mempool_alloc might block
1132 			 * waiting for it.  so hand bio over to raid10d.
1133 			 */
1134 			reschedule_retry(r10_bio);
1135 
1136 			r10_bio = mempool_alloc(conf->r10bio_pool, GFP_NOIO);
1137 
1138 			r10_bio->master_bio = bio;
1139 			r10_bio->sectors = ((bio->bi_size >> 9)
1140 					    - sectors_handled);
1141 			r10_bio->state = 0;
1142 			r10_bio->mddev = mddev;
1143 			r10_bio->sector = bio->bi_sector + sectors_handled;
1144 			goto read_again;
1145 		} else
1146 			generic_make_request(read_bio);
1147 		return;
1148 	}
1149 
1150 	/*
1151 	 * WRITE:
1152 	 */
1153 	if (conf->pending_count >= max_queued_requests) {
1154 		md_wakeup_thread(mddev->thread);
1155 		wait_event(conf->wait_barrier,
1156 			   conf->pending_count < max_queued_requests);
1157 	}
1158 	/* first select target devices under rcu_lock and
1159 	 * inc refcount on their rdev.  Record them by setting
1160 	 * bios[x] to bio
1161 	 * If there are known/acknowledged bad blocks on any device
1162 	 * on which we have seen a write error, we want to avoid
1163 	 * writing to those blocks.  This potentially requires several
1164 	 * writes to write around the bad blocks.  Each set of writes
1165 	 * gets its own r10_bio with a set of bios attached.  The number
1166 	 * of r10_bios is recored in bio->bi_phys_segments just as with
1167 	 * the read case.
1168 	 */
1169 	plugged = mddev_check_plugged(mddev);
1170 
1171 	r10_bio->read_slot = -1; /* make sure repl_bio gets freed */
1172 	raid10_find_phys(conf, r10_bio);
1173 retry_write:
1174 	blocked_rdev = NULL;
1175 	rcu_read_lock();
1176 	max_sectors = r10_bio->sectors;
1177 
1178 	for (i = 0;  i < conf->copies; i++) {
1179 		int d = r10_bio->devs[i].devnum;
1180 		struct md_rdev *rdev = rcu_dereference(conf->mirrors[d].rdev);
1181 		struct md_rdev *rrdev = rcu_dereference(
1182 			conf->mirrors[d].replacement);
1183 		if (rdev == rrdev)
1184 			rrdev = NULL;
1185 		if (rdev && unlikely(test_bit(Blocked, &rdev->flags))) {
1186 			atomic_inc(&rdev->nr_pending);
1187 			blocked_rdev = rdev;
1188 			break;
1189 		}
1190 		if (rrdev && unlikely(test_bit(Blocked, &rrdev->flags))) {
1191 			atomic_inc(&rrdev->nr_pending);
1192 			blocked_rdev = rrdev;
1193 			break;
1194 		}
1195 		if (rdev && (test_bit(Faulty, &rdev->flags)
1196 			     || test_bit(Unmerged, &rdev->flags)))
1197 			rdev = NULL;
1198 		if (rrdev && (test_bit(Faulty, &rrdev->flags)
1199 			      || test_bit(Unmerged, &rrdev->flags)))
1200 			rrdev = NULL;
1201 
1202 		r10_bio->devs[i].bio = NULL;
1203 		r10_bio->devs[i].repl_bio = NULL;
1204 
1205 		if (!rdev && !rrdev) {
1206 			set_bit(R10BIO_Degraded, &r10_bio->state);
1207 			continue;
1208 		}
1209 		if (rdev && test_bit(WriteErrorSeen, &rdev->flags)) {
1210 			sector_t first_bad;
1211 			sector_t dev_sector = r10_bio->devs[i].addr;
1212 			int bad_sectors;
1213 			int is_bad;
1214 
1215 			is_bad = is_badblock(rdev, dev_sector,
1216 					     max_sectors,
1217 					     &first_bad, &bad_sectors);
1218 			if (is_bad < 0) {
1219 				/* Mustn't write here until the bad block
1220 				 * is acknowledged
1221 				 */
1222 				atomic_inc(&rdev->nr_pending);
1223 				set_bit(BlockedBadBlocks, &rdev->flags);
1224 				blocked_rdev = rdev;
1225 				break;
1226 			}
1227 			if (is_bad && first_bad <= dev_sector) {
1228 				/* Cannot write here at all */
1229 				bad_sectors -= (dev_sector - first_bad);
1230 				if (bad_sectors < max_sectors)
1231 					/* Mustn't write more than bad_sectors
1232 					 * to other devices yet
1233 					 */
1234 					max_sectors = bad_sectors;
1235 				/* We don't set R10BIO_Degraded as that
1236 				 * only applies if the disk is missing,
1237 				 * so it might be re-added, and we want to
1238 				 * know to recover this chunk.
1239 				 * In this case the device is here, and the
1240 				 * fact that this chunk is not in-sync is
1241 				 * recorded in the bad block log.
1242 				 */
1243 				continue;
1244 			}
1245 			if (is_bad) {
1246 				int good_sectors = first_bad - dev_sector;
1247 				if (good_sectors < max_sectors)
1248 					max_sectors = good_sectors;
1249 			}
1250 		}
1251 		if (rdev) {
1252 			r10_bio->devs[i].bio = bio;
1253 			atomic_inc(&rdev->nr_pending);
1254 		}
1255 		if (rrdev) {
1256 			r10_bio->devs[i].repl_bio = bio;
1257 			atomic_inc(&rrdev->nr_pending);
1258 		}
1259 	}
1260 	rcu_read_unlock();
1261 
1262 	if (unlikely(blocked_rdev)) {
1263 		/* Have to wait for this device to get unblocked, then retry */
1264 		int j;
1265 		int d;
1266 
1267 		for (j = 0; j < i; j++) {
1268 			if (r10_bio->devs[j].bio) {
1269 				d = r10_bio->devs[j].devnum;
1270 				rdev_dec_pending(conf->mirrors[d].rdev, mddev);
1271 			}
1272 			if (r10_bio->devs[j].repl_bio) {
1273 				struct md_rdev *rdev;
1274 				d = r10_bio->devs[j].devnum;
1275 				rdev = conf->mirrors[d].replacement;
1276 				if (!rdev) {
1277 					/* Race with remove_disk */
1278 					smp_mb();
1279 					rdev = conf->mirrors[d].rdev;
1280 				}
1281 				rdev_dec_pending(rdev, mddev);
1282 			}
1283 		}
1284 		allow_barrier(conf);
1285 		md_wait_for_blocked_rdev(blocked_rdev, mddev);
1286 		wait_barrier(conf);
1287 		goto retry_write;
1288 	}
1289 
1290 	if (max_sectors < r10_bio->sectors) {
1291 		/* We are splitting this into multiple parts, so
1292 		 * we need to prepare for allocating another r10_bio.
1293 		 */
1294 		r10_bio->sectors = max_sectors;
1295 		spin_lock_irq(&conf->device_lock);
1296 		if (bio->bi_phys_segments == 0)
1297 			bio->bi_phys_segments = 2;
1298 		else
1299 			bio->bi_phys_segments++;
1300 		spin_unlock_irq(&conf->device_lock);
1301 	}
1302 	sectors_handled = r10_bio->sector + max_sectors - bio->bi_sector;
1303 
1304 	atomic_set(&r10_bio->remaining, 1);
1305 	bitmap_startwrite(mddev->bitmap, r10_bio->sector, r10_bio->sectors, 0);
1306 
1307 	for (i = 0; i < conf->copies; i++) {
1308 		struct bio *mbio;
1309 		int d = r10_bio->devs[i].devnum;
1310 		if (r10_bio->devs[i].bio) {
1311 			struct md_rdev *rdev = conf->mirrors[d].rdev;
1312 			mbio = bio_clone_mddev(bio, GFP_NOIO, mddev);
1313 			md_trim_bio(mbio, r10_bio->sector - bio->bi_sector,
1314 				    max_sectors);
1315 			r10_bio->devs[i].bio = mbio;
1316 
1317 			mbio->bi_sector	= (r10_bio->devs[i].addr+
1318 					   rdev->data_offset);
1319 			mbio->bi_bdev = rdev->bdev;
1320 			mbio->bi_end_io	= raid10_end_write_request;
1321 			mbio->bi_rw = WRITE | do_sync | do_fua;
1322 			mbio->bi_private = r10_bio;
1323 
1324 			atomic_inc(&r10_bio->remaining);
1325 			spin_lock_irqsave(&conf->device_lock, flags);
1326 			bio_list_add(&conf->pending_bio_list, mbio);
1327 			conf->pending_count++;
1328 			spin_unlock_irqrestore(&conf->device_lock, flags);
1329 		}
1330 
1331 		if (r10_bio->devs[i].repl_bio) {
1332 			struct md_rdev *rdev = conf->mirrors[d].replacement;
1333 			if (rdev == NULL) {
1334 				/* Replacement just got moved to main 'rdev' */
1335 				smp_mb();
1336 				rdev = conf->mirrors[d].rdev;
1337 			}
1338 			mbio = bio_clone_mddev(bio, GFP_NOIO, mddev);
1339 			md_trim_bio(mbio, r10_bio->sector - bio->bi_sector,
1340 				    max_sectors);
1341 			r10_bio->devs[i].repl_bio = mbio;
1342 
1343 			mbio->bi_sector	= (r10_bio->devs[i].addr+
1344 					   rdev->data_offset);
1345 			mbio->bi_bdev = rdev->bdev;
1346 			mbio->bi_end_io	= raid10_end_write_request;
1347 			mbio->bi_rw = WRITE | do_sync | do_fua;
1348 			mbio->bi_private = r10_bio;
1349 
1350 			atomic_inc(&r10_bio->remaining);
1351 			spin_lock_irqsave(&conf->device_lock, flags);
1352 			bio_list_add(&conf->pending_bio_list, mbio);
1353 			conf->pending_count++;
1354 			spin_unlock_irqrestore(&conf->device_lock, flags);
1355 		}
1356 	}
1357 
1358 	/* Don't remove the bias on 'remaining' (one_write_done) until
1359 	 * after checking if we need to go around again.
1360 	 */
1361 
1362 	if (sectors_handled < (bio->bi_size >> 9)) {
1363 		one_write_done(r10_bio);
1364 		/* We need another r10_bio.  It has already been counted
1365 		 * in bio->bi_phys_segments.
1366 		 */
1367 		r10_bio = mempool_alloc(conf->r10bio_pool, GFP_NOIO);
1368 
1369 		r10_bio->master_bio = bio;
1370 		r10_bio->sectors = (bio->bi_size >> 9) - sectors_handled;
1371 
1372 		r10_bio->mddev = mddev;
1373 		r10_bio->sector = bio->bi_sector + sectors_handled;
1374 		r10_bio->state = 0;
1375 		goto retry_write;
1376 	}
1377 	one_write_done(r10_bio);
1378 
1379 	/* In case raid10d snuck in to freeze_array */
1380 	wake_up(&conf->wait_barrier);
1381 
1382 	if (do_sync || !mddev->bitmap || !plugged)
1383 		md_wakeup_thread(mddev->thread);
1384 }
1385 
status(struct seq_file * seq,struct mddev * mddev)1386 static void status(struct seq_file *seq, struct mddev *mddev)
1387 {
1388 	struct r10conf *conf = mddev->private;
1389 	int i;
1390 
1391 	if (conf->near_copies < conf->raid_disks)
1392 		seq_printf(seq, " %dK chunks", mddev->chunk_sectors / 2);
1393 	if (conf->near_copies > 1)
1394 		seq_printf(seq, " %d near-copies", conf->near_copies);
1395 	if (conf->far_copies > 1) {
1396 		if (conf->far_offset)
1397 			seq_printf(seq, " %d offset-copies", conf->far_copies);
1398 		else
1399 			seq_printf(seq, " %d far-copies", conf->far_copies);
1400 	}
1401 	seq_printf(seq, " [%d/%d] [", conf->raid_disks,
1402 					conf->raid_disks - mddev->degraded);
1403 	for (i = 0; i < conf->raid_disks; i++)
1404 		seq_printf(seq, "%s",
1405 			      conf->mirrors[i].rdev &&
1406 			      test_bit(In_sync, &conf->mirrors[i].rdev->flags) ? "U" : "_");
1407 	seq_printf(seq, "]");
1408 }
1409 
1410 /* check if there are enough drives for
1411  * every block to appear on atleast one.
1412  * Don't consider the device numbered 'ignore'
1413  * as we might be about to remove it.
1414  */
enough(struct r10conf * conf,int ignore)1415 static int enough(struct r10conf *conf, int ignore)
1416 {
1417 	int first = 0;
1418 
1419 	do {
1420 		int n = conf->copies;
1421 		int cnt = 0;
1422 		int this = first;
1423 		while (n--) {
1424 			if (conf->mirrors[this].rdev &&
1425 			    this != ignore)
1426 				cnt++;
1427 			this = (this+1) % conf->raid_disks;
1428 		}
1429 		if (cnt == 0)
1430 			return 0;
1431 		first = (first + conf->near_copies) % conf->raid_disks;
1432 	} while (first != 0);
1433 	return 1;
1434 }
1435 
error(struct mddev * mddev,struct md_rdev * rdev)1436 static void error(struct mddev *mddev, struct md_rdev *rdev)
1437 {
1438 	char b[BDEVNAME_SIZE];
1439 	struct r10conf *conf = mddev->private;
1440 
1441 	/*
1442 	 * If it is not operational, then we have already marked it as dead
1443 	 * else if it is the last working disks, ignore the error, let the
1444 	 * next level up know.
1445 	 * else mark the drive as failed
1446 	 */
1447 	if (test_bit(In_sync, &rdev->flags)
1448 	    && !enough(conf, rdev->raid_disk))
1449 		/*
1450 		 * Don't fail the drive, just return an IO error.
1451 		 */
1452 		return;
1453 	if (test_and_clear_bit(In_sync, &rdev->flags)) {
1454 		unsigned long flags;
1455 		spin_lock_irqsave(&conf->device_lock, flags);
1456 		mddev->degraded++;
1457 		spin_unlock_irqrestore(&conf->device_lock, flags);
1458 		/*
1459 		 * if recovery is running, make sure it aborts.
1460 		 */
1461 		set_bit(MD_RECOVERY_INTR, &mddev->recovery);
1462 	}
1463 	set_bit(Blocked, &rdev->flags);
1464 	set_bit(Faulty, &rdev->flags);
1465 	set_bit(MD_CHANGE_DEVS, &mddev->flags);
1466 	printk(KERN_ALERT
1467 	       "md/raid10:%s: Disk failure on %s, disabling device.\n"
1468 	       "md/raid10:%s: Operation continuing on %d devices.\n",
1469 	       mdname(mddev), bdevname(rdev->bdev, b),
1470 	       mdname(mddev), conf->raid_disks - mddev->degraded);
1471 }
1472 
print_conf(struct r10conf * conf)1473 static void print_conf(struct r10conf *conf)
1474 {
1475 	int i;
1476 	struct mirror_info *tmp;
1477 
1478 	printk(KERN_DEBUG "RAID10 conf printout:\n");
1479 	if (!conf) {
1480 		printk(KERN_DEBUG "(!conf)\n");
1481 		return;
1482 	}
1483 	printk(KERN_DEBUG " --- wd:%d rd:%d\n", conf->raid_disks - conf->mddev->degraded,
1484 		conf->raid_disks);
1485 
1486 	for (i = 0; i < conf->raid_disks; i++) {
1487 		char b[BDEVNAME_SIZE];
1488 		tmp = conf->mirrors + i;
1489 		if (tmp->rdev)
1490 			printk(KERN_DEBUG " disk %d, wo:%d, o:%d, dev:%s\n",
1491 				i, !test_bit(In_sync, &tmp->rdev->flags),
1492 			        !test_bit(Faulty, &tmp->rdev->flags),
1493 				bdevname(tmp->rdev->bdev,b));
1494 	}
1495 }
1496 
close_sync(struct r10conf * conf)1497 static void close_sync(struct r10conf *conf)
1498 {
1499 	wait_barrier(conf);
1500 	allow_barrier(conf);
1501 
1502 	mempool_destroy(conf->r10buf_pool);
1503 	conf->r10buf_pool = NULL;
1504 }
1505 
raid10_spare_active(struct mddev * mddev)1506 static int raid10_spare_active(struct mddev *mddev)
1507 {
1508 	int i;
1509 	struct r10conf *conf = mddev->private;
1510 	struct mirror_info *tmp;
1511 	int count = 0;
1512 	unsigned long flags;
1513 
1514 	/*
1515 	 * Find all non-in_sync disks within the RAID10 configuration
1516 	 * and mark them in_sync
1517 	 */
1518 	for (i = 0; i < conf->raid_disks; i++) {
1519 		tmp = conf->mirrors + i;
1520 		if (tmp->replacement
1521 		    && tmp->replacement->recovery_offset == MaxSector
1522 		    && !test_bit(Faulty, &tmp->replacement->flags)
1523 		    && !test_and_set_bit(In_sync, &tmp->replacement->flags)) {
1524 			/* Replacement has just become active */
1525 			if (!tmp->rdev
1526 			    || !test_and_clear_bit(In_sync, &tmp->rdev->flags))
1527 				count++;
1528 			if (tmp->rdev) {
1529 				/* Replaced device not technically faulty,
1530 				 * but we need to be sure it gets removed
1531 				 * and never re-added.
1532 				 */
1533 				set_bit(Faulty, &tmp->rdev->flags);
1534 				sysfs_notify_dirent_safe(
1535 					tmp->rdev->sysfs_state);
1536 			}
1537 			sysfs_notify_dirent_safe(tmp->replacement->sysfs_state);
1538 		} else if (tmp->rdev
1539 			   && tmp->rdev->recovery_offset == MaxSector
1540 			   && !test_bit(Faulty, &tmp->rdev->flags)
1541 			   && !test_and_set_bit(In_sync, &tmp->rdev->flags)) {
1542 			count++;
1543 			sysfs_notify_dirent(tmp->rdev->sysfs_state);
1544 		}
1545 	}
1546 	spin_lock_irqsave(&conf->device_lock, flags);
1547 	mddev->degraded -= count;
1548 	spin_unlock_irqrestore(&conf->device_lock, flags);
1549 
1550 	print_conf(conf);
1551 	return count;
1552 }
1553 
1554 
raid10_add_disk(struct mddev * mddev,struct md_rdev * rdev)1555 static int raid10_add_disk(struct mddev *mddev, struct md_rdev *rdev)
1556 {
1557 	struct r10conf *conf = mddev->private;
1558 	int err = -EEXIST;
1559 	int mirror;
1560 	int first = 0;
1561 	int last = conf->raid_disks - 1;
1562 	struct request_queue *q = bdev_get_queue(rdev->bdev);
1563 
1564 	if (mddev->recovery_cp < MaxSector)
1565 		/* only hot-add to in-sync arrays, as recovery is
1566 		 * very different from resync
1567 		 */
1568 		return -EBUSY;
1569 	if (rdev->saved_raid_disk < 0 && !enough(conf, -1))
1570 		return -EINVAL;
1571 
1572 	if (rdev->raid_disk >= 0)
1573 		first = last = rdev->raid_disk;
1574 
1575 	if (q->merge_bvec_fn) {
1576 		set_bit(Unmerged, &rdev->flags);
1577 		mddev->merge_check_needed = 1;
1578 	}
1579 
1580 	if (rdev->saved_raid_disk >= first &&
1581 	    conf->mirrors[rdev->saved_raid_disk].rdev == NULL)
1582 		mirror = rdev->saved_raid_disk;
1583 	else
1584 		mirror = first;
1585 	for ( ; mirror <= last ; mirror++) {
1586 		struct mirror_info *p = &conf->mirrors[mirror];
1587 		if (p->recovery_disabled == mddev->recovery_disabled)
1588 			continue;
1589 		if (p->rdev) {
1590 			if (!test_bit(WantReplacement, &p->rdev->flags) ||
1591 			    p->replacement != NULL)
1592 				continue;
1593 			clear_bit(In_sync, &rdev->flags);
1594 			set_bit(Replacement, &rdev->flags);
1595 			rdev->raid_disk = mirror;
1596 			err = 0;
1597 			disk_stack_limits(mddev->gendisk, rdev->bdev,
1598 					  rdev->data_offset << 9);
1599 			conf->fullsync = 1;
1600 			rcu_assign_pointer(p->replacement, rdev);
1601 			break;
1602 		}
1603 
1604 		disk_stack_limits(mddev->gendisk, rdev->bdev,
1605 				  rdev->data_offset << 9);
1606 
1607 		p->head_position = 0;
1608 		p->recovery_disabled = mddev->recovery_disabled - 1;
1609 		rdev->raid_disk = mirror;
1610 		err = 0;
1611 		if (rdev->saved_raid_disk != mirror)
1612 			conf->fullsync = 1;
1613 		rcu_assign_pointer(p->rdev, rdev);
1614 		break;
1615 	}
1616 	if (err == 0 && test_bit(Unmerged, &rdev->flags)) {
1617 		/* Some requests might not have seen this new
1618 		 * merge_bvec_fn.  We must wait for them to complete
1619 		 * before merging the device fully.
1620 		 * First we make sure any code which has tested
1621 		 * our function has submitted the request, then
1622 		 * we wait for all outstanding requests to complete.
1623 		 */
1624 		synchronize_sched();
1625 		freeze_array(conf, 0);
1626 		unfreeze_array(conf);
1627 		clear_bit(Unmerged, &rdev->flags);
1628 	}
1629 	md_integrity_add_rdev(rdev, mddev);
1630 	print_conf(conf);
1631 	return err;
1632 }
1633 
raid10_remove_disk(struct mddev * mddev,struct md_rdev * rdev)1634 static int raid10_remove_disk(struct mddev *mddev, struct md_rdev *rdev)
1635 {
1636 	struct r10conf *conf = mddev->private;
1637 	int err = 0;
1638 	int number = rdev->raid_disk;
1639 	struct md_rdev **rdevp;
1640 	struct mirror_info *p = conf->mirrors + number;
1641 
1642 	print_conf(conf);
1643 	if (rdev == p->rdev)
1644 		rdevp = &p->rdev;
1645 	else if (rdev == p->replacement)
1646 		rdevp = &p->replacement;
1647 	else
1648 		return 0;
1649 
1650 	if (test_bit(In_sync, &rdev->flags) ||
1651 	    atomic_read(&rdev->nr_pending)) {
1652 		err = -EBUSY;
1653 		goto abort;
1654 	}
1655 	/* Only remove faulty devices if recovery
1656 	 * is not possible.
1657 	 */
1658 	if (!test_bit(Faulty, &rdev->flags) &&
1659 	    mddev->recovery_disabled != p->recovery_disabled &&
1660 	    (!p->replacement || p->replacement == rdev) &&
1661 	    enough(conf, -1)) {
1662 		err = -EBUSY;
1663 		goto abort;
1664 	}
1665 	*rdevp = NULL;
1666 	synchronize_rcu();
1667 	if (atomic_read(&rdev->nr_pending)) {
1668 		/* lost the race, try later */
1669 		err = -EBUSY;
1670 		*rdevp = rdev;
1671 		goto abort;
1672 	} else if (p->replacement) {
1673 		/* We must have just cleared 'rdev' */
1674 		p->rdev = p->replacement;
1675 		clear_bit(Replacement, &p->replacement->flags);
1676 		smp_mb(); /* Make sure other CPUs may see both as identical
1677 			   * but will never see neither -- if they are careful.
1678 			   */
1679 		p->replacement = NULL;
1680 		clear_bit(WantReplacement, &rdev->flags);
1681 	} else
1682 		/* We might have just remove the Replacement as faulty
1683 		 * Clear the flag just in case
1684 		 */
1685 		clear_bit(WantReplacement, &rdev->flags);
1686 
1687 	err = md_integrity_register(mddev);
1688 
1689 abort:
1690 
1691 	print_conf(conf);
1692 	return err;
1693 }
1694 
1695 
end_sync_read(struct bio * bio,int error)1696 static void end_sync_read(struct bio *bio, int error)
1697 {
1698 	struct r10bio *r10_bio = bio->bi_private;
1699 	struct r10conf *conf = r10_bio->mddev->private;
1700 	int d;
1701 
1702 	d = find_bio_disk(conf, r10_bio, bio, NULL, NULL);
1703 
1704 	if (test_bit(BIO_UPTODATE, &bio->bi_flags))
1705 		set_bit(R10BIO_Uptodate, &r10_bio->state);
1706 	else
1707 		/* The write handler will notice the lack of
1708 		 * R10BIO_Uptodate and record any errors etc
1709 		 */
1710 		atomic_add(r10_bio->sectors,
1711 			   &conf->mirrors[d].rdev->corrected_errors);
1712 
1713 	/* for reconstruct, we always reschedule after a read.
1714 	 * for resync, only after all reads
1715 	 */
1716 	rdev_dec_pending(conf->mirrors[d].rdev, conf->mddev);
1717 	if (test_bit(R10BIO_IsRecover, &r10_bio->state) ||
1718 	    atomic_dec_and_test(&r10_bio->remaining)) {
1719 		/* we have read all the blocks,
1720 		 * do the comparison in process context in raid10d
1721 		 */
1722 		reschedule_retry(r10_bio);
1723 	}
1724 }
1725 
end_sync_request(struct r10bio * r10_bio)1726 static void end_sync_request(struct r10bio *r10_bio)
1727 {
1728 	struct mddev *mddev = r10_bio->mddev;
1729 
1730 	while (atomic_dec_and_test(&r10_bio->remaining)) {
1731 		if (r10_bio->master_bio == NULL) {
1732 			/* the primary of several recovery bios */
1733 			sector_t s = r10_bio->sectors;
1734 			if (test_bit(R10BIO_MadeGood, &r10_bio->state) ||
1735 			    test_bit(R10BIO_WriteError, &r10_bio->state))
1736 				reschedule_retry(r10_bio);
1737 			else
1738 				put_buf(r10_bio);
1739 			md_done_sync(mddev, s, 1);
1740 			break;
1741 		} else {
1742 			struct r10bio *r10_bio2 = (struct r10bio *)r10_bio->master_bio;
1743 			if (test_bit(R10BIO_MadeGood, &r10_bio->state) ||
1744 			    test_bit(R10BIO_WriteError, &r10_bio->state))
1745 				reschedule_retry(r10_bio);
1746 			else
1747 				put_buf(r10_bio);
1748 			r10_bio = r10_bio2;
1749 		}
1750 	}
1751 }
1752 
end_sync_write(struct bio * bio,int error)1753 static void end_sync_write(struct bio *bio, int error)
1754 {
1755 	int uptodate = test_bit(BIO_UPTODATE, &bio->bi_flags);
1756 	struct r10bio *r10_bio = bio->bi_private;
1757 	struct mddev *mddev = r10_bio->mddev;
1758 	struct r10conf *conf = mddev->private;
1759 	int d;
1760 	sector_t first_bad;
1761 	int bad_sectors;
1762 	int slot;
1763 	int repl;
1764 	struct md_rdev *rdev = NULL;
1765 
1766 	d = find_bio_disk(conf, r10_bio, bio, &slot, &repl);
1767 	if (repl)
1768 		rdev = conf->mirrors[d].replacement;
1769 	else
1770 		rdev = conf->mirrors[d].rdev;
1771 
1772 	if (!uptodate) {
1773 		if (repl)
1774 			md_error(mddev, rdev);
1775 		else {
1776 			set_bit(WriteErrorSeen, &rdev->flags);
1777 			if (!test_and_set_bit(WantReplacement, &rdev->flags))
1778 				set_bit(MD_RECOVERY_NEEDED,
1779 					&rdev->mddev->recovery);
1780 			set_bit(R10BIO_WriteError, &r10_bio->state);
1781 		}
1782 	} else if (is_badblock(rdev,
1783 			     r10_bio->devs[slot].addr,
1784 			     r10_bio->sectors,
1785 			     &first_bad, &bad_sectors))
1786 		set_bit(R10BIO_MadeGood, &r10_bio->state);
1787 
1788 	rdev_dec_pending(rdev, mddev);
1789 
1790 	end_sync_request(r10_bio);
1791 }
1792 
1793 /*
1794  * Note: sync and recover and handled very differently for raid10
1795  * This code is for resync.
1796  * For resync, we read through virtual addresses and read all blocks.
1797  * If there is any error, we schedule a write.  The lowest numbered
1798  * drive is authoritative.
1799  * However requests come for physical address, so we need to map.
1800  * For every physical address there are raid_disks/copies virtual addresses,
1801  * which is always are least one, but is not necessarly an integer.
1802  * This means that a physical address can span multiple chunks, so we may
1803  * have to submit multiple io requests for a single sync request.
1804  */
1805 /*
1806  * We check if all blocks are in-sync and only write to blocks that
1807  * aren't in sync
1808  */
sync_request_write(struct mddev * mddev,struct r10bio * r10_bio)1809 static void sync_request_write(struct mddev *mddev, struct r10bio *r10_bio)
1810 {
1811 	struct r10conf *conf = mddev->private;
1812 	int i, first;
1813 	struct bio *tbio, *fbio;
1814 	int vcnt;
1815 
1816 	atomic_set(&r10_bio->remaining, 1);
1817 
1818 	/* find the first device with a block */
1819 	for (i=0; i<conf->copies; i++)
1820 		if (test_bit(BIO_UPTODATE, &r10_bio->devs[i].bio->bi_flags))
1821 			break;
1822 
1823 	if (i == conf->copies)
1824 		goto done;
1825 
1826 	first = i;
1827 	fbio = r10_bio->devs[i].bio;
1828 
1829 	vcnt = (r10_bio->sectors + (PAGE_SIZE >> 9) - 1) >> (PAGE_SHIFT - 9);
1830 	/* now find blocks with errors */
1831 	for (i=0 ; i < conf->copies ; i++) {
1832 		int  j, d;
1833 
1834 		tbio = r10_bio->devs[i].bio;
1835 
1836 		if (tbio->bi_end_io != end_sync_read)
1837 			continue;
1838 		if (i == first)
1839 			continue;
1840 		if (test_bit(BIO_UPTODATE, &r10_bio->devs[i].bio->bi_flags)) {
1841 			/* We know that the bi_io_vec layout is the same for
1842 			 * both 'first' and 'i', so we just compare them.
1843 			 * All vec entries are PAGE_SIZE;
1844 			 */
1845 			for (j = 0; j < vcnt; j++)
1846 				if (memcmp(page_address(fbio->bi_io_vec[j].bv_page),
1847 					   page_address(tbio->bi_io_vec[j].bv_page),
1848 					   fbio->bi_io_vec[j].bv_len))
1849 					break;
1850 			if (j == vcnt)
1851 				continue;
1852 			mddev->resync_mismatches += r10_bio->sectors;
1853 			if (test_bit(MD_RECOVERY_CHECK, &mddev->recovery))
1854 				/* Don't fix anything. */
1855 				continue;
1856 		}
1857 		/* Ok, we need to write this bio, either to correct an
1858 		 * inconsistency or to correct an unreadable block.
1859 		 * First we need to fixup bv_offset, bv_len and
1860 		 * bi_vecs, as the read request might have corrupted these
1861 		 */
1862 		tbio->bi_vcnt = vcnt;
1863 		tbio->bi_size = r10_bio->sectors << 9;
1864 		tbio->bi_idx = 0;
1865 		tbio->bi_phys_segments = 0;
1866 		tbio->bi_flags &= ~(BIO_POOL_MASK - 1);
1867 		tbio->bi_flags |= 1 << BIO_UPTODATE;
1868 		tbio->bi_next = NULL;
1869 		tbio->bi_rw = WRITE;
1870 		tbio->bi_private = r10_bio;
1871 		tbio->bi_sector = r10_bio->devs[i].addr;
1872 
1873 		for (j=0; j < vcnt ; j++) {
1874 			tbio->bi_io_vec[j].bv_offset = 0;
1875 			tbio->bi_io_vec[j].bv_len = PAGE_SIZE;
1876 
1877 			memcpy(page_address(tbio->bi_io_vec[j].bv_page),
1878 			       page_address(fbio->bi_io_vec[j].bv_page),
1879 			       PAGE_SIZE);
1880 		}
1881 		tbio->bi_end_io = end_sync_write;
1882 
1883 		d = r10_bio->devs[i].devnum;
1884 		atomic_inc(&conf->mirrors[d].rdev->nr_pending);
1885 		atomic_inc(&r10_bio->remaining);
1886 		md_sync_acct(conf->mirrors[d].rdev->bdev, tbio->bi_size >> 9);
1887 
1888 		tbio->bi_sector += conf->mirrors[d].rdev->data_offset;
1889 		tbio->bi_bdev = conf->mirrors[d].rdev->bdev;
1890 		generic_make_request(tbio);
1891 	}
1892 
1893 	/* Now write out to any replacement devices
1894 	 * that are active
1895 	 */
1896 	for (i = 0; i < conf->copies; i++) {
1897 		int j, d;
1898 
1899 		tbio = r10_bio->devs[i].repl_bio;
1900 		if (!tbio || !tbio->bi_end_io)
1901 			continue;
1902 		if (r10_bio->devs[i].bio->bi_end_io != end_sync_write
1903 		    && r10_bio->devs[i].bio != fbio)
1904 			for (j = 0; j < vcnt; j++)
1905 				memcpy(page_address(tbio->bi_io_vec[j].bv_page),
1906 				       page_address(fbio->bi_io_vec[j].bv_page),
1907 				       PAGE_SIZE);
1908 		d = r10_bio->devs[i].devnum;
1909 		atomic_inc(&r10_bio->remaining);
1910 		md_sync_acct(conf->mirrors[d].replacement->bdev,
1911 			     tbio->bi_size >> 9);
1912 		generic_make_request(tbio);
1913 	}
1914 
1915 done:
1916 	if (atomic_dec_and_test(&r10_bio->remaining)) {
1917 		md_done_sync(mddev, r10_bio->sectors, 1);
1918 		put_buf(r10_bio);
1919 	}
1920 }
1921 
1922 /*
1923  * Now for the recovery code.
1924  * Recovery happens across physical sectors.
1925  * We recover all non-is_sync drives by finding the virtual address of
1926  * each, and then choose a working drive that also has that virt address.
1927  * There is a separate r10_bio for each non-in_sync drive.
1928  * Only the first two slots are in use. The first for reading,
1929  * The second for writing.
1930  *
1931  */
fix_recovery_read_error(struct r10bio * r10_bio)1932 static void fix_recovery_read_error(struct r10bio *r10_bio)
1933 {
1934 	/* We got a read error during recovery.
1935 	 * We repeat the read in smaller page-sized sections.
1936 	 * If a read succeeds, write it to the new device or record
1937 	 * a bad block if we cannot.
1938 	 * If a read fails, record a bad block on both old and
1939 	 * new devices.
1940 	 */
1941 	struct mddev *mddev = r10_bio->mddev;
1942 	struct r10conf *conf = mddev->private;
1943 	struct bio *bio = r10_bio->devs[0].bio;
1944 	sector_t sect = 0;
1945 	int sectors = r10_bio->sectors;
1946 	int idx = 0;
1947 	int dr = r10_bio->devs[0].devnum;
1948 	int dw = r10_bio->devs[1].devnum;
1949 
1950 	while (sectors) {
1951 		int s = sectors;
1952 		struct md_rdev *rdev;
1953 		sector_t addr;
1954 		int ok;
1955 
1956 		if (s > (PAGE_SIZE>>9))
1957 			s = PAGE_SIZE >> 9;
1958 
1959 		rdev = conf->mirrors[dr].rdev;
1960 		addr = r10_bio->devs[0].addr + sect,
1961 		ok = sync_page_io(rdev,
1962 				  addr,
1963 				  s << 9,
1964 				  bio->bi_io_vec[idx].bv_page,
1965 				  READ, false);
1966 		if (ok) {
1967 			rdev = conf->mirrors[dw].rdev;
1968 			addr = r10_bio->devs[1].addr + sect;
1969 			ok = sync_page_io(rdev,
1970 					  addr,
1971 					  s << 9,
1972 					  bio->bi_io_vec[idx].bv_page,
1973 					  WRITE, false);
1974 			if (!ok) {
1975 				set_bit(WriteErrorSeen, &rdev->flags);
1976 				if (!test_and_set_bit(WantReplacement,
1977 						      &rdev->flags))
1978 					set_bit(MD_RECOVERY_NEEDED,
1979 						&rdev->mddev->recovery);
1980 			}
1981 		}
1982 		if (!ok) {
1983 			/* We don't worry if we cannot set a bad block -
1984 			 * it really is bad so there is no loss in not
1985 			 * recording it yet
1986 			 */
1987 			rdev_set_badblocks(rdev, addr, s, 0);
1988 
1989 			if (rdev != conf->mirrors[dw].rdev) {
1990 				/* need bad block on destination too */
1991 				struct md_rdev *rdev2 = conf->mirrors[dw].rdev;
1992 				addr = r10_bio->devs[1].addr + sect;
1993 				ok = rdev_set_badblocks(rdev2, addr, s, 0);
1994 				if (!ok) {
1995 					/* just abort the recovery */
1996 					printk(KERN_NOTICE
1997 					       "md/raid10:%s: recovery aborted"
1998 					       " due to read error\n",
1999 					       mdname(mddev));
2000 
2001 					conf->mirrors[dw].recovery_disabled
2002 						= mddev->recovery_disabled;
2003 					set_bit(MD_RECOVERY_INTR,
2004 						&mddev->recovery);
2005 					break;
2006 				}
2007 			}
2008 		}
2009 
2010 		sectors -= s;
2011 		sect += s;
2012 		idx++;
2013 	}
2014 }
2015 
recovery_request_write(struct mddev * mddev,struct r10bio * r10_bio)2016 static void recovery_request_write(struct mddev *mddev, struct r10bio *r10_bio)
2017 {
2018 	struct r10conf *conf = mddev->private;
2019 	int d;
2020 	struct bio *wbio, *wbio2;
2021 
2022 	if (!test_bit(R10BIO_Uptodate, &r10_bio->state)) {
2023 		fix_recovery_read_error(r10_bio);
2024 		end_sync_request(r10_bio);
2025 		return;
2026 	}
2027 
2028 	/*
2029 	 * share the pages with the first bio
2030 	 * and submit the write request
2031 	 */
2032 	d = r10_bio->devs[1].devnum;
2033 	wbio = r10_bio->devs[1].bio;
2034 	wbio2 = r10_bio->devs[1].repl_bio;
2035 	/* Need to test wbio2->bi_end_io before we call
2036 	 * generic_make_request as if the former is NULL,
2037 	 * the latter is free to free wbio2.
2038 	 */
2039 	if (wbio2 && !wbio2->bi_end_io)
2040 		wbio2 = NULL;
2041 	if (wbio->bi_end_io) {
2042 		atomic_inc(&conf->mirrors[d].rdev->nr_pending);
2043 		md_sync_acct(conf->mirrors[d].rdev->bdev, wbio->bi_size >> 9);
2044 		generic_make_request(wbio);
2045 	}
2046 	if (wbio2) {
2047 		atomic_inc(&conf->mirrors[d].replacement->nr_pending);
2048 		md_sync_acct(conf->mirrors[d].replacement->bdev,
2049 			     wbio2->bi_size >> 9);
2050 		generic_make_request(wbio2);
2051 	}
2052 }
2053 
2054 
2055 /*
2056  * Used by fix_read_error() to decay the per rdev read_errors.
2057  * We halve the read error count for every hour that has elapsed
2058  * since the last recorded read error.
2059  *
2060  */
check_decay_read_errors(struct mddev * mddev,struct md_rdev * rdev)2061 static void check_decay_read_errors(struct mddev *mddev, struct md_rdev *rdev)
2062 {
2063 	struct timespec cur_time_mon;
2064 	unsigned long hours_since_last;
2065 	unsigned int read_errors = atomic_read(&rdev->read_errors);
2066 
2067 	ktime_get_ts(&cur_time_mon);
2068 
2069 	if (rdev->last_read_error.tv_sec == 0 &&
2070 	    rdev->last_read_error.tv_nsec == 0) {
2071 		/* first time we've seen a read error */
2072 		rdev->last_read_error = cur_time_mon;
2073 		return;
2074 	}
2075 
2076 	hours_since_last = (cur_time_mon.tv_sec -
2077 			    rdev->last_read_error.tv_sec) / 3600;
2078 
2079 	rdev->last_read_error = cur_time_mon;
2080 
2081 	/*
2082 	 * if hours_since_last is > the number of bits in read_errors
2083 	 * just set read errors to 0. We do this to avoid
2084 	 * overflowing the shift of read_errors by hours_since_last.
2085 	 */
2086 	if (hours_since_last >= 8 * sizeof(read_errors))
2087 		atomic_set(&rdev->read_errors, 0);
2088 	else
2089 		atomic_set(&rdev->read_errors, read_errors >> hours_since_last);
2090 }
2091 
r10_sync_page_io(struct md_rdev * rdev,sector_t sector,int sectors,struct page * page,int rw)2092 static int r10_sync_page_io(struct md_rdev *rdev, sector_t sector,
2093 			    int sectors, struct page *page, int rw)
2094 {
2095 	sector_t first_bad;
2096 	int bad_sectors;
2097 
2098 	if (is_badblock(rdev, sector, sectors, &first_bad, &bad_sectors)
2099 	    && (rw == READ || test_bit(WriteErrorSeen, &rdev->flags)))
2100 		return -1;
2101 	if (sync_page_io(rdev, sector, sectors << 9, page, rw, false))
2102 		/* success */
2103 		return 1;
2104 	if (rw == WRITE) {
2105 		set_bit(WriteErrorSeen, &rdev->flags);
2106 		if (!test_and_set_bit(WantReplacement, &rdev->flags))
2107 			set_bit(MD_RECOVERY_NEEDED,
2108 				&rdev->mddev->recovery);
2109 	}
2110 	/* need to record an error - either for the block or the device */
2111 	if (!rdev_set_badblocks(rdev, sector, sectors, 0))
2112 		md_error(rdev->mddev, rdev);
2113 	return 0;
2114 }
2115 
2116 /*
2117  * This is a kernel thread which:
2118  *
2119  *	1.	Retries failed read operations on working mirrors.
2120  *	2.	Updates the raid superblock when problems encounter.
2121  *	3.	Performs writes following reads for array synchronising.
2122  */
2123 
fix_read_error(struct r10conf * conf,struct mddev * mddev,struct r10bio * r10_bio)2124 static void fix_read_error(struct r10conf *conf, struct mddev *mddev, struct r10bio *r10_bio)
2125 {
2126 	int sect = 0; /* Offset from r10_bio->sector */
2127 	int sectors = r10_bio->sectors;
2128 	struct md_rdev*rdev;
2129 	int max_read_errors = atomic_read(&mddev->max_corr_read_errors);
2130 	int d = r10_bio->devs[r10_bio->read_slot].devnum;
2131 
2132 	/* still own a reference to this rdev, so it cannot
2133 	 * have been cleared recently.
2134 	 */
2135 	rdev = conf->mirrors[d].rdev;
2136 
2137 	if (test_bit(Faulty, &rdev->flags))
2138 		/* drive has already been failed, just ignore any
2139 		   more fix_read_error() attempts */
2140 		return;
2141 
2142 	check_decay_read_errors(mddev, rdev);
2143 	atomic_inc(&rdev->read_errors);
2144 	if (atomic_read(&rdev->read_errors) > max_read_errors) {
2145 		char b[BDEVNAME_SIZE];
2146 		bdevname(rdev->bdev, b);
2147 
2148 		printk(KERN_NOTICE
2149 		       "md/raid10:%s: %s: Raid device exceeded "
2150 		       "read_error threshold [cur %d:max %d]\n",
2151 		       mdname(mddev), b,
2152 		       atomic_read(&rdev->read_errors), max_read_errors);
2153 		printk(KERN_NOTICE
2154 		       "md/raid10:%s: %s: Failing raid device\n",
2155 		       mdname(mddev), b);
2156 		md_error(mddev, conf->mirrors[d].rdev);
2157 		r10_bio->devs[r10_bio->read_slot].bio = IO_BLOCKED;
2158 		return;
2159 	}
2160 
2161 	while(sectors) {
2162 		int s = sectors;
2163 		int sl = r10_bio->read_slot;
2164 		int success = 0;
2165 		int start;
2166 
2167 		if (s > (PAGE_SIZE>>9))
2168 			s = PAGE_SIZE >> 9;
2169 
2170 		rcu_read_lock();
2171 		do {
2172 			sector_t first_bad;
2173 			int bad_sectors;
2174 
2175 			d = r10_bio->devs[sl].devnum;
2176 			rdev = rcu_dereference(conf->mirrors[d].rdev);
2177 			if (rdev &&
2178 			    !test_bit(Unmerged, &rdev->flags) &&
2179 			    test_bit(In_sync, &rdev->flags) &&
2180 			    is_badblock(rdev, r10_bio->devs[sl].addr + sect, s,
2181 					&first_bad, &bad_sectors) == 0) {
2182 				atomic_inc(&rdev->nr_pending);
2183 				rcu_read_unlock();
2184 				success = sync_page_io(rdev,
2185 						       r10_bio->devs[sl].addr +
2186 						       sect,
2187 						       s<<9,
2188 						       conf->tmppage, READ, false);
2189 				rdev_dec_pending(rdev, mddev);
2190 				rcu_read_lock();
2191 				if (success)
2192 					break;
2193 			}
2194 			sl++;
2195 			if (sl == conf->copies)
2196 				sl = 0;
2197 		} while (!success && sl != r10_bio->read_slot);
2198 		rcu_read_unlock();
2199 
2200 		if (!success) {
2201 			/* Cannot read from anywhere, just mark the block
2202 			 * as bad on the first device to discourage future
2203 			 * reads.
2204 			 */
2205 			int dn = r10_bio->devs[r10_bio->read_slot].devnum;
2206 			rdev = conf->mirrors[dn].rdev;
2207 
2208 			if (!rdev_set_badblocks(
2209 				    rdev,
2210 				    r10_bio->devs[r10_bio->read_slot].addr
2211 				    + sect,
2212 				    s, 0)) {
2213 				md_error(mddev, rdev);
2214 				r10_bio->devs[r10_bio->read_slot].bio
2215 					= IO_BLOCKED;
2216 			}
2217 			break;
2218 		}
2219 
2220 		start = sl;
2221 		/* write it back and re-read */
2222 		rcu_read_lock();
2223 		while (sl != r10_bio->read_slot) {
2224 			char b[BDEVNAME_SIZE];
2225 
2226 			if (sl==0)
2227 				sl = conf->copies;
2228 			sl--;
2229 			d = r10_bio->devs[sl].devnum;
2230 			rdev = rcu_dereference(conf->mirrors[d].rdev);
2231 			if (!rdev ||
2232 			    test_bit(Unmerged, &rdev->flags) ||
2233 			    !test_bit(In_sync, &rdev->flags))
2234 				continue;
2235 
2236 			atomic_inc(&rdev->nr_pending);
2237 			rcu_read_unlock();
2238 			if (r10_sync_page_io(rdev,
2239 					     r10_bio->devs[sl].addr +
2240 					     sect,
2241 					     s, conf->tmppage, WRITE)
2242 			    == 0) {
2243 				/* Well, this device is dead */
2244 				printk(KERN_NOTICE
2245 				       "md/raid10:%s: read correction "
2246 				       "write failed"
2247 				       " (%d sectors at %llu on %s)\n",
2248 				       mdname(mddev), s,
2249 				       (unsigned long long)(
2250 					       sect + rdev->data_offset),
2251 				       bdevname(rdev->bdev, b));
2252 				printk(KERN_NOTICE "md/raid10:%s: %s: failing "
2253 				       "drive\n",
2254 				       mdname(mddev),
2255 				       bdevname(rdev->bdev, b));
2256 			}
2257 			rdev_dec_pending(rdev, mddev);
2258 			rcu_read_lock();
2259 		}
2260 		sl = start;
2261 		while (sl != r10_bio->read_slot) {
2262 			char b[BDEVNAME_SIZE];
2263 
2264 			if (sl==0)
2265 				sl = conf->copies;
2266 			sl--;
2267 			d = r10_bio->devs[sl].devnum;
2268 			rdev = rcu_dereference(conf->mirrors[d].rdev);
2269 			if (!rdev ||
2270 			    !test_bit(In_sync, &rdev->flags))
2271 				continue;
2272 
2273 			atomic_inc(&rdev->nr_pending);
2274 			rcu_read_unlock();
2275 			switch (r10_sync_page_io(rdev,
2276 					     r10_bio->devs[sl].addr +
2277 					     sect,
2278 					     s, conf->tmppage,
2279 						 READ)) {
2280 			case 0:
2281 				/* Well, this device is dead */
2282 				printk(KERN_NOTICE
2283 				       "md/raid10:%s: unable to read back "
2284 				       "corrected sectors"
2285 				       " (%d sectors at %llu on %s)\n",
2286 				       mdname(mddev), s,
2287 				       (unsigned long long)(
2288 					       sect + rdev->data_offset),
2289 				       bdevname(rdev->bdev, b));
2290 				printk(KERN_NOTICE "md/raid10:%s: %s: failing "
2291 				       "drive\n",
2292 				       mdname(mddev),
2293 				       bdevname(rdev->bdev, b));
2294 				break;
2295 			case 1:
2296 				printk(KERN_INFO
2297 				       "md/raid10:%s: read error corrected"
2298 				       " (%d sectors at %llu on %s)\n",
2299 				       mdname(mddev), s,
2300 				       (unsigned long long)(
2301 					       sect + rdev->data_offset),
2302 				       bdevname(rdev->bdev, b));
2303 				atomic_add(s, &rdev->corrected_errors);
2304 			}
2305 
2306 			rdev_dec_pending(rdev, mddev);
2307 			rcu_read_lock();
2308 		}
2309 		rcu_read_unlock();
2310 
2311 		sectors -= s;
2312 		sect += s;
2313 	}
2314 }
2315 
bi_complete(struct bio * bio,int error)2316 static void bi_complete(struct bio *bio, int error)
2317 {
2318 	complete((struct completion *)bio->bi_private);
2319 }
2320 
submit_bio_wait(int rw,struct bio * bio)2321 static int submit_bio_wait(int rw, struct bio *bio)
2322 {
2323 	struct completion event;
2324 	rw |= REQ_SYNC;
2325 
2326 	init_completion(&event);
2327 	bio->bi_private = &event;
2328 	bio->bi_end_io = bi_complete;
2329 	submit_bio(rw, bio);
2330 	wait_for_completion(&event);
2331 
2332 	return test_bit(BIO_UPTODATE, &bio->bi_flags);
2333 }
2334 
narrow_write_error(struct r10bio * r10_bio,int i)2335 static int narrow_write_error(struct r10bio *r10_bio, int i)
2336 {
2337 	struct bio *bio = r10_bio->master_bio;
2338 	struct mddev *mddev = r10_bio->mddev;
2339 	struct r10conf *conf = mddev->private;
2340 	struct md_rdev *rdev = conf->mirrors[r10_bio->devs[i].devnum].rdev;
2341 	/* bio has the data to be written to slot 'i' where
2342 	 * we just recently had a write error.
2343 	 * We repeatedly clone the bio and trim down to one block,
2344 	 * then try the write.  Where the write fails we record
2345 	 * a bad block.
2346 	 * It is conceivable that the bio doesn't exactly align with
2347 	 * blocks.  We must handle this.
2348 	 *
2349 	 * We currently own a reference to the rdev.
2350 	 */
2351 
2352 	int block_sectors;
2353 	sector_t sector;
2354 	int sectors;
2355 	int sect_to_write = r10_bio->sectors;
2356 	int ok = 1;
2357 
2358 	if (rdev->badblocks.shift < 0)
2359 		return 0;
2360 
2361 	block_sectors = 1 << rdev->badblocks.shift;
2362 	sector = r10_bio->sector;
2363 	sectors = ((r10_bio->sector + block_sectors)
2364 		   & ~(sector_t)(block_sectors - 1))
2365 		- sector;
2366 
2367 	while (sect_to_write) {
2368 		struct bio *wbio;
2369 		if (sectors > sect_to_write)
2370 			sectors = sect_to_write;
2371 		/* Write at 'sector' for 'sectors' */
2372 		wbio = bio_clone_mddev(bio, GFP_NOIO, mddev);
2373 		md_trim_bio(wbio, sector - bio->bi_sector, sectors);
2374 		wbio->bi_sector = (r10_bio->devs[i].addr+
2375 				   rdev->data_offset+
2376 				   (sector - r10_bio->sector));
2377 		wbio->bi_bdev = rdev->bdev;
2378 		if (submit_bio_wait(WRITE, wbio) == 0)
2379 			/* Failure! */
2380 			ok = rdev_set_badblocks(rdev, sector,
2381 						sectors, 0)
2382 				&& ok;
2383 
2384 		bio_put(wbio);
2385 		sect_to_write -= sectors;
2386 		sector += sectors;
2387 		sectors = block_sectors;
2388 	}
2389 	return ok;
2390 }
2391 
handle_read_error(struct mddev * mddev,struct r10bio * r10_bio)2392 static void handle_read_error(struct mddev *mddev, struct r10bio *r10_bio)
2393 {
2394 	int slot = r10_bio->read_slot;
2395 	struct bio *bio;
2396 	struct r10conf *conf = mddev->private;
2397 	struct md_rdev *rdev = r10_bio->devs[slot].rdev;
2398 	char b[BDEVNAME_SIZE];
2399 	unsigned long do_sync;
2400 	int max_sectors;
2401 
2402 	/* we got a read error. Maybe the drive is bad.  Maybe just
2403 	 * the block and we can fix it.
2404 	 * We freeze all other IO, and try reading the block from
2405 	 * other devices.  When we find one, we re-write
2406 	 * and check it that fixes the read error.
2407 	 * This is all done synchronously while the array is
2408 	 * frozen.
2409 	 */
2410 	bio = r10_bio->devs[slot].bio;
2411 	bdevname(bio->bi_bdev, b);
2412 	bio_put(bio);
2413 	r10_bio->devs[slot].bio = NULL;
2414 
2415 	if (mddev->ro == 0) {
2416 		freeze_array(conf, 1);
2417 		fix_read_error(conf, mddev, r10_bio);
2418 		unfreeze_array(conf);
2419 	} else
2420 		r10_bio->devs[slot].bio = IO_BLOCKED;
2421 
2422 	rdev_dec_pending(rdev, mddev);
2423 
2424 read_more:
2425 	rdev = read_balance(conf, r10_bio, &max_sectors);
2426 	if (rdev == NULL) {
2427 		printk(KERN_ALERT "md/raid10:%s: %s: unrecoverable I/O"
2428 		       " read error for block %llu\n",
2429 		       mdname(mddev), b,
2430 		       (unsigned long long)r10_bio->sector);
2431 		raid_end_bio_io(r10_bio);
2432 		return;
2433 	}
2434 
2435 	do_sync = (r10_bio->master_bio->bi_rw & REQ_SYNC);
2436 	slot = r10_bio->read_slot;
2437 	printk_ratelimited(
2438 		KERN_ERR
2439 		"md/raid10:%s: %s: redirecting "
2440 		"sector %llu to another mirror\n",
2441 		mdname(mddev),
2442 		bdevname(rdev->bdev, b),
2443 		(unsigned long long)r10_bio->sector);
2444 	bio = bio_clone_mddev(r10_bio->master_bio,
2445 			      GFP_NOIO, mddev);
2446 	md_trim_bio(bio,
2447 		    r10_bio->sector - bio->bi_sector,
2448 		    max_sectors);
2449 	r10_bio->devs[slot].bio = bio;
2450 	r10_bio->devs[slot].rdev = rdev;
2451 	bio->bi_sector = r10_bio->devs[slot].addr
2452 		+ rdev->data_offset;
2453 	bio->bi_bdev = rdev->bdev;
2454 	bio->bi_rw = READ | do_sync;
2455 	bio->bi_private = r10_bio;
2456 	bio->bi_end_io = raid10_end_read_request;
2457 	if (max_sectors < r10_bio->sectors) {
2458 		/* Drat - have to split this up more */
2459 		struct bio *mbio = r10_bio->master_bio;
2460 		int sectors_handled =
2461 			r10_bio->sector + max_sectors
2462 			- mbio->bi_sector;
2463 		r10_bio->sectors = max_sectors;
2464 		spin_lock_irq(&conf->device_lock);
2465 		if (mbio->bi_phys_segments == 0)
2466 			mbio->bi_phys_segments = 2;
2467 		else
2468 			mbio->bi_phys_segments++;
2469 		spin_unlock_irq(&conf->device_lock);
2470 		generic_make_request(bio);
2471 
2472 		r10_bio = mempool_alloc(conf->r10bio_pool,
2473 					GFP_NOIO);
2474 		r10_bio->master_bio = mbio;
2475 		r10_bio->sectors = (mbio->bi_size >> 9)
2476 			- sectors_handled;
2477 		r10_bio->state = 0;
2478 		set_bit(R10BIO_ReadError,
2479 			&r10_bio->state);
2480 		r10_bio->mddev = mddev;
2481 		r10_bio->sector = mbio->bi_sector
2482 			+ sectors_handled;
2483 
2484 		goto read_more;
2485 	} else
2486 		generic_make_request(bio);
2487 }
2488 
handle_write_completed(struct r10conf * conf,struct r10bio * r10_bio)2489 static void handle_write_completed(struct r10conf *conf, struct r10bio *r10_bio)
2490 {
2491 	/* Some sort of write request has finished and it
2492 	 * succeeded in writing where we thought there was a
2493 	 * bad block.  So forget the bad block.
2494 	 * Or possibly if failed and we need to record
2495 	 * a bad block.
2496 	 */
2497 	int m;
2498 	struct md_rdev *rdev;
2499 
2500 	if (test_bit(R10BIO_IsSync, &r10_bio->state) ||
2501 	    test_bit(R10BIO_IsRecover, &r10_bio->state)) {
2502 		for (m = 0; m < conf->copies; m++) {
2503 			int dev = r10_bio->devs[m].devnum;
2504 			rdev = conf->mirrors[dev].rdev;
2505 			if (r10_bio->devs[m].bio == NULL)
2506 				continue;
2507 			if (test_bit(BIO_UPTODATE,
2508 				     &r10_bio->devs[m].bio->bi_flags)) {
2509 				rdev_clear_badblocks(
2510 					rdev,
2511 					r10_bio->devs[m].addr,
2512 					r10_bio->sectors);
2513 			} else {
2514 				if (!rdev_set_badblocks(
2515 					    rdev,
2516 					    r10_bio->devs[m].addr,
2517 					    r10_bio->sectors, 0))
2518 					md_error(conf->mddev, rdev);
2519 			}
2520 			rdev = conf->mirrors[dev].replacement;
2521 			if (r10_bio->devs[m].repl_bio == NULL)
2522 				continue;
2523 			if (test_bit(BIO_UPTODATE,
2524 				     &r10_bio->devs[m].repl_bio->bi_flags)) {
2525 				rdev_clear_badblocks(
2526 					rdev,
2527 					r10_bio->devs[m].addr,
2528 					r10_bio->sectors);
2529 			} else {
2530 				if (!rdev_set_badblocks(
2531 					    rdev,
2532 					    r10_bio->devs[m].addr,
2533 					    r10_bio->sectors, 0))
2534 					md_error(conf->mddev, rdev);
2535 			}
2536 		}
2537 		put_buf(r10_bio);
2538 	} else {
2539 		for (m = 0; m < conf->copies; m++) {
2540 			int dev = r10_bio->devs[m].devnum;
2541 			struct bio *bio = r10_bio->devs[m].bio;
2542 			rdev = conf->mirrors[dev].rdev;
2543 			if (bio == IO_MADE_GOOD) {
2544 				rdev_clear_badblocks(
2545 					rdev,
2546 					r10_bio->devs[m].addr,
2547 					r10_bio->sectors);
2548 				rdev_dec_pending(rdev, conf->mddev);
2549 			} else if (bio != NULL &&
2550 				   !test_bit(BIO_UPTODATE, &bio->bi_flags)) {
2551 				if (!narrow_write_error(r10_bio, m)) {
2552 					md_error(conf->mddev, rdev);
2553 					set_bit(R10BIO_Degraded,
2554 						&r10_bio->state);
2555 				}
2556 				rdev_dec_pending(rdev, conf->mddev);
2557 			}
2558 			bio = r10_bio->devs[m].repl_bio;
2559 			rdev = conf->mirrors[dev].replacement;
2560 			if (rdev && bio == IO_MADE_GOOD) {
2561 				rdev_clear_badblocks(
2562 					rdev,
2563 					r10_bio->devs[m].addr,
2564 					r10_bio->sectors);
2565 				rdev_dec_pending(rdev, conf->mddev);
2566 			}
2567 		}
2568 		if (test_bit(R10BIO_WriteError,
2569 			     &r10_bio->state))
2570 			close_write(r10_bio);
2571 		raid_end_bio_io(r10_bio);
2572 	}
2573 }
2574 
raid10d(struct mddev * mddev)2575 static void raid10d(struct mddev *mddev)
2576 {
2577 	struct r10bio *r10_bio;
2578 	unsigned long flags;
2579 	struct r10conf *conf = mddev->private;
2580 	struct list_head *head = &conf->retry_list;
2581 	struct blk_plug plug;
2582 
2583 	md_check_recovery(mddev);
2584 
2585 	blk_start_plug(&plug);
2586 	for (;;) {
2587 
2588 		flush_pending_writes(conf);
2589 
2590 		spin_lock_irqsave(&conf->device_lock, flags);
2591 		if (list_empty(head)) {
2592 			spin_unlock_irqrestore(&conf->device_lock, flags);
2593 			break;
2594 		}
2595 		r10_bio = list_entry(head->prev, struct r10bio, retry_list);
2596 		list_del(head->prev);
2597 		conf->nr_queued--;
2598 		spin_unlock_irqrestore(&conf->device_lock, flags);
2599 
2600 		mddev = r10_bio->mddev;
2601 		conf = mddev->private;
2602 		if (test_bit(R10BIO_MadeGood, &r10_bio->state) ||
2603 		    test_bit(R10BIO_WriteError, &r10_bio->state))
2604 			handle_write_completed(conf, r10_bio);
2605 		else if (test_bit(R10BIO_IsSync, &r10_bio->state))
2606 			sync_request_write(mddev, r10_bio);
2607 		else if (test_bit(R10BIO_IsRecover, &r10_bio->state))
2608 			recovery_request_write(mddev, r10_bio);
2609 		else if (test_bit(R10BIO_ReadError, &r10_bio->state))
2610 			handle_read_error(mddev, r10_bio);
2611 		else {
2612 			/* just a partial read to be scheduled from a
2613 			 * separate context
2614 			 */
2615 			int slot = r10_bio->read_slot;
2616 			generic_make_request(r10_bio->devs[slot].bio);
2617 		}
2618 
2619 		cond_resched();
2620 		if (mddev->flags & ~(1<<MD_CHANGE_PENDING))
2621 			md_check_recovery(mddev);
2622 	}
2623 	blk_finish_plug(&plug);
2624 }
2625 
2626 
init_resync(struct r10conf * conf)2627 static int init_resync(struct r10conf *conf)
2628 {
2629 	int buffs;
2630 	int i;
2631 
2632 	buffs = RESYNC_WINDOW / RESYNC_BLOCK_SIZE;
2633 	BUG_ON(conf->r10buf_pool);
2634 	conf->have_replacement = 0;
2635 	for (i = 0; i < conf->raid_disks; i++)
2636 		if (conf->mirrors[i].replacement)
2637 			conf->have_replacement = 1;
2638 	conf->r10buf_pool = mempool_create(buffs, r10buf_pool_alloc, r10buf_pool_free, conf);
2639 	if (!conf->r10buf_pool)
2640 		return -ENOMEM;
2641 	conf->next_resync = 0;
2642 	return 0;
2643 }
2644 
2645 /*
2646  * perform a "sync" on one "block"
2647  *
2648  * We need to make sure that no normal I/O request - particularly write
2649  * requests - conflict with active sync requests.
2650  *
2651  * This is achieved by tracking pending requests and a 'barrier' concept
2652  * that can be installed to exclude normal IO requests.
2653  *
2654  * Resync and recovery are handled very differently.
2655  * We differentiate by looking at MD_RECOVERY_SYNC in mddev->recovery.
2656  *
2657  * For resync, we iterate over virtual addresses, read all copies,
2658  * and update if there are differences.  If only one copy is live,
2659  * skip it.
2660  * For recovery, we iterate over physical addresses, read a good
2661  * value for each non-in_sync drive, and over-write.
2662  *
2663  * So, for recovery we may have several outstanding complex requests for a
2664  * given address, one for each out-of-sync device.  We model this by allocating
2665  * a number of r10_bio structures, one for each out-of-sync device.
2666  * As we setup these structures, we collect all bio's together into a list
2667  * which we then process collectively to add pages, and then process again
2668  * to pass to generic_make_request.
2669  *
2670  * The r10_bio structures are linked using a borrowed master_bio pointer.
2671  * This link is counted in ->remaining.  When the r10_bio that points to NULL
2672  * has its remaining count decremented to 0, the whole complex operation
2673  * is complete.
2674  *
2675  */
2676 
sync_request(struct mddev * mddev,sector_t sector_nr,int * skipped,int go_faster)2677 static sector_t sync_request(struct mddev *mddev, sector_t sector_nr,
2678 			     int *skipped, int go_faster)
2679 {
2680 	struct r10conf *conf = mddev->private;
2681 	struct r10bio *r10_bio;
2682 	struct bio *biolist = NULL, *bio;
2683 	sector_t max_sector, nr_sectors;
2684 	int i;
2685 	int max_sync;
2686 	sector_t sync_blocks;
2687 	sector_t sectors_skipped = 0;
2688 	int chunks_skipped = 0;
2689 
2690 	if (!conf->r10buf_pool)
2691 		if (init_resync(conf))
2692 			return 0;
2693 
2694  skipped:
2695 	max_sector = mddev->dev_sectors;
2696 	if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery))
2697 		max_sector = mddev->resync_max_sectors;
2698 	if (sector_nr >= max_sector) {
2699 		/* If we aborted, we need to abort the
2700 		 * sync on the 'current' bitmap chucks (there can
2701 		 * be several when recovering multiple devices).
2702 		 * as we may have started syncing it but not finished.
2703 		 * We can find the current address in
2704 		 * mddev->curr_resync, but for recovery,
2705 		 * we need to convert that to several
2706 		 * virtual addresses.
2707 		 */
2708 		if (mddev->curr_resync < max_sector) { /* aborted */
2709 			if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery))
2710 				bitmap_end_sync(mddev->bitmap, mddev->curr_resync,
2711 						&sync_blocks, 1);
2712 			else for (i=0; i<conf->raid_disks; i++) {
2713 				sector_t sect =
2714 					raid10_find_virt(conf, mddev->curr_resync, i);
2715 				bitmap_end_sync(mddev->bitmap, sect,
2716 						&sync_blocks, 1);
2717 			}
2718 		} else {
2719 			/* completed sync */
2720 			if ((!mddev->bitmap || conf->fullsync)
2721 			    && conf->have_replacement
2722 			    && test_bit(MD_RECOVERY_SYNC, &mddev->recovery)) {
2723 				/* Completed a full sync so the replacements
2724 				 * are now fully recovered.
2725 				 */
2726 				for (i = 0; i < conf->raid_disks; i++)
2727 					if (conf->mirrors[i].replacement)
2728 						conf->mirrors[i].replacement
2729 							->recovery_offset
2730 							= MaxSector;
2731 			}
2732 			conf->fullsync = 0;
2733 		}
2734 		bitmap_close_sync(mddev->bitmap);
2735 		close_sync(conf);
2736 		*skipped = 1;
2737 		return sectors_skipped;
2738 	}
2739 	if (chunks_skipped >= conf->raid_disks) {
2740 		/* if there has been nothing to do on any drive,
2741 		 * then there is nothing to do at all..
2742 		 */
2743 		*skipped = 1;
2744 		return (max_sector - sector_nr) + sectors_skipped;
2745 	}
2746 
2747 	if (max_sector > mddev->resync_max)
2748 		max_sector = mddev->resync_max; /* Don't do IO beyond here */
2749 
2750 	/* make sure whole request will fit in a chunk - if chunks
2751 	 * are meaningful
2752 	 */
2753 	if (conf->near_copies < conf->raid_disks &&
2754 	    max_sector > (sector_nr | conf->chunk_mask))
2755 		max_sector = (sector_nr | conf->chunk_mask) + 1;
2756 	/*
2757 	 * If there is non-resync activity waiting for us then
2758 	 * put in a delay to throttle resync.
2759 	 */
2760 	if (!go_faster && conf->nr_waiting)
2761 		msleep_interruptible(1000);
2762 
2763 	/* Again, very different code for resync and recovery.
2764 	 * Both must result in an r10bio with a list of bios that
2765 	 * have bi_end_io, bi_sector, bi_bdev set,
2766 	 * and bi_private set to the r10bio.
2767 	 * For recovery, we may actually create several r10bios
2768 	 * with 2 bios in each, that correspond to the bios in the main one.
2769 	 * In this case, the subordinate r10bios link back through a
2770 	 * borrowed master_bio pointer, and the counter in the master
2771 	 * includes a ref from each subordinate.
2772 	 */
2773 	/* First, we decide what to do and set ->bi_end_io
2774 	 * To end_sync_read if we want to read, and
2775 	 * end_sync_write if we will want to write.
2776 	 */
2777 
2778 	max_sync = RESYNC_PAGES << (PAGE_SHIFT-9);
2779 	if (!test_bit(MD_RECOVERY_SYNC, &mddev->recovery)) {
2780 		/* recovery... the complicated one */
2781 		int j;
2782 		r10_bio = NULL;
2783 
2784 		for (i=0 ; i<conf->raid_disks; i++) {
2785 			int still_degraded;
2786 			struct r10bio *rb2;
2787 			sector_t sect;
2788 			int must_sync;
2789 			int any_working;
2790 			struct mirror_info *mirror = &conf->mirrors[i];
2791 
2792 			if ((mirror->rdev == NULL ||
2793 			     test_bit(In_sync, &mirror->rdev->flags))
2794 			    &&
2795 			    (mirror->replacement == NULL ||
2796 			     test_bit(Faulty,
2797 				      &mirror->replacement->flags)))
2798 				continue;
2799 
2800 			still_degraded = 0;
2801 			/* want to reconstruct this device */
2802 			rb2 = r10_bio;
2803 			sect = raid10_find_virt(conf, sector_nr, i);
2804 			if (sect >= mddev->resync_max_sectors) {
2805 				/* last stripe is not complete - don't
2806 				 * try to recover this sector.
2807 				 */
2808 				continue;
2809 			}
2810 			/* Unless we are doing a full sync, or a replacement
2811 			 * we only need to recover the block if it is set in
2812 			 * the bitmap
2813 			 */
2814 			must_sync = bitmap_start_sync(mddev->bitmap, sect,
2815 						      &sync_blocks, 1);
2816 			if (sync_blocks < max_sync)
2817 				max_sync = sync_blocks;
2818 			if (!must_sync &&
2819 			    mirror->replacement == NULL &&
2820 			    !conf->fullsync) {
2821 				/* yep, skip the sync_blocks here, but don't assume
2822 				 * that there will never be anything to do here
2823 				 */
2824 				chunks_skipped = -1;
2825 				continue;
2826 			}
2827 
2828 			r10_bio = mempool_alloc(conf->r10buf_pool, GFP_NOIO);
2829 			raise_barrier(conf, rb2 != NULL);
2830 			atomic_set(&r10_bio->remaining, 0);
2831 
2832 			r10_bio->master_bio = (struct bio*)rb2;
2833 			if (rb2)
2834 				atomic_inc(&rb2->remaining);
2835 			r10_bio->mddev = mddev;
2836 			set_bit(R10BIO_IsRecover, &r10_bio->state);
2837 			r10_bio->sector = sect;
2838 
2839 			raid10_find_phys(conf, r10_bio);
2840 
2841 			/* Need to check if the array will still be
2842 			 * degraded
2843 			 */
2844 			for (j=0; j<conf->raid_disks; j++)
2845 				if (conf->mirrors[j].rdev == NULL ||
2846 				    test_bit(Faulty, &conf->mirrors[j].rdev->flags)) {
2847 					still_degraded = 1;
2848 					break;
2849 				}
2850 
2851 			must_sync = bitmap_start_sync(mddev->bitmap, sect,
2852 						      &sync_blocks, still_degraded);
2853 
2854 			any_working = 0;
2855 			for (j=0; j<conf->copies;j++) {
2856 				int k;
2857 				int d = r10_bio->devs[j].devnum;
2858 				sector_t from_addr, to_addr;
2859 				struct md_rdev *rdev;
2860 				sector_t sector, first_bad;
2861 				int bad_sectors;
2862 				if (!conf->mirrors[d].rdev ||
2863 				    !test_bit(In_sync, &conf->mirrors[d].rdev->flags))
2864 					continue;
2865 				/* This is where we read from */
2866 				any_working = 1;
2867 				rdev = conf->mirrors[d].rdev;
2868 				sector = r10_bio->devs[j].addr;
2869 
2870 				if (is_badblock(rdev, sector, max_sync,
2871 						&first_bad, &bad_sectors)) {
2872 					if (first_bad > sector)
2873 						max_sync = first_bad - sector;
2874 					else {
2875 						bad_sectors -= (sector
2876 								- first_bad);
2877 						if (max_sync > bad_sectors)
2878 							max_sync = bad_sectors;
2879 						continue;
2880 					}
2881 				}
2882 				bio = r10_bio->devs[0].bio;
2883 				bio->bi_next = biolist;
2884 				biolist = bio;
2885 				bio->bi_private = r10_bio;
2886 				bio->bi_end_io = end_sync_read;
2887 				bio->bi_rw = READ;
2888 				from_addr = r10_bio->devs[j].addr;
2889 				bio->bi_sector = from_addr + rdev->data_offset;
2890 				bio->bi_bdev = rdev->bdev;
2891 				atomic_inc(&rdev->nr_pending);
2892 				/* and we write to 'i' (if not in_sync) */
2893 
2894 				for (k=0; k<conf->copies; k++)
2895 					if (r10_bio->devs[k].devnum == i)
2896 						break;
2897 				BUG_ON(k == conf->copies);
2898 				to_addr = r10_bio->devs[k].addr;
2899 				r10_bio->devs[0].devnum = d;
2900 				r10_bio->devs[0].addr = from_addr;
2901 				r10_bio->devs[1].devnum = i;
2902 				r10_bio->devs[1].addr = to_addr;
2903 
2904 				rdev = mirror->rdev;
2905 				if (!test_bit(In_sync, &rdev->flags)) {
2906 					bio = r10_bio->devs[1].bio;
2907 					bio->bi_next = biolist;
2908 					biolist = bio;
2909 					bio->bi_private = r10_bio;
2910 					bio->bi_end_io = end_sync_write;
2911 					bio->bi_rw = WRITE;
2912 					bio->bi_sector = to_addr
2913 						+ rdev->data_offset;
2914 					bio->bi_bdev = rdev->bdev;
2915 					atomic_inc(&r10_bio->remaining);
2916 				} else
2917 					r10_bio->devs[1].bio->bi_end_io = NULL;
2918 
2919 				/* and maybe write to replacement */
2920 				bio = r10_bio->devs[1].repl_bio;
2921 				if (bio)
2922 					bio->bi_end_io = NULL;
2923 				rdev = mirror->replacement;
2924 				/* Note: if rdev != NULL, then bio
2925 				 * cannot be NULL as r10buf_pool_alloc will
2926 				 * have allocated it.
2927 				 * So the second test here is pointless.
2928 				 * But it keeps semantic-checkers happy, and
2929 				 * this comment keeps human reviewers
2930 				 * happy.
2931 				 */
2932 				if (rdev == NULL || bio == NULL ||
2933 				    test_bit(Faulty, &rdev->flags))
2934 					break;
2935 				bio->bi_next = biolist;
2936 				biolist = bio;
2937 				bio->bi_private = r10_bio;
2938 				bio->bi_end_io = end_sync_write;
2939 				bio->bi_rw = WRITE;
2940 				bio->bi_sector = to_addr + rdev->data_offset;
2941 				bio->bi_bdev = rdev->bdev;
2942 				atomic_inc(&r10_bio->remaining);
2943 				break;
2944 			}
2945 			if (j == conf->copies) {
2946 				/* Cannot recover, so abort the recovery or
2947 				 * record a bad block */
2948 				if (any_working) {
2949 					/* problem is that there are bad blocks
2950 					 * on other device(s)
2951 					 */
2952 					int k;
2953 					for (k = 0; k < conf->copies; k++)
2954 						if (r10_bio->devs[k].devnum == i)
2955 							break;
2956 					if (!test_bit(In_sync,
2957 						      &mirror->rdev->flags)
2958 					    && !rdev_set_badblocks(
2959 						    mirror->rdev,
2960 						    r10_bio->devs[k].addr,
2961 						    max_sync, 0))
2962 						any_working = 0;
2963 					if (mirror->replacement &&
2964 					    !rdev_set_badblocks(
2965 						    mirror->replacement,
2966 						    r10_bio->devs[k].addr,
2967 						    max_sync, 0))
2968 						any_working = 0;
2969 				}
2970 				if (!any_working)  {
2971 					if (!test_and_set_bit(MD_RECOVERY_INTR,
2972 							      &mddev->recovery))
2973 						printk(KERN_INFO "md/raid10:%s: insufficient "
2974 						       "working devices for recovery.\n",
2975 						       mdname(mddev));
2976 					mirror->recovery_disabled
2977 						= mddev->recovery_disabled;
2978 				}
2979 				put_buf(r10_bio);
2980 				if (rb2)
2981 					atomic_dec(&rb2->remaining);
2982 				r10_bio = rb2;
2983 				break;
2984 			}
2985 		}
2986 		if (biolist == NULL) {
2987 			while (r10_bio) {
2988 				struct r10bio *rb2 = r10_bio;
2989 				r10_bio = (struct r10bio*) rb2->master_bio;
2990 				rb2->master_bio = NULL;
2991 				put_buf(rb2);
2992 			}
2993 			goto giveup;
2994 		}
2995 	} else {
2996 		/* resync. Schedule a read for every block at this virt offset */
2997 		int count = 0;
2998 
2999 		bitmap_cond_end_sync(mddev->bitmap, sector_nr);
3000 
3001 		if (!bitmap_start_sync(mddev->bitmap, sector_nr,
3002 				       &sync_blocks, mddev->degraded) &&
3003 		    !conf->fullsync && !test_bit(MD_RECOVERY_REQUESTED,
3004 						 &mddev->recovery)) {
3005 			/* We can skip this block */
3006 			*skipped = 1;
3007 			return sync_blocks + sectors_skipped;
3008 		}
3009 		if (sync_blocks < max_sync)
3010 			max_sync = sync_blocks;
3011 		r10_bio = mempool_alloc(conf->r10buf_pool, GFP_NOIO);
3012 
3013 		r10_bio->mddev = mddev;
3014 		atomic_set(&r10_bio->remaining, 0);
3015 		raise_barrier(conf, 0);
3016 		conf->next_resync = sector_nr;
3017 
3018 		r10_bio->master_bio = NULL;
3019 		r10_bio->sector = sector_nr;
3020 		set_bit(R10BIO_IsSync, &r10_bio->state);
3021 		raid10_find_phys(conf, r10_bio);
3022 		r10_bio->sectors = (sector_nr | conf->chunk_mask) - sector_nr +1;
3023 
3024 		for (i=0; i<conf->copies; i++) {
3025 			int d = r10_bio->devs[i].devnum;
3026 			sector_t first_bad, sector;
3027 			int bad_sectors;
3028 
3029 			if (r10_bio->devs[i].repl_bio)
3030 				r10_bio->devs[i].repl_bio->bi_end_io = NULL;
3031 
3032 			bio = r10_bio->devs[i].bio;
3033 			bio->bi_end_io = NULL;
3034 			clear_bit(BIO_UPTODATE, &bio->bi_flags);
3035 			if (conf->mirrors[d].rdev == NULL ||
3036 			    test_bit(Faulty, &conf->mirrors[d].rdev->flags))
3037 				continue;
3038 			sector = r10_bio->devs[i].addr;
3039 			if (is_badblock(conf->mirrors[d].rdev,
3040 					sector, max_sync,
3041 					&first_bad, &bad_sectors)) {
3042 				if (first_bad > sector)
3043 					max_sync = first_bad - sector;
3044 				else {
3045 					bad_sectors -= (sector - first_bad);
3046 					if (max_sync > bad_sectors)
3047 						max_sync = bad_sectors;
3048 					continue;
3049 				}
3050 			}
3051 			atomic_inc(&conf->mirrors[d].rdev->nr_pending);
3052 			atomic_inc(&r10_bio->remaining);
3053 			bio->bi_next = biolist;
3054 			biolist = bio;
3055 			bio->bi_private = r10_bio;
3056 			bio->bi_end_io = end_sync_read;
3057 			bio->bi_rw = READ;
3058 			bio->bi_sector = sector +
3059 				conf->mirrors[d].rdev->data_offset;
3060 			bio->bi_bdev = conf->mirrors[d].rdev->bdev;
3061 			count++;
3062 
3063 			if (conf->mirrors[d].replacement == NULL ||
3064 			    test_bit(Faulty,
3065 				     &conf->mirrors[d].replacement->flags))
3066 				continue;
3067 
3068 			/* Need to set up for writing to the replacement */
3069 			bio = r10_bio->devs[i].repl_bio;
3070 			clear_bit(BIO_UPTODATE, &bio->bi_flags);
3071 
3072 			sector = r10_bio->devs[i].addr;
3073 			atomic_inc(&conf->mirrors[d].rdev->nr_pending);
3074 			bio->bi_next = biolist;
3075 			biolist = bio;
3076 			bio->bi_private = r10_bio;
3077 			bio->bi_end_io = end_sync_write;
3078 			bio->bi_rw = WRITE;
3079 			bio->bi_sector = sector +
3080 				conf->mirrors[d].replacement->data_offset;
3081 			bio->bi_bdev = conf->mirrors[d].replacement->bdev;
3082 			count++;
3083 		}
3084 
3085 		if (count < 2) {
3086 			for (i=0; i<conf->copies; i++) {
3087 				int d = r10_bio->devs[i].devnum;
3088 				if (r10_bio->devs[i].bio->bi_end_io)
3089 					rdev_dec_pending(conf->mirrors[d].rdev,
3090 							 mddev);
3091 				if (r10_bio->devs[i].repl_bio &&
3092 				    r10_bio->devs[i].repl_bio->bi_end_io)
3093 					rdev_dec_pending(
3094 						conf->mirrors[d].replacement,
3095 						mddev);
3096 			}
3097 			put_buf(r10_bio);
3098 			biolist = NULL;
3099 			goto giveup;
3100 		}
3101 	}
3102 
3103 	for (bio = biolist; bio ; bio=bio->bi_next) {
3104 
3105 		bio->bi_flags &= ~(BIO_POOL_MASK - 1);
3106 		if (bio->bi_end_io)
3107 			bio->bi_flags |= 1 << BIO_UPTODATE;
3108 		bio->bi_vcnt = 0;
3109 		bio->bi_idx = 0;
3110 		bio->bi_phys_segments = 0;
3111 		bio->bi_size = 0;
3112 	}
3113 
3114 	nr_sectors = 0;
3115 	if (sector_nr + max_sync < max_sector)
3116 		max_sector = sector_nr + max_sync;
3117 	do {
3118 		struct page *page;
3119 		int len = PAGE_SIZE;
3120 		if (sector_nr + (len>>9) > max_sector)
3121 			len = (max_sector - sector_nr) << 9;
3122 		if (len == 0)
3123 			break;
3124 		for (bio= biolist ; bio ; bio=bio->bi_next) {
3125 			struct bio *bio2;
3126 			page = bio->bi_io_vec[bio->bi_vcnt].bv_page;
3127 			if (bio_add_page(bio, page, len, 0))
3128 				continue;
3129 
3130 			/* stop here */
3131 			bio->bi_io_vec[bio->bi_vcnt].bv_page = page;
3132 			for (bio2 = biolist;
3133 			     bio2 && bio2 != bio;
3134 			     bio2 = bio2->bi_next) {
3135 				/* remove last page from this bio */
3136 				bio2->bi_vcnt--;
3137 				bio2->bi_size -= len;
3138 				bio2->bi_flags &= ~(1<< BIO_SEG_VALID);
3139 			}
3140 			goto bio_full;
3141 		}
3142 		nr_sectors += len>>9;
3143 		sector_nr += len>>9;
3144 	} while (biolist->bi_vcnt < RESYNC_PAGES);
3145  bio_full:
3146 	r10_bio->sectors = nr_sectors;
3147 
3148 	while (biolist) {
3149 		bio = biolist;
3150 		biolist = biolist->bi_next;
3151 
3152 		bio->bi_next = NULL;
3153 		r10_bio = bio->bi_private;
3154 		r10_bio->sectors = nr_sectors;
3155 
3156 		if (bio->bi_end_io == end_sync_read) {
3157 			md_sync_acct(bio->bi_bdev, nr_sectors);
3158 			generic_make_request(bio);
3159 		}
3160 	}
3161 
3162 	if (sectors_skipped)
3163 		/* pretend they weren't skipped, it makes
3164 		 * no important difference in this case
3165 		 */
3166 		md_done_sync(mddev, sectors_skipped, 1);
3167 
3168 	return sectors_skipped + nr_sectors;
3169  giveup:
3170 	/* There is nowhere to write, so all non-sync
3171 	 * drives must be failed or in resync, all drives
3172 	 * have a bad block, so try the next chunk...
3173 	 */
3174 	if (sector_nr + max_sync < max_sector)
3175 		max_sector = sector_nr + max_sync;
3176 
3177 	sectors_skipped += (max_sector - sector_nr);
3178 	chunks_skipped ++;
3179 	sector_nr = max_sector;
3180 	goto skipped;
3181 }
3182 
3183 static sector_t
raid10_size(struct mddev * mddev,sector_t sectors,int raid_disks)3184 raid10_size(struct mddev *mddev, sector_t sectors, int raid_disks)
3185 {
3186 	sector_t size;
3187 	struct r10conf *conf = mddev->private;
3188 
3189 	if (!raid_disks)
3190 		raid_disks = conf->raid_disks;
3191 	if (!sectors)
3192 		sectors = conf->dev_sectors;
3193 
3194 	size = sectors >> conf->chunk_shift;
3195 	sector_div(size, conf->far_copies);
3196 	size = size * raid_disks;
3197 	sector_div(size, conf->near_copies);
3198 
3199 	return size << conf->chunk_shift;
3200 }
3201 
calc_sectors(struct r10conf * conf,sector_t size)3202 static void calc_sectors(struct r10conf *conf, sector_t size)
3203 {
3204 	/* Calculate the number of sectors-per-device that will
3205 	 * actually be used, and set conf->dev_sectors and
3206 	 * conf->stride
3207 	 */
3208 
3209 	size = size >> conf->chunk_shift;
3210 	sector_div(size, conf->far_copies);
3211 	size = size * conf->raid_disks;
3212 	sector_div(size, conf->near_copies);
3213 	/* 'size' is now the number of chunks in the array */
3214 	/* calculate "used chunks per device" */
3215 	size = size * conf->copies;
3216 
3217 	/* We need to round up when dividing by raid_disks to
3218 	 * get the stride size.
3219 	 */
3220 	size = DIV_ROUND_UP_SECTOR_T(size, conf->raid_disks);
3221 
3222 	conf->dev_sectors = size << conf->chunk_shift;
3223 
3224 	if (conf->far_offset)
3225 		conf->stride = 1 << conf->chunk_shift;
3226 	else {
3227 		sector_div(size, conf->far_copies);
3228 		conf->stride = size << conf->chunk_shift;
3229 	}
3230 }
3231 
setup_conf(struct mddev * mddev)3232 static struct r10conf *setup_conf(struct mddev *mddev)
3233 {
3234 	struct r10conf *conf = NULL;
3235 	int nc, fc, fo;
3236 	int err = -EINVAL;
3237 
3238 	if (mddev->new_chunk_sectors < (PAGE_SIZE >> 9) ||
3239 	    !is_power_of_2(mddev->new_chunk_sectors)) {
3240 		printk(KERN_ERR "md/raid10:%s: chunk size must be "
3241 		       "at least PAGE_SIZE(%ld) and be a power of 2.\n",
3242 		       mdname(mddev), PAGE_SIZE);
3243 		goto out;
3244 	}
3245 
3246 	nc = mddev->new_layout & 255;
3247 	fc = (mddev->new_layout >> 8) & 255;
3248 	fo = mddev->new_layout & (1<<16);
3249 
3250 	if ((nc*fc) <2 || (nc*fc) > mddev->raid_disks ||
3251 	    (mddev->new_layout >> 17)) {
3252 		printk(KERN_ERR "md/raid10:%s: unsupported raid10 layout: 0x%8x\n",
3253 		       mdname(mddev), mddev->new_layout);
3254 		goto out;
3255 	}
3256 
3257 	err = -ENOMEM;
3258 	conf = kzalloc(sizeof(struct r10conf), GFP_KERNEL);
3259 	if (!conf)
3260 		goto out;
3261 
3262 	conf->mirrors = kzalloc(sizeof(struct mirror_info)*mddev->raid_disks,
3263 				GFP_KERNEL);
3264 	if (!conf->mirrors)
3265 		goto out;
3266 
3267 	conf->tmppage = alloc_page(GFP_KERNEL);
3268 	if (!conf->tmppage)
3269 		goto out;
3270 
3271 
3272 	conf->raid_disks = mddev->raid_disks;
3273 	conf->near_copies = nc;
3274 	conf->far_copies = fc;
3275 	conf->copies = nc*fc;
3276 	conf->far_offset = fo;
3277 	conf->chunk_mask = mddev->new_chunk_sectors - 1;
3278 	conf->chunk_shift = ffz(~mddev->new_chunk_sectors);
3279 
3280 	conf->r10bio_pool = mempool_create(NR_RAID10_BIOS, r10bio_pool_alloc,
3281 					   r10bio_pool_free, conf);
3282 	if (!conf->r10bio_pool)
3283 		goto out;
3284 
3285 	calc_sectors(conf, mddev->dev_sectors);
3286 
3287 	spin_lock_init(&conf->device_lock);
3288 	INIT_LIST_HEAD(&conf->retry_list);
3289 
3290 	spin_lock_init(&conf->resync_lock);
3291 	init_waitqueue_head(&conf->wait_barrier);
3292 
3293 	conf->thread = md_register_thread(raid10d, mddev, NULL);
3294 	if (!conf->thread)
3295 		goto out;
3296 
3297 	conf->mddev = mddev;
3298 	return conf;
3299 
3300  out:
3301 	printk(KERN_ERR "md/raid10:%s: couldn't allocate memory.\n",
3302 	       mdname(mddev));
3303 	if (conf) {
3304 		if (conf->r10bio_pool)
3305 			mempool_destroy(conf->r10bio_pool);
3306 		kfree(conf->mirrors);
3307 		safe_put_page(conf->tmppage);
3308 		kfree(conf);
3309 	}
3310 	return ERR_PTR(err);
3311 }
3312 
run(struct mddev * mddev)3313 static int run(struct mddev *mddev)
3314 {
3315 	struct r10conf *conf;
3316 	int i, disk_idx, chunk_size;
3317 	struct mirror_info *disk;
3318 	struct md_rdev *rdev;
3319 	sector_t size;
3320 
3321 	/*
3322 	 * copy the already verified devices into our private RAID10
3323 	 * bookkeeping area. [whatever we allocate in run(),
3324 	 * should be freed in stop()]
3325 	 */
3326 
3327 	if (mddev->private == NULL) {
3328 		conf = setup_conf(mddev);
3329 		if (IS_ERR(conf))
3330 			return PTR_ERR(conf);
3331 		mddev->private = conf;
3332 	}
3333 	conf = mddev->private;
3334 	if (!conf)
3335 		goto out;
3336 
3337 	mddev->thread = conf->thread;
3338 	conf->thread = NULL;
3339 
3340 	chunk_size = mddev->chunk_sectors << 9;
3341 	blk_queue_io_min(mddev->queue, chunk_size);
3342 	if (conf->raid_disks % conf->near_copies)
3343 		blk_queue_io_opt(mddev->queue, chunk_size * conf->raid_disks);
3344 	else
3345 		blk_queue_io_opt(mddev->queue, chunk_size *
3346 				 (conf->raid_disks / conf->near_copies));
3347 
3348 	rdev_for_each(rdev, mddev) {
3349 		struct request_queue *q;
3350 		disk_idx = rdev->raid_disk;
3351 		if (disk_idx >= conf->raid_disks
3352 		    || disk_idx < 0)
3353 			continue;
3354 		disk = conf->mirrors + disk_idx;
3355 
3356 		if (test_bit(Replacement, &rdev->flags)) {
3357 			if (disk->replacement)
3358 				goto out_free_conf;
3359 			disk->replacement = rdev;
3360 		} else {
3361 			if (disk->rdev)
3362 				goto out_free_conf;
3363 			disk->rdev = rdev;
3364 		}
3365 		q = bdev_get_queue(rdev->bdev);
3366 		if (q->merge_bvec_fn)
3367 			mddev->merge_check_needed = 1;
3368 
3369 		disk_stack_limits(mddev->gendisk, rdev->bdev,
3370 				  rdev->data_offset << 9);
3371 
3372 		disk->head_position = 0;
3373 	}
3374 	/* need to check that every block has at least one working mirror */
3375 	if (!enough(conf, -1)) {
3376 		printk(KERN_ERR "md/raid10:%s: not enough operational mirrors.\n",
3377 		       mdname(mddev));
3378 		goto out_free_conf;
3379 	}
3380 
3381 	mddev->degraded = 0;
3382 	for (i = 0; i < conf->raid_disks; i++) {
3383 
3384 		disk = conf->mirrors + i;
3385 
3386 		if (!disk->rdev && disk->replacement) {
3387 			/* The replacement is all we have - use it */
3388 			disk->rdev = disk->replacement;
3389 			disk->replacement = NULL;
3390 			clear_bit(Replacement, &disk->rdev->flags);
3391 		}
3392 
3393 		if (!disk->rdev ||
3394 		    !test_bit(In_sync, &disk->rdev->flags)) {
3395 			disk->head_position = 0;
3396 			mddev->degraded++;
3397 			if (disk->rdev)
3398 				conf->fullsync = 1;
3399 		}
3400 		disk->recovery_disabled = mddev->recovery_disabled - 1;
3401 	}
3402 
3403 	if (mddev->recovery_cp != MaxSector)
3404 		printk(KERN_NOTICE "md/raid10:%s: not clean"
3405 		       " -- starting background reconstruction\n",
3406 		       mdname(mddev));
3407 	printk(KERN_INFO
3408 		"md/raid10:%s: active with %d out of %d devices\n",
3409 		mdname(mddev), conf->raid_disks - mddev->degraded,
3410 		conf->raid_disks);
3411 	/*
3412 	 * Ok, everything is just fine now
3413 	 */
3414 	mddev->dev_sectors = conf->dev_sectors;
3415 	size = raid10_size(mddev, 0, 0);
3416 	md_set_array_sectors(mddev, size);
3417 	mddev->resync_max_sectors = size;
3418 
3419 	mddev->queue->backing_dev_info.congested_fn = raid10_congested;
3420 	mddev->queue->backing_dev_info.congested_data = mddev;
3421 
3422 	/* Calculate max read-ahead size.
3423 	 * We need to readahead at least twice a whole stripe....
3424 	 * maybe...
3425 	 */
3426 	{
3427 		int stripe = conf->raid_disks *
3428 			((mddev->chunk_sectors << 9) / PAGE_SIZE);
3429 		stripe /= conf->near_copies;
3430 		if (mddev->queue->backing_dev_info.ra_pages < 2* stripe)
3431 			mddev->queue->backing_dev_info.ra_pages = 2* stripe;
3432 	}
3433 
3434 	blk_queue_merge_bvec(mddev->queue, raid10_mergeable_bvec);
3435 
3436 	if (md_integrity_register(mddev))
3437 		goto out_free_conf;
3438 
3439 	return 0;
3440 
3441 out_free_conf:
3442 	md_unregister_thread(&mddev->thread);
3443 	if (conf->r10bio_pool)
3444 		mempool_destroy(conf->r10bio_pool);
3445 	safe_put_page(conf->tmppage);
3446 	kfree(conf->mirrors);
3447 	kfree(conf);
3448 	mddev->private = NULL;
3449 out:
3450 	return -EIO;
3451 }
3452 
stop(struct mddev * mddev)3453 static int stop(struct mddev *mddev)
3454 {
3455 	struct r10conf *conf = mddev->private;
3456 
3457 	raise_barrier(conf, 0);
3458 	lower_barrier(conf);
3459 
3460 	md_unregister_thread(&mddev->thread);
3461 	blk_sync_queue(mddev->queue); /* the unplug fn references 'conf'*/
3462 	if (conf->r10bio_pool)
3463 		mempool_destroy(conf->r10bio_pool);
3464 	kfree(conf->mirrors);
3465 	kfree(conf);
3466 	mddev->private = NULL;
3467 	return 0;
3468 }
3469 
raid10_quiesce(struct mddev * mddev,int state)3470 static void raid10_quiesce(struct mddev *mddev, int state)
3471 {
3472 	struct r10conf *conf = mddev->private;
3473 
3474 	switch(state) {
3475 	case 1:
3476 		raise_barrier(conf, 0);
3477 		break;
3478 	case 0:
3479 		lower_barrier(conf);
3480 		break;
3481 	}
3482 }
3483 
raid10_resize(struct mddev * mddev,sector_t sectors)3484 static int raid10_resize(struct mddev *mddev, sector_t sectors)
3485 {
3486 	/* Resize of 'far' arrays is not supported.
3487 	 * For 'near' and 'offset' arrays we can set the
3488 	 * number of sectors used to be an appropriate multiple
3489 	 * of the chunk size.
3490 	 * For 'offset', this is far_copies*chunksize.
3491 	 * For 'near' the multiplier is the LCM of
3492 	 * near_copies and raid_disks.
3493 	 * So if far_copies > 1 && !far_offset, fail.
3494 	 * Else find LCM(raid_disks, near_copy)*far_copies and
3495 	 * multiply by chunk_size.  Then round to this number.
3496 	 * This is mostly done by raid10_size()
3497 	 */
3498 	struct r10conf *conf = mddev->private;
3499 	sector_t oldsize, size;
3500 
3501 	if (conf->far_copies > 1 && !conf->far_offset)
3502 		return -EINVAL;
3503 
3504 	oldsize = raid10_size(mddev, 0, 0);
3505 	size = raid10_size(mddev, sectors, 0);
3506 	md_set_array_sectors(mddev, size);
3507 	if (mddev->array_sectors > size)
3508 		return -EINVAL;
3509 	set_capacity(mddev->gendisk, mddev->array_sectors);
3510 	revalidate_disk(mddev->gendisk);
3511 	if (sectors > mddev->dev_sectors &&
3512 	    mddev->recovery_cp > oldsize) {
3513 		mddev->recovery_cp = oldsize;
3514 		set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
3515 	}
3516 	calc_sectors(conf, sectors);
3517 	mddev->dev_sectors = conf->dev_sectors;
3518 	mddev->resync_max_sectors = size;
3519 	return 0;
3520 }
3521 
raid10_takeover_raid0(struct mddev * mddev)3522 static void *raid10_takeover_raid0(struct mddev *mddev)
3523 {
3524 	struct md_rdev *rdev;
3525 	struct r10conf *conf;
3526 
3527 	if (mddev->degraded > 0) {
3528 		printk(KERN_ERR "md/raid10:%s: Error: degraded raid0!\n",
3529 		       mdname(mddev));
3530 		return ERR_PTR(-EINVAL);
3531 	}
3532 
3533 	/* Set new parameters */
3534 	mddev->new_level = 10;
3535 	/* new layout: far_copies = 1, near_copies = 2 */
3536 	mddev->new_layout = (1<<8) + 2;
3537 	mddev->new_chunk_sectors = mddev->chunk_sectors;
3538 	mddev->delta_disks = mddev->raid_disks;
3539 	mddev->raid_disks *= 2;
3540 	/* make sure it will be not marked as dirty */
3541 	mddev->recovery_cp = MaxSector;
3542 
3543 	conf = setup_conf(mddev);
3544 	if (!IS_ERR(conf)) {
3545 		rdev_for_each(rdev, mddev)
3546 			if (rdev->raid_disk >= 0)
3547 				rdev->new_raid_disk = rdev->raid_disk * 2;
3548 		conf->barrier = 1;
3549 	}
3550 
3551 	return conf;
3552 }
3553 
raid10_takeover(struct mddev * mddev)3554 static void *raid10_takeover(struct mddev *mddev)
3555 {
3556 	struct r0conf *raid0_conf;
3557 
3558 	/* raid10 can take over:
3559 	 *  raid0 - providing it has only two drives
3560 	 */
3561 	if (mddev->level == 0) {
3562 		/* for raid0 takeover only one zone is supported */
3563 		raid0_conf = mddev->private;
3564 		if (raid0_conf->nr_strip_zones > 1) {
3565 			printk(KERN_ERR "md/raid10:%s: cannot takeover raid 0"
3566 			       " with more than one zone.\n",
3567 			       mdname(mddev));
3568 			return ERR_PTR(-EINVAL);
3569 		}
3570 		return raid10_takeover_raid0(mddev);
3571 	}
3572 	return ERR_PTR(-EINVAL);
3573 }
3574 
3575 static struct md_personality raid10_personality =
3576 {
3577 	.name		= "raid10",
3578 	.level		= 10,
3579 	.owner		= THIS_MODULE,
3580 	.make_request	= make_request,
3581 	.run		= run,
3582 	.stop		= stop,
3583 	.status		= status,
3584 	.error_handler	= error,
3585 	.hot_add_disk	= raid10_add_disk,
3586 	.hot_remove_disk= raid10_remove_disk,
3587 	.spare_active	= raid10_spare_active,
3588 	.sync_request	= sync_request,
3589 	.quiesce	= raid10_quiesce,
3590 	.size		= raid10_size,
3591 	.resize		= raid10_resize,
3592 	.takeover	= raid10_takeover,
3593 };
3594 
raid_init(void)3595 static int __init raid_init(void)
3596 {
3597 	return register_md_personality(&raid10_personality);
3598 }
3599 
raid_exit(void)3600 static void raid_exit(void)
3601 {
3602 	unregister_md_personality(&raid10_personality);
3603 }
3604 
3605 module_init(raid_init);
3606 module_exit(raid_exit);
3607 MODULE_LICENSE("GPL");
3608 MODULE_DESCRIPTION("RAID10 (striped mirror) personality for MD");
3609 MODULE_ALIAS("md-personality-9"); /* RAID10 */
3610 MODULE_ALIAS("md-raid10");
3611 MODULE_ALIAS("md-level-10");
3612 
3613 module_param(max_queued_requests, int, S_IRUGO|S_IWUSR);
3614