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