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