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