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