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