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