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