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