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