raid5: refactor handle_stripe5 and handle_stripe6 (v3)
[linux-block.git] / drivers / md / raid5.c
1 /*
2  * raid5.c : Multiple Devices driver for Linux
3  *         Copyright (C) 1996, 1997 Ingo Molnar, Miguel de Icaza, Gadi Oxman
4  *         Copyright (C) 1999, 2000 Ingo Molnar
5  *         Copyright (C) 2002, 2003 H. Peter Anvin
6  *
7  * RAID-4/5/6 management functions.
8  * Thanks to Penguin Computing for making the RAID-6 development possible
9  * by donating a test server!
10  *
11  * This program is free software; you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation; either version 2, or (at your option)
14  * any later version.
15  *
16  * You should have received a copy of the GNU General Public License
17  * (for example /usr/src/linux/COPYING); if not, write to the Free
18  * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19  */
20
21 /*
22  * BITMAP UNPLUGGING:
23  *
24  * The sequencing for updating the bitmap reliably is a little
25  * subtle (and I got it wrong the first time) so it deserves some
26  * explanation.
27  *
28  * We group bitmap updates into batches.  Each batch has a number.
29  * We may write out several batches at once, but that isn't very important.
30  * conf->bm_write is the number of the last batch successfully written.
31  * conf->bm_flush is the number of the last batch that was closed to
32  *    new additions.
33  * When we discover that we will need to write to any block in a stripe
34  * (in add_stripe_bio) we update the in-memory bitmap and record in sh->bm_seq
35  * the number of the batch it will be in. This is bm_flush+1.
36  * When we are ready to do a write, if that batch hasn't been written yet,
37  *   we plug the array and queue the stripe for later.
38  * When an unplug happens, we increment bm_flush, thus closing the current
39  *   batch.
40  * When we notice that bm_flush > bm_write, we write out all pending updates
41  * to the bitmap, and advance bm_write to where bm_flush was.
42  * This may occasionally write a bit out twice, but is sure never to
43  * miss any bits.
44  */
45
46 #include <linux/module.h>
47 #include <linux/slab.h>
48 #include <linux/highmem.h>
49 #include <linux/bitops.h>
50 #include <linux/kthread.h>
51 #include <asm/atomic.h>
52 #include "raid6.h"
53
54 #include <linux/raid/bitmap.h>
55
56 /*
57  * Stripe cache
58  */
59
60 #define NR_STRIPES              256
61 #define STRIPE_SIZE             PAGE_SIZE
62 #define STRIPE_SHIFT            (PAGE_SHIFT - 9)
63 #define STRIPE_SECTORS          (STRIPE_SIZE>>9)
64 #define IO_THRESHOLD            1
65 #define NR_HASH                 (PAGE_SIZE / sizeof(struct hlist_head))
66 #define HASH_MASK               (NR_HASH - 1)
67
68 #define stripe_hash(conf, sect) (&((conf)->stripe_hashtbl[((sect) >> STRIPE_SHIFT) & HASH_MASK]))
69
70 /* bio's attached to a stripe+device for I/O are linked together in bi_sector
71  * order without overlap.  There may be several bio's per stripe+device, and
72  * a bio could span several devices.
73  * When walking this list for a particular stripe+device, we must never proceed
74  * beyond a bio that extends past this device, as the next bio might no longer
75  * be valid.
76  * This macro is used to determine the 'next' bio in the list, given the sector
77  * of the current stripe+device
78  */
79 #define r5_next_bio(bio, sect) ( ( (bio)->bi_sector + ((bio)->bi_size>>9) < sect + STRIPE_SECTORS) ? (bio)->bi_next : NULL)
80 /*
81  * The following can be used to debug the driver
82  */
83 #define RAID5_DEBUG     0
84 #define RAID5_PARANOIA  1
85 #if RAID5_PARANOIA && defined(CONFIG_SMP)
86 # define CHECK_DEVLOCK() assert_spin_locked(&conf->device_lock)
87 #else
88 # define CHECK_DEVLOCK()
89 #endif
90
91 #define PRINTK(x...) ((void)(RAID5_DEBUG && printk(x)))
92 #if RAID5_DEBUG
93 #define inline
94 #define __inline__
95 #endif
96
97 #if !RAID6_USE_EMPTY_ZERO_PAGE
98 /* In .bss so it's zeroed */
99 const char raid6_empty_zero_page[PAGE_SIZE] __attribute__((aligned(256)));
100 #endif
101
102 static inline int raid6_next_disk(int disk, int raid_disks)
103 {
104         disk++;
105         return (disk < raid_disks) ? disk : 0;
106 }
107
108 static void return_io(struct bio *return_bi)
109 {
110         struct bio *bi = return_bi;
111         while (bi) {
112                 int bytes = bi->bi_size;
113
114                 return_bi = bi->bi_next;
115                 bi->bi_next = NULL;
116                 bi->bi_size = 0;
117                 bi->bi_end_io(bi, bytes,
118                               test_bit(BIO_UPTODATE, &bi->bi_flags)
119                                 ? 0 : -EIO);
120                 bi = return_bi;
121         }
122 }
123
124 static void print_raid5_conf (raid5_conf_t *conf);
125
126 static void __release_stripe(raid5_conf_t *conf, struct stripe_head *sh)
127 {
128         if (atomic_dec_and_test(&sh->count)) {
129                 BUG_ON(!list_empty(&sh->lru));
130                 BUG_ON(atomic_read(&conf->active_stripes)==0);
131                 if (test_bit(STRIPE_HANDLE, &sh->state)) {
132                         if (test_bit(STRIPE_DELAYED, &sh->state)) {
133                                 list_add_tail(&sh->lru, &conf->delayed_list);
134                                 blk_plug_device(conf->mddev->queue);
135                         } else if (test_bit(STRIPE_BIT_DELAY, &sh->state) &&
136                                    sh->bm_seq - conf->seq_write > 0) {
137                                 list_add_tail(&sh->lru, &conf->bitmap_list);
138                                 blk_plug_device(conf->mddev->queue);
139                         } else {
140                                 clear_bit(STRIPE_BIT_DELAY, &sh->state);
141                                 list_add_tail(&sh->lru, &conf->handle_list);
142                         }
143                         md_wakeup_thread(conf->mddev->thread);
144                 } else {
145                         if (test_and_clear_bit(STRIPE_PREREAD_ACTIVE, &sh->state)) {
146                                 atomic_dec(&conf->preread_active_stripes);
147                                 if (atomic_read(&conf->preread_active_stripes) < IO_THRESHOLD)
148                                         md_wakeup_thread(conf->mddev->thread);
149                         }
150                         atomic_dec(&conf->active_stripes);
151                         if (!test_bit(STRIPE_EXPANDING, &sh->state)) {
152                                 list_add_tail(&sh->lru, &conf->inactive_list);
153                                 wake_up(&conf->wait_for_stripe);
154                                 if (conf->retry_read_aligned)
155                                         md_wakeup_thread(conf->mddev->thread);
156                         }
157                 }
158         }
159 }
160 static void release_stripe(struct stripe_head *sh)
161 {
162         raid5_conf_t *conf = sh->raid_conf;
163         unsigned long flags;
164
165         spin_lock_irqsave(&conf->device_lock, flags);
166         __release_stripe(conf, sh);
167         spin_unlock_irqrestore(&conf->device_lock, flags);
168 }
169
170 static inline void remove_hash(struct stripe_head *sh)
171 {
172         PRINTK("remove_hash(), stripe %llu\n", (unsigned long long)sh->sector);
173
174         hlist_del_init(&sh->hash);
175 }
176
177 static inline void insert_hash(raid5_conf_t *conf, struct stripe_head *sh)
178 {
179         struct hlist_head *hp = stripe_hash(conf, sh->sector);
180
181         PRINTK("insert_hash(), stripe %llu\n", (unsigned long long)sh->sector);
182
183         CHECK_DEVLOCK();
184         hlist_add_head(&sh->hash, hp);
185 }
186
187
188 /* find an idle stripe, make sure it is unhashed, and return it. */
189 static struct stripe_head *get_free_stripe(raid5_conf_t *conf)
190 {
191         struct stripe_head *sh = NULL;
192         struct list_head *first;
193
194         CHECK_DEVLOCK();
195         if (list_empty(&conf->inactive_list))
196                 goto out;
197         first = conf->inactive_list.next;
198         sh = list_entry(first, struct stripe_head, lru);
199         list_del_init(first);
200         remove_hash(sh);
201         atomic_inc(&conf->active_stripes);
202 out:
203         return sh;
204 }
205
206 static void shrink_buffers(struct stripe_head *sh, int num)
207 {
208         struct page *p;
209         int i;
210
211         for (i=0; i<num ; i++) {
212                 p = sh->dev[i].page;
213                 if (!p)
214                         continue;
215                 sh->dev[i].page = NULL;
216                 put_page(p);
217         }
218 }
219
220 static int grow_buffers(struct stripe_head *sh, int num)
221 {
222         int i;
223
224         for (i=0; i<num; i++) {
225                 struct page *page;
226
227                 if (!(page = alloc_page(GFP_KERNEL))) {
228                         return 1;
229                 }
230                 sh->dev[i].page = page;
231         }
232         return 0;
233 }
234
235 static void raid5_build_block (struct stripe_head *sh, int i);
236
237 static void init_stripe(struct stripe_head *sh, sector_t sector, int pd_idx, int disks)
238 {
239         raid5_conf_t *conf = sh->raid_conf;
240         int i;
241
242         BUG_ON(atomic_read(&sh->count) != 0);
243         BUG_ON(test_bit(STRIPE_HANDLE, &sh->state));
244         
245         CHECK_DEVLOCK();
246         PRINTK("init_stripe called, stripe %llu\n", 
247                 (unsigned long long)sh->sector);
248
249         remove_hash(sh);
250
251         sh->sector = sector;
252         sh->pd_idx = pd_idx;
253         sh->state = 0;
254
255         sh->disks = disks;
256
257         for (i = sh->disks; i--; ) {
258                 struct r5dev *dev = &sh->dev[i];
259
260                 if (dev->toread || dev->towrite || dev->written ||
261                     test_bit(R5_LOCKED, &dev->flags)) {
262                         printk("sector=%llx i=%d %p %p %p %d\n",
263                                (unsigned long long)sh->sector, i, dev->toread,
264                                dev->towrite, dev->written,
265                                test_bit(R5_LOCKED, &dev->flags));
266                         BUG();
267                 }
268                 dev->flags = 0;
269                 raid5_build_block(sh, i);
270         }
271         insert_hash(conf, sh);
272 }
273
274 static struct stripe_head *__find_stripe(raid5_conf_t *conf, sector_t sector, int disks)
275 {
276         struct stripe_head *sh;
277         struct hlist_node *hn;
278
279         CHECK_DEVLOCK();
280         PRINTK("__find_stripe, sector %llu\n", (unsigned long long)sector);
281         hlist_for_each_entry(sh, hn, stripe_hash(conf, sector), hash)
282                 if (sh->sector == sector && sh->disks == disks)
283                         return sh;
284         PRINTK("__stripe %llu not in cache\n", (unsigned long long)sector);
285         return NULL;
286 }
287
288 static void unplug_slaves(mddev_t *mddev);
289 static void raid5_unplug_device(request_queue_t *q);
290
291 static struct stripe_head *get_active_stripe(raid5_conf_t *conf, sector_t sector, int disks,
292                                              int pd_idx, int noblock)
293 {
294         struct stripe_head *sh;
295
296         PRINTK("get_stripe, sector %llu\n", (unsigned long long)sector);
297
298         spin_lock_irq(&conf->device_lock);
299
300         do {
301                 wait_event_lock_irq(conf->wait_for_stripe,
302                                     conf->quiesce == 0,
303                                     conf->device_lock, /* nothing */);
304                 sh = __find_stripe(conf, sector, disks);
305                 if (!sh) {
306                         if (!conf->inactive_blocked)
307                                 sh = get_free_stripe(conf);
308                         if (noblock && sh == NULL)
309                                 break;
310                         if (!sh) {
311                                 conf->inactive_blocked = 1;
312                                 wait_event_lock_irq(conf->wait_for_stripe,
313                                                     !list_empty(&conf->inactive_list) &&
314                                                     (atomic_read(&conf->active_stripes)
315                                                      < (conf->max_nr_stripes *3/4)
316                                                      || !conf->inactive_blocked),
317                                                     conf->device_lock,
318                                                     raid5_unplug_device(conf->mddev->queue)
319                                         );
320                                 conf->inactive_blocked = 0;
321                         } else
322                                 init_stripe(sh, sector, pd_idx, disks);
323                 } else {
324                         if (atomic_read(&sh->count)) {
325                           BUG_ON(!list_empty(&sh->lru));
326                         } else {
327                                 if (!test_bit(STRIPE_HANDLE, &sh->state))
328                                         atomic_inc(&conf->active_stripes);
329                                 if (list_empty(&sh->lru) &&
330                                     !test_bit(STRIPE_EXPANDING, &sh->state))
331                                         BUG();
332                                 list_del_init(&sh->lru);
333                         }
334                 }
335         } while (sh == NULL);
336
337         if (sh)
338                 atomic_inc(&sh->count);
339
340         spin_unlock_irq(&conf->device_lock);
341         return sh;
342 }
343
344 static int grow_one_stripe(raid5_conf_t *conf)
345 {
346         struct stripe_head *sh;
347         sh = kmem_cache_alloc(conf->slab_cache, GFP_KERNEL);
348         if (!sh)
349                 return 0;
350         memset(sh, 0, sizeof(*sh) + (conf->raid_disks-1)*sizeof(struct r5dev));
351         sh->raid_conf = conf;
352         spin_lock_init(&sh->lock);
353
354         if (grow_buffers(sh, conf->raid_disks)) {
355                 shrink_buffers(sh, conf->raid_disks);
356                 kmem_cache_free(conf->slab_cache, sh);
357                 return 0;
358         }
359         sh->disks = conf->raid_disks;
360         /* we just created an active stripe so... */
361         atomic_set(&sh->count, 1);
362         atomic_inc(&conf->active_stripes);
363         INIT_LIST_HEAD(&sh->lru);
364         release_stripe(sh);
365         return 1;
366 }
367
368 static int grow_stripes(raid5_conf_t *conf, int num)
369 {
370         struct kmem_cache *sc;
371         int devs = conf->raid_disks;
372
373         sprintf(conf->cache_name[0], "raid5-%s", mdname(conf->mddev));
374         sprintf(conf->cache_name[1], "raid5-%s-alt", mdname(conf->mddev));
375         conf->active_name = 0;
376         sc = kmem_cache_create(conf->cache_name[conf->active_name],
377                                sizeof(struct stripe_head)+(devs-1)*sizeof(struct r5dev),
378                                0, 0, NULL, NULL);
379         if (!sc)
380                 return 1;
381         conf->slab_cache = sc;
382         conf->pool_size = devs;
383         while (num--)
384                 if (!grow_one_stripe(conf))
385                         return 1;
386         return 0;
387 }
388
389 #ifdef CONFIG_MD_RAID5_RESHAPE
390 static int resize_stripes(raid5_conf_t *conf, int newsize)
391 {
392         /* Make all the stripes able to hold 'newsize' devices.
393          * New slots in each stripe get 'page' set to a new page.
394          *
395          * This happens in stages:
396          * 1/ create a new kmem_cache and allocate the required number of
397          *    stripe_heads.
398          * 2/ gather all the old stripe_heads and tranfer the pages across
399          *    to the new stripe_heads.  This will have the side effect of
400          *    freezing the array as once all stripe_heads have been collected,
401          *    no IO will be possible.  Old stripe heads are freed once their
402          *    pages have been transferred over, and the old kmem_cache is
403          *    freed when all stripes are done.
404          * 3/ reallocate conf->disks to be suitable bigger.  If this fails,
405          *    we simple return a failre status - no need to clean anything up.
406          * 4/ allocate new pages for the new slots in the new stripe_heads.
407          *    If this fails, we don't bother trying the shrink the
408          *    stripe_heads down again, we just leave them as they are.
409          *    As each stripe_head is processed the new one is released into
410          *    active service.
411          *
412          * Once step2 is started, we cannot afford to wait for a write,
413          * so we use GFP_NOIO allocations.
414          */
415         struct stripe_head *osh, *nsh;
416         LIST_HEAD(newstripes);
417         struct disk_info *ndisks;
418         int err = 0;
419         struct kmem_cache *sc;
420         int i;
421
422         if (newsize <= conf->pool_size)
423                 return 0; /* never bother to shrink */
424
425         md_allow_write(conf->mddev);
426
427         /* Step 1 */
428         sc = kmem_cache_create(conf->cache_name[1-conf->active_name],
429                                sizeof(struct stripe_head)+(newsize-1)*sizeof(struct r5dev),
430                                0, 0, NULL, NULL);
431         if (!sc)
432                 return -ENOMEM;
433
434         for (i = conf->max_nr_stripes; i; i--) {
435                 nsh = kmem_cache_alloc(sc, GFP_KERNEL);
436                 if (!nsh)
437                         break;
438
439                 memset(nsh, 0, sizeof(*nsh) + (newsize-1)*sizeof(struct r5dev));
440
441                 nsh->raid_conf = conf;
442                 spin_lock_init(&nsh->lock);
443
444                 list_add(&nsh->lru, &newstripes);
445         }
446         if (i) {
447                 /* didn't get enough, give up */
448                 while (!list_empty(&newstripes)) {
449                         nsh = list_entry(newstripes.next, struct stripe_head, lru);
450                         list_del(&nsh->lru);
451                         kmem_cache_free(sc, nsh);
452                 }
453                 kmem_cache_destroy(sc);
454                 return -ENOMEM;
455         }
456         /* Step 2 - Must use GFP_NOIO now.
457          * OK, we have enough stripes, start collecting inactive
458          * stripes and copying them over
459          */
460         list_for_each_entry(nsh, &newstripes, lru) {
461                 spin_lock_irq(&conf->device_lock);
462                 wait_event_lock_irq(conf->wait_for_stripe,
463                                     !list_empty(&conf->inactive_list),
464                                     conf->device_lock,
465                                     unplug_slaves(conf->mddev)
466                         );
467                 osh = get_free_stripe(conf);
468                 spin_unlock_irq(&conf->device_lock);
469                 atomic_set(&nsh->count, 1);
470                 for(i=0; i<conf->pool_size; i++)
471                         nsh->dev[i].page = osh->dev[i].page;
472                 for( ; i<newsize; i++)
473                         nsh->dev[i].page = NULL;
474                 kmem_cache_free(conf->slab_cache, osh);
475         }
476         kmem_cache_destroy(conf->slab_cache);
477
478         /* Step 3.
479          * At this point, we are holding all the stripes so the array
480          * is completely stalled, so now is a good time to resize
481          * conf->disks.
482          */
483         ndisks = kzalloc(newsize * sizeof(struct disk_info), GFP_NOIO);
484         if (ndisks) {
485                 for (i=0; i<conf->raid_disks; i++)
486                         ndisks[i] = conf->disks[i];
487                 kfree(conf->disks);
488                 conf->disks = ndisks;
489         } else
490                 err = -ENOMEM;
491
492         /* Step 4, return new stripes to service */
493         while(!list_empty(&newstripes)) {
494                 nsh = list_entry(newstripes.next, struct stripe_head, lru);
495                 list_del_init(&nsh->lru);
496                 for (i=conf->raid_disks; i < newsize; i++)
497                         if (nsh->dev[i].page == NULL) {
498                                 struct page *p = alloc_page(GFP_NOIO);
499                                 nsh->dev[i].page = p;
500                                 if (!p)
501                                         err = -ENOMEM;
502                         }
503                 release_stripe(nsh);
504         }
505         /* critical section pass, GFP_NOIO no longer needed */
506
507         conf->slab_cache = sc;
508         conf->active_name = 1-conf->active_name;
509         conf->pool_size = newsize;
510         return err;
511 }
512 #endif
513
514 static int drop_one_stripe(raid5_conf_t *conf)
515 {
516         struct stripe_head *sh;
517
518         spin_lock_irq(&conf->device_lock);
519         sh = get_free_stripe(conf);
520         spin_unlock_irq(&conf->device_lock);
521         if (!sh)
522                 return 0;
523         BUG_ON(atomic_read(&sh->count));
524         shrink_buffers(sh, conf->pool_size);
525         kmem_cache_free(conf->slab_cache, sh);
526         atomic_dec(&conf->active_stripes);
527         return 1;
528 }
529
530 static void shrink_stripes(raid5_conf_t *conf)
531 {
532         while (drop_one_stripe(conf))
533                 ;
534
535         if (conf->slab_cache)
536                 kmem_cache_destroy(conf->slab_cache);
537         conf->slab_cache = NULL;
538 }
539
540 static int raid5_end_read_request(struct bio * bi, unsigned int bytes_done,
541                                    int error)
542 {
543         struct stripe_head *sh = bi->bi_private;
544         raid5_conf_t *conf = sh->raid_conf;
545         int disks = sh->disks, i;
546         int uptodate = test_bit(BIO_UPTODATE, &bi->bi_flags);
547         char b[BDEVNAME_SIZE];
548         mdk_rdev_t *rdev;
549
550         if (bi->bi_size)
551                 return 1;
552
553         for (i=0 ; i<disks; i++)
554                 if (bi == &sh->dev[i].req)
555                         break;
556
557         PRINTK("end_read_request %llu/%d, count: %d, uptodate %d.\n", 
558                 (unsigned long long)sh->sector, i, atomic_read(&sh->count), 
559                 uptodate);
560         if (i == disks) {
561                 BUG();
562                 return 0;
563         }
564
565         if (uptodate) {
566                 set_bit(R5_UPTODATE, &sh->dev[i].flags);
567                 if (test_bit(R5_ReadError, &sh->dev[i].flags)) {
568                         rdev = conf->disks[i].rdev;
569                         printk(KERN_INFO "raid5:%s: read error corrected (%lu sectors at %llu on %s)\n",
570                                mdname(conf->mddev), STRIPE_SECTORS,
571                                (unsigned long long)sh->sector + rdev->data_offset,
572                                bdevname(rdev->bdev, b));
573                         clear_bit(R5_ReadError, &sh->dev[i].flags);
574                         clear_bit(R5_ReWrite, &sh->dev[i].flags);
575                 }
576                 if (atomic_read(&conf->disks[i].rdev->read_errors))
577                         atomic_set(&conf->disks[i].rdev->read_errors, 0);
578         } else {
579                 const char *bdn = bdevname(conf->disks[i].rdev->bdev, b);
580                 int retry = 0;
581                 rdev = conf->disks[i].rdev;
582
583                 clear_bit(R5_UPTODATE, &sh->dev[i].flags);
584                 atomic_inc(&rdev->read_errors);
585                 if (conf->mddev->degraded)
586                         printk(KERN_WARNING "raid5:%s: read error not correctable (sector %llu on %s).\n",
587                                mdname(conf->mddev),
588                                (unsigned long long)sh->sector + rdev->data_offset,
589                                bdn);
590                 else if (test_bit(R5_ReWrite, &sh->dev[i].flags))
591                         /* Oh, no!!! */
592                         printk(KERN_WARNING "raid5:%s: read error NOT corrected!! (sector %llu on %s).\n",
593                                mdname(conf->mddev),
594                                (unsigned long long)sh->sector + rdev->data_offset,
595                                bdn);
596                 else if (atomic_read(&rdev->read_errors)
597                          > conf->max_nr_stripes)
598                         printk(KERN_WARNING
599                                "raid5:%s: Too many read errors, failing device %s.\n",
600                                mdname(conf->mddev), bdn);
601                 else
602                         retry = 1;
603                 if (retry)
604                         set_bit(R5_ReadError, &sh->dev[i].flags);
605                 else {
606                         clear_bit(R5_ReadError, &sh->dev[i].flags);
607                         clear_bit(R5_ReWrite, &sh->dev[i].flags);
608                         md_error(conf->mddev, rdev);
609                 }
610         }
611         rdev_dec_pending(conf->disks[i].rdev, conf->mddev);
612         clear_bit(R5_LOCKED, &sh->dev[i].flags);
613         set_bit(STRIPE_HANDLE, &sh->state);
614         release_stripe(sh);
615         return 0;
616 }
617
618 static int raid5_end_write_request (struct bio *bi, unsigned int bytes_done,
619                                     int error)
620 {
621         struct stripe_head *sh = bi->bi_private;
622         raid5_conf_t *conf = sh->raid_conf;
623         int disks = sh->disks, i;
624         int uptodate = test_bit(BIO_UPTODATE, &bi->bi_flags);
625
626         if (bi->bi_size)
627                 return 1;
628
629         for (i=0 ; i<disks; i++)
630                 if (bi == &sh->dev[i].req)
631                         break;
632
633         PRINTK("end_write_request %llu/%d, count %d, uptodate: %d.\n", 
634                 (unsigned long long)sh->sector, i, atomic_read(&sh->count),
635                 uptodate);
636         if (i == disks) {
637                 BUG();
638                 return 0;
639         }
640
641         if (!uptodate)
642                 md_error(conf->mddev, conf->disks[i].rdev);
643
644         rdev_dec_pending(conf->disks[i].rdev, conf->mddev);
645         
646         clear_bit(R5_LOCKED, &sh->dev[i].flags);
647         set_bit(STRIPE_HANDLE, &sh->state);
648         release_stripe(sh);
649         return 0;
650 }
651
652
653 static sector_t compute_blocknr(struct stripe_head *sh, int i);
654         
655 static void raid5_build_block (struct stripe_head *sh, int i)
656 {
657         struct r5dev *dev = &sh->dev[i];
658
659         bio_init(&dev->req);
660         dev->req.bi_io_vec = &dev->vec;
661         dev->req.bi_vcnt++;
662         dev->req.bi_max_vecs++;
663         dev->vec.bv_page = dev->page;
664         dev->vec.bv_len = STRIPE_SIZE;
665         dev->vec.bv_offset = 0;
666
667         dev->req.bi_sector = sh->sector;
668         dev->req.bi_private = sh;
669
670         dev->flags = 0;
671         dev->sector = compute_blocknr(sh, i);
672 }
673
674 static void error(mddev_t *mddev, mdk_rdev_t *rdev)
675 {
676         char b[BDEVNAME_SIZE];
677         raid5_conf_t *conf = (raid5_conf_t *) mddev->private;
678         PRINTK("raid5: error called\n");
679
680         if (!test_bit(Faulty, &rdev->flags)) {
681                 set_bit(MD_CHANGE_DEVS, &mddev->flags);
682                 if (test_and_clear_bit(In_sync, &rdev->flags)) {
683                         unsigned long flags;
684                         spin_lock_irqsave(&conf->device_lock, flags);
685                         mddev->degraded++;
686                         spin_unlock_irqrestore(&conf->device_lock, flags);
687                         /*
688                          * if recovery was running, make sure it aborts.
689                          */
690                         set_bit(MD_RECOVERY_ERR, &mddev->recovery);
691                 }
692                 set_bit(Faulty, &rdev->flags);
693                 printk (KERN_ALERT
694                         "raid5: Disk failure on %s, disabling device."
695                         " Operation continuing on %d devices\n",
696                         bdevname(rdev->bdev,b), conf->raid_disks - mddev->degraded);
697         }
698 }
699
700 /*
701  * Input: a 'big' sector number,
702  * Output: index of the data and parity disk, and the sector # in them.
703  */
704 static sector_t raid5_compute_sector(sector_t r_sector, unsigned int raid_disks,
705                         unsigned int data_disks, unsigned int * dd_idx,
706                         unsigned int * pd_idx, raid5_conf_t *conf)
707 {
708         long stripe;
709         unsigned long chunk_number;
710         unsigned int chunk_offset;
711         sector_t new_sector;
712         int sectors_per_chunk = conf->chunk_size >> 9;
713
714         /* First compute the information on this sector */
715
716         /*
717          * Compute the chunk number and the sector offset inside the chunk
718          */
719         chunk_offset = sector_div(r_sector, sectors_per_chunk);
720         chunk_number = r_sector;
721         BUG_ON(r_sector != chunk_number);
722
723         /*
724          * Compute the stripe number
725          */
726         stripe = chunk_number / data_disks;
727
728         /*
729          * Compute the data disk and parity disk indexes inside the stripe
730          */
731         *dd_idx = chunk_number % data_disks;
732
733         /*
734          * Select the parity disk based on the user selected algorithm.
735          */
736         switch(conf->level) {
737         case 4:
738                 *pd_idx = data_disks;
739                 break;
740         case 5:
741                 switch (conf->algorithm) {
742                 case ALGORITHM_LEFT_ASYMMETRIC:
743                         *pd_idx = data_disks - stripe % raid_disks;
744                         if (*dd_idx >= *pd_idx)
745                                 (*dd_idx)++;
746                         break;
747                 case ALGORITHM_RIGHT_ASYMMETRIC:
748                         *pd_idx = stripe % raid_disks;
749                         if (*dd_idx >= *pd_idx)
750                                 (*dd_idx)++;
751                         break;
752                 case ALGORITHM_LEFT_SYMMETRIC:
753                         *pd_idx = data_disks - stripe % raid_disks;
754                         *dd_idx = (*pd_idx + 1 + *dd_idx) % raid_disks;
755                         break;
756                 case ALGORITHM_RIGHT_SYMMETRIC:
757                         *pd_idx = stripe % raid_disks;
758                         *dd_idx = (*pd_idx + 1 + *dd_idx) % raid_disks;
759                         break;
760                 default:
761                         printk(KERN_ERR "raid5: unsupported algorithm %d\n",
762                                 conf->algorithm);
763                 }
764                 break;
765         case 6:
766
767                 /**** FIX THIS ****/
768                 switch (conf->algorithm) {
769                 case ALGORITHM_LEFT_ASYMMETRIC:
770                         *pd_idx = raid_disks - 1 - (stripe % raid_disks);
771                         if (*pd_idx == raid_disks-1)
772                                 (*dd_idx)++;    /* Q D D D P */
773                         else if (*dd_idx >= *pd_idx)
774                                 (*dd_idx) += 2; /* D D P Q D */
775                         break;
776                 case ALGORITHM_RIGHT_ASYMMETRIC:
777                         *pd_idx = stripe % raid_disks;
778                         if (*pd_idx == raid_disks-1)
779                                 (*dd_idx)++;    /* Q D D D P */
780                         else if (*dd_idx >= *pd_idx)
781                                 (*dd_idx) += 2; /* D D P Q D */
782                         break;
783                 case ALGORITHM_LEFT_SYMMETRIC:
784                         *pd_idx = raid_disks - 1 - (stripe % raid_disks);
785                         *dd_idx = (*pd_idx + 2 + *dd_idx) % raid_disks;
786                         break;
787                 case ALGORITHM_RIGHT_SYMMETRIC:
788                         *pd_idx = stripe % raid_disks;
789                         *dd_idx = (*pd_idx + 2 + *dd_idx) % raid_disks;
790                         break;
791                 default:
792                         printk (KERN_CRIT "raid6: unsupported algorithm %d\n",
793                                 conf->algorithm);
794                 }
795                 break;
796         }
797
798         /*
799          * Finally, compute the new sector number
800          */
801         new_sector = (sector_t)stripe * sectors_per_chunk + chunk_offset;
802         return new_sector;
803 }
804
805
806 static sector_t compute_blocknr(struct stripe_head *sh, int i)
807 {
808         raid5_conf_t *conf = sh->raid_conf;
809         int raid_disks = sh->disks;
810         int data_disks = raid_disks - conf->max_degraded;
811         sector_t new_sector = sh->sector, check;
812         int sectors_per_chunk = conf->chunk_size >> 9;
813         sector_t stripe;
814         int chunk_offset;
815         int chunk_number, dummy1, dummy2, dd_idx = i;
816         sector_t r_sector;
817
818
819         chunk_offset = sector_div(new_sector, sectors_per_chunk);
820         stripe = new_sector;
821         BUG_ON(new_sector != stripe);
822
823         if (i == sh->pd_idx)
824                 return 0;
825         switch(conf->level) {
826         case 4: break;
827         case 5:
828                 switch (conf->algorithm) {
829                 case ALGORITHM_LEFT_ASYMMETRIC:
830                 case ALGORITHM_RIGHT_ASYMMETRIC:
831                         if (i > sh->pd_idx)
832                                 i--;
833                         break;
834                 case ALGORITHM_LEFT_SYMMETRIC:
835                 case ALGORITHM_RIGHT_SYMMETRIC:
836                         if (i < sh->pd_idx)
837                                 i += raid_disks;
838                         i -= (sh->pd_idx + 1);
839                         break;
840                 default:
841                         printk(KERN_ERR "raid5: unsupported algorithm %d\n",
842                                conf->algorithm);
843                 }
844                 break;
845         case 6:
846                 if (i == raid6_next_disk(sh->pd_idx, raid_disks))
847                         return 0; /* It is the Q disk */
848                 switch (conf->algorithm) {
849                 case ALGORITHM_LEFT_ASYMMETRIC:
850                 case ALGORITHM_RIGHT_ASYMMETRIC:
851                         if (sh->pd_idx == raid_disks-1)
852                                 i--;    /* Q D D D P */
853                         else if (i > sh->pd_idx)
854                                 i -= 2; /* D D P Q D */
855                         break;
856                 case ALGORITHM_LEFT_SYMMETRIC:
857                 case ALGORITHM_RIGHT_SYMMETRIC:
858                         if (sh->pd_idx == raid_disks-1)
859                                 i--; /* Q D D D P */
860                         else {
861                                 /* D D P Q D */
862                                 if (i < sh->pd_idx)
863                                         i += raid_disks;
864                                 i -= (sh->pd_idx + 2);
865                         }
866                         break;
867                 default:
868                         printk (KERN_CRIT "raid6: unsupported algorithm %d\n",
869                                 conf->algorithm);
870                 }
871                 break;
872         }
873
874         chunk_number = stripe * data_disks + i;
875         r_sector = (sector_t)chunk_number * sectors_per_chunk + chunk_offset;
876
877         check = raid5_compute_sector (r_sector, raid_disks, data_disks, &dummy1, &dummy2, conf);
878         if (check != sh->sector || dummy1 != dd_idx || dummy2 != sh->pd_idx) {
879                 printk(KERN_ERR "compute_blocknr: map not correct\n");
880                 return 0;
881         }
882         return r_sector;
883 }
884
885
886
887 /*
888  * Copy data between a page in the stripe cache, and one or more bion
889  * The page could align with the middle of the bio, or there could be
890  * several bion, each with several bio_vecs, which cover part of the page
891  * Multiple bion are linked together on bi_next.  There may be extras
892  * at the end of this list.  We ignore them.
893  */
894 static void copy_data(int frombio, struct bio *bio,
895                      struct page *page,
896                      sector_t sector)
897 {
898         char *pa = page_address(page);
899         struct bio_vec *bvl;
900         int i;
901         int page_offset;
902
903         if (bio->bi_sector >= sector)
904                 page_offset = (signed)(bio->bi_sector - sector) * 512;
905         else
906                 page_offset = (signed)(sector - bio->bi_sector) * -512;
907         bio_for_each_segment(bvl, bio, i) {
908                 int len = bio_iovec_idx(bio,i)->bv_len;
909                 int clen;
910                 int b_offset = 0;
911
912                 if (page_offset < 0) {
913                         b_offset = -page_offset;
914                         page_offset += b_offset;
915                         len -= b_offset;
916                 }
917
918                 if (len > 0 && page_offset + len > STRIPE_SIZE)
919                         clen = STRIPE_SIZE - page_offset;
920                 else clen = len;
921
922                 if (clen > 0) {
923                         char *ba = __bio_kmap_atomic(bio, i, KM_USER0);
924                         if (frombio)
925                                 memcpy(pa+page_offset, ba+b_offset, clen);
926                         else
927                                 memcpy(ba+b_offset, pa+page_offset, clen);
928                         __bio_kunmap_atomic(ba, KM_USER0);
929                 }
930                 if (clen < len) /* hit end of page */
931                         break;
932                 page_offset +=  len;
933         }
934 }
935
936 #define check_xor()     do {                                              \
937                                 if (count == MAX_XOR_BLOCKS) {            \
938                                 xor_blocks(count, STRIPE_SIZE, dest, ptr);\
939                                 count = 0;                                \
940                            }                                              \
941                         } while(0)
942
943
944 static void compute_block(struct stripe_head *sh, int dd_idx)
945 {
946         int i, count, disks = sh->disks;
947         void *ptr[MAX_XOR_BLOCKS], *dest, *p;
948
949         PRINTK("compute_block, stripe %llu, idx %d\n", 
950                 (unsigned long long)sh->sector, dd_idx);
951
952         dest = page_address(sh->dev[dd_idx].page);
953         memset(dest, 0, STRIPE_SIZE);
954         count = 0;
955         for (i = disks ; i--; ) {
956                 if (i == dd_idx)
957                         continue;
958                 p = page_address(sh->dev[i].page);
959                 if (test_bit(R5_UPTODATE, &sh->dev[i].flags))
960                         ptr[count++] = p;
961                 else
962                         printk(KERN_ERR "compute_block() %d, stripe %llu, %d"
963                                 " not present\n", dd_idx,
964                                 (unsigned long long)sh->sector, i);
965
966                 check_xor();
967         }
968         if (count)
969                 xor_blocks(count, STRIPE_SIZE, dest, ptr);
970         set_bit(R5_UPTODATE, &sh->dev[dd_idx].flags);
971 }
972
973 static void compute_parity5(struct stripe_head *sh, int method)
974 {
975         raid5_conf_t *conf = sh->raid_conf;
976         int i, pd_idx = sh->pd_idx, disks = sh->disks, count;
977         void *ptr[MAX_XOR_BLOCKS], *dest;
978         struct bio *chosen;
979
980         PRINTK("compute_parity5, stripe %llu, method %d\n",
981                 (unsigned long long)sh->sector, method);
982
983         count = 0;
984         dest = page_address(sh->dev[pd_idx].page);
985         switch(method) {
986         case READ_MODIFY_WRITE:
987                 BUG_ON(!test_bit(R5_UPTODATE, &sh->dev[pd_idx].flags));
988                 for (i=disks ; i-- ;) {
989                         if (i==pd_idx)
990                                 continue;
991                         if (sh->dev[i].towrite &&
992                             test_bit(R5_UPTODATE, &sh->dev[i].flags)) {
993                                 ptr[count++] = page_address(sh->dev[i].page);
994                                 chosen = sh->dev[i].towrite;
995                                 sh->dev[i].towrite = NULL;
996
997                                 if (test_and_clear_bit(R5_Overlap, &sh->dev[i].flags))
998                                         wake_up(&conf->wait_for_overlap);
999
1000                                 BUG_ON(sh->dev[i].written);
1001                                 sh->dev[i].written = chosen;
1002                                 check_xor();
1003                         }
1004                 }
1005                 break;
1006         case RECONSTRUCT_WRITE:
1007                 memset(dest, 0, STRIPE_SIZE);
1008                 for (i= disks; i-- ;)
1009                         if (i!=pd_idx && sh->dev[i].towrite) {
1010                                 chosen = sh->dev[i].towrite;
1011                                 sh->dev[i].towrite = NULL;
1012
1013                                 if (test_and_clear_bit(R5_Overlap, &sh->dev[i].flags))
1014                                         wake_up(&conf->wait_for_overlap);
1015
1016                                 BUG_ON(sh->dev[i].written);
1017                                 sh->dev[i].written = chosen;
1018                         }
1019                 break;
1020         case CHECK_PARITY:
1021                 break;
1022         }
1023         if (count) {
1024                 xor_blocks(count, STRIPE_SIZE, dest, ptr);
1025                 count = 0;
1026         }
1027         
1028         for (i = disks; i--;)
1029                 if (sh->dev[i].written) {
1030                         sector_t sector = sh->dev[i].sector;
1031                         struct bio *wbi = sh->dev[i].written;
1032                         while (wbi && wbi->bi_sector < sector + STRIPE_SECTORS) {
1033                                 copy_data(1, wbi, sh->dev[i].page, sector);
1034                                 wbi = r5_next_bio(wbi, sector);
1035                         }
1036
1037                         set_bit(R5_LOCKED, &sh->dev[i].flags);
1038                         set_bit(R5_UPTODATE, &sh->dev[i].flags);
1039                 }
1040
1041         switch(method) {
1042         case RECONSTRUCT_WRITE:
1043         case CHECK_PARITY:
1044                 for (i=disks; i--;)
1045                         if (i != pd_idx) {
1046                                 ptr[count++] = page_address(sh->dev[i].page);
1047                                 check_xor();
1048                         }
1049                 break;
1050         case READ_MODIFY_WRITE:
1051                 for (i = disks; i--;)
1052                         if (sh->dev[i].written) {
1053                                 ptr[count++] = page_address(sh->dev[i].page);
1054                                 check_xor();
1055                         }
1056         }
1057         if (count)
1058                 xor_blocks(count, STRIPE_SIZE, dest, ptr);
1059
1060         if (method != CHECK_PARITY) {
1061                 set_bit(R5_UPTODATE, &sh->dev[pd_idx].flags);
1062                 set_bit(R5_LOCKED,   &sh->dev[pd_idx].flags);
1063         } else
1064                 clear_bit(R5_UPTODATE, &sh->dev[pd_idx].flags);
1065 }
1066
1067 static void compute_parity6(struct stripe_head *sh, int method)
1068 {
1069         raid6_conf_t *conf = sh->raid_conf;
1070         int i, pd_idx = sh->pd_idx, qd_idx, d0_idx, disks = sh->disks, count;
1071         struct bio *chosen;
1072         /**** FIX THIS: This could be very bad if disks is close to 256 ****/
1073         void *ptrs[disks];
1074
1075         qd_idx = raid6_next_disk(pd_idx, disks);
1076         d0_idx = raid6_next_disk(qd_idx, disks);
1077
1078         PRINTK("compute_parity, stripe %llu, method %d\n",
1079                 (unsigned long long)sh->sector, method);
1080
1081         switch(method) {
1082         case READ_MODIFY_WRITE:
1083                 BUG();          /* READ_MODIFY_WRITE N/A for RAID-6 */
1084         case RECONSTRUCT_WRITE:
1085                 for (i= disks; i-- ;)
1086                         if ( i != pd_idx && i != qd_idx && sh->dev[i].towrite ) {
1087                                 chosen = sh->dev[i].towrite;
1088                                 sh->dev[i].towrite = NULL;
1089
1090                                 if (test_and_clear_bit(R5_Overlap, &sh->dev[i].flags))
1091                                         wake_up(&conf->wait_for_overlap);
1092
1093                                 BUG_ON(sh->dev[i].written);
1094                                 sh->dev[i].written = chosen;
1095                         }
1096                 break;
1097         case CHECK_PARITY:
1098                 BUG();          /* Not implemented yet */
1099         }
1100
1101         for (i = disks; i--;)
1102                 if (sh->dev[i].written) {
1103                         sector_t sector = sh->dev[i].sector;
1104                         struct bio *wbi = sh->dev[i].written;
1105                         while (wbi && wbi->bi_sector < sector + STRIPE_SECTORS) {
1106                                 copy_data(1, wbi, sh->dev[i].page, sector);
1107                                 wbi = r5_next_bio(wbi, sector);
1108                         }
1109
1110                         set_bit(R5_LOCKED, &sh->dev[i].flags);
1111                         set_bit(R5_UPTODATE, &sh->dev[i].flags);
1112                 }
1113
1114 //      switch(method) {
1115 //      case RECONSTRUCT_WRITE:
1116 //      case CHECK_PARITY:
1117 //      case UPDATE_PARITY:
1118                 /* Note that unlike RAID-5, the ordering of the disks matters greatly. */
1119                 /* FIX: Is this ordering of drives even remotely optimal? */
1120                 count = 0;
1121                 i = d0_idx;
1122                 do {
1123                         ptrs[count++] = page_address(sh->dev[i].page);
1124                         if (count <= disks-2 && !test_bit(R5_UPTODATE, &sh->dev[i].flags))
1125                                 printk("block %d/%d not uptodate on parity calc\n", i,count);
1126                         i = raid6_next_disk(i, disks);
1127                 } while ( i != d0_idx );
1128 //              break;
1129 //      }
1130
1131         raid6_call.gen_syndrome(disks, STRIPE_SIZE, ptrs);
1132
1133         switch(method) {
1134         case RECONSTRUCT_WRITE:
1135                 set_bit(R5_UPTODATE, &sh->dev[pd_idx].flags);
1136                 set_bit(R5_UPTODATE, &sh->dev[qd_idx].flags);
1137                 set_bit(R5_LOCKED,   &sh->dev[pd_idx].flags);
1138                 set_bit(R5_LOCKED,   &sh->dev[qd_idx].flags);
1139                 break;
1140         case UPDATE_PARITY:
1141                 set_bit(R5_UPTODATE, &sh->dev[pd_idx].flags);
1142                 set_bit(R5_UPTODATE, &sh->dev[qd_idx].flags);
1143                 break;
1144         }
1145 }
1146
1147
1148 /* Compute one missing block */
1149 static void compute_block_1(struct stripe_head *sh, int dd_idx, int nozero)
1150 {
1151         int i, count, disks = sh->disks;
1152         void *ptr[MAX_XOR_BLOCKS], *dest, *p;
1153         int pd_idx = sh->pd_idx;
1154         int qd_idx = raid6_next_disk(pd_idx, disks);
1155
1156         PRINTK("compute_block_1, stripe %llu, idx %d\n",
1157                 (unsigned long long)sh->sector, dd_idx);
1158
1159         if ( dd_idx == qd_idx ) {
1160                 /* We're actually computing the Q drive */
1161                 compute_parity6(sh, UPDATE_PARITY);
1162         } else {
1163                 dest = page_address(sh->dev[dd_idx].page);
1164                 if (!nozero) memset(dest, 0, STRIPE_SIZE);
1165                 count = 0;
1166                 for (i = disks ; i--; ) {
1167                         if (i == dd_idx || i == qd_idx)
1168                                 continue;
1169                         p = page_address(sh->dev[i].page);
1170                         if (test_bit(R5_UPTODATE, &sh->dev[i].flags))
1171                                 ptr[count++] = p;
1172                         else
1173                                 printk("compute_block() %d, stripe %llu, %d"
1174                                        " not present\n", dd_idx,
1175                                        (unsigned long long)sh->sector, i);
1176
1177                         check_xor();
1178                 }
1179                 if (count)
1180                         xor_blocks(count, STRIPE_SIZE, dest, ptr);
1181                 if (!nozero) set_bit(R5_UPTODATE, &sh->dev[dd_idx].flags);
1182                 else clear_bit(R5_UPTODATE, &sh->dev[dd_idx].flags);
1183         }
1184 }
1185
1186 /* Compute two missing blocks */
1187 static void compute_block_2(struct stripe_head *sh, int dd_idx1, int dd_idx2)
1188 {
1189         int i, count, disks = sh->disks;
1190         int pd_idx = sh->pd_idx;
1191         int qd_idx = raid6_next_disk(pd_idx, disks);
1192         int d0_idx = raid6_next_disk(qd_idx, disks);
1193         int faila, failb;
1194
1195         /* faila and failb are disk numbers relative to d0_idx */
1196         /* pd_idx become disks-2 and qd_idx become disks-1 */
1197         faila = (dd_idx1 < d0_idx) ? dd_idx1+(disks-d0_idx) : dd_idx1-d0_idx;
1198         failb = (dd_idx2 < d0_idx) ? dd_idx2+(disks-d0_idx) : dd_idx2-d0_idx;
1199
1200         BUG_ON(faila == failb);
1201         if ( failb < faila ) { int tmp = faila; faila = failb; failb = tmp; }
1202
1203         PRINTK("compute_block_2, stripe %llu, idx %d,%d (%d,%d)\n",
1204                (unsigned long long)sh->sector, dd_idx1, dd_idx2, faila, failb);
1205
1206         if ( failb == disks-1 ) {
1207                 /* Q disk is one of the missing disks */
1208                 if ( faila == disks-2 ) {
1209                         /* Missing P+Q, just recompute */
1210                         compute_parity6(sh, UPDATE_PARITY);
1211                         return;
1212                 } else {
1213                         /* We're missing D+Q; recompute D from P */
1214                         compute_block_1(sh, (dd_idx1 == qd_idx) ? dd_idx2 : dd_idx1, 0);
1215                         compute_parity6(sh, UPDATE_PARITY); /* Is this necessary? */
1216                         return;
1217                 }
1218         }
1219
1220         /* We're missing D+P or D+D; build pointer table */
1221         {
1222                 /**** FIX THIS: This could be very bad if disks is close to 256 ****/
1223                 void *ptrs[disks];
1224
1225                 count = 0;
1226                 i = d0_idx;
1227                 do {
1228                         ptrs[count++] = page_address(sh->dev[i].page);
1229                         i = raid6_next_disk(i, disks);
1230                         if (i != dd_idx1 && i != dd_idx2 &&
1231                             !test_bit(R5_UPTODATE, &sh->dev[i].flags))
1232                                 printk("compute_2 with missing block %d/%d\n", count, i);
1233                 } while ( i != d0_idx );
1234
1235                 if ( failb == disks-2 ) {
1236                         /* We're missing D+P. */
1237                         raid6_datap_recov(disks, STRIPE_SIZE, faila, ptrs);
1238                 } else {
1239                         /* We're missing D+D. */
1240                         raid6_2data_recov(disks, STRIPE_SIZE, faila, failb, ptrs);
1241                 }
1242
1243                 /* Both the above update both missing blocks */
1244                 set_bit(R5_UPTODATE, &sh->dev[dd_idx1].flags);
1245                 set_bit(R5_UPTODATE, &sh->dev[dd_idx2].flags);
1246         }
1247 }
1248
1249
1250
1251 /*
1252  * Each stripe/dev can have one or more bion attached.
1253  * toread/towrite point to the first in a chain.
1254  * The bi_next chain must be in order.
1255  */
1256 static int add_stripe_bio(struct stripe_head *sh, struct bio *bi, int dd_idx, int forwrite)
1257 {
1258         struct bio **bip;
1259         raid5_conf_t *conf = sh->raid_conf;
1260         int firstwrite=0;
1261
1262         PRINTK("adding bh b#%llu to stripe s#%llu\n",
1263                 (unsigned long long)bi->bi_sector,
1264                 (unsigned long long)sh->sector);
1265
1266
1267         spin_lock(&sh->lock);
1268         spin_lock_irq(&conf->device_lock);
1269         if (forwrite) {
1270                 bip = &sh->dev[dd_idx].towrite;
1271                 if (*bip == NULL && sh->dev[dd_idx].written == NULL)
1272                         firstwrite = 1;
1273         } else
1274                 bip = &sh->dev[dd_idx].toread;
1275         while (*bip && (*bip)->bi_sector < bi->bi_sector) {
1276                 if ((*bip)->bi_sector + ((*bip)->bi_size >> 9) > bi->bi_sector)
1277                         goto overlap;
1278                 bip = & (*bip)->bi_next;
1279         }
1280         if (*bip && (*bip)->bi_sector < bi->bi_sector + ((bi->bi_size)>>9))
1281                 goto overlap;
1282
1283         BUG_ON(*bip && bi->bi_next && (*bip) != bi->bi_next);
1284         if (*bip)
1285                 bi->bi_next = *bip;
1286         *bip = bi;
1287         bi->bi_phys_segments ++;
1288         spin_unlock_irq(&conf->device_lock);
1289         spin_unlock(&sh->lock);
1290
1291         PRINTK("added bi b#%llu to stripe s#%llu, disk %d.\n",
1292                 (unsigned long long)bi->bi_sector,
1293                 (unsigned long long)sh->sector, dd_idx);
1294
1295         if (conf->mddev->bitmap && firstwrite) {
1296                 bitmap_startwrite(conf->mddev->bitmap, sh->sector,
1297                                   STRIPE_SECTORS, 0);
1298                 sh->bm_seq = conf->seq_flush+1;
1299                 set_bit(STRIPE_BIT_DELAY, &sh->state);
1300         }
1301
1302         if (forwrite) {
1303                 /* check if page is covered */
1304                 sector_t sector = sh->dev[dd_idx].sector;
1305                 for (bi=sh->dev[dd_idx].towrite;
1306                      sector < sh->dev[dd_idx].sector + STRIPE_SECTORS &&
1307                              bi && bi->bi_sector <= sector;
1308                      bi = r5_next_bio(bi, sh->dev[dd_idx].sector)) {
1309                         if (bi->bi_sector + (bi->bi_size>>9) >= sector)
1310                                 sector = bi->bi_sector + (bi->bi_size>>9);
1311                 }
1312                 if (sector >= sh->dev[dd_idx].sector + STRIPE_SECTORS)
1313                         set_bit(R5_OVERWRITE, &sh->dev[dd_idx].flags);
1314         }
1315         return 1;
1316
1317  overlap:
1318         set_bit(R5_Overlap, &sh->dev[dd_idx].flags);
1319         spin_unlock_irq(&conf->device_lock);
1320         spin_unlock(&sh->lock);
1321         return 0;
1322 }
1323
1324 static void end_reshape(raid5_conf_t *conf);
1325
1326 static int page_is_zero(struct page *p)
1327 {
1328         char *a = page_address(p);
1329         return ((*(u32*)a) == 0 &&
1330                 memcmp(a, a+4, STRIPE_SIZE-4)==0);
1331 }
1332
1333 static int stripe_to_pdidx(sector_t stripe, raid5_conf_t *conf, int disks)
1334 {
1335         int sectors_per_chunk = conf->chunk_size >> 9;
1336         int pd_idx, dd_idx;
1337         int chunk_offset = sector_div(stripe, sectors_per_chunk);
1338
1339         raid5_compute_sector(stripe * (disks - conf->max_degraded)
1340                              *sectors_per_chunk + chunk_offset,
1341                              disks, disks - conf->max_degraded,
1342                              &dd_idx, &pd_idx, conf);
1343         return pd_idx;
1344 }
1345
1346 static void
1347 handle_requests_to_failed_array(raid5_conf_t *conf, struct stripe_head *sh,
1348                                 struct stripe_head_state *s, int disks,
1349                                 struct bio **return_bi)
1350 {
1351         int i;
1352         for (i = disks; i--; ) {
1353                 struct bio *bi;
1354                 int bitmap_end = 0;
1355
1356                 if (test_bit(R5_ReadError, &sh->dev[i].flags)) {
1357                         mdk_rdev_t *rdev;
1358                         rcu_read_lock();
1359                         rdev = rcu_dereference(conf->disks[i].rdev);
1360                         if (rdev && test_bit(In_sync, &rdev->flags))
1361                                 /* multiple read failures in one stripe */
1362                                 md_error(conf->mddev, rdev);
1363                         rcu_read_unlock();
1364                 }
1365                 spin_lock_irq(&conf->device_lock);
1366                 /* fail all writes first */
1367                 bi = sh->dev[i].towrite;
1368                 sh->dev[i].towrite = NULL;
1369                 if (bi) {
1370                         s->to_write--;
1371                         bitmap_end = 1;
1372                 }
1373
1374                 if (test_and_clear_bit(R5_Overlap, &sh->dev[i].flags))
1375                         wake_up(&conf->wait_for_overlap);
1376
1377                 while (bi && bi->bi_sector <
1378                         sh->dev[i].sector + STRIPE_SECTORS) {
1379                         struct bio *nextbi = r5_next_bio(bi, sh->dev[i].sector);
1380                         clear_bit(BIO_UPTODATE, &bi->bi_flags);
1381                         if (--bi->bi_phys_segments == 0) {
1382                                 md_write_end(conf->mddev);
1383                                 bi->bi_next = *return_bi;
1384                                 *return_bi = bi;
1385                         }
1386                         bi = nextbi;
1387                 }
1388                 /* and fail all 'written' */
1389                 bi = sh->dev[i].written;
1390                 sh->dev[i].written = NULL;
1391                 if (bi) bitmap_end = 1;
1392                 while (bi && bi->bi_sector <
1393                        sh->dev[i].sector + STRIPE_SECTORS) {
1394                         struct bio *bi2 = r5_next_bio(bi, sh->dev[i].sector);
1395                         clear_bit(BIO_UPTODATE, &bi->bi_flags);
1396                         if (--bi->bi_phys_segments == 0) {
1397                                 md_write_end(conf->mddev);
1398                                 bi->bi_next = *return_bi;
1399                                 *return_bi = bi;
1400                         }
1401                         bi = bi2;
1402                 }
1403
1404                 /* fail any reads if this device is non-operational */
1405                 if (!test_bit(R5_Insync, &sh->dev[i].flags) ||
1406                     test_bit(R5_ReadError, &sh->dev[i].flags)) {
1407                         bi = sh->dev[i].toread;
1408                         sh->dev[i].toread = NULL;
1409                         if (test_and_clear_bit(R5_Overlap, &sh->dev[i].flags))
1410                                 wake_up(&conf->wait_for_overlap);
1411                         if (bi) s->to_read--;
1412                         while (bi && bi->bi_sector <
1413                                sh->dev[i].sector + STRIPE_SECTORS) {
1414                                 struct bio *nextbi =
1415                                         r5_next_bio(bi, sh->dev[i].sector);
1416                                 clear_bit(BIO_UPTODATE, &bi->bi_flags);
1417                                 if (--bi->bi_phys_segments == 0) {
1418                                         bi->bi_next = *return_bi;
1419                                         *return_bi = bi;
1420                                 }
1421                                 bi = nextbi;
1422                         }
1423                 }
1424                 spin_unlock_irq(&conf->device_lock);
1425                 if (bitmap_end)
1426                         bitmap_endwrite(conf->mddev->bitmap, sh->sector,
1427                                         STRIPE_SECTORS, 0, 0);
1428         }
1429
1430 }
1431
1432 static void handle_issuing_new_read_requests5(struct stripe_head *sh,
1433                         struct stripe_head_state *s, int disks)
1434 {
1435         int i;
1436         for (i = disks; i--; ) {
1437                 struct r5dev *dev = &sh->dev[i];
1438                 if (!test_bit(R5_LOCKED, &dev->flags) &&
1439                     !test_bit(R5_UPTODATE, &dev->flags) &&
1440                     (dev->toread ||
1441                      (dev->towrite && !test_bit(R5_OVERWRITE, &dev->flags)) ||
1442                      s->syncing || s->expanding ||
1443                      (s->failed && (sh->dev[s->failed_num].toread ||
1444                         (sh->dev[s->failed_num].towrite &&
1445                         !test_bit(R5_OVERWRITE, &sh->dev[s->failed_num].flags))
1446                       )))) {
1447                         /* we would like to get this block, possibly
1448                          * by computing it, but we might not be able to
1449                          */
1450                         if (s->uptodate == disks-1) {
1451                                 PRINTK("Computing block %d\n", i);
1452                                 compute_block(sh, i);
1453                                 s->uptodate++;
1454                         } else if (test_bit(R5_Insync, &dev->flags)) {
1455                                 set_bit(R5_LOCKED, &dev->flags);
1456                                 set_bit(R5_Wantread, &dev->flags);
1457                                 s->locked++;
1458                                 PRINTK("Reading block %d (sync=%d)\n",
1459                                         i, s->syncing);
1460                         }
1461                 }
1462         }
1463         set_bit(STRIPE_HANDLE, &sh->state);
1464 }
1465
1466 static void handle_issuing_new_read_requests6(struct stripe_head *sh,
1467                         struct stripe_head_state *s, struct r6_state *r6s,
1468                         int disks)
1469 {
1470         int i;
1471         for (i = disks; i--; ) {
1472                 struct r5dev *dev = &sh->dev[i];
1473                 if (!test_bit(R5_LOCKED, &dev->flags) &&
1474                     !test_bit(R5_UPTODATE, &dev->flags) &&
1475                     (dev->toread || (dev->towrite &&
1476                      !test_bit(R5_OVERWRITE, &dev->flags)) ||
1477                      s->syncing || s->expanding ||
1478                      (s->failed >= 1 &&
1479                       (sh->dev[r6s->failed_num[0]].toread ||
1480                        s->to_write)) ||
1481                      (s->failed >= 2 &&
1482                       (sh->dev[r6s->failed_num[1]].toread ||
1483                        s->to_write)))) {
1484                         /* we would like to get this block, possibly
1485                          * by computing it, but we might not be able to
1486                          */
1487                         if (s->uptodate == disks-1) {
1488                                 PRINTK("Computing stripe %llu block %d\n",
1489                                        (unsigned long long)sh->sector, i);
1490                                 compute_block_1(sh, i, 0);
1491                                 s->uptodate++;
1492                         } else if ( s->uptodate == disks-2 && s->failed >= 2 ) {
1493                                 /* Computing 2-failure is *very* expensive; only
1494                                  * do it if failed >= 2
1495                                  */
1496                                 int other;
1497                                 for (other = disks; other--; ) {
1498                                         if (other == i)
1499                                                 continue;
1500                                         if (!test_bit(R5_UPTODATE,
1501                                               &sh->dev[other].flags))
1502                                                 break;
1503                                 }
1504                                 BUG_ON(other < 0);
1505                                 PRINTK("Computing stripe %llu blocks %d,%d\n",
1506                                        (unsigned long long)sh->sector,
1507                                        i, other);
1508                                 compute_block_2(sh, i, other);
1509                                 s->uptodate += 2;
1510                         } else if (test_bit(R5_Insync, &dev->flags)) {
1511                                 set_bit(R5_LOCKED, &dev->flags);
1512                                 set_bit(R5_Wantread, &dev->flags);
1513                                 s->locked++;
1514                                 PRINTK("Reading block %d (sync=%d)\n",
1515                                         i, s->syncing);
1516                         }
1517                 }
1518         }
1519         set_bit(STRIPE_HANDLE, &sh->state);
1520 }
1521
1522
1523 /* handle_completed_write_requests
1524  * any written block on an uptodate or failed drive can be returned.
1525  * Note that if we 'wrote' to a failed drive, it will be UPTODATE, but
1526  * never LOCKED, so we don't need to test 'failed' directly.
1527  */
1528 static void handle_completed_write_requests(raid5_conf_t *conf,
1529         struct stripe_head *sh, int disks, struct bio **return_bi)
1530 {
1531         int i;
1532         struct r5dev *dev;
1533
1534         for (i = disks; i--; )
1535                 if (sh->dev[i].written) {
1536                         dev = &sh->dev[i];
1537                         if (!test_bit(R5_LOCKED, &dev->flags) &&
1538                                 test_bit(R5_UPTODATE, &dev->flags)) {
1539                                 /* We can return any write requests */
1540                                 struct bio *wbi, *wbi2;
1541                                 int bitmap_end = 0;
1542                                 PRINTK("Return write for disc %d\n", i);
1543                                 spin_lock_irq(&conf->device_lock);
1544                                 wbi = dev->written;
1545                                 dev->written = NULL;
1546                                 while (wbi && wbi->bi_sector <
1547                                         dev->sector + STRIPE_SECTORS) {
1548                                         wbi2 = r5_next_bio(wbi, dev->sector);
1549                                         if (--wbi->bi_phys_segments == 0) {
1550                                                 md_write_end(conf->mddev);
1551                                                 wbi->bi_next = *return_bi;
1552                                                 *return_bi = wbi;
1553                                         }
1554                                         wbi = wbi2;
1555                                 }
1556                                 if (dev->towrite == NULL)
1557                                         bitmap_end = 1;
1558                                 spin_unlock_irq(&conf->device_lock);
1559                                 if (bitmap_end)
1560                                         bitmap_endwrite(conf->mddev->bitmap,
1561                                                         sh->sector,
1562                                                         STRIPE_SECTORS,
1563                                          !test_bit(STRIPE_DEGRADED, &sh->state),
1564                                                         0);
1565                         }
1566                 }
1567 }
1568
1569 static void handle_issuing_new_write_requests5(raid5_conf_t *conf,
1570                 struct stripe_head *sh, struct stripe_head_state *s, int disks)
1571 {
1572         int rmw = 0, rcw = 0, i;
1573         for (i = disks; i--; ) {
1574                 /* would I have to read this buffer for read_modify_write */
1575                 struct r5dev *dev = &sh->dev[i];
1576                 if ((dev->towrite || i == sh->pd_idx) &&
1577                     !test_bit(R5_LOCKED, &dev->flags) &&
1578                     !test_bit(R5_UPTODATE, &dev->flags)) {
1579                         if (test_bit(R5_Insync, &dev->flags))
1580                                 rmw++;
1581                         else
1582                                 rmw += 2*disks;  /* cannot read it */
1583                 }
1584                 /* Would I have to read this buffer for reconstruct_write */
1585                 if (!test_bit(R5_OVERWRITE, &dev->flags) && i != sh->pd_idx &&
1586                     !test_bit(R5_LOCKED, &dev->flags) &&
1587                     !test_bit(R5_UPTODATE, &dev->flags)) {
1588                         if (test_bit(R5_Insync, &dev->flags))
1589                                 rcw++;
1590                         else
1591                                 rcw += 2*disks;
1592                 }
1593         }
1594         PRINTK("for sector %llu, rmw=%d rcw=%d\n",
1595                 (unsigned long long)sh->sector, rmw, rcw);
1596         set_bit(STRIPE_HANDLE, &sh->state);
1597         if (rmw < rcw && rmw > 0)
1598                 /* prefer read-modify-write, but need to get some data */
1599                 for (i = disks; i--; ) {
1600                         struct r5dev *dev = &sh->dev[i];
1601                         if ((dev->towrite || i == sh->pd_idx) &&
1602                             !test_bit(R5_LOCKED, &dev->flags) &&
1603                             !test_bit(R5_UPTODATE, &dev->flags) &&
1604                             test_bit(R5_Insync, &dev->flags)) {
1605                                 if (
1606                                   test_bit(STRIPE_PREREAD_ACTIVE, &sh->state)) {
1607                                         PRINTK("Read_old block "
1608                                                 "%d for r-m-w\n", i);
1609                                         set_bit(R5_LOCKED, &dev->flags);
1610                                         set_bit(R5_Wantread, &dev->flags);
1611                                         s->locked++;
1612                                 } else {
1613                                         set_bit(STRIPE_DELAYED, &sh->state);
1614                                         set_bit(STRIPE_HANDLE, &sh->state);
1615                                 }
1616                         }
1617                 }
1618         if (rcw <= rmw && rcw > 0)
1619                 /* want reconstruct write, but need to get some data */
1620                 for (i = disks; i--; ) {
1621                         struct r5dev *dev = &sh->dev[i];
1622                         if (!test_bit(R5_OVERWRITE, &dev->flags) &&
1623                             i != sh->pd_idx &&
1624                             !test_bit(R5_LOCKED, &dev->flags) &&
1625                             !test_bit(R5_UPTODATE, &dev->flags) &&
1626                             test_bit(R5_Insync, &dev->flags)) {
1627                                 if (
1628                                   test_bit(STRIPE_PREREAD_ACTIVE, &sh->state)) {
1629                                         PRINTK("Read_old block "
1630                                                 "%d for Reconstruct\n", i);
1631                                         set_bit(R5_LOCKED, &dev->flags);
1632                                         set_bit(R5_Wantread, &dev->flags);
1633                                         s->locked++;
1634                                 } else {
1635                                         set_bit(STRIPE_DELAYED, &sh->state);
1636                                         set_bit(STRIPE_HANDLE, &sh->state);
1637                                 }
1638                         }
1639                 }
1640         /* now if nothing is locked, and if we have enough data,
1641          * we can start a write request
1642          */
1643         if (s->locked == 0 && (rcw == 0 || rmw == 0) &&
1644             !test_bit(STRIPE_BIT_DELAY, &sh->state)) {
1645                 PRINTK("Computing parity...\n");
1646                 compute_parity5(sh, rcw == 0 ?
1647                         RECONSTRUCT_WRITE : READ_MODIFY_WRITE);
1648                 /* now every locked buffer is ready to be written */
1649                 for (i = disks; i--; )
1650                         if (test_bit(R5_LOCKED, &sh->dev[i].flags)) {
1651                                 PRINTK("Writing block %d\n", i);
1652                                 s->locked++;
1653                                 set_bit(R5_Wantwrite, &sh->dev[i].flags);
1654                                 if (!test_bit(R5_Insync, &sh->dev[i].flags)
1655                                     || (i == sh->pd_idx && s->failed == 0))
1656                                         set_bit(STRIPE_INSYNC, &sh->state);
1657                         }
1658                 if (test_and_clear_bit(STRIPE_PREREAD_ACTIVE, &sh->state)) {
1659                         atomic_dec(&conf->preread_active_stripes);
1660                         if (atomic_read(&conf->preread_active_stripes) <
1661                             IO_THRESHOLD)
1662                                 md_wakeup_thread(conf->mddev->thread);
1663                 }
1664         }
1665 }
1666
1667 static void handle_issuing_new_write_requests6(raid5_conf_t *conf,
1668                 struct stripe_head *sh, struct stripe_head_state *s,
1669                 struct r6_state *r6s, int disks)
1670 {
1671         int rcw = 0, must_compute = 0, pd_idx = sh->pd_idx, i;
1672         int qd_idx = r6s->qd_idx;
1673         for (i = disks; i--; ) {
1674                 struct r5dev *dev = &sh->dev[i];
1675                 /* Would I have to read this buffer for reconstruct_write */
1676                 if (!test_bit(R5_OVERWRITE, &dev->flags)
1677                     && i != pd_idx && i != qd_idx
1678                     && (!test_bit(R5_LOCKED, &dev->flags)
1679                             ) &&
1680                     !test_bit(R5_UPTODATE, &dev->flags)) {
1681                         if (test_bit(R5_Insync, &dev->flags)) rcw++;
1682                         else {
1683                                 PRINTK("raid6: must_compute: "
1684                                         "disk %d flags=%#lx\n", i, dev->flags);
1685                                 must_compute++;
1686                         }
1687                 }
1688         }
1689         PRINTK("for sector %llu, rcw=%d, must_compute=%d\n",
1690                (unsigned long long)sh->sector, rcw, must_compute);
1691         set_bit(STRIPE_HANDLE, &sh->state);
1692
1693         if (rcw > 0)
1694                 /* want reconstruct write, but need to get some data */
1695                 for (i = disks; i--; ) {
1696                         struct r5dev *dev = &sh->dev[i];
1697                         if (!test_bit(R5_OVERWRITE, &dev->flags)
1698                             && !(s->failed == 0 && (i == pd_idx || i == qd_idx))
1699                             && !test_bit(R5_LOCKED, &dev->flags) &&
1700                             !test_bit(R5_UPTODATE, &dev->flags) &&
1701                             test_bit(R5_Insync, &dev->flags)) {
1702                                 if (
1703                                   test_bit(STRIPE_PREREAD_ACTIVE, &sh->state)) {
1704                                         PRINTK("Read_old stripe %llu "
1705                                                 "block %d for Reconstruct\n",
1706                                              (unsigned long long)sh->sector, i);
1707                                         set_bit(R5_LOCKED, &dev->flags);
1708                                         set_bit(R5_Wantread, &dev->flags);
1709                                         s->locked++;
1710                                 } else {
1711                                         PRINTK("Request delayed stripe %llu "
1712                                                 "block %d for Reconstruct\n",
1713                                              (unsigned long long)sh->sector, i);
1714                                         set_bit(STRIPE_DELAYED, &sh->state);
1715                                         set_bit(STRIPE_HANDLE, &sh->state);
1716                                 }
1717                         }
1718                 }
1719         /* now if nothing is locked, and if we have enough data, we can start a
1720          * write request
1721          */
1722         if (s->locked == 0 && rcw == 0 &&
1723             !test_bit(STRIPE_BIT_DELAY, &sh->state)) {
1724                 if (must_compute > 0) {
1725                         /* We have failed blocks and need to compute them */
1726                         switch (s->failed) {
1727                         case 0:
1728                                 BUG();
1729                         case 1:
1730                                 compute_block_1(sh, r6s->failed_num[0], 0);
1731                                 break;
1732                         case 2:
1733                                 compute_block_2(sh, r6s->failed_num[0],
1734                                                 r6s->failed_num[1]);
1735                                 break;
1736                         default: /* This request should have been failed? */
1737                                 BUG();
1738                         }
1739                 }
1740
1741                 PRINTK("Computing parity for stripe %llu\n",
1742                         (unsigned long long)sh->sector);
1743                 compute_parity6(sh, RECONSTRUCT_WRITE);
1744                 /* now every locked buffer is ready to be written */
1745                 for (i = disks; i--; )
1746                         if (test_bit(R5_LOCKED, &sh->dev[i].flags)) {
1747                                 PRINTK("Writing stripe %llu block %d\n",
1748                                        (unsigned long long)sh->sector, i);
1749                                 s->locked++;
1750                                 set_bit(R5_Wantwrite, &sh->dev[i].flags);
1751                         }
1752                 /* after a RECONSTRUCT_WRITE, the stripe MUST be in-sync */
1753                 set_bit(STRIPE_INSYNC, &sh->state);
1754
1755                 if (test_and_clear_bit(STRIPE_PREREAD_ACTIVE, &sh->state)) {
1756                         atomic_dec(&conf->preread_active_stripes);
1757                         if (atomic_read(&conf->preread_active_stripes) <
1758                             IO_THRESHOLD)
1759                                 md_wakeup_thread(conf->mddev->thread);
1760                 }
1761         }
1762 }
1763
1764 static void handle_parity_checks5(raid5_conf_t *conf, struct stripe_head *sh,
1765                                 struct stripe_head_state *s, int disks)
1766 {
1767         set_bit(STRIPE_HANDLE, &sh->state);
1768         if (s->failed == 0) {
1769                 BUG_ON(s->uptodate != disks);
1770                 compute_parity5(sh, CHECK_PARITY);
1771                 s->uptodate--;
1772                 if (page_is_zero(sh->dev[sh->pd_idx].page)) {
1773                         /* parity is correct (on disc, not in buffer any more)
1774                          */
1775                         set_bit(STRIPE_INSYNC, &sh->state);
1776                 } else {
1777                         conf->mddev->resync_mismatches += STRIPE_SECTORS;
1778                         if (test_bit(MD_RECOVERY_CHECK, &conf->mddev->recovery))
1779                                 /* don't try to repair!! */
1780                                 set_bit(STRIPE_INSYNC, &sh->state);
1781                         else {
1782                                 compute_block(sh, sh->pd_idx);
1783                                 s->uptodate++;
1784                         }
1785                 }
1786         }
1787         if (!test_bit(STRIPE_INSYNC, &sh->state)) {
1788                 struct r5dev *dev;
1789                 /* either failed parity check, or recovery is happening */
1790                 if (s->failed == 0)
1791                         s->failed_num = sh->pd_idx;
1792                 dev = &sh->dev[s->failed_num];
1793                 BUG_ON(!test_bit(R5_UPTODATE, &dev->flags));
1794                 BUG_ON(s->uptodate != disks);
1795
1796                 set_bit(R5_LOCKED, &dev->flags);
1797                 set_bit(R5_Wantwrite, &dev->flags);
1798                 clear_bit(STRIPE_DEGRADED, &sh->state);
1799                 s->locked++;
1800                 set_bit(STRIPE_INSYNC, &sh->state);
1801         }
1802 }
1803
1804
1805 static void handle_parity_checks6(raid5_conf_t *conf, struct stripe_head *sh,
1806                                 struct stripe_head_state *s,
1807                                 struct r6_state *r6s, struct page *tmp_page,
1808                                 int disks)
1809 {
1810         int update_p = 0, update_q = 0;
1811         struct r5dev *dev;
1812         int pd_idx = sh->pd_idx;
1813         int qd_idx = r6s->qd_idx;
1814
1815         set_bit(STRIPE_HANDLE, &sh->state);
1816
1817         BUG_ON(s->failed > 2);
1818         BUG_ON(s->uptodate < disks);
1819         /* Want to check and possibly repair P and Q.
1820          * However there could be one 'failed' device, in which
1821          * case we can only check one of them, possibly using the
1822          * other to generate missing data
1823          */
1824
1825         /* If !tmp_page, we cannot do the calculations,
1826          * but as we have set STRIPE_HANDLE, we will soon be called
1827          * by stripe_handle with a tmp_page - just wait until then.
1828          */
1829         if (tmp_page) {
1830                 if (s->failed == r6s->q_failed) {
1831                         /* The only possible failed device holds 'Q', so it
1832                          * makes sense to check P (If anything else were failed,
1833                          * we would have used P to recreate it).
1834                          */
1835                         compute_block_1(sh, pd_idx, 1);
1836                         if (!page_is_zero(sh->dev[pd_idx].page)) {
1837                                 compute_block_1(sh, pd_idx, 0);
1838                                 update_p = 1;
1839                         }
1840                 }
1841                 if (!r6s->q_failed && s->failed < 2) {
1842                         /* q is not failed, and we didn't use it to generate
1843                          * anything, so it makes sense to check it
1844                          */
1845                         memcpy(page_address(tmp_page),
1846                                page_address(sh->dev[qd_idx].page),
1847                                STRIPE_SIZE);
1848                         compute_parity6(sh, UPDATE_PARITY);
1849                         if (memcmp(page_address(tmp_page),
1850                                    page_address(sh->dev[qd_idx].page),
1851                                    STRIPE_SIZE) != 0) {
1852                                 clear_bit(STRIPE_INSYNC, &sh->state);
1853                                 update_q = 1;
1854                         }
1855                 }
1856                 if (update_p || update_q) {
1857                         conf->mddev->resync_mismatches += STRIPE_SECTORS;
1858                         if (test_bit(MD_RECOVERY_CHECK, &conf->mddev->recovery))
1859                                 /* don't try to repair!! */
1860                                 update_p = update_q = 0;
1861                 }
1862
1863                 /* now write out any block on a failed drive,
1864                  * or P or Q if they need it
1865                  */
1866
1867                 if (s->failed == 2) {
1868                         dev = &sh->dev[r6s->failed_num[1]];
1869                         s->locked++;
1870                         set_bit(R5_LOCKED, &dev->flags);
1871                         set_bit(R5_Wantwrite, &dev->flags);
1872                 }
1873                 if (s->failed >= 1) {
1874                         dev = &sh->dev[r6s->failed_num[0]];
1875                         s->locked++;
1876                         set_bit(R5_LOCKED, &dev->flags);
1877                         set_bit(R5_Wantwrite, &dev->flags);
1878                 }
1879
1880                 if (update_p) {
1881                         dev = &sh->dev[pd_idx];
1882                         s->locked++;
1883                         set_bit(R5_LOCKED, &dev->flags);
1884                         set_bit(R5_Wantwrite, &dev->flags);
1885                 }
1886                 if (update_q) {
1887                         dev = &sh->dev[qd_idx];
1888                         s->locked++;
1889                         set_bit(R5_LOCKED, &dev->flags);
1890                         set_bit(R5_Wantwrite, &dev->flags);
1891                 }
1892                 clear_bit(STRIPE_DEGRADED, &sh->state);
1893
1894                 set_bit(STRIPE_INSYNC, &sh->state);
1895         }
1896 }
1897
1898 static void handle_stripe_expansion(raid5_conf_t *conf, struct stripe_head *sh,
1899                                 struct r6_state *r6s)
1900 {
1901         int i;
1902
1903         /* We have read all the blocks in this stripe and now we need to
1904          * copy some of them into a target stripe for expand.
1905          */
1906         clear_bit(STRIPE_EXPAND_SOURCE, &sh->state);
1907         for (i = 0; i < sh->disks; i++)
1908                 if (i != sh->pd_idx && (r6s && i != r6s->qd_idx)) {
1909                         int dd_idx, pd_idx, j;
1910                         struct stripe_head *sh2;
1911
1912                         sector_t bn = compute_blocknr(sh, i);
1913                         sector_t s = raid5_compute_sector(bn, conf->raid_disks,
1914                                                 conf->raid_disks -
1915                                                 conf->max_degraded, &dd_idx,
1916                                                 &pd_idx, conf);
1917                         sh2 = get_active_stripe(conf, s, conf->raid_disks,
1918                                                 pd_idx, 1);
1919                         if (sh2 == NULL)
1920                                 /* so far only the early blocks of this stripe
1921                                  * have been requested.  When later blocks
1922                                  * get requested, we will try again
1923                                  */
1924                                 continue;
1925                         if (!test_bit(STRIPE_EXPANDING, &sh2->state) ||
1926                            test_bit(R5_Expanded, &sh2->dev[dd_idx].flags)) {
1927                                 /* must have already done this block */
1928                                 release_stripe(sh2);
1929                                 continue;
1930                         }
1931                         memcpy(page_address(sh2->dev[dd_idx].page),
1932                                page_address(sh->dev[i].page),
1933                                STRIPE_SIZE);
1934                         set_bit(R5_Expanded, &sh2->dev[dd_idx].flags);
1935                         set_bit(R5_UPTODATE, &sh2->dev[dd_idx].flags);
1936                         for (j = 0; j < conf->raid_disks; j++)
1937                                 if (j != sh2->pd_idx &&
1938                                     (r6s && j != r6s->qd_idx) &&
1939                                     !test_bit(R5_Expanded, &sh2->dev[j].flags))
1940                                         break;
1941                         if (j == conf->raid_disks) {
1942                                 set_bit(STRIPE_EXPAND_READY, &sh2->state);
1943                                 set_bit(STRIPE_HANDLE, &sh2->state);
1944                         }
1945                         release_stripe(sh2);
1946                 }
1947 }
1948
1949 /*
1950  * handle_stripe - do things to a stripe.
1951  *
1952  * We lock the stripe and then examine the state of various bits
1953  * to see what needs to be done.
1954  * Possible results:
1955  *    return some read request which now have data
1956  *    return some write requests which are safely on disc
1957  *    schedule a read on some buffers
1958  *    schedule a write of some buffers
1959  *    return confirmation of parity correctness
1960  *
1961  * Parity calculations are done inside the stripe lock
1962  * buffers are taken off read_list or write_list, and bh_cache buffers
1963  * get BH_Lock set before the stripe lock is released.
1964  *
1965  */
1966
1967 static void handle_stripe5(struct stripe_head *sh)
1968 {
1969         raid5_conf_t *conf = sh->raid_conf;
1970         int disks = sh->disks, i;
1971         struct bio *return_bi = NULL;
1972         struct stripe_head_state s;
1973         struct r5dev *dev;
1974
1975         memset(&s, 0, sizeof(s));
1976         PRINTK("handling stripe %llu, cnt=%d, pd_idx=%d\n",
1977                 (unsigned long long)sh->sector, atomic_read(&sh->count),
1978                 sh->pd_idx);
1979
1980         spin_lock(&sh->lock);
1981         clear_bit(STRIPE_HANDLE, &sh->state);
1982         clear_bit(STRIPE_DELAYED, &sh->state);
1983
1984         s.syncing = test_bit(STRIPE_SYNCING, &sh->state);
1985         s.expanding = test_bit(STRIPE_EXPAND_SOURCE, &sh->state);
1986         s.expanded = test_bit(STRIPE_EXPAND_READY, &sh->state);
1987         /* Now to look around and see what can be done */
1988
1989         rcu_read_lock();
1990         for (i=disks; i--; ) {
1991                 mdk_rdev_t *rdev;
1992                 struct r5dev *dev = &sh->dev[i];
1993                 clear_bit(R5_Insync, &dev->flags);
1994
1995                 PRINTK("check %d: state 0x%lx read %p write %p written %p\n",
1996                         i, dev->flags, dev->toread, dev->towrite, dev->written);
1997                 /* maybe we can reply to a read */
1998                 if (test_bit(R5_UPTODATE, &dev->flags) && dev->toread) {
1999                         struct bio *rbi, *rbi2;
2000                         PRINTK("Return read for disc %d\n", i);
2001                         spin_lock_irq(&conf->device_lock);
2002                         rbi = dev->toread;
2003                         dev->toread = NULL;
2004                         if (test_and_clear_bit(R5_Overlap, &dev->flags))
2005                                 wake_up(&conf->wait_for_overlap);
2006                         spin_unlock_irq(&conf->device_lock);
2007                         while (rbi && rbi->bi_sector < dev->sector + STRIPE_SECTORS) {
2008                                 copy_data(0, rbi, dev->page, dev->sector);
2009                                 rbi2 = r5_next_bio(rbi, dev->sector);
2010                                 spin_lock_irq(&conf->device_lock);
2011                                 if (--rbi->bi_phys_segments == 0) {
2012                                         rbi->bi_next = return_bi;
2013                                         return_bi = rbi;
2014                                 }
2015                                 spin_unlock_irq(&conf->device_lock);
2016                                 rbi = rbi2;
2017                         }
2018                 }
2019
2020                 /* now count some things */
2021                 if (test_bit(R5_LOCKED, &dev->flags)) s.locked++;
2022                 if (test_bit(R5_UPTODATE, &dev->flags)) s.uptodate++;
2023
2024                 if (dev->toread)
2025                         s.to_read++;
2026                 if (dev->towrite) {
2027                         s.to_write++;
2028                         if (!test_bit(R5_OVERWRITE, &dev->flags))
2029                                 s.non_overwrite++;
2030                 }
2031                 if (dev->written)
2032                         s.written++;
2033                 rdev = rcu_dereference(conf->disks[i].rdev);
2034                 if (!rdev || !test_bit(In_sync, &rdev->flags)) {
2035                         /* The ReadError flag will just be confusing now */
2036                         clear_bit(R5_ReadError, &dev->flags);
2037                         clear_bit(R5_ReWrite, &dev->flags);
2038                 }
2039                 if (!rdev || !test_bit(In_sync, &rdev->flags)
2040                     || test_bit(R5_ReadError, &dev->flags)) {
2041                         s.failed++;
2042                         s.failed_num = i;
2043                 } else
2044                         set_bit(R5_Insync, &dev->flags);
2045         }
2046         rcu_read_unlock();
2047         PRINTK("locked=%d uptodate=%d to_read=%d"
2048                 " to_write=%d failed=%d failed_num=%d\n",
2049                 s.locked, s.uptodate, s.to_read, s.to_write,
2050                 s.failed, s.failed_num);
2051         /* check if the array has lost two devices and, if so, some requests might
2052          * need to be failed
2053          */
2054         if (s.failed > 1 && s.to_read+s.to_write+s.written)
2055                 handle_requests_to_failed_array(conf, sh, &s, disks,
2056                                                 &return_bi);
2057         if (s.failed > 1 && s.syncing) {
2058                 md_done_sync(conf->mddev, STRIPE_SECTORS,0);
2059                 clear_bit(STRIPE_SYNCING, &sh->state);
2060                 s.syncing = 0;
2061         }
2062
2063         /* might be able to return some write requests if the parity block
2064          * is safe, or on a failed drive
2065          */
2066         dev = &sh->dev[sh->pd_idx];
2067         if ( s.written &&
2068              ((test_bit(R5_Insync, &dev->flags) &&
2069                !test_bit(R5_LOCKED, &dev->flags) &&
2070                test_bit(R5_UPTODATE, &dev->flags)) ||
2071                (s.failed == 1 && s.failed_num == sh->pd_idx)))
2072                 handle_completed_write_requests(conf, sh, disks, &return_bi);
2073
2074         /* Now we might consider reading some blocks, either to check/generate
2075          * parity, or to satisfy requests
2076          * or to load a block that is being partially written.
2077          */
2078         if (s.to_read || s.non_overwrite ||
2079                 (s.syncing && (s.uptodate < disks)) || s.expanding)
2080                 handle_issuing_new_read_requests5(sh, &s, disks);
2081
2082         /* now to consider writing and what else, if anything should be read */
2083         if (s.to_write)
2084                 handle_issuing_new_write_requests5(conf, sh, &s, disks);
2085
2086         /* maybe we need to check and possibly fix the parity for this stripe
2087          * Any reads will already have been scheduled, so we just see if enough data
2088          * is available
2089          */
2090         if (s.syncing && s.locked == 0 &&
2091             !test_bit(STRIPE_INSYNC, &sh->state))
2092                 handle_parity_checks5(conf, sh, &s, disks);
2093         if (s.syncing && s.locked == 0 && test_bit(STRIPE_INSYNC, &sh->state)) {
2094                 md_done_sync(conf->mddev, STRIPE_SECTORS,1);
2095                 clear_bit(STRIPE_SYNCING, &sh->state);
2096         }
2097
2098         /* If the failed drive is just a ReadError, then we might need to progress
2099          * the repair/check process
2100          */
2101         if (s.failed == 1 && !conf->mddev->ro &&
2102             test_bit(R5_ReadError, &sh->dev[s.failed_num].flags)
2103             && !test_bit(R5_LOCKED, &sh->dev[s.failed_num].flags)
2104             && test_bit(R5_UPTODATE, &sh->dev[s.failed_num].flags)
2105                 ) {
2106                 dev = &sh->dev[s.failed_num];
2107                 if (!test_bit(R5_ReWrite, &dev->flags)) {
2108                         set_bit(R5_Wantwrite, &dev->flags);
2109                         set_bit(R5_ReWrite, &dev->flags);
2110                         set_bit(R5_LOCKED, &dev->flags);
2111                         s.locked++;
2112                 } else {
2113                         /* let's read it back */
2114                         set_bit(R5_Wantread, &dev->flags);
2115                         set_bit(R5_LOCKED, &dev->flags);
2116                         s.locked++;
2117                 }
2118         }
2119
2120         if (s.expanded && test_bit(STRIPE_EXPANDING, &sh->state)) {
2121                 /* Need to write out all blocks after computing parity */
2122                 sh->disks = conf->raid_disks;
2123                 sh->pd_idx = stripe_to_pdidx(sh->sector, conf, conf->raid_disks);
2124                 compute_parity5(sh, RECONSTRUCT_WRITE);
2125                 for (i = conf->raid_disks; i--; ) {
2126                         set_bit(R5_LOCKED, &sh->dev[i].flags);
2127                         s.locked++;
2128                         set_bit(R5_Wantwrite, &sh->dev[i].flags);
2129                 }
2130                 clear_bit(STRIPE_EXPANDING, &sh->state);
2131         } else if (s.expanded) {
2132                 clear_bit(STRIPE_EXPAND_READY, &sh->state);
2133                 atomic_dec(&conf->reshape_stripes);
2134                 wake_up(&conf->wait_for_overlap);
2135                 md_done_sync(conf->mddev, STRIPE_SECTORS, 1);
2136         }
2137
2138         if (s.expanding && s.locked == 0)
2139                 handle_stripe_expansion(conf, sh, NULL);
2140
2141         spin_unlock(&sh->lock);
2142
2143         return_io(return_bi);
2144
2145         for (i=disks; i-- ;) {
2146                 int rw;
2147                 struct bio *bi;
2148                 mdk_rdev_t *rdev;
2149                 if (test_and_clear_bit(R5_Wantwrite, &sh->dev[i].flags))
2150                         rw = WRITE;
2151                 else if (test_and_clear_bit(R5_Wantread, &sh->dev[i].flags))
2152                         rw = READ;
2153                 else
2154                         continue;
2155  
2156                 bi = &sh->dev[i].req;
2157  
2158                 bi->bi_rw = rw;
2159                 if (rw == WRITE)
2160                         bi->bi_end_io = raid5_end_write_request;
2161                 else
2162                         bi->bi_end_io = raid5_end_read_request;
2163  
2164                 rcu_read_lock();
2165                 rdev = rcu_dereference(conf->disks[i].rdev);
2166                 if (rdev && test_bit(Faulty, &rdev->flags))
2167                         rdev = NULL;
2168                 if (rdev)
2169                         atomic_inc(&rdev->nr_pending);
2170                 rcu_read_unlock();
2171  
2172                 if (rdev) {
2173                         if (s.syncing || s.expanding || s.expanded)
2174                                 md_sync_acct(rdev->bdev, STRIPE_SECTORS);
2175
2176                         bi->bi_bdev = rdev->bdev;
2177                         PRINTK("for %llu schedule op %ld on disc %d\n",
2178                                 (unsigned long long)sh->sector, bi->bi_rw, i);
2179                         atomic_inc(&sh->count);
2180                         bi->bi_sector = sh->sector + rdev->data_offset;
2181                         bi->bi_flags = 1 << BIO_UPTODATE;
2182                         bi->bi_vcnt = 1;        
2183                         bi->bi_max_vecs = 1;
2184                         bi->bi_idx = 0;
2185                         bi->bi_io_vec = &sh->dev[i].vec;
2186                         bi->bi_io_vec[0].bv_len = STRIPE_SIZE;
2187                         bi->bi_io_vec[0].bv_offset = 0;
2188                         bi->bi_size = STRIPE_SIZE;
2189                         bi->bi_next = NULL;
2190                         if (rw == WRITE &&
2191                             test_bit(R5_ReWrite, &sh->dev[i].flags))
2192                                 atomic_add(STRIPE_SECTORS, &rdev->corrected_errors);
2193                         generic_make_request(bi);
2194                 } else {
2195                         if (rw == WRITE)
2196                                 set_bit(STRIPE_DEGRADED, &sh->state);
2197                         PRINTK("skip op %ld on disc %d for sector %llu\n",
2198                                 bi->bi_rw, i, (unsigned long long)sh->sector);
2199                         clear_bit(R5_LOCKED, &sh->dev[i].flags);
2200                         set_bit(STRIPE_HANDLE, &sh->state);
2201                 }
2202         }
2203 }
2204
2205 static void handle_stripe6(struct stripe_head *sh, struct page *tmp_page)
2206 {
2207         raid6_conf_t *conf = sh->raid_conf;
2208         int disks = sh->disks;
2209         struct bio *return_bi = NULL;
2210         int i, pd_idx = sh->pd_idx;
2211         struct stripe_head_state s;
2212         struct r6_state r6s;
2213         struct r5dev *dev, *pdev, *qdev;
2214
2215         r6s.qd_idx = raid6_next_disk(pd_idx, disks);
2216         PRINTK("handling stripe %llu, state=%#lx cnt=%d, "
2217                 "pd_idx=%d, qd_idx=%d\n",
2218                (unsigned long long)sh->sector, sh->state,
2219                atomic_read(&sh->count), pd_idx, r6s.qd_idx);
2220         memset(&s, 0, sizeof(s));
2221
2222         spin_lock(&sh->lock);
2223         clear_bit(STRIPE_HANDLE, &sh->state);
2224         clear_bit(STRIPE_DELAYED, &sh->state);
2225
2226         s.syncing = test_bit(STRIPE_SYNCING, &sh->state);
2227         s.expanding = test_bit(STRIPE_EXPAND_SOURCE, &sh->state);
2228         s.expanded = test_bit(STRIPE_EXPAND_READY, &sh->state);
2229         /* Now to look around and see what can be done */
2230
2231         rcu_read_lock();
2232         for (i=disks; i--; ) {
2233                 mdk_rdev_t *rdev;
2234                 dev = &sh->dev[i];
2235                 clear_bit(R5_Insync, &dev->flags);
2236
2237                 PRINTK("check %d: state 0x%lx read %p write %p written %p\n",
2238                         i, dev->flags, dev->toread, dev->towrite, dev->written);
2239                 /* maybe we can reply to a read */
2240                 if (test_bit(R5_UPTODATE, &dev->flags) && dev->toread) {
2241                         struct bio *rbi, *rbi2;
2242                         PRINTK("Return read for disc %d\n", i);
2243                         spin_lock_irq(&conf->device_lock);
2244                         rbi = dev->toread;
2245                         dev->toread = NULL;
2246                         if (test_and_clear_bit(R5_Overlap, &dev->flags))
2247                                 wake_up(&conf->wait_for_overlap);
2248                         spin_unlock_irq(&conf->device_lock);
2249                         while (rbi && rbi->bi_sector < dev->sector + STRIPE_SECTORS) {
2250                                 copy_data(0, rbi, dev->page, dev->sector);
2251                                 rbi2 = r5_next_bio(rbi, dev->sector);
2252                                 spin_lock_irq(&conf->device_lock);
2253                                 if (--rbi->bi_phys_segments == 0) {
2254                                         rbi->bi_next = return_bi;
2255                                         return_bi = rbi;
2256                                 }
2257                                 spin_unlock_irq(&conf->device_lock);
2258                                 rbi = rbi2;
2259                         }
2260                 }
2261
2262                 /* now count some things */
2263                 if (test_bit(R5_LOCKED, &dev->flags)) s.locked++;
2264                 if (test_bit(R5_UPTODATE, &dev->flags)) s.uptodate++;
2265
2266
2267                 if (dev->toread)
2268                         s.to_read++;
2269                 if (dev->towrite) {
2270                         s.to_write++;
2271                         if (!test_bit(R5_OVERWRITE, &dev->flags))
2272                                 s.non_overwrite++;
2273                 }
2274                 if (dev->written)
2275                         s.written++;
2276                 rdev = rcu_dereference(conf->disks[i].rdev);
2277                 if (!rdev || !test_bit(In_sync, &rdev->flags)) {
2278                         /* The ReadError flag will just be confusing now */
2279                         clear_bit(R5_ReadError, &dev->flags);
2280                         clear_bit(R5_ReWrite, &dev->flags);
2281                 }
2282                 if (!rdev || !test_bit(In_sync, &rdev->flags)
2283                     || test_bit(R5_ReadError, &dev->flags)) {
2284                         if (s.failed < 2)
2285                                 r6s.failed_num[s.failed] = i;
2286                         s.failed++;
2287                 } else
2288                         set_bit(R5_Insync, &dev->flags);
2289         }
2290         rcu_read_unlock();
2291         PRINTK("locked=%d uptodate=%d to_read=%d"
2292                " to_write=%d failed=%d failed_num=%d,%d\n",
2293                s.locked, s.uptodate, s.to_read, s.to_write, s.failed,
2294                r6s.failed_num[0], r6s.failed_num[1]);
2295         /* check if the array has lost >2 devices and, if so, some requests
2296          * might need to be failed
2297          */
2298         if (s.failed > 2 && s.to_read+s.to_write+s.written)
2299                 handle_requests_to_failed_array(conf, sh, &s, disks,
2300                                                 &return_bi);
2301         if (s.failed > 2 && s.syncing) {
2302                 md_done_sync(conf->mddev, STRIPE_SECTORS,0);
2303                 clear_bit(STRIPE_SYNCING, &sh->state);
2304                 s.syncing = 0;
2305         }
2306
2307         /*
2308          * might be able to return some write requests if the parity blocks
2309          * are safe, or on a failed drive
2310          */
2311         pdev = &sh->dev[pd_idx];
2312         r6s.p_failed = (s.failed >= 1 && r6s.failed_num[0] == pd_idx)
2313                 || (s.failed >= 2 && r6s.failed_num[1] == pd_idx);
2314         qdev = &sh->dev[r6s.qd_idx];
2315         r6s.q_failed = (s.failed >= 1 && r6s.failed_num[0] == r6s.qd_idx)
2316                 || (s.failed >= 2 && r6s.failed_num[1] == r6s.qd_idx);
2317
2318         if ( s.written &&
2319              ( r6s.p_failed || ((test_bit(R5_Insync, &pdev->flags)
2320                              && !test_bit(R5_LOCKED, &pdev->flags)
2321                              && test_bit(R5_UPTODATE, &pdev->flags)))) &&
2322              ( r6s.q_failed || ((test_bit(R5_Insync, &qdev->flags)
2323                              && !test_bit(R5_LOCKED, &qdev->flags)
2324                              && test_bit(R5_UPTODATE, &qdev->flags)))))
2325                 handle_completed_write_requests(conf, sh, disks, &return_bi);
2326
2327         /* Now we might consider reading some blocks, either to check/generate
2328          * parity, or to satisfy requests
2329          * or to load a block that is being partially written.
2330          */
2331         if (s.to_read || s.non_overwrite || (s.to_write && s.failed) ||
2332             (s.syncing && (s.uptodate < disks)) || s.expanding)
2333                 handle_issuing_new_read_requests6(sh, &s, &r6s, disks);
2334
2335         /* now to consider writing and what else, if anything should be read */
2336         if (s.to_write)
2337                 handle_issuing_new_write_requests6(conf, sh, &s, &r6s, disks);
2338
2339         /* maybe we need to check and possibly fix the parity for this stripe
2340          * Any reads will already have been scheduled, so we just see if enough
2341          * data is available
2342          */
2343         if (s.syncing && s.locked == 0 && !test_bit(STRIPE_INSYNC, &sh->state))
2344                 handle_parity_checks6(conf, sh, &s, &r6s, tmp_page, disks);
2345
2346         if (s.syncing && s.locked == 0 && test_bit(STRIPE_INSYNC, &sh->state)) {
2347                 md_done_sync(conf->mddev, STRIPE_SECTORS,1);
2348                 clear_bit(STRIPE_SYNCING, &sh->state);
2349         }
2350
2351         /* If the failed drives are just a ReadError, then we might need
2352          * to progress the repair/check process
2353          */
2354         if (s.failed <= 2 && !conf->mddev->ro)
2355                 for (i = 0; i < s.failed; i++) {
2356                         dev = &sh->dev[r6s.failed_num[i]];
2357                         if (test_bit(R5_ReadError, &dev->flags)
2358                             && !test_bit(R5_LOCKED, &dev->flags)
2359                             && test_bit(R5_UPTODATE, &dev->flags)
2360                                 ) {
2361                                 if (!test_bit(R5_ReWrite, &dev->flags)) {
2362                                         set_bit(R5_Wantwrite, &dev->flags);
2363                                         set_bit(R5_ReWrite, &dev->flags);
2364                                         set_bit(R5_LOCKED, &dev->flags);
2365                                 } else {
2366                                         /* let's read it back */
2367                                         set_bit(R5_Wantread, &dev->flags);
2368                                         set_bit(R5_LOCKED, &dev->flags);
2369                                 }
2370                         }
2371                 }
2372
2373         if (s.expanded && test_bit(STRIPE_EXPANDING, &sh->state)) {
2374                 /* Need to write out all blocks after computing P&Q */
2375                 sh->disks = conf->raid_disks;
2376                 sh->pd_idx = stripe_to_pdidx(sh->sector, conf,
2377                                              conf->raid_disks);
2378                 compute_parity6(sh, RECONSTRUCT_WRITE);
2379                 for (i = conf->raid_disks ; i-- ;  ) {
2380                         set_bit(R5_LOCKED, &sh->dev[i].flags);
2381                         s.locked++;
2382                         set_bit(R5_Wantwrite, &sh->dev[i].flags);
2383                 }
2384                 clear_bit(STRIPE_EXPANDING, &sh->state);
2385         } else if (s.expanded) {
2386                 clear_bit(STRIPE_EXPAND_READY, &sh->state);
2387                 atomic_dec(&conf->reshape_stripes);
2388                 wake_up(&conf->wait_for_overlap);
2389                 md_done_sync(conf->mddev, STRIPE_SECTORS, 1);
2390         }
2391
2392         if (s.expanding && s.locked == 0)
2393                 handle_stripe_expansion(conf, sh, &r6s);
2394
2395         spin_unlock(&sh->lock);
2396
2397         return_io(return_bi);
2398
2399         for (i=disks; i-- ;) {
2400                 int rw;
2401                 struct bio *bi;
2402                 mdk_rdev_t *rdev;
2403                 if (test_and_clear_bit(R5_Wantwrite, &sh->dev[i].flags))
2404                         rw = WRITE;
2405                 else if (test_and_clear_bit(R5_Wantread, &sh->dev[i].flags))
2406                         rw = READ;
2407                 else
2408                         continue;
2409
2410                 bi = &sh->dev[i].req;
2411
2412                 bi->bi_rw = rw;
2413                 if (rw == WRITE)
2414                         bi->bi_end_io = raid5_end_write_request;
2415                 else
2416                         bi->bi_end_io = raid5_end_read_request;
2417
2418                 rcu_read_lock();
2419                 rdev = rcu_dereference(conf->disks[i].rdev);
2420                 if (rdev && test_bit(Faulty, &rdev->flags))
2421                         rdev = NULL;
2422                 if (rdev)
2423                         atomic_inc(&rdev->nr_pending);
2424                 rcu_read_unlock();
2425
2426                 if (rdev) {
2427                         if (s.syncing || s.expanding || s.expanded)
2428                                 md_sync_acct(rdev->bdev, STRIPE_SECTORS);
2429
2430                         bi->bi_bdev = rdev->bdev;
2431                         PRINTK("for %llu schedule op %ld on disc %d\n",
2432                                 (unsigned long long)sh->sector, bi->bi_rw, i);
2433                         atomic_inc(&sh->count);
2434                         bi->bi_sector = sh->sector + rdev->data_offset;
2435                         bi->bi_flags = 1 << BIO_UPTODATE;
2436                         bi->bi_vcnt = 1;
2437                         bi->bi_max_vecs = 1;
2438                         bi->bi_idx = 0;
2439                         bi->bi_io_vec = &sh->dev[i].vec;
2440                         bi->bi_io_vec[0].bv_len = STRIPE_SIZE;
2441                         bi->bi_io_vec[0].bv_offset = 0;
2442                         bi->bi_size = STRIPE_SIZE;
2443                         bi->bi_next = NULL;
2444                         if (rw == WRITE &&
2445                             test_bit(R5_ReWrite, &sh->dev[i].flags))
2446                                 atomic_add(STRIPE_SECTORS, &rdev->corrected_errors);
2447                         generic_make_request(bi);
2448                 } else {
2449                         if (rw == WRITE)
2450                                 set_bit(STRIPE_DEGRADED, &sh->state);
2451                         PRINTK("skip op %ld on disc %d for sector %llu\n",
2452                                 bi->bi_rw, i, (unsigned long long)sh->sector);
2453                         clear_bit(R5_LOCKED, &sh->dev[i].flags);
2454                         set_bit(STRIPE_HANDLE, &sh->state);
2455                 }
2456         }
2457 }
2458
2459 static void handle_stripe(struct stripe_head *sh, struct page *tmp_page)
2460 {
2461         if (sh->raid_conf->level == 6)
2462                 handle_stripe6(sh, tmp_page);
2463         else
2464                 handle_stripe5(sh);
2465 }
2466
2467
2468
2469 static void raid5_activate_delayed(raid5_conf_t *conf)
2470 {
2471         if (atomic_read(&conf->preread_active_stripes) < IO_THRESHOLD) {
2472                 while (!list_empty(&conf->delayed_list)) {
2473                         struct list_head *l = conf->delayed_list.next;
2474                         struct stripe_head *sh;
2475                         sh = list_entry(l, struct stripe_head, lru);
2476                         list_del_init(l);
2477                         clear_bit(STRIPE_DELAYED, &sh->state);
2478                         if (!test_and_set_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
2479                                 atomic_inc(&conf->preread_active_stripes);
2480                         list_add_tail(&sh->lru, &conf->handle_list);
2481                 }
2482         }
2483 }
2484
2485 static void activate_bit_delay(raid5_conf_t *conf)
2486 {
2487         /* device_lock is held */
2488         struct list_head head;
2489         list_add(&head, &conf->bitmap_list);
2490         list_del_init(&conf->bitmap_list);
2491         while (!list_empty(&head)) {
2492                 struct stripe_head *sh = list_entry(head.next, struct stripe_head, lru);
2493                 list_del_init(&sh->lru);
2494                 atomic_inc(&sh->count);
2495                 __release_stripe(conf, sh);
2496         }
2497 }
2498
2499 static void unplug_slaves(mddev_t *mddev)
2500 {
2501         raid5_conf_t *conf = mddev_to_conf(mddev);
2502         int i;
2503
2504         rcu_read_lock();
2505         for (i=0; i<mddev->raid_disks; i++) {
2506                 mdk_rdev_t *rdev = rcu_dereference(conf->disks[i].rdev);
2507                 if (rdev && !test_bit(Faulty, &rdev->flags) && atomic_read(&rdev->nr_pending)) {
2508                         request_queue_t *r_queue = bdev_get_queue(rdev->bdev);
2509
2510                         atomic_inc(&rdev->nr_pending);
2511                         rcu_read_unlock();
2512
2513                         if (r_queue->unplug_fn)
2514                                 r_queue->unplug_fn(r_queue);
2515
2516                         rdev_dec_pending(rdev, mddev);
2517                         rcu_read_lock();
2518                 }
2519         }
2520         rcu_read_unlock();
2521 }
2522
2523 static void raid5_unplug_device(request_queue_t *q)
2524 {
2525         mddev_t *mddev = q->queuedata;
2526         raid5_conf_t *conf = mddev_to_conf(mddev);
2527         unsigned long flags;
2528
2529         spin_lock_irqsave(&conf->device_lock, flags);
2530
2531         if (blk_remove_plug(q)) {
2532                 conf->seq_flush++;
2533                 raid5_activate_delayed(conf);
2534         }
2535         md_wakeup_thread(mddev->thread);
2536
2537         spin_unlock_irqrestore(&conf->device_lock, flags);
2538
2539         unplug_slaves(mddev);
2540 }
2541
2542 static int raid5_issue_flush(request_queue_t *q, struct gendisk *disk,
2543                              sector_t *error_sector)
2544 {
2545         mddev_t *mddev = q->queuedata;
2546         raid5_conf_t *conf = mddev_to_conf(mddev);
2547         int i, ret = 0;
2548
2549         rcu_read_lock();
2550         for (i=0; i<mddev->raid_disks && ret == 0; i++) {
2551                 mdk_rdev_t *rdev = rcu_dereference(conf->disks[i].rdev);
2552                 if (rdev && !test_bit(Faulty, &rdev->flags)) {
2553                         struct block_device *bdev = rdev->bdev;
2554                         request_queue_t *r_queue = bdev_get_queue(bdev);
2555
2556                         if (!r_queue->issue_flush_fn)
2557                                 ret = -EOPNOTSUPP;
2558                         else {
2559                                 atomic_inc(&rdev->nr_pending);
2560                                 rcu_read_unlock();
2561                                 ret = r_queue->issue_flush_fn(r_queue, bdev->bd_disk,
2562                                                               error_sector);
2563                                 rdev_dec_pending(rdev, mddev);
2564                                 rcu_read_lock();
2565                         }
2566                 }
2567         }
2568         rcu_read_unlock();
2569         return ret;
2570 }
2571
2572 static int raid5_congested(void *data, int bits)
2573 {
2574         mddev_t *mddev = data;
2575         raid5_conf_t *conf = mddev_to_conf(mddev);
2576
2577         /* No difference between reads and writes.  Just check
2578          * how busy the stripe_cache is
2579          */
2580         if (conf->inactive_blocked)
2581                 return 1;
2582         if (conf->quiesce)
2583                 return 1;
2584         if (list_empty_careful(&conf->inactive_list))
2585                 return 1;
2586
2587         return 0;
2588 }
2589
2590 /* We want read requests to align with chunks where possible,
2591  * but write requests don't need to.
2592  */
2593 static int raid5_mergeable_bvec(request_queue_t *q, struct bio *bio, struct bio_vec *biovec)
2594 {
2595         mddev_t *mddev = q->queuedata;
2596         sector_t sector = bio->bi_sector + get_start_sect(bio->bi_bdev);
2597         int max;
2598         unsigned int chunk_sectors = mddev->chunk_size >> 9;
2599         unsigned int bio_sectors = bio->bi_size >> 9;
2600
2601         if (bio_data_dir(bio) == WRITE)
2602                 return biovec->bv_len; /* always allow writes to be mergeable */
2603
2604         max =  (chunk_sectors - ((sector & (chunk_sectors - 1)) + bio_sectors)) << 9;
2605         if (max < 0) max = 0;
2606         if (max <= biovec->bv_len && bio_sectors == 0)
2607                 return biovec->bv_len;
2608         else
2609                 return max;
2610 }
2611
2612
2613 static int in_chunk_boundary(mddev_t *mddev, struct bio *bio)
2614 {
2615         sector_t sector = bio->bi_sector + get_start_sect(bio->bi_bdev);
2616         unsigned int chunk_sectors = mddev->chunk_size >> 9;
2617         unsigned int bio_sectors = bio->bi_size >> 9;
2618
2619         return  chunk_sectors >=
2620                 ((sector & (chunk_sectors - 1)) + bio_sectors);
2621 }
2622
2623 /*
2624  *  add bio to the retry LIFO  ( in O(1) ... we are in interrupt )
2625  *  later sampled by raid5d.
2626  */
2627 static void add_bio_to_retry(struct bio *bi,raid5_conf_t *conf)
2628 {
2629         unsigned long flags;
2630
2631         spin_lock_irqsave(&conf->device_lock, flags);
2632
2633         bi->bi_next = conf->retry_read_aligned_list;
2634         conf->retry_read_aligned_list = bi;
2635
2636         spin_unlock_irqrestore(&conf->device_lock, flags);
2637         md_wakeup_thread(conf->mddev->thread);
2638 }
2639
2640
2641 static struct bio *remove_bio_from_retry(raid5_conf_t *conf)
2642 {
2643         struct bio *bi;
2644
2645         bi = conf->retry_read_aligned;
2646         if (bi) {
2647                 conf->retry_read_aligned = NULL;
2648                 return bi;
2649         }
2650         bi = conf->retry_read_aligned_list;
2651         if(bi) {
2652                 conf->retry_read_aligned_list = bi->bi_next;
2653                 bi->bi_next = NULL;
2654                 bi->bi_phys_segments = 1; /* biased count of active stripes */
2655                 bi->bi_hw_segments = 0; /* count of processed stripes */
2656         }
2657
2658         return bi;
2659 }
2660
2661
2662 /*
2663  *  The "raid5_align_endio" should check if the read succeeded and if it
2664  *  did, call bio_endio on the original bio (having bio_put the new bio
2665  *  first).
2666  *  If the read failed..
2667  */
2668 static int raid5_align_endio(struct bio *bi, unsigned int bytes, int error)
2669 {
2670         struct bio* raid_bi  = bi->bi_private;
2671         mddev_t *mddev;
2672         raid5_conf_t *conf;
2673         int uptodate = test_bit(BIO_UPTODATE, &bi->bi_flags);
2674         mdk_rdev_t *rdev;
2675
2676         if (bi->bi_size)
2677                 return 1;
2678         bio_put(bi);
2679
2680         mddev = raid_bi->bi_bdev->bd_disk->queue->queuedata;
2681         conf = mddev_to_conf(mddev);
2682         rdev = (void*)raid_bi->bi_next;
2683         raid_bi->bi_next = NULL;
2684
2685         rdev_dec_pending(rdev, conf->mddev);
2686
2687         if (!error && uptodate) {
2688                 bio_endio(raid_bi, bytes, 0);
2689                 if (atomic_dec_and_test(&conf->active_aligned_reads))
2690                         wake_up(&conf->wait_for_stripe);
2691                 return 0;
2692         }
2693
2694
2695         PRINTK("raid5_align_endio : io error...handing IO for a retry\n");
2696
2697         add_bio_to_retry(raid_bi, conf);
2698         return 0;
2699 }
2700
2701 static int bio_fits_rdev(struct bio *bi)
2702 {
2703         request_queue_t *q = bdev_get_queue(bi->bi_bdev);
2704
2705         if ((bi->bi_size>>9) > q->max_sectors)
2706                 return 0;
2707         blk_recount_segments(q, bi);
2708         if (bi->bi_phys_segments > q->max_phys_segments ||
2709             bi->bi_hw_segments > q->max_hw_segments)
2710                 return 0;
2711
2712         if (q->merge_bvec_fn)
2713                 /* it's too hard to apply the merge_bvec_fn at this stage,
2714                  * just just give up
2715                  */
2716                 return 0;
2717
2718         return 1;
2719 }
2720
2721
2722 static int chunk_aligned_read(request_queue_t *q, struct bio * raid_bio)
2723 {
2724         mddev_t *mddev = q->queuedata;
2725         raid5_conf_t *conf = mddev_to_conf(mddev);
2726         const unsigned int raid_disks = conf->raid_disks;
2727         const unsigned int data_disks = raid_disks - conf->max_degraded;
2728         unsigned int dd_idx, pd_idx;
2729         struct bio* align_bi;
2730         mdk_rdev_t *rdev;
2731
2732         if (!in_chunk_boundary(mddev, raid_bio)) {
2733                 PRINTK("chunk_aligned_read : non aligned\n");
2734                 return 0;
2735         }
2736         /*
2737          * use bio_clone to make a copy of the bio
2738          */
2739         align_bi = bio_clone(raid_bio, GFP_NOIO);
2740         if (!align_bi)
2741                 return 0;
2742         /*
2743          *   set bi_end_io to a new function, and set bi_private to the
2744          *     original bio.
2745          */
2746         align_bi->bi_end_io  = raid5_align_endio;
2747         align_bi->bi_private = raid_bio;
2748         /*
2749          *      compute position
2750          */
2751         align_bi->bi_sector =  raid5_compute_sector(raid_bio->bi_sector,
2752                                         raid_disks,
2753                                         data_disks,
2754                                         &dd_idx,
2755                                         &pd_idx,
2756                                         conf);
2757
2758         rcu_read_lock();
2759         rdev = rcu_dereference(conf->disks[dd_idx].rdev);
2760         if (rdev && test_bit(In_sync, &rdev->flags)) {
2761                 atomic_inc(&rdev->nr_pending);
2762                 rcu_read_unlock();
2763                 raid_bio->bi_next = (void*)rdev;
2764                 align_bi->bi_bdev =  rdev->bdev;
2765                 align_bi->bi_flags &= ~(1 << BIO_SEG_VALID);
2766                 align_bi->bi_sector += rdev->data_offset;
2767
2768                 if (!bio_fits_rdev(align_bi)) {
2769                         /* too big in some way */
2770                         bio_put(align_bi);
2771                         rdev_dec_pending(rdev, mddev);
2772                         return 0;
2773                 }
2774
2775                 spin_lock_irq(&conf->device_lock);
2776                 wait_event_lock_irq(conf->wait_for_stripe,
2777                                     conf->quiesce == 0,
2778                                     conf->device_lock, /* nothing */);
2779                 atomic_inc(&conf->active_aligned_reads);
2780                 spin_unlock_irq(&conf->device_lock);
2781
2782                 generic_make_request(align_bi);
2783                 return 1;
2784         } else {
2785                 rcu_read_unlock();
2786                 bio_put(align_bi);
2787                 return 0;
2788         }
2789 }
2790
2791
2792 static int make_request(request_queue_t *q, struct bio * bi)
2793 {
2794         mddev_t *mddev = q->queuedata;
2795         raid5_conf_t *conf = mddev_to_conf(mddev);
2796         unsigned int dd_idx, pd_idx;
2797         sector_t new_sector;
2798         sector_t logical_sector, last_sector;
2799         struct stripe_head *sh;
2800         const int rw = bio_data_dir(bi);
2801         int remaining;
2802
2803         if (unlikely(bio_barrier(bi))) {
2804                 bio_endio(bi, bi->bi_size, -EOPNOTSUPP);
2805                 return 0;
2806         }
2807
2808         md_write_start(mddev, bi);
2809
2810         disk_stat_inc(mddev->gendisk, ios[rw]);
2811         disk_stat_add(mddev->gendisk, sectors[rw], bio_sectors(bi));
2812
2813         if (rw == READ &&
2814              mddev->reshape_position == MaxSector &&
2815              chunk_aligned_read(q,bi))
2816                 return 0;
2817
2818         logical_sector = bi->bi_sector & ~((sector_t)STRIPE_SECTORS-1);
2819         last_sector = bi->bi_sector + (bi->bi_size>>9);
2820         bi->bi_next = NULL;
2821         bi->bi_phys_segments = 1;       /* over-loaded to count active stripes */
2822
2823         for (;logical_sector < last_sector; logical_sector += STRIPE_SECTORS) {
2824                 DEFINE_WAIT(w);
2825                 int disks, data_disks;
2826
2827         retry:
2828                 prepare_to_wait(&conf->wait_for_overlap, &w, TASK_UNINTERRUPTIBLE);
2829                 if (likely(conf->expand_progress == MaxSector))
2830                         disks = conf->raid_disks;
2831                 else {
2832                         /* spinlock is needed as expand_progress may be
2833                          * 64bit on a 32bit platform, and so it might be
2834                          * possible to see a half-updated value
2835                          * Ofcourse expand_progress could change after
2836                          * the lock is dropped, so once we get a reference
2837                          * to the stripe that we think it is, we will have
2838                          * to check again.
2839                          */
2840                         spin_lock_irq(&conf->device_lock);
2841                         disks = conf->raid_disks;
2842                         if (logical_sector >= conf->expand_progress)
2843                                 disks = conf->previous_raid_disks;
2844                         else {
2845                                 if (logical_sector >= conf->expand_lo) {
2846                                         spin_unlock_irq(&conf->device_lock);
2847                                         schedule();
2848                                         goto retry;
2849                                 }
2850                         }
2851                         spin_unlock_irq(&conf->device_lock);
2852                 }
2853                 data_disks = disks - conf->max_degraded;
2854
2855                 new_sector = raid5_compute_sector(logical_sector, disks, data_disks,
2856                                                   &dd_idx, &pd_idx, conf);
2857                 PRINTK("raid5: make_request, sector %llu logical %llu\n",
2858                         (unsigned long long)new_sector, 
2859                         (unsigned long long)logical_sector);
2860
2861                 sh = get_active_stripe(conf, new_sector, disks, pd_idx, (bi->bi_rw&RWA_MASK));
2862                 if (sh) {
2863                         if (unlikely(conf->expand_progress != MaxSector)) {
2864                                 /* expansion might have moved on while waiting for a
2865                                  * stripe, so we must do the range check again.
2866                                  * Expansion could still move past after this
2867                                  * test, but as we are holding a reference to
2868                                  * 'sh', we know that if that happens,
2869                                  *  STRIPE_EXPANDING will get set and the expansion
2870                                  * won't proceed until we finish with the stripe.
2871                                  */
2872                                 int must_retry = 0;
2873                                 spin_lock_irq(&conf->device_lock);
2874                                 if (logical_sector <  conf->expand_progress &&
2875                                     disks == conf->previous_raid_disks)
2876                                         /* mismatch, need to try again */
2877                                         must_retry = 1;
2878                                 spin_unlock_irq(&conf->device_lock);
2879                                 if (must_retry) {
2880                                         release_stripe(sh);
2881                                         goto retry;
2882                                 }
2883                         }
2884                         /* FIXME what if we get a false positive because these
2885                          * are being updated.
2886                          */
2887                         if (logical_sector >= mddev->suspend_lo &&
2888                             logical_sector < mddev->suspend_hi) {
2889                                 release_stripe(sh);
2890                                 schedule();
2891                                 goto retry;
2892                         }
2893
2894                         if (test_bit(STRIPE_EXPANDING, &sh->state) ||
2895                             !add_stripe_bio(sh, bi, dd_idx, (bi->bi_rw&RW_MASK))) {
2896                                 /* Stripe is busy expanding or
2897                                  * add failed due to overlap.  Flush everything
2898                                  * and wait a while
2899                                  */
2900                                 raid5_unplug_device(mddev->queue);
2901                                 release_stripe(sh);
2902                                 schedule();
2903                                 goto retry;
2904                         }
2905                         finish_wait(&conf->wait_for_overlap, &w);
2906                         handle_stripe(sh, NULL);
2907                         release_stripe(sh);
2908                 } else {
2909                         /* cannot get stripe for read-ahead, just give-up */
2910                         clear_bit(BIO_UPTODATE, &bi->bi_flags);
2911                         finish_wait(&conf->wait_for_overlap, &w);
2912                         break;
2913                 }
2914                         
2915         }
2916         spin_lock_irq(&conf->device_lock);
2917         remaining = --bi->bi_phys_segments;
2918         spin_unlock_irq(&conf->device_lock);
2919         if (remaining == 0) {
2920                 int bytes = bi->bi_size;
2921
2922                 if ( rw == WRITE )
2923                         md_write_end(mddev);
2924                 bi->bi_size = 0;
2925                 bi->bi_end_io(bi, bytes,
2926                               test_bit(BIO_UPTODATE, &bi->bi_flags)
2927                                 ? 0 : -EIO);
2928         }
2929         return 0;
2930 }
2931
2932 static sector_t reshape_request(mddev_t *mddev, sector_t sector_nr, int *skipped)
2933 {
2934         /* reshaping is quite different to recovery/resync so it is
2935          * handled quite separately ... here.
2936          *
2937          * On each call to sync_request, we gather one chunk worth of
2938          * destination stripes and flag them as expanding.
2939          * Then we find all the source stripes and request reads.
2940          * As the reads complete, handle_stripe will copy the data
2941          * into the destination stripe and release that stripe.
2942          */
2943         raid5_conf_t *conf = (raid5_conf_t *) mddev->private;
2944         struct stripe_head *sh;
2945         int pd_idx;
2946         sector_t first_sector, last_sector;
2947         int raid_disks = conf->previous_raid_disks;
2948         int data_disks = raid_disks - conf->max_degraded;
2949         int new_data_disks = conf->raid_disks - conf->max_degraded;
2950         int i;
2951         int dd_idx;
2952         sector_t writepos, safepos, gap;
2953
2954         if (sector_nr == 0 &&
2955             conf->expand_progress != 0) {
2956                 /* restarting in the middle, skip the initial sectors */
2957                 sector_nr = conf->expand_progress;
2958                 sector_div(sector_nr, new_data_disks);
2959                 *skipped = 1;
2960                 return sector_nr;
2961         }
2962
2963         /* we update the metadata when there is more than 3Meg
2964          * in the block range (that is rather arbitrary, should
2965          * probably be time based) or when the data about to be
2966          * copied would over-write the source of the data at
2967          * the front of the range.
2968          * i.e. one new_stripe forward from expand_progress new_maps
2969          * to after where expand_lo old_maps to
2970          */
2971         writepos = conf->expand_progress +
2972                 conf->chunk_size/512*(new_data_disks);
2973         sector_div(writepos, new_data_disks);
2974         safepos = conf->expand_lo;
2975         sector_div(safepos, data_disks);
2976         gap = conf->expand_progress - conf->expand_lo;
2977
2978         if (writepos >= safepos ||
2979             gap > (new_data_disks)*3000*2 /*3Meg*/) {
2980                 /* Cannot proceed until we've updated the superblock... */
2981                 wait_event(conf->wait_for_overlap,
2982                            atomic_read(&conf->reshape_stripes)==0);
2983                 mddev->reshape_position = conf->expand_progress;
2984                 set_bit(MD_CHANGE_DEVS, &mddev->flags);
2985                 md_wakeup_thread(mddev->thread);
2986                 wait_event(mddev->sb_wait, mddev->flags == 0 ||
2987                            kthread_should_stop());
2988                 spin_lock_irq(&conf->device_lock);
2989                 conf->expand_lo = mddev->reshape_position;
2990                 spin_unlock_irq(&conf->device_lock);
2991                 wake_up(&conf->wait_for_overlap);
2992         }
2993
2994         for (i=0; i < conf->chunk_size/512; i+= STRIPE_SECTORS) {
2995                 int j;
2996                 int skipped = 0;
2997                 pd_idx = stripe_to_pdidx(sector_nr+i, conf, conf->raid_disks);
2998                 sh = get_active_stripe(conf, sector_nr+i,
2999                                        conf->raid_disks, pd_idx, 0);
3000                 set_bit(STRIPE_EXPANDING, &sh->state);
3001                 atomic_inc(&conf->reshape_stripes);
3002                 /* If any of this stripe is beyond the end of the old
3003                  * array, then we need to zero those blocks
3004                  */
3005                 for (j=sh->disks; j--;) {
3006                         sector_t s;
3007                         if (j == sh->pd_idx)
3008                                 continue;
3009                         if (conf->level == 6 &&
3010                             j == raid6_next_disk(sh->pd_idx, sh->disks))
3011                                 continue;
3012                         s = compute_blocknr(sh, j);
3013                         if (s < (mddev->array_size<<1)) {
3014                                 skipped = 1;
3015                                 continue;
3016                         }
3017                         memset(page_address(sh->dev[j].page), 0, STRIPE_SIZE);
3018                         set_bit(R5_Expanded, &sh->dev[j].flags);
3019                         set_bit(R5_UPTODATE, &sh->dev[j].flags);
3020                 }
3021                 if (!skipped) {
3022                         set_bit(STRIPE_EXPAND_READY, &sh->state);
3023                         set_bit(STRIPE_HANDLE, &sh->state);
3024                 }
3025                 release_stripe(sh);
3026         }
3027         spin_lock_irq(&conf->device_lock);
3028         conf->expand_progress = (sector_nr + i) * new_data_disks;
3029         spin_unlock_irq(&conf->device_lock);
3030         /* Ok, those stripe are ready. We can start scheduling
3031          * reads on the source stripes.
3032          * The source stripes are determined by mapping the first and last
3033          * block on the destination stripes.
3034          */
3035         first_sector =
3036                 raid5_compute_sector(sector_nr*(new_data_disks),
3037                                      raid_disks, data_disks,
3038                                      &dd_idx, &pd_idx, conf);
3039         last_sector =
3040                 raid5_compute_sector((sector_nr+conf->chunk_size/512)
3041                                      *(new_data_disks) -1,
3042                                      raid_disks, data_disks,
3043                                      &dd_idx, &pd_idx, conf);
3044         if (last_sector >= (mddev->size<<1))
3045                 last_sector = (mddev->size<<1)-1;
3046         while (first_sector <= last_sector) {
3047                 pd_idx = stripe_to_pdidx(first_sector, conf,
3048                                          conf->previous_raid_disks);
3049                 sh = get_active_stripe(conf, first_sector,
3050                                        conf->previous_raid_disks, pd_idx, 0);
3051                 set_bit(STRIPE_EXPAND_SOURCE, &sh->state);
3052                 set_bit(STRIPE_HANDLE, &sh->state);
3053                 release_stripe(sh);
3054                 first_sector += STRIPE_SECTORS;
3055         }
3056         return conf->chunk_size>>9;
3057 }
3058
3059 /* FIXME go_faster isn't used */
3060 static inline sector_t sync_request(mddev_t *mddev, sector_t sector_nr, int *skipped, int go_faster)
3061 {
3062         raid5_conf_t *conf = (raid5_conf_t *) mddev->private;
3063         struct stripe_head *sh;
3064         int pd_idx;
3065         int raid_disks = conf->raid_disks;
3066         sector_t max_sector = mddev->size << 1;
3067         int sync_blocks;
3068         int still_degraded = 0;
3069         int i;
3070
3071         if (sector_nr >= max_sector) {
3072                 /* just being told to finish up .. nothing much to do */
3073                 unplug_slaves(mddev);
3074                 if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery)) {
3075                         end_reshape(conf);
3076                         return 0;
3077                 }
3078
3079                 if (mddev->curr_resync < max_sector) /* aborted */
3080                         bitmap_end_sync(mddev->bitmap, mddev->curr_resync,
3081                                         &sync_blocks, 1);
3082                 else /* completed sync */
3083                         conf->fullsync = 0;
3084                 bitmap_close_sync(mddev->bitmap);
3085
3086                 return 0;
3087         }
3088
3089         if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery))
3090                 return reshape_request(mddev, sector_nr, skipped);
3091
3092         /* if there is too many failed drives and we are trying
3093          * to resync, then assert that we are finished, because there is
3094          * nothing we can do.
3095          */
3096         if (mddev->degraded >= conf->max_degraded &&
3097             test_bit(MD_RECOVERY_SYNC, &mddev->recovery)) {
3098                 sector_t rv = (mddev->size << 1) - sector_nr;
3099                 *skipped = 1;
3100                 return rv;
3101         }
3102         if (!bitmap_start_sync(mddev->bitmap, sector_nr, &sync_blocks, 1) &&
3103             !test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery) &&
3104             !conf->fullsync && sync_blocks >= STRIPE_SECTORS) {
3105                 /* we can skip this block, and probably more */
3106                 sync_blocks /= STRIPE_SECTORS;
3107                 *skipped = 1;
3108                 return sync_blocks * STRIPE_SECTORS; /* keep things rounded to whole stripes */
3109         }
3110
3111         pd_idx = stripe_to_pdidx(sector_nr, conf, raid_disks);
3112         sh = get_active_stripe(conf, sector_nr, raid_disks, pd_idx, 1);
3113         if (sh == NULL) {
3114                 sh = get_active_stripe(conf, sector_nr, raid_disks, pd_idx, 0);
3115                 /* make sure we don't swamp the stripe cache if someone else
3116                  * is trying to get access
3117                  */
3118                 schedule_timeout_uninterruptible(1);
3119         }
3120         /* Need to check if array will still be degraded after recovery/resync
3121          * We don't need to check the 'failed' flag as when that gets set,
3122          * recovery aborts.
3123          */
3124         for (i=0; i<mddev->raid_disks; i++)
3125                 if (conf->disks[i].rdev == NULL)
3126                         still_degraded = 1;
3127
3128         bitmap_start_sync(mddev->bitmap, sector_nr, &sync_blocks, still_degraded);
3129
3130         spin_lock(&sh->lock);
3131         set_bit(STRIPE_SYNCING, &sh->state);
3132         clear_bit(STRIPE_INSYNC, &sh->state);
3133         spin_unlock(&sh->lock);
3134
3135         handle_stripe(sh, NULL);
3136         release_stripe(sh);
3137
3138         return STRIPE_SECTORS;
3139 }
3140
3141 static int  retry_aligned_read(raid5_conf_t *conf, struct bio *raid_bio)
3142 {
3143         /* We may not be able to submit a whole bio at once as there
3144          * may not be enough stripe_heads available.
3145          * We cannot pre-allocate enough stripe_heads as we may need
3146          * more than exist in the cache (if we allow ever large chunks).
3147          * So we do one stripe head at a time and record in
3148          * ->bi_hw_segments how many have been done.
3149          *
3150          * We *know* that this entire raid_bio is in one chunk, so
3151          * it will be only one 'dd_idx' and only need one call to raid5_compute_sector.
3152          */
3153         struct stripe_head *sh;
3154         int dd_idx, pd_idx;
3155         sector_t sector, logical_sector, last_sector;
3156         int scnt = 0;
3157         int remaining;
3158         int handled = 0;
3159
3160         logical_sector = raid_bio->bi_sector & ~((sector_t)STRIPE_SECTORS-1);
3161         sector = raid5_compute_sector(  logical_sector,
3162                                         conf->raid_disks,
3163                                         conf->raid_disks - conf->max_degraded,
3164                                         &dd_idx,
3165                                         &pd_idx,
3166                                         conf);
3167         last_sector = raid_bio->bi_sector + (raid_bio->bi_size>>9);
3168
3169         for (; logical_sector < last_sector;
3170              logical_sector += STRIPE_SECTORS,
3171                      sector += STRIPE_SECTORS,
3172                      scnt++) {
3173
3174                 if (scnt < raid_bio->bi_hw_segments)
3175                         /* already done this stripe */
3176                         continue;
3177
3178                 sh = get_active_stripe(conf, sector, conf->raid_disks, pd_idx, 1);
3179
3180                 if (!sh) {
3181                         /* failed to get a stripe - must wait */
3182                         raid_bio->bi_hw_segments = scnt;
3183                         conf->retry_read_aligned = raid_bio;
3184                         return handled;
3185                 }
3186
3187                 set_bit(R5_ReadError, &sh->dev[dd_idx].flags);
3188                 if (!add_stripe_bio(sh, raid_bio, dd_idx, 0)) {
3189                         release_stripe(sh);
3190                         raid_bio->bi_hw_segments = scnt;
3191                         conf->retry_read_aligned = raid_bio;
3192                         return handled;
3193                 }
3194
3195                 handle_stripe(sh, NULL);
3196                 release_stripe(sh);
3197                 handled++;
3198         }
3199         spin_lock_irq(&conf->device_lock);
3200         remaining = --raid_bio->bi_phys_segments;
3201         spin_unlock_irq(&conf->device_lock);
3202         if (remaining == 0) {
3203                 int bytes = raid_bio->bi_size;
3204
3205                 raid_bio->bi_size = 0;
3206                 raid_bio->bi_end_io(raid_bio, bytes,
3207                               test_bit(BIO_UPTODATE, &raid_bio->bi_flags)
3208                                 ? 0 : -EIO);
3209         }
3210         if (atomic_dec_and_test(&conf->active_aligned_reads))
3211                 wake_up(&conf->wait_for_stripe);
3212         return handled;
3213 }
3214
3215
3216
3217 /*
3218  * This is our raid5 kernel thread.
3219  *
3220  * We scan the hash table for stripes which can be handled now.
3221  * During the scan, completed stripes are saved for us by the interrupt
3222  * handler, so that they will not have to wait for our next wakeup.
3223  */
3224 static void raid5d (mddev_t *mddev)
3225 {
3226         struct stripe_head *sh;
3227         raid5_conf_t *conf = mddev_to_conf(mddev);
3228         int handled;
3229
3230         PRINTK("+++ raid5d active\n");
3231
3232         md_check_recovery(mddev);
3233
3234         handled = 0;
3235         spin_lock_irq(&conf->device_lock);
3236         while (1) {
3237                 struct list_head *first;
3238                 struct bio *bio;
3239
3240                 if (conf->seq_flush != conf->seq_write) {
3241                         int seq = conf->seq_flush;
3242                         spin_unlock_irq(&conf->device_lock);
3243                         bitmap_unplug(mddev->bitmap);
3244                         spin_lock_irq(&conf->device_lock);
3245                         conf->seq_write = seq;
3246                         activate_bit_delay(conf);
3247                 }
3248
3249                 if (list_empty(&conf->handle_list) &&
3250                     atomic_read(&conf->preread_active_stripes) < IO_THRESHOLD &&
3251                     !blk_queue_plugged(mddev->queue) &&
3252                     !list_empty(&conf->delayed_list))
3253                         raid5_activate_delayed(conf);
3254
3255                 while ((bio = remove_bio_from_retry(conf))) {
3256                         int ok;
3257                         spin_unlock_irq(&conf->device_lock);
3258                         ok = retry_aligned_read(conf, bio);
3259                         spin_lock_irq(&conf->device_lock);
3260                         if (!ok)
3261                                 break;
3262                         handled++;
3263                 }
3264
3265                 if (list_empty(&conf->handle_list))
3266                         break;
3267
3268                 first = conf->handle_list.next;
3269                 sh = list_entry(first, struct stripe_head, lru);
3270
3271                 list_del_init(first);
3272                 atomic_inc(&sh->count);
3273                 BUG_ON(atomic_read(&sh->count)!= 1);
3274                 spin_unlock_irq(&conf->device_lock);
3275                 
3276                 handled++;
3277                 handle_stripe(sh, conf->spare_page);
3278                 release_stripe(sh);
3279
3280                 spin_lock_irq(&conf->device_lock);
3281         }
3282         PRINTK("%d stripes handled\n", handled);
3283
3284         spin_unlock_irq(&conf->device_lock);
3285
3286         unplug_slaves(mddev);
3287
3288         PRINTK("--- raid5d inactive\n");
3289 }
3290
3291 static ssize_t
3292 raid5_show_stripe_cache_size(mddev_t *mddev, char *page)
3293 {
3294         raid5_conf_t *conf = mddev_to_conf(mddev);
3295         if (conf)
3296                 return sprintf(page, "%d\n", conf->max_nr_stripes);
3297         else
3298                 return 0;
3299 }
3300
3301 static ssize_t
3302 raid5_store_stripe_cache_size(mddev_t *mddev, const char *page, size_t len)
3303 {
3304         raid5_conf_t *conf = mddev_to_conf(mddev);
3305         char *end;
3306         int new;
3307         if (len >= PAGE_SIZE)
3308                 return -EINVAL;
3309         if (!conf)
3310                 return -ENODEV;
3311
3312         new = simple_strtoul(page, &end, 10);
3313         if (!*page || (*end && *end != '\n') )
3314                 return -EINVAL;
3315         if (new <= 16 || new > 32768)
3316                 return -EINVAL;
3317         while (new < conf->max_nr_stripes) {
3318                 if (drop_one_stripe(conf))
3319                         conf->max_nr_stripes--;
3320                 else
3321                         break;
3322         }
3323         md_allow_write(mddev);
3324         while (new > conf->max_nr_stripes) {
3325                 if (grow_one_stripe(conf))
3326                         conf->max_nr_stripes++;
3327                 else break;
3328         }
3329         return len;
3330 }
3331
3332 static struct md_sysfs_entry
3333 raid5_stripecache_size = __ATTR(stripe_cache_size, S_IRUGO | S_IWUSR,
3334                                 raid5_show_stripe_cache_size,
3335                                 raid5_store_stripe_cache_size);
3336
3337 static ssize_t
3338 stripe_cache_active_show(mddev_t *mddev, char *page)
3339 {
3340         raid5_conf_t *conf = mddev_to_conf(mddev);
3341         if (conf)
3342                 return sprintf(page, "%d\n", atomic_read(&conf->active_stripes));
3343         else
3344                 return 0;
3345 }
3346
3347 static struct md_sysfs_entry
3348 raid5_stripecache_active = __ATTR_RO(stripe_cache_active);
3349
3350 static struct attribute *raid5_attrs[] =  {
3351         &raid5_stripecache_size.attr,
3352         &raid5_stripecache_active.attr,
3353         NULL,
3354 };
3355 static struct attribute_group raid5_attrs_group = {
3356         .name = NULL,
3357         .attrs = raid5_attrs,
3358 };
3359
3360 static int run(mddev_t *mddev)
3361 {
3362         raid5_conf_t *conf;
3363         int raid_disk, memory;
3364         mdk_rdev_t *rdev;
3365         struct disk_info *disk;
3366         struct list_head *tmp;
3367         int working_disks = 0;
3368
3369         if (mddev->level != 5 && mddev->level != 4 && mddev->level != 6) {
3370                 printk(KERN_ERR "raid5: %s: raid level not set to 4/5/6 (%d)\n",
3371                        mdname(mddev), mddev->level);
3372                 return -EIO;
3373         }
3374
3375         if (mddev->reshape_position != MaxSector) {
3376                 /* Check that we can continue the reshape.
3377                  * Currently only disks can change, it must
3378                  * increase, and we must be past the point where
3379                  * a stripe over-writes itself
3380                  */
3381                 sector_t here_new, here_old;
3382                 int old_disks;
3383                 int max_degraded = (mddev->level == 5 ? 1 : 2);
3384
3385                 if (mddev->new_level != mddev->level ||
3386                     mddev->new_layout != mddev->layout ||
3387                     mddev->new_chunk != mddev->chunk_size) {
3388                         printk(KERN_ERR "raid5: %s: unsupported reshape "
3389                                "required - aborting.\n",
3390                                mdname(mddev));
3391                         return -EINVAL;
3392                 }
3393                 if (mddev->delta_disks <= 0) {
3394                         printk(KERN_ERR "raid5: %s: unsupported reshape "
3395                                "(reduce disks) required - aborting.\n",
3396                                mdname(mddev));
3397                         return -EINVAL;
3398                 }
3399                 old_disks = mddev->raid_disks - mddev->delta_disks;
3400                 /* reshape_position must be on a new-stripe boundary, and one
3401                  * further up in new geometry must map after here in old
3402                  * geometry.
3403                  */
3404                 here_new = mddev->reshape_position;
3405                 if (sector_div(here_new, (mddev->chunk_size>>9)*
3406                                (mddev->raid_disks - max_degraded))) {
3407                         printk(KERN_ERR "raid5: reshape_position not "
3408                                "on a stripe boundary\n");
3409                         return -EINVAL;
3410                 }
3411                 /* here_new is the stripe we will write to */
3412                 here_old = mddev->reshape_position;
3413                 sector_div(here_old, (mddev->chunk_size>>9)*
3414                            (old_disks-max_degraded));
3415                 /* here_old is the first stripe that we might need to read
3416                  * from */
3417                 if (here_new >= here_old) {
3418                         /* Reading from the same stripe as writing to - bad */
3419                         printk(KERN_ERR "raid5: reshape_position too early for "
3420                                "auto-recovery - aborting.\n");
3421                         return -EINVAL;
3422                 }
3423                 printk(KERN_INFO "raid5: reshape will continue\n");
3424                 /* OK, we should be able to continue; */
3425         }
3426
3427
3428         mddev->private = kzalloc(sizeof (raid5_conf_t), GFP_KERNEL);
3429         if ((conf = mddev->private) == NULL)
3430                 goto abort;
3431         if (mddev->reshape_position == MaxSector) {
3432                 conf->previous_raid_disks = conf->raid_disks = mddev->raid_disks;
3433         } else {
3434                 conf->raid_disks = mddev->raid_disks;
3435                 conf->previous_raid_disks = mddev->raid_disks - mddev->delta_disks;
3436         }
3437
3438         conf->disks = kzalloc(conf->raid_disks * sizeof(struct disk_info),
3439                               GFP_KERNEL);
3440         if (!conf->disks)
3441                 goto abort;
3442
3443         conf->mddev = mddev;
3444
3445         if ((conf->stripe_hashtbl = kzalloc(PAGE_SIZE, GFP_KERNEL)) == NULL)
3446                 goto abort;
3447
3448         if (mddev->level == 6) {
3449                 conf->spare_page = alloc_page(GFP_KERNEL);
3450                 if (!conf->spare_page)
3451                         goto abort;
3452         }
3453         spin_lock_init(&conf->device_lock);
3454         init_waitqueue_head(&conf->wait_for_stripe);
3455         init_waitqueue_head(&conf->wait_for_overlap);
3456         INIT_LIST_HEAD(&conf->handle_list);
3457         INIT_LIST_HEAD(&conf->delayed_list);
3458         INIT_LIST_HEAD(&conf->bitmap_list);
3459         INIT_LIST_HEAD(&conf->inactive_list);
3460         atomic_set(&conf->active_stripes, 0);
3461         atomic_set(&conf->preread_active_stripes, 0);
3462         atomic_set(&conf->active_aligned_reads, 0);
3463
3464         PRINTK("raid5: run(%s) called.\n", mdname(mddev));
3465
3466         ITERATE_RDEV(mddev,rdev,tmp) {
3467                 raid_disk = rdev->raid_disk;
3468                 if (raid_disk >= conf->raid_disks
3469                     || raid_disk < 0)
3470                         continue;
3471                 disk = conf->disks + raid_disk;
3472
3473                 disk->rdev = rdev;
3474
3475                 if (test_bit(In_sync, &rdev->flags)) {
3476                         char b[BDEVNAME_SIZE];
3477                         printk(KERN_INFO "raid5: device %s operational as raid"
3478                                 " disk %d\n", bdevname(rdev->bdev,b),
3479                                 raid_disk);
3480                         working_disks++;
3481                 }
3482         }
3483
3484         /*
3485          * 0 for a fully functional array, 1 or 2 for a degraded array.
3486          */
3487         mddev->degraded = conf->raid_disks - working_disks;
3488         conf->mddev = mddev;
3489         conf->chunk_size = mddev->chunk_size;
3490         conf->level = mddev->level;
3491         if (conf->level == 6)
3492                 conf->max_degraded = 2;
3493         else
3494                 conf->max_degraded = 1;
3495         conf->algorithm = mddev->layout;
3496         conf->max_nr_stripes = NR_STRIPES;
3497         conf->expand_progress = mddev->reshape_position;
3498
3499         /* device size must be a multiple of chunk size */
3500         mddev->size &= ~(mddev->chunk_size/1024 -1);
3501         mddev->resync_max_sectors = mddev->size << 1;
3502
3503         if (conf->level == 6 && conf->raid_disks < 4) {
3504                 printk(KERN_ERR "raid6: not enough configured devices for %s (%d, minimum 4)\n",
3505                        mdname(mddev), conf->raid_disks);
3506                 goto abort;
3507         }
3508         if (!conf->chunk_size || conf->chunk_size % 4) {
3509                 printk(KERN_ERR "raid5: invalid chunk size %d for %s\n",
3510                         conf->chunk_size, mdname(mddev));
3511                 goto abort;
3512         }
3513         if (conf->algorithm > ALGORITHM_RIGHT_SYMMETRIC) {
3514                 printk(KERN_ERR 
3515                         "raid5: unsupported parity algorithm %d for %s\n",
3516                         conf->algorithm, mdname(mddev));
3517                 goto abort;
3518         }
3519         if (mddev->degraded > conf->max_degraded) {
3520                 printk(KERN_ERR "raid5: not enough operational devices for %s"
3521                         " (%d/%d failed)\n",
3522                         mdname(mddev), mddev->degraded, conf->raid_disks);
3523                 goto abort;
3524         }
3525
3526         if (mddev->degraded > 0 &&
3527             mddev->recovery_cp != MaxSector) {
3528                 if (mddev->ok_start_degraded)
3529                         printk(KERN_WARNING
3530                                "raid5: starting dirty degraded array: %s"
3531                                "- data corruption possible.\n",
3532                                mdname(mddev));
3533                 else {
3534                         printk(KERN_ERR
3535                                "raid5: cannot start dirty degraded array for %s\n",
3536                                mdname(mddev));
3537                         goto abort;
3538                 }
3539         }
3540
3541         {
3542                 mddev->thread = md_register_thread(raid5d, mddev, "%s_raid5");
3543                 if (!mddev->thread) {
3544                         printk(KERN_ERR 
3545                                 "raid5: couldn't allocate thread for %s\n",
3546                                 mdname(mddev));
3547                         goto abort;
3548                 }
3549         }
3550         memory = conf->max_nr_stripes * (sizeof(struct stripe_head) +
3551                  conf->raid_disks * ((sizeof(struct bio) + PAGE_SIZE))) / 1024;
3552         if (grow_stripes(conf, conf->max_nr_stripes)) {
3553                 printk(KERN_ERR 
3554                         "raid5: couldn't allocate %dkB for buffers\n", memory);
3555                 shrink_stripes(conf);
3556                 md_unregister_thread(mddev->thread);
3557                 goto abort;
3558         } else
3559                 printk(KERN_INFO "raid5: allocated %dkB for %s\n",
3560                         memory, mdname(mddev));
3561
3562         if (mddev->degraded == 0)
3563                 printk("raid5: raid level %d set %s active with %d out of %d"
3564                         " devices, algorithm %d\n", conf->level, mdname(mddev), 
3565                         mddev->raid_disks-mddev->degraded, mddev->raid_disks,
3566                         conf->algorithm);
3567         else
3568                 printk(KERN_ALERT "raid5: raid level %d set %s active with %d"
3569                         " out of %d devices, algorithm %d\n", conf->level,
3570                         mdname(mddev), mddev->raid_disks - mddev->degraded,
3571                         mddev->raid_disks, conf->algorithm);
3572
3573         print_raid5_conf(conf);
3574
3575         if (conf->expand_progress != MaxSector) {
3576                 printk("...ok start reshape thread\n");
3577                 conf->expand_lo = conf->expand_progress;
3578                 atomic_set(&conf->reshape_stripes, 0);
3579                 clear_bit(MD_RECOVERY_SYNC, &mddev->recovery);
3580                 clear_bit(MD_RECOVERY_CHECK, &mddev->recovery);
3581                 set_bit(MD_RECOVERY_RESHAPE, &mddev->recovery);
3582                 set_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
3583                 mddev->sync_thread = md_register_thread(md_do_sync, mddev,
3584                                                         "%s_reshape");
3585         }
3586
3587         /* read-ahead size must cover two whole stripes, which is
3588          * 2 * (datadisks) * chunksize where 'n' is the number of raid devices
3589          */
3590         {
3591                 int data_disks = conf->previous_raid_disks - conf->max_degraded;
3592                 int stripe = data_disks *
3593                         (mddev->chunk_size / PAGE_SIZE);
3594                 if (mddev->queue->backing_dev_info.ra_pages < 2 * stripe)
3595                         mddev->queue->backing_dev_info.ra_pages = 2 * stripe;
3596         }
3597
3598         /* Ok, everything is just fine now */
3599         if (sysfs_create_group(&mddev->kobj, &raid5_attrs_group))
3600                 printk(KERN_WARNING
3601                        "raid5: failed to create sysfs attributes for %s\n",
3602                        mdname(mddev));
3603
3604         mddev->queue->unplug_fn = raid5_unplug_device;
3605         mddev->queue->issue_flush_fn = raid5_issue_flush;
3606         mddev->queue->backing_dev_info.congested_data = mddev;
3607         mddev->queue->backing_dev_info.congested_fn = raid5_congested;
3608
3609         mddev->array_size =  mddev->size * (conf->previous_raid_disks -
3610                                             conf->max_degraded);
3611
3612         blk_queue_merge_bvec(mddev->queue, raid5_mergeable_bvec);
3613
3614         return 0;
3615 abort:
3616         if (conf) {
3617                 print_raid5_conf(conf);
3618                 safe_put_page(conf->spare_page);
3619                 kfree(conf->disks);
3620                 kfree(conf->stripe_hashtbl);
3621                 kfree(conf);
3622         }
3623         mddev->private = NULL;
3624         printk(KERN_ALERT "raid5: failed to run raid set %s\n", mdname(mddev));
3625         return -EIO;
3626 }
3627
3628
3629
3630 static int stop(mddev_t *mddev)
3631 {
3632         raid5_conf_t *conf = (raid5_conf_t *) mddev->private;
3633
3634         md_unregister_thread(mddev->thread);
3635         mddev->thread = NULL;
3636         shrink_stripes(conf);
3637         kfree(conf->stripe_hashtbl);
3638         mddev->queue->backing_dev_info.congested_fn = NULL;
3639         blk_sync_queue(mddev->queue); /* the unplug fn references 'conf'*/
3640         sysfs_remove_group(&mddev->kobj, &raid5_attrs_group);
3641         kfree(conf->disks);
3642         kfree(conf);
3643         mddev->private = NULL;
3644         return 0;
3645 }
3646
3647 #if RAID5_DEBUG
3648 static void print_sh (struct seq_file *seq, struct stripe_head *sh)
3649 {
3650         int i;
3651
3652         seq_printf(seq, "sh %llu, pd_idx %d, state %ld.\n",
3653                    (unsigned long long)sh->sector, sh->pd_idx, sh->state);
3654         seq_printf(seq, "sh %llu,  count %d.\n",
3655                    (unsigned long long)sh->sector, atomic_read(&sh->count));
3656         seq_printf(seq, "sh %llu, ", (unsigned long long)sh->sector);
3657         for (i = 0; i < sh->disks; i++) {
3658                 seq_printf(seq, "(cache%d: %p %ld) ",
3659                            i, sh->dev[i].page, sh->dev[i].flags);
3660         }
3661         seq_printf(seq, "\n");
3662 }
3663
3664 static void printall (struct seq_file *seq, raid5_conf_t *conf)
3665 {
3666         struct stripe_head *sh;
3667         struct hlist_node *hn;
3668         int i;
3669
3670         spin_lock_irq(&conf->device_lock);
3671         for (i = 0; i < NR_HASH; i++) {
3672                 hlist_for_each_entry(sh, hn, &conf->stripe_hashtbl[i], hash) {
3673                         if (sh->raid_conf != conf)
3674                                 continue;
3675                         print_sh(seq, sh);
3676                 }
3677         }
3678         spin_unlock_irq(&conf->device_lock);
3679 }
3680 #endif
3681
3682 static void status (struct seq_file *seq, mddev_t *mddev)
3683 {
3684         raid5_conf_t *conf = (raid5_conf_t *) mddev->private;
3685         int i;
3686
3687         seq_printf (seq, " level %d, %dk chunk, algorithm %d", mddev->level, mddev->chunk_size >> 10, mddev->layout);
3688         seq_printf (seq, " [%d/%d] [", conf->raid_disks, conf->raid_disks - mddev->degraded);
3689         for (i = 0; i < conf->raid_disks; i++)
3690                 seq_printf (seq, "%s",
3691                                conf->disks[i].rdev &&
3692                                test_bit(In_sync, &conf->disks[i].rdev->flags) ? "U" : "_");
3693         seq_printf (seq, "]");
3694 #if RAID5_DEBUG
3695         seq_printf (seq, "\n");
3696         printall(seq, conf);
3697 #endif
3698 }
3699
3700 static void print_raid5_conf (raid5_conf_t *conf)
3701 {
3702         int i;
3703         struct disk_info *tmp;
3704
3705         printk("RAID5 conf printout:\n");
3706         if (!conf) {
3707                 printk("(conf==NULL)\n");
3708                 return;
3709         }
3710         printk(" --- rd:%d wd:%d\n", conf->raid_disks,
3711                  conf->raid_disks - conf->mddev->degraded);
3712
3713         for (i = 0; i < conf->raid_disks; i++) {
3714                 char b[BDEVNAME_SIZE];
3715                 tmp = conf->disks + i;
3716                 if (tmp->rdev)
3717                 printk(" disk %d, o:%d, dev:%s\n",
3718                         i, !test_bit(Faulty, &tmp->rdev->flags),
3719                         bdevname(tmp->rdev->bdev,b));
3720         }
3721 }
3722
3723 static int raid5_spare_active(mddev_t *mddev)
3724 {
3725         int i;
3726         raid5_conf_t *conf = mddev->private;
3727         struct disk_info *tmp;
3728
3729         for (i = 0; i < conf->raid_disks; i++) {
3730                 tmp = conf->disks + i;
3731                 if (tmp->rdev
3732                     && !test_bit(Faulty, &tmp->rdev->flags)
3733                     && !test_and_set_bit(In_sync, &tmp->rdev->flags)) {
3734                         unsigned long flags;
3735                         spin_lock_irqsave(&conf->device_lock, flags);
3736                         mddev->degraded--;
3737                         spin_unlock_irqrestore(&conf->device_lock, flags);
3738                 }
3739         }
3740         print_raid5_conf(conf);
3741         return 0;
3742 }
3743
3744 static int raid5_remove_disk(mddev_t *mddev, int number)
3745 {
3746         raid5_conf_t *conf = mddev->private;
3747         int err = 0;
3748         mdk_rdev_t *rdev;
3749         struct disk_info *p = conf->disks + number;
3750
3751         print_raid5_conf(conf);
3752         rdev = p->rdev;
3753         if (rdev) {
3754                 if (test_bit(In_sync, &rdev->flags) ||
3755                     atomic_read(&rdev->nr_pending)) {
3756                         err = -EBUSY;
3757                         goto abort;
3758                 }
3759                 p->rdev = NULL;
3760                 synchronize_rcu();
3761                 if (atomic_read(&rdev->nr_pending)) {
3762                         /* lost the race, try later */
3763                         err = -EBUSY;
3764                         p->rdev = rdev;
3765                 }
3766         }
3767 abort:
3768
3769         print_raid5_conf(conf);
3770         return err;
3771 }
3772
3773 static int raid5_add_disk(mddev_t *mddev, mdk_rdev_t *rdev)
3774 {
3775         raid5_conf_t *conf = mddev->private;
3776         int found = 0;
3777         int disk;
3778         struct disk_info *p;
3779
3780         if (mddev->degraded > conf->max_degraded)
3781                 /* no point adding a device */
3782                 return 0;
3783
3784         /*
3785          * find the disk ... but prefer rdev->saved_raid_disk
3786          * if possible.
3787          */
3788         if (rdev->saved_raid_disk >= 0 &&
3789             conf->disks[rdev->saved_raid_disk].rdev == NULL)
3790                 disk = rdev->saved_raid_disk;
3791         else
3792                 disk = 0;
3793         for ( ; disk < conf->raid_disks; disk++)
3794                 if ((p=conf->disks + disk)->rdev == NULL) {
3795                         clear_bit(In_sync, &rdev->flags);
3796                         rdev->raid_disk = disk;
3797                         found = 1;
3798                         if (rdev->saved_raid_disk != disk)
3799                                 conf->fullsync = 1;
3800                         rcu_assign_pointer(p->rdev, rdev);
3801                         break;
3802                 }
3803         print_raid5_conf(conf);
3804         return found;
3805 }
3806
3807 static int raid5_resize(mddev_t *mddev, sector_t sectors)
3808 {
3809         /* no resync is happening, and there is enough space
3810          * on all devices, so we can resize.
3811          * We need to make sure resync covers any new space.
3812          * If the array is shrinking we should possibly wait until
3813          * any io in the removed space completes, but it hardly seems
3814          * worth it.
3815          */
3816         raid5_conf_t *conf = mddev_to_conf(mddev);
3817
3818         sectors &= ~((sector_t)mddev->chunk_size/512 - 1);
3819         mddev->array_size = (sectors * (mddev->raid_disks-conf->max_degraded))>>1;
3820         set_capacity(mddev->gendisk, mddev->array_size << 1);
3821         mddev->changed = 1;
3822         if (sectors/2  > mddev->size && mddev->recovery_cp == MaxSector) {
3823                 mddev->recovery_cp = mddev->size << 1;
3824                 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
3825         }
3826         mddev->size = sectors /2;
3827         mddev->resync_max_sectors = sectors;
3828         return 0;
3829 }
3830
3831 #ifdef CONFIG_MD_RAID5_RESHAPE
3832 static int raid5_check_reshape(mddev_t *mddev)
3833 {
3834         raid5_conf_t *conf = mddev_to_conf(mddev);
3835         int err;
3836
3837         if (mddev->delta_disks < 0 ||
3838             mddev->new_level != mddev->level)
3839                 return -EINVAL; /* Cannot shrink array or change level yet */
3840         if (mddev->delta_disks == 0)
3841                 return 0; /* nothing to do */
3842
3843         /* Can only proceed if there are plenty of stripe_heads.
3844          * We need a minimum of one full stripe,, and for sensible progress
3845          * it is best to have about 4 times that.
3846          * If we require 4 times, then the default 256 4K stripe_heads will
3847          * allow for chunk sizes up to 256K, which is probably OK.
3848          * If the chunk size is greater, user-space should request more
3849          * stripe_heads first.
3850          */
3851         if ((mddev->chunk_size / STRIPE_SIZE) * 4 > conf->max_nr_stripes ||
3852             (mddev->new_chunk / STRIPE_SIZE) * 4 > conf->max_nr_stripes) {
3853                 printk(KERN_WARNING "raid5: reshape: not enough stripes.  Needed %lu\n",
3854                        (mddev->chunk_size / STRIPE_SIZE)*4);
3855                 return -ENOSPC;
3856         }
3857
3858         err = resize_stripes(conf, conf->raid_disks + mddev->delta_disks);
3859         if (err)
3860                 return err;
3861
3862         if (mddev->degraded > conf->max_degraded)
3863                 return -EINVAL;
3864         /* looks like we might be able to manage this */
3865         return 0;
3866 }
3867
3868 static int raid5_start_reshape(mddev_t *mddev)
3869 {
3870         raid5_conf_t *conf = mddev_to_conf(mddev);
3871         mdk_rdev_t *rdev;
3872         struct list_head *rtmp;
3873         int spares = 0;
3874         int added_devices = 0;
3875         unsigned long flags;
3876
3877         if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
3878                 return -EBUSY;
3879
3880         ITERATE_RDEV(mddev, rdev, rtmp)
3881                 if (rdev->raid_disk < 0 &&
3882                     !test_bit(Faulty, &rdev->flags))
3883                         spares++;
3884
3885         if (spares - mddev->degraded < mddev->delta_disks - conf->max_degraded)
3886                 /* Not enough devices even to make a degraded array
3887                  * of that size
3888                  */
3889                 return -EINVAL;
3890
3891         atomic_set(&conf->reshape_stripes, 0);
3892         spin_lock_irq(&conf->device_lock);
3893         conf->previous_raid_disks = conf->raid_disks;
3894         conf->raid_disks += mddev->delta_disks;
3895         conf->expand_progress = 0;
3896         conf->expand_lo = 0;
3897         spin_unlock_irq(&conf->device_lock);
3898
3899         /* Add some new drives, as many as will fit.
3900          * We know there are enough to make the newly sized array work.
3901          */
3902         ITERATE_RDEV(mddev, rdev, rtmp)
3903                 if (rdev->raid_disk < 0 &&
3904                     !test_bit(Faulty, &rdev->flags)) {
3905                         if (raid5_add_disk(mddev, rdev)) {
3906                                 char nm[20];
3907                                 set_bit(In_sync, &rdev->flags);
3908                                 added_devices++;
3909                                 rdev->recovery_offset = 0;
3910                                 sprintf(nm, "rd%d", rdev->raid_disk);
3911                                 if (sysfs_create_link(&mddev->kobj,
3912                                                       &rdev->kobj, nm))
3913                                         printk(KERN_WARNING
3914                                                "raid5: failed to create "
3915                                                " link %s for %s\n",
3916                                                nm, mdname(mddev));
3917                         } else
3918                                 break;
3919                 }
3920
3921         spin_lock_irqsave(&conf->device_lock, flags);
3922         mddev->degraded = (conf->raid_disks - conf->previous_raid_disks) - added_devices;
3923         spin_unlock_irqrestore(&conf->device_lock, flags);
3924         mddev->raid_disks = conf->raid_disks;
3925         mddev->reshape_position = 0;
3926         set_bit(MD_CHANGE_DEVS, &mddev->flags);
3927
3928         clear_bit(MD_RECOVERY_SYNC, &mddev->recovery);
3929         clear_bit(MD_RECOVERY_CHECK, &mddev->recovery);
3930         set_bit(MD_RECOVERY_RESHAPE, &mddev->recovery);
3931         set_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
3932         mddev->sync_thread = md_register_thread(md_do_sync, mddev,
3933                                                 "%s_reshape");
3934         if (!mddev->sync_thread) {
3935                 mddev->recovery = 0;
3936                 spin_lock_irq(&conf->device_lock);
3937                 mddev->raid_disks = conf->raid_disks = conf->previous_raid_disks;
3938                 conf->expand_progress = MaxSector;
3939                 spin_unlock_irq(&conf->device_lock);
3940                 return -EAGAIN;
3941         }
3942         md_wakeup_thread(mddev->sync_thread);
3943         md_new_event(mddev);
3944         return 0;
3945 }
3946 #endif
3947
3948 static void end_reshape(raid5_conf_t *conf)
3949 {
3950         struct block_device *bdev;
3951
3952         if (!test_bit(MD_RECOVERY_INTR, &conf->mddev->recovery)) {
3953                 conf->mddev->array_size = conf->mddev->size *
3954                         (conf->raid_disks - conf->max_degraded);
3955                 set_capacity(conf->mddev->gendisk, conf->mddev->array_size << 1);
3956                 conf->mddev->changed = 1;
3957
3958                 bdev = bdget_disk(conf->mddev->gendisk, 0);
3959                 if (bdev) {
3960                         mutex_lock(&bdev->bd_inode->i_mutex);
3961                         i_size_write(bdev->bd_inode, (loff_t)conf->mddev->array_size << 10);
3962                         mutex_unlock(&bdev->bd_inode->i_mutex);
3963                         bdput(bdev);
3964                 }
3965                 spin_lock_irq(&conf->device_lock);
3966                 conf->expand_progress = MaxSector;
3967                 spin_unlock_irq(&conf->device_lock);
3968                 conf->mddev->reshape_position = MaxSector;
3969
3970                 /* read-ahead size must cover two whole stripes, which is
3971                  * 2 * (datadisks) * chunksize where 'n' is the number of raid devices
3972                  */
3973                 {
3974                         int data_disks = conf->previous_raid_disks - conf->max_degraded;
3975                         int stripe = data_disks *
3976                                 (conf->mddev->chunk_size / PAGE_SIZE);
3977                         if (conf->mddev->queue->backing_dev_info.ra_pages < 2 * stripe)
3978                                 conf->mddev->queue->backing_dev_info.ra_pages = 2 * stripe;
3979                 }
3980         }
3981 }
3982
3983 static void raid5_quiesce(mddev_t *mddev, int state)
3984 {
3985         raid5_conf_t *conf = mddev_to_conf(mddev);
3986
3987         switch(state) {
3988         case 2: /* resume for a suspend */
3989                 wake_up(&conf->wait_for_overlap);
3990                 break;
3991
3992         case 1: /* stop all writes */
3993                 spin_lock_irq(&conf->device_lock);
3994                 conf->quiesce = 1;
3995                 wait_event_lock_irq(conf->wait_for_stripe,
3996                                     atomic_read(&conf->active_stripes) == 0 &&
3997                                     atomic_read(&conf->active_aligned_reads) == 0,
3998                                     conf->device_lock, /* nothing */);
3999                 spin_unlock_irq(&conf->device_lock);
4000                 break;
4001
4002         case 0: /* re-enable writes */
4003                 spin_lock_irq(&conf->device_lock);
4004                 conf->quiesce = 0;
4005                 wake_up(&conf->wait_for_stripe);
4006                 wake_up(&conf->wait_for_overlap);
4007                 spin_unlock_irq(&conf->device_lock);
4008                 break;
4009         }
4010 }
4011
4012 static struct mdk_personality raid6_personality =
4013 {
4014         .name           = "raid6",
4015         .level          = 6,
4016         .owner          = THIS_MODULE,
4017         .make_request   = make_request,
4018         .run            = run,
4019         .stop           = stop,
4020         .status         = status,
4021         .error_handler  = error,
4022         .hot_add_disk   = raid5_add_disk,
4023         .hot_remove_disk= raid5_remove_disk,
4024         .spare_active   = raid5_spare_active,
4025         .sync_request   = sync_request,
4026         .resize         = raid5_resize,
4027 #ifdef CONFIG_MD_RAID5_RESHAPE
4028         .check_reshape  = raid5_check_reshape,
4029         .start_reshape  = raid5_start_reshape,
4030 #endif
4031         .quiesce        = raid5_quiesce,
4032 };
4033 static struct mdk_personality raid5_personality =
4034 {
4035         .name           = "raid5",
4036         .level          = 5,
4037         .owner          = THIS_MODULE,
4038         .make_request   = make_request,
4039         .run            = run,
4040         .stop           = stop,
4041         .status         = status,
4042         .error_handler  = error,
4043         .hot_add_disk   = raid5_add_disk,
4044         .hot_remove_disk= raid5_remove_disk,
4045         .spare_active   = raid5_spare_active,
4046         .sync_request   = sync_request,
4047         .resize         = raid5_resize,
4048 #ifdef CONFIG_MD_RAID5_RESHAPE
4049         .check_reshape  = raid5_check_reshape,
4050         .start_reshape  = raid5_start_reshape,
4051 #endif
4052         .quiesce        = raid5_quiesce,
4053 };
4054
4055 static struct mdk_personality raid4_personality =
4056 {
4057         .name           = "raid4",
4058         .level          = 4,
4059         .owner          = THIS_MODULE,
4060         .make_request   = make_request,
4061         .run            = run,
4062         .stop           = stop,
4063         .status         = status,
4064         .error_handler  = error,
4065         .hot_add_disk   = raid5_add_disk,
4066         .hot_remove_disk= raid5_remove_disk,
4067         .spare_active   = raid5_spare_active,
4068         .sync_request   = sync_request,
4069         .resize         = raid5_resize,
4070 #ifdef CONFIG_MD_RAID5_RESHAPE
4071         .check_reshape  = raid5_check_reshape,
4072         .start_reshape  = raid5_start_reshape,
4073 #endif
4074         .quiesce        = raid5_quiesce,
4075 };
4076
4077 static int __init raid5_init(void)
4078 {
4079         int e;
4080
4081         e = raid6_select_algo();
4082         if ( e )
4083                 return e;
4084         register_md_personality(&raid6_personality);
4085         register_md_personality(&raid5_personality);
4086         register_md_personality(&raid4_personality);
4087         return 0;
4088 }
4089
4090 static void raid5_exit(void)
4091 {
4092         unregister_md_personality(&raid6_personality);
4093         unregister_md_personality(&raid5_personality);
4094         unregister_md_personality(&raid4_personality);
4095 }
4096
4097 module_init(raid5_init);
4098 module_exit(raid5_exit);
4099 MODULE_LICENSE("GPL");
4100 MODULE_ALIAS("md-personality-4"); /* RAID5 */
4101 MODULE_ALIAS("md-raid5");
4102 MODULE_ALIAS("md-raid4");
4103 MODULE_ALIAS("md-level-5");
4104 MODULE_ALIAS("md-level-4");
4105 MODULE_ALIAS("md-personality-8"); /* RAID6 */
4106 MODULE_ALIAS("md-raid6");
4107 MODULE_ALIAS("md-level-6");
4108
4109 /* This used to be two separate modules, they were: */
4110 MODULE_ALIAS("raid5");
4111 MODULE_ALIAS("raid6");