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