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