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