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