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