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