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