xref: /linux/drivers/md/raid1.c (revision 9ce7677cfd7cd871adb457c80bea3b581b839641)
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 "dm-bio-list.h"
35 #include <linux/raid/raid1.h>
36 #include <linux/raid/bitmap.h>
37 
38 #define DEBUG 0
39 #if DEBUG
40 #define PRINTK(x...) printk(x)
41 #else
42 #define PRINTK(x...)
43 #endif
44 
45 /*
46  * Number of guaranteed r1bios in case of extreme VM load:
47  */
48 #define	NR_RAID1_BIOS 256
49 
50 static mdk_personality_t raid1_personality;
51 
52 static void unplug_slaves(mddev_t *mddev);
53 
54 
55 static void * r1bio_pool_alloc(gfp_t gfp_flags, void *data)
56 {
57 	struct pool_info *pi = data;
58 	r1bio_t *r1_bio;
59 	int size = offsetof(r1bio_t, bios[pi->raid_disks]);
60 
61 	/* allocate a r1bio with room for raid_disks entries in the bios array */
62 	r1_bio = kmalloc(size, gfp_flags);
63 	if (r1_bio)
64 		memset(r1_bio, 0, size);
65 	else
66 		unplug_slaves(pi->mddev);
67 
68 	return r1_bio;
69 }
70 
71 static void r1bio_pool_free(void *r1_bio, void *data)
72 {
73 	kfree(r1_bio);
74 }
75 
76 #define RESYNC_BLOCK_SIZE (64*1024)
77 //#define RESYNC_BLOCK_SIZE PAGE_SIZE
78 #define RESYNC_SECTORS (RESYNC_BLOCK_SIZE >> 9)
79 #define RESYNC_PAGES ((RESYNC_BLOCK_SIZE + PAGE_SIZE-1) / PAGE_SIZE)
80 #define RESYNC_WINDOW (2048*1024)
81 
82 static void * r1buf_pool_alloc(gfp_t gfp_flags, void *data)
83 {
84 	struct pool_info *pi = data;
85 	struct page *page;
86 	r1bio_t *r1_bio;
87 	struct bio *bio;
88 	int i, j;
89 
90 	r1_bio = r1bio_pool_alloc(gfp_flags, pi);
91 	if (!r1_bio) {
92 		unplug_slaves(pi->mddev);
93 		return NULL;
94 	}
95 
96 	/*
97 	 * Allocate bios : 1 for reading, n-1 for writing
98 	 */
99 	for (j = pi->raid_disks ; j-- ; ) {
100 		bio = bio_alloc(gfp_flags, RESYNC_PAGES);
101 		if (!bio)
102 			goto out_free_bio;
103 		r1_bio->bios[j] = bio;
104 	}
105 	/*
106 	 * Allocate RESYNC_PAGES data pages and attach them to
107 	 * the first bio;
108 	 */
109 	bio = r1_bio->bios[0];
110 	for (i = 0; i < RESYNC_PAGES; i++) {
111 		page = alloc_page(gfp_flags);
112 		if (unlikely(!page))
113 			goto out_free_pages;
114 
115 		bio->bi_io_vec[i].bv_page = page;
116 	}
117 
118 	r1_bio->master_bio = NULL;
119 
120 	return r1_bio;
121 
122 out_free_pages:
123 	for ( ; i > 0 ; i--)
124 		__free_page(bio->bi_io_vec[i-1].bv_page);
125 out_free_bio:
126 	while ( ++j < pi->raid_disks )
127 		bio_put(r1_bio->bios[j]);
128 	r1bio_pool_free(r1_bio, data);
129 	return NULL;
130 }
131 
132 static void r1buf_pool_free(void *__r1_bio, void *data)
133 {
134 	struct pool_info *pi = data;
135 	int i;
136 	r1bio_t *r1bio = __r1_bio;
137 	struct bio *bio = r1bio->bios[0];
138 
139 	for (i = 0; i < RESYNC_PAGES; i++) {
140 		__free_page(bio->bi_io_vec[i].bv_page);
141 		bio->bi_io_vec[i].bv_page = NULL;
142 	}
143 	for (i=0 ; i < pi->raid_disks; i++)
144 		bio_put(r1bio->bios[i]);
145 
146 	r1bio_pool_free(r1bio, data);
147 }
148 
149 static void put_all_bios(conf_t *conf, r1bio_t *r1_bio)
150 {
151 	int i;
152 
153 	for (i = 0; i < conf->raid_disks; i++) {
154 		struct bio **bio = r1_bio->bios + i;
155 		if (*bio)
156 			bio_put(*bio);
157 		*bio = NULL;
158 	}
159 }
160 
161 static inline void free_r1bio(r1bio_t *r1_bio)
162 {
163 	unsigned long flags;
164 
165 	conf_t *conf = mddev_to_conf(r1_bio->mddev);
166 
167 	/*
168 	 * Wake up any possible resync thread that waits for the device
169 	 * to go idle.
170 	 */
171 	spin_lock_irqsave(&conf->resync_lock, flags);
172 	if (!--conf->nr_pending) {
173 		wake_up(&conf->wait_idle);
174 		wake_up(&conf->wait_resume);
175 	}
176 	spin_unlock_irqrestore(&conf->resync_lock, flags);
177 
178 	put_all_bios(conf, r1_bio);
179 	mempool_free(r1_bio, conf->r1bio_pool);
180 }
181 
182 static inline void put_buf(r1bio_t *r1_bio)
183 {
184 	conf_t *conf = mddev_to_conf(r1_bio->mddev);
185 	unsigned long flags;
186 
187 	mempool_free(r1_bio, conf->r1buf_pool);
188 
189 	spin_lock_irqsave(&conf->resync_lock, flags);
190 	if (!conf->barrier)
191 		BUG();
192 	--conf->barrier;
193 	wake_up(&conf->wait_resume);
194 	wake_up(&conf->wait_idle);
195 
196 	if (!--conf->nr_pending) {
197 		wake_up(&conf->wait_idle);
198 		wake_up(&conf->wait_resume);
199 	}
200 	spin_unlock_irqrestore(&conf->resync_lock, flags);
201 }
202 
203 static void reschedule_retry(r1bio_t *r1_bio)
204 {
205 	unsigned long flags;
206 	mddev_t *mddev = r1_bio->mddev;
207 	conf_t *conf = mddev_to_conf(mddev);
208 
209 	spin_lock_irqsave(&conf->device_lock, flags);
210 	list_add(&r1_bio->retry_list, &conf->retry_list);
211 	spin_unlock_irqrestore(&conf->device_lock, flags);
212 
213 	md_wakeup_thread(mddev->thread);
214 }
215 
216 /*
217  * raid_end_bio_io() is called when we have finished servicing a mirrored
218  * operation and are ready to return a success/failure code to the buffer
219  * cache layer.
220  */
221 static void raid_end_bio_io(r1bio_t *r1_bio)
222 {
223 	struct bio *bio = r1_bio->master_bio;
224 
225 	/* if nobody has done the final endio yet, do it now */
226 	if (!test_and_set_bit(R1BIO_Returned, &r1_bio->state)) {
227 		PRINTK(KERN_DEBUG "raid1: sync end %s on sectors %llu-%llu\n",
228 			(bio_data_dir(bio) == WRITE) ? "write" : "read",
229 			(unsigned long long) bio->bi_sector,
230 			(unsigned long long) bio->bi_sector +
231 				(bio->bi_size >> 9) - 1);
232 
233 		bio_endio(bio, bio->bi_size,
234 			test_bit(R1BIO_Uptodate, &r1_bio->state) ? 0 : -EIO);
235 	}
236 	free_r1bio(r1_bio);
237 }
238 
239 /*
240  * Update disk head position estimator based on IRQ completion info.
241  */
242 static inline void update_head_pos(int disk, r1bio_t *r1_bio)
243 {
244 	conf_t *conf = mddev_to_conf(r1_bio->mddev);
245 
246 	conf->mirrors[disk].head_position =
247 		r1_bio->sector + (r1_bio->sectors);
248 }
249 
250 static int raid1_end_read_request(struct bio *bio, unsigned int bytes_done, int error)
251 {
252 	int uptodate = test_bit(BIO_UPTODATE, &bio->bi_flags);
253 	r1bio_t * r1_bio = (r1bio_t *)(bio->bi_private);
254 	int mirror;
255 	conf_t *conf = mddev_to_conf(r1_bio->mddev);
256 
257 	if (bio->bi_size)
258 		return 1;
259 
260 	mirror = r1_bio->read_disk;
261 	/*
262 	 * this branch is our 'one mirror IO has finished' event handler:
263 	 */
264 	if (!uptodate)
265 		md_error(r1_bio->mddev, conf->mirrors[mirror].rdev);
266 	else
267 		/*
268 		 * Set R1BIO_Uptodate in our master bio, so that
269 		 * we will return a good error code for to the higher
270 		 * levels even if IO on some other mirrored buffer fails.
271 		 *
272 		 * The 'master' represents the composite IO operation to
273 		 * user-side. So if something waits for IO, then it will
274 		 * wait for the 'master' bio.
275 		 */
276 		set_bit(R1BIO_Uptodate, &r1_bio->state);
277 
278 	update_head_pos(mirror, r1_bio);
279 
280 	/*
281 	 * we have only one bio on the read side
282 	 */
283 	if (uptodate)
284 		raid_end_bio_io(r1_bio);
285 	else {
286 		/*
287 		 * oops, read error:
288 		 */
289 		char b[BDEVNAME_SIZE];
290 		if (printk_ratelimit())
291 			printk(KERN_ERR "raid1: %s: rescheduling sector %llu\n",
292 			       bdevname(conf->mirrors[mirror].rdev->bdev,b), (unsigned long long)r1_bio->sector);
293 		reschedule_retry(r1_bio);
294 	}
295 
296 	rdev_dec_pending(conf->mirrors[mirror].rdev, conf->mddev);
297 	return 0;
298 }
299 
300 static int raid1_end_write_request(struct bio *bio, unsigned int bytes_done, int error)
301 {
302 	int uptodate = test_bit(BIO_UPTODATE, &bio->bi_flags);
303 	r1bio_t * r1_bio = (r1bio_t *)(bio->bi_private);
304 	int mirror, behind = test_bit(R1BIO_BehindIO, &r1_bio->state);
305 	conf_t *conf = mddev_to_conf(r1_bio->mddev);
306 
307 	if (bio->bi_size)
308 		return 1;
309 
310 	for (mirror = 0; mirror < conf->raid_disks; mirror++)
311 		if (r1_bio->bios[mirror] == bio)
312 			break;
313 
314 	if (error == -ENOTSUPP && test_bit(R1BIO_Barrier, &r1_bio->state)) {
315 		set_bit(BarriersNotsupp, &conf->mirrors[mirror].rdev->flags);
316 		set_bit(R1BIO_BarrierRetry, &r1_bio->state);
317 		r1_bio->mddev->barriers_work = 0;
318 	} else {
319 		/*
320 		 * this branch is our 'one mirror IO has finished' event handler:
321 		 */
322 		r1_bio->bios[mirror] = NULL;
323 		if (!uptodate) {
324 			md_error(r1_bio->mddev, conf->mirrors[mirror].rdev);
325 			/* an I/O failed, we can't clear the bitmap */
326 			set_bit(R1BIO_Degraded, &r1_bio->state);
327 		} else
328 			/*
329 			 * Set R1BIO_Uptodate in our master bio, so that
330 			 * we will return a good error code for to the higher
331 			 * levels even if IO on some other mirrored buffer fails.
332 			 *
333 			 * The 'master' represents the composite IO operation to
334 			 * user-side. So if something waits for IO, then it will
335 			 * wait for the 'master' bio.
336 			 */
337 			set_bit(R1BIO_Uptodate, &r1_bio->state);
338 
339 		update_head_pos(mirror, r1_bio);
340 
341 		if (behind) {
342 			if (test_bit(WriteMostly, &conf->mirrors[mirror].rdev->flags))
343 				atomic_dec(&r1_bio->behind_remaining);
344 
345 			/* In behind mode, we ACK the master bio once the I/O has safely
346 			 * reached all non-writemostly disks. Setting the Returned bit
347 			 * ensures that this gets done only once -- we don't ever want to
348 			 * return -EIO here, instead we'll wait */
349 
350 			if (atomic_read(&r1_bio->behind_remaining) >= (atomic_read(&r1_bio->remaining)-1) &&
351 			    test_bit(R1BIO_Uptodate, &r1_bio->state)) {
352 				/* Maybe we can return now */
353 				if (!test_and_set_bit(R1BIO_Returned, &r1_bio->state)) {
354 					struct bio *mbio = r1_bio->master_bio;
355 					PRINTK(KERN_DEBUG "raid1: behind end write sectors %llu-%llu\n",
356 					       (unsigned long long) mbio->bi_sector,
357 					       (unsigned long long) mbio->bi_sector +
358 					       (mbio->bi_size >> 9) - 1);
359 					bio_endio(mbio, mbio->bi_size, 0);
360 				}
361 			}
362 		}
363 	}
364 	/*
365 	 *
366 	 * Let's see if all mirrored write operations have finished
367 	 * already.
368 	 */
369 	if (atomic_dec_and_test(&r1_bio->remaining)) {
370 		if (test_bit(R1BIO_BarrierRetry, &r1_bio->state)) {
371 			reschedule_retry(r1_bio);
372 			/* Don't dec_pending yet, we want to hold
373 			 * the reference over the retry
374 			 */
375 			return 0;
376 		}
377 		if (test_bit(R1BIO_BehindIO, &r1_bio->state)) {
378 			/* free extra copy of the data pages */
379 			int i = bio->bi_vcnt;
380 			while (i--)
381 				__free_page(bio->bi_io_vec[i].bv_page);
382 		}
383 		/* clear the bitmap if all writes complete successfully */
384 		bitmap_endwrite(r1_bio->mddev->bitmap, r1_bio->sector,
385 				r1_bio->sectors,
386 				!test_bit(R1BIO_Degraded, &r1_bio->state),
387 				behind);
388 		md_write_end(r1_bio->mddev);
389 		raid_end_bio_io(r1_bio);
390 	}
391 
392 	if (r1_bio->bios[mirror]==NULL)
393 		bio_put(bio);
394 
395 	rdev_dec_pending(conf->mirrors[mirror].rdev, conf->mddev);
396 	return 0;
397 }
398 
399 
400 /*
401  * This routine returns the disk from which the requested read should
402  * be done. There is a per-array 'next expected sequential IO' sector
403  * number - if this matches on the next IO then we use the last disk.
404  * There is also a per-disk 'last know head position' sector that is
405  * maintained from IRQ contexts, both the normal and the resync IO
406  * completion handlers update this position correctly. If there is no
407  * perfect sequential match then we pick the disk whose head is closest.
408  *
409  * If there are 2 mirrors in the same 2 devices, performance degrades
410  * because position is mirror, not device based.
411  *
412  * The rdev for the device selected will have nr_pending incremented.
413  */
414 static int read_balance(conf_t *conf, r1bio_t *r1_bio)
415 {
416 	const unsigned long this_sector = r1_bio->sector;
417 	int new_disk = conf->last_used, disk = new_disk;
418 	int wonly_disk = -1;
419 	const int sectors = r1_bio->sectors;
420 	sector_t new_distance, current_distance;
421 	mdk_rdev_t *rdev;
422 
423 	rcu_read_lock();
424 	/*
425 	 * Check if we can balance. We can balance on the whole
426 	 * device if no resync is going on, or below the resync window.
427 	 * We take the first readable disk when above the resync window.
428 	 */
429  retry:
430 	if (conf->mddev->recovery_cp < MaxSector &&
431 	    (this_sector + sectors >= conf->next_resync)) {
432 		/* Choose the first operation device, for consistancy */
433 		new_disk = 0;
434 
435 		for (rdev = rcu_dereference(conf->mirrors[new_disk].rdev);
436 		     !rdev || !test_bit(In_sync, &rdev->flags)
437 			     || test_bit(WriteMostly, &rdev->flags);
438 		     rdev = rcu_dereference(conf->mirrors[++new_disk].rdev)) {
439 
440 			if (rdev && test_bit(In_sync, &rdev->flags))
441 				wonly_disk = new_disk;
442 
443 			if (new_disk == conf->raid_disks - 1) {
444 				new_disk = wonly_disk;
445 				break;
446 			}
447 		}
448 		goto rb_out;
449 	}
450 
451 
452 	/* make sure the disk is operational */
453 	for (rdev = rcu_dereference(conf->mirrors[new_disk].rdev);
454 	     !rdev || !test_bit(In_sync, &rdev->flags) ||
455 		     test_bit(WriteMostly, &rdev->flags);
456 	     rdev = rcu_dereference(conf->mirrors[new_disk].rdev)) {
457 
458 		if (rdev && test_bit(In_sync, &rdev->flags))
459 			wonly_disk = new_disk;
460 
461 		if (new_disk <= 0)
462 			new_disk = conf->raid_disks;
463 		new_disk--;
464 		if (new_disk == disk) {
465 			new_disk = wonly_disk;
466 			break;
467 		}
468 	}
469 
470 	if (new_disk < 0)
471 		goto rb_out;
472 
473 	disk = new_disk;
474 	/* now disk == new_disk == starting point for search */
475 
476 	/*
477 	 * Don't change to another disk for sequential reads:
478 	 */
479 	if (conf->next_seq_sect == this_sector)
480 		goto rb_out;
481 	if (this_sector == conf->mirrors[new_disk].head_position)
482 		goto rb_out;
483 
484 	current_distance = abs(this_sector - conf->mirrors[disk].head_position);
485 
486 	/* Find the disk whose head is closest */
487 
488 	do {
489 		if (disk <= 0)
490 			disk = conf->raid_disks;
491 		disk--;
492 
493 		rdev = rcu_dereference(conf->mirrors[disk].rdev);
494 
495 		if (!rdev ||
496 		    !test_bit(In_sync, &rdev->flags) ||
497 		    test_bit(WriteMostly, &rdev->flags))
498 			continue;
499 
500 		if (!atomic_read(&rdev->nr_pending)) {
501 			new_disk = disk;
502 			break;
503 		}
504 		new_distance = abs(this_sector - conf->mirrors[disk].head_position);
505 		if (new_distance < current_distance) {
506 			current_distance = new_distance;
507 			new_disk = disk;
508 		}
509 	} while (disk != conf->last_used);
510 
511  rb_out:
512 
513 
514 	if (new_disk >= 0) {
515 		rdev = rcu_dereference(conf->mirrors[new_disk].rdev);
516 		if (!rdev)
517 			goto retry;
518 		atomic_inc(&rdev->nr_pending);
519 		if (!test_bit(In_sync, &rdev->flags)) {
520 			/* cannot risk returning a device that failed
521 			 * before we inc'ed nr_pending
522 			 */
523 			atomic_dec(&rdev->nr_pending);
524 			goto retry;
525 		}
526 		conf->next_seq_sect = this_sector + sectors;
527 		conf->last_used = new_disk;
528 	}
529 	rcu_read_unlock();
530 
531 	return new_disk;
532 }
533 
534 static void unplug_slaves(mddev_t *mddev)
535 {
536 	conf_t *conf = mddev_to_conf(mddev);
537 	int i;
538 
539 	rcu_read_lock();
540 	for (i=0; i<mddev->raid_disks; i++) {
541 		mdk_rdev_t *rdev = rcu_dereference(conf->mirrors[i].rdev);
542 		if (rdev && !test_bit(Faulty, &rdev->flags) && atomic_read(&rdev->nr_pending)) {
543 			request_queue_t *r_queue = bdev_get_queue(rdev->bdev);
544 
545 			atomic_inc(&rdev->nr_pending);
546 			rcu_read_unlock();
547 
548 			if (r_queue->unplug_fn)
549 				r_queue->unplug_fn(r_queue);
550 
551 			rdev_dec_pending(rdev, mddev);
552 			rcu_read_lock();
553 		}
554 	}
555 	rcu_read_unlock();
556 }
557 
558 static void raid1_unplug(request_queue_t *q)
559 {
560 	mddev_t *mddev = q->queuedata;
561 
562 	unplug_slaves(mddev);
563 	md_wakeup_thread(mddev->thread);
564 }
565 
566 static int raid1_issue_flush(request_queue_t *q, struct gendisk *disk,
567 			     sector_t *error_sector)
568 {
569 	mddev_t *mddev = q->queuedata;
570 	conf_t *conf = mddev_to_conf(mddev);
571 	int i, ret = 0;
572 
573 	rcu_read_lock();
574 	for (i=0; i<mddev->raid_disks && ret == 0; i++) {
575 		mdk_rdev_t *rdev = rcu_dereference(conf->mirrors[i].rdev);
576 		if (rdev && !test_bit(Faulty, &rdev->flags)) {
577 			struct block_device *bdev = rdev->bdev;
578 			request_queue_t *r_queue = bdev_get_queue(bdev);
579 
580 			if (!r_queue->issue_flush_fn)
581 				ret = -EOPNOTSUPP;
582 			else {
583 				atomic_inc(&rdev->nr_pending);
584 				rcu_read_unlock();
585 				ret = r_queue->issue_flush_fn(r_queue, bdev->bd_disk,
586 							      error_sector);
587 				rdev_dec_pending(rdev, mddev);
588 				rcu_read_lock();
589 			}
590 		}
591 	}
592 	rcu_read_unlock();
593 	return ret;
594 }
595 
596 /*
597  * Throttle resync depth, so that we can both get proper overlapping of
598  * requests, but are still able to handle normal requests quickly.
599  */
600 #define RESYNC_DEPTH 32
601 
602 static void device_barrier(conf_t *conf, sector_t sect)
603 {
604 	spin_lock_irq(&conf->resync_lock);
605 	wait_event_lock_irq(conf->wait_idle, !waitqueue_active(&conf->wait_resume),
606 			    conf->resync_lock, raid1_unplug(conf->mddev->queue));
607 
608 	if (!conf->barrier++) {
609 		wait_event_lock_irq(conf->wait_idle, !conf->nr_pending,
610 				    conf->resync_lock, raid1_unplug(conf->mddev->queue));
611 		if (conf->nr_pending)
612 			BUG();
613 	}
614 	wait_event_lock_irq(conf->wait_resume, conf->barrier < RESYNC_DEPTH,
615 			    conf->resync_lock, raid1_unplug(conf->mddev->queue));
616 	conf->next_resync = sect;
617 	spin_unlock_irq(&conf->resync_lock);
618 }
619 
620 /* duplicate the data pages for behind I/O */
621 static struct page **alloc_behind_pages(struct bio *bio)
622 {
623 	int i;
624 	struct bio_vec *bvec;
625 	struct page **pages = kmalloc(bio->bi_vcnt * sizeof(struct page *),
626 					GFP_NOIO);
627 	if (unlikely(!pages))
628 		goto do_sync_io;
629 
630 	memset(pages, 0, bio->bi_vcnt * sizeof(struct page *));
631 
632 	bio_for_each_segment(bvec, bio, i) {
633 		pages[i] = alloc_page(GFP_NOIO);
634 		if (unlikely(!pages[i]))
635 			goto do_sync_io;
636 		memcpy(kmap(pages[i]) + bvec->bv_offset,
637 			kmap(bvec->bv_page) + bvec->bv_offset, bvec->bv_len);
638 		kunmap(pages[i]);
639 		kunmap(bvec->bv_page);
640 	}
641 
642 	return pages;
643 
644 do_sync_io:
645 	if (pages)
646 		for (i = 0; i < bio->bi_vcnt && pages[i]; i++)
647 			__free_page(pages[i]);
648 	kfree(pages);
649 	PRINTK("%dB behind alloc failed, doing sync I/O\n", bio->bi_size);
650 	return NULL;
651 }
652 
653 static int make_request(request_queue_t *q, struct bio * bio)
654 {
655 	mddev_t *mddev = q->queuedata;
656 	conf_t *conf = mddev_to_conf(mddev);
657 	mirror_info_t *mirror;
658 	r1bio_t *r1_bio;
659 	struct bio *read_bio;
660 	int i, targets = 0, disks;
661 	mdk_rdev_t *rdev;
662 	struct bitmap *bitmap = mddev->bitmap;
663 	unsigned long flags;
664 	struct bio_list bl;
665 	struct page **behind_pages = NULL;
666 	const int rw = bio_data_dir(bio);
667 	int do_barriers;
668 
669 	if (unlikely(!mddev->barriers_work && bio_barrier(bio))) {
670 		bio_endio(bio, bio->bi_size, -EOPNOTSUPP);
671 		return 0;
672 	}
673 
674 	/*
675 	 * Register the new request and wait if the reconstruction
676 	 * thread has put up a bar for new requests.
677 	 * Continue immediately if no resync is active currently.
678 	 */
679 	md_write_start(mddev, bio); /* wait on superblock update early */
680 
681 	spin_lock_irq(&conf->resync_lock);
682 	wait_event_lock_irq(conf->wait_resume, !conf->barrier, conf->resync_lock, );
683 	conf->nr_pending++;
684 	spin_unlock_irq(&conf->resync_lock);
685 
686 	disk_stat_inc(mddev->gendisk, ios[rw]);
687 	disk_stat_add(mddev->gendisk, sectors[rw], bio_sectors(bio));
688 
689 	/*
690 	 * make_request() can abort the operation when READA is being
691 	 * used and no empty request is available.
692 	 *
693 	 */
694 	r1_bio = mempool_alloc(conf->r1bio_pool, GFP_NOIO);
695 
696 	r1_bio->master_bio = bio;
697 	r1_bio->sectors = bio->bi_size >> 9;
698 	r1_bio->state = 0;
699 	r1_bio->mddev = mddev;
700 	r1_bio->sector = bio->bi_sector;
701 
702 	if (rw == READ) {
703 		/*
704 		 * read balancing logic:
705 		 */
706 		int rdisk = read_balance(conf, r1_bio);
707 
708 		if (rdisk < 0) {
709 			/* couldn't find anywhere to read from */
710 			raid_end_bio_io(r1_bio);
711 			return 0;
712 		}
713 		mirror = conf->mirrors + rdisk;
714 
715 		r1_bio->read_disk = rdisk;
716 
717 		read_bio = bio_clone(bio, GFP_NOIO);
718 
719 		r1_bio->bios[rdisk] = read_bio;
720 
721 		read_bio->bi_sector = r1_bio->sector + mirror->rdev->data_offset;
722 		read_bio->bi_bdev = mirror->rdev->bdev;
723 		read_bio->bi_end_io = raid1_end_read_request;
724 		read_bio->bi_rw = READ;
725 		read_bio->bi_private = r1_bio;
726 
727 		generic_make_request(read_bio);
728 		return 0;
729 	}
730 
731 	/*
732 	 * WRITE:
733 	 */
734 	/* first select target devices under spinlock and
735 	 * inc refcount on their rdev.  Record them by setting
736 	 * bios[x] to bio
737 	 */
738 	disks = conf->raid_disks;
739 #if 0
740 	{ static int first=1;
741 	if (first) printk("First Write sector %llu disks %d\n",
742 			  (unsigned long long)r1_bio->sector, disks);
743 	first = 0;
744 	}
745 #endif
746 	rcu_read_lock();
747 	for (i = 0;  i < disks; i++) {
748 		if ((rdev=rcu_dereference(conf->mirrors[i].rdev)) != NULL &&
749 		    !test_bit(Faulty, &rdev->flags)) {
750 			atomic_inc(&rdev->nr_pending);
751 			if (test_bit(Faulty, &rdev->flags)) {
752 				atomic_dec(&rdev->nr_pending);
753 				r1_bio->bios[i] = NULL;
754 			} else
755 				r1_bio->bios[i] = bio;
756 			targets++;
757 		} else
758 			r1_bio->bios[i] = NULL;
759 	}
760 	rcu_read_unlock();
761 
762 	BUG_ON(targets == 0); /* we never fail the last device */
763 
764 	if (targets < conf->raid_disks) {
765 		/* array is degraded, we will not clear the bitmap
766 		 * on I/O completion (see raid1_end_write_request) */
767 		set_bit(R1BIO_Degraded, &r1_bio->state);
768 	}
769 
770 	/* do behind I/O ? */
771 	if (bitmap &&
772 	    atomic_read(&bitmap->behind_writes) < bitmap->max_write_behind &&
773 	    (behind_pages = alloc_behind_pages(bio)) != NULL)
774 		set_bit(R1BIO_BehindIO, &r1_bio->state);
775 
776 	atomic_set(&r1_bio->remaining, 0);
777 	atomic_set(&r1_bio->behind_remaining, 0);
778 
779 	do_barriers = bio->bi_rw & BIO_RW_BARRIER;
780 	if (do_barriers)
781 		set_bit(R1BIO_Barrier, &r1_bio->state);
782 
783 	bio_list_init(&bl);
784 	for (i = 0; i < disks; i++) {
785 		struct bio *mbio;
786 		if (!r1_bio->bios[i])
787 			continue;
788 
789 		mbio = bio_clone(bio, GFP_NOIO);
790 		r1_bio->bios[i] = mbio;
791 
792 		mbio->bi_sector	= r1_bio->sector + conf->mirrors[i].rdev->data_offset;
793 		mbio->bi_bdev = conf->mirrors[i].rdev->bdev;
794 		mbio->bi_end_io	= raid1_end_write_request;
795 		mbio->bi_rw = WRITE | do_barriers;
796 		mbio->bi_private = r1_bio;
797 
798 		if (behind_pages) {
799 			struct bio_vec *bvec;
800 			int j;
801 
802 			/* Yes, I really want the '__' version so that
803 			 * we clear any unused pointer in the io_vec, rather
804 			 * than leave them unchanged.  This is important
805 			 * because when we come to free the pages, we won't
806 			 * know the originial bi_idx, so we just free
807 			 * them all
808 			 */
809 			__bio_for_each_segment(bvec, mbio, j, 0)
810 				bvec->bv_page = behind_pages[j];
811 			if (test_bit(WriteMostly, &conf->mirrors[i].rdev->flags))
812 				atomic_inc(&r1_bio->behind_remaining);
813 		}
814 
815 		atomic_inc(&r1_bio->remaining);
816 
817 		bio_list_add(&bl, mbio);
818 	}
819 	kfree(behind_pages); /* the behind pages are attached to the bios now */
820 
821 	bitmap_startwrite(bitmap, bio->bi_sector, r1_bio->sectors,
822 				test_bit(R1BIO_BehindIO, &r1_bio->state));
823 	spin_lock_irqsave(&conf->device_lock, flags);
824 	bio_list_merge(&conf->pending_bio_list, &bl);
825 	bio_list_init(&bl);
826 
827 	blk_plug_device(mddev->queue);
828 	spin_unlock_irqrestore(&conf->device_lock, flags);
829 
830 #if 0
831 	while ((bio = bio_list_pop(&bl)) != NULL)
832 		generic_make_request(bio);
833 #endif
834 
835 	return 0;
836 }
837 
838 static void status(struct seq_file *seq, mddev_t *mddev)
839 {
840 	conf_t *conf = mddev_to_conf(mddev);
841 	int i;
842 
843 	seq_printf(seq, " [%d/%d] [", conf->raid_disks,
844 						conf->working_disks);
845 	for (i = 0; i < conf->raid_disks; i++)
846 		seq_printf(seq, "%s",
847 			      conf->mirrors[i].rdev &&
848 			      test_bit(In_sync, &conf->mirrors[i].rdev->flags) ? "U" : "_");
849 	seq_printf(seq, "]");
850 }
851 
852 
853 static void error(mddev_t *mddev, mdk_rdev_t *rdev)
854 {
855 	char b[BDEVNAME_SIZE];
856 	conf_t *conf = mddev_to_conf(mddev);
857 
858 	/*
859 	 * If it is not operational, then we have already marked it as dead
860 	 * else if it is the last working disks, ignore the error, let the
861 	 * next level up know.
862 	 * else mark the drive as failed
863 	 */
864 	if (test_bit(In_sync, &rdev->flags)
865 	    && conf->working_disks == 1)
866 		/*
867 		 * Don't fail the drive, act as though we were just a
868 		 * normal single drive
869 		 */
870 		return;
871 	if (test_bit(In_sync, &rdev->flags)) {
872 		mddev->degraded++;
873 		conf->working_disks--;
874 		/*
875 		 * if recovery is running, make sure it aborts.
876 		 */
877 		set_bit(MD_RECOVERY_ERR, &mddev->recovery);
878 	}
879 	clear_bit(In_sync, &rdev->flags);
880 	set_bit(Faulty, &rdev->flags);
881 	mddev->sb_dirty = 1;
882 	printk(KERN_ALERT "raid1: Disk failure on %s, disabling device. \n"
883 		"	Operation continuing on %d devices\n",
884 		bdevname(rdev->bdev,b), conf->working_disks);
885 }
886 
887 static void print_conf(conf_t *conf)
888 {
889 	int i;
890 	mirror_info_t *tmp;
891 
892 	printk("RAID1 conf printout:\n");
893 	if (!conf) {
894 		printk("(!conf)\n");
895 		return;
896 	}
897 	printk(" --- wd:%d rd:%d\n", conf->working_disks,
898 		conf->raid_disks);
899 
900 	for (i = 0; i < conf->raid_disks; i++) {
901 		char b[BDEVNAME_SIZE];
902 		tmp = conf->mirrors + i;
903 		if (tmp->rdev)
904 			printk(" disk %d, wo:%d, o:%d, dev:%s\n",
905 				i, !test_bit(In_sync, &tmp->rdev->flags), !test_bit(Faulty, &tmp->rdev->flags),
906 				bdevname(tmp->rdev->bdev,b));
907 	}
908 }
909 
910 static void close_sync(conf_t *conf)
911 {
912 	spin_lock_irq(&conf->resync_lock);
913 	wait_event_lock_irq(conf->wait_resume, !conf->barrier,
914 			    conf->resync_lock, 	raid1_unplug(conf->mddev->queue));
915 	spin_unlock_irq(&conf->resync_lock);
916 
917 	if (conf->barrier) BUG();
918 	if (waitqueue_active(&conf->wait_idle)) BUG();
919 
920 	mempool_destroy(conf->r1buf_pool);
921 	conf->r1buf_pool = NULL;
922 }
923 
924 static int raid1_spare_active(mddev_t *mddev)
925 {
926 	int i;
927 	conf_t *conf = mddev->private;
928 	mirror_info_t *tmp;
929 
930 	/*
931 	 * Find all failed disks within the RAID1 configuration
932 	 * and mark them readable
933 	 */
934 	for (i = 0; i < conf->raid_disks; i++) {
935 		tmp = conf->mirrors + i;
936 		if (tmp->rdev
937 		    && !test_bit(Faulty, &tmp->rdev->flags)
938 		    && !test_bit(In_sync, &tmp->rdev->flags)) {
939 			conf->working_disks++;
940 			mddev->degraded--;
941 			set_bit(In_sync, &tmp->rdev->flags);
942 		}
943 	}
944 
945 	print_conf(conf);
946 	return 0;
947 }
948 
949 
950 static int raid1_add_disk(mddev_t *mddev, mdk_rdev_t *rdev)
951 {
952 	conf_t *conf = mddev->private;
953 	int found = 0;
954 	int mirror = 0;
955 	mirror_info_t *p;
956 
957 	for (mirror=0; mirror < mddev->raid_disks; mirror++)
958 		if ( !(p=conf->mirrors+mirror)->rdev) {
959 
960 			blk_queue_stack_limits(mddev->queue,
961 					       rdev->bdev->bd_disk->queue);
962 			/* as we don't honour merge_bvec_fn, we must never risk
963 			 * violating it, so limit ->max_sector to one PAGE, as
964 			 * a one page request is never in violation.
965 			 */
966 			if (rdev->bdev->bd_disk->queue->merge_bvec_fn &&
967 			    mddev->queue->max_sectors > (PAGE_SIZE>>9))
968 				blk_queue_max_sectors(mddev->queue, PAGE_SIZE>>9);
969 
970 			p->head_position = 0;
971 			rdev->raid_disk = mirror;
972 			found = 1;
973 			/* As all devices are equivalent, we don't need a full recovery
974 			 * if this was recently any drive of the array
975 			 */
976 			if (rdev->saved_raid_disk < 0)
977 				conf->fullsync = 1;
978 			rcu_assign_pointer(p->rdev, rdev);
979 			break;
980 		}
981 
982 	print_conf(conf);
983 	return found;
984 }
985 
986 static int raid1_remove_disk(mddev_t *mddev, int number)
987 {
988 	conf_t *conf = mddev->private;
989 	int err = 0;
990 	mdk_rdev_t *rdev;
991 	mirror_info_t *p = conf->mirrors+ number;
992 
993 	print_conf(conf);
994 	rdev = p->rdev;
995 	if (rdev) {
996 		if (test_bit(In_sync, &rdev->flags) ||
997 		    atomic_read(&rdev->nr_pending)) {
998 			err = -EBUSY;
999 			goto abort;
1000 		}
1001 		p->rdev = NULL;
1002 		synchronize_rcu();
1003 		if (atomic_read(&rdev->nr_pending)) {
1004 			/* lost the race, try later */
1005 			err = -EBUSY;
1006 			p->rdev = rdev;
1007 		}
1008 	}
1009 abort:
1010 
1011 	print_conf(conf);
1012 	return err;
1013 }
1014 
1015 
1016 static int end_sync_read(struct bio *bio, unsigned int bytes_done, int error)
1017 {
1018 	int uptodate = test_bit(BIO_UPTODATE, &bio->bi_flags);
1019 	r1bio_t * r1_bio = (r1bio_t *)(bio->bi_private);
1020 	conf_t *conf = mddev_to_conf(r1_bio->mddev);
1021 
1022 	if (bio->bi_size)
1023 		return 1;
1024 
1025 	if (r1_bio->bios[r1_bio->read_disk] != bio)
1026 		BUG();
1027 	update_head_pos(r1_bio->read_disk, r1_bio);
1028 	/*
1029 	 * we have read a block, now it needs to be re-written,
1030 	 * or re-read if the read failed.
1031 	 * We don't do much here, just schedule handling by raid1d
1032 	 */
1033 	if (!uptodate) {
1034 		md_error(r1_bio->mddev,
1035 			 conf->mirrors[r1_bio->read_disk].rdev);
1036 	} else
1037 		set_bit(R1BIO_Uptodate, &r1_bio->state);
1038 	rdev_dec_pending(conf->mirrors[r1_bio->read_disk].rdev, conf->mddev);
1039 	reschedule_retry(r1_bio);
1040 	return 0;
1041 }
1042 
1043 static int end_sync_write(struct bio *bio, unsigned int bytes_done, int error)
1044 {
1045 	int uptodate = test_bit(BIO_UPTODATE, &bio->bi_flags);
1046 	r1bio_t * r1_bio = (r1bio_t *)(bio->bi_private);
1047 	mddev_t *mddev = r1_bio->mddev;
1048 	conf_t *conf = mddev_to_conf(mddev);
1049 	int i;
1050 	int mirror=0;
1051 
1052 	if (bio->bi_size)
1053 		return 1;
1054 
1055 	for (i = 0; i < conf->raid_disks; i++)
1056 		if (r1_bio->bios[i] == bio) {
1057 			mirror = i;
1058 			break;
1059 		}
1060 	if (!uptodate)
1061 		md_error(mddev, conf->mirrors[mirror].rdev);
1062 
1063 	update_head_pos(mirror, r1_bio);
1064 
1065 	if (atomic_dec_and_test(&r1_bio->remaining)) {
1066 		md_done_sync(mddev, r1_bio->sectors, uptodate);
1067 		put_buf(r1_bio);
1068 	}
1069 	rdev_dec_pending(conf->mirrors[mirror].rdev, mddev);
1070 	return 0;
1071 }
1072 
1073 static void sync_request_write(mddev_t *mddev, r1bio_t *r1_bio)
1074 {
1075 	conf_t *conf = mddev_to_conf(mddev);
1076 	int i;
1077 	int disks = conf->raid_disks;
1078 	struct bio *bio, *wbio;
1079 
1080 	bio = r1_bio->bios[r1_bio->read_disk];
1081 
1082 /*
1083 	if (r1_bio->sector == 0) printk("First sync write startss\n");
1084 */
1085 	/*
1086 	 * schedule writes
1087 	 */
1088 	if (!test_bit(R1BIO_Uptodate, &r1_bio->state)) {
1089 		/*
1090 		 * There is no point trying a read-for-reconstruct as
1091 		 * reconstruct is about to be aborted
1092 		 */
1093 		char b[BDEVNAME_SIZE];
1094 		printk(KERN_ALERT "raid1: %s: unrecoverable I/O read error"
1095 			" for block %llu\n",
1096 			bdevname(bio->bi_bdev,b),
1097 			(unsigned long long)r1_bio->sector);
1098 		md_done_sync(mddev, r1_bio->sectors, 0);
1099 		put_buf(r1_bio);
1100 		return;
1101 	}
1102 
1103 	atomic_set(&r1_bio->remaining, 1);
1104 	for (i = 0; i < disks ; i++) {
1105 		wbio = r1_bio->bios[i];
1106 		if (wbio->bi_end_io != end_sync_write)
1107 			continue;
1108 
1109 		atomic_inc(&conf->mirrors[i].rdev->nr_pending);
1110 		atomic_inc(&r1_bio->remaining);
1111 		md_sync_acct(conf->mirrors[i].rdev->bdev, wbio->bi_size >> 9);
1112 
1113 		generic_make_request(wbio);
1114 	}
1115 
1116 	if (atomic_dec_and_test(&r1_bio->remaining)) {
1117 		/* if we're here, all write(s) have completed, so clean up */
1118 		md_done_sync(mddev, r1_bio->sectors, 1);
1119 		put_buf(r1_bio);
1120 	}
1121 }
1122 
1123 /*
1124  * This is a kernel thread which:
1125  *
1126  *	1.	Retries failed read operations on working mirrors.
1127  *	2.	Updates the raid superblock when problems encounter.
1128  *	3.	Performs writes following reads for array syncronising.
1129  */
1130 
1131 static void raid1d(mddev_t *mddev)
1132 {
1133 	r1bio_t *r1_bio;
1134 	struct bio *bio;
1135 	unsigned long flags;
1136 	conf_t *conf = mddev_to_conf(mddev);
1137 	struct list_head *head = &conf->retry_list;
1138 	int unplug=0;
1139 	mdk_rdev_t *rdev;
1140 
1141 	md_check_recovery(mddev);
1142 
1143 	for (;;) {
1144 		char b[BDEVNAME_SIZE];
1145 		spin_lock_irqsave(&conf->device_lock, flags);
1146 
1147 		if (conf->pending_bio_list.head) {
1148 			bio = bio_list_get(&conf->pending_bio_list);
1149 			blk_remove_plug(mddev->queue);
1150 			spin_unlock_irqrestore(&conf->device_lock, flags);
1151 			/* flush any pending bitmap writes to disk before proceeding w/ I/O */
1152 			if (bitmap_unplug(mddev->bitmap) != 0)
1153 				printk("%s: bitmap file write failed!\n", mdname(mddev));
1154 
1155 			while (bio) { /* submit pending writes */
1156 				struct bio *next = bio->bi_next;
1157 				bio->bi_next = NULL;
1158 				generic_make_request(bio);
1159 				bio = next;
1160 			}
1161 			unplug = 1;
1162 
1163 			continue;
1164 		}
1165 
1166 		if (list_empty(head))
1167 			break;
1168 		r1_bio = list_entry(head->prev, r1bio_t, retry_list);
1169 		list_del(head->prev);
1170 		spin_unlock_irqrestore(&conf->device_lock, flags);
1171 
1172 		mddev = r1_bio->mddev;
1173 		conf = mddev_to_conf(mddev);
1174 		if (test_bit(R1BIO_IsSync, &r1_bio->state)) {
1175 			sync_request_write(mddev, r1_bio);
1176 			unplug = 1;
1177 		} else if (test_bit(R1BIO_BarrierRetry, &r1_bio->state)) {
1178 			/* some requests in the r1bio were BIO_RW_BARRIER
1179 			 * requests which failed with -ENOTSUPP.  Hohumm..
1180 			 * Better resubmit without the barrier.
1181 			 * We know which devices to resubmit for, because
1182 			 * all others have had their bios[] entry cleared.
1183 			 */
1184 			int i;
1185 			clear_bit(R1BIO_BarrierRetry, &r1_bio->state);
1186 			clear_bit(R1BIO_Barrier, &r1_bio->state);
1187 			for (i=0; i < conf->raid_disks; i++)
1188 				if (r1_bio->bios[i]) {
1189 					struct bio_vec *bvec;
1190 					int j;
1191 
1192 					bio = bio_clone(r1_bio->master_bio, GFP_NOIO);
1193 					/* copy pages from the failed bio, as
1194 					 * this might be a write-behind device */
1195 					__bio_for_each_segment(bvec, bio, j, 0)
1196 						bvec->bv_page = bio_iovec_idx(r1_bio->bios[i], j)->bv_page;
1197 					bio_put(r1_bio->bios[i]);
1198 					bio->bi_sector = r1_bio->sector +
1199 						conf->mirrors[i].rdev->data_offset;
1200 					bio->bi_bdev = conf->mirrors[i].rdev->bdev;
1201 					bio->bi_end_io = raid1_end_write_request;
1202 					bio->bi_rw = WRITE;
1203 					bio->bi_private = r1_bio;
1204 					r1_bio->bios[i] = bio;
1205 					generic_make_request(bio);
1206 				}
1207 		} else {
1208 			int disk;
1209 			bio = r1_bio->bios[r1_bio->read_disk];
1210 			if ((disk=read_balance(conf, r1_bio)) == -1) {
1211 				printk(KERN_ALERT "raid1: %s: unrecoverable I/O"
1212 				       " read error for block %llu\n",
1213 				       bdevname(bio->bi_bdev,b),
1214 				       (unsigned long long)r1_bio->sector);
1215 				raid_end_bio_io(r1_bio);
1216 			} else {
1217 				r1_bio->bios[r1_bio->read_disk] = NULL;
1218 				r1_bio->read_disk = disk;
1219 				bio_put(bio);
1220 				bio = bio_clone(r1_bio->master_bio, GFP_NOIO);
1221 				r1_bio->bios[r1_bio->read_disk] = bio;
1222 				rdev = conf->mirrors[disk].rdev;
1223 				if (printk_ratelimit())
1224 					printk(KERN_ERR "raid1: %s: redirecting sector %llu to"
1225 					       " another mirror\n",
1226 					       bdevname(rdev->bdev,b),
1227 					       (unsigned long long)r1_bio->sector);
1228 				bio->bi_sector = r1_bio->sector + rdev->data_offset;
1229 				bio->bi_bdev = rdev->bdev;
1230 				bio->bi_end_io = raid1_end_read_request;
1231 				bio->bi_rw = READ;
1232 				bio->bi_private = r1_bio;
1233 				unplug = 1;
1234 				generic_make_request(bio);
1235 			}
1236 		}
1237 	}
1238 	spin_unlock_irqrestore(&conf->device_lock, flags);
1239 	if (unplug)
1240 		unplug_slaves(mddev);
1241 }
1242 
1243 
1244 static int init_resync(conf_t *conf)
1245 {
1246 	int buffs;
1247 
1248 	buffs = RESYNC_WINDOW / RESYNC_BLOCK_SIZE;
1249 	if (conf->r1buf_pool)
1250 		BUG();
1251 	conf->r1buf_pool = mempool_create(buffs, r1buf_pool_alloc, r1buf_pool_free,
1252 					  conf->poolinfo);
1253 	if (!conf->r1buf_pool)
1254 		return -ENOMEM;
1255 	conf->next_resync = 0;
1256 	return 0;
1257 }
1258 
1259 /*
1260  * perform a "sync" on one "block"
1261  *
1262  * We need to make sure that no normal I/O request - particularly write
1263  * requests - conflict with active sync requests.
1264  *
1265  * This is achieved by tracking pending requests and a 'barrier' concept
1266  * that can be installed to exclude normal IO requests.
1267  */
1268 
1269 static sector_t sync_request(mddev_t *mddev, sector_t sector_nr, int *skipped, int go_faster)
1270 {
1271 	conf_t *conf = mddev_to_conf(mddev);
1272 	mirror_info_t *mirror;
1273 	r1bio_t *r1_bio;
1274 	struct bio *bio;
1275 	sector_t max_sector, nr_sectors;
1276 	int disk;
1277 	int i;
1278 	int wonly;
1279 	int write_targets = 0;
1280 	int sync_blocks;
1281 	int still_degraded = 0;
1282 
1283 	if (!conf->r1buf_pool)
1284 	{
1285 /*
1286 		printk("sync start - bitmap %p\n", mddev->bitmap);
1287 */
1288 		if (init_resync(conf))
1289 			return 0;
1290 	}
1291 
1292 	max_sector = mddev->size << 1;
1293 	if (sector_nr >= max_sector) {
1294 		/* If we aborted, we need to abort the
1295 		 * sync on the 'current' bitmap chunk (there will
1296 		 * only be one in raid1 resync.
1297 		 * We can find the current addess in mddev->curr_resync
1298 		 */
1299 		if (mddev->curr_resync < max_sector) /* aborted */
1300 			bitmap_end_sync(mddev->bitmap, mddev->curr_resync,
1301 						&sync_blocks, 1);
1302 		else /* completed sync */
1303 			conf->fullsync = 0;
1304 
1305 		bitmap_close_sync(mddev->bitmap);
1306 		close_sync(conf);
1307 		return 0;
1308 	}
1309 
1310 	/* before building a request, check if we can skip these blocks..
1311 	 * This call the bitmap_start_sync doesn't actually record anything
1312 	 */
1313 	if (!bitmap_start_sync(mddev->bitmap, sector_nr, &sync_blocks, 1) &&
1314 	    !conf->fullsync && !test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery)) {
1315 		/* We can skip this block, and probably several more */
1316 		*skipped = 1;
1317 		return sync_blocks;
1318 	}
1319 	/*
1320 	 * If there is non-resync activity waiting for us then
1321 	 * put in a delay to throttle resync.
1322 	 */
1323 	if (!go_faster && waitqueue_active(&conf->wait_resume))
1324 		msleep_interruptible(1000);
1325 	device_barrier(conf, sector_nr + RESYNC_SECTORS);
1326 
1327 	/*
1328 	 * If reconstructing, and >1 working disc,
1329 	 * could dedicate one to rebuild and others to
1330 	 * service read requests ..
1331 	 */
1332 	disk = conf->last_used;
1333 	/* make sure disk is operational */
1334 	wonly = disk;
1335 	while (conf->mirrors[disk].rdev == NULL ||
1336 	       !test_bit(In_sync, &conf->mirrors[disk].rdev->flags) ||
1337 	       test_bit(WriteMostly, &conf->mirrors[disk].rdev->flags)
1338 		) {
1339 		if (conf->mirrors[disk].rdev  &&
1340 		    test_bit(In_sync, &conf->mirrors[disk].rdev->flags))
1341 			wonly = disk;
1342 		if (disk <= 0)
1343 			disk = conf->raid_disks;
1344 		disk--;
1345 		if (disk == conf->last_used) {
1346 			disk = wonly;
1347 			break;
1348 		}
1349 	}
1350 	conf->last_used = disk;
1351 	atomic_inc(&conf->mirrors[disk].rdev->nr_pending);
1352 
1353 
1354 	mirror = conf->mirrors + disk;
1355 
1356 	r1_bio = mempool_alloc(conf->r1buf_pool, GFP_NOIO);
1357 
1358 	spin_lock_irq(&conf->resync_lock);
1359 	conf->nr_pending++;
1360 	spin_unlock_irq(&conf->resync_lock);
1361 
1362 	r1_bio->mddev = mddev;
1363 	r1_bio->sector = sector_nr;
1364 	r1_bio->state = 0;
1365 	set_bit(R1BIO_IsSync, &r1_bio->state);
1366 	r1_bio->read_disk = disk;
1367 
1368 	for (i=0; i < conf->raid_disks; i++) {
1369 		bio = r1_bio->bios[i];
1370 
1371 		/* take from bio_init */
1372 		bio->bi_next = NULL;
1373 		bio->bi_flags |= 1 << BIO_UPTODATE;
1374 		bio->bi_rw = 0;
1375 		bio->bi_vcnt = 0;
1376 		bio->bi_idx = 0;
1377 		bio->bi_phys_segments = 0;
1378 		bio->bi_hw_segments = 0;
1379 		bio->bi_size = 0;
1380 		bio->bi_end_io = NULL;
1381 		bio->bi_private = NULL;
1382 
1383 		if (i == disk) {
1384 			bio->bi_rw = READ;
1385 			bio->bi_end_io = end_sync_read;
1386 		} else if (conf->mirrors[i].rdev == NULL ||
1387 			   test_bit(Faulty, &conf->mirrors[i].rdev->flags)) {
1388 			still_degraded = 1;
1389 			continue;
1390 		} else if (!test_bit(In_sync, &conf->mirrors[i].rdev->flags) ||
1391 			   sector_nr + RESYNC_SECTORS > mddev->recovery_cp   ||
1392 			   test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery)) {
1393 			bio->bi_rw = WRITE;
1394 			bio->bi_end_io = end_sync_write;
1395 			write_targets ++;
1396 		} else
1397 			/* no need to read or write here */
1398 			continue;
1399 		bio->bi_sector = sector_nr + conf->mirrors[i].rdev->data_offset;
1400 		bio->bi_bdev = conf->mirrors[i].rdev->bdev;
1401 		bio->bi_private = r1_bio;
1402 	}
1403 
1404 	if (write_targets == 0) {
1405 		/* There is nowhere to write, so all non-sync
1406 		 * drives must be failed - so we are finished
1407 		 */
1408 		sector_t rv = max_sector - sector_nr;
1409 		*skipped = 1;
1410 		put_buf(r1_bio);
1411 		rdev_dec_pending(conf->mirrors[disk].rdev, mddev);
1412 		return rv;
1413 	}
1414 
1415 	nr_sectors = 0;
1416 	sync_blocks = 0;
1417 	do {
1418 		struct page *page;
1419 		int len = PAGE_SIZE;
1420 		if (sector_nr + (len>>9) > max_sector)
1421 			len = (max_sector - sector_nr) << 9;
1422 		if (len == 0)
1423 			break;
1424 		if (sync_blocks == 0) {
1425 			if (!bitmap_start_sync(mddev->bitmap, sector_nr,
1426 					       &sync_blocks, still_degraded) &&
1427 			    !conf->fullsync &&
1428 			    !test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery))
1429 				break;
1430 			if (sync_blocks < (PAGE_SIZE>>9))
1431 				BUG();
1432 			if (len > (sync_blocks<<9))
1433 				len = sync_blocks<<9;
1434 		}
1435 
1436 		for (i=0 ; i < conf->raid_disks; i++) {
1437 			bio = r1_bio->bios[i];
1438 			if (bio->bi_end_io) {
1439 				page = r1_bio->bios[0]->bi_io_vec[bio->bi_vcnt].bv_page;
1440 				if (bio_add_page(bio, page, len, 0) == 0) {
1441 					/* stop here */
1442 					r1_bio->bios[0]->bi_io_vec[bio->bi_vcnt].bv_page = page;
1443 					while (i > 0) {
1444 						i--;
1445 						bio = r1_bio->bios[i];
1446 						if (bio->bi_end_io==NULL)
1447 							continue;
1448 						/* remove last page from this bio */
1449 						bio->bi_vcnt--;
1450 						bio->bi_size -= len;
1451 						bio->bi_flags &= ~(1<< BIO_SEG_VALID);
1452 					}
1453 					goto bio_full;
1454 				}
1455 			}
1456 		}
1457 		nr_sectors += len>>9;
1458 		sector_nr += len>>9;
1459 		sync_blocks -= (len>>9);
1460 	} while (r1_bio->bios[disk]->bi_vcnt < RESYNC_PAGES);
1461  bio_full:
1462 	bio = r1_bio->bios[disk];
1463 	r1_bio->sectors = nr_sectors;
1464 
1465 	md_sync_acct(mirror->rdev->bdev, nr_sectors);
1466 
1467 	generic_make_request(bio);
1468 
1469 	return nr_sectors;
1470 }
1471 
1472 static int run(mddev_t *mddev)
1473 {
1474 	conf_t *conf;
1475 	int i, j, disk_idx;
1476 	mirror_info_t *disk;
1477 	mdk_rdev_t *rdev;
1478 	struct list_head *tmp;
1479 
1480 	if (mddev->level != 1) {
1481 		printk("raid1: %s: raid level not set to mirroring (%d)\n",
1482 		       mdname(mddev), mddev->level);
1483 		goto out;
1484 	}
1485 	/*
1486 	 * copy the already verified devices into our private RAID1
1487 	 * bookkeeping area. [whatever we allocate in run(),
1488 	 * should be freed in stop()]
1489 	 */
1490 	conf = kmalloc(sizeof(conf_t), GFP_KERNEL);
1491 	mddev->private = conf;
1492 	if (!conf)
1493 		goto out_no_mem;
1494 
1495 	memset(conf, 0, sizeof(*conf));
1496 	conf->mirrors = kmalloc(sizeof(struct mirror_info)*mddev->raid_disks,
1497 				 GFP_KERNEL);
1498 	if (!conf->mirrors)
1499 		goto out_no_mem;
1500 
1501 	memset(conf->mirrors, 0, sizeof(struct mirror_info)*mddev->raid_disks);
1502 
1503 	conf->poolinfo = kmalloc(sizeof(*conf->poolinfo), GFP_KERNEL);
1504 	if (!conf->poolinfo)
1505 		goto out_no_mem;
1506 	conf->poolinfo->mddev = mddev;
1507 	conf->poolinfo->raid_disks = mddev->raid_disks;
1508 	conf->r1bio_pool = mempool_create(NR_RAID1_BIOS, r1bio_pool_alloc,
1509 					  r1bio_pool_free,
1510 					  conf->poolinfo);
1511 	if (!conf->r1bio_pool)
1512 		goto out_no_mem;
1513 
1514 	ITERATE_RDEV(mddev, rdev, tmp) {
1515 		disk_idx = rdev->raid_disk;
1516 		if (disk_idx >= mddev->raid_disks
1517 		    || disk_idx < 0)
1518 			continue;
1519 		disk = conf->mirrors + disk_idx;
1520 
1521 		disk->rdev = rdev;
1522 
1523 		blk_queue_stack_limits(mddev->queue,
1524 				       rdev->bdev->bd_disk->queue);
1525 		/* as we don't honour merge_bvec_fn, we must never risk
1526 		 * violating it, so limit ->max_sector to one PAGE, as
1527 		 * a one page request is never in violation.
1528 		 */
1529 		if (rdev->bdev->bd_disk->queue->merge_bvec_fn &&
1530 		    mddev->queue->max_sectors > (PAGE_SIZE>>9))
1531 			blk_queue_max_sectors(mddev->queue, PAGE_SIZE>>9);
1532 
1533 		disk->head_position = 0;
1534 		if (!test_bit(Faulty, &rdev->flags) && test_bit(In_sync, &rdev->flags))
1535 			conf->working_disks++;
1536 	}
1537 	conf->raid_disks = mddev->raid_disks;
1538 	conf->mddev = mddev;
1539 	spin_lock_init(&conf->device_lock);
1540 	INIT_LIST_HEAD(&conf->retry_list);
1541 	if (conf->working_disks == 1)
1542 		mddev->recovery_cp = MaxSector;
1543 
1544 	spin_lock_init(&conf->resync_lock);
1545 	init_waitqueue_head(&conf->wait_idle);
1546 	init_waitqueue_head(&conf->wait_resume);
1547 
1548 	bio_list_init(&conf->pending_bio_list);
1549 	bio_list_init(&conf->flushing_bio_list);
1550 
1551 	if (!conf->working_disks) {
1552 		printk(KERN_ERR "raid1: no operational mirrors for %s\n",
1553 			mdname(mddev));
1554 		goto out_free_conf;
1555 	}
1556 
1557 	mddev->degraded = 0;
1558 	for (i = 0; i < conf->raid_disks; i++) {
1559 
1560 		disk = conf->mirrors + i;
1561 
1562 		if (!disk->rdev) {
1563 			disk->head_position = 0;
1564 			mddev->degraded++;
1565 		}
1566 	}
1567 
1568 	/*
1569 	 * find the first working one and use it as a starting point
1570 	 * to read balancing.
1571 	 */
1572 	for (j = 0; j < conf->raid_disks &&
1573 		     (!conf->mirrors[j].rdev ||
1574 		      !test_bit(In_sync, &conf->mirrors[j].rdev->flags)) ; j++)
1575 		/* nothing */;
1576 	conf->last_used = j;
1577 
1578 
1579 	mddev->thread = md_register_thread(raid1d, mddev, "%s_raid1");
1580 	if (!mddev->thread) {
1581 		printk(KERN_ERR
1582 		       "raid1: couldn't allocate thread for %s\n",
1583 		       mdname(mddev));
1584 		goto out_free_conf;
1585 	}
1586 	if (mddev->bitmap) mddev->thread->timeout = mddev->bitmap->daemon_sleep * HZ;
1587 
1588 	printk(KERN_INFO
1589 		"raid1: raid set %s active with %d out of %d mirrors\n",
1590 		mdname(mddev), mddev->raid_disks - mddev->degraded,
1591 		mddev->raid_disks);
1592 	/*
1593 	 * Ok, everything is just fine now
1594 	 */
1595 	mddev->array_size = mddev->size;
1596 
1597 	mddev->queue->unplug_fn = raid1_unplug;
1598 	mddev->queue->issue_flush_fn = raid1_issue_flush;
1599 
1600 	return 0;
1601 
1602 out_no_mem:
1603 	printk(KERN_ERR "raid1: couldn't allocate memory for %s\n",
1604 	       mdname(mddev));
1605 
1606 out_free_conf:
1607 	if (conf) {
1608 		if (conf->r1bio_pool)
1609 			mempool_destroy(conf->r1bio_pool);
1610 		kfree(conf->mirrors);
1611 		kfree(conf->poolinfo);
1612 		kfree(conf);
1613 		mddev->private = NULL;
1614 	}
1615 out:
1616 	return -EIO;
1617 }
1618 
1619 static int stop(mddev_t *mddev)
1620 {
1621 	conf_t *conf = mddev_to_conf(mddev);
1622 	struct bitmap *bitmap = mddev->bitmap;
1623 	int behind_wait = 0;
1624 
1625 	/* wait for behind writes to complete */
1626 	while (bitmap && atomic_read(&bitmap->behind_writes) > 0) {
1627 		behind_wait++;
1628 		printk(KERN_INFO "raid1: behind writes in progress on device %s, waiting to stop (%d)\n", mdname(mddev), behind_wait);
1629 		set_current_state(TASK_UNINTERRUPTIBLE);
1630 		schedule_timeout(HZ); /* wait a second */
1631 		/* need to kick something here to make sure I/O goes? */
1632 	}
1633 
1634 	md_unregister_thread(mddev->thread);
1635 	mddev->thread = NULL;
1636 	blk_sync_queue(mddev->queue); /* the unplug fn references 'conf'*/
1637 	if (conf->r1bio_pool)
1638 		mempool_destroy(conf->r1bio_pool);
1639 	kfree(conf->mirrors);
1640 	kfree(conf->poolinfo);
1641 	kfree(conf);
1642 	mddev->private = NULL;
1643 	return 0;
1644 }
1645 
1646 static int raid1_resize(mddev_t *mddev, sector_t sectors)
1647 {
1648 	/* no resync is happening, and there is enough space
1649 	 * on all devices, so we can resize.
1650 	 * We need to make sure resync covers any new space.
1651 	 * If the array is shrinking we should possibly wait until
1652 	 * any io in the removed space completes, but it hardly seems
1653 	 * worth it.
1654 	 */
1655 	mddev->array_size = sectors>>1;
1656 	set_capacity(mddev->gendisk, mddev->array_size << 1);
1657 	mddev->changed = 1;
1658 	if (mddev->array_size > mddev->size && mddev->recovery_cp == MaxSector) {
1659 		mddev->recovery_cp = mddev->size << 1;
1660 		set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
1661 	}
1662 	mddev->size = mddev->array_size;
1663 	mddev->resync_max_sectors = sectors;
1664 	return 0;
1665 }
1666 
1667 static int raid1_reshape(mddev_t *mddev, int raid_disks)
1668 {
1669 	/* We need to:
1670 	 * 1/ resize the r1bio_pool
1671 	 * 2/ resize conf->mirrors
1672 	 *
1673 	 * We allocate a new r1bio_pool if we can.
1674 	 * Then raise a device barrier and wait until all IO stops.
1675 	 * Then resize conf->mirrors and swap in the new r1bio pool.
1676 	 *
1677 	 * At the same time, we "pack" the devices so that all the missing
1678 	 * devices have the higher raid_disk numbers.
1679 	 */
1680 	mempool_t *newpool, *oldpool;
1681 	struct pool_info *newpoolinfo;
1682 	mirror_info_t *newmirrors;
1683 	conf_t *conf = mddev_to_conf(mddev);
1684 	int cnt;
1685 
1686 	int d, d2;
1687 
1688 	if (raid_disks < conf->raid_disks) {
1689 		cnt=0;
1690 		for (d= 0; d < conf->raid_disks; d++)
1691 			if (conf->mirrors[d].rdev)
1692 				cnt++;
1693 		if (cnt > raid_disks)
1694 			return -EBUSY;
1695 	}
1696 
1697 	newpoolinfo = kmalloc(sizeof(*newpoolinfo), GFP_KERNEL);
1698 	if (!newpoolinfo)
1699 		return -ENOMEM;
1700 	newpoolinfo->mddev = mddev;
1701 	newpoolinfo->raid_disks = raid_disks;
1702 
1703 	newpool = mempool_create(NR_RAID1_BIOS, r1bio_pool_alloc,
1704 				 r1bio_pool_free, newpoolinfo);
1705 	if (!newpool) {
1706 		kfree(newpoolinfo);
1707 		return -ENOMEM;
1708 	}
1709 	newmirrors = kmalloc(sizeof(struct mirror_info) * raid_disks, GFP_KERNEL);
1710 	if (!newmirrors) {
1711 		kfree(newpoolinfo);
1712 		mempool_destroy(newpool);
1713 		return -ENOMEM;
1714 	}
1715 	memset(newmirrors, 0, sizeof(struct mirror_info)*raid_disks);
1716 
1717 	spin_lock_irq(&conf->resync_lock);
1718 	conf->barrier++;
1719 	wait_event_lock_irq(conf->wait_idle, !conf->nr_pending,
1720 			    conf->resync_lock, raid1_unplug(mddev->queue));
1721 	spin_unlock_irq(&conf->resync_lock);
1722 
1723 	/* ok, everything is stopped */
1724 	oldpool = conf->r1bio_pool;
1725 	conf->r1bio_pool = newpool;
1726 
1727 	for (d=d2=0; d < conf->raid_disks; d++)
1728 		if (conf->mirrors[d].rdev) {
1729 			conf->mirrors[d].rdev->raid_disk = d2;
1730 			newmirrors[d2++].rdev = conf->mirrors[d].rdev;
1731 		}
1732 	kfree(conf->mirrors);
1733 	conf->mirrors = newmirrors;
1734 	kfree(conf->poolinfo);
1735 	conf->poolinfo = newpoolinfo;
1736 
1737 	mddev->degraded += (raid_disks - conf->raid_disks);
1738 	conf->raid_disks = mddev->raid_disks = raid_disks;
1739 
1740 	conf->last_used = 0; /* just make sure it is in-range */
1741 	spin_lock_irq(&conf->resync_lock);
1742 	conf->barrier--;
1743 	spin_unlock_irq(&conf->resync_lock);
1744 	wake_up(&conf->wait_resume);
1745 	wake_up(&conf->wait_idle);
1746 
1747 
1748 	set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
1749 	md_wakeup_thread(mddev->thread);
1750 
1751 	mempool_destroy(oldpool);
1752 	return 0;
1753 }
1754 
1755 static void raid1_quiesce(mddev_t *mddev, int state)
1756 {
1757 	conf_t *conf = mddev_to_conf(mddev);
1758 
1759 	switch(state) {
1760 	case 1:
1761 		spin_lock_irq(&conf->resync_lock);
1762 		conf->barrier++;
1763 		wait_event_lock_irq(conf->wait_idle, !conf->nr_pending,
1764 				    conf->resync_lock, raid1_unplug(mddev->queue));
1765 		spin_unlock_irq(&conf->resync_lock);
1766 		break;
1767 	case 0:
1768 		spin_lock_irq(&conf->resync_lock);
1769 		conf->barrier--;
1770 		spin_unlock_irq(&conf->resync_lock);
1771 		wake_up(&conf->wait_resume);
1772 		wake_up(&conf->wait_idle);
1773 		break;
1774 	}
1775 	if (mddev->thread) {
1776 		if (mddev->bitmap)
1777 			mddev->thread->timeout = mddev->bitmap->daemon_sleep * HZ;
1778 		else
1779 			mddev->thread->timeout = MAX_SCHEDULE_TIMEOUT;
1780 		md_wakeup_thread(mddev->thread);
1781 	}
1782 }
1783 
1784 
1785 static mdk_personality_t raid1_personality =
1786 {
1787 	.name		= "raid1",
1788 	.owner		= THIS_MODULE,
1789 	.make_request	= make_request,
1790 	.run		= run,
1791 	.stop		= stop,
1792 	.status		= status,
1793 	.error_handler	= error,
1794 	.hot_add_disk	= raid1_add_disk,
1795 	.hot_remove_disk= raid1_remove_disk,
1796 	.spare_active	= raid1_spare_active,
1797 	.sync_request	= sync_request,
1798 	.resize		= raid1_resize,
1799 	.reshape	= raid1_reshape,
1800 	.quiesce	= raid1_quiesce,
1801 };
1802 
1803 static int __init raid_init(void)
1804 {
1805 	return register_md_personality(RAID1, &raid1_personality);
1806 }
1807 
1808 static void raid_exit(void)
1809 {
1810 	unregister_md_personality(RAID1);
1811 }
1812 
1813 module_init(raid_init);
1814 module_exit(raid_exit);
1815 MODULE_LICENSE("GPL");
1816 MODULE_ALIAS("md-personality-3"); /* RAID1 */
1817