xref: /linux/drivers/md/raid10.c (revision 7265706c8fd57722f622f336ec110cb35f83e739)
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 futher 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 "dm-bio-list.h"
22 #include <linux/raid/raid10.h>
23 #include <linux/raid/bitmap.h>
24 
25 /*
26  * RAID10 provides a combination of RAID0 and RAID1 functionality.
27  * The layout of data is defined by
28  *    chunk_size
29  *    raid_disks
30  *    near_copies (stored in low byte of layout)
31  *    far_copies (stored in second byte of layout)
32  *    far_offset (stored in bit 16 of layout )
33  *
34  * The data to be stored is divided into chunks using chunksize.
35  * Each device is divided into far_copies sections.
36  * In each section, chunks are laid out in a style similar to raid0, but
37  * near_copies copies of each chunk is stored (each on a different drive).
38  * The starting device for each section is offset near_copies from the starting
39  * device of the previous section.
40  * Thus they are (near_copies*far_copies) of each chunk, and each is on a different
41  * drive.
42  * near_copies and far_copies must be at least one, and their product is at most
43  * raid_disks.
44  *
45  * If far_offset is true, then the far_copies are handled a bit differently.
46  * The copies are still in different stripes, but instead of be very far apart
47  * on disk, there are adjacent stripes.
48  */
49 
50 /*
51  * Number of guaranteed r10bios in case of extreme VM load:
52  */
53 #define	NR_RAID10_BIOS 256
54 
55 static void unplug_slaves(mddev_t *mddev);
56 
57 static void allow_barrier(conf_t *conf);
58 static void lower_barrier(conf_t *conf);
59 
60 static void * r10bio_pool_alloc(gfp_t gfp_flags, void *data)
61 {
62 	conf_t *conf = data;
63 	r10bio_t *r10_bio;
64 	int size = offsetof(struct r10bio_s, devs[conf->copies]);
65 
66 	/* allocate a r10bio with room for raid_disks entries in the bios array */
67 	r10_bio = kzalloc(size, gfp_flags);
68 	if (!r10_bio)
69 		unplug_slaves(conf->mddev);
70 
71 	return r10_bio;
72 }
73 
74 static void r10bio_pool_free(void *r10_bio, void *data)
75 {
76 	kfree(r10_bio);
77 }
78 
79 #define RESYNC_BLOCK_SIZE (64*1024)
80 //#define RESYNC_BLOCK_SIZE PAGE_SIZE
81 #define RESYNC_SECTORS (RESYNC_BLOCK_SIZE >> 9)
82 #define RESYNC_PAGES ((RESYNC_BLOCK_SIZE + PAGE_SIZE-1) / PAGE_SIZE)
83 #define RESYNC_WINDOW (2048*1024)
84 
85 /*
86  * When performing a resync, we need to read and compare, so
87  * we need as many pages are there are copies.
88  * When performing a recovery, we need 2 bios, one for read,
89  * one for write (we recover only one drive per r10buf)
90  *
91  */
92 static void * r10buf_pool_alloc(gfp_t gfp_flags, void *data)
93 {
94 	conf_t *conf = data;
95 	struct page *page;
96 	r10bio_t *r10_bio;
97 	struct bio *bio;
98 	int i, j;
99 	int nalloc;
100 
101 	r10_bio = r10bio_pool_alloc(gfp_flags, conf);
102 	if (!r10_bio) {
103 		unplug_slaves(conf->mddev);
104 		return NULL;
105 	}
106 
107 	if (test_bit(MD_RECOVERY_SYNC, &conf->mddev->recovery))
108 		nalloc = conf->copies; /* resync */
109 	else
110 		nalloc = 2; /* recovery */
111 
112 	/*
113 	 * Allocate bios.
114 	 */
115 	for (j = nalloc ; j-- ; ) {
116 		bio = bio_alloc(gfp_flags, RESYNC_PAGES);
117 		if (!bio)
118 			goto out_free_bio;
119 		r10_bio->devs[j].bio = bio;
120 	}
121 	/*
122 	 * Allocate RESYNC_PAGES data pages and attach them
123 	 * where needed.
124 	 */
125 	for (j = 0 ; j < nalloc; j++) {
126 		bio = r10_bio->devs[j].bio;
127 		for (i = 0; i < RESYNC_PAGES; i++) {
128 			page = alloc_page(gfp_flags);
129 			if (unlikely(!page))
130 				goto out_free_pages;
131 
132 			bio->bi_io_vec[i].bv_page = page;
133 		}
134 	}
135 
136 	return r10_bio;
137 
138 out_free_pages:
139 	for ( ; i > 0 ; i--)
140 		safe_put_page(bio->bi_io_vec[i-1].bv_page);
141 	while (j--)
142 		for (i = 0; i < RESYNC_PAGES ; i++)
143 			safe_put_page(r10_bio->devs[j].bio->bi_io_vec[i].bv_page);
144 	j = -1;
145 out_free_bio:
146 	while ( ++j < nalloc )
147 		bio_put(r10_bio->devs[j].bio);
148 	r10bio_pool_free(r10_bio, conf);
149 	return NULL;
150 }
151 
152 static void r10buf_pool_free(void *__r10_bio, void *data)
153 {
154 	int i;
155 	conf_t *conf = data;
156 	r10bio_t *r10bio = __r10_bio;
157 	int j;
158 
159 	for (j=0; j < conf->copies; j++) {
160 		struct bio *bio = r10bio->devs[j].bio;
161 		if (bio) {
162 			for (i = 0; i < RESYNC_PAGES; i++) {
163 				safe_put_page(bio->bi_io_vec[i].bv_page);
164 				bio->bi_io_vec[i].bv_page = NULL;
165 			}
166 			bio_put(bio);
167 		}
168 	}
169 	r10bio_pool_free(r10bio, conf);
170 }
171 
172 static void put_all_bios(conf_t *conf, r10bio_t *r10_bio)
173 {
174 	int i;
175 
176 	for (i = 0; i < conf->copies; i++) {
177 		struct bio **bio = & r10_bio->devs[i].bio;
178 		if (*bio && *bio != IO_BLOCKED)
179 			bio_put(*bio);
180 		*bio = NULL;
181 	}
182 }
183 
184 static void free_r10bio(r10bio_t *r10_bio)
185 {
186 	conf_t *conf = mddev_to_conf(r10_bio->mddev);
187 
188 	/*
189 	 * Wake up any possible resync thread that waits for the device
190 	 * to go idle.
191 	 */
192 	allow_barrier(conf);
193 
194 	put_all_bios(conf, r10_bio);
195 	mempool_free(r10_bio, conf->r10bio_pool);
196 }
197 
198 static void put_buf(r10bio_t *r10_bio)
199 {
200 	conf_t *conf = mddev_to_conf(r10_bio->mddev);
201 
202 	mempool_free(r10_bio, conf->r10buf_pool);
203 
204 	lower_barrier(conf);
205 }
206 
207 static void reschedule_retry(r10bio_t *r10_bio)
208 {
209 	unsigned long flags;
210 	mddev_t *mddev = r10_bio->mddev;
211 	conf_t *conf = mddev_to_conf(mddev);
212 
213 	spin_lock_irqsave(&conf->device_lock, flags);
214 	list_add(&r10_bio->retry_list, &conf->retry_list);
215 	conf->nr_queued ++;
216 	spin_unlock_irqrestore(&conf->device_lock, flags);
217 
218 	/* wake up frozen array... */
219 	wake_up(&conf->wait_barrier);
220 
221 	md_wakeup_thread(mddev->thread);
222 }
223 
224 /*
225  * raid_end_bio_io() is called when we have finished servicing a mirrored
226  * operation and are ready to return a success/failure code to the buffer
227  * cache layer.
228  */
229 static void raid_end_bio_io(r10bio_t *r10_bio)
230 {
231 	struct bio *bio = r10_bio->master_bio;
232 
233 	bio_endio(bio,
234 		test_bit(R10BIO_Uptodate, &r10_bio->state) ? 0 : -EIO);
235 	free_r10bio(r10_bio);
236 }
237 
238 /*
239  * Update disk head position estimator based on IRQ completion info.
240  */
241 static inline void update_head_pos(int slot, r10bio_t *r10_bio)
242 {
243 	conf_t *conf = mddev_to_conf(r10_bio->mddev);
244 
245 	conf->mirrors[r10_bio->devs[slot].devnum].head_position =
246 		r10_bio->devs[slot].addr + (r10_bio->sectors);
247 }
248 
249 static void raid10_end_read_request(struct bio *bio, int error)
250 {
251 	int uptodate = test_bit(BIO_UPTODATE, &bio->bi_flags);
252 	r10bio_t * r10_bio = (r10bio_t *)(bio->bi_private);
253 	int slot, dev;
254 	conf_t *conf = mddev_to_conf(r10_bio->mddev);
255 
256 
257 	slot = r10_bio->read_slot;
258 	dev = r10_bio->devs[slot].devnum;
259 	/*
260 	 * this branch is our 'one mirror IO has finished' event handler:
261 	 */
262 	update_head_pos(slot, r10_bio);
263 
264 	if (uptodate) {
265 		/*
266 		 * Set R10BIO_Uptodate in our master bio, so that
267 		 * we will return a good error code to the higher
268 		 * levels even if IO on some other mirrored buffer fails.
269 		 *
270 		 * The 'master' represents the composite IO operation to
271 		 * user-side. So if something waits for IO, then it will
272 		 * wait for the 'master' bio.
273 		 */
274 		set_bit(R10BIO_Uptodate, &r10_bio->state);
275 		raid_end_bio_io(r10_bio);
276 	} else {
277 		/*
278 		 * oops, read error:
279 		 */
280 		char b[BDEVNAME_SIZE];
281 		if (printk_ratelimit())
282 			printk(KERN_ERR "raid10: %s: rescheduling sector %llu\n",
283 			       bdevname(conf->mirrors[dev].rdev->bdev,b), (unsigned long long)r10_bio->sector);
284 		reschedule_retry(r10_bio);
285 	}
286 
287 	rdev_dec_pending(conf->mirrors[dev].rdev, conf->mddev);
288 }
289 
290 static void raid10_end_write_request(struct bio *bio, int error)
291 {
292 	int uptodate = test_bit(BIO_UPTODATE, &bio->bi_flags);
293 	r10bio_t * r10_bio = (r10bio_t *)(bio->bi_private);
294 	int slot, dev;
295 	conf_t *conf = mddev_to_conf(r10_bio->mddev);
296 
297 	for (slot = 0; slot < conf->copies; slot++)
298 		if (r10_bio->devs[slot].bio == bio)
299 			break;
300 	dev = r10_bio->devs[slot].devnum;
301 
302 	/*
303 	 * this branch is our 'one mirror IO has finished' event handler:
304 	 */
305 	if (!uptodate) {
306 		md_error(r10_bio->mddev, conf->mirrors[dev].rdev);
307 		/* an I/O failed, we can't clear the bitmap */
308 		set_bit(R10BIO_Degraded, &r10_bio->state);
309 	} else
310 		/*
311 		 * Set R10BIO_Uptodate in our master bio, so that
312 		 * we will return a good error code for to the higher
313 		 * levels even if IO on some other mirrored buffer fails.
314 		 *
315 		 * The 'master' represents the composite IO operation to
316 		 * user-side. So if something waits for IO, then it will
317 		 * wait for the 'master' bio.
318 		 */
319 		set_bit(R10BIO_Uptodate, &r10_bio->state);
320 
321 	update_head_pos(slot, r10_bio);
322 
323 	/*
324 	 *
325 	 * Let's see if all mirrored write operations have finished
326 	 * already.
327 	 */
328 	if (atomic_dec_and_test(&r10_bio->remaining)) {
329 		/* clear the bitmap if all writes complete successfully */
330 		bitmap_endwrite(r10_bio->mddev->bitmap, r10_bio->sector,
331 				r10_bio->sectors,
332 				!test_bit(R10BIO_Degraded, &r10_bio->state),
333 				0);
334 		md_write_end(r10_bio->mddev);
335 		raid_end_bio_io(r10_bio);
336 	}
337 
338 	rdev_dec_pending(conf->mirrors[dev].rdev, conf->mddev);
339 }
340 
341 
342 /*
343  * RAID10 layout manager
344  * Aswell as the chunksize and raid_disks count, there are two
345  * parameters: near_copies and far_copies.
346  * near_copies * far_copies must be <= raid_disks.
347  * Normally one of these will be 1.
348  * If both are 1, we get raid0.
349  * If near_copies == raid_disks, we get raid1.
350  *
351  * Chunks are layed out in raid0 style with near_copies copies of the
352  * first chunk, followed by near_copies copies of the next chunk and
353  * so on.
354  * If far_copies > 1, then after 1/far_copies of the array has been assigned
355  * as described above, we start again with a device offset of near_copies.
356  * So we effectively have another copy of the whole array further down all
357  * the drives, but with blocks on different drives.
358  * With this layout, and block is never stored twice on the one device.
359  *
360  * raid10_find_phys finds the sector offset of a given virtual sector
361  * on each device that it is on.
362  *
363  * raid10_find_virt does the reverse mapping, from a device and a
364  * sector offset to a virtual address
365  */
366 
367 static void raid10_find_phys(conf_t *conf, r10bio_t *r10bio)
368 {
369 	int n,f;
370 	sector_t sector;
371 	sector_t chunk;
372 	sector_t stripe;
373 	int dev;
374 
375 	int slot = 0;
376 
377 	/* now calculate first sector/dev */
378 	chunk = r10bio->sector >> conf->chunk_shift;
379 	sector = r10bio->sector & conf->chunk_mask;
380 
381 	chunk *= conf->near_copies;
382 	stripe = chunk;
383 	dev = sector_div(stripe, conf->raid_disks);
384 	if (conf->far_offset)
385 		stripe *= conf->far_copies;
386 
387 	sector += stripe << conf->chunk_shift;
388 
389 	/* and calculate all the others */
390 	for (n=0; n < conf->near_copies; n++) {
391 		int d = dev;
392 		sector_t s = sector;
393 		r10bio->devs[slot].addr = sector;
394 		r10bio->devs[slot].devnum = d;
395 		slot++;
396 
397 		for (f = 1; f < conf->far_copies; f++) {
398 			d += conf->near_copies;
399 			if (d >= conf->raid_disks)
400 				d -= conf->raid_disks;
401 			s += conf->stride;
402 			r10bio->devs[slot].devnum = d;
403 			r10bio->devs[slot].addr = s;
404 			slot++;
405 		}
406 		dev++;
407 		if (dev >= conf->raid_disks) {
408 			dev = 0;
409 			sector += (conf->chunk_mask + 1);
410 		}
411 	}
412 	BUG_ON(slot != conf->copies);
413 }
414 
415 static sector_t raid10_find_virt(conf_t *conf, sector_t sector, int dev)
416 {
417 	sector_t offset, chunk, vchunk;
418 
419 	offset = sector & conf->chunk_mask;
420 	if (conf->far_offset) {
421 		int fc;
422 		chunk = sector >> conf->chunk_shift;
423 		fc = sector_div(chunk, conf->far_copies);
424 		dev -= fc * conf->near_copies;
425 		if (dev < 0)
426 			dev += conf->raid_disks;
427 	} else {
428 		while (sector >= conf->stride) {
429 			sector -= conf->stride;
430 			if (dev < conf->near_copies)
431 				dev += conf->raid_disks - conf->near_copies;
432 			else
433 				dev -= conf->near_copies;
434 		}
435 		chunk = sector >> conf->chunk_shift;
436 	}
437 	vchunk = chunk * conf->raid_disks + dev;
438 	sector_div(vchunk, conf->near_copies);
439 	return (vchunk << conf->chunk_shift) + offset;
440 }
441 
442 /**
443  *	raid10_mergeable_bvec -- tell bio layer if a two requests can be merged
444  *	@q: request queue
445  *	@bvm: properties of new bio
446  *	@biovec: the request that could be merged to it.
447  *
448  *	Return amount of bytes we can accept at this offset
449  *      If near_copies == raid_disk, there are no striping issues,
450  *      but in that case, the function isn't called at all.
451  */
452 static int raid10_mergeable_bvec(struct request_queue *q,
453 				 struct bvec_merge_data *bvm,
454 				 struct bio_vec *biovec)
455 {
456 	mddev_t *mddev = q->queuedata;
457 	sector_t sector = bvm->bi_sector + get_start_sect(bvm->bi_bdev);
458 	int max;
459 	unsigned int chunk_sectors = mddev->chunk_size >> 9;
460 	unsigned int bio_sectors = bvm->bi_size >> 9;
461 
462 	max =  (chunk_sectors - ((sector & (chunk_sectors - 1)) + bio_sectors)) << 9;
463 	if (max < 0) max = 0; /* bio_add cannot handle a negative return */
464 	if (max <= biovec->bv_len && bio_sectors == 0)
465 		return biovec->bv_len;
466 	else
467 		return max;
468 }
469 
470 /*
471  * This routine returns the disk from which the requested read should
472  * be done. There is a per-array 'next expected sequential IO' sector
473  * number - if this matches on the next IO then we use the last disk.
474  * There is also a per-disk 'last know head position' sector that is
475  * maintained from IRQ contexts, both the normal and the resync IO
476  * completion handlers update this position correctly. If there is no
477  * perfect sequential match then we pick the disk whose head is closest.
478  *
479  * If there are 2 mirrors in the same 2 devices, performance degrades
480  * because position is mirror, not device based.
481  *
482  * The rdev for the device selected will have nr_pending incremented.
483  */
484 
485 /*
486  * FIXME: possibly should rethink readbalancing and do it differently
487  * depending on near_copies / far_copies geometry.
488  */
489 static int read_balance(conf_t *conf, r10bio_t *r10_bio)
490 {
491 	const unsigned long this_sector = r10_bio->sector;
492 	int disk, slot, nslot;
493 	const int sectors = r10_bio->sectors;
494 	sector_t new_distance, current_distance;
495 	mdk_rdev_t *rdev;
496 
497 	raid10_find_phys(conf, r10_bio);
498 	rcu_read_lock();
499 	/*
500 	 * Check if we can balance. We can balance on the whole
501 	 * device if no resync is going on (recovery is ok), or below
502 	 * the resync window. We take the first readable disk when
503 	 * above the resync window.
504 	 */
505 	if (conf->mddev->recovery_cp < MaxSector
506 	    && (this_sector + sectors >= conf->next_resync)) {
507 		/* make sure that disk is operational */
508 		slot = 0;
509 		disk = r10_bio->devs[slot].devnum;
510 
511 		while ((rdev = rcu_dereference(conf->mirrors[disk].rdev)) == NULL ||
512 		       r10_bio->devs[slot].bio == IO_BLOCKED ||
513 		       !test_bit(In_sync, &rdev->flags)) {
514 			slot++;
515 			if (slot == conf->copies) {
516 				slot = 0;
517 				disk = -1;
518 				break;
519 			}
520 			disk = r10_bio->devs[slot].devnum;
521 		}
522 		goto rb_out;
523 	}
524 
525 
526 	/* make sure the disk is operational */
527 	slot = 0;
528 	disk = r10_bio->devs[slot].devnum;
529 	while ((rdev=rcu_dereference(conf->mirrors[disk].rdev)) == NULL ||
530 	       r10_bio->devs[slot].bio == IO_BLOCKED ||
531 	       !test_bit(In_sync, &rdev->flags)) {
532 		slot ++;
533 		if (slot == conf->copies) {
534 			disk = -1;
535 			goto rb_out;
536 		}
537 		disk = r10_bio->devs[slot].devnum;
538 	}
539 
540 
541 	current_distance = abs(r10_bio->devs[slot].addr -
542 			       conf->mirrors[disk].head_position);
543 
544 	/* Find the disk whose head is closest,
545 	 * or - for far > 1 - find the closest to partition beginning */
546 
547 	for (nslot = slot; nslot < conf->copies; nslot++) {
548 		int ndisk = r10_bio->devs[nslot].devnum;
549 
550 
551 		if ((rdev=rcu_dereference(conf->mirrors[ndisk].rdev)) == NULL ||
552 		    r10_bio->devs[nslot].bio == IO_BLOCKED ||
553 		    !test_bit(In_sync, &rdev->flags))
554 			continue;
555 
556 		/* This optimisation is debatable, and completely destroys
557 		 * sequential read speed for 'far copies' arrays.  So only
558 		 * keep it for 'near' arrays, and review those later.
559 		 */
560 		if (conf->near_copies > 1 && !atomic_read(&rdev->nr_pending)) {
561 			disk = ndisk;
562 			slot = nslot;
563 			break;
564 		}
565 
566 		/* for far > 1 always use the lowest address */
567 		if (conf->far_copies > 1)
568 			new_distance = r10_bio->devs[nslot].addr;
569 		else
570 			new_distance = abs(r10_bio->devs[nslot].addr -
571 					   conf->mirrors[ndisk].head_position);
572 		if (new_distance < current_distance) {
573 			current_distance = new_distance;
574 			disk = ndisk;
575 			slot = nslot;
576 		}
577 	}
578 
579 rb_out:
580 	r10_bio->read_slot = slot;
581 /*	conf->next_seq_sect = this_sector + sectors;*/
582 
583 	if (disk >= 0 && (rdev=rcu_dereference(conf->mirrors[disk].rdev))!= NULL)
584 		atomic_inc(&conf->mirrors[disk].rdev->nr_pending);
585 	else
586 		disk = -1;
587 	rcu_read_unlock();
588 
589 	return disk;
590 }
591 
592 static void unplug_slaves(mddev_t *mddev)
593 {
594 	conf_t *conf = mddev_to_conf(mddev);
595 	int i;
596 
597 	rcu_read_lock();
598 	for (i=0; i<mddev->raid_disks; i++) {
599 		mdk_rdev_t *rdev = rcu_dereference(conf->mirrors[i].rdev);
600 		if (rdev && !test_bit(Faulty, &rdev->flags) && atomic_read(&rdev->nr_pending)) {
601 			struct request_queue *r_queue = bdev_get_queue(rdev->bdev);
602 
603 			atomic_inc(&rdev->nr_pending);
604 			rcu_read_unlock();
605 
606 			blk_unplug(r_queue);
607 
608 			rdev_dec_pending(rdev, mddev);
609 			rcu_read_lock();
610 		}
611 	}
612 	rcu_read_unlock();
613 }
614 
615 static void raid10_unplug(struct request_queue *q)
616 {
617 	mddev_t *mddev = q->queuedata;
618 
619 	unplug_slaves(q->queuedata);
620 	md_wakeup_thread(mddev->thread);
621 }
622 
623 static int raid10_congested(void *data, int bits)
624 {
625 	mddev_t *mddev = data;
626 	conf_t *conf = mddev_to_conf(mddev);
627 	int i, ret = 0;
628 
629 	rcu_read_lock();
630 	for (i = 0; i < mddev->raid_disks && ret == 0; i++) {
631 		mdk_rdev_t *rdev = rcu_dereference(conf->mirrors[i].rdev);
632 		if (rdev && !test_bit(Faulty, &rdev->flags)) {
633 			struct request_queue *q = bdev_get_queue(rdev->bdev);
634 
635 			ret |= bdi_congested(&q->backing_dev_info, bits);
636 		}
637 	}
638 	rcu_read_unlock();
639 	return ret;
640 }
641 
642 static int flush_pending_writes(conf_t *conf)
643 {
644 	/* Any writes that have been queued but are awaiting
645 	 * bitmap updates get flushed here.
646 	 * We return 1 if any requests were actually submitted.
647 	 */
648 	int rv = 0;
649 
650 	spin_lock_irq(&conf->device_lock);
651 
652 	if (conf->pending_bio_list.head) {
653 		struct bio *bio;
654 		bio = bio_list_get(&conf->pending_bio_list);
655 		blk_remove_plug(conf->mddev->queue);
656 		spin_unlock_irq(&conf->device_lock);
657 		/* flush any pending bitmap writes to disk
658 		 * before proceeding w/ I/O */
659 		bitmap_unplug(conf->mddev->bitmap);
660 
661 		while (bio) { /* submit pending writes */
662 			struct bio *next = bio->bi_next;
663 			bio->bi_next = NULL;
664 			generic_make_request(bio);
665 			bio = next;
666 		}
667 		rv = 1;
668 	} else
669 		spin_unlock_irq(&conf->device_lock);
670 	return rv;
671 }
672 /* Barriers....
673  * Sometimes we need to suspend IO while we do something else,
674  * either some resync/recovery, or reconfigure the array.
675  * To do this we raise a 'barrier'.
676  * The 'barrier' is a counter that can be raised multiple times
677  * to count how many activities are happening which preclude
678  * normal IO.
679  * We can only raise the barrier if there is no pending IO.
680  * i.e. if nr_pending == 0.
681  * We choose only to raise the barrier if no-one is waiting for the
682  * barrier to go down.  This means that as soon as an IO request
683  * is ready, no other operations which require a barrier will start
684  * until the IO request has had a chance.
685  *
686  * So: regular IO calls 'wait_barrier'.  When that returns there
687  *    is no backgroup IO happening,  It must arrange to call
688  *    allow_barrier when it has finished its IO.
689  * backgroup IO calls must call raise_barrier.  Once that returns
690  *    there is no normal IO happeing.  It must arrange to call
691  *    lower_barrier when the particular background IO completes.
692  */
693 #define RESYNC_DEPTH 32
694 
695 static void raise_barrier(conf_t *conf, int force)
696 {
697 	BUG_ON(force && !conf->barrier);
698 	spin_lock_irq(&conf->resync_lock);
699 
700 	/* Wait until no block IO is waiting (unless 'force') */
701 	wait_event_lock_irq(conf->wait_barrier, force || !conf->nr_waiting,
702 			    conf->resync_lock,
703 			    raid10_unplug(conf->mddev->queue));
704 
705 	/* block any new IO from starting */
706 	conf->barrier++;
707 
708 	/* No wait for all pending IO to complete */
709 	wait_event_lock_irq(conf->wait_barrier,
710 			    !conf->nr_pending && conf->barrier < RESYNC_DEPTH,
711 			    conf->resync_lock,
712 			    raid10_unplug(conf->mddev->queue));
713 
714 	spin_unlock_irq(&conf->resync_lock);
715 }
716 
717 static void lower_barrier(conf_t *conf)
718 {
719 	unsigned long flags;
720 	spin_lock_irqsave(&conf->resync_lock, flags);
721 	conf->barrier--;
722 	spin_unlock_irqrestore(&conf->resync_lock, flags);
723 	wake_up(&conf->wait_barrier);
724 }
725 
726 static void wait_barrier(conf_t *conf)
727 {
728 	spin_lock_irq(&conf->resync_lock);
729 	if (conf->barrier) {
730 		conf->nr_waiting++;
731 		wait_event_lock_irq(conf->wait_barrier, !conf->barrier,
732 				    conf->resync_lock,
733 				    raid10_unplug(conf->mddev->queue));
734 		conf->nr_waiting--;
735 	}
736 	conf->nr_pending++;
737 	spin_unlock_irq(&conf->resync_lock);
738 }
739 
740 static void allow_barrier(conf_t *conf)
741 {
742 	unsigned long flags;
743 	spin_lock_irqsave(&conf->resync_lock, flags);
744 	conf->nr_pending--;
745 	spin_unlock_irqrestore(&conf->resync_lock, flags);
746 	wake_up(&conf->wait_barrier);
747 }
748 
749 static void freeze_array(conf_t *conf)
750 {
751 	/* stop syncio and normal IO and wait for everything to
752 	 * go quiet.
753 	 * We increment barrier and nr_waiting, and then
754 	 * wait until nr_pending match nr_queued+1
755 	 * This is called in the context of one normal IO request
756 	 * that has failed. Thus any sync request that might be pending
757 	 * will be blocked by nr_pending, and we need to wait for
758 	 * pending IO requests to complete or be queued for re-try.
759 	 * Thus the number queued (nr_queued) plus this request (1)
760 	 * must match the number of pending IOs (nr_pending) before
761 	 * we continue.
762 	 */
763 	spin_lock_irq(&conf->resync_lock);
764 	conf->barrier++;
765 	conf->nr_waiting++;
766 	wait_event_lock_irq(conf->wait_barrier,
767 			    conf->nr_pending == conf->nr_queued+1,
768 			    conf->resync_lock,
769 			    ({ flush_pending_writes(conf);
770 			       raid10_unplug(conf->mddev->queue); }));
771 	spin_unlock_irq(&conf->resync_lock);
772 }
773 
774 static void unfreeze_array(conf_t *conf)
775 {
776 	/* reverse the effect of the freeze */
777 	spin_lock_irq(&conf->resync_lock);
778 	conf->barrier--;
779 	conf->nr_waiting--;
780 	wake_up(&conf->wait_barrier);
781 	spin_unlock_irq(&conf->resync_lock);
782 }
783 
784 static int make_request(struct request_queue *q, struct bio * bio)
785 {
786 	mddev_t *mddev = q->queuedata;
787 	conf_t *conf = mddev_to_conf(mddev);
788 	mirror_info_t *mirror;
789 	r10bio_t *r10_bio;
790 	struct bio *read_bio;
791 	int i;
792 	int chunk_sects = conf->chunk_mask + 1;
793 	const int rw = bio_data_dir(bio);
794 	const int do_sync = bio_sync(bio);
795 	struct bio_list bl;
796 	unsigned long flags;
797 	mdk_rdev_t *blocked_rdev;
798 
799 	if (unlikely(bio_barrier(bio))) {
800 		bio_endio(bio, -EOPNOTSUPP);
801 		return 0;
802 	}
803 
804 	/* If this request crosses a chunk boundary, we need to
805 	 * split it.  This will only happen for 1 PAGE (or less) requests.
806 	 */
807 	if (unlikely( (bio->bi_sector & conf->chunk_mask) + (bio->bi_size >> 9)
808 		      > chunk_sects &&
809 		    conf->near_copies < conf->raid_disks)) {
810 		struct bio_pair *bp;
811 		/* Sanity check -- queue functions should prevent this happening */
812 		if (bio->bi_vcnt != 1 ||
813 		    bio->bi_idx != 0)
814 			goto bad_map;
815 		/* This is a one page bio that upper layers
816 		 * refuse to split for us, so we need to split it.
817 		 */
818 		bp = bio_split(bio, bio_split_pool,
819 			       chunk_sects - (bio->bi_sector & (chunk_sects - 1)) );
820 		if (make_request(q, &bp->bio1))
821 			generic_make_request(&bp->bio1);
822 		if (make_request(q, &bp->bio2))
823 			generic_make_request(&bp->bio2);
824 
825 		bio_pair_release(bp);
826 		return 0;
827 	bad_map:
828 		printk("raid10_make_request bug: can't convert block across chunks"
829 		       " or bigger than %dk %llu %d\n", chunk_sects/2,
830 		       (unsigned long long)bio->bi_sector, bio->bi_size >> 10);
831 
832 		bio_io_error(bio);
833 		return 0;
834 	}
835 
836 	md_write_start(mddev, bio);
837 
838 	/*
839 	 * Register the new request and wait if the reconstruction
840 	 * thread has put up a bar for new requests.
841 	 * Continue immediately if no resync is active currently.
842 	 */
843 	wait_barrier(conf);
844 
845 	disk_stat_inc(mddev->gendisk, ios[rw]);
846 	disk_stat_add(mddev->gendisk, sectors[rw], bio_sectors(bio));
847 
848 	r10_bio = mempool_alloc(conf->r10bio_pool, GFP_NOIO);
849 
850 	r10_bio->master_bio = bio;
851 	r10_bio->sectors = bio->bi_size >> 9;
852 
853 	r10_bio->mddev = mddev;
854 	r10_bio->sector = bio->bi_sector;
855 	r10_bio->state = 0;
856 
857 	if (rw == READ) {
858 		/*
859 		 * read balancing logic:
860 		 */
861 		int disk = read_balance(conf, r10_bio);
862 		int slot = r10_bio->read_slot;
863 		if (disk < 0) {
864 			raid_end_bio_io(r10_bio);
865 			return 0;
866 		}
867 		mirror = conf->mirrors + disk;
868 
869 		read_bio = bio_clone(bio, GFP_NOIO);
870 
871 		r10_bio->devs[slot].bio = read_bio;
872 
873 		read_bio->bi_sector = r10_bio->devs[slot].addr +
874 			mirror->rdev->data_offset;
875 		read_bio->bi_bdev = mirror->rdev->bdev;
876 		read_bio->bi_end_io = raid10_end_read_request;
877 		read_bio->bi_rw = READ | do_sync;
878 		read_bio->bi_private = r10_bio;
879 
880 		generic_make_request(read_bio);
881 		return 0;
882 	}
883 
884 	/*
885 	 * WRITE:
886 	 */
887 	/* first select target devices under rcu_lock and
888 	 * inc refcount on their rdev.  Record them by setting
889 	 * bios[x] to bio
890 	 */
891 	raid10_find_phys(conf, r10_bio);
892  retry_write:
893 	blocked_rdev = NULL;
894 	rcu_read_lock();
895 	for (i = 0;  i < conf->copies; i++) {
896 		int d = r10_bio->devs[i].devnum;
897 		mdk_rdev_t *rdev = rcu_dereference(conf->mirrors[d].rdev);
898 		if (rdev && unlikely(test_bit(Blocked, &rdev->flags))) {
899 			atomic_inc(&rdev->nr_pending);
900 			blocked_rdev = rdev;
901 			break;
902 		}
903 		if (rdev && !test_bit(Faulty, &rdev->flags)) {
904 			atomic_inc(&rdev->nr_pending);
905 			r10_bio->devs[i].bio = bio;
906 		} else {
907 			r10_bio->devs[i].bio = NULL;
908 			set_bit(R10BIO_Degraded, &r10_bio->state);
909 		}
910 	}
911 	rcu_read_unlock();
912 
913 	if (unlikely(blocked_rdev)) {
914 		/* Have to wait for this device to get unblocked, then retry */
915 		int j;
916 		int d;
917 
918 		for (j = 0; j < i; j++)
919 			if (r10_bio->devs[j].bio) {
920 				d = r10_bio->devs[j].devnum;
921 				rdev_dec_pending(conf->mirrors[d].rdev, mddev);
922 			}
923 		allow_barrier(conf);
924 		md_wait_for_blocked_rdev(blocked_rdev, mddev);
925 		wait_barrier(conf);
926 		goto retry_write;
927 	}
928 
929 	atomic_set(&r10_bio->remaining, 0);
930 
931 	bio_list_init(&bl);
932 	for (i = 0; i < conf->copies; i++) {
933 		struct bio *mbio;
934 		int d = r10_bio->devs[i].devnum;
935 		if (!r10_bio->devs[i].bio)
936 			continue;
937 
938 		mbio = bio_clone(bio, GFP_NOIO);
939 		r10_bio->devs[i].bio = mbio;
940 
941 		mbio->bi_sector	= r10_bio->devs[i].addr+
942 			conf->mirrors[d].rdev->data_offset;
943 		mbio->bi_bdev = conf->mirrors[d].rdev->bdev;
944 		mbio->bi_end_io	= raid10_end_write_request;
945 		mbio->bi_rw = WRITE | do_sync;
946 		mbio->bi_private = r10_bio;
947 
948 		atomic_inc(&r10_bio->remaining);
949 		bio_list_add(&bl, mbio);
950 	}
951 
952 	if (unlikely(!atomic_read(&r10_bio->remaining))) {
953 		/* the array is dead */
954 		md_write_end(mddev);
955 		raid_end_bio_io(r10_bio);
956 		return 0;
957 	}
958 
959 	bitmap_startwrite(mddev->bitmap, bio->bi_sector, r10_bio->sectors, 0);
960 	spin_lock_irqsave(&conf->device_lock, flags);
961 	bio_list_merge(&conf->pending_bio_list, &bl);
962 	blk_plug_device(mddev->queue);
963 	spin_unlock_irqrestore(&conf->device_lock, flags);
964 
965 	/* In case raid10d snuck in to freeze_array */
966 	wake_up(&conf->wait_barrier);
967 
968 	if (do_sync)
969 		md_wakeup_thread(mddev->thread);
970 
971 	return 0;
972 }
973 
974 static void status(struct seq_file *seq, mddev_t *mddev)
975 {
976 	conf_t *conf = mddev_to_conf(mddev);
977 	int i;
978 
979 	if (conf->near_copies < conf->raid_disks)
980 		seq_printf(seq, " %dK chunks", mddev->chunk_size/1024);
981 	if (conf->near_copies > 1)
982 		seq_printf(seq, " %d near-copies", conf->near_copies);
983 	if (conf->far_copies > 1) {
984 		if (conf->far_offset)
985 			seq_printf(seq, " %d offset-copies", conf->far_copies);
986 		else
987 			seq_printf(seq, " %d far-copies", conf->far_copies);
988 	}
989 	seq_printf(seq, " [%d/%d] [", conf->raid_disks,
990 					conf->raid_disks - mddev->degraded);
991 	for (i = 0; i < conf->raid_disks; i++)
992 		seq_printf(seq, "%s",
993 			      conf->mirrors[i].rdev &&
994 			      test_bit(In_sync, &conf->mirrors[i].rdev->flags) ? "U" : "_");
995 	seq_printf(seq, "]");
996 }
997 
998 static void error(mddev_t *mddev, mdk_rdev_t *rdev)
999 {
1000 	char b[BDEVNAME_SIZE];
1001 	conf_t *conf = mddev_to_conf(mddev);
1002 
1003 	/*
1004 	 * If it is not operational, then we have already marked it as dead
1005 	 * else if it is the last working disks, ignore the error, let the
1006 	 * next level up know.
1007 	 * else mark the drive as failed
1008 	 */
1009 	if (test_bit(In_sync, &rdev->flags)
1010 	    && conf->raid_disks-mddev->degraded == 1)
1011 		/*
1012 		 * Don't fail the drive, just return an IO error.
1013 		 * The test should really be more sophisticated than
1014 		 * "working_disks == 1", but it isn't critical, and
1015 		 * can wait until we do more sophisticated "is the drive
1016 		 * really dead" tests...
1017 		 */
1018 		return;
1019 	if (test_and_clear_bit(In_sync, &rdev->flags)) {
1020 		unsigned long flags;
1021 		spin_lock_irqsave(&conf->device_lock, flags);
1022 		mddev->degraded++;
1023 		spin_unlock_irqrestore(&conf->device_lock, flags);
1024 		/*
1025 		 * if recovery is running, make sure it aborts.
1026 		 */
1027 		set_bit(MD_RECOVERY_INTR, &mddev->recovery);
1028 	}
1029 	set_bit(Faulty, &rdev->flags);
1030 	set_bit(MD_CHANGE_DEVS, &mddev->flags);
1031 	printk(KERN_ALERT "raid10: Disk failure on %s, disabling device.\n"
1032 		"raid10: Operation continuing on %d devices.\n",
1033 		bdevname(rdev->bdev,b), conf->raid_disks - mddev->degraded);
1034 }
1035 
1036 static void print_conf(conf_t *conf)
1037 {
1038 	int i;
1039 	mirror_info_t *tmp;
1040 
1041 	printk("RAID10 conf printout:\n");
1042 	if (!conf) {
1043 		printk("(!conf)\n");
1044 		return;
1045 	}
1046 	printk(" --- wd:%d rd:%d\n", conf->raid_disks - conf->mddev->degraded,
1047 		conf->raid_disks);
1048 
1049 	for (i = 0; i < conf->raid_disks; i++) {
1050 		char b[BDEVNAME_SIZE];
1051 		tmp = conf->mirrors + i;
1052 		if (tmp->rdev)
1053 			printk(" disk %d, wo:%d, o:%d, dev:%s\n",
1054 				i, !test_bit(In_sync, &tmp->rdev->flags),
1055 			        !test_bit(Faulty, &tmp->rdev->flags),
1056 				bdevname(tmp->rdev->bdev,b));
1057 	}
1058 }
1059 
1060 static void close_sync(conf_t *conf)
1061 {
1062 	wait_barrier(conf);
1063 	allow_barrier(conf);
1064 
1065 	mempool_destroy(conf->r10buf_pool);
1066 	conf->r10buf_pool = NULL;
1067 }
1068 
1069 /* check if there are enough drives for
1070  * every block to appear on atleast one
1071  */
1072 static int enough(conf_t *conf)
1073 {
1074 	int first = 0;
1075 
1076 	do {
1077 		int n = conf->copies;
1078 		int cnt = 0;
1079 		while (n--) {
1080 			if (conf->mirrors[first].rdev)
1081 				cnt++;
1082 			first = (first+1) % conf->raid_disks;
1083 		}
1084 		if (cnt == 0)
1085 			return 0;
1086 	} while (first != 0);
1087 	return 1;
1088 }
1089 
1090 static int raid10_spare_active(mddev_t *mddev)
1091 {
1092 	int i;
1093 	conf_t *conf = mddev->private;
1094 	mirror_info_t *tmp;
1095 
1096 	/*
1097 	 * Find all non-in_sync disks within the RAID10 configuration
1098 	 * and mark them in_sync
1099 	 */
1100 	for (i = 0; i < conf->raid_disks; i++) {
1101 		tmp = conf->mirrors + i;
1102 		if (tmp->rdev
1103 		    && !test_bit(Faulty, &tmp->rdev->flags)
1104 		    && !test_and_set_bit(In_sync, &tmp->rdev->flags)) {
1105 			unsigned long flags;
1106 			spin_lock_irqsave(&conf->device_lock, flags);
1107 			mddev->degraded--;
1108 			spin_unlock_irqrestore(&conf->device_lock, flags);
1109 		}
1110 	}
1111 
1112 	print_conf(conf);
1113 	return 0;
1114 }
1115 
1116 
1117 static int raid10_add_disk(mddev_t *mddev, mdk_rdev_t *rdev)
1118 {
1119 	conf_t *conf = mddev->private;
1120 	int err = -EEXIST;
1121 	int mirror;
1122 	mirror_info_t *p;
1123 	int first = 0;
1124 	int last = mddev->raid_disks - 1;
1125 
1126 	if (mddev->recovery_cp < MaxSector)
1127 		/* only hot-add to in-sync arrays, as recovery is
1128 		 * very different from resync
1129 		 */
1130 		return -EBUSY;
1131 	if (!enough(conf))
1132 		return -EINVAL;
1133 
1134 	if (rdev->raid_disk)
1135 		first = last = rdev->raid_disk;
1136 
1137 	if (rdev->saved_raid_disk >= 0 &&
1138 	    rdev->saved_raid_disk >= first &&
1139 	    conf->mirrors[rdev->saved_raid_disk].rdev == NULL)
1140 		mirror = rdev->saved_raid_disk;
1141 	else
1142 		mirror = first;
1143 	for ( ; mirror <= last ; mirror++)
1144 		if ( !(p=conf->mirrors+mirror)->rdev) {
1145 
1146 			blk_queue_stack_limits(mddev->queue,
1147 					       rdev->bdev->bd_disk->queue);
1148 			/* as we don't honour merge_bvec_fn, we must never risk
1149 			 * violating it, so limit ->max_sector to one PAGE, as
1150 			 * a one page request is never in violation.
1151 			 */
1152 			if (rdev->bdev->bd_disk->queue->merge_bvec_fn &&
1153 			    mddev->queue->max_sectors > (PAGE_SIZE>>9))
1154 				mddev->queue->max_sectors = (PAGE_SIZE>>9);
1155 
1156 			p->head_position = 0;
1157 			rdev->raid_disk = mirror;
1158 			err = 0;
1159 			if (rdev->saved_raid_disk != mirror)
1160 				conf->fullsync = 1;
1161 			rcu_assign_pointer(p->rdev, rdev);
1162 			break;
1163 		}
1164 
1165 	print_conf(conf);
1166 	return err;
1167 }
1168 
1169 static int raid10_remove_disk(mddev_t *mddev, int number)
1170 {
1171 	conf_t *conf = mddev->private;
1172 	int err = 0;
1173 	mdk_rdev_t *rdev;
1174 	mirror_info_t *p = conf->mirrors+ number;
1175 
1176 	print_conf(conf);
1177 	rdev = p->rdev;
1178 	if (rdev) {
1179 		if (test_bit(In_sync, &rdev->flags) ||
1180 		    atomic_read(&rdev->nr_pending)) {
1181 			err = -EBUSY;
1182 			goto abort;
1183 		}
1184 		/* Only remove faulty devices in recovery
1185 		 * is not possible.
1186 		 */
1187 		if (!test_bit(Faulty, &rdev->flags) &&
1188 		    enough(conf)) {
1189 			err = -EBUSY;
1190 			goto abort;
1191 		}
1192 		p->rdev = NULL;
1193 		synchronize_rcu();
1194 		if (atomic_read(&rdev->nr_pending)) {
1195 			/* lost the race, try later */
1196 			err = -EBUSY;
1197 			p->rdev = rdev;
1198 		}
1199 	}
1200 abort:
1201 
1202 	print_conf(conf);
1203 	return err;
1204 }
1205 
1206 
1207 static void end_sync_read(struct bio *bio, int error)
1208 {
1209 	r10bio_t * r10_bio = (r10bio_t *)(bio->bi_private);
1210 	conf_t *conf = mddev_to_conf(r10_bio->mddev);
1211 	int i,d;
1212 
1213 	for (i=0; i<conf->copies; i++)
1214 		if (r10_bio->devs[i].bio == bio)
1215 			break;
1216 	BUG_ON(i == conf->copies);
1217 	update_head_pos(i, r10_bio);
1218 	d = r10_bio->devs[i].devnum;
1219 
1220 	if (test_bit(BIO_UPTODATE, &bio->bi_flags))
1221 		set_bit(R10BIO_Uptodate, &r10_bio->state);
1222 	else {
1223 		atomic_add(r10_bio->sectors,
1224 			   &conf->mirrors[d].rdev->corrected_errors);
1225 		if (!test_bit(MD_RECOVERY_SYNC, &conf->mddev->recovery))
1226 			md_error(r10_bio->mddev,
1227 				 conf->mirrors[d].rdev);
1228 	}
1229 
1230 	/* for reconstruct, we always reschedule after a read.
1231 	 * for resync, only after all reads
1232 	 */
1233 	if (test_bit(R10BIO_IsRecover, &r10_bio->state) ||
1234 	    atomic_dec_and_test(&r10_bio->remaining)) {
1235 		/* we have read all the blocks,
1236 		 * do the comparison in process context in raid10d
1237 		 */
1238 		reschedule_retry(r10_bio);
1239 	}
1240 	rdev_dec_pending(conf->mirrors[d].rdev, conf->mddev);
1241 }
1242 
1243 static void end_sync_write(struct bio *bio, int error)
1244 {
1245 	int uptodate = test_bit(BIO_UPTODATE, &bio->bi_flags);
1246 	r10bio_t * r10_bio = (r10bio_t *)(bio->bi_private);
1247 	mddev_t *mddev = r10_bio->mddev;
1248 	conf_t *conf = mddev_to_conf(mddev);
1249 	int i,d;
1250 
1251 	for (i = 0; i < conf->copies; i++)
1252 		if (r10_bio->devs[i].bio == bio)
1253 			break;
1254 	d = r10_bio->devs[i].devnum;
1255 
1256 	if (!uptodate)
1257 		md_error(mddev, conf->mirrors[d].rdev);
1258 
1259 	update_head_pos(i, r10_bio);
1260 
1261 	while (atomic_dec_and_test(&r10_bio->remaining)) {
1262 		if (r10_bio->master_bio == NULL) {
1263 			/* the primary of several recovery bios */
1264 			md_done_sync(mddev, r10_bio->sectors, 1);
1265 			put_buf(r10_bio);
1266 			break;
1267 		} else {
1268 			r10bio_t *r10_bio2 = (r10bio_t *)r10_bio->master_bio;
1269 			put_buf(r10_bio);
1270 			r10_bio = r10_bio2;
1271 		}
1272 	}
1273 	rdev_dec_pending(conf->mirrors[d].rdev, mddev);
1274 }
1275 
1276 /*
1277  * Note: sync and recover and handled very differently for raid10
1278  * This code is for resync.
1279  * For resync, we read through virtual addresses and read all blocks.
1280  * If there is any error, we schedule a write.  The lowest numbered
1281  * drive is authoritative.
1282  * However requests come for physical address, so we need to map.
1283  * For every physical address there are raid_disks/copies virtual addresses,
1284  * which is always are least one, but is not necessarly an integer.
1285  * This means that a physical address can span multiple chunks, so we may
1286  * have to submit multiple io requests for a single sync request.
1287  */
1288 /*
1289  * We check if all blocks are in-sync and only write to blocks that
1290  * aren't in sync
1291  */
1292 static void sync_request_write(mddev_t *mddev, r10bio_t *r10_bio)
1293 {
1294 	conf_t *conf = mddev_to_conf(mddev);
1295 	int i, first;
1296 	struct bio *tbio, *fbio;
1297 
1298 	atomic_set(&r10_bio->remaining, 1);
1299 
1300 	/* find the first device with a block */
1301 	for (i=0; i<conf->copies; i++)
1302 		if (test_bit(BIO_UPTODATE, &r10_bio->devs[i].bio->bi_flags))
1303 			break;
1304 
1305 	if (i == conf->copies)
1306 		goto done;
1307 
1308 	first = i;
1309 	fbio = r10_bio->devs[i].bio;
1310 
1311 	/* now find blocks with errors */
1312 	for (i=0 ; i < conf->copies ; i++) {
1313 		int  j, d;
1314 		int vcnt = r10_bio->sectors >> (PAGE_SHIFT-9);
1315 
1316 		tbio = r10_bio->devs[i].bio;
1317 
1318 		if (tbio->bi_end_io != end_sync_read)
1319 			continue;
1320 		if (i == first)
1321 			continue;
1322 		if (test_bit(BIO_UPTODATE, &r10_bio->devs[i].bio->bi_flags)) {
1323 			/* We know that the bi_io_vec layout is the same for
1324 			 * both 'first' and 'i', so we just compare them.
1325 			 * All vec entries are PAGE_SIZE;
1326 			 */
1327 			for (j = 0; j < vcnt; j++)
1328 				if (memcmp(page_address(fbio->bi_io_vec[j].bv_page),
1329 					   page_address(tbio->bi_io_vec[j].bv_page),
1330 					   PAGE_SIZE))
1331 					break;
1332 			if (j == vcnt)
1333 				continue;
1334 			mddev->resync_mismatches += r10_bio->sectors;
1335 		}
1336 		if (test_bit(MD_RECOVERY_CHECK, &mddev->recovery))
1337 			/* Don't fix anything. */
1338 			continue;
1339 		/* Ok, we need to write this bio
1340 		 * First we need to fixup bv_offset, bv_len and
1341 		 * bi_vecs, as the read request might have corrupted these
1342 		 */
1343 		tbio->bi_vcnt = vcnt;
1344 		tbio->bi_size = r10_bio->sectors << 9;
1345 		tbio->bi_idx = 0;
1346 		tbio->bi_phys_segments = 0;
1347 		tbio->bi_hw_segments = 0;
1348 		tbio->bi_hw_front_size = 0;
1349 		tbio->bi_hw_back_size = 0;
1350 		tbio->bi_flags &= ~(BIO_POOL_MASK - 1);
1351 		tbio->bi_flags |= 1 << BIO_UPTODATE;
1352 		tbio->bi_next = NULL;
1353 		tbio->bi_rw = WRITE;
1354 		tbio->bi_private = r10_bio;
1355 		tbio->bi_sector = r10_bio->devs[i].addr;
1356 
1357 		for (j=0; j < vcnt ; j++) {
1358 			tbio->bi_io_vec[j].bv_offset = 0;
1359 			tbio->bi_io_vec[j].bv_len = PAGE_SIZE;
1360 
1361 			memcpy(page_address(tbio->bi_io_vec[j].bv_page),
1362 			       page_address(fbio->bi_io_vec[j].bv_page),
1363 			       PAGE_SIZE);
1364 		}
1365 		tbio->bi_end_io = end_sync_write;
1366 
1367 		d = r10_bio->devs[i].devnum;
1368 		atomic_inc(&conf->mirrors[d].rdev->nr_pending);
1369 		atomic_inc(&r10_bio->remaining);
1370 		md_sync_acct(conf->mirrors[d].rdev->bdev, tbio->bi_size >> 9);
1371 
1372 		tbio->bi_sector += conf->mirrors[d].rdev->data_offset;
1373 		tbio->bi_bdev = conf->mirrors[d].rdev->bdev;
1374 		generic_make_request(tbio);
1375 	}
1376 
1377 done:
1378 	if (atomic_dec_and_test(&r10_bio->remaining)) {
1379 		md_done_sync(mddev, r10_bio->sectors, 1);
1380 		put_buf(r10_bio);
1381 	}
1382 }
1383 
1384 /*
1385  * Now for the recovery code.
1386  * Recovery happens across physical sectors.
1387  * We recover all non-is_sync drives by finding the virtual address of
1388  * each, and then choose a working drive that also has that virt address.
1389  * There is a separate r10_bio for each non-in_sync drive.
1390  * Only the first two slots are in use. The first for reading,
1391  * The second for writing.
1392  *
1393  */
1394 
1395 static void recovery_request_write(mddev_t *mddev, r10bio_t *r10_bio)
1396 {
1397 	conf_t *conf = mddev_to_conf(mddev);
1398 	int i, d;
1399 	struct bio *bio, *wbio;
1400 
1401 
1402 	/* move the pages across to the second bio
1403 	 * and submit the write request
1404 	 */
1405 	bio = r10_bio->devs[0].bio;
1406 	wbio = r10_bio->devs[1].bio;
1407 	for (i=0; i < wbio->bi_vcnt; i++) {
1408 		struct page *p = bio->bi_io_vec[i].bv_page;
1409 		bio->bi_io_vec[i].bv_page = wbio->bi_io_vec[i].bv_page;
1410 		wbio->bi_io_vec[i].bv_page = p;
1411 	}
1412 	d = r10_bio->devs[1].devnum;
1413 
1414 	atomic_inc(&conf->mirrors[d].rdev->nr_pending);
1415 	md_sync_acct(conf->mirrors[d].rdev->bdev, wbio->bi_size >> 9);
1416 	if (test_bit(R10BIO_Uptodate, &r10_bio->state))
1417 		generic_make_request(wbio);
1418 	else
1419 		bio_endio(wbio, -EIO);
1420 }
1421 
1422 
1423 /*
1424  * This is a kernel thread which:
1425  *
1426  *	1.	Retries failed read operations on working mirrors.
1427  *	2.	Updates the raid superblock when problems encounter.
1428  *	3.	Performs writes following reads for array synchronising.
1429  */
1430 
1431 static void fix_read_error(conf_t *conf, mddev_t *mddev, r10bio_t *r10_bio)
1432 {
1433 	int sect = 0; /* Offset from r10_bio->sector */
1434 	int sectors = r10_bio->sectors;
1435 	mdk_rdev_t*rdev;
1436 	while(sectors) {
1437 		int s = sectors;
1438 		int sl = r10_bio->read_slot;
1439 		int success = 0;
1440 		int start;
1441 
1442 		if (s > (PAGE_SIZE>>9))
1443 			s = PAGE_SIZE >> 9;
1444 
1445 		rcu_read_lock();
1446 		do {
1447 			int d = r10_bio->devs[sl].devnum;
1448 			rdev = rcu_dereference(conf->mirrors[d].rdev);
1449 			if (rdev &&
1450 			    test_bit(In_sync, &rdev->flags)) {
1451 				atomic_inc(&rdev->nr_pending);
1452 				rcu_read_unlock();
1453 				success = sync_page_io(rdev->bdev,
1454 						       r10_bio->devs[sl].addr +
1455 						       sect + rdev->data_offset,
1456 						       s<<9,
1457 						       conf->tmppage, READ);
1458 				rdev_dec_pending(rdev, mddev);
1459 				rcu_read_lock();
1460 				if (success)
1461 					break;
1462 			}
1463 			sl++;
1464 			if (sl == conf->copies)
1465 				sl = 0;
1466 		} while (!success && sl != r10_bio->read_slot);
1467 		rcu_read_unlock();
1468 
1469 		if (!success) {
1470 			/* Cannot read from anywhere -- bye bye array */
1471 			int dn = r10_bio->devs[r10_bio->read_slot].devnum;
1472 			md_error(mddev, conf->mirrors[dn].rdev);
1473 			break;
1474 		}
1475 
1476 		start = sl;
1477 		/* write it back and re-read */
1478 		rcu_read_lock();
1479 		while (sl != r10_bio->read_slot) {
1480 			int d;
1481 			if (sl==0)
1482 				sl = conf->copies;
1483 			sl--;
1484 			d = r10_bio->devs[sl].devnum;
1485 			rdev = rcu_dereference(conf->mirrors[d].rdev);
1486 			if (rdev &&
1487 			    test_bit(In_sync, &rdev->flags)) {
1488 				atomic_inc(&rdev->nr_pending);
1489 				rcu_read_unlock();
1490 				atomic_add(s, &rdev->corrected_errors);
1491 				if (sync_page_io(rdev->bdev,
1492 						 r10_bio->devs[sl].addr +
1493 						 sect + rdev->data_offset,
1494 						 s<<9, conf->tmppage, WRITE)
1495 				    == 0)
1496 					/* Well, this device is dead */
1497 					md_error(mddev, rdev);
1498 				rdev_dec_pending(rdev, mddev);
1499 				rcu_read_lock();
1500 			}
1501 		}
1502 		sl = start;
1503 		while (sl != r10_bio->read_slot) {
1504 			int d;
1505 			if (sl==0)
1506 				sl = conf->copies;
1507 			sl--;
1508 			d = r10_bio->devs[sl].devnum;
1509 			rdev = rcu_dereference(conf->mirrors[d].rdev);
1510 			if (rdev &&
1511 			    test_bit(In_sync, &rdev->flags)) {
1512 				char b[BDEVNAME_SIZE];
1513 				atomic_inc(&rdev->nr_pending);
1514 				rcu_read_unlock();
1515 				if (sync_page_io(rdev->bdev,
1516 						 r10_bio->devs[sl].addr +
1517 						 sect + rdev->data_offset,
1518 						 s<<9, conf->tmppage, READ) == 0)
1519 					/* Well, this device is dead */
1520 					md_error(mddev, rdev);
1521 				else
1522 					printk(KERN_INFO
1523 					       "raid10:%s: read error corrected"
1524 					       " (%d sectors at %llu on %s)\n",
1525 					       mdname(mddev), s,
1526 					       (unsigned long long)(sect+
1527 					            rdev->data_offset),
1528 					       bdevname(rdev->bdev, b));
1529 
1530 				rdev_dec_pending(rdev, mddev);
1531 				rcu_read_lock();
1532 			}
1533 		}
1534 		rcu_read_unlock();
1535 
1536 		sectors -= s;
1537 		sect += s;
1538 	}
1539 }
1540 
1541 static void raid10d(mddev_t *mddev)
1542 {
1543 	r10bio_t *r10_bio;
1544 	struct bio *bio;
1545 	unsigned long flags;
1546 	conf_t *conf = mddev_to_conf(mddev);
1547 	struct list_head *head = &conf->retry_list;
1548 	int unplug=0;
1549 	mdk_rdev_t *rdev;
1550 
1551 	md_check_recovery(mddev);
1552 
1553 	for (;;) {
1554 		char b[BDEVNAME_SIZE];
1555 
1556 		unplug += flush_pending_writes(conf);
1557 
1558 		spin_lock_irqsave(&conf->device_lock, flags);
1559 		if (list_empty(head)) {
1560 			spin_unlock_irqrestore(&conf->device_lock, flags);
1561 			break;
1562 		}
1563 		r10_bio = list_entry(head->prev, r10bio_t, retry_list);
1564 		list_del(head->prev);
1565 		conf->nr_queued--;
1566 		spin_unlock_irqrestore(&conf->device_lock, flags);
1567 
1568 		mddev = r10_bio->mddev;
1569 		conf = mddev_to_conf(mddev);
1570 		if (test_bit(R10BIO_IsSync, &r10_bio->state)) {
1571 			sync_request_write(mddev, r10_bio);
1572 			unplug = 1;
1573 		} else 	if (test_bit(R10BIO_IsRecover, &r10_bio->state)) {
1574 			recovery_request_write(mddev, r10_bio);
1575 			unplug = 1;
1576 		} else {
1577 			int mirror;
1578 			/* we got a read error. Maybe the drive is bad.  Maybe just
1579 			 * the block and we can fix it.
1580 			 * We freeze all other IO, and try reading the block from
1581 			 * other devices.  When we find one, we re-write
1582 			 * and check it that fixes the read error.
1583 			 * This is all done synchronously while the array is
1584 			 * frozen.
1585 			 */
1586 			if (mddev->ro == 0) {
1587 				freeze_array(conf);
1588 				fix_read_error(conf, mddev, r10_bio);
1589 				unfreeze_array(conf);
1590 			}
1591 
1592 			bio = r10_bio->devs[r10_bio->read_slot].bio;
1593 			r10_bio->devs[r10_bio->read_slot].bio =
1594 				mddev->ro ? IO_BLOCKED : NULL;
1595 			mirror = read_balance(conf, r10_bio);
1596 			if (mirror == -1) {
1597 				printk(KERN_ALERT "raid10: %s: unrecoverable I/O"
1598 				       " read error for block %llu\n",
1599 				       bdevname(bio->bi_bdev,b),
1600 				       (unsigned long long)r10_bio->sector);
1601 				raid_end_bio_io(r10_bio);
1602 				bio_put(bio);
1603 			} else {
1604 				const int do_sync = bio_sync(r10_bio->master_bio);
1605 				bio_put(bio);
1606 				rdev = conf->mirrors[mirror].rdev;
1607 				if (printk_ratelimit())
1608 					printk(KERN_ERR "raid10: %s: redirecting sector %llu to"
1609 					       " another mirror\n",
1610 					       bdevname(rdev->bdev,b),
1611 					       (unsigned long long)r10_bio->sector);
1612 				bio = bio_clone(r10_bio->master_bio, GFP_NOIO);
1613 				r10_bio->devs[r10_bio->read_slot].bio = bio;
1614 				bio->bi_sector = r10_bio->devs[r10_bio->read_slot].addr
1615 					+ rdev->data_offset;
1616 				bio->bi_bdev = rdev->bdev;
1617 				bio->bi_rw = READ | do_sync;
1618 				bio->bi_private = r10_bio;
1619 				bio->bi_end_io = raid10_end_read_request;
1620 				unplug = 1;
1621 				generic_make_request(bio);
1622 			}
1623 		}
1624 	}
1625 	if (unplug)
1626 		unplug_slaves(mddev);
1627 }
1628 
1629 
1630 static int init_resync(conf_t *conf)
1631 {
1632 	int buffs;
1633 
1634 	buffs = RESYNC_WINDOW / RESYNC_BLOCK_SIZE;
1635 	BUG_ON(conf->r10buf_pool);
1636 	conf->r10buf_pool = mempool_create(buffs, r10buf_pool_alloc, r10buf_pool_free, conf);
1637 	if (!conf->r10buf_pool)
1638 		return -ENOMEM;
1639 	conf->next_resync = 0;
1640 	return 0;
1641 }
1642 
1643 /*
1644  * perform a "sync" on one "block"
1645  *
1646  * We need to make sure that no normal I/O request - particularly write
1647  * requests - conflict with active sync requests.
1648  *
1649  * This is achieved by tracking pending requests and a 'barrier' concept
1650  * that can be installed to exclude normal IO requests.
1651  *
1652  * Resync and recovery are handled very differently.
1653  * We differentiate by looking at MD_RECOVERY_SYNC in mddev->recovery.
1654  *
1655  * For resync, we iterate over virtual addresses, read all copies,
1656  * and update if there are differences.  If only one copy is live,
1657  * skip it.
1658  * For recovery, we iterate over physical addresses, read a good
1659  * value for each non-in_sync drive, and over-write.
1660  *
1661  * So, for recovery we may have several outstanding complex requests for a
1662  * given address, one for each out-of-sync device.  We model this by allocating
1663  * a number of r10_bio structures, one for each out-of-sync device.
1664  * As we setup these structures, we collect all bio's together into a list
1665  * which we then process collectively to add pages, and then process again
1666  * to pass to generic_make_request.
1667  *
1668  * The r10_bio structures are linked using a borrowed master_bio pointer.
1669  * This link is counted in ->remaining.  When the r10_bio that points to NULL
1670  * has its remaining count decremented to 0, the whole complex operation
1671  * is complete.
1672  *
1673  */
1674 
1675 static sector_t sync_request(mddev_t *mddev, sector_t sector_nr, int *skipped, int go_faster)
1676 {
1677 	conf_t *conf = mddev_to_conf(mddev);
1678 	r10bio_t *r10_bio;
1679 	struct bio *biolist = NULL, *bio;
1680 	sector_t max_sector, nr_sectors;
1681 	int disk;
1682 	int i;
1683 	int max_sync;
1684 	int sync_blocks;
1685 
1686 	sector_t sectors_skipped = 0;
1687 	int chunks_skipped = 0;
1688 
1689 	if (!conf->r10buf_pool)
1690 		if (init_resync(conf))
1691 			return 0;
1692 
1693  skipped:
1694 	max_sector = mddev->size << 1;
1695 	if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery))
1696 		max_sector = mddev->resync_max_sectors;
1697 	if (sector_nr >= max_sector) {
1698 		/* If we aborted, we need to abort the
1699 		 * sync on the 'current' bitmap chucks (there can
1700 		 * be several when recovering multiple devices).
1701 		 * as we may have started syncing it but not finished.
1702 		 * We can find the current address in
1703 		 * mddev->curr_resync, but for recovery,
1704 		 * we need to convert that to several
1705 		 * virtual addresses.
1706 		 */
1707 		if (mddev->curr_resync < max_sector) { /* aborted */
1708 			if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery))
1709 				bitmap_end_sync(mddev->bitmap, mddev->curr_resync,
1710 						&sync_blocks, 1);
1711 			else for (i=0; i<conf->raid_disks; i++) {
1712 				sector_t sect =
1713 					raid10_find_virt(conf, mddev->curr_resync, i);
1714 				bitmap_end_sync(mddev->bitmap, sect,
1715 						&sync_blocks, 1);
1716 			}
1717 		} else /* completed sync */
1718 			conf->fullsync = 0;
1719 
1720 		bitmap_close_sync(mddev->bitmap);
1721 		close_sync(conf);
1722 		*skipped = 1;
1723 		return sectors_skipped;
1724 	}
1725 	if (chunks_skipped >= conf->raid_disks) {
1726 		/* if there has been nothing to do on any drive,
1727 		 * then there is nothing to do at all..
1728 		 */
1729 		*skipped = 1;
1730 		return (max_sector - sector_nr) + sectors_skipped;
1731 	}
1732 
1733 	if (max_sector > mddev->resync_max)
1734 		max_sector = mddev->resync_max; /* Don't do IO beyond here */
1735 
1736 	/* make sure whole request will fit in a chunk - if chunks
1737 	 * are meaningful
1738 	 */
1739 	if (conf->near_copies < conf->raid_disks &&
1740 	    max_sector > (sector_nr | conf->chunk_mask))
1741 		max_sector = (sector_nr | conf->chunk_mask) + 1;
1742 	/*
1743 	 * If there is non-resync activity waiting for us then
1744 	 * put in a delay to throttle resync.
1745 	 */
1746 	if (!go_faster && conf->nr_waiting)
1747 		msleep_interruptible(1000);
1748 
1749 	bitmap_cond_end_sync(mddev->bitmap, sector_nr);
1750 
1751 	/* Again, very different code for resync and recovery.
1752 	 * Both must result in an r10bio with a list of bios that
1753 	 * have bi_end_io, bi_sector, bi_bdev set,
1754 	 * and bi_private set to the r10bio.
1755 	 * For recovery, we may actually create several r10bios
1756 	 * with 2 bios in each, that correspond to the bios in the main one.
1757 	 * In this case, the subordinate r10bios link back through a
1758 	 * borrowed master_bio pointer, and the counter in the master
1759 	 * includes a ref from each subordinate.
1760 	 */
1761 	/* First, we decide what to do and set ->bi_end_io
1762 	 * To end_sync_read if we want to read, and
1763 	 * end_sync_write if we will want to write.
1764 	 */
1765 
1766 	max_sync = RESYNC_PAGES << (PAGE_SHIFT-9);
1767 	if (!test_bit(MD_RECOVERY_SYNC, &mddev->recovery)) {
1768 		/* recovery... the complicated one */
1769 		int i, j, k;
1770 		r10_bio = NULL;
1771 
1772 		for (i=0 ; i<conf->raid_disks; i++)
1773 			if (conf->mirrors[i].rdev &&
1774 			    !test_bit(In_sync, &conf->mirrors[i].rdev->flags)) {
1775 				int still_degraded = 0;
1776 				/* want to reconstruct this device */
1777 				r10bio_t *rb2 = r10_bio;
1778 				sector_t sect = raid10_find_virt(conf, sector_nr, i);
1779 				int must_sync;
1780 				/* Unless we are doing a full sync, we only need
1781 				 * to recover the block if it is set in the bitmap
1782 				 */
1783 				must_sync = bitmap_start_sync(mddev->bitmap, sect,
1784 							      &sync_blocks, 1);
1785 				if (sync_blocks < max_sync)
1786 					max_sync = sync_blocks;
1787 				if (!must_sync &&
1788 				    !conf->fullsync) {
1789 					/* yep, skip the sync_blocks here, but don't assume
1790 					 * that there will never be anything to do here
1791 					 */
1792 					chunks_skipped = -1;
1793 					continue;
1794 				}
1795 
1796 				r10_bio = mempool_alloc(conf->r10buf_pool, GFP_NOIO);
1797 				raise_barrier(conf, rb2 != NULL);
1798 				atomic_set(&r10_bio->remaining, 0);
1799 
1800 				r10_bio->master_bio = (struct bio*)rb2;
1801 				if (rb2)
1802 					atomic_inc(&rb2->remaining);
1803 				r10_bio->mddev = mddev;
1804 				set_bit(R10BIO_IsRecover, &r10_bio->state);
1805 				r10_bio->sector = sect;
1806 
1807 				raid10_find_phys(conf, r10_bio);
1808 				/* Need to check if this section will still be
1809 				 * degraded
1810 				 */
1811 				for (j=0; j<conf->copies;j++) {
1812 					int d = r10_bio->devs[j].devnum;
1813 					if (conf->mirrors[d].rdev == NULL ||
1814 					    test_bit(Faulty, &conf->mirrors[d].rdev->flags)) {
1815 						still_degraded = 1;
1816 						break;
1817 					}
1818 				}
1819 				must_sync = bitmap_start_sync(mddev->bitmap, sect,
1820 							      &sync_blocks, still_degraded);
1821 
1822 				for (j=0; j<conf->copies;j++) {
1823 					int d = r10_bio->devs[j].devnum;
1824 					if (conf->mirrors[d].rdev &&
1825 					    test_bit(In_sync, &conf->mirrors[d].rdev->flags)) {
1826 						/* This is where we read from */
1827 						bio = r10_bio->devs[0].bio;
1828 						bio->bi_next = biolist;
1829 						biolist = bio;
1830 						bio->bi_private = r10_bio;
1831 						bio->bi_end_io = end_sync_read;
1832 						bio->bi_rw = READ;
1833 						bio->bi_sector = r10_bio->devs[j].addr +
1834 							conf->mirrors[d].rdev->data_offset;
1835 						bio->bi_bdev = conf->mirrors[d].rdev->bdev;
1836 						atomic_inc(&conf->mirrors[d].rdev->nr_pending);
1837 						atomic_inc(&r10_bio->remaining);
1838 						/* and we write to 'i' */
1839 
1840 						for (k=0; k<conf->copies; k++)
1841 							if (r10_bio->devs[k].devnum == i)
1842 								break;
1843 						BUG_ON(k == conf->copies);
1844 						bio = r10_bio->devs[1].bio;
1845 						bio->bi_next = biolist;
1846 						biolist = bio;
1847 						bio->bi_private = r10_bio;
1848 						bio->bi_end_io = end_sync_write;
1849 						bio->bi_rw = WRITE;
1850 						bio->bi_sector = r10_bio->devs[k].addr +
1851 							conf->mirrors[i].rdev->data_offset;
1852 						bio->bi_bdev = conf->mirrors[i].rdev->bdev;
1853 
1854 						r10_bio->devs[0].devnum = d;
1855 						r10_bio->devs[1].devnum = i;
1856 
1857 						break;
1858 					}
1859 				}
1860 				if (j == conf->copies) {
1861 					/* Cannot recover, so abort the recovery */
1862 					put_buf(r10_bio);
1863 					if (rb2)
1864 						atomic_dec(&rb2->remaining);
1865 					r10_bio = rb2;
1866 					if (!test_and_set_bit(MD_RECOVERY_INTR,
1867 							      &mddev->recovery))
1868 						printk(KERN_INFO "raid10: %s: insufficient working devices for recovery.\n",
1869 						       mdname(mddev));
1870 					break;
1871 				}
1872 			}
1873 		if (biolist == NULL) {
1874 			while (r10_bio) {
1875 				r10bio_t *rb2 = r10_bio;
1876 				r10_bio = (r10bio_t*) rb2->master_bio;
1877 				rb2->master_bio = NULL;
1878 				put_buf(rb2);
1879 			}
1880 			goto giveup;
1881 		}
1882 	} else {
1883 		/* resync. Schedule a read for every block at this virt offset */
1884 		int count = 0;
1885 
1886 		if (!bitmap_start_sync(mddev->bitmap, sector_nr,
1887 				       &sync_blocks, mddev->degraded) &&
1888 		    !conf->fullsync && !test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery)) {
1889 			/* We can skip this block */
1890 			*skipped = 1;
1891 			return sync_blocks + sectors_skipped;
1892 		}
1893 		if (sync_blocks < max_sync)
1894 			max_sync = sync_blocks;
1895 		r10_bio = mempool_alloc(conf->r10buf_pool, GFP_NOIO);
1896 
1897 		r10_bio->mddev = mddev;
1898 		atomic_set(&r10_bio->remaining, 0);
1899 		raise_barrier(conf, 0);
1900 		conf->next_resync = sector_nr;
1901 
1902 		r10_bio->master_bio = NULL;
1903 		r10_bio->sector = sector_nr;
1904 		set_bit(R10BIO_IsSync, &r10_bio->state);
1905 		raid10_find_phys(conf, r10_bio);
1906 		r10_bio->sectors = (sector_nr | conf->chunk_mask) - sector_nr +1;
1907 
1908 		for (i=0; i<conf->copies; i++) {
1909 			int d = r10_bio->devs[i].devnum;
1910 			bio = r10_bio->devs[i].bio;
1911 			bio->bi_end_io = NULL;
1912 			clear_bit(BIO_UPTODATE, &bio->bi_flags);
1913 			if (conf->mirrors[d].rdev == NULL ||
1914 			    test_bit(Faulty, &conf->mirrors[d].rdev->flags))
1915 				continue;
1916 			atomic_inc(&conf->mirrors[d].rdev->nr_pending);
1917 			atomic_inc(&r10_bio->remaining);
1918 			bio->bi_next = biolist;
1919 			biolist = bio;
1920 			bio->bi_private = r10_bio;
1921 			bio->bi_end_io = end_sync_read;
1922 			bio->bi_rw = READ;
1923 			bio->bi_sector = r10_bio->devs[i].addr +
1924 				conf->mirrors[d].rdev->data_offset;
1925 			bio->bi_bdev = conf->mirrors[d].rdev->bdev;
1926 			count++;
1927 		}
1928 
1929 		if (count < 2) {
1930 			for (i=0; i<conf->copies; i++) {
1931 				int d = r10_bio->devs[i].devnum;
1932 				if (r10_bio->devs[i].bio->bi_end_io)
1933 					rdev_dec_pending(conf->mirrors[d].rdev, mddev);
1934 			}
1935 			put_buf(r10_bio);
1936 			biolist = NULL;
1937 			goto giveup;
1938 		}
1939 	}
1940 
1941 	for (bio = biolist; bio ; bio=bio->bi_next) {
1942 
1943 		bio->bi_flags &= ~(BIO_POOL_MASK - 1);
1944 		if (bio->bi_end_io)
1945 			bio->bi_flags |= 1 << BIO_UPTODATE;
1946 		bio->bi_vcnt = 0;
1947 		bio->bi_idx = 0;
1948 		bio->bi_phys_segments = 0;
1949 		bio->bi_hw_segments = 0;
1950 		bio->bi_size = 0;
1951 	}
1952 
1953 	nr_sectors = 0;
1954 	if (sector_nr + max_sync < max_sector)
1955 		max_sector = sector_nr + max_sync;
1956 	do {
1957 		struct page *page;
1958 		int len = PAGE_SIZE;
1959 		disk = 0;
1960 		if (sector_nr + (len>>9) > max_sector)
1961 			len = (max_sector - sector_nr) << 9;
1962 		if (len == 0)
1963 			break;
1964 		for (bio= biolist ; bio ; bio=bio->bi_next) {
1965 			page = bio->bi_io_vec[bio->bi_vcnt].bv_page;
1966 			if (bio_add_page(bio, page, len, 0) == 0) {
1967 				/* stop here */
1968 				struct bio *bio2;
1969 				bio->bi_io_vec[bio->bi_vcnt].bv_page = page;
1970 				for (bio2 = biolist; bio2 && bio2 != bio; bio2 = bio2->bi_next) {
1971 					/* remove last page from this bio */
1972 					bio2->bi_vcnt--;
1973 					bio2->bi_size -= len;
1974 					bio2->bi_flags &= ~(1<< BIO_SEG_VALID);
1975 				}
1976 				goto bio_full;
1977 			}
1978 			disk = i;
1979 		}
1980 		nr_sectors += len>>9;
1981 		sector_nr += len>>9;
1982 	} while (biolist->bi_vcnt < RESYNC_PAGES);
1983  bio_full:
1984 	r10_bio->sectors = nr_sectors;
1985 
1986 	while (biolist) {
1987 		bio = biolist;
1988 		biolist = biolist->bi_next;
1989 
1990 		bio->bi_next = NULL;
1991 		r10_bio = bio->bi_private;
1992 		r10_bio->sectors = nr_sectors;
1993 
1994 		if (bio->bi_end_io == end_sync_read) {
1995 			md_sync_acct(bio->bi_bdev, nr_sectors);
1996 			generic_make_request(bio);
1997 		}
1998 	}
1999 
2000 	if (sectors_skipped)
2001 		/* pretend they weren't skipped, it makes
2002 		 * no important difference in this case
2003 		 */
2004 		md_done_sync(mddev, sectors_skipped, 1);
2005 
2006 	return sectors_skipped + nr_sectors;
2007  giveup:
2008 	/* There is nowhere to write, so all non-sync
2009 	 * drives must be failed, so try the next chunk...
2010 	 */
2011 	{
2012 	sector_t sec = max_sector - sector_nr;
2013 	sectors_skipped += sec;
2014 	chunks_skipped ++;
2015 	sector_nr = max_sector;
2016 	goto skipped;
2017 	}
2018 }
2019 
2020 static int run(mddev_t *mddev)
2021 {
2022 	conf_t *conf;
2023 	int i, disk_idx;
2024 	mirror_info_t *disk;
2025 	mdk_rdev_t *rdev;
2026 	struct list_head *tmp;
2027 	int nc, fc, fo;
2028 	sector_t stride, size;
2029 
2030 	if (mddev->chunk_size == 0) {
2031 		printk(KERN_ERR "md/raid10: non-zero chunk size required.\n");
2032 		return -EINVAL;
2033 	}
2034 
2035 	nc = mddev->layout & 255;
2036 	fc = (mddev->layout >> 8) & 255;
2037 	fo = mddev->layout & (1<<16);
2038 	if ((nc*fc) <2 || (nc*fc) > mddev->raid_disks ||
2039 	    (mddev->layout >> 17)) {
2040 		printk(KERN_ERR "raid10: %s: unsupported raid10 layout: 0x%8x\n",
2041 		       mdname(mddev), mddev->layout);
2042 		goto out;
2043 	}
2044 	/*
2045 	 * copy the already verified devices into our private RAID10
2046 	 * bookkeeping area. [whatever we allocate in run(),
2047 	 * should be freed in stop()]
2048 	 */
2049 	conf = kzalloc(sizeof(conf_t), GFP_KERNEL);
2050 	mddev->private = conf;
2051 	if (!conf) {
2052 		printk(KERN_ERR "raid10: couldn't allocate memory for %s\n",
2053 			mdname(mddev));
2054 		goto out;
2055 	}
2056 	conf->mirrors = kzalloc(sizeof(struct mirror_info)*mddev->raid_disks,
2057 				 GFP_KERNEL);
2058 	if (!conf->mirrors) {
2059 		printk(KERN_ERR "raid10: couldn't allocate memory for %s\n",
2060 		       mdname(mddev));
2061 		goto out_free_conf;
2062 	}
2063 
2064 	conf->tmppage = alloc_page(GFP_KERNEL);
2065 	if (!conf->tmppage)
2066 		goto out_free_conf;
2067 
2068 	conf->mddev = mddev;
2069 	conf->raid_disks = mddev->raid_disks;
2070 	conf->near_copies = nc;
2071 	conf->far_copies = fc;
2072 	conf->copies = nc*fc;
2073 	conf->far_offset = fo;
2074 	conf->chunk_mask = (sector_t)(mddev->chunk_size>>9)-1;
2075 	conf->chunk_shift = ffz(~mddev->chunk_size) - 9;
2076 	size = mddev->size >> (conf->chunk_shift-1);
2077 	sector_div(size, fc);
2078 	size = size * conf->raid_disks;
2079 	sector_div(size, nc);
2080 	/* 'size' is now the number of chunks in the array */
2081 	/* calculate "used chunks per device" in 'stride' */
2082 	stride = size * conf->copies;
2083 
2084 	/* We need to round up when dividing by raid_disks to
2085 	 * get the stride size.
2086 	 */
2087 	stride += conf->raid_disks - 1;
2088 	sector_div(stride, conf->raid_disks);
2089 	mddev->size = stride  << (conf->chunk_shift-1);
2090 
2091 	if (fo)
2092 		stride = 1;
2093 	else
2094 		sector_div(stride, fc);
2095 	conf->stride = stride << conf->chunk_shift;
2096 
2097 	conf->r10bio_pool = mempool_create(NR_RAID10_BIOS, r10bio_pool_alloc,
2098 						r10bio_pool_free, conf);
2099 	if (!conf->r10bio_pool) {
2100 		printk(KERN_ERR "raid10: couldn't allocate memory for %s\n",
2101 			mdname(mddev));
2102 		goto out_free_conf;
2103 	}
2104 
2105 	spin_lock_init(&conf->device_lock);
2106 	mddev->queue->queue_lock = &conf->device_lock;
2107 
2108 	rdev_for_each(rdev, tmp, mddev) {
2109 		disk_idx = rdev->raid_disk;
2110 		if (disk_idx >= mddev->raid_disks
2111 		    || disk_idx < 0)
2112 			continue;
2113 		disk = conf->mirrors + disk_idx;
2114 
2115 		disk->rdev = rdev;
2116 
2117 		blk_queue_stack_limits(mddev->queue,
2118 				       rdev->bdev->bd_disk->queue);
2119 		/* as we don't honour merge_bvec_fn, we must never risk
2120 		 * violating it, so limit ->max_sector to one PAGE, as
2121 		 * a one page request is never in violation.
2122 		 */
2123 		if (rdev->bdev->bd_disk->queue->merge_bvec_fn &&
2124 		    mddev->queue->max_sectors > (PAGE_SIZE>>9))
2125 			mddev->queue->max_sectors = (PAGE_SIZE>>9);
2126 
2127 		disk->head_position = 0;
2128 	}
2129 	INIT_LIST_HEAD(&conf->retry_list);
2130 
2131 	spin_lock_init(&conf->resync_lock);
2132 	init_waitqueue_head(&conf->wait_barrier);
2133 
2134 	/* need to check that every block has at least one working mirror */
2135 	if (!enough(conf)) {
2136 		printk(KERN_ERR "raid10: not enough operational mirrors for %s\n",
2137 		       mdname(mddev));
2138 		goto out_free_conf;
2139 	}
2140 
2141 	mddev->degraded = 0;
2142 	for (i = 0; i < conf->raid_disks; i++) {
2143 
2144 		disk = conf->mirrors + i;
2145 
2146 		if (!disk->rdev ||
2147 		    !test_bit(In_sync, &disk->rdev->flags)) {
2148 			disk->head_position = 0;
2149 			mddev->degraded++;
2150 			if (disk->rdev)
2151 				conf->fullsync = 1;
2152 		}
2153 	}
2154 
2155 
2156 	mddev->thread = md_register_thread(raid10d, mddev, "%s_raid10");
2157 	if (!mddev->thread) {
2158 		printk(KERN_ERR
2159 		       "raid10: couldn't allocate thread for %s\n",
2160 		       mdname(mddev));
2161 		goto out_free_conf;
2162 	}
2163 
2164 	printk(KERN_INFO
2165 		"raid10: raid set %s active with %d out of %d devices\n",
2166 		mdname(mddev), mddev->raid_disks - mddev->degraded,
2167 		mddev->raid_disks);
2168 	/*
2169 	 * Ok, everything is just fine now
2170 	 */
2171 	mddev->array_sectors = size << conf->chunk_shift;
2172 	mddev->resync_max_sectors = size << conf->chunk_shift;
2173 
2174 	mddev->queue->unplug_fn = raid10_unplug;
2175 	mddev->queue->backing_dev_info.congested_fn = raid10_congested;
2176 	mddev->queue->backing_dev_info.congested_data = mddev;
2177 
2178 	/* Calculate max read-ahead size.
2179 	 * We need to readahead at least twice a whole stripe....
2180 	 * maybe...
2181 	 */
2182 	{
2183 		int stripe = conf->raid_disks * (mddev->chunk_size / PAGE_SIZE);
2184 		stripe /= conf->near_copies;
2185 		if (mddev->queue->backing_dev_info.ra_pages < 2* stripe)
2186 			mddev->queue->backing_dev_info.ra_pages = 2* stripe;
2187 	}
2188 
2189 	if (conf->near_copies < mddev->raid_disks)
2190 		blk_queue_merge_bvec(mddev->queue, raid10_mergeable_bvec);
2191 	return 0;
2192 
2193 out_free_conf:
2194 	if (conf->r10bio_pool)
2195 		mempool_destroy(conf->r10bio_pool);
2196 	safe_put_page(conf->tmppage);
2197 	kfree(conf->mirrors);
2198 	kfree(conf);
2199 	mddev->private = NULL;
2200 out:
2201 	return -EIO;
2202 }
2203 
2204 static int stop(mddev_t *mddev)
2205 {
2206 	conf_t *conf = mddev_to_conf(mddev);
2207 
2208 	md_unregister_thread(mddev->thread);
2209 	mddev->thread = NULL;
2210 	blk_sync_queue(mddev->queue); /* the unplug fn references 'conf'*/
2211 	if (conf->r10bio_pool)
2212 		mempool_destroy(conf->r10bio_pool);
2213 	kfree(conf->mirrors);
2214 	kfree(conf);
2215 	mddev->private = NULL;
2216 	return 0;
2217 }
2218 
2219 static void raid10_quiesce(mddev_t *mddev, int state)
2220 {
2221 	conf_t *conf = mddev_to_conf(mddev);
2222 
2223 	switch(state) {
2224 	case 1:
2225 		raise_barrier(conf, 0);
2226 		break;
2227 	case 0:
2228 		lower_barrier(conf);
2229 		break;
2230 	}
2231 	if (mddev->thread) {
2232 		if (mddev->bitmap)
2233 			mddev->thread->timeout = mddev->bitmap->daemon_sleep * HZ;
2234 		else
2235 			mddev->thread->timeout = MAX_SCHEDULE_TIMEOUT;
2236 		md_wakeup_thread(mddev->thread);
2237 	}
2238 }
2239 
2240 static struct mdk_personality raid10_personality =
2241 {
2242 	.name		= "raid10",
2243 	.level		= 10,
2244 	.owner		= THIS_MODULE,
2245 	.make_request	= make_request,
2246 	.run		= run,
2247 	.stop		= stop,
2248 	.status		= status,
2249 	.error_handler	= error,
2250 	.hot_add_disk	= raid10_add_disk,
2251 	.hot_remove_disk= raid10_remove_disk,
2252 	.spare_active	= raid10_spare_active,
2253 	.sync_request	= sync_request,
2254 	.quiesce	= raid10_quiesce,
2255 };
2256 
2257 static int __init raid_init(void)
2258 {
2259 	return register_md_personality(&raid10_personality);
2260 }
2261 
2262 static void raid_exit(void)
2263 {
2264 	unregister_md_personality(&raid10_personality);
2265 }
2266 
2267 module_init(raid_init);
2268 module_exit(raid_exit);
2269 MODULE_LICENSE("GPL");
2270 MODULE_ALIAS("md-personality-9"); /* RAID10 */
2271 MODULE_ALIAS("md-raid10");
2272 MODULE_ALIAS("md-level-10");
2273