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