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