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