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