patch-2_6_7-vs1_9_1_12
[linux-2.6.git] / drivers / md / raid6main.c
1 /*
2  * raid6main.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-6 management functions.  This code is derived from raid5.c.
8  * Last merge from raid5.c bkcvs version 1.79 (kernel 2.6.1).
9  *
10  * Thanks to Penguin Computing for making the RAID-6 development possible
11  * by donating a test server!
12  *
13  * This program is free software; you can redistribute it and/or modify
14  * it under the terms of the GNU General Public License as published by
15  * the Free Software Foundation; either version 2, or (at your option)
16  * any later version.
17  *
18  * You should have received a copy of the GNU General Public License
19  * (for example /usr/src/linux/COPYING); if not, write to the Free
20  * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21  */
22
23
24 #include <linux/config.h>
25 #include <linux/module.h>
26 #include <linux/slab.h>
27 #include <linux/highmem.h>
28 #include <asm/bitops.h>
29 #include <asm/atomic.h>
30 #include "raid6.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 HASH_PAGES              1
42 #define HASH_PAGES_ORDER        0
43 #define NR_HASH                 (HASH_PAGES * PAGE_SIZE / sizeof(struct stripe_head *))
44 #define HASH_MASK               (NR_HASH - 1)
45
46 #define stripe_hash(conf, sect) ((conf)->stripe_hashtbl[((sect) >> STRIPE_SHIFT) & HASH_MASK])
47
48 /* bio's attached to a stripe+device for I/O are linked together in bi_sector
49  * order without overlap.  There may be several bio's per stripe+device, and
50  * a bio could span several devices.
51  * When walking this list for a particular stripe+device, we must never proceed
52  * beyond a bio that extends past this device, as the next bio might no longer
53  * be valid.
54  * This macro is used to determine the 'next' bio in the list, given the sector
55  * of the current stripe+device
56  */
57 #define r5_next_bio(bio, sect) ( ( bio->bi_sector + (bio->bi_size>>9) < sect + STRIPE_SECTORS) ? bio->bi_next : NULL)
58 /*
59  * The following can be used to debug the driver
60  */
61 #define RAID6_DEBUG     0       /* Extremely verbose printk */
62 #define RAID6_PARANOIA  1       /* Check spinlocks */
63 #define RAID6_DUMPSTATE 0       /* Include stripe cache state in /proc/mdstat */
64 #if RAID6_PARANOIA && CONFIG_SMP
65 # define CHECK_DEVLOCK() if (!spin_is_locked(&conf->device_lock)) BUG()
66 #else
67 # define CHECK_DEVLOCK()
68 #endif
69
70 #define PRINTK(x...) ((void)(RAID6_DEBUG && printk(KERN_DEBUG x)))
71 #if RAID6_DEBUG
72 #undef inline
73 #undef __inline__
74 #define inline
75 #define __inline__
76 #endif
77
78 #if !RAID6_USE_EMPTY_ZERO_PAGE
79 /* In .bss so it's zeroed */
80 const char raid6_empty_zero_page[PAGE_SIZE] __attribute__((aligned(256)));
81 #endif
82
83 static inline int raid6_next_disk(int disk, int raid_disks)
84 {
85         disk++;
86         return (disk < raid_disks) ? disk : 0;
87 }
88
89 static void print_raid6_conf (raid6_conf_t *conf);
90
91 static inline void __release_stripe(raid6_conf_t *conf, struct stripe_head *sh)
92 {
93         if (atomic_dec_and_test(&sh->count)) {
94                 if (!list_empty(&sh->lru))
95                         BUG();
96                 if (atomic_read(&conf->active_stripes)==0)
97                         BUG();
98                 if (test_bit(STRIPE_HANDLE, &sh->state)) {
99                         if (test_bit(STRIPE_DELAYED, &sh->state))
100                                 list_add_tail(&sh->lru, &conf->delayed_list);
101                         else
102                                 list_add_tail(&sh->lru, &conf->handle_list);
103                         md_wakeup_thread(conf->mddev->thread);
104                 } else {
105                         if (test_and_clear_bit(STRIPE_PREREAD_ACTIVE, &sh->state)) {
106                                 atomic_dec(&conf->preread_active_stripes);
107                                 if (atomic_read(&conf->preread_active_stripes) < IO_THRESHOLD)
108                                         md_wakeup_thread(conf->mddev->thread);
109                         }
110                         list_add_tail(&sh->lru, &conf->inactive_list);
111                         atomic_dec(&conf->active_stripes);
112                         if (!conf->inactive_blocked ||
113                             atomic_read(&conf->active_stripes) < (NR_STRIPES*3/4))
114                                 wake_up(&conf->wait_for_stripe);
115                 }
116         }
117 }
118 static void release_stripe(struct stripe_head *sh)
119 {
120         raid6_conf_t *conf = sh->raid_conf;
121         unsigned long flags;
122
123         spin_lock_irqsave(&conf->device_lock, flags);
124         __release_stripe(conf, sh);
125         spin_unlock_irqrestore(&conf->device_lock, flags);
126 }
127
128 static void remove_hash(struct stripe_head *sh)
129 {
130         PRINTK("remove_hash(), stripe %llu\n", (unsigned long long)sh->sector);
131
132         if (sh->hash_pprev) {
133                 if (sh->hash_next)
134                         sh->hash_next->hash_pprev = sh->hash_pprev;
135                 *sh->hash_pprev = sh->hash_next;
136                 sh->hash_pprev = NULL;
137         }
138 }
139
140 static __inline__ void insert_hash(raid6_conf_t *conf, struct stripe_head *sh)
141 {
142         struct stripe_head **shp = &stripe_hash(conf, sh->sector);
143
144         PRINTK("insert_hash(), stripe %llu\n", (unsigned long long)sh->sector);
145
146         CHECK_DEVLOCK();
147         if ((sh->hash_next = *shp) != NULL)
148                 (*shp)->hash_pprev = &sh->hash_next;
149         *shp = sh;
150         sh->hash_pprev = shp;
151 }
152
153
154 /* find an idle stripe, make sure it is unhashed, and return it. */
155 static struct stripe_head *get_free_stripe(raid6_conf_t *conf)
156 {
157         struct stripe_head *sh = NULL;
158         struct list_head *first;
159
160         CHECK_DEVLOCK();
161         if (list_empty(&conf->inactive_list))
162                 goto out;
163         first = conf->inactive_list.next;
164         sh = list_entry(first, struct stripe_head, lru);
165         list_del_init(first);
166         remove_hash(sh);
167         atomic_inc(&conf->active_stripes);
168 out:
169         return sh;
170 }
171
172 static void shrink_buffers(struct stripe_head *sh, int num)
173 {
174         struct page *p;
175         int i;
176
177         for (i=0; i<num ; i++) {
178                 p = sh->dev[i].page;
179                 if (!p)
180                         continue;
181                 sh->dev[i].page = NULL;
182                 page_cache_release(p);
183         }
184 }
185
186 static int grow_buffers(struct stripe_head *sh, int num)
187 {
188         int i;
189
190         for (i=0; i<num; i++) {
191                 struct page *page;
192
193                 if (!(page = alloc_page(GFP_KERNEL))) {
194                         return 1;
195                 }
196                 sh->dev[i].page = page;
197         }
198         return 0;
199 }
200
201 static void raid6_build_block (struct stripe_head *sh, int i);
202
203 static inline void init_stripe(struct stripe_head *sh, sector_t sector, int pd_idx)
204 {
205         raid6_conf_t *conf = sh->raid_conf;
206         int disks = conf->raid_disks, i;
207
208         if (atomic_read(&sh->count) != 0)
209                 BUG();
210         if (test_bit(STRIPE_HANDLE, &sh->state))
211                 BUG();
212
213         CHECK_DEVLOCK();
214         PRINTK("init_stripe called, stripe %llu\n",
215                 (unsigned long long)sh->sector);
216
217         remove_hash(sh);
218
219         sh->sector = sector;
220         sh->pd_idx = pd_idx;
221         sh->state = 0;
222
223         for (i=disks; i--; ) {
224                 struct r5dev *dev = &sh->dev[i];
225
226                 if (dev->toread || dev->towrite || dev->written ||
227                     test_bit(R5_LOCKED, &dev->flags)) {
228                         PRINTK("sector=%llx i=%d %p %p %p %d\n",
229                                (unsigned long long)sh->sector, i, dev->toread,
230                                dev->towrite, dev->written,
231                                test_bit(R5_LOCKED, &dev->flags));
232                         BUG();
233                 }
234                 dev->flags = 0;
235                 raid6_build_block(sh, i);
236         }
237         insert_hash(conf, sh);
238 }
239
240 static struct stripe_head *__find_stripe(raid6_conf_t *conf, sector_t sector)
241 {
242         struct stripe_head *sh;
243
244         CHECK_DEVLOCK();
245         PRINTK("__find_stripe, sector %llu\n", (unsigned long long)sector);
246         for (sh = stripe_hash(conf, sector); sh; sh = sh->hash_next)
247                 if (sh->sector == sector)
248                         return sh;
249         PRINTK("__stripe %llu not in cache\n", (unsigned long long)sector);
250         return NULL;
251 }
252
253 static void unplug_slaves(mddev_t *mddev);
254
255 static struct stripe_head *get_active_stripe(raid6_conf_t *conf, sector_t sector,
256                                              int pd_idx, int noblock)
257 {
258         struct stripe_head *sh;
259
260         PRINTK("get_stripe, sector %llu\n", (unsigned long long)sector);
261
262         spin_lock_irq(&conf->device_lock);
263
264         do {
265                 sh = __find_stripe(conf, sector);
266                 if (!sh) {
267                         if (!conf->inactive_blocked)
268                                 sh = get_free_stripe(conf);
269                         if (noblock && sh == NULL)
270                                 break;
271                         if (!sh) {
272                                 conf->inactive_blocked = 1;
273                                 wait_event_lock_irq(conf->wait_for_stripe,
274                                                     !list_empty(&conf->inactive_list) &&
275                                                     (atomic_read(&conf->active_stripes) < (NR_STRIPES *3/4)
276                                                      || !conf->inactive_blocked),
277                                                     conf->device_lock,
278                                                     unplug_slaves(conf->mddev);
279                                         );
280                                 conf->inactive_blocked = 0;
281                         } else
282                                 init_stripe(sh, sector, pd_idx);
283                 } else {
284                         if (atomic_read(&sh->count)) {
285                                 if (!list_empty(&sh->lru))
286                                         BUG();
287                         } else {
288                                 if (!test_bit(STRIPE_HANDLE, &sh->state))
289                                         atomic_inc(&conf->active_stripes);
290                                 if (list_empty(&sh->lru))
291                                         BUG();
292                                 list_del_init(&sh->lru);
293                         }
294                 }
295         } while (sh == NULL);
296
297         if (sh)
298                 atomic_inc(&sh->count);
299
300         spin_unlock_irq(&conf->device_lock);
301         return sh;
302 }
303
304 static int grow_stripes(raid6_conf_t *conf, int num)
305 {
306         struct stripe_head *sh;
307         kmem_cache_t *sc;
308         int devs = conf->raid_disks;
309
310         sprintf(conf->cache_name, "raid6/%s", mdname(conf->mddev));
311
312         sc = kmem_cache_create(conf->cache_name,
313                                sizeof(struct stripe_head)+(devs-1)*sizeof(struct r5dev),
314                                0, 0, NULL, NULL);
315         if (!sc)
316                 return 1;
317         conf->slab_cache = sc;
318         while (num--) {
319                 sh = kmem_cache_alloc(sc, GFP_KERNEL);
320                 if (!sh)
321                         return 1;
322                 memset(sh, 0, sizeof(*sh) + (devs-1)*sizeof(struct r5dev));
323                 sh->raid_conf = conf;
324                 sh->lock = SPIN_LOCK_UNLOCKED;
325
326                 if (grow_buffers(sh, conf->raid_disks)) {
327                         shrink_buffers(sh, conf->raid_disks);
328                         kmem_cache_free(sc, sh);
329                         return 1;
330                 }
331                 /* we just created an active stripe so... */
332                 atomic_set(&sh->count, 1);
333                 atomic_inc(&conf->active_stripes);
334                 INIT_LIST_HEAD(&sh->lru);
335                 release_stripe(sh);
336         }
337         return 0;
338 }
339
340 static void shrink_stripes(raid6_conf_t *conf)
341 {
342         struct stripe_head *sh;
343
344         while (1) {
345                 spin_lock_irq(&conf->device_lock);
346                 sh = get_free_stripe(conf);
347                 spin_unlock_irq(&conf->device_lock);
348                 if (!sh)
349                         break;
350                 if (atomic_read(&sh->count))
351                         BUG();
352                 shrink_buffers(sh, conf->raid_disks);
353                 kmem_cache_free(conf->slab_cache, sh);
354                 atomic_dec(&conf->active_stripes);
355         }
356         kmem_cache_destroy(conf->slab_cache);
357         conf->slab_cache = NULL;
358 }
359
360 static int raid6_end_read_request (struct bio * bi, unsigned int bytes_done,
361                                    int error)
362 {
363         struct stripe_head *sh = bi->bi_private;
364         raid6_conf_t *conf = sh->raid_conf;
365         int disks = conf->raid_disks, i;
366         int uptodate = test_bit(BIO_UPTODATE, &bi->bi_flags);
367
368         if (bi->bi_size)
369                 return 1;
370
371         for (i=0 ; i<disks; i++)
372                 if (bi == &sh->dev[i].req)
373                         break;
374
375         PRINTK("end_read_request %llu/%d, count: %d, uptodate %d.\n",
376                 (unsigned long long)sh->sector, i, atomic_read(&sh->count),
377                 uptodate);
378         if (i == disks) {
379                 BUG();
380                 return 0;
381         }
382
383         if (uptodate) {
384 #if 0
385                 struct bio *bio;
386                 unsigned long flags;
387                 spin_lock_irqsave(&conf->device_lock, flags);
388                 /* we can return a buffer if we bypassed the cache or
389                  * if the top buffer is not in highmem.  If there are
390                  * multiple buffers, leave the extra work to
391                  * handle_stripe
392                  */
393                 buffer = sh->bh_read[i];
394                 if (buffer &&
395                     (!PageHighMem(buffer->b_page)
396                      || buffer->b_page == bh->b_page )
397                         ) {
398                         sh->bh_read[i] = buffer->b_reqnext;
399                         buffer->b_reqnext = NULL;
400                 } else
401                         buffer = NULL;
402                 spin_unlock_irqrestore(&conf->device_lock, flags);
403                 if (sh->bh_page[i]==bh->b_page)
404                         set_buffer_uptodate(bh);
405                 if (buffer) {
406                         if (buffer->b_page != bh->b_page)
407                                 memcpy(buffer->b_data, bh->b_data, bh->b_size);
408                         buffer->b_end_io(buffer, 1);
409                 }
410 #else
411                 set_bit(R5_UPTODATE, &sh->dev[i].flags);
412 #endif
413         } else {
414                 md_error(conf->mddev, conf->disks[i].rdev);
415                 clear_bit(R5_UPTODATE, &sh->dev[i].flags);
416         }
417         rdev_dec_pending(conf->disks[i].rdev, conf->mddev);
418 #if 0
419         /* must restore b_page before unlocking buffer... */
420         if (sh->bh_page[i] != bh->b_page) {
421                 bh->b_page = sh->bh_page[i];
422                 bh->b_data = page_address(bh->b_page);
423                 clear_buffer_uptodate(bh);
424         }
425 #endif
426         clear_bit(R5_LOCKED, &sh->dev[i].flags);
427         set_bit(STRIPE_HANDLE, &sh->state);
428         release_stripe(sh);
429         return 0;
430 }
431
432 static int raid6_end_write_request (struct bio *bi, unsigned int bytes_done,
433                                     int error)
434 {
435         struct stripe_head *sh = bi->bi_private;
436         raid6_conf_t *conf = sh->raid_conf;
437         int disks = conf->raid_disks, i;
438         unsigned long flags;
439         int uptodate = test_bit(BIO_UPTODATE, &bi->bi_flags);
440
441         if (bi->bi_size)
442                 return 1;
443
444         for (i=0 ; i<disks; i++)
445                 if (bi == &sh->dev[i].req)
446                         break;
447
448         PRINTK("end_write_request %llu/%d, count %d, uptodate: %d.\n",
449                 (unsigned long long)sh->sector, i, atomic_read(&sh->count),
450                 uptodate);
451         if (i == disks) {
452                 BUG();
453                 return 0;
454         }
455
456         spin_lock_irqsave(&conf->device_lock, flags);
457         if (!uptodate)
458                 md_error(conf->mddev, conf->disks[i].rdev);
459
460         rdev_dec_pending(conf->disks[i].rdev, conf->mddev);
461
462         clear_bit(R5_LOCKED, &sh->dev[i].flags);
463         set_bit(STRIPE_HANDLE, &sh->state);
464         __release_stripe(conf, sh);
465         spin_unlock_irqrestore(&conf->device_lock, flags);
466         return 0;
467 }
468
469
470 static sector_t compute_blocknr(struct stripe_head *sh, int i);
471
472 static void raid6_build_block (struct stripe_head *sh, int i)
473 {
474         struct r5dev *dev = &sh->dev[i];
475         int pd_idx = sh->pd_idx;
476         int qd_idx = raid6_next_disk(pd_idx, sh->raid_conf->raid_disks);
477
478         bio_init(&dev->req);
479         dev->req.bi_io_vec = &dev->vec;
480         dev->req.bi_vcnt++;
481         dev->vec.bv_page = dev->page;
482         dev->vec.bv_len = STRIPE_SIZE;
483         dev->vec.bv_offset = 0;
484
485         dev->req.bi_sector = sh->sector;
486         dev->req.bi_private = sh;
487
488         dev->flags = 0;
489         if (i != pd_idx && i != qd_idx)
490                 dev->sector = compute_blocknr(sh, i);
491 }
492
493 static void error(mddev_t *mddev, mdk_rdev_t *rdev)
494 {
495         char b[BDEVNAME_SIZE];
496         raid6_conf_t *conf = (raid6_conf_t *) mddev->private;
497         PRINTK("raid6: error called\n");
498
499         if (!rdev->faulty) {
500                 mddev->sb_dirty = 1;
501                 conf->working_disks--;
502                 if (rdev->in_sync) {
503                         mddev->degraded++;
504                         conf->failed_disks++;
505                         rdev->in_sync = 0;
506                         /*
507                          * if recovery was running, make sure it aborts.
508                          */
509                         set_bit(MD_RECOVERY_ERR, &mddev->recovery);
510                 }
511                 rdev->faulty = 1;
512                 printk (KERN_ALERT
513                         "raid6: Disk failure on %s, disabling device."
514                         " Operation continuing on %d devices\n",
515                         bdevname(rdev->bdev,b), conf->working_disks);
516         }
517 }
518
519 /*
520  * Input: a 'big' sector number,
521  * Output: index of the data and parity disk, and the sector # in them.
522  */
523 static sector_t raid6_compute_sector(sector_t r_sector, unsigned int raid_disks,
524                         unsigned int data_disks, unsigned int * dd_idx,
525                         unsigned int * pd_idx, raid6_conf_t *conf)
526 {
527         long stripe;
528         unsigned long chunk_number;
529         unsigned int chunk_offset;
530         sector_t new_sector;
531         int sectors_per_chunk = conf->chunk_size >> 9;
532
533         /* First compute the information on this sector */
534
535         /*
536          * Compute the chunk number and the sector offset inside the chunk
537          */
538         chunk_offset = sector_div(r_sector, sectors_per_chunk);
539         chunk_number = r_sector;
540         if ( r_sector != chunk_number ) {
541                 printk(KERN_CRIT "raid6: ERROR: r_sector = %llu, chunk_number = %lu\n",
542                        (unsigned long long)r_sector, (unsigned long)chunk_number);
543                 BUG();
544         }
545
546         /*
547          * Compute the stripe number
548          */
549         stripe = chunk_number / data_disks;
550
551         /*
552          * Compute the data disk and parity disk indexes inside the stripe
553          */
554         *dd_idx = chunk_number % data_disks;
555
556         /*
557          * Select the parity disk based on the user selected algorithm.
558          */
559
560         /**** FIX THIS ****/
561         switch (conf->algorithm) {
562         case ALGORITHM_LEFT_ASYMMETRIC:
563                 *pd_idx = raid_disks - 1 - (stripe % raid_disks);
564                 if (*pd_idx == raid_disks-1)
565                         (*dd_idx)++;    /* Q D D D P */
566                 else if (*dd_idx >= *pd_idx)
567                         (*dd_idx) += 2; /* D D P Q D */
568                 break;
569         case ALGORITHM_RIGHT_ASYMMETRIC:
570                 *pd_idx = stripe % raid_disks;
571                 if (*pd_idx == raid_disks-1)
572                         (*dd_idx)++;    /* Q D D D P */
573                 else if (*dd_idx >= *pd_idx)
574                         (*dd_idx) += 2; /* D D P Q D */
575                 break;
576         case ALGORITHM_LEFT_SYMMETRIC:
577                 *pd_idx = raid_disks - 1 - (stripe % raid_disks);
578                 *dd_idx = (*pd_idx + 2 + *dd_idx) % raid_disks;
579                 break;
580         case ALGORITHM_RIGHT_SYMMETRIC:
581                 *pd_idx = stripe % raid_disks;
582                 *dd_idx = (*pd_idx + 2 + *dd_idx) % raid_disks;
583                 break;
584         default:
585                 printk (KERN_CRIT "raid6: unsupported algorithm %d\n",
586                         conf->algorithm);
587         }
588
589         PRINTK("raid6: chunk_number = %lu, pd_idx = %u, dd_idx = %u\n",
590                chunk_number, *pd_idx, *dd_idx);
591
592         /*
593          * Finally, compute the new sector number
594          */
595         new_sector = (sector_t) stripe * sectors_per_chunk + chunk_offset;
596         return new_sector;
597 }
598
599
600 static sector_t compute_blocknr(struct stripe_head *sh, int i)
601 {
602         raid6_conf_t *conf = sh->raid_conf;
603         int raid_disks = conf->raid_disks, data_disks = raid_disks - 2;
604         sector_t new_sector = sh->sector, check;
605         int sectors_per_chunk = conf->chunk_size >> 9;
606         sector_t stripe;
607         int chunk_offset;
608         int chunk_number, dummy1, dummy2, dd_idx = i;
609         sector_t r_sector;
610         int i0 = i;
611
612         chunk_offset = sector_div(new_sector, sectors_per_chunk);
613         stripe = new_sector;
614         if ( new_sector != stripe ) {
615                 printk(KERN_CRIT "raid6: ERROR: new_sector = %llu, stripe = %lu\n",
616                        (unsigned long long)new_sector, (unsigned long)stripe);
617                 BUG();
618         }
619
620         switch (conf->algorithm) {
621                 case ALGORITHM_LEFT_ASYMMETRIC:
622                 case ALGORITHM_RIGHT_ASYMMETRIC:
623                         if (sh->pd_idx == raid_disks-1)
624                                 i--;    /* Q D D D P */
625                         else if (i > sh->pd_idx)
626                                 i -= 2; /* D D P Q D */
627                         break;
628                 case ALGORITHM_LEFT_SYMMETRIC:
629                 case ALGORITHM_RIGHT_SYMMETRIC:
630                         if (sh->pd_idx == raid_disks-1)
631                                 i--; /* Q D D D P */
632                         else {
633                                 /* D D P Q D */
634                                 if (i < sh->pd_idx)
635                                         i += raid_disks;
636                                 i -= (sh->pd_idx + 2);
637                         }
638                         break;
639                 default:
640                         printk (KERN_CRIT "raid6: unsupported algorithm %d\n",
641                                 conf->algorithm);
642         }
643
644         PRINTK("raid6: compute_blocknr: pd_idx = %u, i0 = %u, i = %u\n", sh->pd_idx, i0, i);
645
646         chunk_number = stripe * data_disks + i;
647         r_sector = (sector_t)chunk_number * sectors_per_chunk + chunk_offset;
648
649         check = raid6_compute_sector (r_sector, raid_disks, data_disks, &dummy1, &dummy2, conf);
650         if (check != sh->sector || dummy1 != dd_idx || dummy2 != sh->pd_idx) {
651                 printk(KERN_CRIT "raid6: compute_blocknr: map not correct\n");
652                 return 0;
653         }
654         return r_sector;
655 }
656
657
658
659 /*
660  * Copy data between a page in the stripe cache, and one or more bion
661  * The page could align with the middle of the bio, or there could be
662  * several bion, each with several bio_vecs, which cover part of the page
663  * Multiple bion are linked together on bi_next.  There may be extras
664  * at the end of this list.  We ignore them.
665  */
666 static void copy_data(int frombio, struct bio *bio,
667                      struct page *page,
668                      sector_t sector)
669 {
670         char *pa = page_address(page);
671         struct bio_vec *bvl;
672         int i;
673
674         for (;bio && bio->bi_sector < sector+STRIPE_SECTORS;
675               bio = r5_next_bio(bio, sector) ) {
676                 int page_offset;
677                 if (bio->bi_sector >= sector)
678                         page_offset = (signed)(bio->bi_sector - sector) * 512;
679                 else
680                         page_offset = (signed)(sector - bio->bi_sector) * -512;
681                 bio_for_each_segment(bvl, bio, i) {
682                         int len = bio_iovec_idx(bio,i)->bv_len;
683                         int clen;
684                         int b_offset = 0;
685
686                         if (page_offset < 0) {
687                                 b_offset = -page_offset;
688                                 page_offset += b_offset;
689                                 len -= b_offset;
690                         }
691
692                         if (len > 0 && page_offset + len > STRIPE_SIZE)
693                                 clen = STRIPE_SIZE - page_offset;
694                         else clen = len;
695
696                         if (clen > 0) {
697                                 char *ba = __bio_kmap_atomic(bio, i, KM_USER0);
698                                 if (frombio)
699                                         memcpy(pa+page_offset, ba+b_offset, clen);
700                                 else
701                                         memcpy(ba+b_offset, pa+page_offset, clen);
702                                 __bio_kunmap_atomic(ba, KM_USER0);
703                         }
704                         if (clen < len) /* hit end of page */
705                                 break;
706                         page_offset +=  len;
707                 }
708         }
709 }
710
711 #define check_xor()     do {                                            \
712                            if (count == MAX_XOR_BLOCKS) {               \
713                                 xor_block(count, STRIPE_SIZE, ptr);     \
714                                 count = 1;                              \
715                            }                                            \
716                         } while(0)
717
718 /* Compute P and Q syndromes */
719 static void compute_parity(struct stripe_head *sh, int method)
720 {
721         raid6_conf_t *conf = sh->raid_conf;
722         int i, pd_idx = sh->pd_idx, qd_idx, d0_idx, disks = conf->raid_disks, count;
723         struct bio *chosen;
724         /**** FIX THIS: This could be very bad if disks is close to 256 ****/
725         void *ptrs[disks];
726
727         qd_idx = raid6_next_disk(pd_idx, disks);
728         d0_idx = raid6_next_disk(qd_idx, disks);
729
730         PRINTK("compute_parity, stripe %llu, method %d\n",
731                 (unsigned long long)sh->sector, method);
732
733         switch(method) {
734         case READ_MODIFY_WRITE:
735                 BUG();          /* READ_MODIFY_WRITE N/A for RAID-6 */
736         case RECONSTRUCT_WRITE:
737         case UPDATE_PARITY:     /* Is this right? */
738                 for (i= disks; i-- ;)
739                         if ( i != pd_idx && i != qd_idx && sh->dev[i].towrite ) {
740                                 chosen = sh->dev[i].towrite;
741                                 sh->dev[i].towrite = NULL;
742                                 if (sh->dev[i].written) BUG();
743                                 sh->dev[i].written = chosen;
744                         }
745                 break;
746         case CHECK_PARITY:
747                 BUG();          /* Not implemented yet */
748         }
749
750         for (i = disks; i--;)
751                 if (sh->dev[i].written) {
752                         sector_t sector = sh->dev[i].sector;
753                         struct bio *wbi = sh->dev[i].written;
754                         while (wbi && wbi->bi_sector < sector + STRIPE_SECTORS) {
755                                 copy_data(1, wbi, sh->dev[i].page, sector);
756                                 wbi = r5_next_bio(wbi, sector);
757                         }
758
759                         set_bit(R5_LOCKED, &sh->dev[i].flags);
760                         set_bit(R5_UPTODATE, &sh->dev[i].flags);
761                 }
762
763 //      switch(method) {
764 //      case RECONSTRUCT_WRITE:
765 //      case CHECK_PARITY:
766 //      case UPDATE_PARITY:
767                 /* Note that unlike RAID-5, the ordering of the disks matters greatly. */
768                 /* FIX: Is this ordering of drives even remotely optimal? */
769                 count = 0;
770                 i = d0_idx;
771                 do {
772                         ptrs[count++] = page_address(sh->dev[i].page);
773
774                         i = raid6_next_disk(i, disks);
775                 } while ( i != d0_idx );
776 //              break;
777 //      }
778
779         raid6_call.gen_syndrome(disks, STRIPE_SIZE, ptrs);
780
781         switch(method) {
782         case RECONSTRUCT_WRITE:
783                 set_bit(R5_UPTODATE, &sh->dev[pd_idx].flags);
784                 set_bit(R5_UPTODATE, &sh->dev[qd_idx].flags);
785                 set_bit(R5_LOCKED,   &sh->dev[pd_idx].flags);
786                 set_bit(R5_LOCKED,   &sh->dev[qd_idx].flags);
787                 break;
788         case UPDATE_PARITY:
789                 set_bit(R5_UPTODATE, &sh->dev[pd_idx].flags);
790                 set_bit(R5_UPTODATE, &sh->dev[qd_idx].flags);
791                 break;
792         }
793 }
794
795 /* Compute one missing block */
796 static void compute_block_1(struct stripe_head *sh, int dd_idx)
797 {
798         raid6_conf_t *conf = sh->raid_conf;
799         int i, count, disks = conf->raid_disks;
800         void *ptr[MAX_XOR_BLOCKS], *p;
801         int pd_idx = sh->pd_idx;
802         int qd_idx = raid6_next_disk(pd_idx, disks);
803
804         PRINTK("compute_block_1, stripe %llu, idx %d\n",
805                 (unsigned long long)sh->sector, dd_idx);
806
807         if ( dd_idx == qd_idx ) {
808                 /* We're actually computing the Q drive */
809                 compute_parity(sh, UPDATE_PARITY);
810         } else {
811                 ptr[0] = page_address(sh->dev[dd_idx].page);
812                 memset(ptr[0], 0, STRIPE_SIZE);
813                 count = 1;
814                 for (i = disks ; i--; ) {
815                         if (i == dd_idx || i == qd_idx)
816                                 continue;
817                         p = page_address(sh->dev[i].page);
818                         if (test_bit(R5_UPTODATE, &sh->dev[i].flags))
819                                 ptr[count++] = p;
820                         else
821                                 PRINTK("compute_block() %d, stripe %llu, %d"
822                                        " not present\n", dd_idx,
823                                        (unsigned long long)sh->sector, i);
824
825                         check_xor();
826                 }
827                 if (count != 1)
828                         xor_block(count, STRIPE_SIZE, ptr);
829                 set_bit(R5_UPTODATE, &sh->dev[dd_idx].flags);
830         }
831 }
832
833 /* Compute two missing blocks */
834 static void compute_block_2(struct stripe_head *sh, int dd_idx1, int dd_idx2)
835 {
836         raid6_conf_t *conf = sh->raid_conf;
837         int i, count, disks = conf->raid_disks;
838         int pd_idx = sh->pd_idx;
839         int qd_idx = raid6_next_disk(pd_idx, disks);
840         int d0_idx = raid6_next_disk(qd_idx, disks);
841         int faila, failb;
842
843         /* faila and failb are disk numbers relative to d0_idx */
844         /* pd_idx become disks-2 and qd_idx become disks-1 */
845         faila = (dd_idx1 < d0_idx) ? dd_idx1+(disks-d0_idx) : dd_idx1-d0_idx;
846         failb = (dd_idx2 < d0_idx) ? dd_idx2+(disks-d0_idx) : dd_idx2-d0_idx;
847
848         BUG_ON(faila == failb);
849         if ( failb < faila ) { int tmp = faila; faila = failb; failb = tmp; }
850
851         PRINTK("compute_block_2, stripe %llu, idx %d,%d (%d,%d)\n",
852                (unsigned long long)sh->sector, dd_idx1, dd_idx2, faila, failb);
853
854         if ( failb == disks-1 ) {
855                 /* Q disk is one of the missing disks */
856                 if ( faila == disks-2 ) {
857                         /* Missing P+Q, just recompute */
858                         compute_parity(sh, UPDATE_PARITY);
859                         return;
860                 } else {
861                         /* We're missing D+Q; recompute D from P */
862                         compute_block_1(sh, (dd_idx1 == qd_idx) ? dd_idx2 : dd_idx1);
863                         compute_parity(sh, UPDATE_PARITY); /* Is this necessary? */
864                         return;
865                 }
866         }
867
868         /* We're missing D+P or D+D; build pointer table */
869         {
870                 /**** FIX THIS: This could be very bad if disks is close to 256 ****/
871                 void *ptrs[disks];
872
873                 count = 0;
874                 i = d0_idx;
875                 do {
876                         ptrs[count++] = page_address(sh->dev[i].page);
877                         i = raid6_next_disk(i, disks);
878                 } while ( i != d0_idx );
879
880                 if ( failb == disks-2 ) {
881                         /* We're missing D+P. */
882                         raid6_datap_recov(disks, STRIPE_SIZE, faila, ptrs);
883                 } else {
884                         /* We're missing D+D. */
885                         raid6_2data_recov(disks, STRIPE_SIZE, faila, failb, ptrs);
886                 }
887
888                 /* Both the above update both missing blocks */
889                 set_bit(R5_UPTODATE, &sh->dev[dd_idx1].flags);
890                 set_bit(R5_UPTODATE, &sh->dev[dd_idx2].flags);
891         }
892 }
893
894
895 /*
896  * Each stripe/dev can have one or more bion attached.
897  * toread/towrite point to the first in a chain.
898  * The bi_next chain must be in order.
899  */
900 static void add_stripe_bio (struct stripe_head *sh, struct bio *bi, int dd_idx, int forwrite)
901 {
902         struct bio **bip;
903         raid6_conf_t *conf = sh->raid_conf;
904
905         PRINTK("adding bh b#%llu to stripe s#%llu\n",
906                 (unsigned long long)bi->bi_sector,
907                 (unsigned long long)sh->sector);
908
909
910         spin_lock(&sh->lock);
911         spin_lock_irq(&conf->device_lock);
912         if (forwrite)
913                 bip = &sh->dev[dd_idx].towrite;
914         else
915                 bip = &sh->dev[dd_idx].toread;
916         while (*bip && (*bip)->bi_sector < bi->bi_sector) {
917                 BUG_ON((*bip)->bi_sector + ((*bip)->bi_size >> 9) > bi->bi_sector);
918                 bip = & (*bip)->bi_next;
919         }
920 /* FIXME do I need to worry about overlapping bion */
921         if (*bip && bi->bi_next && (*bip) != bi->bi_next)
922                 BUG();
923         if (*bip)
924                 bi->bi_next = *bip;
925         *bip = bi;
926         bi->bi_phys_segments ++;
927         spin_unlock_irq(&conf->device_lock);
928         spin_unlock(&sh->lock);
929
930         PRINTK("added bi b#%llu to stripe s#%llu, disk %d.\n",
931                 (unsigned long long)bi->bi_sector,
932                 (unsigned long long)sh->sector, dd_idx);
933
934         if (forwrite) {
935                 /* check if page is coverred */
936                 sector_t sector = sh->dev[dd_idx].sector;
937                 for (bi=sh->dev[dd_idx].towrite;
938                      sector < sh->dev[dd_idx].sector + STRIPE_SECTORS &&
939                              bi && bi->bi_sector <= sector;
940                      bi = r5_next_bio(bi, sh->dev[dd_idx].sector)) {
941                         if (bi->bi_sector + (bi->bi_size>>9) >= sector)
942                                 sector = bi->bi_sector + (bi->bi_size>>9);
943                 }
944                 if (sector >= sh->dev[dd_idx].sector + STRIPE_SECTORS)
945                         set_bit(R5_OVERWRITE, &sh->dev[dd_idx].flags);
946         }
947 }
948
949
950 /*
951  * handle_stripe - do things to a stripe.
952  *
953  * We lock the stripe and then examine the state of various bits
954  * to see what needs to be done.
955  * Possible results:
956  *    return some read request which now have data
957  *    return some write requests which are safely on disc
958  *    schedule a read on some buffers
959  *    schedule a write of some buffers
960  *    return confirmation of parity correctness
961  *
962  * Parity calculations are done inside the stripe lock
963  * buffers are taken off read_list or write_list, and bh_cache buffers
964  * get BH_Lock set before the stripe lock is released.
965  *
966  */
967
968 static void handle_stripe(struct stripe_head *sh)
969 {
970         raid6_conf_t *conf = sh->raid_conf;
971         int disks = conf->raid_disks;
972         struct bio *return_bi= NULL;
973         struct bio *bi;
974         int i;
975         int syncing;
976         int locked=0, uptodate=0, to_read=0, to_write=0, failed=0, written=0;
977         int non_overwrite = 0;
978         int failed_num[2] = {0, 0};
979         struct r5dev *dev, *pdev, *qdev;
980         int pd_idx = sh->pd_idx;
981         int qd_idx = raid6_next_disk(pd_idx, disks);
982         int p_failed, q_failed;
983
984         PRINTK("handling stripe %llu, state=%#lx cnt=%d, pd_idx=%d, qd_idx=%d\n",
985                (unsigned long long)sh->sector, sh->state, atomic_read(&sh->count),
986                pd_idx, qd_idx);
987
988         spin_lock(&sh->lock);
989         clear_bit(STRIPE_HANDLE, &sh->state);
990         clear_bit(STRIPE_DELAYED, &sh->state);
991
992         syncing = test_bit(STRIPE_SYNCING, &sh->state);
993         /* Now to look around and see what can be done */
994
995         for (i=disks; i--; ) {
996                 mdk_rdev_t *rdev;
997                 dev = &sh->dev[i];
998                 clear_bit(R5_Insync, &dev->flags);
999                 clear_bit(R5_Syncio, &dev->flags);
1000
1001                 PRINTK("check %d: state 0x%lx read %p write %p written %p\n",
1002                         i, dev->flags, dev->toread, dev->towrite, dev->written);
1003                 /* maybe we can reply to a read */
1004                 if (test_bit(R5_UPTODATE, &dev->flags) && dev->toread) {
1005                         struct bio *rbi, *rbi2;
1006                         PRINTK("Return read for disc %d\n", i);
1007                         spin_lock_irq(&conf->device_lock);
1008                         rbi = dev->toread;
1009                         dev->toread = NULL;
1010                         spin_unlock_irq(&conf->device_lock);
1011                         while (rbi && rbi->bi_sector < dev->sector + STRIPE_SECTORS) {
1012                                 copy_data(0, rbi, dev->page, dev->sector);
1013                                 rbi2 = r5_next_bio(rbi, dev->sector);
1014                                 spin_lock_irq(&conf->device_lock);
1015                                 if (--rbi->bi_phys_segments == 0) {
1016                                         rbi->bi_next = return_bi;
1017                                         return_bi = rbi;
1018                                 }
1019                                 spin_unlock_irq(&conf->device_lock);
1020                                 rbi = rbi2;
1021                         }
1022                 }
1023
1024                 /* now count some things */
1025                 if (test_bit(R5_LOCKED, &dev->flags)) locked++;
1026                 if (test_bit(R5_UPTODATE, &dev->flags)) uptodate++;
1027
1028
1029                 if (dev->toread) to_read++;
1030                 if (dev->towrite) {
1031                         to_write++;
1032                         if (!test_bit(R5_OVERWRITE, &dev->flags))
1033                                 non_overwrite++;
1034                 }
1035                 if (dev->written) written++;
1036                 rdev = conf->disks[i].rdev; /* FIXME, should I be looking rdev */
1037                 if (!rdev || !rdev->in_sync) {
1038                         if ( failed < 2 )
1039                                 failed_num[failed] = i;
1040                         failed++;
1041                 } else
1042                         set_bit(R5_Insync, &dev->flags);
1043         }
1044         PRINTK("locked=%d uptodate=%d to_read=%d"
1045                " to_write=%d failed=%d failed_num=%d,%d\n",
1046                locked, uptodate, to_read, to_write, failed,
1047                failed_num[0], failed_num[1]);
1048         /* check if the array has lost >2 devices and, if so, some requests might
1049          * need to be failed
1050          */
1051         if (failed > 2 && to_read+to_write+written) {
1052                 spin_lock_irq(&conf->device_lock);
1053                 for (i=disks; i--; ) {
1054                         /* fail all writes first */
1055                         bi = sh->dev[i].towrite;
1056                         sh->dev[i].towrite = NULL;
1057                         if (bi) to_write--;
1058
1059                         while (bi && bi->bi_sector < sh->dev[i].sector + STRIPE_SECTORS){
1060                                 struct bio *nextbi = r5_next_bio(bi, sh->dev[i].sector);
1061                                 clear_bit(BIO_UPTODATE, &bi->bi_flags);
1062                                 if (--bi->bi_phys_segments == 0) {
1063                                         md_write_end(conf->mddev);
1064                                         bi->bi_next = return_bi;
1065                                         return_bi = bi;
1066                                 }
1067                                 bi = nextbi;
1068                         }
1069                         /* and fail all 'written' */
1070                         bi = sh->dev[i].written;
1071                         sh->dev[i].written = NULL;
1072                         while (bi && bi->bi_sector < sh->dev[i].sector + STRIPE_SECTORS) {
1073                                 struct bio *bi2 = r5_next_bio(bi, sh->dev[i].sector);
1074                                 clear_bit(BIO_UPTODATE, &bi->bi_flags);
1075                                 if (--bi->bi_phys_segments == 0) {
1076                                         md_write_end(conf->mddev);
1077                                         bi->bi_next = return_bi;
1078                                         return_bi = bi;
1079                                 }
1080                                 bi = bi2;
1081                         }
1082
1083                         /* fail any reads if this device is non-operational */
1084                         if (!test_bit(R5_Insync, &sh->dev[i].flags)) {
1085                                 bi = sh->dev[i].toread;
1086                                 sh->dev[i].toread = NULL;
1087                                 if (bi) to_read--;
1088                                 while (bi && bi->bi_sector < sh->dev[i].sector + STRIPE_SECTORS){
1089                                         struct bio *nextbi = r5_next_bio(bi, sh->dev[i].sector);
1090                                         clear_bit(BIO_UPTODATE, &bi->bi_flags);
1091                                         if (--bi->bi_phys_segments == 0) {
1092                                                 bi->bi_next = return_bi;
1093                                                 return_bi = bi;
1094                                         }
1095                                         bi = nextbi;
1096                                 }
1097                         }
1098                 }
1099                 spin_unlock_irq(&conf->device_lock);
1100         }
1101         if (failed > 2 && syncing) {
1102                 md_done_sync(conf->mddev, STRIPE_SECTORS,0);
1103                 clear_bit(STRIPE_SYNCING, &sh->state);
1104                 syncing = 0;
1105         }
1106
1107         /*
1108          * might be able to return some write requests if the parity blocks
1109          * are safe, or on a failed drive
1110          */
1111         pdev = &sh->dev[pd_idx];
1112         p_failed = (failed >= 1 && failed_num[0] == pd_idx)
1113                 || (failed >= 2 && failed_num[1] == pd_idx);
1114         qdev = &sh->dev[qd_idx];
1115         q_failed = (failed >= 1 && failed_num[0] == qd_idx)
1116                 || (failed >= 2 && failed_num[1] == qd_idx);
1117
1118         if ( written &&
1119              ( p_failed || ((test_bit(R5_Insync, &pdev->flags)
1120                              && !test_bit(R5_LOCKED, &pdev->flags)
1121                              && test_bit(R5_UPTODATE, &pdev->flags))) ) &&
1122              ( q_failed || ((test_bit(R5_Insync, &qdev->flags)
1123                              && !test_bit(R5_LOCKED, &qdev->flags)
1124                              && test_bit(R5_UPTODATE, &qdev->flags))) ) ) {
1125                 /* any written block on an uptodate or failed drive can be
1126                  * returned.  Note that if we 'wrote' to a failed drive,
1127                  * it will be UPTODATE, but never LOCKED, so we don't need
1128                  * to test 'failed' directly.
1129                  */
1130                 for (i=disks; i--; )
1131                         if (sh->dev[i].written) {
1132                                 dev = &sh->dev[i];
1133                                 if (!test_bit(R5_LOCKED, &dev->flags) &&
1134                                     test_bit(R5_UPTODATE, &dev->flags) ) {
1135                                         /* We can return any write requests */
1136                                         struct bio *wbi, *wbi2;
1137                                         PRINTK("Return write for stripe %llu disc %d\n",
1138                                                (unsigned long long)sh->sector, i);
1139                                         spin_lock_irq(&conf->device_lock);
1140                                         wbi = dev->written;
1141                                         dev->written = NULL;
1142                                         while (wbi && wbi->bi_sector < dev->sector + STRIPE_SECTORS) {
1143                                                 wbi2 = r5_next_bio(wbi, dev->sector);
1144                                                 if (--wbi->bi_phys_segments == 0) {
1145                                                         md_write_end(conf->mddev);
1146                                                         wbi->bi_next = return_bi;
1147                                                         return_bi = wbi;
1148                                                 }
1149                                                 wbi = wbi2;
1150                                         }
1151                                         spin_unlock_irq(&conf->device_lock);
1152                                 }
1153                         }
1154         }
1155
1156         /* Now we might consider reading some blocks, either to check/generate
1157          * parity, or to satisfy requests
1158          * or to load a block that is being partially written.
1159          */
1160         if (to_read || non_overwrite || (syncing && (uptodate < disks))) {
1161                 for (i=disks; i--;) {
1162                         dev = &sh->dev[i];
1163                         if (!test_bit(R5_LOCKED, &dev->flags) && !test_bit(R5_UPTODATE, &dev->flags) &&
1164                             (dev->toread ||
1165                              (dev->towrite && !test_bit(R5_OVERWRITE, &dev->flags)) ||
1166                              syncing ||
1167                              (failed >= 1 && (sh->dev[failed_num[0]].toread ||
1168                                          (sh->dev[failed_num[0]].towrite && !test_bit(R5_OVERWRITE, &sh->dev[failed_num[0]].flags)))) ||
1169                              (failed >= 2 && (sh->dev[failed_num[1]].toread ||
1170                                          (sh->dev[failed_num[1]].towrite && !test_bit(R5_OVERWRITE, &sh->dev[failed_num[1]].flags))))
1171                                     )
1172                                 ) {
1173                                 /* we would like to get this block, possibly
1174                                  * by computing it, but we might not be able to
1175                                  */
1176                                 if (uptodate == disks-1) {
1177                                         PRINTK("Computing stripe %llu block %d\n",
1178                                                (unsigned long long)sh->sector, i);
1179                                         compute_block_1(sh, i);
1180                                         uptodate++;
1181                                 } else if ( uptodate == disks-2 && failed >= 2 ) {
1182                                         /* Computing 2-failure is *very* expensive; only do it if failed >= 2 */
1183                                         int other;
1184                                         for (other=disks; other--;) {
1185                                                 if ( other == i )
1186                                                         continue;
1187                                                 if ( !test_bit(R5_UPTODATE, &sh->dev[other].flags) )
1188                                                         break;
1189                                         }
1190                                         BUG_ON(other < 0);
1191                                         PRINTK("Computing stripe %llu blocks %d,%d\n",
1192                                                (unsigned long long)sh->sector, i, other);
1193                                         compute_block_2(sh, i, other);
1194                                         uptodate += 2;
1195                                 } else if (test_bit(R5_Insync, &dev->flags)) {
1196                                         set_bit(R5_LOCKED, &dev->flags);
1197                                         set_bit(R5_Wantread, &dev->flags);
1198 #if 0
1199                                         /* if I am just reading this block and we don't have
1200                                            a failed drive, or any pending writes then sidestep the cache */
1201                                         if (sh->bh_read[i] && !sh->bh_read[i]->b_reqnext &&
1202                                             ! syncing && !failed && !to_write) {
1203                                                 sh->bh_cache[i]->b_page =  sh->bh_read[i]->b_page;
1204                                                 sh->bh_cache[i]->b_data =  sh->bh_read[i]->b_data;
1205                                         }
1206 #endif
1207                                         locked++;
1208                                         PRINTK("Reading block %d (sync=%d)\n",
1209                                                 i, syncing);
1210                                         if (syncing)
1211                                                 md_sync_acct(conf->disks[i].rdev, STRIPE_SECTORS);
1212                                 }
1213                         }
1214                 }
1215                 set_bit(STRIPE_HANDLE, &sh->state);
1216         }
1217
1218         /* now to consider writing and what else, if anything should be read */
1219         if (to_write) {
1220                 int rcw=0, must_compute=0;
1221                 for (i=disks ; i--;) {
1222                         dev = &sh->dev[i];
1223                         /* Would I have to read this buffer for reconstruct_write */
1224                         if (!test_bit(R5_OVERWRITE, &dev->flags)
1225                             && i != pd_idx && i != qd_idx
1226                             && (!test_bit(R5_LOCKED, &dev->flags)
1227 #if 0
1228                                 || sh->bh_page[i] != bh->b_page
1229 #endif
1230                                     ) &&
1231                             !test_bit(R5_UPTODATE, &dev->flags)) {
1232                                 if (test_bit(R5_Insync, &dev->flags)) rcw++;
1233                                 else {
1234                                         PRINTK("raid6: must_compute: disk %d flags=%#lx\n", i, dev->flags);
1235                                         must_compute++;
1236                                 }
1237                         }
1238                 }
1239                 PRINTK("for sector %llu, rcw=%d, must_compute=%d\n",
1240                        (unsigned long long)sh->sector, rcw, must_compute);
1241                 set_bit(STRIPE_HANDLE, &sh->state);
1242
1243                 if (rcw > 0)
1244                         /* want reconstruct write, but need to get some data */
1245                         for (i=disks; i--;) {
1246                                 dev = &sh->dev[i];
1247                                 if (!test_bit(R5_OVERWRITE, &dev->flags)
1248                                     && !(failed == 0 && (i == pd_idx || i == qd_idx))
1249                                     && !test_bit(R5_LOCKED, &dev->flags) && !test_bit(R5_UPTODATE, &dev->flags) &&
1250                                     test_bit(R5_Insync, &dev->flags)) {
1251                                         if (test_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
1252                                         {
1253                                                 PRINTK("Read_old stripe %llu block %d for Reconstruct\n",
1254                                                        (unsigned long long)sh->sector, i);
1255                                                 set_bit(R5_LOCKED, &dev->flags);
1256                                                 set_bit(R5_Wantread, &dev->flags);
1257                                                 locked++;
1258                                         } else {
1259                                                 PRINTK("Request delayed stripe %llu block %d for Reconstruct\n",
1260                                                        (unsigned long long)sh->sector, i);
1261                                                 set_bit(STRIPE_DELAYED, &sh->state);
1262                                                 set_bit(STRIPE_HANDLE, &sh->state);
1263                                         }
1264                                 }
1265                         }
1266                 /* now if nothing is locked, and if we have enough data, we can start a write request */
1267                 if (locked == 0 && rcw == 0) {
1268                         if ( must_compute > 0 ) {
1269                                 /* We have failed blocks and need to compute them */
1270                                 switch ( failed ) {
1271                                 case 0: BUG();
1272                                 case 1: compute_block_1(sh, failed_num[0]); break;
1273                                 case 2: compute_block_2(sh, failed_num[0], failed_num[1]); break;
1274                                 default: BUG(); /* This request should have been failed? */
1275                                 }
1276                         }
1277
1278                         PRINTK("Computing parity for stripe %llu\n", (unsigned long long)sh->sector);
1279                         compute_parity(sh, RECONSTRUCT_WRITE);
1280                         /* now every locked buffer is ready to be written */
1281                         for (i=disks; i--;)
1282                                 if (test_bit(R5_LOCKED, &sh->dev[i].flags)) {
1283                                         PRINTK("Writing stripe %llu block %d\n",
1284                                                (unsigned long long)sh->sector, i);
1285                                         locked++;
1286                                         set_bit(R5_Wantwrite, &sh->dev[i].flags);
1287 #if 0 /**** FIX: I don't understand the logic here... ****/
1288                                         if (!test_bit(R5_Insync, &sh->dev[i].flags)
1289                                             || ((i==pd_idx || i==qd_idx) && failed == 0)) /* FIX? */
1290                                                 set_bit(STRIPE_INSYNC, &sh->state);
1291 #endif
1292                                 }
1293                         if (test_and_clear_bit(STRIPE_PREREAD_ACTIVE, &sh->state)) {
1294                                 atomic_dec(&conf->preread_active_stripes);
1295                                 if (atomic_read(&conf->preread_active_stripes) < IO_THRESHOLD)
1296                                         md_wakeup_thread(conf->mddev->thread);
1297                         }
1298                 }
1299         }
1300
1301         /* maybe we need to check and possibly fix the parity for this stripe
1302          * Any reads will already have been scheduled, so we just see if enough data
1303          * is available
1304          */
1305         if (syncing && locked == 0 &&
1306             !test_bit(STRIPE_INSYNC, &sh->state) && failed <= 2) {
1307                 set_bit(STRIPE_HANDLE, &sh->state);
1308 #if 0 /* RAID-6: Don't support CHECK PARITY yet */
1309                 if (failed == 0) {
1310                         char *pagea;
1311                         if (uptodate != disks)
1312                                 BUG();
1313                         compute_parity(sh, CHECK_PARITY);
1314                         uptodate--;
1315                         pagea = page_address(sh->dev[pd_idx].page);
1316                         if ((*(u32*)pagea) == 0 &&
1317                             !memcmp(pagea, pagea+4, STRIPE_SIZE-4)) {
1318                                 /* parity is correct (on disc, not in buffer any more) */
1319                                 set_bit(STRIPE_INSYNC, &sh->state);
1320                         }
1321                 }
1322 #endif
1323                 if (!test_bit(STRIPE_INSYNC, &sh->state)) {
1324                         int failed_needupdate[2];
1325                         struct r5dev *adev, *bdev;
1326
1327                         if ( failed < 1 )
1328                                 failed_num[0] = pd_idx;
1329                         if ( failed < 2 )
1330                                 failed_num[1] = (failed_num[0] == qd_idx) ? pd_idx : qd_idx;
1331
1332                         failed_needupdate[0] = !test_bit(R5_UPTODATE, &sh->dev[failed_num[0]].flags);
1333                         failed_needupdate[1] = !test_bit(R5_UPTODATE, &sh->dev[failed_num[1]].flags);
1334
1335                         PRINTK("sync: failed=%d num=%d,%d fnu=%u%u\n",
1336                                failed, failed_num[0], failed_num[1], failed_needupdate[0], failed_needupdate[1]);
1337
1338 #if 0  /* RAID-6: This code seems to require that CHECK_PARITY destroys the uptodateness of the parity */
1339                         /* should be able to compute the missing block(s) and write to spare */
1340                         if ( failed_needupdate[0] ^ failed_needupdate[1] ) {
1341                                 if (uptodate+1 != disks)
1342                                         BUG();
1343                                 compute_block_1(sh, failed_needupdate[0] ? failed_num[0] : failed_num[1]);
1344                                 uptodate++;
1345                         } else if ( failed_needupdate[0] & failed_needupdate[1] ) {
1346                                 if (uptodate+2 != disks)
1347                                         BUG();
1348                                 compute_block_2(sh, failed_num[0], failed_num[1]);
1349                                 uptodate += 2;
1350                         }
1351 #else
1352                         compute_block_2(sh, failed_num[0], failed_num[1]);
1353                         uptodate += failed_needupdate[0] + failed_needupdate[1];
1354 #endif
1355
1356                         if (uptodate != disks)
1357                                 BUG();
1358
1359                         PRINTK("Marking for sync stripe %llu blocks %d,%d\n",
1360                                (unsigned long long)sh->sector, failed_num[0], failed_num[1]);
1361
1362                         /**** FIX: Should we really do both of these unconditionally? ****/
1363                         adev = &sh->dev[failed_num[0]];
1364                         locked += !test_bit(R5_LOCKED, &adev->flags);
1365                         set_bit(R5_LOCKED, &adev->flags);
1366                         set_bit(R5_Wantwrite, &adev->flags);
1367                         bdev = &sh->dev[failed_num[1]];
1368                         locked += !test_bit(R5_LOCKED, &bdev->flags);
1369                         set_bit(R5_LOCKED, &bdev->flags);
1370                         set_bit(R5_Wantwrite, &bdev->flags);
1371
1372                         set_bit(STRIPE_INSYNC, &sh->state);
1373                         set_bit(R5_Syncio, &adev->flags);
1374                         set_bit(R5_Syncio, &bdev->flags);
1375                 }
1376         }
1377         if (syncing && locked == 0 && test_bit(STRIPE_INSYNC, &sh->state)) {
1378                 md_done_sync(conf->mddev, STRIPE_SECTORS,1);
1379                 clear_bit(STRIPE_SYNCING, &sh->state);
1380         }
1381
1382         spin_unlock(&sh->lock);
1383
1384         while ((bi=return_bi)) {
1385                 int bytes = bi->bi_size;
1386
1387                 return_bi = bi->bi_next;
1388                 bi->bi_next = NULL;
1389                 bi->bi_size = 0;
1390                 bi->bi_end_io(bi, bytes, 0);
1391         }
1392         for (i=disks; i-- ;) {
1393                 int rw;
1394                 struct bio *bi;
1395                 mdk_rdev_t *rdev;
1396                 if (test_and_clear_bit(R5_Wantwrite, &sh->dev[i].flags))
1397                         rw = 1;
1398                 else if (test_and_clear_bit(R5_Wantread, &sh->dev[i].flags))
1399                         rw = 0;
1400                 else
1401                         continue;
1402
1403                 bi = &sh->dev[i].req;
1404
1405                 bi->bi_rw = rw;
1406                 if (rw)
1407                         bi->bi_end_io = raid6_end_write_request;
1408                 else
1409                         bi->bi_end_io = raid6_end_read_request;
1410
1411                 spin_lock_irq(&conf->device_lock);
1412                 rdev = conf->disks[i].rdev;
1413                 if (rdev && rdev->faulty)
1414                         rdev = NULL;
1415                 if (rdev)
1416                         atomic_inc(&rdev->nr_pending);
1417                 spin_unlock_irq(&conf->device_lock);
1418
1419                 if (rdev) {
1420                         if (test_bit(R5_Syncio, &sh->dev[i].flags))
1421                                 md_sync_acct(rdev, STRIPE_SECTORS);
1422
1423                         bi->bi_bdev = rdev->bdev;
1424                         PRINTK("for %llu schedule op %ld on disc %d\n",
1425                                 (unsigned long long)sh->sector, bi->bi_rw, i);
1426                         atomic_inc(&sh->count);
1427                         bi->bi_sector = sh->sector + rdev->data_offset;
1428                         bi->bi_flags = 1 << BIO_UPTODATE;
1429                         bi->bi_vcnt = 1;
1430                         bi->bi_idx = 0;
1431                         bi->bi_io_vec = &sh->dev[i].vec;
1432                         bi->bi_io_vec[0].bv_len = STRIPE_SIZE;
1433                         bi->bi_io_vec[0].bv_offset = 0;
1434                         bi->bi_size = STRIPE_SIZE;
1435                         bi->bi_next = NULL;
1436                         generic_make_request(bi);
1437                 } else {
1438                         PRINTK("skip op %ld on disc %d for sector %llu\n",
1439                                 bi->bi_rw, i, (unsigned long long)sh->sector);
1440                         clear_bit(R5_LOCKED, &sh->dev[i].flags);
1441                         set_bit(STRIPE_HANDLE, &sh->state);
1442                 }
1443         }
1444 }
1445
1446 static inline void raid6_activate_delayed(raid6_conf_t *conf)
1447 {
1448         if (atomic_read(&conf->preread_active_stripes) < IO_THRESHOLD) {
1449                 while (!list_empty(&conf->delayed_list)) {
1450                         struct list_head *l = conf->delayed_list.next;
1451                         struct stripe_head *sh;
1452                         sh = list_entry(l, struct stripe_head, lru);
1453                         list_del_init(l);
1454                         clear_bit(STRIPE_DELAYED, &sh->state);
1455                         if (!test_and_set_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
1456                                 atomic_inc(&conf->preread_active_stripes);
1457                         list_add_tail(&sh->lru, &conf->handle_list);
1458                 }
1459         }
1460 }
1461
1462 static void unplug_slaves(mddev_t *mddev)
1463 {
1464         raid6_conf_t *conf = mddev_to_conf(mddev);
1465         int i;
1466         unsigned long flags;
1467
1468         spin_lock_irqsave(&conf->device_lock, flags);
1469         for (i=0; i<mddev->raid_disks; i++) {
1470                 mdk_rdev_t *rdev = conf->disks[i].rdev;
1471                 if (rdev && atomic_read(&rdev->nr_pending)) {
1472                         request_queue_t *r_queue = bdev_get_queue(rdev->bdev);
1473
1474                         atomic_inc(&rdev->nr_pending);
1475                         spin_unlock_irqrestore(&conf->device_lock, flags);
1476
1477                         if (r_queue && r_queue->unplug_fn)
1478                                 r_queue->unplug_fn(r_queue);
1479
1480                         spin_lock_irqsave(&conf->device_lock, flags);
1481                         atomic_dec(&rdev->nr_pending);
1482                 }
1483         }
1484         spin_unlock_irqrestore(&conf->device_lock, flags);
1485 }
1486
1487 static void raid6_unplug_device(request_queue_t *q)
1488 {
1489         mddev_t *mddev = q->queuedata;
1490         raid6_conf_t *conf = mddev_to_conf(mddev);
1491         unsigned long flags;
1492
1493         spin_lock_irqsave(&conf->device_lock, flags);
1494
1495         if (blk_remove_plug(q))
1496                 raid6_activate_delayed(conf);
1497         md_wakeup_thread(mddev->thread);
1498
1499         spin_unlock_irqrestore(&conf->device_lock, flags);
1500
1501         unplug_slaves(mddev);
1502 }
1503
1504 static inline void raid6_plug_device(raid6_conf_t *conf)
1505 {
1506         spin_lock_irq(&conf->device_lock);
1507         blk_plug_device(conf->mddev->queue);
1508         spin_unlock_irq(&conf->device_lock);
1509 }
1510
1511 static int make_request (request_queue_t *q, struct bio * bi)
1512 {
1513         mddev_t *mddev = q->queuedata;
1514         raid6_conf_t *conf = mddev_to_conf(mddev);
1515         const unsigned int raid_disks = conf->raid_disks;
1516         const unsigned int data_disks = raid_disks - 2;
1517         unsigned int dd_idx, pd_idx;
1518         sector_t new_sector;
1519         sector_t logical_sector, last_sector;
1520         struct stripe_head *sh;
1521
1522         if (bio_data_dir(bi)==WRITE) {
1523                 disk_stat_inc(mddev->gendisk, writes);
1524                 disk_stat_add(mddev->gendisk, write_sectors, bio_sectors(bi));
1525         } else {
1526                 disk_stat_inc(mddev->gendisk, reads);
1527                 disk_stat_add(mddev->gendisk, read_sectors, bio_sectors(bi));
1528         }
1529
1530         logical_sector = bi->bi_sector & ~((sector_t)STRIPE_SECTORS-1);
1531         last_sector = bi->bi_sector + (bi->bi_size>>9);
1532
1533         bi->bi_next = NULL;
1534         bi->bi_phys_segments = 1;       /* over-loaded to count active stripes */
1535         if ( bio_data_dir(bi) == WRITE )
1536                 md_write_start(mddev);
1537         for (;logical_sector < last_sector; logical_sector += STRIPE_SECTORS) {
1538
1539                 new_sector = raid6_compute_sector(logical_sector,
1540                                                   raid_disks, data_disks, &dd_idx, &pd_idx, conf);
1541
1542                 PRINTK("raid6: make_request, sector %Lu logical %Lu\n",
1543                        (unsigned long long)new_sector,
1544                        (unsigned long long)logical_sector);
1545
1546                 sh = get_active_stripe(conf, new_sector, pd_idx, (bi->bi_rw&RWA_MASK));
1547                 if (sh) {
1548
1549                         add_stripe_bio(sh, bi, dd_idx, (bi->bi_rw&RW_MASK));
1550
1551                         raid6_plug_device(conf);
1552                         handle_stripe(sh);
1553                         release_stripe(sh);
1554                 } else {
1555                         /* cannot get stripe for read-ahead, just give-up */
1556                         clear_bit(BIO_UPTODATE, &bi->bi_flags);
1557                         break;
1558                 }
1559
1560         }
1561         spin_lock_irq(&conf->device_lock);
1562         if (--bi->bi_phys_segments == 0) {
1563                 int bytes = bi->bi_size;
1564
1565                 if ( bio_data_dir(bi) == WRITE )
1566                         md_write_end(mddev);
1567                 bi->bi_size = 0;
1568                 bi->bi_end_io(bi, bytes, 0);
1569         }
1570         spin_unlock_irq(&conf->device_lock);
1571         return 0;
1572 }
1573
1574 /* FIXME go_faster isn't used */
1575 static int sync_request (mddev_t *mddev, sector_t sector_nr, int go_faster)
1576 {
1577         raid6_conf_t *conf = (raid6_conf_t *) mddev->private;
1578         struct stripe_head *sh;
1579         int sectors_per_chunk = conf->chunk_size >> 9;
1580         sector_t x;
1581         unsigned long stripe;
1582         int chunk_offset;
1583         int dd_idx, pd_idx;
1584         sector_t first_sector;
1585         int raid_disks = conf->raid_disks;
1586         int data_disks = raid_disks - 2;
1587
1588         if (sector_nr >= mddev->size <<1) {
1589                 /* just being told to finish up .. nothing much to do */
1590                 unplug_slaves(mddev);
1591                 return 0;
1592         }
1593
1594         x = sector_nr;
1595         chunk_offset = sector_div(x, sectors_per_chunk);
1596         stripe = x;
1597         BUG_ON(x != stripe);
1598
1599         first_sector = raid6_compute_sector((sector_t)stripe*data_disks*sectors_per_chunk
1600                 + chunk_offset, raid_disks, data_disks, &dd_idx, &pd_idx, conf);
1601         sh = get_active_stripe(conf, sector_nr, pd_idx, 1);
1602         if (sh == NULL) {
1603                 sh = get_active_stripe(conf, sector_nr, pd_idx, 0);
1604                 /* make sure we don't swamp the stripe cache if someone else
1605                  * is trying to get access
1606                  */
1607                 set_current_state(TASK_UNINTERRUPTIBLE);
1608                 schedule_timeout(1);
1609         }
1610         spin_lock(&sh->lock);
1611         set_bit(STRIPE_SYNCING, &sh->state);
1612         clear_bit(STRIPE_INSYNC, &sh->state);
1613         spin_unlock(&sh->lock);
1614
1615         handle_stripe(sh);
1616         release_stripe(sh);
1617
1618         return STRIPE_SECTORS;
1619 }
1620
1621 /*
1622  * This is our raid6 kernel thread.
1623  *
1624  * We scan the hash table for stripes which can be handled now.
1625  * During the scan, completed stripes are saved for us by the interrupt
1626  * handler, so that they will not have to wait for our next wakeup.
1627  */
1628 static void raid6d (mddev_t *mddev)
1629 {
1630         struct stripe_head *sh;
1631         raid6_conf_t *conf = mddev_to_conf(mddev);
1632         int handled;
1633
1634         PRINTK("+++ raid6d active\n");
1635
1636         md_check_recovery(mddev);
1637         md_handle_safemode(mddev);
1638
1639         handled = 0;
1640         spin_lock_irq(&conf->device_lock);
1641         while (1) {
1642                 struct list_head *first;
1643
1644                 if (list_empty(&conf->handle_list) &&
1645                     atomic_read(&conf->preread_active_stripes) < IO_THRESHOLD &&
1646                     !blk_queue_plugged(mddev->queue) &&
1647                     !list_empty(&conf->delayed_list))
1648                         raid6_activate_delayed(conf);
1649
1650                 if (list_empty(&conf->handle_list))
1651                         break;
1652
1653                 first = conf->handle_list.next;
1654                 sh = list_entry(first, struct stripe_head, lru);
1655
1656                 list_del_init(first);
1657                 atomic_inc(&sh->count);
1658                 if (atomic_read(&sh->count)!= 1)
1659                         BUG();
1660                 spin_unlock_irq(&conf->device_lock);
1661
1662                 handled++;
1663                 handle_stripe(sh);
1664                 release_stripe(sh);
1665
1666                 spin_lock_irq(&conf->device_lock);
1667         }
1668         PRINTK("%d stripes handled\n", handled);
1669
1670         spin_unlock_irq(&conf->device_lock);
1671
1672         unplug_slaves(mddev);
1673
1674         PRINTK("--- raid6d inactive\n");
1675 }
1676
1677 static int run (mddev_t *mddev)
1678 {
1679         raid6_conf_t *conf;
1680         int raid_disk, memory;
1681         mdk_rdev_t *rdev;
1682         struct disk_info *disk;
1683         struct list_head *tmp;
1684
1685         if (mddev->level != 6) {
1686                 PRINTK("raid6: %s: raid level not set to 6 (%d)\n", mdname(mddev), mddev->level);
1687                 return -EIO;
1688         }
1689
1690         mddev->private = kmalloc (sizeof (raid6_conf_t)
1691                                   + mddev->raid_disks * sizeof(struct disk_info),
1692                                   GFP_KERNEL);
1693         if ((conf = mddev->private) == NULL)
1694                 goto abort;
1695         memset (conf, 0, sizeof (*conf) + mddev->raid_disks * sizeof(struct disk_info) );
1696         conf->mddev = mddev;
1697
1698         if ((conf->stripe_hashtbl = (struct stripe_head **) __get_free_pages(GFP_ATOMIC, HASH_PAGES_ORDER)) == NULL)
1699                 goto abort;
1700         memset(conf->stripe_hashtbl, 0, HASH_PAGES * PAGE_SIZE);
1701
1702         conf->device_lock = SPIN_LOCK_UNLOCKED;
1703         init_waitqueue_head(&conf->wait_for_stripe);
1704         INIT_LIST_HEAD(&conf->handle_list);
1705         INIT_LIST_HEAD(&conf->delayed_list);
1706         INIT_LIST_HEAD(&conf->inactive_list);
1707         atomic_set(&conf->active_stripes, 0);
1708         atomic_set(&conf->preread_active_stripes, 0);
1709
1710         mddev->queue->unplug_fn = raid6_unplug_device;
1711
1712         PRINTK("raid6: run(%s) called.\n", mdname(mddev));
1713
1714         ITERATE_RDEV(mddev,rdev,tmp) {
1715                 raid_disk = rdev->raid_disk;
1716                 if (raid_disk >= mddev->raid_disks
1717                     || raid_disk < 0)
1718                         continue;
1719                 disk = conf->disks + raid_disk;
1720
1721                 disk->rdev = rdev;
1722
1723                 if (rdev->in_sync) {
1724                         char b[BDEVNAME_SIZE];
1725                         printk(KERN_INFO "raid6: device %s operational as raid"
1726                                " disk %d\n", bdevname(rdev->bdev,b),
1727                                raid_disk);
1728                         conf->working_disks++;
1729                 }
1730         }
1731
1732         conf->raid_disks = mddev->raid_disks;
1733
1734         /*
1735          * 0 for a fully functional array, 1 or 2 for a degraded array.
1736          */
1737         mddev->degraded = conf->failed_disks = conf->raid_disks - conf->working_disks;
1738         conf->mddev = mddev;
1739         conf->chunk_size = mddev->chunk_size;
1740         conf->level = mddev->level;
1741         conf->algorithm = mddev->layout;
1742         conf->max_nr_stripes = NR_STRIPES;
1743
1744         /* device size must be a multiple of chunk size */
1745         mddev->size &= ~(mddev->chunk_size/1024 -1);
1746
1747         if (conf->raid_disks < 4) {
1748                 printk(KERN_ERR "raid6: not enough configured devices for %s (%d, minimum 4)\n",
1749                        mdname(mddev), conf->raid_disks);
1750                 goto abort;
1751         }
1752         if (!conf->chunk_size || conf->chunk_size % 4) {
1753                 printk(KERN_ERR "raid6: invalid chunk size %d for %s\n",
1754                        conf->chunk_size, mdname(mddev));
1755                 goto abort;
1756         }
1757         if (conf->algorithm > ALGORITHM_RIGHT_SYMMETRIC) {
1758                 printk(KERN_ERR
1759                        "raid6: unsupported parity algorithm %d for %s\n",
1760                        conf->algorithm, mdname(mddev));
1761                 goto abort;
1762         }
1763         if (mddev->degraded > 2) {
1764                 printk(KERN_ERR "raid6: not enough operational devices for %s"
1765                        " (%d/%d failed)\n",
1766                        mdname(mddev), conf->failed_disks, conf->raid_disks);
1767                 goto abort;
1768         }
1769
1770 #if 0                           /* FIX: For now */
1771         if (mddev->degraded > 0 &&
1772             mddev->recovery_cp != MaxSector) {
1773                 printk(KERN_ERR "raid6: cannot start dirty degraded array for %s\n", mdname(mddev));
1774                 goto abort;
1775         }
1776 #endif
1777
1778         {
1779                 mddev->thread = md_register_thread(raid6d, mddev, "%s_raid6");
1780                 if (!mddev->thread) {
1781                         printk(KERN_ERR
1782                                "raid6: couldn't allocate thread for %s\n",
1783                                mdname(mddev));
1784                         goto abort;
1785                 }
1786         }
1787
1788         memory = conf->max_nr_stripes * (sizeof(struct stripe_head) +
1789                  conf->raid_disks * ((sizeof(struct bio) + PAGE_SIZE))) / 1024;
1790         if (grow_stripes(conf, conf->max_nr_stripes)) {
1791                 printk(KERN_ERR
1792                        "raid6: couldn't allocate %dkB for buffers\n", memory);
1793                 shrink_stripes(conf);
1794                 md_unregister_thread(mddev->thread);
1795                 goto abort;
1796         } else
1797                 printk(KERN_INFO "raid6: allocated %dkB for %s\n",
1798                        memory, mdname(mddev));
1799
1800         if (mddev->degraded == 0)
1801                 printk(KERN_INFO "raid6: raid level %d set %s active with %d out of %d"
1802                        " devices, algorithm %d\n", conf->level, mdname(mddev),
1803                        mddev->raid_disks-mddev->degraded, mddev->raid_disks,
1804                        conf->algorithm);
1805         else
1806                 printk(KERN_ALERT "raid6: raid level %d set %s active with %d"
1807                        " out of %d devices, algorithm %d\n", conf->level,
1808                        mdname(mddev), mddev->raid_disks - mddev->degraded,
1809                        mddev->raid_disks, conf->algorithm);
1810
1811         print_raid6_conf(conf);
1812
1813         /* read-ahead size must cover two whole stripes, which is
1814          * 2 * (n-2) * chunksize where 'n' is the number of raid devices
1815          */
1816         {
1817                 int stripe = (mddev->raid_disks-2) * mddev->chunk_size
1818                         / PAGE_CACHE_SIZE;
1819                 if (mddev->queue->backing_dev_info.ra_pages < 2 * stripe)
1820                         mddev->queue->backing_dev_info.ra_pages = 2 * stripe;
1821         }
1822
1823         /* Ok, everything is just fine now */
1824         mddev->array_size =  mddev->size * (mddev->raid_disks - 2);
1825         return 0;
1826 abort:
1827         if (conf) {
1828                 print_raid6_conf(conf);
1829                 if (conf->stripe_hashtbl)
1830                         free_pages((unsigned long) conf->stripe_hashtbl,
1831                                                         HASH_PAGES_ORDER);
1832                 kfree(conf);
1833         }
1834         mddev->private = NULL;
1835         printk(KERN_ALERT "raid6: failed to run raid set %s\n", mdname(mddev));
1836         return -EIO;
1837 }
1838
1839
1840
1841 static int stop (mddev_t *mddev)
1842 {
1843         raid6_conf_t *conf = (raid6_conf_t *) mddev->private;
1844
1845         md_unregister_thread(mddev->thread);
1846         mddev->thread = NULL;
1847         shrink_stripes(conf);
1848         free_pages((unsigned long) conf->stripe_hashtbl, HASH_PAGES_ORDER);
1849         kfree(conf);
1850         mddev->private = NULL;
1851         return 0;
1852 }
1853
1854 #if RAID6_DUMPSTATE
1855 static void print_sh (struct seq_file *seq, struct stripe_head *sh)
1856 {
1857         int i;
1858
1859         seq_printf(seq, "sh %llu, pd_idx %d, state %ld.\n",
1860                    (unsigned long long)sh->sector, sh->pd_idx, sh->state);
1861         seq_printf(seq, "sh %llu,  count %d.\n",
1862                    (unsigned long long)sh->sector, atomic_read(&sh->count));
1863         seq_printf(seq, "sh %llu, ", (unsigned long long)sh->sector);
1864         for (i = 0; i < sh->raid_conf->raid_disks; i++) {
1865                 seq_printf(seq, "(cache%d: %p %ld) ",
1866                            i, sh->dev[i].page, sh->dev[i].flags);
1867         }
1868         seq_printf(seq, "\n");
1869 }
1870
1871 static void printall (struct seq_file *seq, raid6_conf_t *conf)
1872 {
1873         struct stripe_head *sh;
1874         int i;
1875
1876         spin_lock_irq(&conf->device_lock);
1877         for (i = 0; i < NR_HASH; i++) {
1878                 sh = conf->stripe_hashtbl[i];
1879                 for (; sh; sh = sh->hash_next) {
1880                         if (sh->raid_conf != conf)
1881                                 continue;
1882                         print_sh(seq, sh);
1883                 }
1884         }
1885         spin_unlock_irq(&conf->device_lock);
1886 }
1887 #endif
1888
1889 static void status (struct seq_file *seq, mddev_t *mddev)
1890 {
1891         raid6_conf_t *conf = (raid6_conf_t *) mddev->private;
1892         int i;
1893
1894         seq_printf (seq, " level %d, %dk chunk, algorithm %d", mddev->level, mddev->chunk_size >> 10, mddev->layout);
1895         seq_printf (seq, " [%d/%d] [", conf->raid_disks, conf->working_disks);
1896         for (i = 0; i < conf->raid_disks; i++)
1897                 seq_printf (seq, "%s",
1898                             conf->disks[i].rdev &&
1899                             conf->disks[i].rdev->in_sync ? "U" : "_");
1900         seq_printf (seq, "]");
1901 #if RAID6_DUMPSTATE
1902         seq_printf (seq, "\n");
1903         printall(seq, conf);
1904 #endif
1905 }
1906
1907 static void print_raid6_conf (raid6_conf_t *conf)
1908 {
1909         int i;
1910         struct disk_info *tmp;
1911
1912         printk("RAID6 conf printout:\n");
1913         if (!conf) {
1914                 printk("(conf==NULL)\n");
1915                 return;
1916         }
1917         printk(" --- rd:%d wd:%d fd:%d\n", conf->raid_disks,
1918                  conf->working_disks, conf->failed_disks);
1919
1920         for (i = 0; i < conf->raid_disks; i++) {
1921                 char b[BDEVNAME_SIZE];
1922                 tmp = conf->disks + i;
1923                 if (tmp->rdev)
1924                 printk(" disk %d, o:%d, dev:%s\n",
1925                         i, !tmp->rdev->faulty,
1926                         bdevname(tmp->rdev->bdev,b));
1927         }
1928 }
1929
1930 static int raid6_spare_active(mddev_t *mddev)
1931 {
1932         int i;
1933         raid6_conf_t *conf = mddev->private;
1934         struct disk_info *tmp;
1935
1936         spin_lock_irq(&conf->device_lock);
1937         for (i = 0; i < conf->raid_disks; i++) {
1938                 tmp = conf->disks + i;
1939                 if (tmp->rdev
1940                     && !tmp->rdev->faulty
1941                     && !tmp->rdev->in_sync) {
1942                         mddev->degraded--;
1943                         conf->failed_disks--;
1944                         conf->working_disks++;
1945                         tmp->rdev->in_sync = 1;
1946                 }
1947         }
1948         spin_unlock_irq(&conf->device_lock);
1949         print_raid6_conf(conf);
1950         return 0;
1951 }
1952
1953 static int raid6_remove_disk(mddev_t *mddev, int number)
1954 {
1955         raid6_conf_t *conf = mddev->private;
1956         int err = 1;
1957         struct disk_info *p = conf->disks + number;
1958
1959         print_raid6_conf(conf);
1960         spin_lock_irq(&conf->device_lock);
1961
1962         if (p->rdev) {
1963                 if (p->rdev->in_sync ||
1964                     atomic_read(&p->rdev->nr_pending)) {
1965                         err = -EBUSY;
1966                         goto abort;
1967                 }
1968                 p->rdev = NULL;
1969                 err = 0;
1970         }
1971         if (err)
1972                 MD_BUG();
1973 abort:
1974         spin_unlock_irq(&conf->device_lock);
1975         print_raid6_conf(conf);
1976         return err;
1977 }
1978
1979 static int raid6_add_disk(mddev_t *mddev, mdk_rdev_t *rdev)
1980 {
1981         raid6_conf_t *conf = mddev->private;
1982         int found = 0;
1983         int disk;
1984         struct disk_info *p;
1985
1986         spin_lock_irq(&conf->device_lock);
1987         /*
1988          * find the disk ...
1989          */
1990         for (disk=0; disk < mddev->raid_disks; disk++)
1991                 if ((p=conf->disks + disk)->rdev == NULL) {
1992                         p->rdev = rdev;
1993                         rdev->in_sync = 0;
1994                         rdev->raid_disk = disk;
1995                         found = 1;
1996                         break;
1997                 }
1998         spin_unlock_irq(&conf->device_lock);
1999         print_raid6_conf(conf);
2000         return found;
2001 }
2002
2003 static int raid6_resize(mddev_t *mddev, sector_t sectors)
2004 {
2005         /* no resync is happening, and there is enough space
2006          * on all devices, so we can resize.
2007          * We need to make sure resync covers any new space.
2008          * If the array is shrinking we should possibly wait until
2009          * any io in the removed space completes, but it hardly seems
2010          * worth it.
2011          */
2012         sectors &= ~((sector_t)mddev->chunk_size/512 - 1);
2013         mddev->array_size = (sectors * (mddev->raid_disks-2))>>1;
2014         set_capacity(mddev->gendisk, mddev->array_size << 1);
2015         mddev->changed = 1;
2016         if (sectors/2  > mddev->size && mddev->recovery_cp == MaxSector) {
2017                 mddev->recovery_cp = mddev->size << 1;
2018                 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
2019         }
2020         mddev->size = sectors /2;
2021         return 0;
2022 }
2023
2024 static mdk_personality_t raid6_personality=
2025 {
2026         .name           = "raid6",
2027         .owner          = THIS_MODULE,
2028         .make_request   = make_request,
2029         .run            = run,
2030         .stop           = stop,
2031         .status         = status,
2032         .error_handler  = error,
2033         .hot_add_disk   = raid6_add_disk,
2034         .hot_remove_disk= raid6_remove_disk,
2035         .spare_active   = raid6_spare_active,
2036         .sync_request   = sync_request,
2037         .resize         = raid6_resize,
2038 };
2039
2040 static int __init raid6_init (void)
2041 {
2042         int e;
2043
2044         e = raid6_select_algo();
2045         if ( e )
2046                 return e;
2047
2048         return register_md_personality (RAID6, &raid6_personality);
2049 }
2050
2051 static void raid6_exit (void)
2052 {
2053         unregister_md_personality (RAID6);
2054 }
2055
2056 module_init(raid6_init);
2057 module_exit(raid6_exit);
2058 MODULE_LICENSE("GPL");
2059 MODULE_ALIAS("md-personality-8"); /* RAID6 */