]> git.openfabrics.org - ~shefty/rdma-dev.git/blob - drivers/md/raid5.c
Merge git://git.kernel.org/pub/scm/linux/kernel/git/pkl/squashfs-next
[~shefty/rdma-dev.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->seq_write is the number of the last batch successfully written.
31  * conf->seq_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 seq_flush+1.
36  * When we are ready to do a write, if that batch hasn't been written yet,
37  *   we plug the array and queue the stripe for later.
38  * When an unplug happens, we increment bm_flush, thus closing the current
39  *   batch.
40  * When we notice that bm_flush > bm_write, we write out all pending updates
41  * to the bitmap, and advance bm_write to where bm_flush was.
42  * This may occasionally write a bit out twice, but is sure never to
43  * miss any bits.
44  */
45
46 #include <linux/blkdev.h>
47 #include <linux/kthread.h>
48 #include <linux/raid/pq.h>
49 #include <linux/async_tx.h>
50 #include <linux/async.h>
51 #include <linux/seq_file.h>
52 #include <linux/cpu.h>
53 #include <linux/slab.h>
54 #include <linux/ratelimit.h>
55 #include "md.h"
56 #include "raid5.h"
57 #include "raid0.h"
58 #include "bitmap.h"
59
60 /*
61  * Stripe cache
62  */
63
64 #define NR_STRIPES              256
65 #define STRIPE_SIZE             PAGE_SIZE
66 #define STRIPE_SHIFT            (PAGE_SHIFT - 9)
67 #define STRIPE_SECTORS          (STRIPE_SIZE>>9)
68 #define IO_THRESHOLD            1
69 #define BYPASS_THRESHOLD        1
70 #define NR_HASH                 (PAGE_SIZE / sizeof(struct hlist_head))
71 #define HASH_MASK               (NR_HASH - 1)
72
73 static inline struct hlist_head *stripe_hash(struct r5conf *conf, sector_t sect)
74 {
75         int hash = (sect >> STRIPE_SHIFT) & HASH_MASK;
76         return &conf->stripe_hashtbl[hash];
77 }
78
79 /* bio's attached to a stripe+device for I/O are linked together in bi_sector
80  * order without overlap.  There may be several bio's per stripe+device, and
81  * a bio could span several devices.
82  * When walking this list for a particular stripe+device, we must never proceed
83  * beyond a bio that extends past this device, as the next bio might no longer
84  * be valid.
85  * This function is used to determine the 'next' bio in the list, given the sector
86  * of the current stripe+device
87  */
88 static inline struct bio *r5_next_bio(struct bio *bio, sector_t sector)
89 {
90         int sectors = bio->bi_size >> 9;
91         if (bio->bi_sector + sectors < sector + STRIPE_SECTORS)
92                 return bio->bi_next;
93         else
94                 return NULL;
95 }
96
97 /*
98  * We maintain a biased count of active stripes in the bottom 16 bits of
99  * bi_phys_segments, and a count of processed stripes in the upper 16 bits
100  */
101 static inline int raid5_bi_phys_segments(struct bio *bio)
102 {
103         return bio->bi_phys_segments & 0xffff;
104 }
105
106 static inline int raid5_bi_hw_segments(struct bio *bio)
107 {
108         return (bio->bi_phys_segments >> 16) & 0xffff;
109 }
110
111 static inline int raid5_dec_bi_phys_segments(struct bio *bio)
112 {
113         --bio->bi_phys_segments;
114         return raid5_bi_phys_segments(bio);
115 }
116
117 static inline int raid5_dec_bi_hw_segments(struct bio *bio)
118 {
119         unsigned short val = raid5_bi_hw_segments(bio);
120
121         --val;
122         bio->bi_phys_segments = (val << 16) | raid5_bi_phys_segments(bio);
123         return val;
124 }
125
126 static inline void raid5_set_bi_hw_segments(struct bio *bio, unsigned int cnt)
127 {
128         bio->bi_phys_segments = raid5_bi_phys_segments(bio) | (cnt << 16);
129 }
130
131 /* Find first data disk in a raid6 stripe */
132 static inline int raid6_d0(struct stripe_head *sh)
133 {
134         if (sh->ddf_layout)
135                 /* ddf always start from first device */
136                 return 0;
137         /* md starts just after Q block */
138         if (sh->qd_idx == sh->disks - 1)
139                 return 0;
140         else
141                 return sh->qd_idx + 1;
142 }
143 static inline int raid6_next_disk(int disk, int raid_disks)
144 {
145         disk++;
146         return (disk < raid_disks) ? disk : 0;
147 }
148
149 /* When walking through the disks in a raid5, starting at raid6_d0,
150  * We need to map each disk to a 'slot', where the data disks are slot
151  * 0 .. raid_disks-3, the parity disk is raid_disks-2 and the Q disk
152  * is raid_disks-1.  This help does that mapping.
153  */
154 static int raid6_idx_to_slot(int idx, struct stripe_head *sh,
155                              int *count, int syndrome_disks)
156 {
157         int slot = *count;
158
159         if (sh->ddf_layout)
160                 (*count)++;
161         if (idx == sh->pd_idx)
162                 return syndrome_disks;
163         if (idx == sh->qd_idx)
164                 return syndrome_disks + 1;
165         if (!sh->ddf_layout)
166                 (*count)++;
167         return slot;
168 }
169
170 static void return_io(struct bio *return_bi)
171 {
172         struct bio *bi = return_bi;
173         while (bi) {
174
175                 return_bi = bi->bi_next;
176                 bi->bi_next = NULL;
177                 bi->bi_size = 0;
178                 bio_endio(bi, 0);
179                 bi = return_bi;
180         }
181 }
182
183 static void print_raid5_conf (struct r5conf *conf);
184
185 static int stripe_operations_active(struct stripe_head *sh)
186 {
187         return sh->check_state || sh->reconstruct_state ||
188                test_bit(STRIPE_BIOFILL_RUN, &sh->state) ||
189                test_bit(STRIPE_COMPUTE_RUN, &sh->state);
190 }
191
192 static void __release_stripe(struct r5conf *conf, struct stripe_head *sh)
193 {
194         if (atomic_dec_and_test(&sh->count)) {
195                 BUG_ON(!list_empty(&sh->lru));
196                 BUG_ON(atomic_read(&conf->active_stripes)==0);
197                 if (test_bit(STRIPE_HANDLE, &sh->state)) {
198                         if (test_bit(STRIPE_DELAYED, &sh->state))
199                                 list_add_tail(&sh->lru, &conf->delayed_list);
200                         else if (test_bit(STRIPE_BIT_DELAY, &sh->state) &&
201                                    sh->bm_seq - conf->seq_write > 0)
202                                 list_add_tail(&sh->lru, &conf->bitmap_list);
203                         else {
204                                 clear_bit(STRIPE_BIT_DELAY, &sh->state);
205                                 list_add_tail(&sh->lru, &conf->handle_list);
206                         }
207                         md_wakeup_thread(conf->mddev->thread);
208                 } else {
209                         BUG_ON(stripe_operations_active(sh));
210                         if (test_and_clear_bit(STRIPE_PREREAD_ACTIVE, &sh->state)) {
211                                 atomic_dec(&conf->preread_active_stripes);
212                                 if (atomic_read(&conf->preread_active_stripes) < IO_THRESHOLD)
213                                         md_wakeup_thread(conf->mddev->thread);
214                         }
215                         atomic_dec(&conf->active_stripes);
216                         if (!test_bit(STRIPE_EXPANDING, &sh->state)) {
217                                 list_add_tail(&sh->lru, &conf->inactive_list);
218                                 wake_up(&conf->wait_for_stripe);
219                                 if (conf->retry_read_aligned)
220                                         md_wakeup_thread(conf->mddev->thread);
221                         }
222                 }
223         }
224 }
225
226 static void release_stripe(struct stripe_head *sh)
227 {
228         struct r5conf *conf = sh->raid_conf;
229         unsigned long flags;
230
231         spin_lock_irqsave(&conf->device_lock, flags);
232         __release_stripe(conf, sh);
233         spin_unlock_irqrestore(&conf->device_lock, flags);
234 }
235
236 static inline void remove_hash(struct stripe_head *sh)
237 {
238         pr_debug("remove_hash(), stripe %llu\n",
239                 (unsigned long long)sh->sector);
240
241         hlist_del_init(&sh->hash);
242 }
243
244 static inline void insert_hash(struct r5conf *conf, struct stripe_head *sh)
245 {
246         struct hlist_head *hp = stripe_hash(conf, sh->sector);
247
248         pr_debug("insert_hash(), stripe %llu\n",
249                 (unsigned long long)sh->sector);
250
251         hlist_add_head(&sh->hash, hp);
252 }
253
254
255 /* find an idle stripe, make sure it is unhashed, and return it. */
256 static struct stripe_head *get_free_stripe(struct r5conf *conf)
257 {
258         struct stripe_head *sh = NULL;
259         struct list_head *first;
260
261         if (list_empty(&conf->inactive_list))
262                 goto out;
263         first = conf->inactive_list.next;
264         sh = list_entry(first, struct stripe_head, lru);
265         list_del_init(first);
266         remove_hash(sh);
267         atomic_inc(&conf->active_stripes);
268 out:
269         return sh;
270 }
271
272 static void shrink_buffers(struct stripe_head *sh)
273 {
274         struct page *p;
275         int i;
276         int num = sh->raid_conf->pool_size;
277
278         for (i = 0; i < num ; i++) {
279                 p = sh->dev[i].page;
280                 if (!p)
281                         continue;
282                 sh->dev[i].page = NULL;
283                 put_page(p);
284         }
285 }
286
287 static int grow_buffers(struct stripe_head *sh)
288 {
289         int i;
290         int num = sh->raid_conf->pool_size;
291
292         for (i = 0; i < num; i++) {
293                 struct page *page;
294
295                 if (!(page = alloc_page(GFP_KERNEL))) {
296                         return 1;
297                 }
298                 sh->dev[i].page = page;
299         }
300         return 0;
301 }
302
303 static void raid5_build_block(struct stripe_head *sh, int i, int previous);
304 static void stripe_set_idx(sector_t stripe, struct r5conf *conf, int previous,
305                             struct stripe_head *sh);
306
307 static void init_stripe(struct stripe_head *sh, sector_t sector, int previous)
308 {
309         struct r5conf *conf = sh->raid_conf;
310         int i;
311
312         BUG_ON(atomic_read(&sh->count) != 0);
313         BUG_ON(test_bit(STRIPE_HANDLE, &sh->state));
314         BUG_ON(stripe_operations_active(sh));
315
316         pr_debug("init_stripe called, stripe %llu\n",
317                 (unsigned long long)sh->sector);
318
319         remove_hash(sh);
320
321         sh->generation = conf->generation - previous;
322         sh->disks = previous ? conf->previous_raid_disks : conf->raid_disks;
323         sh->sector = sector;
324         stripe_set_idx(sector, conf, previous, sh);
325         sh->state = 0;
326
327
328         for (i = sh->disks; i--; ) {
329                 struct r5dev *dev = &sh->dev[i];
330
331                 if (dev->toread || dev->read || dev->towrite || dev->written ||
332                     test_bit(R5_LOCKED, &dev->flags)) {
333                         printk(KERN_ERR "sector=%llx i=%d %p %p %p %p %d\n",
334                                (unsigned long long)sh->sector, i, dev->toread,
335                                dev->read, dev->towrite, dev->written,
336                                test_bit(R5_LOCKED, &dev->flags));
337                         WARN_ON(1);
338                 }
339                 dev->flags = 0;
340                 raid5_build_block(sh, i, previous);
341         }
342         insert_hash(conf, sh);
343 }
344
345 static struct stripe_head *__find_stripe(struct r5conf *conf, sector_t sector,
346                                          short generation)
347 {
348         struct stripe_head *sh;
349         struct hlist_node *hn;
350
351         pr_debug("__find_stripe, sector %llu\n", (unsigned long long)sector);
352         hlist_for_each_entry(sh, hn, stripe_hash(conf, sector), hash)
353                 if (sh->sector == sector && sh->generation == generation)
354                         return sh;
355         pr_debug("__stripe %llu not in cache\n", (unsigned long long)sector);
356         return NULL;
357 }
358
359 /*
360  * Need to check if array has failed when deciding whether to:
361  *  - start an array
362  *  - remove non-faulty devices
363  *  - add a spare
364  *  - allow a reshape
365  * This determination is simple when no reshape is happening.
366  * However if there is a reshape, we need to carefully check
367  * both the before and after sections.
368  * This is because some failed devices may only affect one
369  * of the two sections, and some non-in_sync devices may
370  * be insync in the section most affected by failed devices.
371  */
372 static int has_failed(struct r5conf *conf)
373 {
374         int degraded;
375         int i;
376         if (conf->mddev->reshape_position == MaxSector)
377                 return conf->mddev->degraded > conf->max_degraded;
378
379         rcu_read_lock();
380         degraded = 0;
381         for (i = 0; i < conf->previous_raid_disks; i++) {
382                 struct md_rdev *rdev = rcu_dereference(conf->disks[i].rdev);
383                 if (!rdev || test_bit(Faulty, &rdev->flags))
384                         degraded++;
385                 else if (test_bit(In_sync, &rdev->flags))
386                         ;
387                 else
388                         /* not in-sync or faulty.
389                          * If the reshape increases the number of devices,
390                          * this is being recovered by the reshape, so
391                          * this 'previous' section is not in_sync.
392                          * If the number of devices is being reduced however,
393                          * the device can only be part of the array if
394                          * we are reverting a reshape, so this section will
395                          * be in-sync.
396                          */
397                         if (conf->raid_disks >= conf->previous_raid_disks)
398                                 degraded++;
399         }
400         rcu_read_unlock();
401         if (degraded > conf->max_degraded)
402                 return 1;
403         rcu_read_lock();
404         degraded = 0;
405         for (i = 0; i < conf->raid_disks; i++) {
406                 struct md_rdev *rdev = rcu_dereference(conf->disks[i].rdev);
407                 if (!rdev || test_bit(Faulty, &rdev->flags))
408                         degraded++;
409                 else if (test_bit(In_sync, &rdev->flags))
410                         ;
411                 else
412                         /* not in-sync or faulty.
413                          * If reshape increases the number of devices, this
414                          * section has already been recovered, else it
415                          * almost certainly hasn't.
416                          */
417                         if (conf->raid_disks <= conf->previous_raid_disks)
418                                 degraded++;
419         }
420         rcu_read_unlock();
421         if (degraded > conf->max_degraded)
422                 return 1;
423         return 0;
424 }
425
426 static struct stripe_head *
427 get_active_stripe(struct r5conf *conf, sector_t sector,
428                   int previous, int noblock, int noquiesce)
429 {
430         struct stripe_head *sh;
431
432         pr_debug("get_stripe, sector %llu\n", (unsigned long long)sector);
433
434         spin_lock_irq(&conf->device_lock);
435
436         do {
437                 wait_event_lock_irq(conf->wait_for_stripe,
438                                     conf->quiesce == 0 || noquiesce,
439                                     conf->device_lock, /* nothing */);
440                 sh = __find_stripe(conf, sector, conf->generation - previous);
441                 if (!sh) {
442                         if (!conf->inactive_blocked)
443                                 sh = get_free_stripe(conf);
444                         if (noblock && sh == NULL)
445                                 break;
446                         if (!sh) {
447                                 conf->inactive_blocked = 1;
448                                 wait_event_lock_irq(conf->wait_for_stripe,
449                                                     !list_empty(&conf->inactive_list) &&
450                                                     (atomic_read(&conf->active_stripes)
451                                                      < (conf->max_nr_stripes *3/4)
452                                                      || !conf->inactive_blocked),
453                                                     conf->device_lock,
454                                                     );
455                                 conf->inactive_blocked = 0;
456                         } else
457                                 init_stripe(sh, sector, previous);
458                 } else {
459                         if (atomic_read(&sh->count)) {
460                                 BUG_ON(!list_empty(&sh->lru)
461                                     && !test_bit(STRIPE_EXPANDING, &sh->state));
462                         } else {
463                                 if (!test_bit(STRIPE_HANDLE, &sh->state))
464                                         atomic_inc(&conf->active_stripes);
465                                 if (list_empty(&sh->lru) &&
466                                     !test_bit(STRIPE_EXPANDING, &sh->state))
467                                         BUG();
468                                 list_del_init(&sh->lru);
469                         }
470                 }
471         } while (sh == NULL);
472
473         if (sh)
474                 atomic_inc(&sh->count);
475
476         spin_unlock_irq(&conf->device_lock);
477         return sh;
478 }
479
480 static void
481 raid5_end_read_request(struct bio *bi, int error);
482 static void
483 raid5_end_write_request(struct bio *bi, int error);
484
485 static void ops_run_io(struct stripe_head *sh, struct stripe_head_state *s)
486 {
487         struct r5conf *conf = sh->raid_conf;
488         int i, disks = sh->disks;
489
490         might_sleep();
491
492         for (i = disks; i--; ) {
493                 int rw;
494                 struct bio *bi;
495                 struct md_rdev *rdev;
496                 if (test_and_clear_bit(R5_Wantwrite, &sh->dev[i].flags)) {
497                         if (test_and_clear_bit(R5_WantFUA, &sh->dev[i].flags))
498                                 rw = WRITE_FUA;
499                         else
500                                 rw = WRITE;
501                 } else if (test_and_clear_bit(R5_Wantread, &sh->dev[i].flags))
502                         rw = READ;
503                 else
504                         continue;
505
506                 bi = &sh->dev[i].req;
507
508                 bi->bi_rw = rw;
509                 if (rw & WRITE)
510                         bi->bi_end_io = raid5_end_write_request;
511                 else
512                         bi->bi_end_io = raid5_end_read_request;
513
514                 rcu_read_lock();
515                 rdev = rcu_dereference(conf->disks[i].rdev);
516                 if (rdev && test_bit(Faulty, &rdev->flags))
517                         rdev = NULL;
518                 if (rdev)
519                         atomic_inc(&rdev->nr_pending);
520                 rcu_read_unlock();
521
522                 /* We have already checked bad blocks for reads.  Now
523                  * need to check for writes.
524                  */
525                 while ((rw & WRITE) && rdev &&
526                        test_bit(WriteErrorSeen, &rdev->flags)) {
527                         sector_t first_bad;
528                         int bad_sectors;
529                         int bad = is_badblock(rdev, sh->sector, STRIPE_SECTORS,
530                                               &first_bad, &bad_sectors);
531                         if (!bad)
532                                 break;
533
534                         if (bad < 0) {
535                                 set_bit(BlockedBadBlocks, &rdev->flags);
536                                 if (!conf->mddev->external &&
537                                     conf->mddev->flags) {
538                                         /* It is very unlikely, but we might
539                                          * still need to write out the
540                                          * bad block log - better give it
541                                          * a chance*/
542                                         md_check_recovery(conf->mddev);
543                                 }
544                                 md_wait_for_blocked_rdev(rdev, conf->mddev);
545                         } else {
546                                 /* Acknowledged bad block - skip the write */
547                                 rdev_dec_pending(rdev, conf->mddev);
548                                 rdev = NULL;
549                         }
550                 }
551
552                 if (rdev) {
553                         if (s->syncing || s->expanding || s->expanded)
554                                 md_sync_acct(rdev->bdev, STRIPE_SECTORS);
555
556                         set_bit(STRIPE_IO_STARTED, &sh->state);
557
558                         bi->bi_bdev = rdev->bdev;
559                         pr_debug("%s: for %llu schedule op %ld on disc %d\n",
560                                 __func__, (unsigned long long)sh->sector,
561                                 bi->bi_rw, i);
562                         atomic_inc(&sh->count);
563                         bi->bi_sector = sh->sector + rdev->data_offset;
564                         bi->bi_flags = 1 << BIO_UPTODATE;
565                         bi->bi_vcnt = 1;
566                         bi->bi_max_vecs = 1;
567                         bi->bi_idx = 0;
568                         bi->bi_io_vec = &sh->dev[i].vec;
569                         bi->bi_io_vec[0].bv_len = STRIPE_SIZE;
570                         bi->bi_io_vec[0].bv_offset = 0;
571                         bi->bi_size = STRIPE_SIZE;
572                         bi->bi_next = NULL;
573                         generic_make_request(bi);
574                 } else {
575                         if (rw & WRITE)
576                                 set_bit(STRIPE_DEGRADED, &sh->state);
577                         pr_debug("skip op %ld on disc %d for sector %llu\n",
578                                 bi->bi_rw, i, (unsigned long long)sh->sector);
579                         clear_bit(R5_LOCKED, &sh->dev[i].flags);
580                         set_bit(STRIPE_HANDLE, &sh->state);
581                 }
582         }
583 }
584
585 static struct dma_async_tx_descriptor *
586 async_copy_data(int frombio, struct bio *bio, struct page *page,
587         sector_t sector, struct dma_async_tx_descriptor *tx)
588 {
589         struct bio_vec *bvl;
590         struct page *bio_page;
591         int i;
592         int page_offset;
593         struct async_submit_ctl submit;
594         enum async_tx_flags flags = 0;
595
596         if (bio->bi_sector >= sector)
597                 page_offset = (signed)(bio->bi_sector - sector) * 512;
598         else
599                 page_offset = (signed)(sector - bio->bi_sector) * -512;
600
601         if (frombio)
602                 flags |= ASYNC_TX_FENCE;
603         init_async_submit(&submit, flags, tx, NULL, NULL, NULL);
604
605         bio_for_each_segment(bvl, bio, i) {
606                 int len = bvl->bv_len;
607                 int clen;
608                 int b_offset = 0;
609
610                 if (page_offset < 0) {
611                         b_offset = -page_offset;
612                         page_offset += b_offset;
613                         len -= b_offset;
614                 }
615
616                 if (len > 0 && page_offset + len > STRIPE_SIZE)
617                         clen = STRIPE_SIZE - page_offset;
618                 else
619                         clen = len;
620
621                 if (clen > 0) {
622                         b_offset += bvl->bv_offset;
623                         bio_page = bvl->bv_page;
624                         if (frombio)
625                                 tx = async_memcpy(page, bio_page, page_offset,
626                                                   b_offset, clen, &submit);
627                         else
628                                 tx = async_memcpy(bio_page, page, b_offset,
629                                                   page_offset, clen, &submit);
630                 }
631                 /* chain the operations */
632                 submit.depend_tx = tx;
633
634                 if (clen < len) /* hit end of page */
635                         break;
636                 page_offset +=  len;
637         }
638
639         return tx;
640 }
641
642 static void ops_complete_biofill(void *stripe_head_ref)
643 {
644         struct stripe_head *sh = stripe_head_ref;
645         struct bio *return_bi = NULL;
646         struct r5conf *conf = sh->raid_conf;
647         int i;
648
649         pr_debug("%s: stripe %llu\n", __func__,
650                 (unsigned long long)sh->sector);
651
652         /* clear completed biofills */
653         spin_lock_irq(&conf->device_lock);
654         for (i = sh->disks; i--; ) {
655                 struct r5dev *dev = &sh->dev[i];
656
657                 /* acknowledge completion of a biofill operation */
658                 /* and check if we need to reply to a read request,
659                  * new R5_Wantfill requests are held off until
660                  * !STRIPE_BIOFILL_RUN
661                  */
662                 if (test_and_clear_bit(R5_Wantfill, &dev->flags)) {
663                         struct bio *rbi, *rbi2;
664
665                         BUG_ON(!dev->read);
666                         rbi = dev->read;
667                         dev->read = NULL;
668                         while (rbi && rbi->bi_sector <
669                                 dev->sector + STRIPE_SECTORS) {
670                                 rbi2 = r5_next_bio(rbi, dev->sector);
671                                 if (!raid5_dec_bi_phys_segments(rbi)) {
672                                         rbi->bi_next = return_bi;
673                                         return_bi = rbi;
674                                 }
675                                 rbi = rbi2;
676                         }
677                 }
678         }
679         spin_unlock_irq(&conf->device_lock);
680         clear_bit(STRIPE_BIOFILL_RUN, &sh->state);
681
682         return_io(return_bi);
683
684         set_bit(STRIPE_HANDLE, &sh->state);
685         release_stripe(sh);
686 }
687
688 static void ops_run_biofill(struct stripe_head *sh)
689 {
690         struct dma_async_tx_descriptor *tx = NULL;
691         struct r5conf *conf = sh->raid_conf;
692         struct async_submit_ctl submit;
693         int i;
694
695         pr_debug("%s: stripe %llu\n", __func__,
696                 (unsigned long long)sh->sector);
697
698         for (i = sh->disks; i--; ) {
699                 struct r5dev *dev = &sh->dev[i];
700                 if (test_bit(R5_Wantfill, &dev->flags)) {
701                         struct bio *rbi;
702                         spin_lock_irq(&conf->device_lock);
703                         dev->read = rbi = dev->toread;
704                         dev->toread = NULL;
705                         spin_unlock_irq(&conf->device_lock);
706                         while (rbi && rbi->bi_sector <
707                                 dev->sector + STRIPE_SECTORS) {
708                                 tx = async_copy_data(0, rbi, dev->page,
709                                         dev->sector, tx);
710                                 rbi = r5_next_bio(rbi, dev->sector);
711                         }
712                 }
713         }
714
715         atomic_inc(&sh->count);
716         init_async_submit(&submit, ASYNC_TX_ACK, tx, ops_complete_biofill, sh, NULL);
717         async_trigger_callback(&submit);
718 }
719
720 static void mark_target_uptodate(struct stripe_head *sh, int target)
721 {
722         struct r5dev *tgt;
723
724         if (target < 0)
725                 return;
726
727         tgt = &sh->dev[target];
728         set_bit(R5_UPTODATE, &tgt->flags);
729         BUG_ON(!test_bit(R5_Wantcompute, &tgt->flags));
730         clear_bit(R5_Wantcompute, &tgt->flags);
731 }
732
733 static void ops_complete_compute(void *stripe_head_ref)
734 {
735         struct stripe_head *sh = stripe_head_ref;
736
737         pr_debug("%s: stripe %llu\n", __func__,
738                 (unsigned long long)sh->sector);
739
740         /* mark the computed target(s) as uptodate */
741         mark_target_uptodate(sh, sh->ops.target);
742         mark_target_uptodate(sh, sh->ops.target2);
743
744         clear_bit(STRIPE_COMPUTE_RUN, &sh->state);
745         if (sh->check_state == check_state_compute_run)
746                 sh->check_state = check_state_compute_result;
747         set_bit(STRIPE_HANDLE, &sh->state);
748         release_stripe(sh);
749 }
750
751 /* return a pointer to the address conversion region of the scribble buffer */
752 static addr_conv_t *to_addr_conv(struct stripe_head *sh,
753                                  struct raid5_percpu *percpu)
754 {
755         return percpu->scribble + sizeof(struct page *) * (sh->disks + 2);
756 }
757
758 static struct dma_async_tx_descriptor *
759 ops_run_compute5(struct stripe_head *sh, struct raid5_percpu *percpu)
760 {
761         int disks = sh->disks;
762         struct page **xor_srcs = percpu->scribble;
763         int target = sh->ops.target;
764         struct r5dev *tgt = &sh->dev[target];
765         struct page *xor_dest = tgt->page;
766         int count = 0;
767         struct dma_async_tx_descriptor *tx;
768         struct async_submit_ctl submit;
769         int i;
770
771         pr_debug("%s: stripe %llu block: %d\n",
772                 __func__, (unsigned long long)sh->sector, target);
773         BUG_ON(!test_bit(R5_Wantcompute, &tgt->flags));
774
775         for (i = disks; i--; )
776                 if (i != target)
777                         xor_srcs[count++] = sh->dev[i].page;
778
779         atomic_inc(&sh->count);
780
781         init_async_submit(&submit, ASYNC_TX_FENCE|ASYNC_TX_XOR_ZERO_DST, NULL,
782                           ops_complete_compute, sh, to_addr_conv(sh, percpu));
783         if (unlikely(count == 1))
784                 tx = async_memcpy(xor_dest, xor_srcs[0], 0, 0, STRIPE_SIZE, &submit);
785         else
786                 tx = async_xor(xor_dest, xor_srcs, 0, count, STRIPE_SIZE, &submit);
787
788         return tx;
789 }
790
791 /* set_syndrome_sources - populate source buffers for gen_syndrome
792  * @srcs - (struct page *) array of size sh->disks
793  * @sh - stripe_head to parse
794  *
795  * Populates srcs in proper layout order for the stripe and returns the
796  * 'count' of sources to be used in a call to async_gen_syndrome.  The P
797  * destination buffer is recorded in srcs[count] and the Q destination
798  * is recorded in srcs[count+1]].
799  */
800 static int set_syndrome_sources(struct page **srcs, struct stripe_head *sh)
801 {
802         int disks = sh->disks;
803         int syndrome_disks = sh->ddf_layout ? disks : (disks - 2);
804         int d0_idx = raid6_d0(sh);
805         int count;
806         int i;
807
808         for (i = 0; i < disks; i++)
809                 srcs[i] = NULL;
810
811         count = 0;
812         i = d0_idx;
813         do {
814                 int slot = raid6_idx_to_slot(i, sh, &count, syndrome_disks);
815
816                 srcs[slot] = sh->dev[i].page;
817                 i = raid6_next_disk(i, disks);
818         } while (i != d0_idx);
819
820         return syndrome_disks;
821 }
822
823 static struct dma_async_tx_descriptor *
824 ops_run_compute6_1(struct stripe_head *sh, struct raid5_percpu *percpu)
825 {
826         int disks = sh->disks;
827         struct page **blocks = percpu->scribble;
828         int target;
829         int qd_idx = sh->qd_idx;
830         struct dma_async_tx_descriptor *tx;
831         struct async_submit_ctl submit;
832         struct r5dev *tgt;
833         struct page *dest;
834         int i;
835         int count;
836
837         if (sh->ops.target < 0)
838                 target = sh->ops.target2;
839         else if (sh->ops.target2 < 0)
840                 target = sh->ops.target;
841         else
842                 /* we should only have one valid target */
843                 BUG();
844         BUG_ON(target < 0);
845         pr_debug("%s: stripe %llu block: %d\n",
846                 __func__, (unsigned long long)sh->sector, target);
847
848         tgt = &sh->dev[target];
849         BUG_ON(!test_bit(R5_Wantcompute, &tgt->flags));
850         dest = tgt->page;
851
852         atomic_inc(&sh->count);
853
854         if (target == qd_idx) {
855                 count = set_syndrome_sources(blocks, sh);
856                 blocks[count] = NULL; /* regenerating p is not necessary */
857                 BUG_ON(blocks[count+1] != dest); /* q should already be set */
858                 init_async_submit(&submit, ASYNC_TX_FENCE, NULL,
859                                   ops_complete_compute, sh,
860                                   to_addr_conv(sh, percpu));
861                 tx = async_gen_syndrome(blocks, 0, count+2, STRIPE_SIZE, &submit);
862         } else {
863                 /* Compute any data- or p-drive using XOR */
864                 count = 0;
865                 for (i = disks; i-- ; ) {
866                         if (i == target || i == qd_idx)
867                                 continue;
868                         blocks[count++] = sh->dev[i].page;
869                 }
870
871                 init_async_submit(&submit, ASYNC_TX_FENCE|ASYNC_TX_XOR_ZERO_DST,
872                                   NULL, ops_complete_compute, sh,
873                                   to_addr_conv(sh, percpu));
874                 tx = async_xor(dest, blocks, 0, count, STRIPE_SIZE, &submit);
875         }
876
877         return tx;
878 }
879
880 static struct dma_async_tx_descriptor *
881 ops_run_compute6_2(struct stripe_head *sh, struct raid5_percpu *percpu)
882 {
883         int i, count, disks = sh->disks;
884         int syndrome_disks = sh->ddf_layout ? disks : disks-2;
885         int d0_idx = raid6_d0(sh);
886         int faila = -1, failb = -1;
887         int target = sh->ops.target;
888         int target2 = sh->ops.target2;
889         struct r5dev *tgt = &sh->dev[target];
890         struct r5dev *tgt2 = &sh->dev[target2];
891         struct dma_async_tx_descriptor *tx;
892         struct page **blocks = percpu->scribble;
893         struct async_submit_ctl submit;
894
895         pr_debug("%s: stripe %llu block1: %d block2: %d\n",
896                  __func__, (unsigned long long)sh->sector, target, target2);
897         BUG_ON(target < 0 || target2 < 0);
898         BUG_ON(!test_bit(R5_Wantcompute, &tgt->flags));
899         BUG_ON(!test_bit(R5_Wantcompute, &tgt2->flags));
900
901         /* we need to open-code set_syndrome_sources to handle the
902          * slot number conversion for 'faila' and 'failb'
903          */
904         for (i = 0; i < disks ; i++)
905                 blocks[i] = NULL;
906         count = 0;
907         i = d0_idx;
908         do {
909                 int slot = raid6_idx_to_slot(i, sh, &count, syndrome_disks);
910
911                 blocks[slot] = sh->dev[i].page;
912
913                 if (i == target)
914                         faila = slot;
915                 if (i == target2)
916                         failb = slot;
917                 i = raid6_next_disk(i, disks);
918         } while (i != d0_idx);
919
920         BUG_ON(faila == failb);
921         if (failb < faila)
922                 swap(faila, failb);
923         pr_debug("%s: stripe: %llu faila: %d failb: %d\n",
924                  __func__, (unsigned long long)sh->sector, faila, failb);
925
926         atomic_inc(&sh->count);
927
928         if (failb == syndrome_disks+1) {
929                 /* Q disk is one of the missing disks */
930                 if (faila == syndrome_disks) {
931                         /* Missing P+Q, just recompute */
932                         init_async_submit(&submit, ASYNC_TX_FENCE, NULL,
933                                           ops_complete_compute, sh,
934                                           to_addr_conv(sh, percpu));
935                         return async_gen_syndrome(blocks, 0, syndrome_disks+2,
936                                                   STRIPE_SIZE, &submit);
937                 } else {
938                         struct page *dest;
939                         int data_target;
940                         int qd_idx = sh->qd_idx;
941
942                         /* Missing D+Q: recompute D from P, then recompute Q */
943                         if (target == qd_idx)
944                                 data_target = target2;
945                         else
946                                 data_target = target;
947
948                         count = 0;
949                         for (i = disks; i-- ; ) {
950                                 if (i == data_target || i == qd_idx)
951                                         continue;
952                                 blocks[count++] = sh->dev[i].page;
953                         }
954                         dest = sh->dev[data_target].page;
955                         init_async_submit(&submit,
956                                           ASYNC_TX_FENCE|ASYNC_TX_XOR_ZERO_DST,
957                                           NULL, NULL, NULL,
958                                           to_addr_conv(sh, percpu));
959                         tx = async_xor(dest, blocks, 0, count, STRIPE_SIZE,
960                                        &submit);
961
962                         count = set_syndrome_sources(blocks, sh);
963                         init_async_submit(&submit, ASYNC_TX_FENCE, tx,
964                                           ops_complete_compute, sh,
965                                           to_addr_conv(sh, percpu));
966                         return async_gen_syndrome(blocks, 0, count+2,
967                                                   STRIPE_SIZE, &submit);
968                 }
969         } else {
970                 init_async_submit(&submit, ASYNC_TX_FENCE, NULL,
971                                   ops_complete_compute, sh,
972                                   to_addr_conv(sh, percpu));
973                 if (failb == syndrome_disks) {
974                         /* We're missing D+P. */
975                         return async_raid6_datap_recov(syndrome_disks+2,
976                                                        STRIPE_SIZE, faila,
977                                                        blocks, &submit);
978                 } else {
979                         /* We're missing D+D. */
980                         return async_raid6_2data_recov(syndrome_disks+2,
981                                                        STRIPE_SIZE, faila, failb,
982                                                        blocks, &submit);
983                 }
984         }
985 }
986
987
988 static void ops_complete_prexor(void *stripe_head_ref)
989 {
990         struct stripe_head *sh = stripe_head_ref;
991
992         pr_debug("%s: stripe %llu\n", __func__,
993                 (unsigned long long)sh->sector);
994 }
995
996 static struct dma_async_tx_descriptor *
997 ops_run_prexor(struct stripe_head *sh, struct raid5_percpu *percpu,
998                struct dma_async_tx_descriptor *tx)
999 {
1000         int disks = sh->disks;
1001         struct page **xor_srcs = percpu->scribble;
1002         int count = 0, pd_idx = sh->pd_idx, i;
1003         struct async_submit_ctl submit;
1004
1005         /* existing parity data subtracted */
1006         struct page *xor_dest = xor_srcs[count++] = sh->dev[pd_idx].page;
1007
1008         pr_debug("%s: stripe %llu\n", __func__,
1009                 (unsigned long long)sh->sector);
1010
1011         for (i = disks; i--; ) {
1012                 struct r5dev *dev = &sh->dev[i];
1013                 /* Only process blocks that are known to be uptodate */
1014                 if (test_bit(R5_Wantdrain, &dev->flags))
1015                         xor_srcs[count++] = dev->page;
1016         }
1017
1018         init_async_submit(&submit, ASYNC_TX_FENCE|ASYNC_TX_XOR_DROP_DST, tx,
1019                           ops_complete_prexor, sh, to_addr_conv(sh, percpu));
1020         tx = async_xor(xor_dest, xor_srcs, 0, count, STRIPE_SIZE, &submit);
1021
1022         return tx;
1023 }
1024
1025 static struct dma_async_tx_descriptor *
1026 ops_run_biodrain(struct stripe_head *sh, struct dma_async_tx_descriptor *tx)
1027 {
1028         int disks = sh->disks;
1029         int i;
1030
1031         pr_debug("%s: stripe %llu\n", __func__,
1032                 (unsigned long long)sh->sector);
1033
1034         for (i = disks; i--; ) {
1035                 struct r5dev *dev = &sh->dev[i];
1036                 struct bio *chosen;
1037
1038                 if (test_and_clear_bit(R5_Wantdrain, &dev->flags)) {
1039                         struct bio *wbi;
1040
1041                         spin_lock_irq(&sh->raid_conf->device_lock);
1042                         chosen = dev->towrite;
1043                         dev->towrite = NULL;
1044                         BUG_ON(dev->written);
1045                         wbi = dev->written = chosen;
1046                         spin_unlock_irq(&sh->raid_conf->device_lock);
1047
1048                         while (wbi && wbi->bi_sector <
1049                                 dev->sector + STRIPE_SECTORS) {
1050                                 if (wbi->bi_rw & REQ_FUA)
1051                                         set_bit(R5_WantFUA, &dev->flags);
1052                                 tx = async_copy_data(1, wbi, dev->page,
1053                                         dev->sector, tx);
1054                                 wbi = r5_next_bio(wbi, dev->sector);
1055                         }
1056                 }
1057         }
1058
1059         return tx;
1060 }
1061
1062 static void ops_complete_reconstruct(void *stripe_head_ref)
1063 {
1064         struct stripe_head *sh = stripe_head_ref;
1065         int disks = sh->disks;
1066         int pd_idx = sh->pd_idx;
1067         int qd_idx = sh->qd_idx;
1068         int i;
1069         bool fua = false;
1070
1071         pr_debug("%s: stripe %llu\n", __func__,
1072                 (unsigned long long)sh->sector);
1073
1074         for (i = disks; i--; )
1075                 fua |= test_bit(R5_WantFUA, &sh->dev[i].flags);
1076
1077         for (i = disks; i--; ) {
1078                 struct r5dev *dev = &sh->dev[i];
1079
1080                 if (dev->written || i == pd_idx || i == qd_idx) {
1081                         set_bit(R5_UPTODATE, &dev->flags);
1082                         if (fua)
1083                                 set_bit(R5_WantFUA, &dev->flags);
1084                 }
1085         }
1086
1087         if (sh->reconstruct_state == reconstruct_state_drain_run)
1088                 sh->reconstruct_state = reconstruct_state_drain_result;
1089         else if (sh->reconstruct_state == reconstruct_state_prexor_drain_run)
1090                 sh->reconstruct_state = reconstruct_state_prexor_drain_result;
1091         else {
1092                 BUG_ON(sh->reconstruct_state != reconstruct_state_run);
1093                 sh->reconstruct_state = reconstruct_state_result;
1094         }
1095
1096         set_bit(STRIPE_HANDLE, &sh->state);
1097         release_stripe(sh);
1098 }
1099
1100 static void
1101 ops_run_reconstruct5(struct stripe_head *sh, struct raid5_percpu *percpu,
1102                      struct dma_async_tx_descriptor *tx)
1103 {
1104         int disks = sh->disks;
1105         struct page **xor_srcs = percpu->scribble;
1106         struct async_submit_ctl submit;
1107         int count = 0, pd_idx = sh->pd_idx, i;
1108         struct page *xor_dest;
1109         int prexor = 0;
1110         unsigned long flags;
1111
1112         pr_debug("%s: stripe %llu\n", __func__,
1113                 (unsigned long long)sh->sector);
1114
1115         /* check if prexor is active which means only process blocks
1116          * that are part of a read-modify-write (written)
1117          */
1118         if (sh->reconstruct_state == reconstruct_state_prexor_drain_run) {
1119                 prexor = 1;
1120                 xor_dest = xor_srcs[count++] = sh->dev[pd_idx].page;
1121                 for (i = disks; i--; ) {
1122                         struct r5dev *dev = &sh->dev[i];
1123                         if (dev->written)
1124                                 xor_srcs[count++] = dev->page;
1125                 }
1126         } else {
1127                 xor_dest = sh->dev[pd_idx].page;
1128                 for (i = disks; i--; ) {
1129                         struct r5dev *dev = &sh->dev[i];
1130                         if (i != pd_idx)
1131                                 xor_srcs[count++] = dev->page;
1132                 }
1133         }
1134
1135         /* 1/ if we prexor'd then the dest is reused as a source
1136          * 2/ if we did not prexor then we are redoing the parity
1137          * set ASYNC_TX_XOR_DROP_DST and ASYNC_TX_XOR_ZERO_DST
1138          * for the synchronous xor case
1139          */
1140         flags = ASYNC_TX_ACK |
1141                 (prexor ? ASYNC_TX_XOR_DROP_DST : ASYNC_TX_XOR_ZERO_DST);
1142
1143         atomic_inc(&sh->count);
1144
1145         init_async_submit(&submit, flags, tx, ops_complete_reconstruct, sh,
1146                           to_addr_conv(sh, percpu));
1147         if (unlikely(count == 1))
1148                 tx = async_memcpy(xor_dest, xor_srcs[0], 0, 0, STRIPE_SIZE, &submit);
1149         else
1150                 tx = async_xor(xor_dest, xor_srcs, 0, count, STRIPE_SIZE, &submit);
1151 }
1152
1153 static void
1154 ops_run_reconstruct6(struct stripe_head *sh, struct raid5_percpu *percpu,
1155                      struct dma_async_tx_descriptor *tx)
1156 {
1157         struct async_submit_ctl submit;
1158         struct page **blocks = percpu->scribble;
1159         int count;
1160
1161         pr_debug("%s: stripe %llu\n", __func__, (unsigned long long)sh->sector);
1162
1163         count = set_syndrome_sources(blocks, sh);
1164
1165         atomic_inc(&sh->count);
1166
1167         init_async_submit(&submit, ASYNC_TX_ACK, tx, ops_complete_reconstruct,
1168                           sh, to_addr_conv(sh, percpu));
1169         async_gen_syndrome(blocks, 0, count+2, STRIPE_SIZE,  &submit);
1170 }
1171
1172 static void ops_complete_check(void *stripe_head_ref)
1173 {
1174         struct stripe_head *sh = stripe_head_ref;
1175
1176         pr_debug("%s: stripe %llu\n", __func__,
1177                 (unsigned long long)sh->sector);
1178
1179         sh->check_state = check_state_check_result;
1180         set_bit(STRIPE_HANDLE, &sh->state);
1181         release_stripe(sh);
1182 }
1183
1184 static void ops_run_check_p(struct stripe_head *sh, struct raid5_percpu *percpu)
1185 {
1186         int disks = sh->disks;
1187         int pd_idx = sh->pd_idx;
1188         int qd_idx = sh->qd_idx;
1189         struct page *xor_dest;
1190         struct page **xor_srcs = percpu->scribble;
1191         struct dma_async_tx_descriptor *tx;
1192         struct async_submit_ctl submit;
1193         int count;
1194         int i;
1195
1196         pr_debug("%s: stripe %llu\n", __func__,
1197                 (unsigned long long)sh->sector);
1198
1199         count = 0;
1200         xor_dest = sh->dev[pd_idx].page;
1201         xor_srcs[count++] = xor_dest;
1202         for (i = disks; i--; ) {
1203                 if (i == pd_idx || i == qd_idx)
1204                         continue;
1205                 xor_srcs[count++] = sh->dev[i].page;
1206         }
1207
1208         init_async_submit(&submit, 0, NULL, NULL, NULL,
1209                           to_addr_conv(sh, percpu));
1210         tx = async_xor_val(xor_dest, xor_srcs, 0, count, STRIPE_SIZE,
1211                            &sh->ops.zero_sum_result, &submit);
1212
1213         atomic_inc(&sh->count);
1214         init_async_submit(&submit, ASYNC_TX_ACK, tx, ops_complete_check, sh, NULL);
1215         tx = async_trigger_callback(&submit);
1216 }
1217
1218 static void ops_run_check_pq(struct stripe_head *sh, struct raid5_percpu *percpu, int checkp)
1219 {
1220         struct page **srcs = percpu->scribble;
1221         struct async_submit_ctl submit;
1222         int count;
1223
1224         pr_debug("%s: stripe %llu checkp: %d\n", __func__,
1225                 (unsigned long long)sh->sector, checkp);
1226
1227         count = set_syndrome_sources(srcs, sh);
1228         if (!checkp)
1229                 srcs[count] = NULL;
1230
1231         atomic_inc(&sh->count);
1232         init_async_submit(&submit, ASYNC_TX_ACK, NULL, ops_complete_check,
1233                           sh, to_addr_conv(sh, percpu));
1234         async_syndrome_val(srcs, 0, count+2, STRIPE_SIZE,
1235                            &sh->ops.zero_sum_result, percpu->spare_page, &submit);
1236 }
1237
1238 static void __raid_run_ops(struct stripe_head *sh, unsigned long ops_request)
1239 {
1240         int overlap_clear = 0, i, disks = sh->disks;
1241         struct dma_async_tx_descriptor *tx = NULL;
1242         struct r5conf *conf = sh->raid_conf;
1243         int level = conf->level;
1244         struct raid5_percpu *percpu;
1245         unsigned long cpu;
1246
1247         cpu = get_cpu();
1248         percpu = per_cpu_ptr(conf->percpu, cpu);
1249         if (test_bit(STRIPE_OP_BIOFILL, &ops_request)) {
1250                 ops_run_biofill(sh);
1251                 overlap_clear++;
1252         }
1253
1254         if (test_bit(STRIPE_OP_COMPUTE_BLK, &ops_request)) {
1255                 if (level < 6)
1256                         tx = ops_run_compute5(sh, percpu);
1257                 else {
1258                         if (sh->ops.target2 < 0 || sh->ops.target < 0)
1259                                 tx = ops_run_compute6_1(sh, percpu);
1260                         else
1261                                 tx = ops_run_compute6_2(sh, percpu);
1262                 }
1263                 /* terminate the chain if reconstruct is not set to be run */
1264                 if (tx && !test_bit(STRIPE_OP_RECONSTRUCT, &ops_request))
1265                         async_tx_ack(tx);
1266         }
1267
1268         if (test_bit(STRIPE_OP_PREXOR, &ops_request))
1269                 tx = ops_run_prexor(sh, percpu, tx);
1270
1271         if (test_bit(STRIPE_OP_BIODRAIN, &ops_request)) {
1272                 tx = ops_run_biodrain(sh, tx);
1273                 overlap_clear++;
1274         }
1275
1276         if (test_bit(STRIPE_OP_RECONSTRUCT, &ops_request)) {
1277                 if (level < 6)
1278                         ops_run_reconstruct5(sh, percpu, tx);
1279                 else
1280                         ops_run_reconstruct6(sh, percpu, tx);
1281         }
1282
1283         if (test_bit(STRIPE_OP_CHECK, &ops_request)) {
1284                 if (sh->check_state == check_state_run)
1285                         ops_run_check_p(sh, percpu);
1286                 else if (sh->check_state == check_state_run_q)
1287                         ops_run_check_pq(sh, percpu, 0);
1288                 else if (sh->check_state == check_state_run_pq)
1289                         ops_run_check_pq(sh, percpu, 1);
1290                 else
1291                         BUG();
1292         }
1293
1294         if (overlap_clear)
1295                 for (i = disks; i--; ) {
1296                         struct r5dev *dev = &sh->dev[i];
1297                         if (test_and_clear_bit(R5_Overlap, &dev->flags))
1298                                 wake_up(&sh->raid_conf->wait_for_overlap);
1299                 }
1300         put_cpu();
1301 }
1302
1303 #ifdef CONFIG_MULTICORE_RAID456
1304 static void async_run_ops(void *param, async_cookie_t cookie)
1305 {
1306         struct stripe_head *sh = param;
1307         unsigned long ops_request = sh->ops.request;
1308
1309         clear_bit_unlock(STRIPE_OPS_REQ_PENDING, &sh->state);
1310         wake_up(&sh->ops.wait_for_ops);
1311
1312         __raid_run_ops(sh, ops_request);
1313         release_stripe(sh);
1314 }
1315
1316 static void raid_run_ops(struct stripe_head *sh, unsigned long ops_request)
1317 {
1318         /* since handle_stripe can be called outside of raid5d context
1319          * we need to ensure sh->ops.request is de-staged before another
1320          * request arrives
1321          */
1322         wait_event(sh->ops.wait_for_ops,
1323                    !test_and_set_bit_lock(STRIPE_OPS_REQ_PENDING, &sh->state));
1324         sh->ops.request = ops_request;
1325
1326         atomic_inc(&sh->count);
1327         async_schedule(async_run_ops, sh);
1328 }
1329 #else
1330 #define raid_run_ops __raid_run_ops
1331 #endif
1332
1333 static int grow_one_stripe(struct r5conf *conf)
1334 {
1335         struct stripe_head *sh;
1336         sh = kmem_cache_zalloc(conf->slab_cache, GFP_KERNEL);
1337         if (!sh)
1338                 return 0;
1339
1340         sh->raid_conf = conf;
1341         #ifdef CONFIG_MULTICORE_RAID456
1342         init_waitqueue_head(&sh->ops.wait_for_ops);
1343         #endif
1344
1345         if (grow_buffers(sh)) {
1346                 shrink_buffers(sh);
1347                 kmem_cache_free(conf->slab_cache, sh);
1348                 return 0;
1349         }
1350         /* we just created an active stripe so... */
1351         atomic_set(&sh->count, 1);
1352         atomic_inc(&conf->active_stripes);
1353         INIT_LIST_HEAD(&sh->lru);
1354         release_stripe(sh);
1355         return 1;
1356 }
1357
1358 static int grow_stripes(struct r5conf *conf, int num)
1359 {
1360         struct kmem_cache *sc;
1361         int devs = max(conf->raid_disks, conf->previous_raid_disks);
1362
1363         if (conf->mddev->gendisk)
1364                 sprintf(conf->cache_name[0],
1365                         "raid%d-%s", conf->level, mdname(conf->mddev));
1366         else
1367                 sprintf(conf->cache_name[0],
1368                         "raid%d-%p", conf->level, conf->mddev);
1369         sprintf(conf->cache_name[1], "%s-alt", conf->cache_name[0]);
1370
1371         conf->active_name = 0;
1372         sc = kmem_cache_create(conf->cache_name[conf->active_name],
1373                                sizeof(struct stripe_head)+(devs-1)*sizeof(struct r5dev),
1374                                0, 0, NULL);
1375         if (!sc)
1376                 return 1;
1377         conf->slab_cache = sc;
1378         conf->pool_size = devs;
1379         while (num--)
1380                 if (!grow_one_stripe(conf))
1381                         return 1;
1382         return 0;
1383 }
1384
1385 /**
1386  * scribble_len - return the required size of the scribble region
1387  * @num - total number of disks in the array
1388  *
1389  * The size must be enough to contain:
1390  * 1/ a struct page pointer for each device in the array +2
1391  * 2/ room to convert each entry in (1) to its corresponding dma
1392  *    (dma_map_page()) or page (page_address()) address.
1393  *
1394  * Note: the +2 is for the destination buffers of the ddf/raid6 case where we
1395  * calculate over all devices (not just the data blocks), using zeros in place
1396  * of the P and Q blocks.
1397  */
1398 static size_t scribble_len(int num)
1399 {
1400         size_t len;
1401
1402         len = sizeof(struct page *) * (num+2) + sizeof(addr_conv_t) * (num+2);
1403
1404         return len;
1405 }
1406
1407 static int resize_stripes(struct r5conf *conf, int newsize)
1408 {
1409         /* Make all the stripes able to hold 'newsize' devices.
1410          * New slots in each stripe get 'page' set to a new page.
1411          *
1412          * This happens in stages:
1413          * 1/ create a new kmem_cache and allocate the required number of
1414          *    stripe_heads.
1415          * 2/ gather all the old stripe_heads and tranfer the pages across
1416          *    to the new stripe_heads.  This will have the side effect of
1417          *    freezing the array as once all stripe_heads have been collected,
1418          *    no IO will be possible.  Old stripe heads are freed once their
1419          *    pages have been transferred over, and the old kmem_cache is
1420          *    freed when all stripes are done.
1421          * 3/ reallocate conf->disks to be suitable bigger.  If this fails,
1422          *    we simple return a failre status - no need to clean anything up.
1423          * 4/ allocate new pages for the new slots in the new stripe_heads.
1424          *    If this fails, we don't bother trying the shrink the
1425          *    stripe_heads down again, we just leave them as they are.
1426          *    As each stripe_head is processed the new one is released into
1427          *    active service.
1428          *
1429          * Once step2 is started, we cannot afford to wait for a write,
1430          * so we use GFP_NOIO allocations.
1431          */
1432         struct stripe_head *osh, *nsh;
1433         LIST_HEAD(newstripes);
1434         struct disk_info *ndisks;
1435         unsigned long cpu;
1436         int err;
1437         struct kmem_cache *sc;
1438         int i;
1439
1440         if (newsize <= conf->pool_size)
1441                 return 0; /* never bother to shrink */
1442
1443         err = md_allow_write(conf->mddev);
1444         if (err)
1445                 return err;
1446
1447         /* Step 1 */
1448         sc = kmem_cache_create(conf->cache_name[1-conf->active_name],
1449                                sizeof(struct stripe_head)+(newsize-1)*sizeof(struct r5dev),
1450                                0, 0, NULL);
1451         if (!sc)
1452                 return -ENOMEM;
1453
1454         for (i = conf->max_nr_stripes; i; i--) {
1455                 nsh = kmem_cache_zalloc(sc, GFP_KERNEL);
1456                 if (!nsh)
1457                         break;
1458
1459                 nsh->raid_conf = conf;
1460                 #ifdef CONFIG_MULTICORE_RAID456
1461                 init_waitqueue_head(&nsh->ops.wait_for_ops);
1462                 #endif
1463
1464                 list_add(&nsh->lru, &newstripes);
1465         }
1466         if (i) {
1467                 /* didn't get enough, give up */
1468                 while (!list_empty(&newstripes)) {
1469                         nsh = list_entry(newstripes.next, struct stripe_head, lru);
1470                         list_del(&nsh->lru);
1471                         kmem_cache_free(sc, nsh);
1472                 }
1473                 kmem_cache_destroy(sc);
1474                 return -ENOMEM;
1475         }
1476         /* Step 2 - Must use GFP_NOIO now.
1477          * OK, we have enough stripes, start collecting inactive
1478          * stripes and copying them over
1479          */
1480         list_for_each_entry(nsh, &newstripes, lru) {
1481                 spin_lock_irq(&conf->device_lock);
1482                 wait_event_lock_irq(conf->wait_for_stripe,
1483                                     !list_empty(&conf->inactive_list),
1484                                     conf->device_lock,
1485                                     );
1486                 osh = get_free_stripe(conf);
1487                 spin_unlock_irq(&conf->device_lock);
1488                 atomic_set(&nsh->count, 1);
1489                 for(i=0; i<conf->pool_size; i++)
1490                         nsh->dev[i].page = osh->dev[i].page;
1491                 for( ; i<newsize; i++)
1492                         nsh->dev[i].page = NULL;
1493                 kmem_cache_free(conf->slab_cache, osh);
1494         }
1495         kmem_cache_destroy(conf->slab_cache);
1496
1497         /* Step 3.
1498          * At this point, we are holding all the stripes so the array
1499          * is completely stalled, so now is a good time to resize
1500          * conf->disks and the scribble region
1501          */
1502         ndisks = kzalloc(newsize * sizeof(struct disk_info), GFP_NOIO);
1503         if (ndisks) {
1504                 for (i=0; i<conf->raid_disks; i++)
1505                         ndisks[i] = conf->disks[i];
1506                 kfree(conf->disks);
1507                 conf->disks = ndisks;
1508         } else
1509                 err = -ENOMEM;
1510
1511         get_online_cpus();
1512         conf->scribble_len = scribble_len(newsize);
1513         for_each_present_cpu(cpu) {
1514                 struct raid5_percpu *percpu;
1515                 void *scribble;
1516
1517                 percpu = per_cpu_ptr(conf->percpu, cpu);
1518                 scribble = kmalloc(conf->scribble_len, GFP_NOIO);
1519
1520                 if (scribble) {
1521                         kfree(percpu->scribble);
1522                         percpu->scribble = scribble;
1523                 } else {
1524                         err = -ENOMEM;
1525                         break;
1526                 }
1527         }
1528         put_online_cpus();
1529
1530         /* Step 4, return new stripes to service */
1531         while(!list_empty(&newstripes)) {
1532                 nsh = list_entry(newstripes.next, struct stripe_head, lru);
1533                 list_del_init(&nsh->lru);
1534
1535                 for (i=conf->raid_disks; i < newsize; i++)
1536                         if (nsh->dev[i].page == NULL) {
1537                                 struct page *p = alloc_page(GFP_NOIO);
1538                                 nsh->dev[i].page = p;
1539                                 if (!p)
1540                                         err = -ENOMEM;
1541                         }
1542                 release_stripe(nsh);
1543         }
1544         /* critical section pass, GFP_NOIO no longer needed */
1545
1546         conf->slab_cache = sc;
1547         conf->active_name = 1-conf->active_name;
1548         conf->pool_size = newsize;
1549         return err;
1550 }
1551
1552 static int drop_one_stripe(struct r5conf *conf)
1553 {
1554         struct stripe_head *sh;
1555
1556         spin_lock_irq(&conf->device_lock);
1557         sh = get_free_stripe(conf);
1558         spin_unlock_irq(&conf->device_lock);
1559         if (!sh)
1560                 return 0;
1561         BUG_ON(atomic_read(&sh->count));
1562         shrink_buffers(sh);
1563         kmem_cache_free(conf->slab_cache, sh);
1564         atomic_dec(&conf->active_stripes);
1565         return 1;
1566 }
1567
1568 static void shrink_stripes(struct r5conf *conf)
1569 {
1570         while (drop_one_stripe(conf))
1571                 ;
1572
1573         if (conf->slab_cache)
1574                 kmem_cache_destroy(conf->slab_cache);
1575         conf->slab_cache = NULL;
1576 }
1577
1578 static void raid5_end_read_request(struct bio * bi, int error)
1579 {
1580         struct stripe_head *sh = bi->bi_private;
1581         struct r5conf *conf = sh->raid_conf;
1582         int disks = sh->disks, i;
1583         int uptodate = test_bit(BIO_UPTODATE, &bi->bi_flags);
1584         char b[BDEVNAME_SIZE];
1585         struct md_rdev *rdev;
1586
1587
1588         for (i=0 ; i<disks; i++)
1589                 if (bi == &sh->dev[i].req)
1590                         break;
1591
1592         pr_debug("end_read_request %llu/%d, count: %d, uptodate %d.\n",
1593                 (unsigned long long)sh->sector, i, atomic_read(&sh->count),
1594                 uptodate);
1595         if (i == disks) {
1596                 BUG();
1597                 return;
1598         }
1599
1600         if (uptodate) {
1601                 set_bit(R5_UPTODATE, &sh->dev[i].flags);
1602                 if (test_bit(R5_ReadError, &sh->dev[i].flags)) {
1603                         rdev = conf->disks[i].rdev;
1604                         printk_ratelimited(
1605                                 KERN_INFO
1606                                 "md/raid:%s: read error corrected"
1607                                 " (%lu sectors at %llu on %s)\n",
1608                                 mdname(conf->mddev), STRIPE_SECTORS,
1609                                 (unsigned long long)(sh->sector
1610                                                      + rdev->data_offset),
1611                                 bdevname(rdev->bdev, b));
1612                         atomic_add(STRIPE_SECTORS, &rdev->corrected_errors);
1613                         clear_bit(R5_ReadError, &sh->dev[i].flags);
1614                         clear_bit(R5_ReWrite, &sh->dev[i].flags);
1615                 }
1616                 if (atomic_read(&conf->disks[i].rdev->read_errors))
1617                         atomic_set(&conf->disks[i].rdev->read_errors, 0);
1618         } else {
1619                 const char *bdn = bdevname(conf->disks[i].rdev->bdev, b);
1620                 int retry = 0;
1621                 rdev = conf->disks[i].rdev;
1622
1623                 clear_bit(R5_UPTODATE, &sh->dev[i].flags);
1624                 atomic_inc(&rdev->read_errors);
1625                 if (conf->mddev->degraded >= conf->max_degraded)
1626                         printk_ratelimited(
1627                                 KERN_WARNING
1628                                 "md/raid:%s: read error not correctable "
1629                                 "(sector %llu on %s).\n",
1630                                 mdname(conf->mddev),
1631                                 (unsigned long long)(sh->sector
1632                                                      + rdev->data_offset),
1633                                 bdn);
1634                 else if (test_bit(R5_ReWrite, &sh->dev[i].flags))
1635                         /* Oh, no!!! */
1636                         printk_ratelimited(
1637                                 KERN_WARNING
1638                                 "md/raid:%s: read error NOT corrected!! "
1639                                 "(sector %llu on %s).\n",
1640                                 mdname(conf->mddev),
1641                                 (unsigned long long)(sh->sector
1642                                                      + rdev->data_offset),
1643                                 bdn);
1644                 else if (atomic_read(&rdev->read_errors)
1645                          > conf->max_nr_stripes)
1646                         printk(KERN_WARNING
1647                                "md/raid:%s: Too many read errors, failing device %s.\n",
1648                                mdname(conf->mddev), bdn);
1649                 else
1650                         retry = 1;
1651                 if (retry)
1652                         set_bit(R5_ReadError, &sh->dev[i].flags);
1653                 else {
1654                         clear_bit(R5_ReadError, &sh->dev[i].flags);
1655                         clear_bit(R5_ReWrite, &sh->dev[i].flags);
1656                         md_error(conf->mddev, rdev);
1657                 }
1658         }
1659         rdev_dec_pending(conf->disks[i].rdev, conf->mddev);
1660         clear_bit(R5_LOCKED, &sh->dev[i].flags);
1661         set_bit(STRIPE_HANDLE, &sh->state);
1662         release_stripe(sh);
1663 }
1664
1665 static void raid5_end_write_request(struct bio *bi, int error)
1666 {
1667         struct stripe_head *sh = bi->bi_private;
1668         struct r5conf *conf = sh->raid_conf;
1669         int disks = sh->disks, i;
1670         int uptodate = test_bit(BIO_UPTODATE, &bi->bi_flags);
1671         sector_t first_bad;
1672         int bad_sectors;
1673
1674         for (i=0 ; i<disks; i++)
1675                 if (bi == &sh->dev[i].req)
1676                         break;
1677
1678         pr_debug("end_write_request %llu/%d, count %d, uptodate: %d.\n",
1679                 (unsigned long long)sh->sector, i, atomic_read(&sh->count),
1680                 uptodate);
1681         if (i == disks) {
1682                 BUG();
1683                 return;
1684         }
1685
1686         if (!uptodate) {
1687                 set_bit(WriteErrorSeen, &conf->disks[i].rdev->flags);
1688                 set_bit(R5_WriteError, &sh->dev[i].flags);
1689         } else if (is_badblock(conf->disks[i].rdev, sh->sector, STRIPE_SECTORS,
1690                                &first_bad, &bad_sectors))
1691                 set_bit(R5_MadeGood, &sh->dev[i].flags);
1692
1693         rdev_dec_pending(conf->disks[i].rdev, conf->mddev);
1694         
1695         clear_bit(R5_LOCKED, &sh->dev[i].flags);
1696         set_bit(STRIPE_HANDLE, &sh->state);
1697         release_stripe(sh);
1698 }
1699
1700
1701 static sector_t compute_blocknr(struct stripe_head *sh, int i, int previous);
1702         
1703 static void raid5_build_block(struct stripe_head *sh, int i, int previous)
1704 {
1705         struct r5dev *dev = &sh->dev[i];
1706
1707         bio_init(&dev->req);
1708         dev->req.bi_io_vec = &dev->vec;
1709         dev->req.bi_vcnt++;
1710         dev->req.bi_max_vecs++;
1711         dev->vec.bv_page = dev->page;
1712         dev->vec.bv_len = STRIPE_SIZE;
1713         dev->vec.bv_offset = 0;
1714
1715         dev->req.bi_sector = sh->sector;
1716         dev->req.bi_private = sh;
1717
1718         dev->flags = 0;
1719         dev->sector = compute_blocknr(sh, i, previous);
1720 }
1721
1722 static void error(struct mddev *mddev, struct md_rdev *rdev)
1723 {
1724         char b[BDEVNAME_SIZE];
1725         struct r5conf *conf = mddev->private;
1726         pr_debug("raid456: error called\n");
1727
1728         if (test_and_clear_bit(In_sync, &rdev->flags)) {
1729                 unsigned long flags;
1730                 spin_lock_irqsave(&conf->device_lock, flags);
1731                 mddev->degraded++;
1732                 spin_unlock_irqrestore(&conf->device_lock, flags);
1733                 /*
1734                  * if recovery was running, make sure it aborts.
1735                  */
1736                 set_bit(MD_RECOVERY_INTR, &mddev->recovery);
1737         }
1738         set_bit(Blocked, &rdev->flags);
1739         set_bit(Faulty, &rdev->flags);
1740         set_bit(MD_CHANGE_DEVS, &mddev->flags);
1741         printk(KERN_ALERT
1742                "md/raid:%s: Disk failure on %s, disabling device.\n"
1743                "md/raid:%s: Operation continuing on %d devices.\n",
1744                mdname(mddev),
1745                bdevname(rdev->bdev, b),
1746                mdname(mddev),
1747                conf->raid_disks - mddev->degraded);
1748 }
1749
1750 /*
1751  * Input: a 'big' sector number,
1752  * Output: index of the data and parity disk, and the sector # in them.
1753  */
1754 static sector_t raid5_compute_sector(struct r5conf *conf, sector_t r_sector,
1755                                      int previous, int *dd_idx,
1756                                      struct stripe_head *sh)
1757 {
1758         sector_t stripe, stripe2;
1759         sector_t chunk_number;
1760         unsigned int chunk_offset;
1761         int pd_idx, qd_idx;
1762         int ddf_layout = 0;
1763         sector_t new_sector;
1764         int algorithm = previous ? conf->prev_algo
1765                                  : conf->algorithm;
1766         int sectors_per_chunk = previous ? conf->prev_chunk_sectors
1767                                          : conf->chunk_sectors;
1768         int raid_disks = previous ? conf->previous_raid_disks
1769                                   : conf->raid_disks;
1770         int data_disks = raid_disks - conf->max_degraded;
1771
1772         /* First compute the information on this sector */
1773
1774         /*
1775          * Compute the chunk number and the sector offset inside the chunk
1776          */
1777         chunk_offset = sector_div(r_sector, sectors_per_chunk);
1778         chunk_number = r_sector;
1779
1780         /*
1781          * Compute the stripe number
1782          */
1783         stripe = chunk_number;
1784         *dd_idx = sector_div(stripe, data_disks);
1785         stripe2 = stripe;
1786         /*
1787          * Select the parity disk based on the user selected algorithm.
1788          */
1789         pd_idx = qd_idx = -1;
1790         switch(conf->level) {
1791         case 4:
1792                 pd_idx = data_disks;
1793                 break;
1794         case 5:
1795                 switch (algorithm) {
1796                 case ALGORITHM_LEFT_ASYMMETRIC:
1797                         pd_idx = data_disks - sector_div(stripe2, raid_disks);
1798                         if (*dd_idx >= pd_idx)
1799                                 (*dd_idx)++;
1800                         break;
1801                 case ALGORITHM_RIGHT_ASYMMETRIC:
1802                         pd_idx = sector_div(stripe2, raid_disks);
1803                         if (*dd_idx >= pd_idx)
1804                                 (*dd_idx)++;
1805                         break;
1806                 case ALGORITHM_LEFT_SYMMETRIC:
1807                         pd_idx = data_disks - sector_div(stripe2, raid_disks);
1808                         *dd_idx = (pd_idx + 1 + *dd_idx) % raid_disks;
1809                         break;
1810                 case ALGORITHM_RIGHT_SYMMETRIC:
1811                         pd_idx = sector_div(stripe2, raid_disks);
1812                         *dd_idx = (pd_idx + 1 + *dd_idx) % raid_disks;
1813                         break;
1814                 case ALGORITHM_PARITY_0:
1815                         pd_idx = 0;
1816                         (*dd_idx)++;
1817                         break;
1818                 case ALGORITHM_PARITY_N:
1819                         pd_idx = data_disks;
1820                         break;
1821                 default:
1822                         BUG();
1823                 }
1824                 break;
1825         case 6:
1826
1827                 switch (algorithm) {
1828                 case ALGORITHM_LEFT_ASYMMETRIC:
1829                         pd_idx = raid_disks - 1 - sector_div(stripe2, raid_disks);
1830                         qd_idx = pd_idx + 1;
1831                         if (pd_idx == raid_disks-1) {
1832                                 (*dd_idx)++;    /* Q D D D P */
1833                                 qd_idx = 0;
1834                         } else if (*dd_idx >= pd_idx)
1835                                 (*dd_idx) += 2; /* D D P Q D */
1836                         break;
1837                 case ALGORITHM_RIGHT_ASYMMETRIC:
1838                         pd_idx = sector_div(stripe2, raid_disks);
1839                         qd_idx = pd_idx + 1;
1840                         if (pd_idx == raid_disks-1) {
1841                                 (*dd_idx)++;    /* Q D D D P */
1842                                 qd_idx = 0;
1843                         } else if (*dd_idx >= pd_idx)
1844                                 (*dd_idx) += 2; /* D D P Q D */
1845                         break;
1846                 case ALGORITHM_LEFT_SYMMETRIC:
1847                         pd_idx = raid_disks - 1 - sector_div(stripe2, raid_disks);
1848                         qd_idx = (pd_idx + 1) % raid_disks;
1849                         *dd_idx = (pd_idx + 2 + *dd_idx) % raid_disks;
1850                         break;
1851                 case ALGORITHM_RIGHT_SYMMETRIC:
1852                         pd_idx = sector_div(stripe2, raid_disks);
1853                         qd_idx = (pd_idx + 1) % raid_disks;
1854                         *dd_idx = (pd_idx + 2 + *dd_idx) % raid_disks;
1855                         break;
1856
1857                 case ALGORITHM_PARITY_0:
1858                         pd_idx = 0;
1859                         qd_idx = 1;
1860                         (*dd_idx) += 2;
1861                         break;
1862                 case ALGORITHM_PARITY_N:
1863                         pd_idx = data_disks;
1864                         qd_idx = data_disks + 1;
1865                         break;
1866
1867                 case ALGORITHM_ROTATING_ZERO_RESTART:
1868                         /* Exactly the same as RIGHT_ASYMMETRIC, but or
1869                          * of blocks for computing Q is different.
1870                          */
1871                         pd_idx = sector_div(stripe2, raid_disks);
1872                         qd_idx = pd_idx + 1;
1873                         if (pd_idx == raid_disks-1) {
1874                                 (*dd_idx)++;    /* Q D D D P */
1875                                 qd_idx = 0;
1876                         } else if (*dd_idx >= pd_idx)
1877                                 (*dd_idx) += 2; /* D D P Q D */
1878                         ddf_layout = 1;
1879                         break;
1880
1881                 case ALGORITHM_ROTATING_N_RESTART:
1882                         /* Same a left_asymmetric, by first stripe is
1883                          * D D D P Q  rather than
1884                          * Q D D D P
1885                          */
1886                         stripe2 += 1;
1887                         pd_idx = raid_disks - 1 - sector_div(stripe2, raid_disks);
1888                         qd_idx = pd_idx + 1;
1889                         if (pd_idx == raid_disks-1) {
1890                                 (*dd_idx)++;    /* Q D D D P */
1891                                 qd_idx = 0;
1892                         } else if (*dd_idx >= pd_idx)
1893                                 (*dd_idx) += 2; /* D D P Q D */
1894                         ddf_layout = 1;
1895                         break;
1896
1897                 case ALGORITHM_ROTATING_N_CONTINUE:
1898                         /* Same as left_symmetric but Q is before P */
1899                         pd_idx = raid_disks - 1 - sector_div(stripe2, raid_disks);
1900                         qd_idx = (pd_idx + raid_disks - 1) % raid_disks;
1901                         *dd_idx = (pd_idx + 1 + *dd_idx) % raid_disks;
1902                         ddf_layout = 1;
1903                         break;
1904
1905                 case ALGORITHM_LEFT_ASYMMETRIC_6:
1906                         /* RAID5 left_asymmetric, with Q on last device */
1907                         pd_idx = data_disks - sector_div(stripe2, raid_disks-1);
1908                         if (*dd_idx >= pd_idx)
1909                                 (*dd_idx)++;
1910                         qd_idx = raid_disks - 1;
1911                         break;
1912
1913                 case ALGORITHM_RIGHT_ASYMMETRIC_6:
1914                         pd_idx = sector_div(stripe2, raid_disks-1);
1915                         if (*dd_idx >= pd_idx)
1916                                 (*dd_idx)++;
1917                         qd_idx = raid_disks - 1;
1918                         break;
1919
1920                 case ALGORITHM_LEFT_SYMMETRIC_6:
1921                         pd_idx = data_disks - sector_div(stripe2, raid_disks-1);
1922                         *dd_idx = (pd_idx + 1 + *dd_idx) % (raid_disks-1);
1923                         qd_idx = raid_disks - 1;
1924                         break;
1925
1926                 case ALGORITHM_RIGHT_SYMMETRIC_6:
1927                         pd_idx = sector_div(stripe2, raid_disks-1);
1928                         *dd_idx = (pd_idx + 1 + *dd_idx) % (raid_disks-1);
1929                         qd_idx = raid_disks - 1;
1930                         break;
1931
1932                 case ALGORITHM_PARITY_0_6:
1933                         pd_idx = 0;
1934                         (*dd_idx)++;
1935                         qd_idx = raid_disks - 1;
1936                         break;
1937
1938                 default:
1939                         BUG();
1940                 }
1941                 break;
1942         }
1943
1944         if (sh) {
1945                 sh->pd_idx = pd_idx;
1946                 sh->qd_idx = qd_idx;
1947                 sh->ddf_layout = ddf_layout;
1948         }
1949         /*
1950          * Finally, compute the new sector number
1951          */
1952         new_sector = (sector_t)stripe * sectors_per_chunk + chunk_offset;
1953         return new_sector;
1954 }
1955
1956
1957 static sector_t compute_blocknr(struct stripe_head *sh, int i, int previous)
1958 {
1959         struct r5conf *conf = sh->raid_conf;
1960         int raid_disks = sh->disks;
1961         int data_disks = raid_disks - conf->max_degraded;
1962         sector_t new_sector = sh->sector, check;
1963         int sectors_per_chunk = previous ? conf->prev_chunk_sectors
1964                                          : conf->chunk_sectors;
1965         int algorithm = previous ? conf->prev_algo
1966                                  : conf->algorithm;
1967         sector_t stripe;
1968         int chunk_offset;
1969         sector_t chunk_number;
1970         int dummy1, dd_idx = i;
1971         sector_t r_sector;
1972         struct stripe_head sh2;
1973
1974
1975         chunk_offset = sector_div(new_sector, sectors_per_chunk);
1976         stripe = new_sector;
1977
1978         if (i == sh->pd_idx)
1979                 return 0;
1980         switch(conf->level) {
1981         case 4: break;
1982         case 5:
1983                 switch (algorithm) {
1984                 case ALGORITHM_LEFT_ASYMMETRIC:
1985                 case ALGORITHM_RIGHT_ASYMMETRIC:
1986                         if (i > sh->pd_idx)
1987                                 i--;
1988                         break;
1989                 case ALGORITHM_LEFT_SYMMETRIC:
1990                 case ALGORITHM_RIGHT_SYMMETRIC:
1991                         if (i < sh->pd_idx)
1992                                 i += raid_disks;
1993                         i -= (sh->pd_idx + 1);
1994                         break;
1995                 case ALGORITHM_PARITY_0:
1996                         i -= 1;
1997                         break;
1998                 case ALGORITHM_PARITY_N:
1999                         break;
2000                 default:
2001                         BUG();
2002                 }
2003                 break;
2004         case 6:
2005                 if (i == sh->qd_idx)
2006                         return 0; /* It is the Q disk */
2007                 switch (algorithm) {
2008                 case ALGORITHM_LEFT_ASYMMETRIC:
2009                 case ALGORITHM_RIGHT_ASYMMETRIC:
2010                 case ALGORITHM_ROTATING_ZERO_RESTART:
2011                 case ALGORITHM_ROTATING_N_RESTART:
2012                         if (sh->pd_idx == raid_disks-1)
2013                                 i--;    /* Q D D D P */
2014                         else if (i > sh->pd_idx)
2015                                 i -= 2; /* D D P Q D */
2016                         break;
2017                 case ALGORITHM_LEFT_SYMMETRIC:
2018                 case ALGORITHM_RIGHT_SYMMETRIC:
2019                         if (sh->pd_idx == raid_disks-1)
2020                                 i--; /* Q D D D P */
2021                         else {
2022                                 /* D D P Q D */
2023                                 if (i < sh->pd_idx)
2024                                         i += raid_disks;
2025                                 i -= (sh->pd_idx + 2);
2026                         }
2027                         break;
2028                 case ALGORITHM_PARITY_0:
2029                         i -= 2;
2030                         break;
2031                 case ALGORITHM_PARITY_N:
2032                         break;
2033                 case ALGORITHM_ROTATING_N_CONTINUE:
2034                         /* Like left_symmetric, but P is before Q */
2035                         if (sh->pd_idx == 0)
2036                                 i--;    /* P D D D Q */
2037                         else {
2038                                 /* D D Q P D */
2039                                 if (i < sh->pd_idx)
2040                                         i += raid_disks;
2041                                 i -= (sh->pd_idx + 1);
2042                         }
2043                         break;
2044                 case ALGORITHM_LEFT_ASYMMETRIC_6:
2045                 case ALGORITHM_RIGHT_ASYMMETRIC_6:
2046                         if (i > sh->pd_idx)
2047                                 i--;
2048                         break;
2049                 case ALGORITHM_LEFT_SYMMETRIC_6:
2050                 case ALGORITHM_RIGHT_SYMMETRIC_6:
2051                         if (i < sh->pd_idx)
2052                                 i += data_disks + 1;
2053                         i -= (sh->pd_idx + 1);
2054                         break;
2055                 case ALGORITHM_PARITY_0_6:
2056                         i -= 1;
2057                         break;
2058                 default:
2059                         BUG();
2060                 }
2061                 break;
2062         }
2063
2064         chunk_number = stripe * data_disks + i;
2065         r_sector = chunk_number * sectors_per_chunk + chunk_offset;
2066
2067         check = raid5_compute_sector(conf, r_sector,
2068                                      previous, &dummy1, &sh2);
2069         if (check != sh->sector || dummy1 != dd_idx || sh2.pd_idx != sh->pd_idx
2070                 || sh2.qd_idx != sh->qd_idx) {
2071                 printk(KERN_ERR "md/raid:%s: compute_blocknr: map not correct\n",
2072                        mdname(conf->mddev));
2073                 return 0;
2074         }
2075         return r_sector;
2076 }
2077
2078
2079 static void
2080 schedule_reconstruction(struct stripe_head *sh, struct stripe_head_state *s,
2081                          int rcw, int expand)
2082 {
2083         int i, pd_idx = sh->pd_idx, disks = sh->disks;
2084         struct r5conf *conf = sh->raid_conf;
2085         int level = conf->level;
2086
2087         if (rcw) {
2088                 /* if we are not expanding this is a proper write request, and
2089                  * there will be bios with new data to be drained into the
2090                  * stripe cache
2091                  */
2092                 if (!expand) {
2093                         sh->reconstruct_state = reconstruct_state_drain_run;
2094                         set_bit(STRIPE_OP_BIODRAIN, &s->ops_request);
2095                 } else
2096                         sh->reconstruct_state = reconstruct_state_run;
2097
2098                 set_bit(STRIPE_OP_RECONSTRUCT, &s->ops_request);
2099
2100                 for (i = disks; i--; ) {
2101                         struct r5dev *dev = &sh->dev[i];
2102
2103                         if (dev->towrite) {
2104                                 set_bit(R5_LOCKED, &dev->flags);
2105                                 set_bit(R5_Wantdrain, &dev->flags);
2106                                 if (!expand)
2107                                         clear_bit(R5_UPTODATE, &dev->flags);
2108                                 s->locked++;
2109                         }
2110                 }
2111                 if (s->locked + conf->max_degraded == disks)
2112                         if (!test_and_set_bit(STRIPE_FULL_WRITE, &sh->state))
2113                                 atomic_inc(&conf->pending_full_writes);
2114         } else {
2115                 BUG_ON(level == 6);
2116                 BUG_ON(!(test_bit(R5_UPTODATE, &sh->dev[pd_idx].flags) ||
2117                         test_bit(R5_Wantcompute, &sh->dev[pd_idx].flags)));
2118
2119                 sh->reconstruct_state = reconstruct_state_prexor_drain_run;
2120                 set_bit(STRIPE_OP_PREXOR, &s->ops_request);
2121                 set_bit(STRIPE_OP_BIODRAIN, &s->ops_request);
2122                 set_bit(STRIPE_OP_RECONSTRUCT, &s->ops_request);
2123
2124                 for (i = disks; i--; ) {
2125                         struct r5dev *dev = &sh->dev[i];
2126                         if (i == pd_idx)
2127                                 continue;
2128
2129                         if (dev->towrite &&
2130                             (test_bit(R5_UPTODATE, &dev->flags) ||
2131                              test_bit(R5_Wantcompute, &dev->flags))) {
2132                                 set_bit(R5_Wantdrain, &dev->flags);
2133                                 set_bit(R5_LOCKED, &dev->flags);
2134                                 clear_bit(R5_UPTODATE, &dev->flags);
2135                                 s->locked++;
2136                         }
2137                 }
2138         }
2139
2140         /* keep the parity disk(s) locked while asynchronous operations
2141          * are in flight
2142          */
2143         set_bit(R5_LOCKED, &sh->dev[pd_idx].flags);
2144         clear_bit(R5_UPTODATE, &sh->dev[pd_idx].flags);
2145         s->locked++;
2146
2147         if (level == 6) {
2148                 int qd_idx = sh->qd_idx;
2149                 struct r5dev *dev = &sh->dev[qd_idx];
2150
2151                 set_bit(R5_LOCKED, &dev->flags);
2152                 clear_bit(R5_UPTODATE, &dev->flags);
2153                 s->locked++;
2154         }
2155
2156         pr_debug("%s: stripe %llu locked: %d ops_request: %lx\n",
2157                 __func__, (unsigned long long)sh->sector,
2158                 s->locked, s->ops_request);
2159 }
2160
2161 /*
2162  * Each stripe/dev can have one or more bion attached.
2163  * toread/towrite point to the first in a chain.
2164  * The bi_next chain must be in order.
2165  */
2166 static int add_stripe_bio(struct stripe_head *sh, struct bio *bi, int dd_idx, int forwrite)
2167 {
2168         struct bio **bip;
2169         struct r5conf *conf = sh->raid_conf;
2170         int firstwrite=0;
2171
2172         pr_debug("adding bi b#%llu to stripe s#%llu\n",
2173                 (unsigned long long)bi->bi_sector,
2174                 (unsigned long long)sh->sector);
2175
2176
2177         spin_lock_irq(&conf->device_lock);
2178         if (forwrite) {
2179                 bip = &sh->dev[dd_idx].towrite;
2180                 if (*bip == NULL && sh->dev[dd_idx].written == NULL)
2181                         firstwrite = 1;
2182         } else
2183                 bip = &sh->dev[dd_idx].toread;
2184         while (*bip && (*bip)->bi_sector < bi->bi_sector) {
2185                 if ((*bip)->bi_sector + ((*bip)->bi_size >> 9) > bi->bi_sector)
2186                         goto overlap;
2187                 bip = & (*bip)->bi_next;
2188         }
2189         if (*bip && (*bip)->bi_sector < bi->bi_sector + ((bi->bi_size)>>9))
2190                 goto overlap;
2191
2192         BUG_ON(*bip && bi->bi_next && (*bip) != bi->bi_next);
2193         if (*bip)
2194                 bi->bi_next = *bip;
2195         *bip = bi;
2196         bi->bi_phys_segments++;
2197
2198         if (forwrite) {
2199                 /* check if page is covered */
2200                 sector_t sector = sh->dev[dd_idx].sector;
2201                 for (bi=sh->dev[dd_idx].towrite;
2202                      sector < sh->dev[dd_idx].sector + STRIPE_SECTORS &&
2203                              bi && bi->bi_sector <= sector;
2204                      bi = r5_next_bio(bi, sh->dev[dd_idx].sector)) {
2205                         if (bi->bi_sector + (bi->bi_size>>9) >= sector)
2206                                 sector = bi->bi_sector + (bi->bi_size>>9);
2207                 }
2208                 if (sector >= sh->dev[dd_idx].sector + STRIPE_SECTORS)
2209                         set_bit(R5_OVERWRITE, &sh->dev[dd_idx].flags);
2210         }
2211         spin_unlock_irq(&conf->device_lock);
2212
2213         pr_debug("added bi b#%llu to stripe s#%llu, disk %d.\n",
2214                 (unsigned long long)(*bip)->bi_sector,
2215                 (unsigned long long)sh->sector, dd_idx);
2216
2217         if (conf->mddev->bitmap && firstwrite) {
2218                 bitmap_startwrite(conf->mddev->bitmap, sh->sector,
2219                                   STRIPE_SECTORS, 0);
2220                 sh->bm_seq = conf->seq_flush+1;
2221                 set_bit(STRIPE_BIT_DELAY, &sh->state);
2222         }
2223         return 1;
2224
2225  overlap:
2226         set_bit(R5_Overlap, &sh->dev[dd_idx].flags);
2227         spin_unlock_irq(&conf->device_lock);
2228         return 0;
2229 }
2230
2231 static void end_reshape(struct r5conf *conf);
2232
2233 static void stripe_set_idx(sector_t stripe, struct r5conf *conf, int previous,
2234                             struct stripe_head *sh)
2235 {
2236         int sectors_per_chunk =
2237                 previous ? conf->prev_chunk_sectors : conf->chunk_sectors;
2238         int dd_idx;
2239         int chunk_offset = sector_div(stripe, sectors_per_chunk);
2240         int disks = previous ? conf->previous_raid_disks : conf->raid_disks;
2241
2242         raid5_compute_sector(conf,
2243                              stripe * (disks - conf->max_degraded)
2244                              *sectors_per_chunk + chunk_offset,
2245                              previous,
2246                              &dd_idx, sh);
2247 }
2248
2249 static void
2250 handle_failed_stripe(struct r5conf *conf, struct stripe_head *sh,
2251                                 struct stripe_head_state *s, int disks,
2252                                 struct bio **return_bi)
2253 {
2254         int i;
2255         for (i = disks; i--; ) {
2256                 struct bio *bi;
2257                 int bitmap_end = 0;
2258
2259                 if (test_bit(R5_ReadError, &sh->dev[i].flags)) {
2260                         struct md_rdev *rdev;
2261                         rcu_read_lock();
2262                         rdev = rcu_dereference(conf->disks[i].rdev);
2263                         if (rdev && test_bit(In_sync, &rdev->flags))
2264                                 atomic_inc(&rdev->nr_pending);
2265                         else
2266                                 rdev = NULL;
2267                         rcu_read_unlock();
2268                         if (rdev) {
2269                                 if (!rdev_set_badblocks(
2270                                             rdev,
2271                                             sh->sector,
2272                                             STRIPE_SECTORS, 0))
2273                                         md_error(conf->mddev, rdev);
2274                                 rdev_dec_pending(rdev, conf->mddev);
2275                         }
2276                 }
2277                 spin_lock_irq(&conf->device_lock);
2278                 /* fail all writes first */
2279                 bi = sh->dev[i].towrite;
2280                 sh->dev[i].towrite = NULL;
2281                 if (bi) {
2282                         s->to_write--;
2283                         bitmap_end = 1;
2284                 }
2285
2286                 if (test_and_clear_bit(R5_Overlap, &sh->dev[i].flags))
2287                         wake_up(&conf->wait_for_overlap);
2288
2289                 while (bi && bi->bi_sector <
2290                         sh->dev[i].sector + STRIPE_SECTORS) {
2291                         struct bio *nextbi = r5_next_bio(bi, sh->dev[i].sector);
2292                         clear_bit(BIO_UPTODATE, &bi->bi_flags);
2293                         if (!raid5_dec_bi_phys_segments(bi)) {
2294                                 md_write_end(conf->mddev);
2295                                 bi->bi_next = *return_bi;
2296                                 *return_bi = bi;
2297                         }
2298                         bi = nextbi;
2299                 }
2300                 /* and fail all 'written' */
2301                 bi = sh->dev[i].written;
2302                 sh->dev[i].written = NULL;
2303                 if (bi) bitmap_end = 1;
2304                 while (bi && bi->bi_sector <
2305                        sh->dev[i].sector + STRIPE_SECTORS) {
2306                         struct bio *bi2 = r5_next_bio(bi, sh->dev[i].sector);
2307                         clear_bit(BIO_UPTODATE, &bi->bi_flags);
2308                         if (!raid5_dec_bi_phys_segments(bi)) {
2309                                 md_write_end(conf->mddev);
2310                                 bi->bi_next = *return_bi;
2311                                 *return_bi = bi;
2312                         }
2313                         bi = bi2;
2314                 }
2315
2316                 /* fail any reads if this device is non-operational and
2317                  * the data has not reached the cache yet.
2318                  */
2319                 if (!test_bit(R5_Wantfill, &sh->dev[i].flags) &&
2320                     (!test_bit(R5_Insync, &sh->dev[i].flags) ||
2321                       test_bit(R5_ReadError, &sh->dev[i].flags))) {
2322                         bi = sh->dev[i].toread;
2323                         sh->dev[i].toread = NULL;
2324                         if (test_and_clear_bit(R5_Overlap, &sh->dev[i].flags))
2325                                 wake_up(&conf->wait_for_overlap);
2326                         if (bi) s->to_read--;
2327                         while (bi && bi->bi_sector <
2328                                sh->dev[i].sector + STRIPE_SECTORS) {
2329                                 struct bio *nextbi =
2330                                         r5_next_bio(bi, sh->dev[i].sector);
2331                                 clear_bit(BIO_UPTODATE, &bi->bi_flags);
2332                                 if (!raid5_dec_bi_phys_segments(bi)) {
2333                                         bi->bi_next = *return_bi;
2334                                         *return_bi = bi;
2335                                 }
2336                                 bi = nextbi;
2337                         }
2338                 }
2339                 spin_unlock_irq(&conf->device_lock);
2340                 if (bitmap_end)
2341                         bitmap_endwrite(conf->mddev->bitmap, sh->sector,
2342                                         STRIPE_SECTORS, 0, 0);
2343                 /* If we were in the middle of a write the parity block might
2344                  * still be locked - so just clear all R5_LOCKED flags
2345                  */
2346                 clear_bit(R5_LOCKED, &sh->dev[i].flags);
2347         }
2348
2349         if (test_and_clear_bit(STRIPE_FULL_WRITE, &sh->state))
2350                 if (atomic_dec_and_test(&conf->pending_full_writes))
2351                         md_wakeup_thread(conf->mddev->thread);
2352 }
2353
2354 static void
2355 handle_failed_sync(struct r5conf *conf, struct stripe_head *sh,
2356                    struct stripe_head_state *s)
2357 {
2358         int abort = 0;
2359         int i;
2360
2361         md_done_sync(conf->mddev, STRIPE_SECTORS, 0);
2362         clear_bit(STRIPE_SYNCING, &sh->state);
2363         s->syncing = 0;
2364         /* There is nothing more to do for sync/check/repair.
2365          * For recover we need to record a bad block on all
2366          * non-sync devices, or abort the recovery
2367          */
2368         if (!test_bit(MD_RECOVERY_RECOVER, &conf->mddev->recovery))
2369                 return;
2370         /* During recovery devices cannot be removed, so locking and
2371          * refcounting of rdevs is not needed
2372          */
2373         for (i = 0; i < conf->raid_disks; i++) {
2374                 struct md_rdev *rdev = conf->disks[i].rdev;
2375                 if (!rdev
2376                     || test_bit(Faulty, &rdev->flags)
2377                     || test_bit(In_sync, &rdev->flags))
2378                         continue;
2379                 if (!rdev_set_badblocks(rdev, sh->sector,
2380                                         STRIPE_SECTORS, 0))
2381                         abort = 1;
2382         }
2383         if (abort) {
2384                 conf->recovery_disabled = conf->mddev->recovery_disabled;
2385                 set_bit(MD_RECOVERY_INTR, &conf->mddev->recovery);
2386         }
2387 }
2388
2389 /* fetch_block - checks the given member device to see if its data needs
2390  * to be read or computed to satisfy a request.
2391  *
2392  * Returns 1 when no more member devices need to be checked, otherwise returns
2393  * 0 to tell the loop in handle_stripe_fill to continue
2394  */
2395 static int fetch_block(struct stripe_head *sh, struct stripe_head_state *s,
2396                        int disk_idx, int disks)
2397 {
2398         struct r5dev *dev = &sh->dev[disk_idx];
2399         struct r5dev *fdev[2] = { &sh->dev[s->failed_num[0]],
2400                                   &sh->dev[s->failed_num[1]] };
2401
2402         /* is the data in this block needed, and can we get it? */
2403         if (!test_bit(R5_LOCKED, &dev->flags) &&
2404             !test_bit(R5_UPTODATE, &dev->flags) &&
2405             (dev->toread ||
2406              (dev->towrite && !test_bit(R5_OVERWRITE, &dev->flags)) ||
2407              s->syncing || s->expanding ||
2408              (s->failed >= 1 && fdev[0]->toread) ||
2409              (s->failed >= 2 && fdev[1]->toread) ||
2410              (sh->raid_conf->level <= 5 && s->failed && fdev[0]->towrite &&
2411               !test_bit(R5_OVERWRITE, &fdev[0]->flags)) ||
2412              (sh->raid_conf->level == 6 && s->failed && s->to_write))) {
2413                 /* we would like to get this block, possibly by computing it,
2414                  * otherwise read it if the backing disk is insync
2415                  */
2416                 BUG_ON(test_bit(R5_Wantcompute, &dev->flags));
2417                 BUG_ON(test_bit(R5_Wantread, &dev->flags));
2418                 if ((s->uptodate == disks - 1) &&
2419                     (s->failed && (disk_idx == s->failed_num[0] ||
2420                                    disk_idx == s->failed_num[1]))) {
2421                         /* have disk failed, and we're requested to fetch it;
2422                          * do compute it
2423                          */
2424                         pr_debug("Computing stripe %llu block %d\n",
2425                                (unsigned long long)sh->sector, disk_idx);
2426                         set_bit(STRIPE_COMPUTE_RUN, &sh->state);
2427                         set_bit(STRIPE_OP_COMPUTE_BLK, &s->ops_request);
2428                         set_bit(R5_Wantcompute, &dev->flags);
2429                         sh->ops.target = disk_idx;
2430                         sh->ops.target2 = -1; /* no 2nd target */
2431                         s->req_compute = 1;
2432                         /* Careful: from this point on 'uptodate' is in the eye
2433                          * of raid_run_ops which services 'compute' operations
2434                          * before writes. R5_Wantcompute flags a block that will
2435                          * be R5_UPTODATE by the time it is needed for a
2436                          * subsequent operation.
2437                          */
2438                         s->uptodate++;
2439                         return 1;
2440                 } else if (s->uptodate == disks-2 && s->failed >= 2) {
2441                         /* Computing 2-failure is *very* expensive; only
2442                          * do it if failed >= 2
2443                          */
2444                         int other;
2445                         for (other = disks; other--; ) {
2446                                 if (other == disk_idx)
2447                                         continue;
2448                                 if (!test_bit(R5_UPTODATE,
2449                                       &sh->dev[other].flags))
2450                                         break;
2451                         }
2452                         BUG_ON(other < 0);
2453                         pr_debug("Computing stripe %llu blocks %d,%d\n",
2454                                (unsigned long long)sh->sector,
2455                                disk_idx, other);
2456                         set_bit(STRIPE_COMPUTE_RUN, &sh->state);
2457                         set_bit(STRIPE_OP_COMPUTE_BLK, &s->ops_request);
2458                         set_bit(R5_Wantcompute, &sh->dev[disk_idx].flags);
2459                         set_bit(R5_Wantcompute, &sh->dev[other].flags);
2460                         sh->ops.target = disk_idx;
2461                         sh->ops.target2 = other;
2462                         s->uptodate += 2;
2463                         s->req_compute = 1;
2464                         return 1;
2465                 } else if (test_bit(R5_Insync, &dev->flags)) {
2466                         set_bit(R5_LOCKED, &dev->flags);
2467                         set_bit(R5_Wantread, &dev->flags);
2468                         s->locked++;
2469                         pr_debug("Reading block %d (sync=%d)\n",
2470                                 disk_idx, s->syncing);
2471                 }
2472         }
2473
2474         return 0;
2475 }
2476
2477 /**
2478  * handle_stripe_fill - read or compute data to satisfy pending requests.
2479  */
2480 static void handle_stripe_fill(struct stripe_head *sh,
2481                                struct stripe_head_state *s,
2482                                int disks)
2483 {
2484         int i;
2485
2486         /* look for blocks to read/compute, skip this if a compute
2487          * is already in flight, or if the stripe contents are in the
2488          * midst of changing due to a write
2489          */
2490         if (!test_bit(STRIPE_COMPUTE_RUN, &sh->state) && !sh->check_state &&
2491             !sh->reconstruct_state)
2492                 for (i = disks; i--; )
2493                         if (fetch_block(sh, s, i, disks))
2494                                 break;
2495         set_bit(STRIPE_HANDLE, &sh->state);
2496 }
2497
2498
2499 /* handle_stripe_clean_event
2500  * any written block on an uptodate or failed drive can be returned.
2501  * Note that if we 'wrote' to a failed drive, it will be UPTODATE, but
2502  * never LOCKED, so we don't need to test 'failed' directly.
2503  */
2504 static void handle_stripe_clean_event(struct r5conf *conf,
2505         struct stripe_head *sh, int disks, struct bio **return_bi)
2506 {
2507         int i;
2508         struct r5dev *dev;
2509
2510         for (i = disks; i--; )
2511                 if (sh->dev[i].written) {
2512                         dev = &sh->dev[i];
2513                         if (!test_bit(R5_LOCKED, &dev->flags) &&
2514                                 test_bit(R5_UPTODATE, &dev->flags)) {
2515                                 /* We can return any write requests */
2516                                 struct bio *wbi, *wbi2;
2517                                 int bitmap_end = 0;
2518                                 pr_debug("Return write for disc %d\n", i);
2519                                 spin_lock_irq(&conf->device_lock);
2520                                 wbi = dev->written;
2521                                 dev->written = NULL;
2522                                 while (wbi && wbi->bi_sector <
2523                                         dev->sector + STRIPE_SECTORS) {
2524                                         wbi2 = r5_next_bio(wbi, dev->sector);
2525                                         if (!raid5_dec_bi_phys_segments(wbi)) {
2526                                                 md_write_end(conf->mddev);
2527                                                 wbi->bi_next = *return_bi;
2528                                                 *return_bi = wbi;
2529                                         }
2530                                         wbi = wbi2;
2531                                 }
2532                                 if (dev->towrite == NULL)
2533                                         bitmap_end = 1;
2534                                 spin_unlock_irq(&conf->device_lock);
2535                                 if (bitmap_end)
2536                                         bitmap_endwrite(conf->mddev->bitmap,
2537                                                         sh->sector,
2538                                                         STRIPE_SECTORS,
2539                                          !test_bit(STRIPE_DEGRADED, &sh->state),
2540                                                         0);
2541                         }
2542                 }
2543
2544         if (test_and_clear_bit(STRIPE_FULL_WRITE, &sh->state))
2545                 if (atomic_dec_and_test(&conf->pending_full_writes))
2546                         md_wakeup_thread(conf->mddev->thread);
2547 }
2548
2549 static void handle_stripe_dirtying(struct r5conf *conf,
2550                                    struct stripe_head *sh,
2551                                    struct stripe_head_state *s,
2552                                    int disks)
2553 {
2554         int rmw = 0, rcw = 0, i;
2555         if (conf->max_degraded == 2) {
2556                 /* RAID6 requires 'rcw' in current implementation
2557                  * Calculate the real rcw later - for now fake it
2558                  * look like rcw is cheaper
2559                  */
2560                 rcw = 1; rmw = 2;
2561         } else for (i = disks; i--; ) {
2562                 /* would I have to read this buffer for read_modify_write */
2563                 struct r5dev *dev = &sh->dev[i];
2564                 if ((dev->towrite || i == sh->pd_idx) &&
2565                     !test_bit(R5_LOCKED, &dev->flags) &&
2566                     !(test_bit(R5_UPTODATE, &dev->flags) ||
2567                       test_bit(R5_Wantcompute, &dev->flags))) {
2568                         if (test_bit(R5_Insync, &dev->flags))
2569                                 rmw++;
2570                         else
2571                                 rmw += 2*disks;  /* cannot read it */
2572                 }
2573                 /* Would I have to read this buffer for reconstruct_write */
2574                 if (!test_bit(R5_OVERWRITE, &dev->flags) && i != sh->pd_idx &&
2575                     !test_bit(R5_LOCKED, &dev->flags) &&
2576                     !(test_bit(R5_UPTODATE, &dev->flags) ||
2577                     test_bit(R5_Wantcompute, &dev->flags))) {
2578                         if (test_bit(R5_Insync, &dev->flags)) rcw++;
2579                         else
2580                                 rcw += 2*disks;
2581                 }
2582         }
2583         pr_debug("for sector %llu, rmw=%d rcw=%d\n",
2584                 (unsigned long long)sh->sector, rmw, rcw);
2585         set_bit(STRIPE_HANDLE, &sh->state);
2586         if (rmw < rcw && rmw > 0)
2587                 /* prefer read-modify-write, but need to get some data */
2588                 for (i = disks; i--; ) {
2589                         struct r5dev *dev = &sh->dev[i];
2590                         if ((dev->towrite || i == sh->pd_idx) &&
2591                             !test_bit(R5_LOCKED, &dev->flags) &&
2592                             !(test_bit(R5_UPTODATE, &dev->flags) ||
2593                             test_bit(R5_Wantcompute, &dev->flags)) &&
2594                             test_bit(R5_Insync, &dev->flags)) {
2595                                 if (
2596                                   test_bit(STRIPE_PREREAD_ACTIVE, &sh->state)) {
2597                                         pr_debug("Read_old block "
2598                                                 "%d for r-m-w\n", i);
2599                                         set_bit(R5_LOCKED, &dev->flags);
2600                                         set_bit(R5_Wantread, &dev->flags);
2601                                         s->locked++;
2602                                 } else {
2603                                         set_bit(STRIPE_DELAYED, &sh->state);
2604                                         set_bit(STRIPE_HANDLE, &sh->state);
2605                                 }
2606                         }
2607                 }
2608         if (rcw <= rmw && rcw > 0) {
2609                 /* want reconstruct write, but need to get some data */
2610                 rcw = 0;
2611                 for (i = disks; i--; ) {
2612                         struct r5dev *dev = &sh->dev[i];
2613                         if (!test_bit(R5_OVERWRITE, &dev->flags) &&
2614                             i != sh->pd_idx && i != sh->qd_idx &&
2615                             !test_bit(R5_LOCKED, &dev->flags) &&
2616                             !(test_bit(R5_UPTODATE, &dev->flags) ||
2617                               test_bit(R5_Wantcompute, &dev->flags))) {
2618                                 rcw++;
2619                                 if (!test_bit(R5_Insync, &dev->flags))
2620                                         continue; /* it's a failed drive */
2621                                 if (
2622                                   test_bit(STRIPE_PREREAD_ACTIVE, &sh->state)) {
2623                                         pr_debug("Read_old block "
2624                                                 "%d for Reconstruct\n", i);
2625                                         set_bit(R5_LOCKED, &dev->flags);
2626                                         set_bit(R5_Wantread, &dev->flags);
2627                                         s->locked++;
2628                                 } else {
2629                                         set_bit(STRIPE_DELAYED, &sh->state);
2630                                         set_bit(STRIPE_HANDLE, &sh->state);
2631                                 }
2632                         }
2633                 }
2634         }
2635         /* now if nothing is locked, and if we have enough data,
2636          * we can start a write request
2637          */
2638         /* since handle_stripe can be called at any time we need to handle the
2639          * case where a compute block operation has been submitted and then a
2640          * subsequent call wants to start a write request.  raid_run_ops only
2641          * handles the case where compute block and reconstruct are requested
2642          * simultaneously.  If this is not the case then new writes need to be
2643          * held off until the compute completes.
2644          */
2645         if ((s->req_compute || !test_bit(STRIPE_COMPUTE_RUN, &sh->state)) &&
2646             (s->locked == 0 && (rcw == 0 || rmw == 0) &&
2647             !test_bit(STRIPE_BIT_DELAY, &sh->state)))
2648                 schedule_reconstruction(sh, s, rcw == 0, 0);
2649 }
2650
2651 static void handle_parity_checks5(struct r5conf *conf, struct stripe_head *sh,
2652                                 struct stripe_head_state *s, int disks)
2653 {
2654         struct r5dev *dev = NULL;
2655
2656         set_bit(STRIPE_HANDLE, &sh->state);
2657
2658         switch (sh->check_state) {
2659         case check_state_idle:
2660                 /* start a new check operation if there are no failures */
2661                 if (s->failed == 0) {
2662                         BUG_ON(s->uptodate != disks);
2663                         sh->check_state = check_state_run;
2664                         set_bit(STRIPE_OP_CHECK, &s->ops_request);
2665                         clear_bit(R5_UPTODATE, &sh->dev[sh->pd_idx].flags);
2666                         s->uptodate--;
2667                         break;
2668                 }
2669                 dev = &sh->dev[s->failed_num[0]];
2670                 /* fall through */
2671         case check_state_compute_result:
2672                 sh->check_state = check_state_idle;
2673                 if (!dev)
2674                         dev = &sh->dev[sh->pd_idx];
2675
2676                 /* check that a write has not made the stripe insync */
2677                 if (test_bit(STRIPE_INSYNC, &sh->state))
2678                         break;
2679
2680                 /* either failed parity check, or recovery is happening */
2681                 BUG_ON(!test_bit(R5_UPTODATE, &dev->flags));
2682                 BUG_ON(s->uptodate != disks);
2683
2684                 set_bit(R5_LOCKED, &dev->flags);
2685                 s->locked++;
2686                 set_bit(R5_Wantwrite, &dev->flags);
2687
2688                 clear_bit(STRIPE_DEGRADED, &sh->state);
2689                 set_bit(STRIPE_INSYNC, &sh->state);
2690                 break;
2691         case check_state_run:
2692                 break; /* we will be called again upon completion */
2693         case check_state_check_result:
2694                 sh->check_state = check_state_idle;
2695
2696                 /* if a failure occurred during the check operation, leave
2697                  * STRIPE_INSYNC not set and let the stripe be handled again
2698                  */
2699                 if (s->failed)
2700                         break;
2701
2702                 /* handle a successful check operation, if parity is correct
2703                  * we are done.  Otherwise update the mismatch count and repair
2704                  * parity if !MD_RECOVERY_CHECK
2705                  */
2706                 if ((sh->ops.zero_sum_result & SUM_CHECK_P_RESULT) == 0)
2707                         /* parity is correct (on disc,
2708                          * not in buffer any more)
2709                          */
2710                         set_bit(STRIPE_INSYNC, &sh->state);
2711                 else {
2712                         conf->mddev->resync_mismatches += STRIPE_SECTORS;
2713                         if (test_bit(MD_RECOVERY_CHECK, &conf->mddev->recovery))
2714                                 /* don't try to repair!! */
2715                                 set_bit(STRIPE_INSYNC, &sh->state);
2716                         else {
2717                                 sh->check_state = check_state_compute_run;
2718                                 set_bit(STRIPE_COMPUTE_RUN, &sh->state);
2719                                 set_bit(STRIPE_OP_COMPUTE_BLK, &s->ops_request);
2720                                 set_bit(R5_Wantcompute,
2721                                         &sh->dev[sh->pd_idx].flags);
2722                                 sh->ops.target = sh->pd_idx;
2723                                 sh->ops.target2 = -1;
2724                                 s->uptodate++;
2725                         }
2726                 }
2727                 break;
2728         case check_state_compute_run:
2729                 break;
2730         default:
2731                 printk(KERN_ERR "%s: unknown check_state: %d sector: %llu\n",
2732                        __func__, sh->check_state,
2733                        (unsigned long long) sh->sector);
2734                 BUG();
2735         }
2736 }
2737
2738
2739 static void handle_parity_checks6(struct r5conf *conf, struct stripe_head *sh,
2740                                   struct stripe_head_state *s,
2741                                   int disks)
2742 {
2743         int pd_idx = sh->pd_idx;
2744         int qd_idx = sh->qd_idx;
2745         struct r5dev *dev;
2746
2747         set_bit(STRIPE_HANDLE, &sh->state);
2748
2749         BUG_ON(s->failed > 2);
2750
2751         /* Want to check and possibly repair P and Q.
2752          * However there could be one 'failed' device, in which
2753          * case we can only check one of them, possibly using the
2754          * other to generate missing data
2755          */
2756
2757         switch (sh->check_state) {
2758         case check_state_idle:
2759                 /* start a new check operation if there are < 2 failures */
2760                 if (s->failed == s->q_failed) {
2761                         /* The only possible failed device holds Q, so it
2762                          * makes sense to check P (If anything else were failed,
2763                          * we would have used P to recreate it).
2764                          */
2765                         sh->check_state = check_state_run;
2766                 }
2767                 if (!s->q_failed && s->failed < 2) {
2768                         /* Q is not failed, and we didn't use it to generate
2769                          * anything, so it makes sense to check it
2770                          */
2771                         if (sh->check_state == check_state_run)
2772                                 sh->check_state = check_state_run_pq;
2773                         else
2774                                 sh->check_state = check_state_run_q;
2775                 }
2776
2777                 /* discard potentially stale zero_sum_result */
2778                 sh->ops.zero_sum_result = 0;
2779
2780                 if (sh->check_state == check_state_run) {
2781                         /* async_xor_zero_sum destroys the contents of P */
2782                         clear_bit(R5_UPTODATE, &sh->dev[pd_idx].flags);
2783                         s->uptodate--;
2784                 }
2785                 if (sh->check_state >= check_state_run &&
2786                     sh->check_state <= check_state_run_pq) {
2787                         /* async_syndrome_zero_sum preserves P and Q, so
2788                          * no need to mark them !uptodate here
2789                          */
2790                         set_bit(STRIPE_OP_CHECK, &s->ops_request);
2791                         break;
2792                 }
2793
2794                 /* we have 2-disk failure */
2795                 BUG_ON(s->failed != 2);
2796                 /* fall through */
2797         case check_state_compute_result:
2798                 sh->check_state = check_state_idle;
2799
2800                 /* check that a write has not made the stripe insync */
2801                 if (test_bit(STRIPE_INSYNC, &sh->state))
2802                         break;
2803
2804                 /* now write out any block on a failed drive,
2805                  * or P or Q if they were recomputed
2806                  */
2807                 BUG_ON(s->uptodate < disks - 1); /* We don't need Q to recover */
2808                 if (s->failed == 2) {
2809                         dev = &sh->dev[s->failed_num[1]];
2810                         s->locked++;
2811                         set_bit(R5_LOCKED, &dev->flags);
2812                         set_bit(R5_Wantwrite, &dev->flags);
2813                 }
2814                 if (s->failed >= 1) {
2815                         dev = &sh->dev[s->failed_num[0]];
2816                         s->locked++;
2817                         set_bit(R5_LOCKED, &dev->flags);
2818                         set_bit(R5_Wantwrite, &dev->flags);
2819                 }
2820                 if (sh->ops.zero_sum_result & SUM_CHECK_P_RESULT) {
2821                         dev = &sh->dev[pd_idx];
2822                         s->locked++;
2823                         set_bit(R5_LOCKED, &dev->flags);
2824                         set_bit(R5_Wantwrite, &dev->flags);
2825                 }
2826                 if (sh->ops.zero_sum_result & SUM_CHECK_Q_RESULT) {
2827                         dev = &sh->dev[qd_idx];
2828                         s->locked++;
2829                         set_bit(R5_LOCKED, &dev->flags);
2830                         set_bit(R5_Wantwrite, &dev->flags);
2831                 }
2832                 clear_bit(STRIPE_DEGRADED, &sh->state);
2833
2834                 set_bit(STRIPE_INSYNC, &sh->state);
2835                 break;
2836         case check_state_run:
2837         case check_state_run_q:
2838         case check_state_run_pq:
2839                 break; /* we will be called again upon completion */
2840         case check_state_check_result:
2841                 sh->check_state = check_state_idle;
2842
2843                 /* handle a successful check operation, if parity is correct
2844                  * we are done.  Otherwise update the mismatch count and repair
2845                  * parity if !MD_RECOVERY_CHECK
2846                  */
2847                 if (sh->ops.zero_sum_result == 0) {
2848                         /* both parities are correct */
2849                         if (!s->failed)
2850                                 set_bit(STRIPE_INSYNC, &sh->state);
2851                         else {
2852                                 /* in contrast to the raid5 case we can validate
2853                                  * parity, but still have a failure to write
2854                                  * back
2855                                  */
2856                                 sh->check_state = check_state_compute_result;
2857                                 /* Returning at this point means that we may go
2858                                  * off and bring p and/or q uptodate again so
2859                                  * we make sure to check zero_sum_result again
2860                                  * to verify if p or q need writeback
2861                                  */
2862                         }
2863                 } else {
2864                         conf->mddev->resync_mismatches += STRIPE_SECTORS;
2865                         if (test_bit(MD_RECOVERY_CHECK, &conf->mddev->recovery))
2866                                 /* don't try to repair!! */
2867                                 set_bit(STRIPE_INSYNC, &sh->state);
2868                         else {
2869                                 int *target = &sh->ops.target;
2870
2871                                 sh->ops.target = -1;
2872                                 sh->ops.target2 = -1;
2873                                 sh->check_state = check_state_compute_run;
2874                                 set_bit(STRIPE_COMPUTE_RUN, &sh->state);
2875                                 set_bit(STRIPE_OP_COMPUTE_BLK, &s->ops_request);
2876                                 if (sh->ops.zero_sum_result & SUM_CHECK_P_RESULT) {
2877                                         set_bit(R5_Wantcompute,
2878                                                 &sh->dev[pd_idx].flags);
2879                                         *target = pd_idx;
2880                                         target = &sh->ops.target2;
2881                                         s->uptodate++;
2882                                 }
2883                                 if (sh->ops.zero_sum_result & SUM_CHECK_Q_RESULT) {
2884                                         set_bit(R5_Wantcompute,
2885                                                 &sh->dev[qd_idx].flags);
2886                                         *target = qd_idx;
2887                                         s->uptodate++;
2888                                 }
2889                         }
2890                 }
2891                 break;
2892         case check_state_compute_run:
2893                 break;
2894         default:
2895                 printk(KERN_ERR "%s: unknown check_state: %d sector: %llu\n",
2896                        __func__, sh->check_state,
2897                        (unsigned long long) sh->sector);
2898                 BUG();
2899         }
2900 }
2901
2902 static void handle_stripe_expansion(struct r5conf *conf, struct stripe_head *sh)
2903 {
2904         int i;
2905
2906         /* We have read all the blocks in this stripe and now we need to
2907          * copy some of them into a target stripe for expand.
2908          */
2909         struct dma_async_tx_descriptor *tx = NULL;
2910         clear_bit(STRIPE_EXPAND_SOURCE, &sh->state);
2911         for (i = 0; i < sh->disks; i++)
2912                 if (i != sh->pd_idx && i != sh->qd_idx) {
2913                         int dd_idx, j;
2914                         struct stripe_head *sh2;
2915                         struct async_submit_ctl submit;
2916
2917                         sector_t bn = compute_blocknr(sh, i, 1);
2918                         sector_t s = raid5_compute_sector(conf, bn, 0,
2919                                                           &dd_idx, NULL);
2920                         sh2 = get_active_stripe(conf, s, 0, 1, 1);
2921                         if (sh2 == NULL)
2922                                 /* so far only the early blocks of this stripe
2923                                  * have been requested.  When later blocks
2924                                  * get requested, we will try again
2925                                  */
2926                                 continue;
2927                         if (!test_bit(STRIPE_EXPANDING, &sh2->state) ||
2928                            test_bit(R5_Expanded, &sh2->dev[dd_idx].flags)) {
2929                                 /* must have already done this block */
2930                                 release_stripe(sh2);
2931                                 continue;
2932                         }
2933
2934                         /* place all the copies on one channel */
2935                         init_async_submit(&submit, 0, tx, NULL, NULL, NULL);
2936                         tx = async_memcpy(sh2->dev[dd_idx].page,
2937                                           sh->dev[i].page, 0, 0, STRIPE_SIZE,
2938                                           &submit);
2939
2940                         set_bit(R5_Expanded, &sh2->dev[dd_idx].flags);
2941                         set_bit(R5_UPTODATE, &sh2->dev[dd_idx].flags);
2942                         for (j = 0; j < conf->raid_disks; j++)
2943                                 if (j != sh2->pd_idx &&
2944                                     j != sh2->qd_idx &&
2945                                     !test_bit(R5_Expanded, &sh2->dev[j].flags))
2946                                         break;
2947                         if (j == conf->raid_disks) {
2948                                 set_bit(STRIPE_EXPAND_READY, &sh2->state);
2949                                 set_bit(STRIPE_HANDLE, &sh2->state);
2950                         }
2951                         release_stripe(sh2);
2952
2953                 }
2954         /* done submitting copies, wait for them to complete */
2955         if (tx) {
2956                 async_tx_ack(tx);
2957                 dma_wait_for_async_tx(tx);
2958         }
2959 }
2960
2961
2962 /*
2963  * handle_stripe - do things to a stripe.
2964  *
2965  * We lock the stripe and then examine the state of various bits
2966  * to see what needs to be done.
2967  * Possible results:
2968  *    return some read request which now have data
2969  *    return some write requests which are safely on disc
2970  *    schedule a read on some buffers
2971  *    schedule a write of some buffers
2972  *    return confirmation of parity correctness
2973  *
2974  * buffers are taken off read_list or write_list, and bh_cache buffers
2975  * get BH_Lock set before the stripe lock is released.
2976  *
2977  */
2978
2979 static void analyse_stripe(struct stripe_head *sh, struct stripe_head_state *s)
2980 {
2981         struct r5conf *conf = sh->raid_conf;
2982         int disks = sh->disks;
2983         struct r5dev *dev;
2984         int i;
2985
2986         memset(s, 0, sizeof(*s));
2987
2988         s->syncing = test_bit(STRIPE_SYNCING, &sh->state);
2989         s->expanding = test_bit(STRIPE_EXPAND_SOURCE, &sh->state);
2990         s->expanded = test_bit(STRIPE_EXPAND_READY, &sh->state);
2991         s->failed_num[0] = -1;
2992         s->failed_num[1] = -1;
2993
2994         /* Now to look around and see what can be done */
2995         rcu_read_lock();
2996         spin_lock_irq(&conf->device_lock);
2997         for (i=disks; i--; ) {
2998                 struct md_rdev *rdev;
2999                 sector_t first_bad;
3000                 int bad_sectors;
3001                 int is_bad = 0;
3002
3003                 dev = &sh->dev[i];
3004
3005                 pr_debug("check %d: state 0x%lx read %p write %p written %p\n",
3006                         i, dev->flags, dev->toread, dev->towrite, dev->written);
3007                 /* maybe we can reply to a read
3008                  *
3009                  * new wantfill requests are only permitted while
3010                  * ops_complete_biofill is guaranteed to be inactive
3011                  */
3012                 if (test_bit(R5_UPTODATE, &dev->flags) && dev->toread &&
3013                     !test_bit(STRIPE_BIOFILL_RUN, &sh->state))
3014                         set_bit(R5_Wantfill, &dev->flags);
3015
3016                 /* now count some things */
3017                 if (test_bit(R5_LOCKED, &dev->flags))
3018                         s->locked++;
3019                 if (test_bit(R5_UPTODATE, &dev->flags))
3020                         s->uptodate++;
3021                 if (test_bit(R5_Wantcompute, &dev->flags)) {
3022                         s->compute++;
3023                         BUG_ON(s->compute > 2);
3024                 }
3025
3026                 if (test_bit(R5_Wantfill, &dev->flags))
3027                         s->to_fill++;
3028                 else if (dev->toread)
3029                         s->to_read++;
3030                 if (dev->towrite) {
3031                         s->to_write++;
3032                         if (!test_bit(R5_OVERWRITE, &dev->flags))
3033                                 s->non_overwrite++;
3034                 }
3035                 if (dev->written)
3036                         s->written++;
3037                 rdev = rcu_dereference(conf->disks[i].rdev);
3038                 if (rdev) {
3039                         is_bad = is_badblock(rdev, sh->sector, STRIPE_SECTORS,
3040                                              &first_bad, &bad_sectors);
3041                         if (s->blocked_rdev == NULL
3042                             && (test_bit(Blocked, &rdev->flags)
3043                                 || is_bad < 0)) {
3044                                 if (is_bad < 0)
3045                                         set_bit(BlockedBadBlocks,
3046                                                 &rdev->flags);
3047                                 s->blocked_rdev = rdev;
3048                                 atomic_inc(&rdev->nr_pending);
3049                         }
3050                 }
3051                 clear_bit(R5_Insync, &dev->flags);
3052                 if (!rdev)
3053                         /* Not in-sync */;
3054                 else if (is_bad) {
3055                         /* also not in-sync */
3056                         if (!test_bit(WriteErrorSeen, &rdev->flags)) {
3057                                 /* treat as in-sync, but with a read error
3058                                  * which we can now try to correct
3059                                  */
3060                                 set_bit(R5_Insync, &dev->flags);
3061                                 set_bit(R5_ReadError, &dev->flags);
3062                         }
3063                 } else if (test_bit(In_sync, &rdev->flags))
3064                         set_bit(R5_Insync, &dev->flags);
3065                 else if (!test_bit(Faulty, &rdev->flags)) {
3066                         /* in sync if before recovery_offset */
3067                         if (sh->sector + STRIPE_SECTORS <= rdev->recovery_offset)
3068                                 set_bit(R5_Insync, &dev->flags);
3069                 }
3070                 if (test_bit(R5_WriteError, &dev->flags)) {
3071                         clear_bit(R5_Insync, &dev->flags);
3072                         if (!test_bit(Faulty, &rdev->flags)) {
3073                                 s->handle_bad_blocks = 1;
3074                                 atomic_inc(&rdev->nr_pending);
3075                         } else
3076                                 clear_bit(R5_WriteError, &dev->flags);
3077                 }
3078                 if (test_bit(R5_MadeGood, &dev->flags)) {
3079                         if (!test_bit(Faulty, &rdev->flags)) {
3080                                 s->handle_bad_blocks = 1;
3081                          &nb