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