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