aoe: Fix unitialized var usage
[firefly-linux-kernel-4.4.55.git] / drivers / md / raid5.c
1 /*
2  * raid5.c : Multiple Devices driver for Linux
3  *         Copyright (C) 1996, 1997 Ingo Molnar, Miguel de Icaza, Gadi Oxman
4  *         Copyright (C) 1999, 2000 Ingo Molnar
5  *         Copyright (C) 2002, 2003 H. Peter Anvin
6  *
7  * RAID-4/5/6 management functions.
8  * Thanks to Penguin Computing for making the RAID-6 development possible
9  * by donating a test server!
10  *
11  * This program is free software; you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation; either version 2, or (at your option)
14  * any later version.
15  *
16  * You should have received a copy of the GNU General Public License
17  * (for example /usr/src/linux/COPYING); if not, write to the Free
18  * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19  */
20
21 /*
22  * BITMAP UNPLUGGING:
23  *
24  * The sequencing for updating the bitmap reliably is a little
25  * subtle (and I got it wrong the first time) so it deserves some
26  * explanation.
27  *
28  * We group bitmap updates into batches.  Each batch has a number.
29  * We may write out several batches at once, but that isn't very important.
30  * conf->seq_write is the number of the last batch successfully written.
31  * conf->seq_flush is the number of the last batch that was closed to
32  *    new additions.
33  * When we discover that we will need to write to any block in a stripe
34  * (in add_stripe_bio) we update the in-memory bitmap and record in sh->bm_seq
35  * the number of the batch it will be in. This is seq_flush+1.
36  * When we are ready to do a write, if that batch hasn't been written yet,
37  *   we plug the array and queue the stripe for later.
38  * When an unplug happens, we increment bm_flush, thus closing the current
39  *   batch.
40  * When we notice that bm_flush > bm_write, we write out all pending updates
41  * to the bitmap, and advance bm_write to where bm_flush was.
42  * This may occasionally write a bit out twice, but is sure never to
43  * miss any bits.
44  */
45
46 #include <linux/blkdev.h>
47 #include <linux/kthread.h>
48 #include <linux/raid/pq.h>
49 #include <linux/async_tx.h>
50 #include <linux/module.h>
51 #include <linux/async.h>
52 #include <linux/seq_file.h>
53 #include <linux/cpu.h>
54 #include <linux/slab.h>
55 #include <linux/ratelimit.h>
56 #include <trace/events/block.h>
57
58 #include "md.h"
59 #include "raid5.h"
60 #include "raid0.h"
61 #include "bitmap.h"
62
63 /*
64  * Stripe cache
65  */
66
67 #define NR_STRIPES              256
68 #define STRIPE_SIZE             PAGE_SIZE
69 #define STRIPE_SHIFT            (PAGE_SHIFT - 9)
70 #define STRIPE_SECTORS          (STRIPE_SIZE>>9)
71 #define IO_THRESHOLD            1
72 #define BYPASS_THRESHOLD        1
73 #define NR_HASH                 (PAGE_SIZE / sizeof(struct hlist_head))
74 #define HASH_MASK               (NR_HASH - 1)
75
76 static inline struct hlist_head *stripe_hash(struct r5conf *conf, sector_t sect)
77 {
78         int hash = (sect >> STRIPE_SHIFT) & HASH_MASK;
79         return &conf->stripe_hashtbl[hash];
80 }
81
82 /* bio's attached to a stripe+device for I/O are linked together in bi_sector
83  * order without overlap.  There may be several bio's per stripe+device, and
84  * a bio could span several devices.
85  * When walking this list for a particular stripe+device, we must never proceed
86  * beyond a bio that extends past this device, as the next bio might no longer
87  * be valid.
88  * This function is used to determine the 'next' bio in the list, given the sector
89  * of the current stripe+device
90  */
91 static inline struct bio *r5_next_bio(struct bio *bio, sector_t sector)
92 {
93         int sectors = bio_sectors(bio);
94         if (bio->bi_sector + sectors < sector + STRIPE_SECTORS)
95                 return bio->bi_next;
96         else
97                 return NULL;
98 }
99
100 /*
101  * We maintain a biased count of active stripes in the bottom 16 bits of
102  * bi_phys_segments, and a count of processed stripes in the upper 16 bits
103  */
104 static inline int raid5_bi_processed_stripes(struct bio *bio)
105 {
106         atomic_t *segments = (atomic_t *)&bio->bi_phys_segments;
107         return (atomic_read(segments) >> 16) & 0xffff;
108 }
109
110 static inline int raid5_dec_bi_active_stripes(struct bio *bio)
111 {
112         atomic_t *segments = (atomic_t *)&bio->bi_phys_segments;
113         return atomic_sub_return(1, segments) & 0xffff;
114 }
115
116 static inline void raid5_inc_bi_active_stripes(struct bio *bio)
117 {
118         atomic_t *segments = (atomic_t *)&bio->bi_phys_segments;
119         atomic_inc(segments);
120 }
121
122 static inline void raid5_set_bi_processed_stripes(struct bio *bio,
123         unsigned int cnt)
124 {
125         atomic_t *segments = (atomic_t *)&bio->bi_phys_segments;
126         int old, new;
127
128         do {
129                 old = atomic_read(segments);
130                 new = (old & 0xffff) | (cnt << 16);
131         } while (atomic_cmpxchg(segments, old, new) != old);
132 }
133
134 static inline void raid5_set_bi_stripes(struct bio *bio, unsigned int cnt)
135 {
136         atomic_t *segments = (atomic_t *)&bio->bi_phys_segments;
137         atomic_set(segments, cnt);
138 }
139
140 /* Find first data disk in a raid6 stripe */
141 static inline int raid6_d0(struct stripe_head *sh)
142 {
143         if (sh->ddf_layout)
144                 /* ddf always start from first device */
145                 return 0;
146         /* md starts just after Q block */
147         if (sh->qd_idx == sh->disks - 1)
148                 return 0;
149         else
150                 return sh->qd_idx + 1;
151 }
152 static inline int raid6_next_disk(int disk, int raid_disks)
153 {
154         disk++;
155         return (disk < raid_disks) ? disk : 0;
156 }
157
158 /* When walking through the disks in a raid5, starting at raid6_d0,
159  * We need to map each disk to a 'slot', where the data disks are slot
160  * 0 .. raid_disks-3, the parity disk is raid_disks-2 and the Q disk
161  * is raid_disks-1.  This help does that mapping.
162  */
163 static int raid6_idx_to_slot(int idx, struct stripe_head *sh,
164                              int *count, int syndrome_disks)
165 {
166         int slot = *count;
167
168         if (sh->ddf_layout)
169                 (*count)++;
170         if (idx == sh->pd_idx)
171                 return syndrome_disks;
172         if (idx == sh->qd_idx)
173                 return syndrome_disks + 1;
174         if (!sh->ddf_layout)
175                 (*count)++;
176         return slot;
177 }
178
179 static void return_io(struct bio *return_bi)
180 {
181         struct bio *bi = return_bi;
182         while (bi) {
183
184                 return_bi = bi->bi_next;
185                 bi->bi_next = NULL;
186                 bi->bi_size = 0;
187                 bio_endio(bi, 0);
188                 bi = return_bi;
189         }
190 }
191
192 static void print_raid5_conf (struct r5conf *conf);
193
194 static int stripe_operations_active(struct stripe_head *sh)
195 {
196         return sh->check_state || sh->reconstruct_state ||
197                test_bit(STRIPE_BIOFILL_RUN, &sh->state) ||
198                test_bit(STRIPE_COMPUTE_RUN, &sh->state);
199 }
200
201 static void do_release_stripe(struct r5conf *conf, struct stripe_head *sh)
202 {
203         BUG_ON(!list_empty(&sh->lru));
204         BUG_ON(atomic_read(&conf->active_stripes)==0);
205         if (test_bit(STRIPE_HANDLE, &sh->state)) {
206                 if (test_bit(STRIPE_DELAYED, &sh->state) &&
207                     !test_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
208                         list_add_tail(&sh->lru, &conf->delayed_list);
209                 else if (test_bit(STRIPE_BIT_DELAY, &sh->state) &&
210                            sh->bm_seq - conf->seq_write > 0)
211                         list_add_tail(&sh->lru, &conf->bitmap_list);
212                 else {
213                         clear_bit(STRIPE_DELAYED, &sh->state);
214                         clear_bit(STRIPE_BIT_DELAY, &sh->state);
215                         list_add_tail(&sh->lru, &conf->handle_list);
216                 }
217                 md_wakeup_thread(conf->mddev->thread);
218         } else {
219                 BUG_ON(stripe_operations_active(sh));
220                 if (test_and_clear_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
221                         if (atomic_dec_return(&conf->preread_active_stripes)
222                             < IO_THRESHOLD)
223                                 md_wakeup_thread(conf->mddev->thread);
224                 atomic_dec(&conf->active_stripes);
225                 if (!test_bit(STRIPE_EXPANDING, &sh->state)) {
226                         list_add_tail(&sh->lru, &conf->inactive_list);
227                         wake_up(&conf->wait_for_stripe);
228                         if (conf->retry_read_aligned)
229                                 md_wakeup_thread(conf->mddev->thread);
230                 }
231         }
232 }
233
234 static void __release_stripe(struct r5conf *conf, struct stripe_head *sh)
235 {
236         if (atomic_dec_and_test(&sh->count))
237                 do_release_stripe(conf, sh);
238 }
239
240 static void release_stripe(struct stripe_head *sh)
241 {
242         struct r5conf *conf = sh->raid_conf;
243         unsigned long flags;
244
245         local_irq_save(flags);
246         if (atomic_dec_and_lock(&sh->count, &conf->device_lock)) {
247                 do_release_stripe(conf, sh);
248                 spin_unlock(&conf->device_lock);
249         }
250         local_irq_restore(flags);
251 }
252
253 static inline void remove_hash(struct stripe_head *sh)
254 {
255         pr_debug("remove_hash(), stripe %llu\n",
256                 (unsigned long long)sh->sector);
257
258         hlist_del_init(&sh->hash);
259 }
260
261 static inline void insert_hash(struct r5conf *conf, struct stripe_head *sh)
262 {
263         struct hlist_head *hp = stripe_hash(conf, sh->sector);
264
265         pr_debug("insert_hash(), stripe %llu\n",
266                 (unsigned long long)sh->sector);
267
268         hlist_add_head(&sh->hash, hp);
269 }
270
271
272 /* find an idle stripe, make sure it is unhashed, and return it. */
273 static struct stripe_head *get_free_stripe(struct r5conf *conf)
274 {
275         struct stripe_head *sh = NULL;
276         struct list_head *first;
277
278         if (list_empty(&conf->inactive_list))
279                 goto out;
280         first = conf->inactive_list.next;
281         sh = list_entry(first, struct stripe_head, lru);
282         list_del_init(first);
283         remove_hash(sh);
284         atomic_inc(&conf->active_stripes);
285 out:
286         return sh;
287 }
288
289 static void shrink_buffers(struct stripe_head *sh)
290 {
291         struct page *p;
292         int i;
293         int num = sh->raid_conf->pool_size;
294
295         for (i = 0; i < num ; i++) {
296                 p = sh->dev[i].page;
297                 if (!p)
298                         continue;
299                 sh->dev[i].page = NULL;
300                 put_page(p);
301         }
302 }
303
304 static int grow_buffers(struct stripe_head *sh)
305 {
306         int i;
307         int num = sh->raid_conf->pool_size;
308
309         for (i = 0; i < num; i++) {
310                 struct page *page;
311
312                 if (!(page = alloc_page(GFP_KERNEL))) {
313                         return 1;
314                 }
315                 sh->dev[i].page = page;
316         }
317         return 0;
318 }
319
320 static void raid5_build_block(struct stripe_head *sh, int i, int previous);
321 static void stripe_set_idx(sector_t stripe, struct r5conf *conf, int previous,
322                             struct stripe_head *sh);
323
324 static void init_stripe(struct stripe_head *sh, sector_t sector, int previous)
325 {
326         struct r5conf *conf = sh->raid_conf;
327         int i;
328
329         BUG_ON(atomic_read(&sh->count) != 0);
330         BUG_ON(test_bit(STRIPE_HANDLE, &sh->state));
331         BUG_ON(stripe_operations_active(sh));
332
333         pr_debug("init_stripe called, stripe %llu\n",
334                 (unsigned long long)sh->sector);
335
336         remove_hash(sh);
337
338         sh->generation = conf->generation - previous;
339         sh->disks = previous ? conf->previous_raid_disks : conf->raid_disks;
340         sh->sector = sector;
341         stripe_set_idx(sector, conf, previous, sh);
342         sh->state = 0;
343
344
345         for (i = sh->disks; i--; ) {
346                 struct r5dev *dev = &sh->dev[i];
347
348                 if (dev->toread || dev->read || dev->towrite || dev->written ||
349                     test_bit(R5_LOCKED, &dev->flags)) {
350                         printk(KERN_ERR "sector=%llx i=%d %p %p %p %p %d\n",
351                                (unsigned long long)sh->sector, i, dev->toread,
352                                dev->read, dev->towrite, dev->written,
353                                test_bit(R5_LOCKED, &dev->flags));
354                         WARN_ON(1);
355                 }
356                 dev->flags = 0;
357                 raid5_build_block(sh, i, previous);
358         }
359         insert_hash(conf, sh);
360 }
361
362 static struct stripe_head *__find_stripe(struct r5conf *conf, sector_t sector,
363                                          short generation)
364 {
365         struct stripe_head *sh;
366
367         pr_debug("__find_stripe, sector %llu\n", (unsigned long long)sector);
368         hlist_for_each_entry(sh, stripe_hash(conf, sector), hash)
369                 if (sh->sector == sector && sh->generation == generation)
370                         return sh;
371         pr_debug("__stripe %llu not in cache\n", (unsigned long long)sector);
372         return NULL;
373 }
374
375 /*
376  * Need to check if array has failed when deciding whether to:
377  *  - start an array
378  *  - remove non-faulty devices
379  *  - add a spare
380  *  - allow a reshape
381  * This determination is simple when no reshape is happening.
382  * However if there is a reshape, we need to carefully check
383  * both the before and after sections.
384  * This is because some failed devices may only affect one
385  * of the two sections, and some non-in_sync devices may
386  * be insync in the section most affected by failed devices.
387  */
388 static int calc_degraded(struct r5conf *conf)
389 {
390         int degraded, degraded2;
391         int i;
392
393         rcu_read_lock();
394         degraded = 0;
395         for (i = 0; i < conf->previous_raid_disks; i++) {
396                 struct md_rdev *rdev = rcu_dereference(conf->disks[i].rdev);
397                 if (rdev && test_bit(Faulty, &rdev->flags))
398                         rdev = rcu_dereference(conf->disks[i].replacement);
399                 if (!rdev || test_bit(Faulty, &rdev->flags))
400                         degraded++;
401                 else if (test_bit(In_sync, &rdev->flags))
402                         ;
403                 else
404                         /* not in-sync or faulty.
405                          * If the reshape increases the number of devices,
406                          * this is being recovered by the reshape, so
407                          * this 'previous' section is not in_sync.
408                          * If the number of devices is being reduced however,
409                          * the device can only be part of the array if
410                          * we are reverting a reshape, so this section will
411                          * be in-sync.
412                          */
413                         if (conf->raid_disks >= conf->previous_raid_disks)
414                                 degraded++;
415         }
416         rcu_read_unlock();
417         if (conf->raid_disks == conf->previous_raid_disks)
418                 return degraded;
419         rcu_read_lock();
420         degraded2 = 0;
421         for (i = 0; i < conf->raid_disks; i++) {
422                 struct md_rdev *rdev = rcu_dereference(conf->disks[i].rdev);
423                 if (rdev && test_bit(Faulty, &rdev->flags))
424                         rdev = rcu_dereference(conf->disks[i].replacement);
425                 if (!rdev || test_bit(Faulty, &rdev->flags))
426                         degraded2++;
427                 else if (test_bit(In_sync, &rdev->flags))
428                         ;
429                 else
430                         /* not in-sync or faulty.
431                          * If reshape increases the number of devices, this
432                          * section has already been recovered, else it
433                          * almost certainly hasn't.
434                          */
435                         if (conf->raid_disks <= conf->previous_raid_disks)
436                                 degraded2++;
437         }
438         rcu_read_unlock();
439         if (degraded2 > degraded)
440                 return degraded2;
441         return degraded;
442 }
443
444 static int has_failed(struct r5conf *conf)
445 {
446         int degraded;
447
448         if (conf->mddev->reshape_position == MaxSector)
449                 return conf->mddev->degraded > conf->max_degraded;
450
451         degraded = calc_degraded(conf);
452         if (degraded > conf->max_degraded)
453                 return 1;
454         return 0;
455 }
456
457 static struct stripe_head *
458 get_active_stripe(struct r5conf *conf, sector_t sector,
459                   int previous, int noblock, int noquiesce)
460 {
461         struct stripe_head *sh;
462
463         pr_debug("get_stripe, sector %llu\n", (unsigned long long)sector);
464
465         spin_lock_irq(&conf->device_lock);
466
467         do {
468                 wait_event_lock_irq(conf->wait_for_stripe,
469                                     conf->quiesce == 0 || noquiesce,
470                                     conf->device_lock);
471                 sh = __find_stripe(conf, sector, conf->generation - previous);
472                 if (!sh) {
473                         if (!conf->inactive_blocked)
474                                 sh = get_free_stripe(conf);
475                         if (noblock && sh == NULL)
476                                 break;
477                         if (!sh) {
478                                 conf->inactive_blocked = 1;
479                                 wait_event_lock_irq(conf->wait_for_stripe,
480                                                     !list_empty(&conf->inactive_list) &&
481                                                     (atomic_read(&conf->active_stripes)
482                                                      < (conf->max_nr_stripes *3/4)
483                                                      || !conf->inactive_blocked),
484                                                     conf->device_lock);
485                                 conf->inactive_blocked = 0;
486                         } else
487                                 init_stripe(sh, sector, previous);
488                 } else {
489                         if (atomic_read(&sh->count)) {
490                                 BUG_ON(!list_empty(&sh->lru)
491                                     && !test_bit(STRIPE_EXPANDING, &sh->state)
492                                     && !test_bit(STRIPE_ON_UNPLUG_LIST, &sh->state));
493                         } else {
494                                 if (!test_bit(STRIPE_HANDLE, &sh->state))
495                                         atomic_inc(&conf->active_stripes);
496                                 if (list_empty(&sh->lru) &&
497                                     !test_bit(STRIPE_EXPANDING, &sh->state))
498                                         BUG();
499                                 list_del_init(&sh->lru);
500                         }
501                 }
502         } while (sh == NULL);
503
504         if (sh)
505                 atomic_inc(&sh->count);
506
507         spin_unlock_irq(&conf->device_lock);
508         return sh;
509 }
510
511 /* Determine if 'data_offset' or 'new_data_offset' should be used
512  * in this stripe_head.
513  */
514 static int use_new_offset(struct r5conf *conf, struct stripe_head *sh)
515 {
516         sector_t progress = conf->reshape_progress;
517         /* Need a memory barrier to make sure we see the value
518          * of conf->generation, or ->data_offset that was set before
519          * reshape_progress was updated.
520          */
521         smp_rmb();
522         if (progress == MaxSector)
523                 return 0;
524         if (sh->generation == conf->generation - 1)
525                 return 0;
526         /* We are in a reshape, and this is a new-generation stripe,
527          * so use new_data_offset.
528          */
529         return 1;
530 }
531
532 static void
533 raid5_end_read_request(struct bio *bi, int error);
534 static void
535 raid5_end_write_request(struct bio *bi, int error);
536
537 static void ops_run_io(struct stripe_head *sh, struct stripe_head_state *s)
538 {
539         struct r5conf *conf = sh->raid_conf;
540         int i, disks = sh->disks;
541
542         might_sleep();
543
544         for (i = disks; i--; ) {
545                 int rw;
546                 int replace_only = 0;
547                 struct bio *bi, *rbi;
548                 struct md_rdev *rdev, *rrdev = NULL;
549                 if (test_and_clear_bit(R5_Wantwrite, &sh->dev[i].flags)) {
550                         if (test_and_clear_bit(R5_WantFUA, &sh->dev[i].flags))
551                                 rw = WRITE_FUA;
552                         else
553                                 rw = WRITE;
554                         if (test_bit(R5_Discard, &sh->dev[i].flags))
555                                 rw |= REQ_DISCARD;
556                 } else if (test_and_clear_bit(R5_Wantread, &sh->dev[i].flags))
557                         rw = READ;
558                 else if (test_and_clear_bit(R5_WantReplace,
559                                             &sh->dev[i].flags)) {
560                         rw = WRITE;
561                         replace_only = 1;
562                 } else
563                         continue;
564                 if (test_and_clear_bit(R5_SyncIO, &sh->dev[i].flags))
565                         rw |= REQ_SYNC;
566
567                 bi = &sh->dev[i].req;
568                 rbi = &sh->dev[i].rreq; /* For writing to replacement */
569
570                 rcu_read_lock();
571                 rrdev = rcu_dereference(conf->disks[i].replacement);
572                 smp_mb(); /* Ensure that if rrdev is NULL, rdev won't be */
573                 rdev = rcu_dereference(conf->disks[i].rdev);
574                 if (!rdev) {
575                         rdev = rrdev;
576                         rrdev = NULL;
577                 }
578                 if (rw & WRITE) {
579                         if (replace_only)
580                                 rdev = NULL;
581                         if (rdev == rrdev)
582                                 /* We raced and saw duplicates */
583                                 rrdev = NULL;
584                 } else {
585                         if (test_bit(R5_ReadRepl, &sh->dev[i].flags) && rrdev)
586                                 rdev = rrdev;
587                         rrdev = NULL;
588                 }
589
590                 if (rdev && test_bit(Faulty, &rdev->flags))
591                         rdev = NULL;
592                 if (rdev)
593                         atomic_inc(&rdev->nr_pending);
594                 if (rrdev && test_bit(Faulty, &rrdev->flags))
595                         rrdev = NULL;
596                 if (rrdev)
597                         atomic_inc(&rrdev->nr_pending);
598                 rcu_read_unlock();
599
600                 /* We have already checked bad blocks for reads.  Now
601                  * need to check for writes.  We never accept write errors
602                  * on the replacement, so we don't to check rrdev.
603                  */
604                 while ((rw & WRITE) && rdev &&
605                        test_bit(WriteErrorSeen, &rdev->flags)) {
606                         sector_t first_bad;
607                         int bad_sectors;
608                         int bad = is_badblock(rdev, sh->sector, STRIPE_SECTORS,
609                                               &first_bad, &bad_sectors);
610                         if (!bad)
611                                 break;
612
613                         if (bad < 0) {
614                                 set_bit(BlockedBadBlocks, &rdev->flags);
615                                 if (!conf->mddev->external &&
616                                     conf->mddev->flags) {
617                                         /* It is very unlikely, but we might
618                                          * still need to write out the
619                                          * bad block log - better give it
620                                          * a chance*/
621                                         md_check_recovery(conf->mddev);
622                                 }
623                                 /*
624                                  * Because md_wait_for_blocked_rdev
625                                  * will dec nr_pending, we must
626                                  * increment it first.
627                                  */
628                                 atomic_inc(&rdev->nr_pending);
629                                 md_wait_for_blocked_rdev(rdev, conf->mddev);
630                         } else {
631                                 /* Acknowledged bad block - skip the write */
632                                 rdev_dec_pending(rdev, conf->mddev);
633                                 rdev = NULL;
634                         }
635                 }
636
637                 if (rdev) {
638                         if (s->syncing || s->expanding || s->expanded
639                             || s->replacing)
640                                 md_sync_acct(rdev->bdev, STRIPE_SECTORS);
641
642                         set_bit(STRIPE_IO_STARTED, &sh->state);
643
644                         bio_reset(bi);
645                         bi->bi_bdev = rdev->bdev;
646                         bi->bi_rw = rw;
647                         bi->bi_end_io = (rw & WRITE)
648                                 ? raid5_end_write_request
649                                 : raid5_end_read_request;
650                         bi->bi_private = sh;
651
652                         pr_debug("%s: for %llu schedule op %ld on disc %d\n",
653                                 __func__, (unsigned long long)sh->sector,
654                                 bi->bi_rw, i);
655                         atomic_inc(&sh->count);
656                         if (use_new_offset(conf, sh))
657                                 bi->bi_sector = (sh->sector
658                                                  + rdev->new_data_offset);
659                         else
660                                 bi->bi_sector = (sh->sector
661                                                  + rdev->data_offset);
662                         if (test_bit(R5_ReadNoMerge, &sh->dev[i].flags))
663                                 bi->bi_rw |= REQ_FLUSH;
664
665                         bi->bi_io_vec[0].bv_len = STRIPE_SIZE;
666                         bi->bi_io_vec[0].bv_offset = 0;
667                         bi->bi_size = STRIPE_SIZE;
668                         if (rrdev)
669                                 set_bit(R5_DOUBLE_LOCKED, &sh->dev[i].flags);
670                         trace_block_bio_remap(bdev_get_queue(bi->bi_bdev),
671                                               bi, disk_devt(conf->mddev->gendisk),
672                                               sh->dev[i].sector);
673                         generic_make_request(bi);
674                 }
675                 if (rrdev) {
676                         if (s->syncing || s->expanding || s->expanded
677                             || s->replacing)
678                                 md_sync_acct(rrdev->bdev, STRIPE_SECTORS);
679
680                         set_bit(STRIPE_IO_STARTED, &sh->state);
681
682                         bio_reset(rbi);
683                         rbi->bi_bdev = rrdev->bdev;
684                         rbi->bi_rw = rw;
685                         BUG_ON(!(rw & WRITE));
686                         rbi->bi_end_io = raid5_end_write_request;
687                         rbi->bi_private = sh;
688
689                         pr_debug("%s: for %llu schedule op %ld on "
690                                  "replacement disc %d\n",
691                                 __func__, (unsigned long long)sh->sector,
692                                 rbi->bi_rw, i);
693                         atomic_inc(&sh->count);
694                         if (use_new_offset(conf, sh))
695                                 rbi->bi_sector = (sh->sector
696                                                   + rrdev->new_data_offset);
697                         else
698                                 rbi->bi_sector = (sh->sector
699                                                   + rrdev->data_offset);
700                         rbi->bi_io_vec[0].bv_len = STRIPE_SIZE;
701                         rbi->bi_io_vec[0].bv_offset = 0;
702                         rbi->bi_size = STRIPE_SIZE;
703                         trace_block_bio_remap(bdev_get_queue(rbi->bi_bdev),
704                                               rbi, disk_devt(conf->mddev->gendisk),
705                                               sh->dev[i].sector);
706                         generic_make_request(rbi);
707                 }
708                 if (!rdev && !rrdev) {
709                         if (rw & WRITE)
710                                 set_bit(STRIPE_DEGRADED, &sh->state);
711                         pr_debug("skip op %ld on disc %d for sector %llu\n",
712                                 bi->bi_rw, i, (unsigned long long)sh->sector);
713                         clear_bit(R5_LOCKED, &sh->dev[i].flags);
714                         set_bit(STRIPE_HANDLE, &sh->state);
715                 }
716         }
717 }
718
719 static struct dma_async_tx_descriptor *
720 async_copy_data(int frombio, struct bio *bio, struct page *page,
721         sector_t sector, struct dma_async_tx_descriptor *tx)
722 {
723         struct bio_vec *bvl;
724         struct page *bio_page;
725         int i;
726         int page_offset;
727         struct async_submit_ctl submit;
728         enum async_tx_flags flags = 0;
729
730         if (bio->bi_sector >= sector)
731                 page_offset = (signed)(bio->bi_sector - sector) * 512;
732         else
733                 page_offset = (signed)(sector - bio->bi_sector) * -512;
734
735         if (frombio)
736                 flags |= ASYNC_TX_FENCE;
737         init_async_submit(&submit, flags, tx, NULL, NULL, NULL);
738
739         bio_for_each_segment(bvl, bio, i) {
740                 int len = bvl->bv_len;
741                 int clen;
742                 int b_offset = 0;
743
744                 if (page_offset < 0) {
745                         b_offset = -page_offset;
746                         page_offset += b_offset;
747                         len -= b_offset;
748                 }
749
750                 if (len > 0 && page_offset + len > STRIPE_SIZE)
751                         clen = STRIPE_SIZE - page_offset;
752                 else
753                         clen = len;
754
755                 if (clen > 0) {
756                         b_offset += bvl->bv_offset;
757                         bio_page = bvl->bv_page;
758                         if (frombio)
759                                 tx = async_memcpy(page, bio_page, page_offset,
760                                                   b_offset, clen, &submit);
761                         else
762                                 tx = async_memcpy(bio_page, page, b_offset,
763                                                   page_offset, clen, &submit);
764                 }
765                 /* chain the operations */
766                 submit.depend_tx = tx;
767
768                 if (clen < len) /* hit end of page */
769                         break;
770                 page_offset +=  len;
771         }
772
773         return tx;
774 }
775
776 static void ops_complete_biofill(void *stripe_head_ref)
777 {
778         struct stripe_head *sh = stripe_head_ref;
779         struct bio *return_bi = NULL;
780         int i;
781
782         pr_debug("%s: stripe %llu\n", __func__,
783                 (unsigned long long)sh->sector);
784
785         /* clear completed biofills */
786         for (i = sh->disks; i--; ) {
787                 struct r5dev *dev = &sh->dev[i];
788
789                 /* acknowledge completion of a biofill operation */
790                 /* and check if we need to reply to a read request,
791                  * new R5_Wantfill requests are held off until
792                  * !STRIPE_BIOFILL_RUN
793                  */
794                 if (test_and_clear_bit(R5_Wantfill, &dev->flags)) {
795                         struct bio *rbi, *rbi2;
796
797                         BUG_ON(!dev->read);
798                         rbi = dev->read;
799                         dev->read = NULL;
800                         while (rbi && rbi->bi_sector <
801                                 dev->sector + STRIPE_SECTORS) {
802                                 rbi2 = r5_next_bio(rbi, dev->sector);
803                                 if (!raid5_dec_bi_active_stripes(rbi)) {
804                                         rbi->bi_next = return_bi;
805                                         return_bi = rbi;
806                                 }
807                                 rbi = rbi2;
808                         }
809                 }
810         }
811         clear_bit(STRIPE_BIOFILL_RUN, &sh->state);
812
813         return_io(return_bi);
814
815         set_bit(STRIPE_HANDLE, &sh->state);
816         release_stripe(sh);
817 }
818
819 static void ops_run_biofill(struct stripe_head *sh)
820 {
821         struct dma_async_tx_descriptor *tx = NULL;
822         struct async_submit_ctl submit;
823         int i;
824
825         pr_debug("%s: stripe %llu\n", __func__,
826                 (unsigned long long)sh->sector);
827
828         for (i = sh->disks; i--; ) {
829                 struct r5dev *dev = &sh->dev[i];
830                 if (test_bit(R5_Wantfill, &dev->flags)) {
831                         struct bio *rbi;
832                         spin_lock_irq(&sh->stripe_lock);
833                         dev->read = rbi = dev->toread;
834                         dev->toread = NULL;
835                         spin_unlock_irq(&sh->stripe_lock);
836                         while (rbi && rbi->bi_sector <
837                                 dev->sector + STRIPE_SECTORS) {
838                                 tx = async_copy_data(0, rbi, dev->page,
839                                         dev->sector, tx);
840                                 rbi = r5_next_bio(rbi, dev->sector);
841                         }
842                 }
843         }
844
845         atomic_inc(&sh->count);
846         init_async_submit(&submit, ASYNC_TX_ACK, tx, ops_complete_biofill, sh, NULL);
847         async_trigger_callback(&submit);
848 }
849
850 static void mark_target_uptodate(struct stripe_head *sh, int target)
851 {
852         struct r5dev *tgt;
853
854         if (target < 0)
855                 return;
856
857         tgt = &sh->dev[target];
858         set_bit(R5_UPTODATE, &tgt->flags);
859         BUG_ON(!test_bit(R5_Wantcompute, &tgt->flags));
860         clear_bit(R5_Wantcompute, &tgt->flags);
861 }
862
863 static void ops_complete_compute(void *stripe_head_ref)
864 {
865         struct stripe_head *sh = stripe_head_ref;
866
867         pr_debug("%s: stripe %llu\n", __func__,
868                 (unsigned long long)sh->sector);
869
870         /* mark the computed target(s) as uptodate */
871         mark_target_uptodate(sh, sh->ops.target);
872         mark_target_uptodate(sh, sh->ops.target2);
873
874         clear_bit(STRIPE_COMPUTE_RUN, &sh->state);
875         if (sh->check_state == check_state_compute_run)
876                 sh->check_state = check_state_compute_result;
877         set_bit(STRIPE_HANDLE, &sh->state);
878         release_stripe(sh);
879 }
880
881 /* return a pointer to the address conversion region of the scribble buffer */
882 static addr_conv_t *to_addr_conv(struct stripe_head *sh,
883                                  struct raid5_percpu *percpu)
884 {
885         return percpu->scribble + sizeof(struct page *) * (sh->disks + 2);
886 }
887
888 static struct dma_async_tx_descriptor *
889 ops_run_compute5(struct stripe_head *sh, struct raid5_percpu *percpu)
890 {
891         int disks = sh->disks;
892         struct page **xor_srcs = percpu->scribble;
893         int target = sh->ops.target;
894         struct r5dev *tgt = &sh->dev[target];
895         struct page *xor_dest = tgt->page;
896         int count = 0;
897         struct dma_async_tx_descriptor *tx;
898         struct async_submit_ctl submit;
899         int i;
900
901         pr_debug("%s: stripe %llu block: %d\n",
902                 __func__, (unsigned long long)sh->sector, target);
903         BUG_ON(!test_bit(R5_Wantcompute, &tgt->flags));
904
905         for (i = disks; i--; )
906                 if (i != target)
907                         xor_srcs[count++] = sh->dev[i].page;
908
909         atomic_inc(&sh->count);
910
911         init_async_submit(&submit, ASYNC_TX_FENCE|ASYNC_TX_XOR_ZERO_DST, NULL,
912                           ops_complete_compute, sh, to_addr_conv(sh, percpu));
913         if (unlikely(count == 1))
914                 tx = async_memcpy(xor_dest, xor_srcs[0], 0, 0, STRIPE_SIZE, &submit);
915         else
916                 tx = async_xor(xor_dest, xor_srcs, 0, count, STRIPE_SIZE, &submit);
917
918         return tx;
919 }
920
921 /* set_syndrome_sources - populate source buffers for gen_syndrome
922  * @srcs - (struct page *) array of size sh->disks
923  * @sh - stripe_head to parse
924  *
925  * Populates srcs in proper layout order for the stripe and returns the
926  * 'count' of sources to be used in a call to async_gen_syndrome.  The P
927  * destination buffer is recorded in srcs[count] and the Q destination
928  * is recorded in srcs[count+1]].
929  */
930 static int set_syndrome_sources(struct page **srcs, struct stripe_head *sh)
931 {
932         int disks = sh->disks;
933         int syndrome_disks = sh->ddf_layout ? disks : (disks - 2);
934         int d0_idx = raid6_d0(sh);
935         int count;
936         int i;
937
938         for (i = 0; i < disks; i++)
939                 srcs[i] = NULL;
940
941         count = 0;
942         i = d0_idx;
943         do {
944                 int slot = raid6_idx_to_slot(i, sh, &count, syndrome_disks);
945
946                 srcs[slot] = sh->dev[i].page;
947                 i = raid6_next_disk(i, disks);
948         } while (i != d0_idx);
949
950         return syndrome_disks;
951 }
952
953 static struct dma_async_tx_descriptor *
954 ops_run_compute6_1(struct stripe_head *sh, struct raid5_percpu *percpu)
955 {
956         int disks = sh->disks;
957         struct page **blocks = percpu->scribble;
958         int target;
959         int qd_idx = sh->qd_idx;
960         struct dma_async_tx_descriptor *tx;
961         struct async_submit_ctl submit;
962         struct r5dev *tgt;
963         struct page *dest;
964         int i;
965         int count;
966
967         if (sh->ops.target < 0)
968                 target = sh->ops.target2;
969         else if (sh->ops.target2 < 0)
970                 target = sh->ops.target;
971         else
972                 /* we should only have one valid target */
973                 BUG();
974         BUG_ON(target < 0);
975         pr_debug("%s: stripe %llu block: %d\n",
976                 __func__, (unsigned long long)sh->sector, target);
977
978         tgt = &sh->dev[target];
979         BUG_ON(!test_bit(R5_Wantcompute, &tgt->flags));
980         dest = tgt->page;
981
982         atomic_inc(&sh->count);
983
984         if (target == qd_idx) {
985                 count = set_syndrome_sources(blocks, sh);
986                 blocks[count] = NULL; /* regenerating p is not necessary */
987                 BUG_ON(blocks[count+1] != dest); /* q should already be set */
988                 init_async_submit(&submit, ASYNC_TX_FENCE, NULL,
989                                   ops_complete_compute, sh,
990                                   to_addr_conv(sh, percpu));
991                 tx = async_gen_syndrome(blocks, 0, count+2, STRIPE_SIZE, &submit);
992         } else {
993                 /* Compute any data- or p-drive using XOR */
994                 count = 0;
995                 for (i = disks; i-- ; ) {
996                         if (i == target || i == qd_idx)
997                                 continue;
998                         blocks[count++] = sh->dev[i].page;
999                 }
1000
1001                 init_async_submit(&submit, ASYNC_TX_FENCE|ASYNC_TX_XOR_ZERO_DST,
1002                                   NULL, ops_complete_compute, sh,
1003                                   to_addr_conv(sh, percpu));
1004                 tx = async_xor(dest, blocks, 0, count, STRIPE_SIZE, &submit);
1005         }
1006
1007         return tx;
1008 }
1009
1010 static struct dma_async_tx_descriptor *
1011 ops_run_compute6_2(struct stripe_head *sh, struct raid5_percpu *percpu)
1012 {
1013         int i, count, disks = sh->disks;
1014         int syndrome_disks = sh->ddf_layout ? disks : disks-2;
1015         int d0_idx = raid6_d0(sh);
1016         int faila = -1, failb = -1;
1017         int target = sh->ops.target;
1018         int target2 = sh->ops.target2;
1019         struct r5dev *tgt = &sh->dev[target];
1020         struct r5dev *tgt2 = &sh->dev[target2];
1021         struct dma_async_tx_descriptor *tx;
1022         struct page **blocks = percpu->scribble;
1023         struct async_submit_ctl submit;
1024
1025         pr_debug("%s: stripe %llu block1: %d block2: %d\n",
1026                  __func__, (unsigned long long)sh->sector, target, target2);
1027         BUG_ON(target < 0 || target2 < 0);
1028         BUG_ON(!test_bit(R5_Wantcompute, &tgt->flags));
1029         BUG_ON(!test_bit(R5_Wantcompute, &tgt2->flags));
1030
1031         /* we need to open-code set_syndrome_sources to handle the
1032          * slot number conversion for 'faila' and 'failb'
1033          */
1034         for (i = 0; i < disks ; i++)
1035                 blocks[i] = NULL;
1036         count = 0;
1037         i = d0_idx;
1038         do {
1039                 int slot = raid6_idx_to_slot(i, sh, &count, syndrome_disks);
1040
1041                 blocks[slot] = sh->dev[i].page;
1042
1043                 if (i == target)
1044                         faila = slot;
1045                 if (i == target2)
1046                         failb = slot;
1047                 i = raid6_next_disk(i, disks);
1048         } while (i != d0_idx);
1049
1050         BUG_ON(faila == failb);
1051         if (failb < faila)
1052                 swap(faila, failb);
1053         pr_debug("%s: stripe: %llu faila: %d failb: %d\n",
1054                  __func__, (unsigned long long)sh->sector, faila, failb);
1055
1056         atomic_inc(&sh->count);
1057
1058         if (failb == syndrome_disks+1) {
1059                 /* Q disk is one of the missing disks */
1060                 if (faila == syndrome_disks) {
1061                         /* Missing P+Q, just recompute */
1062                         init_async_submit(&submit, ASYNC_TX_FENCE, NULL,
1063                                           ops_complete_compute, sh,
1064                                           to_addr_conv(sh, percpu));
1065                         return async_gen_syndrome(blocks, 0, syndrome_disks+2,
1066                                                   STRIPE_SIZE, &submit);
1067                 } else {
1068                         struct page *dest;
1069                         int data_target;
1070                         int qd_idx = sh->qd_idx;
1071
1072                         /* Missing D+Q: recompute D from P, then recompute Q */
1073                         if (target == qd_idx)
1074                                 data_target = target2;
1075                         else
1076                                 data_target = target;
1077
1078                         count = 0;
1079                         for (i = disks; i-- ; ) {
1080                                 if (i == data_target || i == qd_idx)
1081                                         continue;
1082                                 blocks[count++] = sh->dev[i].page;
1083                         }
1084                         dest = sh->dev[data_target].page;
1085                         init_async_submit(&submit,
1086                                           ASYNC_TX_FENCE|ASYNC_TX_XOR_ZERO_DST,
1087                                           NULL, NULL, NULL,
1088                                           to_addr_conv(sh, percpu));
1089                         tx = async_xor(dest, blocks, 0, count, STRIPE_SIZE,
1090                                        &submit);
1091
1092                         count = set_syndrome_sources(blocks, sh);
1093                         init_async_submit(&submit, ASYNC_TX_FENCE, tx,
1094                                           ops_complete_compute, sh,
1095                                           to_addr_conv(sh, percpu));
1096                         return async_gen_syndrome(blocks, 0, count+2,
1097                                                   STRIPE_SIZE, &submit);
1098                 }
1099         } else {
1100                 init_async_submit(&submit, ASYNC_TX_FENCE, NULL,
1101                                   ops_complete_compute, sh,
1102                                   to_addr_conv(sh, percpu));
1103                 if (failb == syndrome_disks) {
1104                         /* We're missing D+P. */
1105                         return async_raid6_datap_recov(syndrome_disks+2,
1106                                                        STRIPE_SIZE, faila,
1107                                                        blocks, &submit);
1108                 } else {
1109                         /* We're missing D+D. */
1110                         return async_raid6_2data_recov(syndrome_disks+2,
1111                                                        STRIPE_SIZE, faila, failb,
1112                                                        blocks, &submit);
1113                 }
1114         }
1115 }
1116
1117
1118 static void ops_complete_prexor(void *stripe_head_ref)
1119 {
1120         struct stripe_head *sh = stripe_head_ref;
1121
1122         pr_debug("%s: stripe %llu\n", __func__,
1123                 (unsigned long long)sh->sector);
1124 }
1125
1126 static struct dma_async_tx_descriptor *
1127 ops_run_prexor(struct stripe_head *sh, struct raid5_percpu *percpu,
1128                struct dma_async_tx_descriptor *tx)
1129 {
1130         int disks = sh->disks;
1131         struct page **xor_srcs = percpu->scribble;
1132         int count = 0, pd_idx = sh->pd_idx, i;
1133         struct async_submit_ctl submit;
1134
1135         /* existing parity data subtracted */
1136         struct page *xor_dest = xor_srcs[count++] = sh->dev[pd_idx].page;
1137
1138         pr_debug("%s: stripe %llu\n", __func__,
1139                 (unsigned long long)sh->sector);
1140
1141         for (i = disks; i--; ) {
1142                 struct r5dev *dev = &sh->dev[i];
1143                 /* Only process blocks that are known to be uptodate */
1144                 if (test_bit(R5_Wantdrain, &dev->flags))
1145                         xor_srcs[count++] = dev->page;
1146         }
1147
1148         init_async_submit(&submit, ASYNC_TX_FENCE|ASYNC_TX_XOR_DROP_DST, tx,
1149                           ops_complete_prexor, sh, to_addr_conv(sh, percpu));
1150         tx = async_xor(xor_dest, xor_srcs, 0, count, STRIPE_SIZE, &submit);
1151
1152         return tx;
1153 }
1154
1155 static struct dma_async_tx_descriptor *
1156 ops_run_biodrain(struct stripe_head *sh, struct dma_async_tx_descriptor *tx)
1157 {
1158         int disks = sh->disks;
1159         int i;
1160
1161         pr_debug("%s: stripe %llu\n", __func__,
1162                 (unsigned long long)sh->sector);
1163
1164         for (i = disks; i--; ) {
1165                 struct r5dev *dev = &sh->dev[i];
1166                 struct bio *chosen;
1167
1168                 if (test_and_clear_bit(R5_Wantdrain, &dev->flags)) {
1169                         struct bio *wbi;
1170
1171                         spin_lock_irq(&sh->stripe_lock);
1172                         chosen = dev->towrite;
1173                         dev->towrite = NULL;
1174                         BUG_ON(dev->written);
1175                         wbi = dev->written = chosen;
1176                         spin_unlock_irq(&sh->stripe_lock);
1177
1178                         while (wbi && wbi->bi_sector <
1179                                 dev->sector + STRIPE_SECTORS) {
1180                                 if (wbi->bi_rw & REQ_FUA)
1181                                         set_bit(R5_WantFUA, &dev->flags);
1182                                 if (wbi->bi_rw & REQ_SYNC)
1183                                         set_bit(R5_SyncIO, &dev->flags);
1184                                 if (wbi->bi_rw & REQ_DISCARD)
1185                                         set_bit(R5_Discard, &dev->flags);
1186                                 else
1187                                         tx = async_copy_data(1, wbi, dev->page,
1188                                                 dev->sector, tx);
1189                                 wbi = r5_next_bio(wbi, dev->sector);
1190                         }
1191                 }
1192         }
1193
1194         return tx;
1195 }
1196
1197 static void ops_complete_reconstruct(void *stripe_head_ref)
1198 {
1199         struct stripe_head *sh = stripe_head_ref;
1200         int disks = sh->disks;
1201         int pd_idx = sh->pd_idx;
1202         int qd_idx = sh->qd_idx;
1203         int i;
1204         bool fua = false, sync = false, discard = false;
1205
1206         pr_debug("%s: stripe %llu\n", __func__,
1207                 (unsigned long long)sh->sector);
1208
1209         for (i = disks; i--; ) {
1210                 fua |= test_bit(R5_WantFUA, &sh->dev[i].flags);
1211                 sync |= test_bit(R5_SyncIO, &sh->dev[i].flags);
1212                 discard |= test_bit(R5_Discard, &sh->dev[i].flags);
1213         }
1214
1215         for (i = disks; i--; ) {
1216                 struct r5dev *dev = &sh->dev[i];
1217
1218                 if (dev->written || i == pd_idx || i == qd_idx) {
1219                         if (!discard)
1220                                 set_bit(R5_UPTODATE, &dev->flags);
1221                         if (fua)
1222                                 set_bit(R5_WantFUA, &dev->flags);
1223                         if (sync)
1224                                 set_bit(R5_SyncIO, &dev->flags);
1225                 }
1226         }
1227
1228         if (sh->reconstruct_state == reconstruct_state_drain_run)
1229                 sh->reconstruct_state = reconstruct_state_drain_result;
1230         else if (sh->reconstruct_state == reconstruct_state_prexor_drain_run)
1231                 sh->reconstruct_state = reconstruct_state_prexor_drain_result;
1232         else {
1233                 BUG_ON(sh->reconstruct_state != reconstruct_state_run);
1234                 sh->reconstruct_state = reconstruct_state_result;
1235         }
1236
1237         set_bit(STRIPE_HANDLE, &sh->state);
1238         release_stripe(sh);
1239 }
1240
1241 static void
1242 ops_run_reconstruct5(struct stripe_head *sh, struct raid5_percpu *percpu,
1243                      struct dma_async_tx_descriptor *tx)
1244 {
1245         int disks = sh->disks;
1246         struct page **xor_srcs = percpu->scribble;
1247         struct async_submit_ctl submit;
1248         int count = 0, pd_idx = sh->pd_idx, i;
1249         struct page *xor_dest;
1250         int prexor = 0;
1251         unsigned long flags;
1252
1253         pr_debug("%s: stripe %llu\n", __func__,
1254                 (unsigned long long)sh->sector);
1255
1256         for (i = 0; i < sh->disks; i++) {
1257                 if (pd_idx == i)
1258                         continue;
1259                 if (!test_bit(R5_Discard, &sh->dev[i].flags))
1260                         break;
1261         }
1262         if (i >= sh->disks) {
1263                 atomic_inc(&sh->count);
1264                 set_bit(R5_Discard, &sh->dev[pd_idx].flags);
1265                 ops_complete_reconstruct(sh);
1266                 return;
1267         }
1268         /* check if prexor is active which means only process blocks
1269          * that are part of a read-modify-write (written)
1270          */
1271         if (sh->reconstruct_state == reconstruct_state_prexor_drain_run) {
1272                 prexor = 1;
1273                 xor_dest = xor_srcs[count++] = sh->dev[pd_idx].page;
1274                 for (i = disks; i--; ) {
1275                         struct r5dev *dev = &sh->dev[i];
1276                         if (dev->written)
1277                                 xor_srcs[count++] = dev->page;
1278                 }
1279         } else {
1280                 xor_dest = sh->dev[pd_idx].page;
1281                 for (i = disks; i--; ) {
1282                         struct r5dev *dev = &sh->dev[i];
1283                         if (i != pd_idx)
1284                                 xor_srcs[count++] = dev->page;
1285                 }
1286         }
1287
1288         /* 1/ if we prexor'd then the dest is reused as a source
1289          * 2/ if we did not prexor then we are redoing the parity
1290          * set ASYNC_TX_XOR_DROP_DST and ASYNC_TX_XOR_ZERO_DST
1291          * for the synchronous xor case
1292          */
1293         flags = ASYNC_TX_ACK |
1294                 (prexor ? ASYNC_TX_XOR_DROP_DST : ASYNC_TX_XOR_ZERO_DST);
1295
1296         atomic_inc(&sh->count);
1297
1298         init_async_submit(&submit, flags, tx, ops_complete_reconstruct, sh,
1299                           to_addr_conv(sh, percpu));
1300         if (unlikely(count == 1))
1301                 tx = async_memcpy(xor_dest, xor_srcs[0], 0, 0, STRIPE_SIZE, &submit);
1302         else
1303                 tx = async_xor(xor_dest, xor_srcs, 0, count, STRIPE_SIZE, &submit);
1304 }
1305
1306 static void
1307 ops_run_reconstruct6(struct stripe_head *sh, struct raid5_percpu *percpu,
1308                      struct dma_async_tx_descriptor *tx)
1309 {
1310         struct async_submit_ctl submit;
1311         struct page **blocks = percpu->scribble;
1312         int count, i;
1313
1314         pr_debug("%s: stripe %llu\n", __func__, (unsigned long long)sh->sector);
1315
1316         for (i = 0; i < sh->disks; i++) {
1317                 if (sh->pd_idx == i || sh->qd_idx == i)
1318                         continue;
1319                 if (!test_bit(R5_Discard, &sh->dev[i].flags))
1320                         break;
1321         }
1322         if (i >= sh->disks) {
1323                 atomic_inc(&sh->count);
1324                 set_bit(R5_Discard, &sh->dev[sh->pd_idx].flags);
1325                 set_bit(R5_Discard, &sh->dev[sh->qd_idx].flags);
1326                 ops_complete_reconstruct(sh);
1327                 return;
1328         }
1329
1330         count = set_syndrome_sources(blocks, sh);
1331
1332         atomic_inc(&sh->count);
1333
1334         init_async_submit(&submit, ASYNC_TX_ACK, tx, ops_complete_reconstruct,
1335                           sh, to_addr_conv(sh, percpu));
1336         async_gen_syndrome(blocks, 0, count+2, STRIPE_SIZE,  &submit);
1337 }
1338
1339 static void ops_complete_check(void *stripe_head_ref)
1340 {
1341         struct stripe_head *sh = stripe_head_ref;
1342
1343         pr_debug("%s: stripe %llu\n", __func__,
1344                 (unsigned long long)sh->sector);
1345
1346         sh->check_state = check_state_check_result;
1347         set_bit(STRIPE_HANDLE, &sh->state);
1348         release_stripe(sh);
1349 }
1350
1351 static void ops_run_check_p(struct stripe_head *sh, struct raid5_percpu *percpu)
1352 {
1353         int disks = sh->disks;
1354         int pd_idx = sh->pd_idx;
1355         int qd_idx = sh->qd_idx;
1356         struct page *xor_dest;
1357         struct page **xor_srcs = percpu->scribble;
1358         struct dma_async_tx_descriptor *tx;
1359         struct async_submit_ctl submit;
1360         int count;
1361         int i;
1362
1363         pr_debug("%s: stripe %llu\n", __func__,
1364                 (unsigned long long)sh->sector);
1365
1366         count = 0;
1367         xor_dest = sh->dev[pd_idx].page;
1368         xor_srcs[count++] = xor_dest;
1369         for (i = disks; i--; ) {
1370                 if (i == pd_idx || i == qd_idx)
1371                         continue;
1372                 xor_srcs[count++] = sh->dev[i].page;
1373         }
1374
1375         init_async_submit(&submit, 0, NULL, NULL, NULL,
1376                           to_addr_conv(sh, percpu));
1377         tx = async_xor_val(xor_dest, xor_srcs, 0, count, STRIPE_SIZE,
1378                            &sh->ops.zero_sum_result, &submit);
1379
1380         atomic_inc(&sh->count);
1381         init_async_submit(&submit, ASYNC_TX_ACK, tx, ops_complete_check, sh, NULL);
1382         tx = async_trigger_callback(&submit);
1383 }
1384
1385 static void ops_run_check_pq(struct stripe_head *sh, struct raid5_percpu *percpu, int checkp)
1386 {
1387         struct page **srcs = percpu->scribble;
1388         struct async_submit_ctl submit;
1389         int count;
1390
1391         pr_debug("%s: stripe %llu checkp: %d\n", __func__,
1392                 (unsigned long long)sh->sector, checkp);
1393
1394         count = set_syndrome_sources(srcs, sh);
1395         if (!checkp)
1396                 srcs[count] = NULL;
1397
1398         atomic_inc(&sh->count);
1399         init_async_submit(&submit, ASYNC_TX_ACK, NULL, ops_complete_check,
1400                           sh, to_addr_conv(sh, percpu));
1401         async_syndrome_val(srcs, 0, count+2, STRIPE_SIZE,
1402                            &sh->ops.zero_sum_result, percpu->spare_page, &submit);
1403 }
1404
1405 static void raid_run_ops(struct stripe_head *sh, unsigned long ops_request)
1406 {
1407         int overlap_clear = 0, i, disks = sh->disks;
1408         struct dma_async_tx_descriptor *tx = NULL;
1409         struct r5conf *conf = sh->raid_conf;
1410         int level = conf->level;
1411         struct raid5_percpu *percpu;
1412         unsigned long cpu;
1413
1414         cpu = get_cpu();
1415         percpu = per_cpu_ptr(conf->percpu, cpu);
1416         if (test_bit(STRIPE_OP_BIOFILL, &ops_request)) {
1417                 ops_run_biofill(sh);
1418                 overlap_clear++;
1419         }
1420
1421         if (test_bit(STRIPE_OP_COMPUTE_BLK, &ops_request)) {
1422                 if (level < 6)
1423                         tx = ops_run_compute5(sh, percpu);
1424                 else {
1425                         if (sh->ops.target2 < 0 || sh->ops.target < 0)
1426                                 tx = ops_run_compute6_1(sh, percpu);
1427                         else
1428                                 tx = ops_run_compute6_2(sh, percpu);
1429                 }
1430                 /* terminate the chain if reconstruct is not set to be run */
1431                 if (tx && !test_bit(STRIPE_OP_RECONSTRUCT, &ops_request))
1432                         async_tx_ack(tx);
1433         }
1434
1435         if (test_bit(STRIPE_OP_PREXOR, &ops_request))
1436                 tx = ops_run_prexor(sh, percpu, tx);
1437
1438         if (test_bit(STRIPE_OP_BIODRAIN, &ops_request)) {
1439                 tx = ops_run_biodrain(sh, tx);
1440                 overlap_clear++;
1441         }
1442
1443         if (test_bit(STRIPE_OP_RECONSTRUCT, &ops_request)) {
1444                 if (level < 6)
1445                         ops_run_reconstruct5(sh, percpu, tx);
1446                 else
1447                         ops_run_reconstruct6(sh, percpu, tx);
1448         }
1449
1450         if (test_bit(STRIPE_OP_CHECK, &ops_request)) {
1451                 if (sh->check_state == check_state_run)
1452                         ops_run_check_p(sh, percpu);
1453                 else if (sh->check_state == check_state_run_q)
1454                         ops_run_check_pq(sh, percpu, 0);
1455                 else if (sh->check_state == check_state_run_pq)
1456                         ops_run_check_pq(sh, percpu, 1);
1457                 else
1458                         BUG();
1459         }
1460
1461         if (overlap_clear)
1462                 for (i = disks; i--; ) {
1463                         struct r5dev *dev = &sh->dev[i];
1464                         if (test_and_clear_bit(R5_Overlap, &dev->flags))
1465                                 wake_up(&sh->raid_conf->wait_for_overlap);
1466                 }
1467         put_cpu();
1468 }
1469
1470 static int grow_one_stripe(struct r5conf *conf)
1471 {
1472         struct stripe_head *sh;
1473         sh = kmem_cache_zalloc(conf->slab_cache, GFP_KERNEL);
1474         if (!sh)
1475                 return 0;
1476
1477         sh->raid_conf = conf;
1478
1479         spin_lock_init(&sh->stripe_lock);
1480
1481         if (grow_buffers(sh)) {
1482                 shrink_buffers(sh);
1483                 kmem_cache_free(conf->slab_cache, sh);
1484                 return 0;
1485         }
1486         /* we just created an active stripe so... */
1487         atomic_set(&sh->count, 1);
1488         atomic_inc(&conf->active_stripes);
1489         INIT_LIST_HEAD(&sh->lru);
1490         release_stripe(sh);
1491         return 1;
1492 }
1493
1494 static int grow_stripes(struct r5conf *conf, int num)
1495 {
1496         struct kmem_cache *sc;
1497         int devs = max(conf->raid_disks, conf->previous_raid_disks);
1498
1499         if (conf->mddev->gendisk)
1500                 sprintf(conf->cache_name[0],
1501                         "raid%d-%s", conf->level, mdname(conf->mddev));
1502         else
1503                 sprintf(conf->cache_name[0],
1504                         "raid%d-%p", conf->level, conf->mddev);
1505         sprintf(conf->cache_name[1], "%s-alt", conf->cache_name[0]);
1506
1507         conf->active_name = 0;
1508         sc = kmem_cache_create(conf->cache_name[conf->active_name],
1509                                sizeof(struct stripe_head)+(devs-1)*sizeof(struct r5dev),
1510                                0, 0, NULL);
1511         if (!sc)
1512                 return 1;
1513         conf->slab_cache = sc;
1514         conf->pool_size = devs;
1515         while (num--)
1516                 if (!grow_one_stripe(conf))
1517                         return 1;
1518         return 0;
1519 }
1520
1521 /**
1522  * scribble_len - return the required size of the scribble region
1523  * @num - total number of disks in the array
1524  *
1525  * The size must be enough to contain:
1526  * 1/ a struct page pointer for each device in the array +2
1527  * 2/ room to convert each entry in (1) to its corresponding dma
1528  *    (dma_map_page()) or page (page_address()) address.
1529  *
1530  * Note: the +2 is for the destination buffers of the ddf/raid6 case where we
1531  * calculate over all devices (not just the data blocks), using zeros in place
1532  * of the P and Q blocks.
1533  */
1534 static size_t scribble_len(int num)
1535 {
1536         size_t len;
1537
1538         len = sizeof(struct page *) * (num+2) + sizeof(addr_conv_t) * (num+2);
1539
1540         return len;
1541 }
1542
1543 static int resize_stripes(struct r5conf *conf, int newsize)
1544 {
1545         /* Make all the stripes able to hold 'newsize' devices.
1546          * New slots in each stripe get 'page' set to a new page.
1547          *
1548          * This happens in stages:
1549          * 1/ create a new kmem_cache and allocate the required number of
1550          *    stripe_heads.
1551          * 2/ gather all the old stripe_heads and transfer the pages across
1552          *    to the new stripe_heads.  This will have the side effect of
1553          *    freezing the array as once all stripe_heads have been collected,
1554          *    no IO will be possible.  Old stripe heads are freed once their
1555          *    pages have been transferred over, and the old kmem_cache is
1556          *    freed when all stripes are done.
1557          * 3/ reallocate conf->disks to be suitable bigger.  If this fails,
1558          *    we simple return a failre status - no need to clean anything up.
1559          * 4/ allocate new pages for the new slots in the new stripe_heads.
1560          *    If this fails, we don't bother trying the shrink the
1561          *    stripe_heads down again, we just leave them as they are.
1562          *    As each stripe_head is processed the new one is released into
1563          *    active service.
1564          *
1565          * Once step2 is started, we cannot afford to wait for a write,
1566          * so we use GFP_NOIO allocations.
1567          */
1568         struct stripe_head *osh, *nsh;
1569         LIST_HEAD(newstripes);
1570         struct disk_info *ndisks;
1571         unsigned long cpu;
1572         int err;
1573         struct kmem_cache *sc;
1574         int i;
1575
1576         if (newsize <= conf->pool_size)
1577                 return 0; /* never bother to shrink */
1578
1579         err = md_allow_write(conf->mddev);
1580         if (err)
1581                 return err;
1582
1583         /* Step 1 */
1584         sc = kmem_cache_create(conf->cache_name[1-conf->active_name],
1585                                sizeof(struct stripe_head)+(newsize-1)*sizeof(struct r5dev),
1586                                0, 0, NULL);
1587         if (!sc)
1588                 return -ENOMEM;
1589
1590         for (i = conf->max_nr_stripes; i; i--) {
1591                 nsh = kmem_cache_zalloc(sc, GFP_KERNEL);
1592                 if (!nsh)
1593                         break;
1594
1595                 nsh->raid_conf = conf;
1596                 spin_lock_init(&nsh->stripe_lock);
1597
1598                 list_add(&nsh->lru, &newstripes);
1599         }
1600         if (i) {
1601                 /* didn't get enough, give up */
1602                 while (!list_empty(&newstripes)) {
1603                         nsh = list_entry(newstripes.next, struct stripe_head, lru);
1604                         list_del(&nsh->lru);
1605                         kmem_cache_free(sc, nsh);
1606                 }
1607                 kmem_cache_destroy(sc);
1608                 return -ENOMEM;
1609         }
1610         /* Step 2 - Must use GFP_NOIO now.
1611          * OK, we have enough stripes, start collecting inactive
1612          * stripes and copying them over
1613          */
1614         list_for_each_entry(nsh, &newstripes, lru) {
1615                 spin_lock_irq(&conf->device_lock);
1616                 wait_event_lock_irq(conf->wait_for_stripe,
1617                                     !list_empty(&conf->inactive_list),
1618                                     conf->device_lock);
1619                 osh = get_free_stripe(conf);
1620                 spin_unlock_irq(&conf->device_lock);
1621                 atomic_set(&nsh->count, 1);
1622                 for(i=0; i<conf->pool_size; i++)
1623                         nsh->dev[i].page = osh->dev[i].page;
1624                 for( ; i<newsize; i++)
1625                         nsh->dev[i].page = NULL;
1626                 kmem_cache_free(conf->slab_cache, osh);
1627         }
1628         kmem_cache_destroy(conf->slab_cache);
1629
1630         /* Step 3.
1631          * At this point, we are holding all the stripes so the array
1632          * is completely stalled, so now is a good time to resize
1633          * conf->disks and the scribble region
1634          */
1635         ndisks = kzalloc(newsize * sizeof(struct disk_info), GFP_NOIO);
1636         if (ndisks) {
1637                 for (i=0; i<conf->raid_disks; i++)
1638                         ndisks[i] = conf->disks[i];
1639                 kfree(conf->disks);
1640                 conf->disks = ndisks;
1641         } else
1642                 err = -ENOMEM;
1643
1644         get_online_cpus();
1645         conf->scribble_len = scribble_len(newsize);
1646         for_each_present_cpu(cpu) {
1647                 struct raid5_percpu *percpu;
1648                 void *scribble;
1649
1650                 percpu = per_cpu_ptr(conf->percpu, cpu);
1651                 scribble = kmalloc(conf->scribble_len, GFP_NOIO);
1652
1653                 if (scribble) {
1654                         kfree(percpu->scribble);
1655                         percpu->scribble = scribble;
1656                 } else {
1657                         err = -ENOMEM;
1658                         break;
1659                 }
1660         }
1661         put_online_cpus();
1662
1663         /* Step 4, return new stripes to service */
1664         while(!list_empty(&newstripes)) {
1665                 nsh = list_entry(newstripes.next, struct stripe_head, lru);
1666                 list_del_init(&nsh->lru);
1667
1668                 for (i=conf->raid_disks; i < newsize; i++)
1669                         if (nsh->dev[i].page == NULL) {
1670                                 struct page *p = alloc_page(GFP_NOIO);
1671                                 nsh->dev[i].page = p;
1672                                 if (!p)
1673                                         err = -ENOMEM;
1674                         }
1675                 release_stripe(nsh);
1676         }
1677         /* critical section pass, GFP_NOIO no longer needed */
1678
1679         conf->slab_cache = sc;
1680         conf->active_name = 1-conf->active_name;
1681         conf->pool_size = newsize;
1682         return err;
1683 }
1684
1685 static int drop_one_stripe(struct r5conf *conf)
1686 {
1687         struct stripe_head *sh;
1688
1689         spin_lock_irq(&conf->device_lock);
1690         sh = get_free_stripe(conf);
1691         spin_unlock_irq(&conf->device_lock);
1692         if (!sh)
1693                 return 0;
1694         BUG_ON(atomic_read(&sh->count));
1695         shrink_buffers(sh);
1696         kmem_cache_free(conf->slab_cache, sh);
1697         atomic_dec(&conf->active_stripes);
1698         return 1;
1699 }
1700
1701 static void shrink_stripes(struct r5conf *conf)
1702 {
1703         while (drop_one_stripe(conf))
1704                 ;
1705
1706         if (conf->slab_cache)
1707                 kmem_cache_destroy(conf->slab_cache);
1708         conf->slab_cache = NULL;
1709 }
1710
1711 static void raid5_end_read_request(struct bio * bi, int error)
1712 {
1713         struct stripe_head *sh = bi->bi_private;
1714         struct r5conf *conf = sh->raid_conf;
1715         int disks = sh->disks, i;
1716         int uptodate = test_bit(BIO_UPTODATE, &bi->bi_flags);
1717         char b[BDEVNAME_SIZE];
1718         struct md_rdev *rdev = NULL;
1719         sector_t s;
1720
1721         for (i=0 ; i<disks; i++)
1722                 if (bi == &sh->dev[i].req)
1723                         break;
1724
1725         pr_debug("end_read_request %llu/%d, count: %d, uptodate %d.\n",
1726                 (unsigned long long)sh->sector, i, atomic_read(&sh->count),
1727                 uptodate);
1728         if (i == disks) {
1729                 BUG();
1730                 return;
1731         }
1732         if (test_bit(R5_ReadRepl, &sh->dev[i].flags))
1733                 /* If replacement finished while this request was outstanding,
1734                  * 'replacement' might be NULL already.
1735                  * In that case it moved down to 'rdev'.
1736                  * rdev is not removed until all requests are finished.
1737                  */
1738                 rdev = conf->disks[i].replacement;
1739         if (!rdev)
1740                 rdev = conf->disks[i].rdev;
1741
1742         if (use_new_offset(conf, sh))
1743                 s = sh->sector + rdev->new_data_offset;
1744         else
1745                 s = sh->sector + rdev->data_offset;
1746         if (uptodate) {
1747                 set_bit(R5_UPTODATE, &sh->dev[i].flags);
1748                 if (test_bit(R5_ReadError, &sh->dev[i].flags)) {
1749                         /* Note that this cannot happen on a
1750                          * replacement device.  We just fail those on
1751                          * any error
1752                          */
1753                         printk_ratelimited(
1754                                 KERN_INFO
1755                                 "md/raid:%s: read error corrected"
1756                                 " (%lu sectors at %llu on %s)\n",
1757                                 mdname(conf->mddev), STRIPE_SECTORS,
1758                                 (unsigned long long)s,
1759                                 bdevname(rdev->bdev, b));
1760                         atomic_add(STRIPE_SECTORS, &rdev->corrected_errors);
1761                         clear_bit(R5_ReadError, &sh->dev[i].flags);
1762                         clear_bit(R5_ReWrite, &sh->dev[i].flags);
1763                 } else if (test_bit(R5_ReadNoMerge, &sh->dev[i].flags))
1764                         clear_bit(R5_ReadNoMerge, &sh->dev[i].flags);
1765
1766                 if (atomic_read(&rdev->read_errors))
1767                         atomic_set(&rdev->read_errors, 0);
1768         } else {
1769                 const char *bdn = bdevname(rdev->bdev, b);
1770                 int retry = 0;
1771                 int set_bad = 0;
1772
1773                 clear_bit(R5_UPTODATE, &sh->dev[i].flags);
1774                 atomic_inc(&rdev->read_errors);
1775                 if (test_bit(R5_ReadRepl, &sh->dev[i].flags))
1776                         printk_ratelimited(
1777                                 KERN_WARNING
1778                                 "md/raid:%s: read error on replacement device "
1779                                 "(sector %llu on %s).\n",
1780                                 mdname(conf->mddev),
1781                                 (unsigned long long)s,
1782                                 bdn);
1783                 else if (conf->mddev->degraded >= conf->max_degraded) {
1784                         set_bad = 1;
1785                         printk_ratelimited(
1786                                 KERN_WARNING
1787                                 "md/raid:%s: read error not correctable "
1788                                 "(sector %llu on %s).\n",
1789                                 mdname(conf->mddev),
1790                                 (unsigned long long)s,
1791                                 bdn);
1792                 } else if (test_bit(R5_ReWrite, &sh->dev[i].flags)) {
1793                         /* Oh, no!!! */
1794                         set_bad = 1;
1795                         printk_ratelimited(
1796                                 KERN_WARNING
1797                                 "md/raid:%s: read error NOT corrected!! "
1798                                 "(sector %llu on %s).\n",
1799                                 mdname(conf->mddev),
1800                                 (unsigned long long)s,
1801                                 bdn);
1802                 } else if (atomic_read(&rdev->read_errors)
1803                          > conf->max_nr_stripes)
1804                         printk(KERN_WARNING
1805                                "md/raid:%s: Too many read errors, failing device %s.\n",
1806                                mdname(conf->mddev), bdn);
1807                 else
1808                         retry = 1;
1809                 if (retry)
1810                         if (test_bit(R5_ReadNoMerge, &sh->dev[i].flags)) {
1811                                 set_bit(R5_ReadError, &sh->dev[i].flags);
1812                                 clear_bit(R5_ReadNoMerge, &sh->dev[i].flags);
1813                         } else
1814                                 set_bit(R5_ReadNoMerge, &sh->dev[i].flags);
1815                 else {
1816                         clear_bit(R5_ReadError, &sh->dev[i].flags);
1817                         clear_bit(R5_ReWrite, &sh->dev[i].flags);
1818                         if (!(set_bad
1819                               && test_bit(In_sync, &rdev->flags)
1820                               && rdev_set_badblocks(
1821                                       rdev, sh->sector, STRIPE_SECTORS, 0)))
1822                                 md_error(conf->mddev, rdev);
1823                 }
1824         }
1825         rdev_dec_pending(rdev, conf->mddev);
1826         clear_bit(R5_LOCKED, &sh->dev[i].flags);
1827         set_bit(STRIPE_HANDLE, &sh->state);
1828         release_stripe(sh);
1829 }
1830
1831 static void raid5_end_write_request(struct bio *bi, int error)
1832 {
1833         struct stripe_head *sh = bi->bi_private;
1834         struct r5conf *conf = sh->raid_conf;
1835         int disks = sh->disks, i;
1836         struct md_rdev *uninitialized_var(rdev);
1837         int uptodate = test_bit(BIO_UPTODATE, &bi->bi_flags);
1838         sector_t first_bad;
1839         int bad_sectors;
1840         int replacement = 0;
1841
1842         for (i = 0 ; i < disks; i++) {
1843                 if (bi == &sh->dev[i].req) {
1844                         rdev = conf->disks[i].rdev;
1845                         break;
1846                 }
1847                 if (bi == &sh->dev[i].rreq) {
1848                         rdev = conf->disks[i].replacement;
1849                         if (rdev)
1850                                 replacement = 1;
1851                         else
1852                                 /* rdev was removed and 'replacement'
1853                                  * replaced it.  rdev is not removed
1854                                  * until all requests are finished.
1855                                  */
1856                                 rdev = conf->disks[i].rdev;
1857                         break;
1858                 }
1859         }
1860         pr_debug("end_write_request %llu/%d, count %d, uptodate: %d.\n",
1861                 (unsigned long long)sh->sector, i, atomic_read(&sh->count),
1862                 uptodate);
1863         if (i == disks) {
1864                 BUG();
1865                 return;
1866         }
1867
1868         if (replacement) {
1869                 if (!uptodate)
1870                         md_error(conf->mddev, rdev);
1871                 else if (is_badblock(rdev, sh->sector,
1872                                      STRIPE_SECTORS,
1873                                      &first_bad, &bad_sectors))
1874                         set_bit(R5_MadeGoodRepl, &sh->dev[i].flags);
1875         } else {
1876                 if (!uptodate) {
1877                         set_bit(WriteErrorSeen, &rdev->flags);
1878                         set_bit(R5_WriteError, &sh->dev[i].flags);
1879                         if (!test_and_set_bit(WantReplacement, &rdev->flags))
1880                                 set_bit(MD_RECOVERY_NEEDED,
1881                                         &rdev->mddev->recovery);
1882                 } else if (is_badblock(rdev, sh->sector,
1883                                        STRIPE_SECTORS,
1884                                        &first_bad, &bad_sectors))
1885                         set_bit(R5_MadeGood, &sh->dev[i].flags);
1886         }
1887         rdev_dec_pending(rdev, conf->mddev);
1888
1889         if (!test_and_clear_bit(R5_DOUBLE_LOCKED, &sh->dev[i].flags))
1890                 clear_bit(R5_LOCKED, &sh->dev[i].flags);
1891         set_bit(STRIPE_HANDLE, &sh->state);
1892         release_stripe(sh);
1893 }
1894
1895 static sector_t compute_blocknr(struct stripe_head *sh, int i, int previous);
1896         
1897 static void raid5_build_block(struct stripe_head *sh, int i, int previous)
1898 {
1899         struct r5dev *dev = &sh->dev[i];
1900
1901         bio_init(&dev->req);
1902         dev->req.bi_io_vec = &dev->vec;
1903         dev->req.bi_vcnt++;
1904         dev->req.bi_max_vecs++;
1905         dev->req.bi_private = sh;
1906         dev->vec.bv_page = dev->page;
1907
1908         bio_init(&dev->rreq);
1909         dev->rreq.bi_io_vec = &dev->rvec;
1910         dev->rreq.bi_vcnt++;
1911         dev->rreq.bi_max_vecs++;
1912         dev->rreq.bi_private = sh;
1913         dev->rvec.bv_page = dev->page;
1914
1915         dev->flags = 0;
1916         dev->sector = compute_blocknr(sh, i, previous);
1917 }
1918
1919 static void error(struct mddev *mddev, struct md_rdev *rdev)
1920 {
1921         char b[BDEVNAME_SIZE];
1922         struct r5conf *conf = mddev->private;
1923         unsigned long flags;
1924         pr_debug("raid456: error called\n");
1925
1926         spin_lock_irqsave(&conf->device_lock, flags);
1927         clear_bit(In_sync, &rdev->flags);
1928         mddev->degraded = calc_degraded(conf);
1929         spin_unlock_irqrestore(&conf->device_lock, flags);
1930         set_bit(MD_RECOVERY_INTR, &mddev->recovery);
1931
1932         set_bit(Blocked, &rdev->flags);
1933         set_bit(Faulty, &rdev->flags);
1934         set_bit(MD_CHANGE_DEVS, &mddev->flags);
1935         printk(KERN_ALERT
1936                "md/raid:%s: Disk failure on %s, disabling device.\n"
1937                "md/raid:%s: Operation continuing on %d devices.\n",
1938                mdname(mddev),
1939                bdevname(rdev->bdev, b),
1940                mdname(mddev),
1941                conf->raid_disks - mddev->degraded);
1942 }
1943
1944 /*
1945  * Input: a 'big' sector number,
1946  * Output: index of the data and parity disk, and the sector # in them.
1947  */
1948 static sector_t raid5_compute_sector(struct r5conf *conf, sector_t r_sector,
1949                                      int previous, int *dd_idx,
1950                                      struct stripe_head *sh)
1951 {
1952         sector_t stripe, stripe2;
1953         sector_t chunk_number;
1954         unsigned int chunk_offset;
1955         int pd_idx, qd_idx;
1956         int ddf_layout = 0;
1957         sector_t new_sector;
1958         int algorithm = previous ? conf->prev_algo
1959                                  : conf->algorithm;
1960         int sectors_per_chunk = previous ? conf->prev_chunk_sectors
1961                                          : conf->chunk_sectors;
1962         int raid_disks = previous ? conf->previous_raid_disks
1963                                   : conf->raid_disks;
1964         int data_disks = raid_disks - conf->max_degraded;
1965
1966         /* First compute the information on this sector */
1967
1968         /*
1969          * Compute the chunk number and the sector offset inside the chunk
1970          */
1971         chunk_offset = sector_div(r_sector, sectors_per_chunk);
1972         chunk_number = r_sector;
1973
1974         /*
1975          * Compute the stripe number
1976          */
1977         stripe = chunk_number;
1978         *dd_idx = sector_div(stripe, data_disks);
1979         stripe2 = stripe;
1980         /*
1981          * Select the parity disk based on the user selected algorithm.
1982          */
1983         pd_idx = qd_idx = -1;
1984         switch(conf->level) {
1985         case 4:
1986                 pd_idx = data_disks;
1987                 break;
1988         case 5:
1989                 switch (algorithm) {
1990                 case ALGORITHM_LEFT_ASYMMETRIC:
1991                         pd_idx = data_disks - sector_div(stripe2, raid_disks);
1992                         if (*dd_idx >= pd_idx)
1993                                 (*dd_idx)++;
1994                         break;
1995                 case ALGORITHM_RIGHT_ASYMMETRIC:
1996                         pd_idx = sector_div(stripe2, raid_disks);
1997                         if (*dd_idx >= pd_idx)
1998                                 (*dd_idx)++;
1999                         break;
2000                 case ALGORITHM_LEFT_SYMMETRIC:
2001                         pd_idx = data_disks - sector_div(stripe2, raid_disks);
2002                         *dd_idx = (pd_idx + 1 + *dd_idx) % raid_disks;
2003                         break;
2004                 case ALGORITHM_RIGHT_SYMMETRIC:
2005                         pd_idx = sector_div(stripe2, raid_disks);
2006                         *dd_idx = (pd_idx + 1 + *dd_idx) % raid_disks;
2007                         break;
2008                 case ALGORITHM_PARITY_0:
2009                         pd_idx = 0;
2010                         (*dd_idx)++;
2011                         break;
2012                 case ALGORITHM_PARITY_N:
2013                         pd_idx = data_disks;
2014                         break;
2015                 default:
2016                         BUG();
2017                 }
2018                 break;
2019         case 6:
2020
2021                 switch (algorithm) {
2022                 case ALGORITHM_LEFT_ASYMMETRIC:
2023                         pd_idx = raid_disks - 1 - sector_div(stripe2, raid_disks);
2024                         qd_idx = pd_idx + 1;
2025                         if (pd_idx == raid_disks-1) {
2026                                 (*dd_idx)++;    /* Q D D D P */
2027                                 qd_idx = 0;
2028                         } else if (*dd_idx >= pd_idx)
2029                                 (*dd_idx) += 2; /* D D P Q D */
2030                         break;
2031                 case ALGORITHM_RIGHT_ASYMMETRIC:
2032                         pd_idx = sector_div(stripe2, raid_disks);
2033                         qd_idx = pd_idx + 1;
2034                         if (pd_idx == raid_disks-1) {
2035                                 (*dd_idx)++;    /* Q D D D P */
2036                                 qd_idx = 0;
2037                         } else if (*dd_idx >= pd_idx)
2038                                 (*dd_idx) += 2; /* D D P Q D */
2039                         break;
2040                 case ALGORITHM_LEFT_SYMMETRIC:
2041                         pd_idx = raid_disks - 1 - sector_div(stripe2, raid_disks);
2042                         qd_idx = (pd_idx + 1) % raid_disks;
2043                         *dd_idx = (pd_idx + 2 + *dd_idx) % raid_disks;
2044                         break;
2045                 case ALGORITHM_RIGHT_SYMMETRIC:
2046                         pd_idx = sector_div(stripe2, raid_disks);
2047                         qd_idx = (pd_idx + 1) % raid_disks;
2048                         *dd_idx = (pd_idx + 2 + *dd_idx) % raid_disks;
2049                         break;
2050
2051                 case ALGORITHM_PARITY_0:
2052                         pd_idx = 0;
2053                         qd_idx = 1;
2054                         (*dd_idx) += 2;
2055                         break;
2056                 case ALGORITHM_PARITY_N:
2057                         pd_idx = data_disks;
2058                         qd_idx = data_disks + 1;
2059                         break;
2060
2061                 case ALGORITHM_ROTATING_ZERO_RESTART:
2062                         /* Exactly the same as RIGHT_ASYMMETRIC, but or
2063                          * of blocks for computing Q is different.
2064                          */
2065                         pd_idx = sector_div(stripe2, raid_disks);
2066                         qd_idx = pd_idx + 1;
2067                         if (pd_idx == raid_disks-1) {
2068                                 (*dd_idx)++;    /* Q D D D P */
2069                                 qd_idx = 0;
2070                         } else if (*dd_idx >= pd_idx)
2071                                 (*dd_idx) += 2; /* D D P Q D */
2072                         ddf_layout = 1;
2073                         break;
2074
2075                 case ALGORITHM_ROTATING_N_RESTART:
2076                         /* Same a left_asymmetric, by first stripe is
2077                          * D D D P Q  rather than
2078                          * Q D D D P
2079                          */
2080                         stripe2 += 1;
2081                         pd_idx = raid_disks - 1 - sector_div(stripe2, raid_disks);
2082                         qd_idx = pd_idx + 1;
2083                         if (pd_idx == raid_disks-1) {
2084                                 (*dd_idx)++;    /* Q D D D P */
2085                                 qd_idx = 0;
2086                         } else if (*dd_idx >= pd_idx)
2087                                 (*dd_idx) += 2; /* D D P Q D */
2088                         ddf_layout = 1;
2089                         break;
2090
2091                 case ALGORITHM_ROTATING_N_CONTINUE:
2092                         /* Same as left_symmetric but Q is before P */
2093                         pd_idx = raid_disks - 1 - sector_div(stripe2, raid_disks);
2094                         qd_idx = (pd_idx + raid_disks - 1) % raid_disks;
2095                         *dd_idx = (pd_idx + 1 + *dd_idx) % raid_disks;
2096                         ddf_layout = 1;
2097                         break;
2098
2099                 case ALGORITHM_LEFT_ASYMMETRIC_6:
2100                         /* RAID5 left_asymmetric, with Q on last device */
2101                         pd_idx = data_disks - 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_RIGHT_ASYMMETRIC_6:
2108                         pd_idx = sector_div(stripe2, raid_disks-1);
2109                         if (*dd_idx >= pd_idx)
2110                                 (*dd_idx)++;
2111                         qd_idx = raid_disks - 1;
2112                         break;
2113
2114                 case ALGORITHM_LEFT_SYMMETRIC_6:
2115                         pd_idx = data_disks - sector_div(stripe2, raid_disks-1);
2116                         *dd_idx = (pd_idx + 1 + *dd_idx) % (raid_disks-1);
2117                         qd_idx = raid_disks - 1;
2118                         break;
2119
2120                 case ALGORITHM_RIGHT_SYMMETRIC_6:
2121                         pd_idx = sector_div(stripe2, raid_disks-1);
2122                         *dd_idx = (pd_idx + 1 + *dd_idx) % (raid_disks-1);
2123                         qd_idx = raid_disks - 1;
2124                         break;
2125
2126                 case ALGORITHM_PARITY_0_6:
2127                         pd_idx = 0;
2128                         (*dd_idx)++;
2129                         qd_idx = raid_disks - 1;
2130                         break;
2131
2132                 default:
2133                         BUG();
2134                 }
2135                 break;
2136         }
2137
2138         if (sh) {
2139                 sh->pd_idx = pd_idx;
2140                 sh->qd_idx = qd_idx;
2141                 sh->ddf_layout = ddf_layout;
2142         }
2143         /*
2144          * Finally, compute the new sector number
2145          */
2146         new_sector = (sector_t)stripe * sectors_per_chunk + chunk_offset;
2147         return new_sector;
2148 }
2149
2150
2151 static sector_t compute_blocknr(struct stripe_head *sh, int i, int previous)
2152 {
2153         struct r5conf *conf = sh->raid_conf;
2154         int raid_disks = sh->disks;
2155         int data_disks = raid_disks - conf->max_degraded;
2156         sector_t new_sector = sh->sector, check;
2157         int sectors_per_chunk = previous ? conf->prev_chunk_sectors
2158                                          : conf->chunk_sectors;
2159         int algorithm = previous ? conf->prev_algo
2160                                  : conf->algorithm;
2161         sector_t stripe;
2162         int chunk_offset;
2163         sector_t chunk_number;
2164         int dummy1, dd_idx = i;
2165         sector_t r_sector;
2166         struct stripe_head sh2;
2167
2168
2169         chunk_offset = sector_div(new_sector, sectors_per_chunk);
2170         stripe = new_sector;
2171
2172         if (i == sh->pd_idx)
2173                 return 0;
2174         switch(conf->level) {
2175         case 4: break;
2176         case 5:
2177                 switch (algorithm) {
2178                 case ALGORITHM_LEFT_ASYMMETRIC:
2179                 case ALGORITHM_RIGHT_ASYMMETRIC:
2180                         if (i > sh->pd_idx)
2181                                 i--;
2182                         break;
2183                 case ALGORITHM_LEFT_SYMMETRIC:
2184                 case ALGORITHM_RIGHT_SYMMETRIC:
2185                         if (i < sh->pd_idx)
2186                                 i += raid_disks;
2187                         i -= (sh->pd_idx + 1);
2188                         break;
2189                 case ALGORITHM_PARITY_0:
2190                         i -= 1;
2191                         break;
2192                 case ALGORITHM_PARITY_N:
2193                         break;
2194                 default:
2195                         BUG();
2196                 }
2197                 break;
2198         case 6:
2199                 if (i == sh->qd_idx)
2200                         return 0; /* It is the Q disk */
2201                 switch (algorithm) {
2202                 case ALGORITHM_LEFT_ASYMMETRIC:
2203                 case ALGORITHM_RIGHT_ASYMMETRIC:
2204                 case ALGORITHM_ROTATING_ZERO_RESTART:
2205                 case ALGORITHM_ROTATING_N_RESTART:
2206                         if (sh->pd_idx == raid_disks-1)
2207                                 i--;    /* Q D D D P */
2208                         else if (i > sh->pd_idx)
2209                                 i -= 2; /* D D P Q D */
2210                         break;
2211                 case ALGORITHM_LEFT_SYMMETRIC:
2212                 case ALGORITHM_RIGHT_SYMMETRIC:
2213                         if (sh->pd_idx == raid_disks-1)
2214                                 i--; /* Q D D D P */
2215                         else {
2216                                 /* D D P Q D */
2217                                 if (i < sh->pd_idx)
2218                                         i += raid_disks;
2219                                 i -= (sh->pd_idx + 2);
2220                         }
2221                         break;
2222                 case ALGORITHM_PARITY_0:
2223                         i -= 2;
2224                         break;
2225                 case ALGORITHM_PARITY_N:
2226                         break;
2227                 case ALGORITHM_ROTATING_N_CONTINUE:
2228                         /* Like left_symmetric, but P is before Q */
2229                         if (sh->pd_idx == 0)
2230                                 i--;    /* P D D D Q */
2231                         else {
2232                                 /* D D Q P D */
2233                                 if (i < sh->pd_idx)
2234                                         i += raid_disks;
2235                                 i -= (sh->pd_idx + 1);
2236                         }
2237                         break;
2238                 case ALGORITHM_LEFT_ASYMMETRIC_6:
2239                 case ALGORITHM_RIGHT_ASYMMETRIC_6:
2240                         if (i > sh->pd_idx)
2241                                 i--;
2242                         break;
2243                 case ALGORITHM_LEFT_SYMMETRIC_6:
2244                 case ALGORITHM_RIGHT_SYMMETRIC_6:
2245                         if (i < sh->pd_idx)
2246                                 i += data_disks + 1;
2247                         i -= (sh->pd_idx + 1);
2248                         break;
2249                 case ALGORITHM_PARITY_0_6:
2250                         i -= 1;
2251                         break;
2252                 default:
2253                         BUG();
2254                 }
2255                 break;
2256         }
2257
2258         chunk_number = stripe * data_disks + i;
2259         r_sector = chunk_number * sectors_per_chunk + chunk_offset;
2260
2261         check = raid5_compute_sector(conf, r_sector,
2262                                      previous, &dummy1, &sh2);
2263         if (check != sh->sector || dummy1 != dd_idx || sh2.pd_idx != sh->pd_idx
2264                 || sh2.qd_idx != sh->qd_idx) {
2265                 printk(KERN_ERR "md/raid:%s: compute_blocknr: map not correct\n",
2266                        mdname(conf->mddev));
2267                 return 0;
2268         }
2269         return r_sector;
2270 }
2271
2272
2273 static void
2274 schedule_reconstruction(struct stripe_head *sh, struct stripe_head_state *s,
2275                          int rcw, int expand)
2276 {
2277         int i, pd_idx = sh->pd_idx, disks = sh->disks;
2278         struct r5conf *conf = sh->raid_conf;
2279         int level = conf->level;
2280
2281         if (rcw) {
2282                 /* if we are not expanding this is a proper write request, and
2283                  * there will be bios with new data to be drained into the
2284                  * stripe cache
2285                  */
2286                 if (!expand) {
2287                         sh->reconstruct_state = reconstruct_state_drain_run;
2288                         set_bit(STRIPE_OP_BIODRAIN, &s->ops_request);
2289                 } else
2290                         sh->reconstruct_state = reconstruct_state_run;
2291
2292                 set_bit(STRIPE_OP_RECONSTRUCT, &s->ops_request);
2293
2294                 for (i = disks; i--; ) {
2295                         struct r5dev *dev = &sh->dev[i];
2296
2297                         if (dev->towrite) {
2298                                 set_bit(R5_LOCKED, &dev->flags);
2299                                 set_bit(R5_Wantdrain, &dev->flags);
2300                                 if (!expand)
2301                                         clear_bit(R5_UPTODATE, &dev->flags);
2302                                 s->locked++;
2303                         }
2304                 }
2305                 if (s->locked + conf->max_degraded == disks)
2306                         if (!test_and_set_bit(STRIPE_FULL_WRITE, &sh->state))
2307                                 atomic_inc(&conf->pending_full_writes);
2308         } else {
2309                 BUG_ON(level == 6);
2310                 BUG_ON(!(test_bit(R5_UPTODATE, &sh->dev[pd_idx].flags) ||
2311                         test_bit(R5_Wantcompute, &sh->dev[pd_idx].flags)));
2312
2313                 sh->reconstruct_state = reconstruct_state_prexor_drain_run;
2314                 set_bit(STRIPE_OP_PREXOR, &s->ops_request);
2315                 set_bit(STRIPE_OP_BIODRAIN, &s->ops_request);
2316                 set_bit(STRIPE_OP_RECONSTRUCT, &s->ops_request);
2317
2318                 for (i = disks; i--; ) {
2319                         struct r5dev *dev = &sh->dev[i];
2320                         if (i == pd_idx)
2321                                 continue;
2322
2323                         if (dev->towrite &&
2324                             (test_bit(R5_UPTODATE, &dev->flags) ||
2325                              test_bit(R5_Wantcompute, &dev->flags))) {
2326                                 set_bit(R5_Wantdrain, &dev->flags);
2327                                 set_bit(R5_LOCKED, &dev->flags);
2328                                 clear_bit(R5_UPTODATE, &dev->flags);
2329                                 s->locked++;
2330                         }
2331                 }
2332         }
2333
2334         /* keep the parity disk(s) locked while asynchronous operations
2335          * are in flight
2336          */
2337         set_bit(R5_LOCKED, &sh->dev[pd_idx].flags);
2338         clear_bit(R5_UPTODATE, &sh->dev[pd_idx].flags);
2339         s->locked++;
2340
2341         if (level == 6) {
2342                 int qd_idx = sh->qd_idx;
2343                 struct r5dev *dev = &sh->dev[qd_idx];
2344
2345                 set_bit(R5_LOCKED, &dev->flags);
2346                 clear_bit(R5_UPTODATE, &dev->flags);
2347                 s->locked++;
2348         }
2349
2350         pr_debug("%s: stripe %llu locked: %d ops_request: %lx\n",
2351                 __func__, (unsigned long long)sh->sector,
2352                 s->locked, s->ops_request);
2353 }
2354
2355 /*
2356  * Each stripe/dev can have one or more bion attached.
2357  * toread/towrite point to the first in a chain.
2358  * The bi_next chain must be in order.
2359  */
2360 static int add_stripe_bio(struct stripe_head *sh, struct bio *bi, int dd_idx, int forwrite)
2361 {
2362         struct bio **bip;
2363         struct r5conf *conf = sh->raid_conf;
2364         int firstwrite=0;
2365
2366         pr_debug("adding bi b#%llu to stripe s#%llu\n",
2367                 (unsigned long long)bi->bi_sector,
2368                 (unsigned long long)sh->sector);
2369
2370         /*
2371          * If several bio share a stripe. The bio bi_phys_segments acts as a
2372          * reference count to avoid race. The reference count should already be
2373          * increased before this function is called (for example, in
2374          * make_request()), so other bio sharing this stripe will not free the
2375          * stripe. If a stripe is owned by one stripe, the stripe lock will
2376          * protect it.
2377          */
2378         spin_lock_irq(&sh->stripe_lock);
2379         if (forwrite) {
2380                 bip = &sh->dev[dd_idx].towrite;
2381                 if (*bip == NULL)
2382                         firstwrite = 1;
2383         } else
2384                 bip = &sh->dev[dd_idx].toread;
2385         while (*bip && (*bip)->bi_sector < bi->bi_sector) {
2386                 if (bio_end_sector(*bip) > bi->bi_sector)
2387                         goto overlap;
2388                 bip = & (*bip)->bi_next;
2389         }
2390         if (*bip && (*bip)->bi_sector < bio_end_sector(bi))
2391                 goto overlap;
2392
2393         BUG_ON(*bip && bi->bi_next && (*bip) != bi->bi_next);
2394         if (*bip)
2395                 bi->bi_next = *bip;
2396         *bip = bi;
2397         raid5_inc_bi_active_stripes(bi);
2398
2399         if (forwrite) {
2400                 /* check if page is covered */
2401                 sector_t sector = sh->dev[dd_idx].sector;
2402                 for (bi=sh->dev[dd_idx].towrite;
2403                      sector < sh->dev[dd_idx].sector + STRIPE_SECTORS &&
2404                              bi && bi->bi_sector <= sector;
2405                      bi = r5_next_bio(bi, sh->dev[dd_idx].sector)) {
2406                         if (bio_end_sector(bi) >= sector)
2407                                 sector = bio_end_sector(bi);
2408                 }
2409                 if (sector >= sh->dev[dd_idx].sector + STRIPE_SECTORS)
2410                         set_bit(R5_OVERWRITE, &sh->dev[dd_idx].flags);
2411         }
2412
2413         pr_debug("added bi b#%llu to stripe s#%llu, disk %d.\n",
2414                 (unsigned long long)(*bip)->bi_sector,
2415                 (unsigned long long)sh->sector, dd_idx);
2416         spin_unlock_irq(&sh->stripe_lock);
2417
2418         if (conf->mddev->bitmap && firstwrite) {
2419                 bitmap_startwrite(conf->mddev->bitmap, sh->sector,
2420                                   STRIPE_SECTORS, 0);
2421                 sh->bm_seq = conf->seq_flush+1;
2422                 set_bit(STRIPE_BIT_DELAY, &sh->state);
2423         }
2424         return 1;
2425
2426  overlap:
2427         set_bit(R5_Overlap, &sh->dev[dd_idx].flags);
2428         spin_unlock_irq(&sh->stripe_lock);
2429         return 0;
2430 }
2431
2432 static void end_reshape(struct r5conf *conf);
2433
2434 static void stripe_set_idx(sector_t stripe, struct r5conf *conf, int previous,
2435                             struct stripe_head *sh)
2436 {
2437         int sectors_per_chunk =
2438                 previous ? conf->prev_chunk_sectors : conf->chunk_sectors;
2439         int dd_idx;
2440         int chunk_offset = sector_div(stripe, sectors_per_chunk);
2441         int disks = previous ? conf->previous_raid_disks : conf->raid_disks;
2442
2443         raid5_compute_sector(conf,
2444                              stripe * (disks - conf->max_degraded)
2445                              *sectors_per_chunk + chunk_offset,
2446                              previous,
2447                              &dd_idx, sh);
2448 }
2449
2450 static void
2451 handle_failed_stripe(struct r5conf *conf, struct stripe_head *sh,
2452                                 struct stripe_head_state *s, int disks,
2453                                 struct bio **return_bi)
2454 {
2455         int i;
2456         for (i = disks; i--; ) {
2457                 struct bio *bi;
2458                 int bitmap_end = 0;
2459
2460                 if (test_bit(R5_ReadError, &sh->dev[i].flags)) {
2461                         struct md_rdev *rdev;
2462                         rcu_read_lock();
2463                         rdev = rcu_dereference(conf->disks[i].rdev);
2464                         if (rdev && test_bit(In_sync, &rdev->flags))
2465                                 atomic_inc(&rdev->nr_pending);
2466                         else
2467                                 rdev = NULL;
2468                         rcu_read_unlock();
2469                         if (rdev) {
2470                                 if (!rdev_set_badblocks(
2471                                             rdev,
2472                                             sh->sector,
2473                                             STRIPE_SECTORS, 0))
2474                                         md_error(conf->mddev, rdev);
2475                                 rdev_dec_pending(rdev, conf->mddev);
2476                         }
2477                 }
2478                 spin_lock_irq(&sh->stripe_lock);
2479                 /* fail all writes first */
2480                 bi = sh->dev[i].towrite;
2481                 sh->dev[i].towrite = NULL;
2482                 spin_unlock_irq(&sh->stripe_lock);
2483                 if (bi)
2484                         bitmap_end = 1;
2485
2486                 if (test_and_clear_bit(R5_Overlap, &sh->dev[i].flags))
2487                         wake_up(&conf->wait_for_overlap);
2488
2489                 while (bi && bi->bi_sector <
2490                         sh->dev[i].sector + STRIPE_SECTORS) {
2491                         struct bio *nextbi = r5_next_bio(bi, sh->dev[i].sector);
2492                         clear_bit(BIO_UPTODATE, &bi->bi_flags);
2493                         if (!raid5_dec_bi_active_stripes(bi)) {
2494                                 md_write_end(conf->mddev);
2495                                 bi->bi_next = *return_bi;
2496                                 *return_bi = bi;
2497                         }
2498                         bi = nextbi;
2499                 }
2500                 if (bitmap_end)
2501                         bitmap_endwrite(conf->mddev->bitmap, sh->sector,
2502                                 STRIPE_SECTORS, 0, 0);
2503                 bitmap_end = 0;
2504                 /* and fail all 'written' */
2505                 bi = sh->dev[i].written;
2506                 sh->dev[i].written = NULL;
2507                 if (bi) bitmap_end = 1;
2508                 while (bi && bi->bi_sector <
2509                        sh->dev[i].sector + STRIPE_SECTORS) {
2510                         struct bio *bi2 = r5_next_bio(bi, sh->dev[i].sector);
2511                         clear_bit(BIO_UPTODATE, &bi->bi_flags);
2512                         if (!raid5_dec_bi_active_stripes(bi)) {
2513                                 md_write_end(conf->mddev);
2514                                 bi->bi_next = *return_bi;
2515                                 *return_bi = bi;
2516                         }
2517                         bi = bi2;
2518                 }
2519
2520                 /* fail any reads if this device is non-operational and
2521                  * the data has not reached the cache yet.
2522                  */
2523                 if (!test_bit(R5_Wantfill, &sh->dev[i].flags) &&
2524                     (!test_bit(R5_Insync, &sh->dev[i].flags) ||
2525                       test_bit(R5_ReadError, &sh->dev[i].flags))) {
2526                         spin_lock_irq(&sh->stripe_lock);
2527                         bi = sh->dev[i].toread;
2528                         sh->dev[i].toread = NULL;
2529                         spin_unlock_irq(&sh->stripe_lock);
2530                         if (test_and_clear_bit(R5_Overlap, &sh->dev[i].flags))
2531                                 wake_up(&conf->wait_for_overlap);
2532                         while (bi && bi->bi_sector <
2533                                sh->dev[i].sector + STRIPE_SECTORS) {
2534                                 struct bio *nextbi =
2535                                         r5_next_bio(bi, sh->dev[i].sector);
2536                                 clear_bit(BIO_UPTODATE, &bi->bi_flags);
2537                                 if (!raid5_dec_bi_active_stripes(bi)) {
2538                                         bi->bi_next = *return_bi;
2539                                         *return_bi = bi;
2540                                 }
2541                                 bi = nextbi;
2542                         }
2543                 }
2544                 if (bitmap_end)
2545                         bitmap_endwrite(conf->mddev->bitmap, sh->sector,
2546                                         STRIPE_SECTORS, 0, 0);
2547                 /* If we were in the middle of a write the parity block might
2548                  * still be locked - so just clear all R5_LOCKED flags
2549                  */
2550                 clear_bit(R5_LOCKED, &sh->dev[i].flags);
2551         }
2552
2553         if (test_and_clear_bit(STRIPE_FULL_WRITE, &sh->state))
2554                 if (atomic_dec_and_test(&conf->pending_full_writes))
2555                         md_wakeup_thread(conf->mddev->thread);
2556 }
2557
2558 static void
2559 handle_failed_sync(struct r5conf *conf, struct stripe_head *sh,
2560                    struct stripe_head_state *s)
2561 {
2562         int abort = 0;
2563         int i;
2564
2565         clear_bit(STRIPE_SYNCING, &sh->state);
2566         s->syncing = 0;
2567         s->replacing = 0;
2568         /* There is nothing more to do for sync/check/repair.
2569          * Don't even need to abort as that is handled elsewhere
2570          * if needed, and not always wanted e.g. if there is a known
2571          * bad block here.
2572          * For recover/replace we need to record a bad block on all
2573          * non-sync devices, or abort the recovery
2574          */
2575         if (test_bit(MD_RECOVERY_RECOVER, &conf->mddev->recovery)) {
2576                 /* During recovery devices cannot be removed, so
2577                  * locking and refcounting of rdevs is not needed
2578                  */
2579                 for (i = 0; i < conf->raid_disks; i++) {
2580                         struct md_rdev *rdev = conf->disks[i].rdev;
2581                         if (rdev
2582                             && !test_bit(Faulty, &rdev->flags)
2583                             && !test_bit(In_sync, &rdev->flags)
2584                             && !rdev_set_badblocks(rdev, sh->sector,
2585                                                    STRIPE_SECTORS, 0))
2586                                 abort = 1;
2587                         rdev = conf->disks[i].replacement;
2588                         if (rdev
2589                             && !test_bit(Faulty, &rdev->flags)
2590                             && !test_bit(In_sync, &rdev->flags)
2591                             && !rdev_set_badblocks(rdev, sh->sector,
2592                                                    STRIPE_SECTORS, 0))
2593                                 abort = 1;
2594                 }
2595                 if (abort)
2596                         conf->recovery_disabled =
2597                                 conf->mddev->recovery_disabled;
2598         }
2599         md_done_sync(conf->mddev, STRIPE_SECTORS, !abort);
2600 }
2601
2602 static int want_replace(struct stripe_head *sh, int disk_idx)
2603 {
2604         struct md_rdev *rdev;
2605         int rv = 0;
2606         /* Doing recovery so rcu locking not required */
2607         rdev = sh->raid_conf->disks[disk_idx].replacement;
2608         if (rdev
2609             && !test_bit(Faulty, &rdev->flags)
2610             && !test_bit(In_sync, &rdev->flags)
2611             && (rdev->recovery_offset <= sh->sector
2612                 || rdev->mddev->recovery_cp <= sh->sector))
2613                 rv = 1;
2614
2615         return rv;
2616 }
2617
2618 /* fetch_block - checks the given member device to see if its data needs
2619  * to be read or computed to satisfy a request.
2620  *
2621  * Returns 1 when no more member devices need to be checked, otherwise returns
2622  * 0 to tell the loop in handle_stripe_fill to continue
2623  */
2624 static int fetch_block(struct stripe_head *sh, struct stripe_head_state *s,
2625                        int disk_idx, int disks)
2626 {
2627         struct r5dev *dev = &sh->dev[disk_idx];
2628         struct r5dev *fdev[2] = { &sh->dev[s->failed_num[0]],
2629                                   &sh->dev[s->failed_num[1]] };
2630
2631         /* is the data in this block needed, and can we get it? */
2632         if (!test_bit(R5_LOCKED, &dev->flags) &&
2633             !test_bit(R5_UPTODATE, &dev->flags) &&
2634             (dev->toread ||
2635              (dev->towrite && !test_bit(R5_OVERWRITE, &dev->flags)) ||
2636              s->syncing || s->expanding ||
2637              (s->replacing && want_replace(sh, disk_idx)) ||
2638              (s->failed >= 1 && fdev[0]->toread) ||
2639              (s->failed >= 2 && fdev[1]->toread) ||
2640              (sh->raid_conf->level <= 5 && s->failed && fdev[0]->towrite &&
2641               !test_bit(R5_OVERWRITE, &fdev[0]->flags)) ||
2642              (sh->raid_conf->level == 6 && s->failed && s->to_write))) {
2643                 /* we would like to get this block, possibly by computing it,
2644                  * otherwise read it if the backing disk is insync
2645                  */
2646                 BUG_ON(test_bit(R5_Wantcompute, &dev->flags));
2647                 BUG_ON(test_bit(R5_Wantread, &dev->flags));
2648                 if ((s->uptodate == disks - 1) &&
2649                     (s->failed && (disk_idx == s->failed_num[0] ||
2650                                    disk_idx == s->failed_num[1]))) {
2651                         /* have disk failed, and we're requested to fetch it;
2652                          * do compute it
2653                          */
2654                         pr_debug("Computing stripe %llu block %d\n",
2655                                (unsigned long long)sh->sector, disk_idx);
2656                         set_bit(STRIPE_COMPUTE_RUN, &sh->state);
2657                         set_bit(STRIPE_OP_COMPUTE_BLK, &s->ops_request);
2658                         set_bit(R5_Wantcompute, &dev->flags);
2659                         sh->ops.target = disk_idx;
2660                         sh->ops.target2 = -1; /* no 2nd target */
2661                         s->req_compute = 1;
2662                         /* Careful: from this point on 'uptodate' is in the eye
2663                          * of raid_run_ops which services 'compute' operations
2664                          * before writes. R5_Wantcompute flags a block that will
2665                          * be R5_UPTODATE by the time it is needed for a
2666                          * subsequent operation.
2667                          */
2668                         s->uptodate++;
2669                         return 1;
2670                 } else if (s->uptodate == disks-2 && s->failed >= 2) {
2671                         /* Computing 2-failure is *very* expensive; only
2672                          * do it if failed >= 2
2673                          */
2674                         int other;
2675                         for (other = disks; other--; ) {
2676                                 if (other == disk_idx)
2677                                         continue;
2678                                 if (!test_bit(R5_UPTODATE,
2679                                       &sh->dev[other].flags))
2680                                         break;
2681                         }
2682                         BUG_ON(other < 0);
2683                         pr_debug("Computing stripe %llu blocks %d,%d\n",
2684                                (unsigned long long)sh->sector,
2685                                disk_idx, other);
2686                         set_bit(STRIPE_COMPUTE_RUN, &sh->state);
2687                         set_bit(STRIPE_OP_COMPUTE_BLK, &s->ops_request);
2688                         set_bit(R5_Wantcompute, &sh->dev[disk_idx].flags);
2689                         set_bit(R5_Wantcompute, &sh->dev[other].flags);
2690                         sh->ops.target = disk_idx;
2691                         sh->ops.target2 = other;
2692                         s->uptodate += 2;
2693                         s->req_compute = 1;
2694                         return 1;
2695                 } else if (test_bit(R5_Insync, &dev->flags)) {
2696                         set_bit(R5_LOCKED, &dev->flags);
2697                         set_bit(R5_Wantread, &dev->flags);
2698                         s->locked++;
2699                         pr_debug("Reading block %d (sync=%d)\n",
2700                                 disk_idx, s->syncing);
2701                 }
2702         }
2703
2704         return 0;
2705 }
2706
2707 /**
2708  * handle_stripe_fill - read or compute data to satisfy pending requests.
2709  */
2710 static void handle_stripe_fill(struct stripe_head *sh,
2711                                struct stripe_head_state *s,
2712                                int disks)
2713 {
2714         int i;
2715
2716         /* look for blocks to read/compute, skip this if a compute
2717          * is already in flight, or if the stripe contents are in the
2718          * midst of changing due to a write
2719          */
2720         if (!test_bit(STRIPE_COMPUTE_RUN, &sh->state) && !sh->check_state &&
2721             !sh->reconstruct_state)
2722                 for (i = disks; i--; )
2723                         if (fetch_block(sh, s, i, disks))
2724                                 break;
2725         set_bit(STRIPE_HANDLE, &sh->state);
2726 }
2727
2728
2729 /* handle_stripe_clean_event
2730  * any written block on an uptodate or failed drive can be returned.
2731  * Note that if we 'wrote' to a failed drive, it will be UPTODATE, but
2732  * never LOCKED, so we don't need to test 'failed' directly.
2733  */
2734 static void handle_stripe_clean_event(struct r5conf *conf,
2735         struct stripe_head *sh, int disks, struct bio **return_bi)
2736 {
2737         int i;
2738         struct r5dev *dev;
2739
2740         for (i = disks; i--; )
2741                 if (sh->dev[i].written) {
2742                         dev = &sh->dev[i];
2743                         if (!test_bit(R5_LOCKED, &dev->flags) &&
2744                             (test_bit(R5_UPTODATE, &dev->flags) ||
2745                              test_bit(R5_Discard, &dev->flags))) {
2746                                 /* We can return any write requests */
2747                                 struct bio *wbi, *wbi2;
2748                                 pr_debug("Return write for disc %d\n", i);
2749                                 if (test_and_clear_bit(R5_Discard, &dev->flags))
2750                                         clear_bit(R5_UPTODATE, &dev->flags);
2751                                 wbi = dev->written;
2752                                 dev->written = NULL;
2753                                 while (wbi && wbi->bi_sector <
2754                                         dev->sector + STRIPE_SECTORS) {
2755                                         wbi2 = r5_next_bio(wbi, dev->sector);
2756                                         if (!raid5_dec_bi_active_stripes(wbi)) {
2757                                                 md_write_end(conf->mddev);
2758                                                 wbi->bi_next = *return_bi;
2759                                                 *return_bi = wbi;
2760                                         }
2761                                         wbi = wbi2;
2762                                 }
2763                                 bitmap_endwrite(conf->mddev->bitmap, sh->sector,
2764                                                 STRIPE_SECTORS,
2765                                          !test_bit(STRIPE_DEGRADED, &sh->state),
2766                                                 0);
2767                         }
2768                 } else if (test_bit(R5_Discard, &sh->dev[i].flags))
2769                         clear_bit(R5_Discard, &sh->dev[i].flags);
2770
2771         if (test_and_clear_bit(STRIPE_FULL_WRITE, &sh->state))
2772                 if (atomic_dec_and_test(&conf->pending_full_writes))
2773                         md_wakeup_thread(conf->mddev->thread);
2774 }
2775
2776 static void handle_stripe_dirtying(struct r5conf *conf,
2777                                    struct stripe_head *sh,
2778                                    struct stripe_head_state *s,
2779                                    int disks)
2780 {
2781         int rmw = 0, rcw = 0, i;
2782         sector_t recovery_cp = conf->mddev->recovery_cp;
2783
2784         /* RAID6 requires 'rcw' in current implementation.
2785          * Otherwise, check whether resync is now happening or should start.
2786          * If yes, then the array is dirty (after unclean shutdown or
2787          * initial creation), so parity in some stripes might be inconsistent.
2788          * In this case, we need to always do reconstruct-write, to ensure
2789          * that in case of drive failure or read-error correction, we
2790          * generate correct data from the parity.
2791          */
2792         if (conf->max_degraded == 2 ||
2793             (recovery_cp < MaxSector && sh->sector >= recovery_cp)) {
2794                 /* Calculate the real rcw later - for now make it
2795                  * look like rcw is cheaper
2796                  */
2797                 rcw = 1; rmw = 2;
2798                 pr_debug("force RCW max_degraded=%u, recovery_cp=%llu sh->sector=%llu\n",
2799                          conf->max_degraded, (unsigned long long)recovery_cp,
2800                          (unsigned long long)sh->sector);
2801         } else for (i = disks; i--; ) {
2802                 /* would I have to read this buffer for read_modify_write */
2803                 struct r5dev *dev = &sh->dev[i];
2804                 if ((dev->towrite || i == sh->pd_idx) &&
2805                     !test_bit(R5_LOCKED, &dev->flags) &&
2806                     !(test_bit(R5_UPTODATE, &dev->flags) ||
2807                       test_bit(R5_Wantcompute, &dev->flags))) {
2808                         if (test_bit(R5_Insync, &dev->flags))
2809                                 rmw++;
2810                         else
2811                                 rmw += 2*disks;  /* cannot read it */
2812                 }
2813                 /* Would I have to read this buffer for reconstruct_write */
2814                 if (!test_bit(R5_OVERWRITE, &dev->flags) && i != sh->pd_idx &&
2815                     !test_bit(R5_LOCKED, &dev->flags) &&
2816                     !(test_bit(R5_UPTODATE, &dev->flags) ||
2817                     test_bit(R5_Wantcompute, &dev->flags))) {
2818                         if (test_bit(R5_Insync, &dev->flags)) rcw++;
2819                         else
2820                                 rcw += 2*disks;
2821                 }
2822         }
2823         pr_debug("for sector %llu, rmw=%d rcw=%d\n",
2824                 (unsigned long long)sh->sector, rmw, rcw);
2825         set_bit(STRIPE_HANDLE, &sh->state);
2826         if (rmw < rcw && rmw > 0) {
2827                 /* prefer read-modify-write, but need to get some data */
2828                 blk_add_trace_msg(conf->mddev->queue, "raid5 rmw %llu %d",
2829                                   (unsigned long long)sh->sector, rmw);
2830                 for (i = disks; i--; ) {
2831                         struct r5dev *dev = &sh->dev[i];
2832                         if ((dev->towrite || i == sh->pd_idx) &&
2833                             !test_bit(R5_LOCKED, &dev->flags) &&
2834                             !(test_bit(R5_UPTODATE, &dev->flags) ||
2835                             test_bit(R5_Wantcompute, &dev->flags)) &&
2836                             test_bit(R5_Insync, &dev->flags)) {
2837                                 if (
2838                                   test_bit(STRIPE_PREREAD_ACTIVE, &sh->state)) {
2839                                         pr_debug("Read_old block "
2840                                                  "%d for r-m-w\n", i);
2841                                         set_bit(R5_LOCKED, &dev->flags);
2842                                         set_bit(R5_Wantread, &dev->flags);
2843                                         s->locked++;
2844                                 } else {
2845                                         set_bit(STRIPE_DELAYED, &sh->state);
2846                                         set_bit(STRIPE_HANDLE, &sh->state);
2847                                 }
2848                         }
2849                 }
2850         }
2851         if (rcw <= rmw && rcw > 0) {
2852                 /* want reconstruct write, but need to get some data */
2853                 int qread =0;
2854                 rcw = 0;
2855                 for (i = disks; i--; ) {
2856                         struct r5dev *dev = &sh->dev[i];
2857                         if (!test_bit(R5_OVERWRITE, &dev->flags) &&
2858                             i != sh->pd_idx && i != sh->qd_idx &&
2859                             !test_bit(R5_LOCKED, &dev->flags) &&
2860                             !(test_bit(R5_UPTODATE, &dev->flags) ||
2861                               test_bit(R5_Wantcompute, &dev->flags))) {
2862                                 rcw++;
2863                                 if (!test_bit(R5_Insync, &dev->flags))
2864                                         continue; /* it's a failed drive */
2865                                 if (
2866                                   test_bit(STRIPE_PREREAD_ACTIVE, &sh->state)) {
2867                                         pr_debug("Read_old block "
2868                                                 "%d for Reconstruct\n", i);
2869                                         set_bit(R5_LOCKED, &dev->flags);
2870                                         set_bit(R5_Wantread, &dev->flags);
2871                                         s->locked++;
2872                                         qread++;
2873                                 } else {
2874                                         set_bit(STRIPE_DELAYED, &sh->state);
2875                                         set_bit(STRIPE_HANDLE, &sh->state);
2876                                 }
2877                         }
2878                 }
2879                 if (rcw)
2880                         blk_add_trace_msg(conf->mddev->queue, "raid5 rcw %llu %d %d %d",
2881                                           (unsigned long long)sh->sector,
2882                                           rcw, qread, test_bit(STRIPE_DELAYED, &sh->state));
2883         }
2884         /* now if nothing is locked, and if we have enough data,
2885          * we can start a write request
2886          */
2887         /* since handle_stripe can be called at any time we need to handle the
2888          * case where a compute block operation has been submitted and then a
2889          * subsequent call wants to start a write request.  raid_run_ops only
2890          * handles the case where compute block and reconstruct are requested
2891          * simultaneously.  If this is not the case then new writes need to be
2892          * held off until the compute completes.
2893          */
2894         if ((s->req_compute || !test_bit(STRIPE_COMPUTE_RUN, &sh->state)) &&
2895             (s->locked == 0 && (rcw == 0 || rmw == 0) &&
2896             !test_bit(STRIPE_BIT_DELAY, &sh->state)))
2897                 schedule_reconstruction(sh, s, rcw == 0, 0);
2898 }
2899
2900 static void handle_parity_checks5(struct r5conf *conf, struct stripe_head *sh,
2901                                 struct stripe_head_state *s, int disks)
2902 {
2903         struct r5dev *dev = NULL;
2904
2905         set_bit(STRIPE_HANDLE, &sh->state);
2906
2907         switch (sh->check_state) {
2908         case check_state_idle:
2909                 /* start a new check operation if there are no failures */
2910                 if (s->failed == 0) {
2911                         BUG_ON(s->uptodate != disks);
2912                         sh->check_state = check_state_run;
2913                         set_bit(STRIPE_OP_CHECK, &s->ops_request);
2914                         clear_bit(R5_UPTODATE, &sh->dev[sh->pd_idx].flags);
2915                         s->uptodate--;
2916                         break;
2917                 }
2918                 dev = &sh->dev[s->failed_num[0]];
2919                 /* fall through */
2920         case check_state_compute_result:
2921                 sh->check_state = check_state_idle;
2922                 if (!dev)
2923                         dev = &sh->dev[sh->pd_idx];
2924
2925                 /* check that a write has not made the stripe insync */
2926                 if (test_bit(STRIPE_INSYNC, &sh->state))
2927                         break;
2928
2929                 /* either failed parity check, or recovery is happening */
2930                 BUG_ON(!test_bit(R5_UPTODATE, &dev->flags));
2931                 BUG_ON(s->uptodate != disks);
2932
2933                 set_bit(R5_LOCKED, &dev->flags);
2934                 s->locked++;
2935                 set_bit(R5_Wantwrite, &dev->flags);
2936
2937                 clear_bit(STRIPE_DEGRADED, &sh->state);
2938                 set_bit(STRIPE_INSYNC, &sh->state);
2939                 break;
2940         case check_state_run:
2941                 break; /* we will be called again upon completion */
2942         case check_state_check_result:
2943                 sh->check_state = check_state_idle;
2944
2945                 /* if a failure occurred during the check operation, leave
2946                  * STRIPE_INSYNC not set and let the stripe be handled again
2947                  */
2948                 if (s->failed)
2949                         break;
2950
2951                 /* handle a successful check operation, if parity is correct
2952                  * we are done.  Otherwise update the mismatch count and repair
2953                  * parity if !MD_RECOVERY_CHECK
2954                  */
2955                 if ((sh->ops.zero_sum_result & SUM_CHECK_P_RESULT) == 0)
2956                         /* parity is correct (on disc,
2957                          * not in buffer any more)
2958                          */
2959                         set_bit(STRIPE_INSYNC, &sh->state);
2960                 else {
2961                         atomic64_add(STRIPE_SECTORS, &conf->mddev->resync_mismatches);
2962                         if (test_bit(MD_RECOVERY_CHECK, &conf->mddev->recovery))
2963                                 /* don't try to repair!! */
2964                                 set_bit(STRIPE_INSYNC, &sh->state);
2965                         else {
2966                                 sh->check_state = check_state_compute_run;
2967                                 set_bit(STRIPE_COMPUTE_RUN, &sh->state);
2968                                 set_bit(STRIPE_OP_COMPUTE_BLK, &s->ops_request);
2969                                 set_bit(R5_Wantcompute,
2970                                         &sh->dev[sh->pd_idx].flags);
2971                                 sh->ops.target = sh->pd_idx;
2972                                 sh->ops.target2 = -1;
2973                                 s->uptodate++;
2974                         }
2975                 }
2976                 break;
2977         case check_state_compute_run:
2978                 break;
2979         default:
2980                 printk(KERN_ERR "%s: unknown check_state: %d sector: %llu\n",
2981                        __func__, sh->check_state,
2982                        (unsigned long long) sh->sector);
2983                 BUG();
2984         }
2985 }
2986
2987
2988 static void handle_parity_checks6(struct r5conf *conf, struct stripe_head *sh,
2989                                   struct stripe_head_state *s,
2990                                   int disks)
2991 {
2992         int pd_idx = sh->pd_idx;
2993         int qd_idx = sh->qd_idx;
2994         struct r5dev *dev;
2995
2996         set_bit(STRIPE_HANDLE, &sh->state);
2997
2998         BUG_ON(s->failed > 2);
2999
3000         /* Want to check and possibly repair P and Q.
3001          * However there could be one 'failed' device, in which
3002          * case we can only check one of them, possibly using the
3003          * other to generate missing data
3004          */
3005
3006         switch (sh->check_state) {
3007         case check_state_idle:
3008                 /* start a new check operation if there are < 2 failures */
3009                 if (s->failed == s->q_failed) {
3010                         /* The only possible failed device holds Q, so it
3011                          * makes sense to check P (If anything else were failed,
3012                          * we would have used P to recreate it).
3013                          */
3014                         sh->check_state = check_state_run;
3015                 }
3016                 if (!s->q_failed && s->failed < 2) {
3017                         /* Q is not failed, and we didn't use it to generate
3018                          * anything, so it makes sense to check it
3019                          */
3020                         if (sh->check_state == check_state_run)
3021                                 sh->check_state = check_state_run_pq;
3022                         else
3023                                 sh->check_state = check_state_run_q;
3024                 }
3025
3026                 /* discard potentially stale zero_sum_result */
3027                 sh->ops.zero_sum_result = 0;
3028
3029                 if (sh->check_state == check_state_run) {
3030                         /* async_xor_zero_sum destroys the contents of P */
3031                         clear_bit(R5_UPTODATE, &sh->dev[pd_idx].flags);
3032                         s->uptodate--;
3033                 }
3034                 if (sh->check_state >= check_state_run &&
3035                     sh->check_state <= check_state_run_pq) {
3036                         /* async_syndrome_zero_sum preserves P and Q, so
3037                          * no need to mark them !uptodate here
3038                          */
3039                         set_bit(STRIPE_OP_CHECK, &s->ops_request);
3040                         break;
3041                 }
3042
3043                 /* we have 2-disk failure */
3044                 BUG_ON(s->failed != 2);
3045                 /* fall through */
3046         case check_state_compute_result:
3047                 sh->check_state = check_state_idle;
3048
3049                 /* check that a write has not made the stripe insync */
3050                 if (test_bit(STRIPE_INSYNC, &sh->state))
3051                         break;
3052
3053                 /* now write out any block on a failed drive,
3054                  * or P or Q if they were recomputed
3055                  */
3056                 BUG_ON(s->uptodate < disks - 1); /* We don't need Q to recover */
3057                 if (s->failed == 2) {
3058                         dev = &sh->dev[s->failed_num[1]];
3059                         s->locked++;
3060                         set_bit(R5_LOCKED, &dev->flags);
3061                         set_bit(R5_Wantwrite, &dev->flags);
3062                 }
3063                 if (s->failed >= 1) {
3064                         dev = &sh->dev[s->failed_num[0]];
3065                         s->locked++;
3066                         set_bit(R5_LOCKED, &dev->flags);
3067                         set_bit(R5_Wantwrite, &dev->flags);
3068                 }
3069                 if (sh->ops.zero_sum_result & SUM_CHECK_P_RESULT) {
3070                         dev = &sh->dev[pd_idx];
3071                         s->locked++;
3072                         set_bit(R5_LOCKED, &dev->flags);
3073                         set_bit(R5_Wantwrite, &dev->flags);
3074                 }
3075                 if (sh->ops.zero_sum_result & SUM_CHECK_Q_RESULT) {
3076                         dev = &sh->dev[qd_idx];
3077                         s->locked++;
3078                         set_bit(R5_LOCKED, &dev->flags);
3079                         set_bit(R5_Wantwrite, &dev->flags);
3080                 }
3081                 clear_bit(STRIPE_DEGRADED, &sh->state);
3082
3083                 set_bit(STRIPE_INSYNC, &sh->state);
3084                 break;
3085         case check_state_run:
3086         case check_state_run_q:
3087         case check_state_run_pq:
3088                 break; /* we will be called again upon completion */
3089         case check_state_check_result:
3090                 sh->check_state = check_state_idle;
3091
3092                 /* handle a successful check operation, if parity is correct
3093                  * we are done.  Otherwise update the mismatch count and repair
3094                  * parity if !MD_RECOVERY_CHECK
3095                  */
3096                 if (sh->ops.zero_sum_result == 0) {
3097                         /* both parities are correct */
3098                         if (!s->failed)
3099                                 set_bit(STRIPE_INSYNC, &sh->state);
3100                         else {
3101                                 /* in contrast to the raid5 case we can validate
3102                                  * parity, but still have a failure to write
3103                                  * back
3104                                  */
3105                                 sh->check_state = check_state_compute_result;
3106                                 /* Returning at this point means that we may go
3107                                  * off and bring p and/or q uptodate again so
3108                                  * we make sure to check zero_sum_result again
3109                                  * to verify if p or q need writeback
3110                                  */
3111                         }
3112                 } else {
3113                         atomic64_add(STRIPE_SECTORS, &conf->mddev->resync_mismatches);
3114                         if (test_bit(MD_RECOVERY_CHECK, &conf->mddev->recovery))
3115                                 /* don't try to repair!! */
3116                                 set_bit(STRIPE_INSYNC, &sh->state);
3117                         else {
3118                                 int *target = &sh->ops.target;
3119
3120                                 sh->ops.target = -1;
3121                                 sh->ops.target2 = -1;
3122                                 sh->check_state = check_state_compute_run;
3123                                 set_bit(STRIPE_COMPUTE_RUN, &sh->state);
3124                                 set_bit(STRIPE_OP_COMPUTE_BLK, &s->ops_request);
3125                                 if (sh->ops.zero_sum_result & SUM_CHECK_P_RESULT) {
3126                                         set_bit(R5_Wantcompute,
3127                                                 &sh->dev[pd_idx].flags);
3128                                         *target = pd_idx;
3129                                         target = &sh->ops.target2;
3130                                         s->uptodate++;
3131                                 }
3132                                 if (sh->ops.zero_sum_result & SUM_CHECK_Q_RESULT) {
3133                                         set_bit(R5_Wantcompute,
3134                                                 &sh->dev[qd_idx].flags);
3135                                         *target = qd_idx;
3136                                         s->uptodate++;
3137                                 }
3138                         }
3139                 }
3140                 break;
3141         case check_state_compute_run:
3142                 break;
3143         default:
3144                 printk(KERN_ERR "%s: unknown check_state: %d sector: %llu\n",
3145                        __func__, sh->check_state,
3146                        (unsigned long long) sh->sector);
3147                 BUG();
3148         }
3149 }
3150
3151 static void handle_stripe_expansion(struct r5conf *conf, struct stripe_head *sh)
3152 {
3153         int i;
3154
3155         /* We have read all the blocks in this stripe and now we need to
3156          * copy some of them into a target stripe for expand.
3157          */
3158         struct dma_async_tx_descriptor *tx = NULL;
3159         clear_bit(STRIPE_EXPAND_SOURCE, &sh->state);
3160         for (i = 0; i < sh->disks; i++)
3161                 if (i != sh->pd_idx && i != sh->qd_idx) {
3162                         int dd_idx, j;
3163                         struct stripe_head *sh2;
3164                         struct async_submit_ctl submit;
3165
3166                         sector_t bn = compute_blocknr(sh, i, 1);
3167                         sector_t s = raid5_compute_sector(conf, bn, 0,
3168                                                           &dd_idx, NULL);
3169                         sh2 = get_active_stripe(conf, s, 0, 1, 1);
3170                         if (sh2 == NULL)
3171                                 /* so far only the early blocks of this stripe
3172                                  * have been requested.  When later blocks
3173                                  * get requested, we will try again
3174                                  */
3175                                 continue;
3176                         if (!test_bit(STRIPE_EXPANDING, &sh2->state) ||
3177                            test_bit(R5_Expanded, &sh2->dev[dd_idx].flags)) {
3178                                 /* must have already done this block */
3179                                 release_stripe(sh2);
3180                                 continue;
3181                         }
3182
3183                         /* place all the copies on one channel */
3184                         init_async_submit(&submit, 0, tx, NULL, NULL, NULL);
3185                         tx = async_memcpy(sh2->dev[dd_idx].page,
3186                                           sh->dev[i].page, 0, 0, STRIPE_SIZE,
3187                                           &submit);
3188
3189                         set_bit(R5_Expanded, &sh2->dev[dd_idx].flags);
3190                         set_bit(R5_UPTODATE, &sh2->dev[dd_idx].flags);
3191                         for (j = 0; j < conf->raid_disks; j++)
3192                                 if (j != sh2->pd_idx &&
3193                                     j != sh2->qd_idx &&
3194                                     !test_bit(R5_Expanded, &sh2->dev[j].flags))
3195                                         break;
3196                         if (j == conf->raid_disks) {
3197                                 set_bit(STRIPE_EXPAND_READY, &sh2->state);
3198                                 set_bit(STRIPE_HANDLE, &sh2->state);
3199                         }
3200                         release_stripe(sh2);
3201
3202                 }
3203         /* done submitting copies, wait for them to complete */
3204         async_tx_quiesce(&tx);
3205 }
3206
3207 /*
3208  * handle_stripe - do things to a stripe.
3209  *
3210  * We lock the stripe by setting STRIPE_ACTIVE and then examine the
3211  * state of various bits to see what needs to be done.
3212  * Possible results:
3213  *    return some read requests which now have data
3214  *    return some write requests which are safely on storage
3215  *    schedule a read on some buffers
3216  *    schedule a write of some buffers
3217  *    return confirmation of parity correctness
3218  *
3219  */
3220
3221 static void analyse_stripe(struct stripe_head *sh, struct stripe_head_state *s)
3222 {
3223         struct r5conf *conf = sh->raid_conf;
3224         int disks = sh->disks;
3225         struct r5dev *dev;
3226         int i;
3227         int do_recovery = 0;
3228
3229         memset(s, 0, sizeof(*s));
3230
3231         s->expanding = test_bit(STRIPE_EXPAND_SOURCE, &sh->state);
3232         s->expanded = test_bit(STRIPE_EXPAND_READY, &sh->state);
3233         s->failed_num[0] = -1;
3234         s->failed_num[1] = -1;
3235
3236         /* Now to look around and see what can be done */
3237         rcu_read_lock();
3238         for (i=disks; i--; ) {
3239                 struct md_rdev *rdev;
3240                 sector_t first_bad;
3241                 int bad_sectors;
3242                 int is_bad = 0;
3243
3244                 dev = &sh->dev[i];
3245
3246                 pr_debug("check %d: state 0x%lx read %p write %p written %p\n",
3247                          i, dev->flags,
3248                          dev->toread, dev->towrite, dev->written);
3249                 /* maybe we can reply to a read
3250                  *
3251                  * new wantfill requests are only permitted while
3252                  * ops_complete_biofill is guaranteed to be inactive
3253                  */
3254                 if (test_bit(R5_UPTODATE, &dev->flags) && dev->toread &&
3255                     !test_bit(STRIPE_BIOFILL_RUN, &sh->state))
3256                         set_bit(R5_Wantfill, &dev->flags);
3257
3258                 /* now count some things */
3259                 if (test_bit(R5_LOCKED, &dev->flags))
3260                         s->locked++;
3261                 if (test_bit(R5_UPTODATE, &dev->flags))
3262                         s->uptodate++;
3263                 if (test_bit(R5_Wantcompute, &dev->flags)) {
3264                         s->compute++;
3265                         BUG_ON(s->compute > 2);
3266                 }
3267
3268                 if (test_bit(R5_Wantfill, &dev->flags))
3269                         s->to_fill++;
3270                 else if (dev->toread)
3271                         s->to_read++;
3272                 if (dev->towrite) {
3273                         s->to_write++;
3274                         if (!test_bit(R5_OVERWRITE, &dev->flags))
3275                                 s->non_overwrite++;
3276                 }
3277                 if (dev->written)
3278                         s->written++;
3279                 /* Prefer to use the replacement for reads, but only
3280                  * if it is recovered enough and has no bad blocks.
3281                  */
3282                 rdev = rcu_dereference(conf->disks[i].replacement);
3283                 if (rdev && !test_bit(Faulty, &rdev->flags) &&
3284                     rdev->recovery_offset >= sh->sector + STRIPE_SECTORS &&
3285                     !is_badblock(rdev, sh->sector, STRIPE_SECTORS,
3286                                  &first_bad, &bad_sectors))
3287                         set_bit(R5_ReadRepl, &dev->flags);
3288                 else {
3289                         if (rdev)
3290                                 set_bit(R5_NeedReplace, &dev->flags);
3291                         rdev = rcu_dereference(conf->disks[i].rdev);
3292                         clear_bit(R5_ReadRepl, &dev->flags);
3293                 }
3294                 if (rdev && test_bit(Faulty, &rdev->flags))
3295                         rdev = NULL;
3296                 if (rdev) {
3297                         is_bad = is_badblock(rdev, sh->sector, STRIPE_SECTORS,
3298                                              &first_bad, &bad_sectors);
3299                         if (s->blocked_rdev == NULL
3300                             && (test_bit(Blocked, &rdev->flags)
3301                                 || is_bad < 0)) {
3302                                 if (is_bad < 0)
3303                                         set_bit(BlockedBadBlocks,
3304                                                 &rdev->flags);
3305                                 s->blocked_rdev = rdev;
3306                                 atomic_inc(&rdev->nr_pending);
3307                         }
3308                 }
3309                 clear_bit(R5_Insync, &dev->flags);
3310                 if (!rdev)
3311                         /* Not in-sync */;
3312                 else if (is_bad) {
3313                         /* also not in-sync */
3314                         if (!test_bit(WriteErrorSeen, &rdev->flags) &&
3315                             test_bit(R5_UPTODATE, &dev->flags)) {
3316                                 /* treat as in-sync, but with a read error
3317                                  * which we can now try to correct
3318                                  */
3319                                 set_bit(R5_Insync, &dev->flags);
3320                                 set_bit(R5_ReadError, &dev->flags);
3321                         }
3322                 } else if (test_bit(In_sync, &rdev->flags))
3323                         set_bit(R5_Insync, &dev->flags);
3324                 else if (sh->sector + STRIPE_SECTORS <= rdev->recovery_offset)
3325                         /* in sync if before recovery_offset */
3326                         set_bit(R5_Insync, &dev->flags);
3327                 else if (test_bit(R5_UPTODATE, &dev->flags) &&
3328                          test_bit(R5_Expanded, &dev->flags))
3329                         /* If we've reshaped into here, we assume it is Insync.
3330                          * We will shortly update recovery_offset to make
3331                          * it official.
3332                          */
3333                         set_bit(R5_Insync, &dev->flags);
3334
3335                 if (rdev && test_bit(R5_WriteError, &dev->flags)) {
3336                         /* This flag does not apply to '.replacement'
3337                          * only to .rdev, so make sure to check that*/
3338                         struct md_rdev *rdev2 = rcu_dereference(
3339                                 conf->disks[i].rdev);
3340                         if (rdev2 == rdev)
3341                                 clear_bit(R5_Insync, &dev->flags);
3342                         if (rdev2 && !test_bit(Faulty, &rdev2->flags)) {
3343                                 s->handle_bad_blocks = 1;
3344                                 atomic_inc(&rdev2->nr_pending);
3345                         } else
3346                                 clear_bit(R5_WriteError, &dev->flags);
3347                 }
3348                 if (rdev && test_bit(R5_MadeGood, &dev->flags)) {
3349                         /* This flag does not apply to '.replacement'
3350                          * only to .rdev, so make sure to check that*/
3351                         struct md_rdev *rdev2 = rcu_dereference(
3352                                 conf->disks[i].rdev);
3353                         if (rdev2 && !test_bit(Faulty, &rdev2->flags)) {
3354                                 s->handle_bad_blocks = 1;
3355                                 atomic_inc(&rdev2->nr_pending);
3356                         } else
3357                                 clear_bit(R5_MadeGood, &dev->flags);
3358                 }
3359                 if (test_bit(R5_MadeGoodRepl, &dev->flags)) {
3360                         struct md_rdev *rdev2 = rcu_dereference(
3361                                 conf->disks[i].replacement);
3362                         if (rdev2 && !test_bit(Faulty, &rdev2->flags)) {
3363                                 s->handle_bad_blocks = 1;
3364                                 atomic_inc(&rdev2->nr_pending);
3365                         } else
3366                                 clear_bit(R5_MadeGoodRepl, &dev->flags);
3367                 }
3368                 if (!test_bit(R5_Insync, &dev->flags)) {
3369                         /* The ReadError flag will just be confusing now */
3370                         clear_bit(R5_ReadError, &dev->flags);
3371                         clear_bit(R5_ReWrite, &dev->flags);
3372                 }
3373                 if (test_bit(R5_ReadError, &dev->flags))
3374                         clear_bit(R5_Insync, &dev->flags);
3375                 if (!test_bit(R5_Insync, &dev->flags)) {
3376                         if (s->failed < 2)
3377                                 s->failed_num[s->failed] = i;
3378                         s->failed++;
3379                         if (rdev && !test_bit(Faulty, &rdev->flags))
3380                                 do_recovery = 1;
3381                 }
3382         }
3383         if (test_bit(STRIPE_SYNCING, &sh->state)) {
3384                 /* If there is a failed device being replaced,
3385                  *     we must be recovering.
3386                  * else if we are after recovery_cp, we must be syncing
3387                  * else if MD_RECOVERY_REQUESTED is set, we also are syncing.
3388                  * else we can only be replacing
3389                  * sync and recovery both need to read all devices, and so
3390                  * use the same flag.
3391                  */
3392                 if (do_recovery ||
3393                     sh->sector >= conf->mddev->recovery_cp ||
3394                     test_bit(MD_RECOVERY_REQUESTED, &(conf->mddev->recovery)))
3395                         s->syncing = 1;
3396                 else
3397                         s->replacing = 1;
3398         }
3399         rcu_read_unlock();
3400 }
3401
3402 static void handle_stripe(struct stripe_head *sh)
3403 {
3404         struct stripe_head_state s;
3405         struct r5conf *conf = sh->raid_conf;
3406         int i;
3407         int prexor;
3408         int disks = sh->disks;
3409         struct r5dev *pdev, *qdev;
3410
3411         clear_bit(STRIPE_HANDLE, &sh->state);
3412         if (test_and_set_bit_lock(STRIPE_ACTIVE, &sh->state)) {
3413                 /* already being handled, ensure it gets handled
3414                  * again when current action finishes */
3415                 set_bit(STRIPE_HANDLE, &sh->state);
3416                 return;
3417         }
3418
3419         if (test_and_clear_bit(STRIPE_SYNC_REQUESTED, &sh->state)) {
3420                 set_bit(STRIPE_SYNCING, &sh->state);
3421                 clear_bit(STRIPE_INSYNC, &sh->state);
3422         }
3423         clear_bit(STRIPE_DELAYED, &sh->state);
3424
3425         pr_debug("handling stripe %llu, state=%#lx cnt=%d, "
3426                 "pd_idx=%d, qd_idx=%d\n, check:%d, reconstruct:%d\n",
3427                (unsigned long long)sh->sector, sh->state,
3428                atomic_read(&sh->count), sh->pd_idx, sh->qd_idx,
3429                sh->check_state, sh->reconstruct_state);
3430
3431         analyse_stripe(sh, &s);
3432
3433         if (s.handle_bad_blocks) {
3434                 set_bit(STRIPE_HANDLE, &sh->state);
3435                 goto finish;
3436         }
3437
3438         if (unlikely(s.blocked_rdev)) {
3439                 if (s.syncing || s.expanding || s.expanded ||
3440                     s.replacing || s.to_write || s.written) {
3441                         set_bit(STRIPE_HANDLE, &sh->state);
3442                         goto finish;
3443                 }
3444                 /* There is nothing for the blocked_rdev to block */
3445                 rdev_dec_pending(s.blocked_rdev, conf->mddev);
3446                 s.blocked_rdev = NULL;
3447         }
3448
3449         if (s.to_fill && !test_bit(STRIPE_BIOFILL_RUN, &sh->state)) {
3450                 set_bit(STRIPE_OP_BIOFILL, &s.ops_request);
3451                 set_bit(STRIPE_BIOFILL_RUN, &sh->state);
3452         }
3453
3454         pr_debug("locked=%d uptodate=%d to_read=%d"
3455                " to_write=%d failed=%d failed_num=%d,%d\n",
3456                s.locked, s.uptodate, s.to_read, s.to_write, s.failed,
3457                s.failed_num[0], s.failed_num[1]);
3458         /* check if the array has lost more than max_degraded devices and,
3459          * if so, some requests might need to be failed.
3460          */
3461         if (s.failed > conf->max_degraded) {
3462                 sh->check_state = 0;
3463                 sh->reconstruct_state = 0;
3464                 if (s.to_read+s.to_write+s.written)
3465                         handle_failed_stripe(conf, sh, &s, disks, &s.return_bi);
3466                 if (s.syncing + s.replacing)
3467                         handle_failed_sync(conf, sh, &s);
3468         }
3469
3470         /* Now we check to see if any write operations have recently
3471          * completed
3472          */
3473         prexor = 0;
3474         if (sh->reconstruct_state == reconstruct_state_prexor_drain_result)
3475                 prexor = 1;
3476         if (sh->reconstruct_state == reconstruct_state_drain_result ||
3477             sh->reconstruct_state == reconstruct_state_prexor_drain_result) {
3478                 sh->reconstruct_state = reconstruct_state_idle;
3479
3480                 /* All the 'written' buffers and the parity block are ready to
3481                  * be written back to disk
3482                  */
3483                 BUG_ON(!test_bit(R5_UPTODATE, &sh->dev[sh->pd_idx].flags) &&
3484                        !test_bit(R5_Discard, &sh->dev[sh->pd_idx].flags));
3485                 BUG_ON(sh->qd_idx >= 0 &&
3486                        !test_bit(R5_UPTODATE, &sh->dev[sh->qd_idx].flags) &&
3487                        !test_bit(R5_Discard, &sh->dev[sh->qd_idx].flags));
3488                 for (i = disks; i--; ) {
3489                         struct r5dev *dev = &sh->dev[i];
3490                         if (test_bit(R5_LOCKED, &dev->flags) &&
3491                                 (i == sh->pd_idx || i == sh->qd_idx ||
3492                                  dev->written)) {
3493                                 pr_debug("Writing block %d\n", i);
3494                                 set_bit(R5_Wantwrite, &dev->flags);
3495                                 if (prexor)
3496                                         continue;
3497                                 if (!test_bit(R5_Insync, &dev->flags) ||
3498                                     ((i == sh->pd_idx || i == sh->qd_idx)  &&
3499                                      s.failed == 0))
3500                                         set_bit(STRIPE_INSYNC, &sh->state);
3501                         }
3502                 }
3503                 if (test_and_clear_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
3504                         s.dec_preread_active = 1;
3505         }
3506
3507         /*
3508          * might be able to return some write requests if the parity blocks
3509          * are safe, or on a failed drive
3510          */
3511         pdev = &sh->dev[sh->pd_idx];
3512         s.p_failed = (s.failed >= 1 && s.failed_num[0] == sh->pd_idx)
3513                 || (s.failed >= 2 && s.failed_num[1] == sh->pd_idx);
3514         qdev = &sh->dev[sh->qd_idx];
3515         s.q_failed = (s.failed >= 1 && s.failed_num[0] == sh->qd_idx)
3516                 || (s.failed >= 2 && s.failed_num[1] == sh->qd_idx)
3517                 || conf->level < 6;
3518
3519         if (s.written &&
3520             (s.p_failed || ((test_bit(R5_Insync, &pdev->flags)
3521                              && !test_bit(R5_LOCKED, &pdev->flags)
3522                              && (test_bit(R5_UPTODATE, &pdev->flags) ||
3523                                  test_bit(R5_Discard, &pdev->flags))))) &&
3524             (s.q_failed || ((test_bit(R5_Insync, &qdev->flags)
3525                              && !test_bit(R5_LOCKED, &qdev->flags)
3526                              && (test_bit(R5_UPTODATE, &qdev->flags) ||
3527                                  test_bit(R5_Discard, &qdev->flags))))))
3528                 handle_stripe_clean_event(conf, sh, disks, &s.return_bi);
3529
3530         /* Now we might consider reading some blocks, either to check/generate
3531          * parity, or to satisfy requests
3532          * or to load a block that is being partially written.
3533          */
3534         if (s.to_read || s.non_overwrite
3535             || (conf->level == 6 && s.to_write && s.failed)
3536             || (s.syncing && (s.uptodate + s.compute < disks))
3537             || s.replacing
3538             || s.expanding)
3539                 handle_stripe_fill(sh, &s, disks);
3540
3541         /* Now to consider new write requests and what else, if anything
3542          * should be read.  We do not handle new writes when:
3543          * 1/ A 'write' operation (copy+xor) is already in flight.
3544          * 2/ A 'check' operation is in flight, as it may clobber the parity
3545          *    block.
3546          */
3547         if (s.to_write && !sh->reconstruct_state && !sh->check_state)
3548                 handle_stripe_dirtying(conf, sh, &s, disks);
3549
3550         /* maybe we need to check and possibly fix the parity for this stripe
3551          * Any reads will already have been scheduled, so we just see if enough
3552          * data is available.  The parity check is held off while parity
3553          * dependent operations are in flight.
3554          */
3555         if (sh->check_state ||
3556             (s.syncing && s.locked == 0 &&
3557              !test_bit(STRIPE_COMPUTE_RUN, &sh->state) &&
3558              !test_bit(STRIPE_INSYNC, &sh->state))) {
3559                 if (conf->level == 6)
3560                         handle_parity_checks6(conf, sh, &s, disks);
3561                 else
3562                         handle_parity_checks5(conf, sh, &s, disks);
3563         }
3564
3565         if (s.replacing && s.locked == 0
3566             && !test_bit(STRIPE_INSYNC, &sh->state)) {
3567                 /* Write out to replacement devices where possible */
3568                 for (i = 0; i < conf->raid_disks; i++)
3569                         if (test_bit(R5_UPTODATE, &sh->dev[i].flags) &&
3570                             test_bit(R5_NeedReplace, &sh->dev[i].flags)) {
3571                                 set_bit(R5_WantReplace, &sh->dev[i].flags);
3572                                 set_bit(R5_LOCKED, &sh->dev[i].flags);
3573                                 s.locked++;
3574                         }
3575                 set_bit(STRIPE_INSYNC, &sh->state);
3576         }
3577         if ((s.syncing || s.replacing) && s.locked == 0 &&
3578             test_bit(STRIPE_INSYNC, &sh->state)) {
3579                 md_done_sync(conf->mddev, STRIPE_SECTORS, 1);
3580                 clear_bit(STRIPE_SYNCING, &sh->state);
3581         }
3582
3583         /* If the failed drives are just a ReadError, then we might need
3584          * to progress the repair/check process
3585          */
3586         if (s.failed <= conf->max_degraded && !conf->mddev->ro)
3587                 for (i = 0; i < s.failed; i++) {
3588                         struct r5dev *dev = &sh->dev[s.failed_num[i]];
3589                         if (test_bit(R5_ReadError, &dev->flags)
3590                             && !test_bit(R5_LOCKED, &dev->flags)
3591                             && test_bit(R5_UPTODATE, &dev->flags)
3592                                 ) {
3593                                 if (!test_bit(R5_ReWrite, &dev->flags)) {
3594                                         set_bit(R5_Wantwrite, &dev->flags);
3595                                         set_bit(R5_ReWrite, &dev->flags);
3596                                         set_bit(R5_LOCKED, &dev->flags);
3597                                         s.locked++;
3598                                 } else {
3599                                         /* let's read it back */
3600                                         set_bit(R5_Wantread, &dev->flags);
3601                                         set_bit(R5_LOCKED, &dev->flags);
3602                                         s.locked++;
3603                                 }
3604                         }
3605                 }
3606
3607
3608         /* Finish reconstruct operations initiated by the expansion process */
3609         if (sh->reconstruct_state == reconstruct_state_result) {
3610                 struct stripe_head *sh_src
3611                         = get_active_stripe(conf, sh->sector, 1, 1, 1);
3612                 if (sh_src && test_bit(STRIPE_EXPAND_SOURCE, &sh_src->state)) {
3613                         /* sh cannot be written until sh_src has been read.
3614                          * so arrange for sh to be delayed a little
3615                          */
3616                         set_bit(STRIPE_DELAYED, &sh->state);
3617                         set_bit(STRIPE_HANDLE, &sh->state);
3618                         if (!test_and_set_bit(STRIPE_PREREAD_ACTIVE,
3619                                               &sh_src->state))
3620                                 atomic_inc(&conf->preread_active_stripes);
3621                         release_stripe(sh_src);
3622                         goto finish;
3623                 }
3624                 if (sh_src)
3625                         release_stripe(sh_src);
3626
3627                 sh->reconstruct_state = reconstruct_state_idle;
3628                 clear_bit(STRIPE_EXPANDING, &sh->state);
3629                 for (i = conf->raid_disks; i--; ) {
3630                         set_bit(R5_Wantwrite, &sh->dev[i].flags);
3631                         set_bit(R5_LOCKED, &sh->dev[i].flags);
3632                         s.locked++;
3633                 }
3634         }
3635
3636         if (s.expanded && test_bit(STRIPE_EXPANDING, &sh->state) &&
3637             !sh->reconstruct_state) {
3638                 /* Need to write out all blocks after computing parity */
3639                 sh->disks = conf->raid_disks;
3640                 stripe_set_idx(sh->sector, conf, 0, sh);
3641                 schedule_reconstruction(sh, &s, 1, 1);
3642         } else if (s.expanded && !sh->reconstruct_state && s.locked == 0) {
3643                 clear_bit(STRIPE_EXPAND_READY, &sh->state);
3644                 atomic_dec(&conf->reshape_stripes);
3645                 wake_up(&conf->wait_for_overlap);
3646                 md_done_sync(conf->mddev, STRIPE_SECTORS, 1);
3647         }
3648
3649         if (s.expanding && s.locked == 0 &&
3650             !test_bit(STRIPE_COMPUTE_RUN, &sh->state))
3651                 handle_stripe_expansion(conf, sh);
3652
3653 finish:
3654         /* wait for this device to become unblocked */
3655         if (unlikely(s.blocked_rdev)) {
3656                 if (conf->mddev->external)
3657                         md_wait_for_blocked_rdev(s.blocked_rdev,
3658                                                  conf->mddev);
3659                 else
3660                         /* Internal metadata will immediately
3661                          * be written by raid5d, so we don't
3662                          * need to wait here.
3663                          */
3664                         rdev_dec_pending(s.blocked_rdev,
3665                                          conf->mddev);
3666         }
3667
3668         if (s.handle_bad_blocks)
3669                 for (i = disks; i--; ) {
3670                         struct md_rdev *rdev;
3671                         struct r5dev *dev = &sh->dev[i];
3672                         if (test_and_clear_bit(R5_WriteError, &dev->flags)) {
3673                                 /* We own a safe reference to the rdev */
3674                                 rdev = conf->disks[i].rdev;
3675                                 if (!rdev_set_badblocks(rdev, sh->sector,
3676                                                         STRIPE_SECTORS, 0))
3677                                         md_error(conf->mddev, rdev);
3678                                 rdev_dec_pending(rdev, conf->mddev);
3679                         }
3680                         if (test_and_clear_bit(R5_MadeGood, &dev->flags)) {
3681                                 rdev = conf->disks[i].rdev;
3682                                 rdev_clear_badblocks(rdev, sh->sector,
3683                                                      STRIPE_SECTORS, 0);
3684                                 rdev_dec_pending(rdev, conf->mddev);
3685                         }
3686                         if (test_and_clear_bit(R5_MadeGoodRepl, &dev->flags)) {
3687                                 rdev = conf->disks[i].replacement;
3688                                 if (!rdev)
3689                                         /* rdev have been moved down */
3690                                         rdev = conf->disks[i].rdev;
3691                                 rdev_clear_badblocks(rdev, sh->sector,
3692                                                      STRIPE_SECTORS, 0);
3693                                 rdev_dec_pending(rdev, conf->mddev);
3694                         }
3695                 }
3696
3697         if (s.ops_request)
3698                 raid_run_ops(sh, s.ops_request);
3699
3700         ops_run_io(sh, &s);
3701
3702         if (s.dec_preread_active) {
3703                 /* We delay this until after ops_run_io so that if make_request
3704                  * is waiting on a flush, it won't continue until the writes
3705                  * have actually been submitted.
3706                  */
3707                 atomic_dec(&conf->preread_active_stripes);
3708                 if (atomic_read(&conf->preread_active_stripes) <
3709                     IO_THRESHOLD)
3710                         md_wakeup_thread(conf->mddev->thread);
3711         }
3712
3713         return_io(s.return_bi);
3714
3715         clear_bit_unlock(STRIPE_ACTIVE, &sh->state);
3716 }
3717
3718 static void raid5_activate_delayed(struct r5conf *conf)
3719 {
3720         if (atomic_read(&conf->preread_active_stripes) < IO_THRESHOLD) {
3721                 while (!list_empty(&conf->delayed_list)) {
3722                         struct list_head *l = conf->delayed_list.next;
3723                         struct stripe_head *sh;
3724                         sh = list_entry(l, struct stripe_head, lru);
3725                         list_del_init(l);
3726                         clear_bit(STRIPE_DELAYED, &sh->state);
3727                         if (!test_and_set_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
3728                                 atomic_inc(&conf->preread_active_stripes);
3729                         list_add_tail(&sh->lru, &conf->hold_list);
3730                 }
3731         }
3732 }
3733
3734 static void activate_bit_delay(struct r5conf *conf)
3735 {
3736         /* device_lock is held */
3737         struct list_head head;
3738         list_add(&head, &conf->bitmap_list);
3739         list_del_init(&conf->bitmap_list);
3740         while (!list_empty(&head)) {
3741                 struct stripe_head *sh = list_entry(head.next, struct stripe_head, lru);
3742                 list_del_init(&sh->lru);
3743                 atomic_inc(&sh->count);
3744                 __release_stripe(conf, sh);
3745         }
3746 }
3747
3748 int md_raid5_congested(struct mddev *mddev, int bits)
3749 {
3750         struct r5conf *conf = mddev->private;
3751
3752         /* No difference between reads and writes.  Just check
3753          * how busy the stripe_cache is
3754          */
3755
3756         if (conf->inactive_blocked)
3757                 return 1;
3758         if (conf->quiesce)
3759                 return 1;
3760         if (list_empty_careful(&conf->inactive_list))
3761                 return 1;
3762
3763         return 0;
3764 }
3765 EXPORT_SYMBOL_GPL(md_raid5_congested);
3766
3767 static int raid5_congested(void *data, int bits)
3768 {
3769         struct mddev *mddev = data;
3770
3771         return mddev_congested(mddev, bits) ||
3772                 md_raid5_congested(mddev, bits);
3773 }
3774
3775 /* We want read requests to align with chunks where possible,
3776  * but write requests don't need to.
3777  */
3778 static int raid5_mergeable_bvec(struct request_queue *q,
3779                                 struct bvec_merge_data *bvm,
3780                                 struct bio_vec *biovec)
3781 {
3782         struct mddev *mddev = q->queuedata;
3783         sector_t sector = bvm->bi_sector + get_start_sect(bvm->bi_bdev);
3784         int max;
3785         unsigned int chunk_sectors = mddev->chunk_sectors;
3786         unsigned int bio_sectors = bvm->bi_size >> 9;
3787
3788         if ((bvm->bi_rw & 1) == WRITE)
3789                 return biovec->bv_len; /* always allow writes to be mergeable */
3790
3791         if (mddev->new_chunk_sectors < mddev->chunk_sectors)
3792                 chunk_sectors = mddev->new_chunk_sectors;
3793         max =  (chunk_sectors - ((sector & (chunk_sectors - 1)) + bio_sectors)) << 9;
3794         if (max < 0) max = 0;
3795         if (max <= biovec->bv_len && bio_sectors == 0)
3796                 return biovec->bv_len;
3797         else
3798                 return max;
3799 }
3800
3801
3802 static int in_chunk_boundary(struct mddev *mddev, struct bio *bio)
3803 {
3804         sector_t sector = bio->bi_sector + get_start_sect(bio->bi_bdev);
3805         unsigned int chunk_sectors = mddev->chunk_sectors;
3806         unsigned int bio_sectors = bio_sectors(bio);
3807
3808         if (mddev->new_chunk_sectors < mddev->chunk_sectors)
3809                 chunk_sectors = mddev->new_chunk_sectors;
3810         return  chunk_sectors >=
3811                 ((sector & (chunk_sectors - 1)) + bio_sectors);
3812 }
3813
3814 /*
3815  *  add bio to the retry LIFO  ( in O(1) ... we are in interrupt )
3816  *  later sampled by raid5d.
3817  */
3818 static void add_bio_to_retry(struct bio *bi,struct r5conf *conf)
3819 {
3820         unsigned long flags;
3821
3822         spin_lock_irqsave(&conf->device_lock, flags);
3823
3824         bi->bi_next = conf->retry_read_aligned_list;
3825         conf->retry_read_aligned_list = bi;
3826
3827         spin_unlock_irqrestore(&conf->device_lock, flags);
3828         md_wakeup_thread(conf->mddev->thread);
3829 }
3830
3831
3832 static struct bio *remove_bio_from_retry(struct r5conf *conf)
3833 {
3834         struct bio *bi;
3835
3836         bi = conf->retry_read_aligned;
3837         if (bi) {
3838                 conf->retry_read_aligned = NULL;
3839                 return bi;
3840         }
3841         bi = conf->retry_read_aligned_list;
3842         if(bi) {
3843                 conf->retry_read_aligned_list = bi->bi_next;
3844                 bi->bi_next = NULL;
3845                 /*
3846                  * this sets the active strip count to 1 and the processed
3847                  * strip count to zero (upper 8 bits)
3848                  */
3849                 raid5_set_bi_stripes(bi, 1); /* biased count of active stripes */
3850         }
3851
3852         return bi;
3853 }
3854
3855
3856 /*
3857  *  The "raid5_align_endio" should check if the read succeeded and if it
3858  *  did, call bio_endio on the original bio (having bio_put the new bio
3859  *  first).
3860  *  If the read failed..
3861  */
3862 static void raid5_align_endio(struct bio *bi, int error)
3863 {
3864         struct bio* raid_bi  = bi->bi_private;
3865         struct mddev *mddev;
3866         struct r5conf *conf;
3867         int uptodate = test_bit(BIO_UPTODATE, &bi->bi_flags);
3868         struct md_rdev *rdev;
3869
3870         bio_put(bi);
3871
3872         rdev = (void*)raid_bi->bi_next;
3873         raid_bi->bi_next = NULL;
3874         mddev = rdev->mddev;
3875         conf = mddev->private;
3876
3877         rdev_dec_pending(rdev, conf->mddev);
3878
3879         if (!error && uptodate) {
3880                 bio_endio(raid_bi, 0);
3881                 if (atomic_dec_and_test(&conf->active_aligned_reads))
3882                         wake_up(&conf->wait_for_stripe);
3883                 return;
3884         }
3885
3886
3887         pr_debug("raid5_align_endio : io error...handing IO for a retry\n");
3888
3889         add_bio_to_retry(raid_bi, conf);
3890 }
3891
3892 static int bio_fits_rdev(struct bio *bi)
3893 {
3894         struct request_queue *q = bdev_get_queue(bi->bi_bdev);
3895
3896         if (bio_sectors(bi) > queue_max_sectors(q))
3897                 return 0;
3898         blk_recount_segments(q, bi);
3899         if (bi->bi_phys_segments > queue_max_segments(q))
3900                 return 0;
3901
3902         if (q->merge_bvec_fn)
3903                 /* it's too hard to apply the merge_bvec_fn at this stage,
3904                  * just just give up
3905                  */
3906                 return 0;
3907
3908         return 1;
3909 }
3910
3911
3912 static int chunk_aligned_read(struct mddev *mddev, struct bio * raid_bio)
3913 {
3914         struct r5conf *conf = mddev->private;
3915         int dd_idx;
3916         struct bio* align_bi;
3917         struct md_rdev *rdev;
3918         sector_t end_sector;
3919
3920         if (!in_chunk_boundary(mddev, raid_bio)) {
3921                 pr_debug("chunk_aligned_read : non aligned\n");
3922                 return 0;
3923         }
3924         /*
3925          * use bio_clone_mddev to make a copy of the bio
3926          */
3927         align_bi = bio_clone_mddev(raid_bio, GFP_NOIO, mddev);
3928         if (!align_bi)
3929                 return 0;
3930         /*
3931          *   set bi_end_io to a new function, and set bi_private to the
3932          *     original bio.
3933          */
3934         align_bi->bi_end_io  = raid5_align_endio;
3935         align_bi->bi_private = raid_bio;
3936         /*
3937          *      compute position
3938          */
3939         align_bi->bi_sector =  raid5_compute_sector(conf, raid_bio->bi_sector,
3940                                                     0,
3941                                                     &dd_idx, NULL);
3942
3943         end_sector = bio_end_sector(align_bi);
3944         rcu_read_lock();
3945         rdev = rcu_dereference(conf->disks[dd_idx].replacement);
3946         if (!rdev || test_bit(Faulty, &rdev->flags) ||
3947             rdev->recovery_offset < end_sector) {
3948                 rdev = rcu_dereference(conf->disks[dd_idx].rdev);
3949                 if (rdev &&
3950                     (test_bit(Faulty, &rdev->flags) ||
3951                     !(test_bit(In_sync, &rdev->flags) ||
3952                       rdev->recovery_offset >= end_sector)))
3953                         rdev = NULL;
3954         }
3955         if (rdev) {
3956                 sector_t first_bad;
3957                 int bad_sectors;
3958
3959                 atomic_inc(&rdev->nr_pending);
3960                 rcu_read_unlock();
3961                 raid_bio->bi_next = (void*)rdev;
3962                 align_bi->bi_bdev =  rdev->bdev;
3963                 align_bi->bi_flags &= ~(1 << BIO_SEG_VALID);
3964
3965                 if (!bio_fits_rdev(align_bi) ||
3966                     is_badblock(rdev, align_bi->bi_sector, bio_sectors(align_bi),
3967                                 &first_bad, &bad_sectors)) {
3968                         /* too big in some way, or has a known bad block */
3969                         bio_put(align_bi);
3970                         rdev_dec_pending(rdev, mddev);
3971                         return 0;
3972                 }
3973
3974                 /* No reshape active, so we can trust rdev->data_offset */
3975                 align_bi->bi_sector += rdev->data_offset;
3976
3977                 spin_lock_irq(&conf->device_lock);
3978                 wait_event_lock_irq(conf->wait_for_stripe,
3979                                     conf->quiesce == 0,
3980                                     conf->device_lock);
3981                 atomic_inc(&conf->active_aligned_reads);
3982                 spin_unlock_irq(&conf->device_lock);
3983
3984                 trace_block_bio_remap(bdev_get_queue(align_bi->bi_bdev),
3985                                       align_bi, disk_devt(mddev->gendisk),
3986                                       raid_bio->bi_sector);
3987                 generic_make_request(align_bi);
3988                 return 1;
3989         } else {
3990                 rcu_read_unlock();
3991                 bio_put(align_bi);
3992                 return 0;
3993         }
3994 }
3995
3996 /* __get_priority_stripe - get the next stripe to process
3997  *
3998  * Full stripe writes are allowed to pass preread active stripes up until
3999  * the bypass_threshold is exceeded.  In general the bypass_count
4000  * increments when the handle_list is handled before the hold_list; however, it
4001  * will not be incremented when STRIPE_IO_STARTED is sampled set signifying a
4002  * stripe with in flight i/o.  The bypass_count will be reset when the
4003  * head of the hold_list has changed, i.e. the head was promoted to the
4004  * handle_list.
4005  */
4006 static struct stripe_head *__get_priority_stripe(struct r5conf *conf)
4007 {
4008         struct stripe_head *sh;
4009
4010         pr_debug("%s: handle: %s hold: %s full_writes: %d bypass_count: %d\n",
4011                   __func__,
4012                   list_empty(&conf->handle_list) ? "empty" : "busy",
4013                   list_empty(&conf->hold_list) ? "empty" : "busy",
4014                   atomic_read(&conf->pending_full_writes), conf->bypass_count);
4015
4016         if (!list_empty(&conf->handle_list)) {
4017                 sh = list_entry(conf->handle_list.next, typeof(*sh), lru);
4018
4019                 if (list_empty(&conf->hold_list))
4020                         conf->bypass_count = 0;
4021                 else if (!test_bit(STRIPE_IO_STARTED, &sh->state)) {
4022                         if (conf->hold_list.next == conf->last_hold)
4023                                 conf->bypass_count++;
4024                         else {
4025                                 conf->last_hold = conf->hold_list.next;
4026                                 conf->bypass_count -= conf->bypass_threshold;
4027                                 if (conf->bypass_count < 0)
4028                                         conf->bypass_count = 0;
4029                         }
4030                 }
4031         } else if (!list_empty(&conf->hold_list) &&
4032                    ((conf->bypass_threshold &&
4033                      conf->bypass_count > conf->bypass_threshold) ||
4034                     atomic_read(&conf->pending_full_writes) == 0)) {
4035                 sh = list_entry(conf->hold_list.next,
4036                                 typeof(*sh), lru);
4037                 conf->bypass_count -= conf->bypass_threshold;
4038                 if (conf->bypass_count < 0)
4039                         conf->bypass_count = 0;
4040         } else
4041                 return NULL;
4042
4043         list_del_init(&sh->lru);
4044         atomic_inc(&sh->count);
4045         BUG_ON(atomic_read(&sh->count) != 1);
4046         return sh;
4047 }
4048
4049 struct raid5_plug_cb {
4050         struct blk_plug_cb      cb;
4051         struct list_head        list;
4052 };
4053
4054 static void raid5_unplug(struct blk_plug_cb *blk_cb, bool from_schedule)
4055 {
4056         struct raid5_plug_cb *cb = container_of(
4057                 blk_cb, struct raid5_plug_cb, cb);
4058         struct stripe_head *sh;
4059         struct mddev *mddev = cb->cb.data;
4060         struct r5conf *conf = mddev->private;
4061         int cnt = 0;
4062
4063         if (cb->list.next && !list_empty(&cb->list)) {
4064                 spin_lock_irq(&conf->device_lock);
4065                 while (!list_empty(&cb->list)) {
4066                         sh = list_first_entry(&cb->list, struct stripe_head, lru);
4067                         list_del_init(&sh->lru);
4068                         /*
4069                          * avoid race release_stripe_plug() sees
4070                          * STRIPE_ON_UNPLUG_LIST clear but the stripe
4071                          * is still in our list
4072                          */
4073                         smp_mb__before_clear_bit();
4074                         clear_bit(STRIPE_ON_UNPLUG_LIST, &sh->state);
4075                         __release_stripe(conf, sh);
4076                         cnt++;
4077                 }
4078                 spin_unlock_irq(&conf->device_lock);
4079         }
4080         trace_block_unplug(mddev->queue, cnt, !from_schedule);
4081         kfree(cb);
4082 }
4083
4084 static void release_stripe_plug(struct mddev *mddev,
4085                                 struct stripe_head *sh)
4086 {
4087         struct blk_plug_cb *blk_cb = blk_check_plugged(
4088                 raid5_unplug, mddev,
4089                 sizeof(struct raid5_plug_cb));
4090         struct raid5_plug_cb *cb;
4091
4092         if (!blk_cb) {
4093                 release_stripe(sh);
4094                 return;
4095         }
4096
4097         cb = container_of(blk_cb, struct raid5_plug_cb, cb);
4098
4099         if (cb->list.next == NULL)
4100                 INIT_LIST_HEAD(&cb->list);
4101
4102         if (!test_and_set_bit(STRIPE_ON_UNPLUG_LIST, &sh->state))
4103                 list_add_tail(&sh->lru, &cb->list);
4104         else
4105                 release_stripe(sh);
4106 }
4107
4108 static void make_discard_request(struct mddev *mddev, struct bio *bi)
4109 {
4110         struct r5conf *conf = mddev->private;
4111         sector_t logical_sector, last_sector;
4112         struct stripe_head *sh;
4113         int remaining;
4114         int stripe_sectors;
4115
4116         if (mddev->reshape_position != MaxSector)
4117                 /* Skip discard while reshape is happening */
4118                 return;
4119
4120         logical_sector = bi->bi_sector & ~((sector_t)STRIPE_SECTORS-1);
4121         last_sector = bi->bi_sector + (bi->bi_size>>9);
4122
4123         bi->bi_next = NULL;
4124         bi->bi_phys_segments = 1; /* over-loaded to count active stripes */
4125
4126         stripe_sectors = conf->chunk_sectors *
4127                 (conf->raid_disks - conf->max_degraded);
4128         logical_sector = DIV_ROUND_UP_SECTOR_T(logical_sector,
4129                                                stripe_sectors);
4130         sector_div(last_sector, stripe_sectors);
4131
4132         logical_sector *= conf->chunk_sectors;
4133         last_sector *= conf->chunk_sectors;
4134
4135         for (; logical_sector < last_sector;
4136              logical_sector += STRIPE_SECTORS) {
4137                 DEFINE_WAIT(w);
4138                 int d;
4139         again:
4140                 sh = get_active_stripe(conf, logical_sector, 0, 0, 0);
4141                 prepare_to_wait(&conf->wait_for_overlap, &w,
4142                                 TASK_UNINTERRUPTIBLE);
4143                 spin_lock_irq(&sh->stripe_lock);
4144                 for (d = 0; d < conf->raid_disks; d++) {
4145                         if (d == sh->pd_idx || d == sh->qd_idx)
4146                                 continue;
4147                         if (sh->dev[d].towrite || sh->dev[d].toread) {
4148                                 set_bit(R5_Overlap, &sh->dev[d].flags);
4149                                 spin_unlock_irq(&sh->stripe_lock);
4150                                 release_stripe(sh);
4151                                 schedule();
4152                                 goto again;
4153                         }
4154                 }
4155                 finish_wait(&conf->wait_for_overlap, &w);
4156                 for (d = 0; d < conf->raid_disks; d++) {
4157                         if (d == sh->pd_idx || d == sh->qd_idx)
4158                                 continue;
4159                         sh->dev[d].towrite = bi;
4160                         set_bit(R5_OVERWRITE, &sh->dev[d].flags);
4161                         raid5_inc_bi_active_stripes(bi);
4162                 }
4163                 spin_unlock_irq(&sh->stripe_lock);
4164                 if (conf->mddev->bitmap) {
4165                         for (d = 0;
4166                              d < conf->raid_disks - conf->max_degraded;
4167                              d++)
4168                                 bitmap_startwrite(mddev->bitmap,
4169                                                   sh->sector,
4170                                                   STRIPE_SECTORS,
4171                                                   0);
4172                         sh->bm_seq = conf->seq_flush + 1;
4173                         set_bit(STRIPE_BIT_DELAY, &sh->state);
4174                 }
4175
4176                 set_bit(STRIPE_HANDLE, &sh->state);
4177                 clear_bit(STRIPE_DELAYED, &sh->state);
4178                 if (!test_and_set_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
4179                         atomic_inc(&conf->preread_active_stripes);
4180                 release_stripe_plug(mddev, sh);
4181         }
4182
4183         remaining = raid5_dec_bi_active_stripes(bi);
4184         if (remaining == 0) {
4185                 md_write_end(mddev);
4186                 bio_endio(bi, 0);
4187         }
4188 }
4189
4190 static void make_request(struct mddev *mddev, struct bio * bi)
4191 {
4192         struct r5conf *conf = mddev->private;
4193         int dd_idx;
4194         sector_t new_sector;
4195         sector_t logical_sector, last_sector;
4196         struct stripe_head *sh;
4197         const int rw = bio_data_dir(bi);
4198         int remaining;
4199
4200         if (unlikely(bi->bi_rw & REQ_FLUSH)) {
4201                 md_flush_request(mddev, bi);
4202                 return;
4203         }
4204
4205         md_write_start(mddev, bi);
4206
4207         if (rw == READ &&
4208              mddev->reshape_position == MaxSector &&
4209              chunk_aligned_read(mddev,bi))
4210                 return;
4211
4212         if (unlikely(bi->bi_rw & REQ_DISCARD)) {
4213                 make_discard_request(mddev, bi);
4214                 return;
4215         }
4216
4217         logical_sector = bi->bi_sector & ~((sector_t)STRIPE_SECTORS-1);
4218         last_sector = bio_end_sector(bi);
4219         bi->bi_next = NULL;
4220         bi->bi_phys_segments = 1;       /* over-loaded to count active stripes */
4221
4222         for (;logical_sector < last_sector; logical_sector += STRIPE_SECTORS) {
4223                 DEFINE_WAIT(w);
4224                 int previous;
4225
4226         retry:
4227                 previous = 0;
4228                 prepare_to_wait(&conf->wait_for_overlap, &w, TASK_UNINTERRUPTIBLE);
4229                 if (unlikely(conf->reshape_progress != MaxSector)) {
4230                         /* spinlock is needed as reshape_progress may be
4231                          * 64bit on a 32bit platform, and so it might be
4232                          * possible to see a half-updated value
4233                          * Of course reshape_progress could change after
4234                          * the lock is dropped, so once we get a reference
4235                          * to the stripe that we think it is, we will have
4236                          * to check again.
4237                          */
4238                         spin_lock_irq(&conf->device_lock);
4239                         if (mddev->reshape_backwards
4240                             ? logical_sector < conf->reshape_progress
4241                             : logical_sector >= conf->reshape_progress) {
4242                                 previous = 1;
4243                         } else {
4244                                 if (mddev->reshape_backwards
4245                                     ? logical_sector < conf->reshape_safe
4246                                     : logical_sector >= conf->reshape_safe) {
4247                                         spin_unlock_irq(&conf->device_lock);
4248                                         schedule();
4249                                         goto retry;
4250                                 }
4251                         }
4252                         spin_unlock_irq(&conf->device_lock);
4253                 }
4254
4255                 new_sector = raid5_compute_sector(conf, logical_sector,
4256                                                   previous,
4257                                                   &dd_idx, NULL);
4258                 pr_debug("raid456: make_request, sector %llu logical %llu\n",
4259                         (unsigned long long)new_sector, 
4260                         (unsigned long long)logical_sector);
4261
4262                 sh = get_active_stripe(conf, new_sector, previous,
4263                                        (bi->bi_rw&RWA_MASK), 0);
4264                 if (sh) {
4265                         if (unlikely(previous)) {
4266                                 /* expansion might have moved on while waiting for a
4267                                  * stripe, so we must do the range check again.
4268                                  * Expansion could still move past after this
4269                                  * test, but as we are holding a reference to
4270                                  * 'sh', we know that if that happens,
4271                                  *  STRIPE_EXPANDING will get set and the expansion
4272                                  * won't proceed until we finish with the stripe.
4273                                  */
4274                                 int must_retry = 0;
4275                                 spin_lock_irq(&conf->device_lock);
4276                                 if (mddev->reshape_backwards
4277                                     ? logical_sector >= conf->reshape_progress
4278                                     : logical_sector < conf->reshape_progress)
4279                                         /* mismatch, need to try again */
4280                                         must_retry = 1;
4281                                 spin_unlock_irq(&conf->device_lock);
4282                                 if (must_retry) {
4283                                         release_stripe(sh);
4284                                         schedule();
4285                                         goto retry;
4286                                 }
4287                         }
4288
4289                         if (rw == WRITE &&
4290                             logical_sector >= mddev->suspend_lo &&
4291                             logical_sector < mddev->suspend_hi) {
4292                                 release_stripe(sh);
4293                                 /* As the suspend_* range is controlled by
4294                                  * userspace, we want an interruptible
4295                                  * wait.
4296                                  */
4297                                 flush_signals(current);
4298                                 prepare_to_wait(&conf->wait_for_overlap,
4299                                                 &w, TASK_INTERRUPTIBLE);
4300                                 if (logical_sector >= mddev->suspend_lo &&
4301                                     logical_sector < mddev->suspend_hi)
4302                                         schedule();
4303                                 goto retry;
4304                         }
4305
4306                         if (test_bit(STRIPE_EXPANDING, &sh->state) ||
4307                             !add_stripe_bio(sh, bi, dd_idx, rw)) {
4308                                 /* Stripe is busy expanding or
4309                                  * add failed due to overlap.  Flush everything
4310                                  * and wait a while
4311                                  */
4312                                 md_wakeup_thread(mddev->thread);
4313                                 release_stripe(sh);
4314                                 schedule();
4315                                 goto retry;
4316                         }
4317                         finish_wait(&conf->wait_for_overlap, &w);
4318                         set_bit(STRIPE_HANDLE, &sh->state);
4319                         clear_bit(STRIPE_DELAYED, &sh->state);
4320                         if ((bi->bi_rw & REQ_SYNC) &&
4321                             !test_and_set_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
4322                                 atomic_inc(&conf->preread_active_stripes);
4323                         release_stripe_plug(mddev, sh);
4324                 } else {
4325                         /* cannot get stripe for read-ahead, just give-up */
4326                         clear_bit(BIO_UPTODATE, &bi->bi_flags);
4327                         finish_wait(&conf->wait_for_overlap, &w);
4328                         break;
4329                 }
4330         }
4331
4332         remaining = raid5_dec_bi_active_stripes(bi);
4333         if (remaining == 0) {
4334
4335                 if ( rw == WRITE )
4336                         md_write_end(mddev);
4337
4338                 bio_endio(bi, 0);
4339         }
4340 }
4341
4342 static sector_t raid5_size(struct mddev *mddev, sector_t sectors, int raid_disks);
4343
4344 static sector_t reshape_request(struct mddev *mddev, sector_t sector_nr, int *skipped)
4345 {
4346         /* reshaping is quite different to recovery/resync so it is
4347          * handled quite separately ... here.
4348          *
4349          * On each call to sync_request, we gather one chunk worth of
4350          * destination stripes and flag them as expanding.
4351          * Then we find all the source stripes and request reads.
4352          * As the reads complete, handle_stripe will copy the data
4353          * into the destination stripe and release that stripe.
4354          */
4355         struct r5conf *conf = mddev->private;
4356         struct stripe_head *sh;
4357         sector_t first_sector, last_sector;
4358         int raid_disks = conf->previous_raid_disks;
4359         int data_disks = raid_disks - conf->max_degraded;
4360         int new_data_disks = conf->raid_disks - conf->max_degraded;
4361         int i;
4362         int dd_idx;
4363         sector_t writepos, readpos, safepos;
4364         sector_t stripe_addr;
4365         int reshape_sectors;
4366         struct list_head stripes;
4367
4368         if (sector_nr == 0) {
4369                 /* If restarting in the middle, skip the initial sectors */
4370                 if (mddev->reshape_backwards &&
4371                     conf->reshape_progress < raid5_size(mddev, 0, 0)) {
4372                         sector_nr = raid5_size(mddev, 0, 0)
4373                                 - conf->reshape_progress;
4374                 } else if (!mddev->reshape_backwards &&
4375                            conf->reshape_progress > 0)
4376                         sector_nr = conf->reshape_progress;
4377                 sector_div(sector_nr, new_data_disks);
4378                 if (sector_nr) {
4379                         mddev->curr_resync_completed = sector_nr;
4380                         sysfs_notify(&mddev->kobj, NULL, "sync_completed");
4381                         *skipped = 1;
4382                         return sector_nr;
4383                 }
4384         }
4385
4386         /* We need to process a full chunk at a time.
4387          * If old and new chunk sizes differ, we need to process the
4388          * largest of these
4389          */
4390         if (mddev->new_chunk_sectors > mddev->chunk_sectors)
4391                 reshape_sectors = mddev->new_chunk_sectors;
4392         else
4393                 reshape_sectors = mddev->chunk_sectors;
4394
4395         /* We update the metadata at least every 10 seconds, or when
4396          * the data about to be copied would over-write the source of
4397          * the data at the front of the range.  i.e. one new_stripe
4398          * along from reshape_progress new_maps to after where
4399          * reshape_safe old_maps to
4400          */
4401         writepos = conf->reshape_progress;
4402         sector_div(writepos, new_data_disks);
4403         readpos = conf->reshape_progress;
4404         sector_div(readpos, data_disks);
4405         safepos = conf->reshape_safe;
4406         sector_div(safepos, data_disks);
4407         if (mddev->reshape_backwards) {
4408                 writepos -= min_t(sector_t, reshape_sectors, writepos);
4409                 readpos += reshape_sectors;
4410                 safepos += reshape_sectors;
4411         } else {
4412                 writepos += reshape_sectors;
4413                 readpos -= min_t(sector_t, reshape_sectors, readpos);
4414                 safepos -= min_t(sector_t, reshape_sectors, safepos);
4415         }
4416
4417         /* Having calculated the 'writepos' possibly use it
4418          * to set 'stripe_addr' which is where we will write to.
4419          */
4420         if (mddev->reshape_backwards) {
4421                 BUG_ON(conf->reshape_progress == 0);
4422                 stripe_addr = writepos;
4423                 BUG_ON((mddev->dev_sectors &
4424                         ~((sector_t)reshape_sectors - 1))
4425                        - reshape_sectors - stripe_addr
4426                        != sector_nr);
4427         } else {
4428                 BUG_ON(writepos != sector_nr + reshape_sectors);
4429                 stripe_addr = sector_nr;
4430         }
4431
4432         /* 'writepos' is the most advanced device address we might write.
4433          * 'readpos' is the least advanced device address we might read.
4434          * 'safepos' is the least address recorded in the metadata as having
4435          *     been reshaped.
4436          * If there is a min_offset_diff, these are adjusted either by
4437          * increasing the safepos/readpos if diff is negative, or
4438          * increasing writepos if diff is positive.
4439          * If 'readpos' is then behind 'writepos', there is no way that we can
4440          * ensure safety in the face of a crash - that must be done by userspace
4441          * making a backup of the data.  So in that case there is no particular
4442          * rush to update metadata.
4443          * Otherwise if 'safepos' is behind 'writepos', then we really need to
4444          * update the metadata to advance 'safepos' to match 'readpos' so that
4445          * we can be safe in the event of a crash.
4446          * So we insist on updating metadata if safepos is behind writepos and
4447          * readpos is beyond writepos.
4448          * In any case, update the metadata every 10 seconds.
4449          * Maybe that number should be configurable, but I'm not sure it is
4450          * worth it.... maybe it could be a multiple of safemode_delay???
4451          */
4452         if (conf->min_offset_diff < 0) {
4453                 safepos += -conf->min_offset_diff;
4454                 readpos += -conf->min_offset_diff;
4455         } else
4456                 writepos += conf->min_offset_diff;
4457
4458         if ((mddev->reshape_backwards
4459              ? (safepos > writepos && readpos < writepos)
4460              : (safepos < writepos && readpos > writepos)) ||
4461             time_after(jiffies, conf->reshape_checkpoint + 10*HZ)) {
4462                 /* Cannot proceed until we've updated the superblock... */
4463                 wait_event(conf->wait_for_overlap,
4464                            atomic_read(&conf->reshape_stripes)==0);
4465                 mddev->reshape_position = conf->reshape_progress;
4466                 mddev->curr_resync_completed = sector_nr;
4467                 conf->reshape_checkpoint = jiffies;
4468                 set_bit(MD_CHANGE_DEVS, &mddev->flags);
4469                 md_wakeup_thread(mddev->thread);
4470                 wait_event(mddev->sb_wait, mddev->flags == 0 ||
4471                            kthread_should_stop());
4472                 spin_lock_irq(&conf->device_lock);
4473                 conf->reshape_safe = mddev->reshape_position;
4474                 spin_unlock_irq(&conf->device_lock);
4475                 wake_up(&conf->wait_for_overlap);
4476                 sysfs_notify(&mddev->kobj, NULL, "sync_completed");
4477         }
4478
4479         INIT_LIST_HEAD(&stripes);
4480         for (i = 0; i < reshape_sectors; i += STRIPE_SECTORS) {
4481                 int j;
4482                 int skipped_disk = 0;
4483                 sh = get_active_stripe(conf, stripe_addr+i, 0, 0, 1);
4484                 set_bit(STRIPE_EXPANDING, &sh->state);
4485                 atomic_inc(&conf->reshape_stripes);
4486                 /* If any of this stripe is beyond the end of the old
4487                  * array, then we need to zero those blocks
4488                  */
4489                 for (j=sh->disks; j--;) {
4490                         sector_t s;
4491                         if (j == sh->pd_idx)
4492                                 continue;
4493                         if (conf->level == 6 &&
4494                             j == sh->qd_idx)
4495                                 continue;
4496                         s = compute_blocknr(sh, j, 0);
4497                         if (s < raid5_size(mddev, 0, 0)) {
4498                                 skipped_disk = 1;
4499                                 continue;
4500                         }
4501                         memset(page_address(sh->dev[j].page), 0, STRIPE_SIZE);
4502                         set_bit(R5_Expanded, &sh->dev[j].flags);
4503                         set_bit(R5_UPTODATE, &sh->dev[j].flags);
4504                 }
4505                 if (!skipped_disk) {
4506                         set_bit(STRIPE_EXPAND_READY, &sh->state);
4507                         set_bit(STRIPE_HANDLE, &sh->state);
4508                 }
4509                 list_add(&sh->lru, &stripes);
4510         }
4511         spin_lock_irq(&conf->device_lock);
4512         if (mddev->reshape_backwards)
4513                 conf->reshape_progress -= reshape_sectors * new_data_disks;
4514         else
4515                 conf->reshape_progress += reshape_sectors * new_data_disks;
4516         spin_unlock_irq(&conf->device_lock);
4517         /* Ok, those stripe are ready. We can start scheduling
4518          * reads on the source stripes.
4519          * The source stripes are determined by mapping the first and last
4520          * block on the destination stripes.
4521          */
4522         first_sector =
4523                 raid5_compute_sector(conf, stripe_addr*(new_data_disks),
4524                                      1, &dd_idx, NULL);
4525         last_sector =
4526                 raid5_compute_sector(conf, ((stripe_addr+reshape_sectors)
4527                                             * new_data_disks - 1),
4528                                      1, &dd_idx, NULL);
4529         if (last_sector >= mddev->dev_sectors)
4530                 last_sector = mddev->dev_sectors - 1;
4531         while (first_sector <= last_sector) {
4532                 sh = get_active_stripe(conf, first_sector, 1, 0, 1);
4533                 set_bit(STRIPE_EXPAND_SOURCE, &sh->state);
4534                 set_bit(STRIPE_HANDLE, &sh->state);
4535                 release_stripe(sh);
4536                 first_sector += STRIPE_SECTORS;
4537         }
4538         /* Now that the sources are clearly marked, we can release
4539          * the destination stripes
4540          */
4541         while (!list_empty(&stripes)) {
4542                 sh = list_entry(stripes.next, struct stripe_head, lru);
4543                 list_del_init(&sh->lru);
4544                 release_stripe(sh);
4545         }
4546         /* If this takes us to the resync_max point where we have to pause,
4547          * then we need to write out the superblock.
4548          */
4549         sector_nr += reshape_sectors;
4550         if ((sector_nr - mddev->curr_resync_completed) * 2
4551             >= mddev->resync_max - mddev->curr_resync_completed) {
4552                 /* Cannot proceed until we've updated the superblock... */
4553                 wait_event(conf->wait_for_overlap,
4554                            atomic_read(&conf->reshape_stripes) == 0);
4555                 mddev->reshape_position = conf->reshape_progress;
4556                 mddev->curr_resync_completed = sector_nr;
4557                 conf->reshape_checkpoint = jiffies;
4558                 set_bit(MD_CHANGE_DEVS, &mddev->flags);
4559                 md_wakeup_thread(mddev->thread);
4560                 wait_event(mddev->sb_wait,
4561                            !test_bit(MD_CHANGE_DEVS, &mddev->flags)
4562                            || kthread_should_stop());
4563                 spin_lock_irq(&conf->device_lock);
4564                 conf->reshape_safe = mddev->reshape_position;
4565                 spin_unlock_irq(&conf->device_lock);
4566                 wake_up(&conf->wait_for_overlap);
4567                 sysfs_notify(&mddev->kobj, NULL, "sync_completed");
4568         }
4569         return reshape_sectors;
4570 }
4571
4572 /* FIXME go_faster isn't used */
4573 static inline sector_t sync_request(struct mddev *mddev, sector_t sector_nr, int *skipped, int go_faster)
4574 {
4575         struct r5conf *conf = mddev->private;
4576         struct stripe_head *sh;
4577         sector_t max_sector = mddev->dev_sectors;
4578         sector_t sync_blocks;
4579         int still_degraded = 0;
4580         int i;
4581
4582         if (sector_nr >= max_sector) {
4583                 /* just being told to finish up .. nothing much to do */
4584
4585                 if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery)) {
4586                         end_reshape(conf);
4587                         return 0;
4588                 }
4589
4590                 if (mddev->curr_resync < max_sector) /* aborted */
4591                         bitmap_end_sync(mddev->bitmap, mddev->curr_resync,
4592                                         &sync_blocks, 1);
4593                 else /* completed sync */
4594                         conf->fullsync = 0;
4595                 bitmap_close_sync(mddev->bitmap);
4596
4597                 return 0;
4598         }
4599
4600         /* Allow raid5_quiesce to complete */
4601         wait_event(conf->wait_for_overlap, conf->quiesce != 2);
4602
4603         if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery))
4604                 return reshape_request(mddev, sector_nr, skipped);
4605
4606         /* No need to check resync_max as we never do more than one
4607          * stripe, and as resync_max will always be on a chunk boundary,
4608          * if the check in md_do_sync didn't fire, there is no chance
4609          * of overstepping resync_max here
4610          */
4611
4612         /* if there is too many failed drives and we are trying
4613          * to resync, then assert that we are finished, because there is
4614          * nothing we can do.
4615          */
4616         if (mddev->degraded >= conf->max_degraded &&
4617             test_bit(MD_RECOVERY_SYNC, &mddev->recovery)) {
4618                 sector_t rv = mddev->dev_sectors - sector_nr;
4619                 *skipped = 1;
4620                 return rv;
4621         }
4622         if (!bitmap_start_sync(mddev->bitmap, sector_nr, &sync_blocks, 1) &&
4623             !test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery) &&
4624             !conf->fullsync && sync_blocks >= STRIPE_SECTORS) {
4625                 /* we can skip this block, and probably more */
4626                 sync_blocks /= STRIPE_SECTORS;
4627                 *skipped = 1;
4628                 return sync_blocks * STRIPE_SECTORS; /* keep things rounded to whole stripes */
4629         }
4630
4631         bitmap_cond_end_sync(mddev->bitmap, sector_nr);
4632
4633         sh = get_active_stripe(conf, sector_nr, 0, 1, 0);
4634         if (sh == NULL) {
4635                 sh = get_active_stripe(conf, sector_nr, 0, 0, 0);
4636                 /* make sure we don't swamp the stripe cache if someone else
4637                  * is trying to get access
4638                  */
4639                 schedule_timeout_uninterruptible(1);
4640         }
4641         /* Need to check if array will still be degraded after recovery/resync
4642          * We don't need to check the 'failed' flag as when that gets set,
4643          * recovery aborts.
4644          */
4645         for (i = 0; i < conf->raid_disks; i++)
4646                 if (conf->disks[i].rdev == NULL)
4647                         still_degraded = 1;
4648
4649         bitmap_start_sync(mddev->bitmap, sector_nr, &sync_blocks, still_degraded);
4650
4651         set_bit(STRIPE_SYNC_REQUESTED, &sh->state);
4652
4653         handle_stripe(sh);
4654         release_stripe(sh);
4655
4656         return STRIPE_SECTORS;
4657 }
4658
4659 static int  retry_aligned_read(struct r5conf *conf, struct bio *raid_bio)
4660 {
4661         /* We may not be able to submit a whole bio at once as there
4662          * may not be enough stripe_heads available.
4663          * We cannot pre-allocate enough stripe_heads as we may need
4664          * more than exist in the cache (if we allow ever large chunks).
4665          * So we do one stripe head at a time and record in
4666          * ->bi_hw_segments how many have been done.
4667          *
4668          * We *know* that this entire raid_bio is in one chunk, so
4669          * it will be only one 'dd_idx' and only need one call to raid5_compute_sector.
4670          */
4671         struct stripe_head *sh;
4672         int dd_idx;
4673         sector_t sector, logical_sector, last_sector;
4674         int scnt = 0;
4675         int remaining;
4676         int handled = 0;
4677
4678         logical_sector = raid_bio->bi_sector & ~((sector_t)STRIPE_SECTORS-1);
4679         sector = raid5_compute_sector(conf, logical_sector,
4680                                       0, &dd_idx, NULL);
4681         last_sector = bio_end_sector(raid_bio);
4682
4683         for (; logical_sector < last_sector;
4684              logical_sector += STRIPE_SECTORS,
4685                      sector += STRIPE_SECTORS,
4686                      scnt++) {
4687
4688                 if (scnt < raid5_bi_processed_stripes(raid_bio))
4689                         /* already done this stripe */
4690                         continue;
4691
4692                 sh = get_active_stripe(conf, sector, 0, 1, 0);
4693
4694                 if (!sh) {
4695                         /* failed to get a stripe - must wait */
4696                         raid5_set_bi_processed_stripes(raid_bio, scnt);
4697                         conf->retry_read_aligned = raid_bio;
4698                         return handled;
4699                 }
4700
4701                 if (!add_stripe_bio(sh, raid_bio, dd_idx, 0)) {
4702                         release_stripe(sh);
4703                         raid5_set_bi_processed_stripes(raid_bio, scnt);
4704                         conf->retry_read_aligned = raid_bio;
4705                         return handled;
4706                 }
4707
4708                 set_bit(R5_ReadNoMerge, &sh->dev[dd_idx].flags);
4709                 handle_stripe(sh);
4710                 release_stripe(sh);
4711                 handled++;
4712         }
4713         remaining = raid5_dec_bi_active_stripes(raid_bio);
4714         if (remaining == 0)
4715                 bio_endio(raid_bio, 0);
4716         if (atomic_dec_and_test(&conf->active_aligned_reads))
4717                 wake_up(&conf->wait_for_stripe);
4718         return handled;
4719 }
4720
4721 #define MAX_STRIPE_BATCH 8
4722 static int handle_active_stripes(struct r5conf *conf)
4723 {
4724         struct stripe_head *batch[MAX_STRIPE_BATCH], *sh;
4725         int i, batch_size = 0;
4726
4727         while (batch_size < MAX_STRIPE_BATCH &&
4728                         (sh = __get_priority_stripe(conf)) != NULL)
4729                 batch[batch_size++] = sh;
4730
4731         if (batch_size == 0)
4732                 return batch_size;
4733         spin_unlock_irq(&conf->device_lock);
4734
4735         for (i = 0; i < batch_size; i++)
4736                 handle_stripe(batch[i]);
4737
4738         cond_resched();
4739
4740         spin_lock_irq(&conf->device_lock);
4741         for (i = 0; i < batch_size; i++)
4742                 __release_stripe(conf, batch[i]);
4743         return batch_size;
4744 }
4745
4746 /*
4747  * This is our raid5 kernel thread.
4748  *
4749  * We scan the hash table for stripes which can be handled now.
4750  * During the scan, completed stripes are saved for us by the interrupt
4751  * handler, so that they will not have to wait for our next wakeup.
4752  */
4753 static void raid5d(struct md_thread *thread)
4754 {
4755         struct mddev *mddev = thread->mddev;
4756         struct r5conf *conf = mddev->private;
4757         int handled;
4758         struct blk_plug plug;
4759
4760         pr_debug("+++ raid5d active\n");
4761
4762         md_check_recovery(mddev);
4763
4764         blk_start_plug(&plug);
4765         handled = 0;
4766         spin_lock_irq(&conf->device_lock);
4767         while (1) {
4768                 struct bio *bio;
4769                 int batch_size;
4770
4771                 if (
4772                     !list_empty(&conf->bitmap_list)) {
4773                         /* Now is a good time to flush some bitmap updates */
4774                         conf->seq_flush++;
4775                         spin_unlock_irq(&conf->device_lock);
4776                         bitmap_unplug(mddev->bitmap);
4777                         spin_lock_irq(&conf->device_lock);
4778                         conf->seq_write = conf->seq_flush;
4779                         activate_bit_delay(conf);
4780                 }
4781                 raid5_activate_delayed(conf);
4782
4783                 while ((bio = remove_bio_from_retry(conf))) {
4784                         int ok;
4785                         spin_unlock_irq(&conf->device_lock);
4786                         ok = retry_aligned_read(conf, bio);
4787                         spin_lock_irq(&conf->device_lock);
4788                         if (!ok)
4789                                 break;
4790                         handled++;
4791                 }
4792
4793                 batch_size = handle_active_stripes(conf);
4794                 if (!batch_size)
4795                         break;
4796                 handled += batch_size;
4797
4798                 if (mddev->flags & ~(1<<MD_CHANGE_PENDING)) {
4799                         spin_unlock_irq(&conf->device_lock);
4800                         md_check_recovery(mddev);
4801                         spin_lock_irq(&conf->device_lock);
4802                 }
4803         }
4804         pr_debug("%d stripes handled\n", handled);
4805
4806         spin_unlock_irq(&conf->device_lock);
4807
4808         async_tx_issue_pending_all();
4809         blk_finish_plug(&plug);
4810
4811         pr_debug("--- raid5d inactive\n");
4812 }
4813
4814 static ssize_t
4815 raid5_show_stripe_cache_size(struct mddev *mddev, char *page)
4816 {
4817         struct r5conf *conf = mddev->private;
4818         if (conf)
4819                 return sprintf(page, "%d\n", conf->max_nr_stripes);
4820         else
4821                 return 0;
4822 }
4823
4824 int
4825 raid5_set_cache_size(struct mddev *mddev, int size)
4826 {
4827         struct r5conf *conf = mddev->private;
4828         int err;
4829
4830         if (size <= 16 || size > 32768)
4831                 return -EINVAL;
4832         while (size < conf->max_nr_stripes) {
4833                 if (drop_one_stripe(conf))
4834                         conf->max_nr_stripes--;
4835                 else
4836                         break;
4837         }
4838         err = md_allow_write(mddev);
4839         if (err)
4840                 return err;
4841         while (size > conf->max_nr_stripes) {
4842                 if (grow_one_stripe(conf))
4843                         conf->max_nr_stripes++;
4844                 else break;
4845         }
4846         return 0;
4847 }
4848 EXPORT_SYMBOL(raid5_set_cache_size);
4849
4850 static ssize_t
4851 raid5_store_stripe_cache_size(struct mddev *mddev, const char *page, size_t len)
4852 {
4853         struct r5conf *conf = mddev->private;
4854         unsigned long new;
4855         int err;
4856
4857         if (len >= PAGE_SIZE)
4858                 return -EINVAL;
4859         if (!conf)
4860                 return -ENODEV;
4861
4862         if (strict_strtoul(page, 10, &new))
4863                 return -EINVAL;
4864         err = raid5_set_cache_size(mddev, new);
4865         if (err)
4866                 return err;
4867         return len;
4868 }
4869
4870 static struct md_sysfs_entry
4871 raid5_stripecache_size = __ATTR(stripe_cache_size, S_IRUGO | S_IWUSR,
4872                                 raid5_show_stripe_cache_size,
4873                                 raid5_store_stripe_cache_size);
4874
4875 static ssize_t
4876 raid5_show_preread_threshold(struct mddev *mddev, char *page)
4877 {
4878         struct r5conf *conf = mddev->private;
4879         if (conf)
4880                 return sprintf(page, "%d\n", conf->bypass_threshold);
4881         else
4882                 return 0;
4883 }
4884
4885 static ssize_t
4886 raid5_store_preread_threshold(struct mddev *mddev, const char *page, size_t len)
4887 {
4888         struct r5conf *conf = mddev->private;
4889         unsigned long new;
4890         if (len >= PAGE_SIZE)
4891                 return -EINVAL;
4892         if (!conf)
4893                 return -ENODEV;
4894
4895         if (strict_strtoul(page, 10, &new))
4896                 return -EINVAL;
4897         if (new > conf->max_nr_stripes)
4898                 return -EINVAL;
4899         conf->bypass_threshold = new;
4900         return len;
4901 }
4902
4903 static struct md_sysfs_entry
4904 raid5_preread_bypass_threshold = __ATTR(preread_bypass_threshold,
4905                                         S_IRUGO | S_IWUSR,
4906                                         raid5_show_preread_threshold,
4907                                         raid5_store_preread_threshold);
4908
4909 static ssize_t
4910 stripe_cache_active_show(struct mddev *mddev, char *page)
4911 {
4912         struct r5conf *conf = mddev->private;
4913         if (conf)
4914                 return sprintf(page, "%d\n", atomic_read(&conf->active_stripes));
4915         else
4916                 return 0;
4917 }
4918
4919 static struct md_sysfs_entry
4920 raid5_stripecache_active = __ATTR_RO(stripe_cache_active);
4921
4922 static struct attribute *raid5_attrs[] =  {
4923         &raid5_stripecache_size.attr,
4924         &raid5_stripecache_active.attr,
4925         &raid5_preread_bypass_threshold.attr,
4926         NULL,
4927 };
4928 static struct attribute_group raid5_attrs_group = {
4929         .name = NULL,
4930         .attrs = raid5_attrs,
4931 };
4932
4933 static sector_t
4934 raid5_size(struct mddev *mddev, sector_t sectors, int raid_disks)
4935 {
4936         struct r5conf *conf = mddev->private;
4937
4938         if (!sectors)
4939                 sectors = mddev->dev_sectors;
4940         if (!raid_disks)
4941                 /* size is defined by the smallest of previous and new size */
4942                 raid_disks = min(conf->raid_disks, conf->previous_raid_disks);
4943
4944         sectors &= ~((sector_t)mddev->chunk_sectors - 1);
4945         sectors &= ~((sector_t)mddev->new_chunk_sectors - 1);
4946         return sectors * (raid_disks - conf->max_degraded);
4947 }
4948
4949 static void raid5_free_percpu(struct r5conf *conf)
4950 {
4951         struct raid5_percpu *percpu;
4952         unsigned long cpu;
4953
4954         if (!conf->percpu)
4955                 return;
4956
4957         get_online_cpus();
4958         for_each_possible_cpu(cpu) {
4959                 percpu = per_cpu_ptr(conf->percpu, cpu);
4960                 safe_put_page(percpu->spare_page);
4961                 kfree(percpu->scribble);
4962         }
4963 #ifdef CONFIG_HOTPLUG_CPU
4964         unregister_cpu_notifier(&conf->cpu_notify);
4965 #endif
4966         put_online_cpus();
4967
4968         free_percpu(conf->percpu);
4969 }
4970
4971 static void free_conf(struct r5conf *conf)
4972 {
4973         shrink_stripes(conf);
4974         raid5_free_percpu(conf);
4975         kfree(conf->disks);
4976         kfree(conf->stripe_hashtbl);
4977         kfree(conf);
4978 }
4979
4980 #ifdef CONFIG_HOTPLUG_CPU
4981 static int raid456_cpu_notify(struct notifier_block *nfb, unsigned long action,
4982                               void *hcpu)
4983 {
4984         struct r5conf *conf = container_of(nfb, struct r5conf, cpu_notify);
4985         long cpu = (long)hcpu;
4986         struct raid5_percpu *percpu = per_cpu_ptr(conf->percpu, cpu);
4987
4988         switch (action) {
4989         case CPU_UP_PREPARE:
4990         case CPU_UP_PREPARE_FROZEN:
4991                 if (conf->level == 6 && !percpu->spare_page)
4992                         percpu->spare_page = alloc_page(GFP_KERNEL);
4993                 if (!percpu->scribble)
4994                         percpu->scribble = kmalloc(conf->scribble_len, GFP_KERNEL);
4995
4996                 if (!percpu->scribble ||
4997                     (conf->level == 6 && !percpu->spare_page)) {
4998                         safe_put_page(percpu->spare_page);
4999                         kfree(percpu->scribble);
5000                         pr_err("%s: failed memory allocation for cpu%ld\n",
5001                                __func__, cpu);
5002                         return notifier_from_errno(-ENOMEM);
5003                 }
5004                 break;
5005         case CPU_DEAD:
5006         case CPU_DEAD_FROZEN:
5007                 safe_put_page(percpu->spare_page);
5008                 kfree(percpu->scribble);
5009                 percpu->spare_page = NULL;
5010                 percpu->scribble = NULL;
5011                 break;
5012         default:
5013                 break;
5014         }
5015         return NOTIFY_OK;
5016 }
5017 #endif
5018
5019 static int raid5_alloc_percpu(struct r5conf *conf)
5020 {
5021         unsigned long cpu;
5022         struct page *spare_page;
5023         struct raid5_percpu __percpu *allcpus;
5024         void *scribble;
5025         int err;
5026
5027         allcpus = alloc_percpu(struct raid5_percpu);
5028         if (!allcpus)
5029                 return -ENOMEM;
5030         conf->percpu = allcpus;
5031
5032         get_online_cpus();
5033         err = 0;
5034         for_each_present_cpu(cpu) {
5035                 if (conf->level == 6) {
5036                         spare_page = alloc_page(GFP_KERNEL);
5037                         if (!spare_page) {
5038                                 err = -ENOMEM;
5039                                 break;
5040                         }
5041                         per_cpu_ptr(conf->percpu, cpu)->spare_page = spare_page;
5042                 }
5043                 scribble = kmalloc(conf->scribble_len, GFP_KERNEL);
5044                 if (!scribble) {
5045                         err = -ENOMEM;
5046                         break;
5047                 }
5048                 per_cpu_ptr(conf->percpu, cpu)->scribble = scribble;
5049         }
5050 #ifdef CONFIG_HOTPLUG_CPU
5051         conf->cpu_notify.notifier_call = raid456_cpu_notify;
5052         conf->cpu_notify.priority = 0;
5053         if (err == 0)
5054                 err = register_cpu_notifier(&conf->cpu_notify);
5055 #endif
5056         put_online_cpus();
5057
5058         return err;
5059 }
5060
5061 static struct r5conf *setup_conf(struct mddev *mddev)
5062 {
5063         struct r5conf *conf;
5064         int raid_disk, memory, max_disks;
5065         struct md_rdev *rdev;
5066         struct disk_info *disk;
5067         char pers_name[6];
5068
5069         if (mddev->new_level != 5
5070             && mddev->new_level != 4
5071             && mddev->new_level != 6) {
5072                 printk(KERN_ERR "md/raid:%s: raid level not set to 4/5/6 (%d)\n",
5073                        mdname(mddev), mddev->new_level);
5074                 return ERR_PTR(-EIO);
5075         }
5076         if ((mddev->new_level == 5
5077              && !algorithm_valid_raid5(mddev->new_layout)) ||
5078             (mddev->new_level == 6
5079              && !algorithm_valid_raid6(mddev->new_layout))) {
5080                 printk(KERN_ERR "md/raid:%s: layout %d not supported\n",
5081                        mdname(mddev), mddev->new_layout);
5082                 return ERR_PTR(-EIO);
5083         }
5084         if (mddev->new_level == 6 && mddev->raid_disks < 4) {
5085                 printk(KERN_ERR "md/raid:%s: not enough configured devices (%d, minimum 4)\n",
5086                        mdname(mddev), mddev->raid_disks);
5087                 return ERR_PTR(-EINVAL);
5088         }
5089
5090         if (!mddev->new_chunk_sectors ||
5091             (mddev->new_chunk_sectors << 9) % PAGE_SIZE ||
5092             !is_power_of_2(mddev->new_chunk_sectors)) {
5093                 printk(KERN_ERR "md/raid:%s: invalid chunk size %d\n",
5094                        mdname(mddev), mddev->new_chunk_sectors << 9);
5095                 return ERR_PTR(-EINVAL);
5096         }
5097
5098         conf = kzalloc(sizeof(struct r5conf), GFP_KERNEL);
5099         if (conf == NULL)
5100                 goto abort;
5101         spin_lock_init(&conf->device_lock);
5102         init_waitqueue_head(&conf->wait_for_stripe);
5103         init_waitqueue_head(&conf->wait_for_overlap);
5104         INIT_LIST_HEAD(&conf->handle_list);
5105         INIT_LIST_HEAD(&conf->hold_list);
5106         INIT_LIST_HEAD(&conf->delayed_list);
5107         INIT_LIST_HEAD(&conf->bitmap_list);
5108         INIT_LIST_HEAD(&conf->inactive_list);
5109         atomic_set(&conf->active_stripes, 0);
5110         atomic_set(&conf->preread_active_stripes, 0);
5111         atomic_set(&conf->active_aligned_reads, 0);
5112         conf->bypass_threshold = BYPASS_THRESHOLD;
5113         conf->recovery_disabled = mddev->recovery_disabled - 1;
5114
5115         conf->raid_disks = mddev->raid_disks;
5116         if (mddev->reshape_position == MaxSector)
5117                 conf->previous_raid_disks = mddev->raid_disks;
5118         else
5119                 conf->previous_raid_disks = mddev->raid_disks - mddev->delta_disks;
5120         max_disks = max(conf->raid_disks, conf->previous_raid_disks);
5121         conf->scribble_len = scribble_len(max_disks);
5122
5123         conf->disks = kzalloc(max_disks * sizeof(struct disk_info),
5124                               GFP_KERNEL);
5125         if (!conf->disks)
5126                 goto abort;
5127
5128         conf->mddev = mddev;
5129
5130         if ((conf->stripe_hashtbl = kzalloc(PAGE_SIZE, GFP_KERNEL)) == NULL)
5131                 goto abort;
5132
5133         conf->level = mddev->new_level;
5134         if (raid5_alloc_percpu(conf) != 0)
5135                 goto abort;
5136
5137         pr_debug("raid456: run(%s) called.\n", mdname(mddev));
5138
5139         rdev_for_each(rdev, mddev) {
5140                 raid_disk = rdev->raid_disk;
5141                 if (raid_disk >= max_disks
5142                     || raid_disk < 0)
5143                         continue;
5144                 disk = conf->disks + raid_disk;
5145
5146                 if (test_bit(Replacement, &rdev->flags)) {
5147                         if (disk->replacement)
5148                                 goto abort;
5149                         disk->replacement = rdev;
5150                 } else {
5151                         if (disk->rdev)
5152                                 goto abort;
5153                         disk->rdev = rdev;
5154                 }
5155
5156                 if (test_bit(In_sync, &rdev->flags)) {
5157                         char b[BDEVNAME_SIZE];
5158                         printk(KERN_INFO "md/raid:%s: device %s operational as raid"
5159                                " disk %d\n",
5160                                mdname(mddev), bdevname(rdev->bdev, b), raid_disk);
5161                 } else if (rdev->saved_raid_disk != raid_disk)
5162                         /* Cannot rely on bitmap to complete recovery */
5163                         conf->fullsync = 1;
5164         }
5165
5166         conf->chunk_sectors = mddev->new_chunk_sectors;
5167         conf->level = mddev->new_level;
5168         if (conf->level == 6)
5169                 conf->max_degraded = 2;
5170         else
5171                 conf->max_degraded = 1;
5172         conf->algorithm = mddev->new_layout;
5173         conf->max_nr_stripes = NR_STRIPES;
5174         conf->reshape_progress = mddev->reshape_position;
5175         if (conf->reshape_progress != MaxSector) {
5176                 conf->prev_chunk_sectors = mddev->chunk_sectors;
5177                 conf->prev_algo = mddev->layout;
5178         }
5179
5180         memory = conf->max_nr_stripes * (sizeof(struct stripe_head) +
5181                  max_disks * ((sizeof(struct bio) + PAGE_SIZE))) / 1024;
5182         if (grow_stripes(conf, conf->max_nr_stripes)) {
5183                 printk(KERN_ERR
5184                        "md/raid:%s: couldn't allocate %dkB for buffers\n",
5185                        mdname(mddev), memory);
5186                 goto abort;
5187         } else
5188                 printk(KERN_INFO "md/raid:%s: allocated %dkB\n",
5189                        mdname(mddev), memory);
5190
5191         sprintf(pers_name, "raid%d", mddev->new_level);
5192         conf->thread = md_register_thread(raid5d, mddev, pers_name);
5193         if (!conf->thread) {
5194                 printk(KERN_ERR
5195                        "md/raid:%s: couldn't allocate thread.\n",
5196                        mdname(mddev));
5197                 goto abort;
5198         }
5199
5200         return conf;
5201
5202  abort:
5203         if (conf) {
5204                 free_conf(conf);
5205                 return ERR_PTR(-EIO);
5206         } else
5207                 return ERR_PTR(-ENOMEM);
5208 }
5209
5210
5211 static int only_parity(int raid_disk, int algo, int raid_disks, int max_degraded)
5212 {
5213         switch (algo) {
5214         case ALGORITHM_PARITY_0:
5215                 if (raid_disk < max_degraded)
5216                         return 1;
5217                 break;
5218         case ALGORITHM_PARITY_N:
5219                 if (raid_disk >= raid_disks - max_degraded)
5220                         return 1;
5221                 break;
5222         case ALGORITHM_PARITY_0_6:
5223                 if (raid_disk == 0 || 
5224                     raid_disk == raid_disks - 1)
5225                         return 1;
5226                 break;
5227         case ALGORITHM_LEFT_ASYMMETRIC_6:
5228         case ALGORITHM_RIGHT_ASYMMETRIC_6:
5229         case ALGORITHM_LEFT_SYMMETRIC_6:
5230         case ALGORITHM_RIGHT_SYMMETRIC_6:
5231                 if (raid_disk == raid_disks - 1)
5232                         return 1;
5233         }
5234         return 0;
5235 }
5236
5237 static int run(struct mddev *mddev)
5238 {
5239         struct r5conf *conf;
5240         int working_disks = 0;
5241         int dirty_parity_disks = 0;
5242         struct md_rdev *rdev;
5243         sector_t reshape_offset = 0;
5244         int i;
5245         long long min_offset_diff = 0;
5246         int first = 1;
5247
5248         if (mddev->recovery_cp != MaxSector)
5249                 printk(KERN_NOTICE "md/raid:%s: not clean"
5250                        " -- starting background reconstruction\n",
5251                        mdname(mddev));
5252
5253         rdev_for_each(rdev, mddev) {
5254                 long long diff;
5255                 if (rdev->raid_disk < 0)
5256                         continue;
5257                 diff = (rdev->new_data_offset - rdev->data_offset);
5258                 if (first) {
5259                         min_offset_diff = diff;
5260                         first = 0;
5261                 } else if (mddev->reshape_backwards &&
5262                          diff < min_offset_diff)
5263                         min_offset_diff = diff;
5264                 else if (!mddev->reshape_backwards &&
5265                          diff > min_offset_diff)
5266                         min_offset_diff = diff;
5267         }
5268
5269         if (mddev->reshape_position != MaxSector) {
5270                 /* Check that we can continue the reshape.
5271                  * Difficulties arise if the stripe we would write to
5272                  * next is at or after the stripe we would read from next.
5273                  * For a reshape that changes the number of devices, this
5274                  * is only possible for a very short time, and mdadm makes
5275                  * sure that time appears to have past before assembling
5276                  * the array.  So we fail if that time hasn't passed.
5277                  * For a reshape that keeps the number of devices the same
5278                  * mdadm must be monitoring the reshape can keeping the
5279                  * critical areas read-only and backed up.  It will start
5280                  * the array in read-only mode, so we check for that.
5281                  */
5282                 sector_t here_new, here_old;
5283                 int old_disks;
5284                 int max_degraded = (mddev->level == 6 ? 2 : 1);
5285
5286                 if (mddev->new_level != mddev->level) {
5287                         printk(KERN_ERR "md/raid:%s: unsupported reshape "
5288                                "required - aborting.\n",
5289                                mdname(mddev));
5290                         return -EINVAL;
5291                 }
5292                 old_disks = mddev->raid_disks - mddev->delta_disks;
5293                 /* reshape_position must be on a new-stripe boundary, and one
5294                  * further up in new geometry must map after here in old
5295                  * geometry.
5296                  */
5297                 here_new = mddev->reshape_position;
5298                 if (sector_div(here_new, mddev->new_chunk_sectors *
5299                                (mddev->raid_disks - max_degraded))) {
5300                         printk(KERN_ERR "md/raid:%s: reshape_position not "
5301                                "on a stripe boundary\n", mdname(mddev));
5302                         return -EINVAL;
5303                 }
5304                 reshape_offset = here_new * mddev->new_chunk_sectors;
5305                 /* here_new is the stripe we will write to */
5306                 here_old = mddev->reshape_position;
5307                 sector_div(here_old, mddev->chunk_sectors *
5308                            (old_disks-max_degraded));
5309                 /* here_old is the first stripe that we might need to read
5310                  * from */
5311                 if (mddev->delta_disks == 0) {
5312                         if ((here_new * mddev->new_chunk_sectors !=
5313                              here_old * mddev->chunk_sectors)) {
5314                                 printk(KERN_ERR "md/raid:%s: reshape position is"
5315                                        " confused - aborting\n", mdname(mddev));
5316                                 return -EINVAL;
5317                         }
5318                         /* We cannot be sure it is safe to start an in-place
5319                          * reshape.  It is only safe if user-space is monitoring
5320                          * and taking constant backups.
5321                          * mdadm always starts a situation like this in
5322                          * readonly mode so it can take control before
5323                          * allowing any writes.  So just check for that.
5324                          */
5325                         if (abs(min_offset_diff) >= mddev->chunk_sectors &&
5326                             abs(min_offset_diff) >= mddev->new_chunk_sectors)
5327                                 /* not really in-place - so OK */;
5328                         else if (mddev->ro == 0) {
5329                                 printk(KERN_ERR "md/raid:%s: in-place reshape "
5330                                        "must be started in read-only mode "
5331                                        "- aborting\n",
5332                                        mdname(mddev));
5333                                 return -EINVAL;
5334                         }
5335                 } else if (mddev->reshape_backwards
5336                     ? (here_new * mddev->new_chunk_sectors + min_offset_diff <=
5337                        here_old * mddev->chunk_sectors)
5338                     : (here_new * mddev->new_chunk_sectors >=
5339                        here_old * mddev->chunk_sectors + (-min_offset_diff))) {
5340                         /* Reading from the same stripe as writing to - bad */
5341                         printk(KERN_ERR "md/raid:%s: reshape_position too early for "
5342                                "auto-recovery - aborting.\n",
5343                                mdname(mddev));
5344                         return -EINVAL;
5345                 }
5346                 printk(KERN_INFO "md/raid:%s: reshape will continue\n",
5347                        mdname(mddev));
5348                 /* OK, we should be able to continue; */
5349         } else {
5350                 BUG_ON(mddev->level != mddev->new_level);
5351                 BUG_ON(mddev->layout != mddev->new_layout);
5352                 BUG_ON(mddev->chunk_sectors != mddev->new_chunk_sectors);
5353                 BUG_ON(mddev->delta_disks != 0);
5354         }
5355
5356         if (mddev->private == NULL)
5357                 conf = setup_conf(mddev);
5358         else
5359                 conf = mddev->private;
5360
5361         if (IS_ERR(conf))
5362                 return PTR_ERR(conf);
5363
5364         conf->min_offset_diff = min_offset_diff;
5365         mddev->thread = conf->thread;
5366         conf->thread = NULL;
5367         mddev->private = conf;
5368
5369         for (i = 0; i < conf->raid_disks && conf->previous_raid_disks;
5370              i++) {
5371                 rdev = conf->disks[i].rdev;
5372                 if (!rdev && conf->disks[i].replacement) {
5373                         /* The replacement is all we have yet */
5374                         rdev = conf->disks[i].replacement;
5375                         conf->disks[i].replacement = NULL;
5376                         clear_bit(Replacement, &rdev->flags);
5377                         conf->disks[i].rdev = rdev;
5378                 }
5379                 if (!rdev)
5380                         continue;
5381                 if (conf->disks[i].replacement &&
5382                     conf->reshape_progress != MaxSector) {
5383                         /* replacements and reshape simply do not mix. */
5384                         printk(KERN_ERR "md: cannot handle concurrent "
5385                                "replacement and reshape.\n");
5386                         goto abort;
5387                 }
5388                 if (test_bit(In_sync, &rdev->flags)) {
5389                         working_disks++;
5390                         continue;
5391                 }
5392                 /* This disc is not fully in-sync.  However if it
5393                  * just stored parity (beyond the recovery_offset),
5394                  * when we don't need to be concerned about the
5395                  * array being dirty.
5396                  * When reshape goes 'backwards', we never have
5397                  * partially completed devices, so we only need
5398                  * to worry about reshape going forwards.
5399                  */
5400                 /* Hack because v0.91 doesn't store recovery_offset properly. */
5401                 if (mddev->major_version == 0 &&
5402                     mddev->minor_version > 90)
5403                         rdev->recovery_offset = reshape_offset;
5404                         
5405                 if (rdev->recovery_offset < reshape_offset) {
5406                         /* We need to check old and new layout */
5407                         if (!only_parity(rdev->raid_disk,
5408                                          conf->algorithm,
5409                                          conf->raid_disks,
5410                                          conf->max_degraded))
5411                                 continue;
5412                 }
5413                 if (!only_parity(rdev->raid_disk,
5414                                  conf->prev_algo,
5415                                  conf->previous_raid_disks,
5416                                  conf->max_degraded))
5417                         continue;
5418                 dirty_parity_disks++;
5419         }
5420
5421         /*
5422          * 0 for a fully functional array, 1 or 2 for a degraded array.
5423          */
5424         mddev->degraded = calc_degraded(conf);
5425
5426         if (has_failed(conf)) {
5427                 printk(KERN_ERR "md/raid:%s: not enough operational devices"
5428                         " (%d/%d failed)\n",
5429                         mdname(mddev), mddev->degraded, conf->raid_disks);
5430                 goto abort;
5431         }
5432
5433         /* device size must be a multiple of chunk size */
5434         mddev->dev_sectors &= ~(mddev->chunk_sectors - 1);
5435         mddev->resync_max_sectors = mddev->dev_sectors;
5436
5437         if (mddev->degraded > dirty_parity_disks &&
5438             mddev->recovery_cp != MaxSector) {
5439                 if (mddev->ok_start_degraded)
5440                         printk(KERN_WARNING
5441                                "md/raid:%s: starting dirty degraded array"
5442                                " - data corruption possible.\n",
5443                                mdname(mddev));
5444                 else {
5445                         printk(KERN_ERR
5446                                "md/raid:%s: cannot start dirty degraded array.\n",
5447                                mdname(mddev));
5448                         goto abort;
5449                 }
5450         }
5451
5452         if (mddev->degraded == 0)
5453                 printk(KERN_INFO "md/raid:%s: raid level %d active with %d out of %d"
5454                        " devices, algorithm %d\n", mdname(mddev), conf->level,
5455                        mddev->raid_disks-mddev->degraded, mddev->raid_disks,
5456                        mddev->new_layout);
5457         else
5458                 printk(KERN_ALERT "md/raid:%s: raid level %d active with %d"
5459                        " out of %d devices, algorithm %d\n",
5460                        mdname(mddev), conf->level,
5461                        mddev->raid_disks - mddev->degraded,
5462                        mddev->raid_disks, mddev->new_layout);
5463
5464         print_raid5_conf(conf);
5465
5466         if (conf->reshape_progress != MaxSector) {
5467                 conf->reshape_safe = conf->reshape_progress;
5468                 atomic_set(&conf->reshape_stripes, 0);
5469                 clear_bit(MD_RECOVERY_SYNC, &mddev->recovery);
5470                 clear_bit(MD_RECOVERY_CHECK, &mddev->recovery);
5471                 set_bit(MD_RECOVERY_RESHAPE, &mddev->recovery);
5472                 set_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
5473                 mddev->sync_thread = md_register_thread(md_do_sync, mddev,
5474                                                         "reshape");
5475         }
5476
5477
5478         /* Ok, everything is just fine now */
5479         if (mddev->to_remove == &raid5_attrs_group)
5480                 mddev->to_remove = NULL;
5481         else if (mddev->kobj.sd &&
5482             sysfs_create_group(&mddev->kobj, &raid5_attrs_group))
5483                 printk(KERN_WARNING
5484                        "raid5: failed to create sysfs attributes for %s\n",
5485                        mdname(mddev));
5486         md_set_array_sectors(mddev, raid5_size(mddev, 0, 0));
5487
5488         if (mddev->queue) {
5489                 int chunk_size;
5490                 bool discard_supported = true;
5491                 /* read-ahead size must cover two whole stripes, which
5492                  * is 2 * (datadisks) * chunksize where 'n' is the
5493                  * number of raid devices
5494                  */
5495                 int data_disks = conf->previous_raid_disks - conf->max_degraded;
5496                 int stripe = data_disks *
5497                         ((mddev->chunk_sectors << 9) / PAGE_SIZE);
5498                 if (mddev->queue->backing_dev_info.ra_pages < 2 * stripe)
5499                         mddev->queue->backing_dev_info.ra_pages = 2 * stripe;
5500
5501                 blk_queue_merge_bvec(mddev->queue, raid5_mergeable_bvec);
5502
5503                 mddev->queue->backing_dev_info.congested_data = mddev;
5504                 mddev->queue->backing_dev_info.congested_fn = raid5_congested;
5505
5506                 chunk_size = mddev->chunk_sectors << 9;
5507                 blk_queue_io_min(mddev->queue, chunk_size);
5508                 blk_queue_io_opt(mddev->queue, chunk_size *
5509                                  (conf->raid_disks - conf->max_degraded));
5510                 /*
5511                  * We can only discard a whole stripe. It doesn't make sense to
5512                  * discard data disk but write parity disk
5513                  */
5514                 stripe = stripe * PAGE_SIZE;
5515                 /* Round up to power of 2, as discard handling
5516                  * currently assumes that */
5517                 while ((stripe-1) & stripe)
5518                         stripe = (stripe | (stripe-1)) + 1;
5519                 mddev->queue->limits.discard_alignment = stripe;
5520                 mddev->queue->limits.discard_granularity = stripe;
5521                 /*
5522                  * unaligned part of discard request will be ignored, so can't
5523                  * guarantee discard_zerors_data
5524                  */
5525                 mddev->queue->limits.discard_zeroes_data = 0;
5526
5527                 rdev_for_each(rdev, mddev) {
5528                         disk_stack_limits(mddev->gendisk, rdev->bdev,
5529                                           rdev->data_offset << 9);
5530                         disk_stack_limits(mddev->gendisk, rdev->bdev,
5531                                           rdev->new_data_offset << 9);
5532                         /*
5533                          * discard_zeroes_data is required, otherwise data
5534                          * could be lost. Consider a scenario: discard a stripe
5535                          * (the stripe could be inconsistent if
5536                          * discard_zeroes_data is 0); write one disk of the
5537                          * stripe (the stripe could be inconsistent again
5538                          * depending on which disks are used to calculate
5539                          * parity); the disk is broken; The stripe data of this
5540                          * disk is lost.
5541                          */
5542                         if (!blk_queue_discard(bdev_get_queue(rdev->bdev)) ||
5543                             !bdev_get_queue(rdev->bdev)->
5544                                                 limits.discard_zeroes_data)
5545                                 discard_supported = false;
5546                 }
5547
5548                 if (discard_supported &&
5549                    mddev->queue->limits.max_discard_sectors >= stripe &&
5550                    mddev->queue->limits.discard_granularity >= stripe)
5551                         queue_flag_set_unlocked(QUEUE_FLAG_DISCARD,
5552                                                 mddev->queue);
5553                 else
5554                         queue_flag_clear_unlocked(QUEUE_FLAG_DISCARD,
5555                                                 mddev->queue);
5556         }
5557
5558         return 0;
5559 abort:
5560         md_unregister_thread(&mddev->thread);
5561         print_raid5_conf(conf);
5562         free_conf(conf);
5563         mddev->private = NULL;
5564         printk(KERN_ALERT "md/raid:%s: failed to run raid set.\n", mdname(mddev));
5565         return -EIO;
5566 }
5567
5568 static int stop(struct mddev *mddev)
5569 {
5570         struct r5conf *conf = mddev->private;
5571
5572         md_unregister_thread(&mddev->thread);
5573         if (mddev->queue)
5574                 mddev->queue->backing_dev_info.congested_fn = NULL;
5575         free_conf(conf);
5576         mddev->private = NULL;
5577         mddev->to_remove = &raid5_attrs_group;
5578         return 0;
5579 }
5580
5581 static void status(struct seq_file *seq, struct mddev *mddev)
5582 {
5583         struct r5conf *conf = mddev->private;
5584         int i;
5585
5586         seq_printf(seq, " level %d, %dk chunk, algorithm %d", mddev->level,
5587                 mddev->chunk_sectors / 2, mddev->layout);
5588         seq_printf (seq, " [%d/%d] [", conf->raid_disks, conf->raid_disks - mddev->degraded);
5589         for (i = 0; i < conf->raid_disks; i++)
5590                 seq_printf (seq, "%s",
5591                                conf->disks[i].rdev &&
5592                                test_bit(In_sync, &conf->disks[i].rdev->flags) ? "U" : "_");
5593         seq_printf (seq, "]");
5594 }
5595
5596 static void print_raid5_conf (struct r5conf *conf)
5597 {
5598         int i;
5599         struct disk_info *tmp;
5600
5601         printk(KERN_DEBUG "RAID conf printout:\n");
5602         if (!conf) {
5603                 printk("(conf==NULL)\n");
5604                 return;
5605         }
5606         printk(KERN_DEBUG " --- level:%d rd:%d wd:%d\n", conf->level,
5607                conf->raid_disks,
5608                conf->raid_disks - conf->mddev->degraded);
5609
5610         for (i = 0; i < conf->raid_disks; i++) {
5611                 char b[BDEVNAME_SIZE];
5612                 tmp = conf->disks + i;
5613                 if (tmp->rdev)
5614                         printk(KERN_DEBUG " disk %d, o:%d, dev:%s\n",
5615                                i, !test_bit(Faulty, &tmp->rdev->flags),
5616                                bdevname(tmp->rdev->bdev, b));
5617         }
5618 }
5619
5620 static int raid5_spare_active(struct mddev *mddev)
5621 {
5622         int i;
5623         struct r5conf *conf = mddev->private;
5624         struct disk_info *tmp;
5625         int count = 0;
5626         unsigned long flags;
5627
5628         for (i = 0; i < conf->raid_disks; i++) {
5629                 tmp = conf->disks + i;
5630                 if (tmp->replacement
5631                     && tmp->replacement->recovery_offset == MaxSector
5632                     && !test_bit(Faulty, &tmp->replacement->flags)
5633                     && !test_and_set_bit(In_sync, &tmp->replacement->flags)) {
5634                         /* Replacement has just become active. */
5635                         if (!tmp->rdev
5636                             || !test_and_clear_bit(In_sync, &tmp->rdev->flags))
5637                                 count++;
5638                         if (tmp->rdev) {
5639                                 /* Replaced device not technically faulty,
5640                                  * but we need to be sure it gets removed
5641                                  * and never re-added.
5642                                  */
5643                                 set_bit(Faulty, &tmp->rdev->flags);
5644                                 sysfs_notify_dirent_safe(
5645                                         tmp->rdev->sysfs_state);
5646                         }
5647                         sysfs_notify_dirent_safe(tmp->replacement->sysfs_state);
5648                 } else if (tmp->rdev
5649                     && tmp->rdev->recovery_offset == MaxSector
5650                     && !test_bit(Faulty, &tmp->rdev->flags)
5651                     && !test_and_set_bit(In_sync, &tmp->rdev->flags)) {
5652                         count++;
5653                         sysfs_notify_dirent_safe(tmp->rdev->sysfs_state);
5654                 }
5655         }
5656         spin_lock_irqsave(&conf->device_lock, flags);
5657         mddev->degraded = calc_degraded(conf);
5658         spin_unlock_irqrestore(&conf->device_lock, flags);
5659         print_raid5_conf(conf);
5660         return count;
5661 }
5662
5663 static int raid5_remove_disk(struct mddev *mddev, struct md_rdev *rdev)
5664 {
5665         struct r5conf *conf = mddev->private;
5666         int err = 0;
5667         int number = rdev->raid_disk;
5668         struct md_rdev **rdevp;
5669         struct disk_info *p = conf->disks + number;
5670
5671         print_raid5_conf(conf);
5672         if (rdev == p->rdev)
5673                 rdevp = &p->rdev;
5674         else if (rdev == p->replacement)
5675                 rdevp = &p->replacement;
5676         else
5677                 return 0;
5678
5679         if (number >= conf->raid_disks &&
5680             conf->reshape_progress == MaxSector)
5681                 clear_bit(In_sync, &rdev->flags);
5682
5683         if (test_bit(In_sync, &rdev->flags) ||
5684             atomic_read(&rdev->nr_pending)) {
5685                 err = -EBUSY;
5686                 goto abort;
5687         }
5688         /* Only remove non-faulty devices if recovery
5689          * isn't possible.
5690          */
5691         if (!test_bit(Faulty, &rdev->flags) &&
5692             mddev->recovery_disabled != conf->recovery_disabled &&
5693             !has_failed(conf) &&
5694             (!p->replacement || p->replacement == rdev) &&
5695             number < conf->raid_disks) {
5696                 err = -EBUSY;
5697                 goto abort;
5698         }
5699         *rdevp = NULL;
5700         synchronize_rcu();
5701         if (atomic_read(&rdev->nr_pending)) {
5702                 /* lost the race, try later */
5703                 err = -EBUSY;
5704                 *rdevp = rdev;
5705         } else if (p->replacement) {
5706                 /* We must have just cleared 'rdev' */
5707                 p->rdev = p->replacement;
5708                 clear_bit(Replacement, &p->replacement->flags);
5709                 smp_mb(); /* Make sure other CPUs may see both as identical
5710                            * but will never see neither - if they are careful
5711                            */
5712                 p->replacement = NULL;
5713                 clear_bit(WantReplacement, &rdev->flags);
5714         } else
5715                 /* We might have just removed the Replacement as faulty-
5716                  * clear the bit just in case
5717                  */
5718                 clear_bit(WantReplacement, &rdev->flags);
5719 abort:
5720
5721         print_raid5_conf(conf);
5722         return err;
5723 }
5724
5725 static int raid5_add_disk(struct mddev *mddev, struct md_rdev *rdev)
5726 {
5727         struct r5conf *conf = mddev->private;
5728         int err = -EEXIST;
5729         int disk;
5730         struct disk_info *p;
5731         int first = 0;
5732         int last = conf->raid_disks - 1;
5733
5734         if (mddev->recovery_disabled == conf->recovery_disabled)
5735                 return -EBUSY;
5736
5737         if (rdev->saved_raid_disk < 0 && has_failed(conf))
5738                 /* no point adding a device */
5739                 return -EINVAL;
5740
5741         if (rdev->raid_disk >= 0)
5742                 first = last = rdev->raid_disk;
5743
5744         /*
5745          * find the disk ... but prefer rdev->saved_raid_disk
5746          * if possible.
5747          */
5748         if (rdev->saved_raid_disk >= 0 &&
5749             rdev->saved_raid_disk >= first &&
5750             conf->disks[rdev->saved_raid_disk].rdev == NULL)
5751                 first = rdev->saved_raid_disk;
5752
5753         for (disk = first; disk <= last; disk++) {
5754                 p = conf->disks + disk;
5755                 if (p->rdev == NULL) {
5756                         clear_bit(In_sync, &rdev->flags);
5757                         rdev->raid_disk = disk;
5758                         err = 0;
5759                         if (rdev->saved_raid_disk != disk)
5760                                 conf->fullsync = 1;
5761                         rcu_assign_pointer(p->rdev, rdev);
5762                         goto out;
5763                 }
5764         }
5765         for (disk = first; disk <= last; disk++) {
5766                 p = conf->disks + disk;
5767                 if (test_bit(WantReplacement, &p->rdev->flags) &&
5768                     p->replacement == NULL) {
5769                         clear_bit(In_sync, &rdev->flags);
5770                         set_bit(Replacement, &rdev->flags);
5771                         rdev->raid_disk = disk;
5772                         err = 0;
5773                         conf->fullsync = 1;
5774                         rcu_assign_pointer(p->replacement, rdev);
5775                         break;
5776                 }
5777         }
5778 out:
5779         print_raid5_conf(conf);
5780         return err;
5781 }
5782
5783 static int raid5_resize(struct mddev *mddev, sector_t sectors)
5784 {
5785         /* no resync is happening, and there is enough space
5786          * on all devices, so we can resize.
5787          * We need to make sure resync covers any new space.
5788          * If the array is shrinking we should possibly wait until
5789          * any io in the removed space completes, but it hardly seems
5790          * worth it.
5791          */
5792         sector_t newsize;
5793         sectors &= ~((sector_t)mddev->chunk_sectors - 1);
5794         newsize = raid5_size(mddev, sectors, mddev->raid_disks);
5795         if (mddev->external_size &&
5796             mddev->array_sectors > newsize)
5797                 return -EINVAL;
5798         if (mddev->bitmap) {
5799                 int ret = bitmap_resize(mddev->bitmap, sectors, 0, 0);
5800                 if (ret)
5801                         return ret;
5802         }
5803         md_set_array_sectors(mddev, newsize);
5804         set_capacity(mddev->gendisk, mddev->array_sectors);
5805         revalidate_disk(mddev->gendisk);
5806         if (sectors > mddev->dev_sectors &&
5807             mddev->recovery_cp > mddev->dev_sectors) {
5808                 mddev->recovery_cp = mddev->dev_sectors;
5809                 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
5810         }
5811         mddev->dev_sectors = sectors;
5812         mddev->resync_max_sectors = sectors;
5813         return 0;
5814 }
5815
5816 static int check_stripe_cache(struct mddev *mddev)
5817 {
5818         /* Can only proceed if there are plenty of stripe_heads.
5819          * We need a minimum of one full stripe,, and for sensible progress
5820          * it is best to have about 4 times that.
5821          * If we require 4 times, then the default 256 4K stripe_heads will
5822          * allow for chunk sizes up to 256K, which is probably OK.
5823          * If the chunk size is greater, user-space should request more
5824          * stripe_heads first.
5825          */
5826         struct r5conf *conf = mddev->private;
5827         if (((mddev->chunk_sectors << 9) / STRIPE_SIZE) * 4
5828             > conf->max_nr_stripes ||
5829             ((mddev->new_chunk_sectors << 9) / STRIPE_SIZE) * 4
5830             > conf->max_nr_stripes) {
5831                 printk(KERN_WARNING "md/raid:%s: reshape: not enough stripes.  Needed %lu\n",
5832                        mdname(mddev),
5833                        ((max(mddev->chunk_sectors, mddev->new_chunk_sectors) << 9)
5834                         / STRIPE_SIZE)*4);
5835                 return 0;
5836         }
5837         return 1;
5838 }
5839
5840 static int check_reshape(struct mddev *mddev)
5841 {
5842         struct r5conf *conf = mddev->private;
5843
5844         if (mddev->delta_disks == 0 &&
5845             mddev->new_layout == mddev->layout &&
5846             mddev->new_chunk_sectors == mddev->chunk_sectors)
5847                 return 0; /* nothing to do */
5848         if (has_failed(conf))
5849                 return -EINVAL;
5850         if (mddev->delta_disks < 0) {
5851                 /* We might be able to shrink, but the devices must
5852                  * be made bigger first.
5853                  * For raid6, 4 is the minimum size.
5854                  * Otherwise 2 is the minimum
5855                  */
5856                 int min = 2;
5857                 if (mddev->level == 6)
5858                         min = 4;
5859                 if (mddev->raid_disks + mddev->delta_disks < min)
5860                         return -EINVAL;
5861         }
5862
5863         if (!check_stripe_cache(mddev))
5864                 return -ENOSPC;
5865
5866         return resize_stripes(conf, (conf->previous_raid_disks
5867                                      + mddev->delta_disks));
5868 }
5869
5870 static int raid5_start_reshape(struct mddev *mddev)
5871 {
5872         struct r5conf *conf = mddev->private;
5873         struct md_rdev *rdev;
5874         int spares = 0;
5875         unsigned long flags;
5876
5877         if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
5878                 return -EBUSY;
5879
5880         if (!check_stripe_cache(mddev))
5881                 return -ENOSPC;
5882
5883         if (has_failed(conf))
5884                 return -EINVAL;
5885
5886         rdev_for_each(rdev, mddev) {
5887                 if (!test_bit(In_sync, &rdev->flags)
5888                     && !test_bit(Faulty, &rdev->flags))
5889                         spares++;
5890         }
5891
5892         if (spares - mddev->degraded < mddev->delta_disks - conf->max_degraded)
5893                 /* Not enough devices even to make a degraded array
5894                  * of that size
5895                  */
5896                 return -EINVAL;
5897
5898         /* Refuse to reduce size of the array.  Any reductions in
5899          * array size must be through explicit setting of array_size
5900          * attribute.
5901          */
5902         if (raid5_size(mddev, 0, conf->raid_disks + mddev->delta_disks)
5903             < mddev->array_sectors) {
5904                 printk(KERN_ERR "md/raid:%s: array size must be reduced "
5905                        "before number of disks\n", mdname(mddev));
5906                 return -EINVAL;
5907         }
5908
5909         atomic_set(&conf->reshape_stripes, 0);
5910         spin_lock_irq(&conf->device_lock);
5911         conf->previous_raid_disks = conf->raid_disks;
5912         conf->raid_disks += mddev->delta_disks;
5913         conf->prev_chunk_sectors = conf->chunk_sectors;
5914         conf->chunk_sectors = mddev->new_chunk_sectors;
5915         conf->prev_algo = conf->algorithm;
5916         conf->algorithm = mddev->new_layout;
5917         conf->generation++;
5918         /* Code that selects data_offset needs to see the generation update
5919          * if reshape_progress has been set - so a memory barrier needed.
5920          */
5921         smp_mb();
5922         if (mddev->reshape_backwards)
5923                 conf->reshape_progress = raid5_size(mddev, 0, 0);
5924         else
5925                 conf->reshape_progress = 0;
5926         conf->reshape_safe = conf->reshape_progress;
5927         spin_unlock_irq(&conf->device_lock);
5928
5929         /* Add some new drives, as many as will fit.
5930          * We know there are enough to make the newly sized array work.
5931          * Don't add devices if we are reducing the number of
5932          * devices in the array.  This is because it is not possible
5933          * to correctly record the "partially reconstructed" state of
5934          * such devices during the reshape and confusion could result.
5935          */
5936         if (mddev->delta_disks >= 0) {
5937                 rdev_for_each(rdev, mddev)
5938                         if (rdev->raid_disk < 0 &&
5939                             !test_bit(Faulty, &rdev->flags)) {
5940                                 if (raid5_add_disk(mddev, rdev) == 0) {
5941                                         if (rdev->raid_disk
5942                                             >= conf->previous_raid_disks)
5943                                                 set_bit(In_sync, &rdev->flags);
5944                                         else
5945                                                 rdev->recovery_offset = 0;
5946
5947                                         if (sysfs_link_rdev(mddev, rdev))
5948                                                 /* Failure here is OK */;
5949                                 }
5950                         } else if (rdev->raid_disk >= conf->previous_raid_disks
5951                                    && !test_bit(Faulty, &rdev->flags)) {
5952                                 /* This is a spare that was manually added */
5953                                 set_bit(In_sync, &rdev->flags);
5954                         }
5955
5956                 /* When a reshape changes the number of devices,
5957                  * ->degraded is measured against the larger of the
5958                  * pre and post number of devices.
5959                  */
5960                 spin_lock_irqsave(&conf->device_lock, flags);
5961                 mddev->degraded = calc_degraded(conf);
5962                 spin_unlock_irqrestore(&conf->device_lock, flags);
5963         }
5964         mddev->raid_disks = conf->raid_disks;
5965         mddev->reshape_position = conf->reshape_progress;
5966         set_bit(MD_CHANGE_DEVS, &mddev->flags);
5967
5968         clear_bit(MD_RECOVERY_SYNC, &mddev->recovery);
5969         clear_bit(MD_RECOVERY_CHECK, &mddev->recovery);
5970         set_bit(MD_RECOVERY_RESHAPE, &mddev->recovery);
5971         set_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
5972         mddev->sync_thread = md_register_thread(md_do_sync, mddev,
5973                                                 "reshape");
5974         if (!mddev->sync_thread) {
5975                 mddev->recovery = 0;
5976                 spin_lock_irq(&conf->device_lock);
5977                 mddev->raid_disks = conf->raid_disks = conf->previous_raid_disks;
5978                 rdev_for_each(rdev, mddev)
5979                         rdev->new_data_offset = rdev->data_offset;
5980                 smp_wmb();
5981                 conf->reshape_progress = MaxSector;
5982                 mddev->reshape_position = MaxSector;
5983                 spin_unlock_irq(&conf->device_lock);
5984                 return -EAGAIN;
5985         }
5986         conf->reshape_checkpoint = jiffies;
5987         md_wakeup_thread(mddev->sync_thread);
5988         md_new_event(mddev);
5989         return 0;
5990 }
5991
5992 /* This is called from the reshape thread and should make any
5993  * changes needed in 'conf'
5994  */
5995 static void end_reshape(struct r5conf *conf)
5996 {
5997
5998         if (!test_bit(MD_RECOVERY_INTR, &conf->mddev->recovery)) {
5999                 struct md_rdev *rdev;
6000
6001                 spin_lock_irq(&conf->device_lock);
6002                 conf->previous_raid_disks = conf->raid_disks;
6003                 rdev_for_each(rdev, conf->mddev)
6004                         rdev->data_offset = rdev->new_data_offset;
6005                 smp_wmb();
6006                 conf->reshape_progress = MaxSector;
6007                 spin_unlock_irq(&conf->device_lock);
6008                 wake_up(&conf->wait_for_overlap);
6009
6010                 /* read-ahead size must cover two whole stripes, which is
6011                  * 2 * (datadisks) * chunksize where 'n' is the number of raid devices
6012                  */
6013                 if (conf->mddev->queue) {
6014                         int data_disks = conf->raid_disks - conf->max_degraded;
6015                         int stripe = data_disks * ((conf->chunk_sectors << 9)
6016                                                    / PAGE_SIZE);
6017                         if (conf->mddev->queue->backing_dev_info.ra_pages < 2 * stripe)
6018                                 conf->mddev->queue->backing_dev_info.ra_pages = 2 * stripe;
6019                 }
6020         }
6021 }
6022
6023 /* This is called from the raid5d thread with mddev_lock held.
6024  * It makes config changes to the device.
6025  */
6026 static void raid5_finish_reshape(struct mddev *mddev)
6027 {
6028         struct r5conf *conf = mddev->private;
6029
6030         if (!test_bit(MD_RECOVERY_INTR, &mddev->recovery)) {
6031
6032                 if (mddev->delta_disks > 0) {
6033                         md_set_array_sectors(mddev, raid5_size(mddev, 0, 0));
6034                         set_capacity(mddev->gendisk, mddev->array_sectors);
6035                         revalidate_disk(mddev->gendisk);
6036                 } else {
6037                         int d;
6038                         spin_lock_irq(&conf->device_lock);
6039                         mddev->degraded = calc_degraded(conf);
6040                         spin_unlock_irq(&conf->device_lock);
6041                         for (d = conf->raid_disks ;
6042                              d < conf->raid_disks - mddev->delta_disks;
6043                              d++) {
6044                                 struct md_rdev *rdev = conf->disks[d].rdev;
6045                                 if (rdev)
6046                                         clear_bit(In_sync, &rdev->flags);
6047                                 rdev = conf->disks[d].replacement;
6048                                 if (rdev)
6049                                         clear_bit(In_sync, &rdev->flags);
6050                         }
6051                 }
6052                 mddev->layout = conf->algorithm;
6053                 mddev->chunk_sectors = conf->chunk_sectors;
6054                 mddev->reshape_position = MaxSector;
6055                 mddev->delta_disks = 0;
6056                 mddev->reshape_backwards = 0;
6057         }
6058 }
6059
6060 static void raid5_quiesce(struct mddev *mddev, int state)
6061 {
6062         struct r5conf *conf = mddev->private;
6063
6064         switch(state) {
6065         case 2: /* resume for a suspend */
6066                 wake_up(&conf->wait_for_overlap);
6067                 break;
6068
6069         case 1: /* stop all writes */
6070                 spin_lock_irq(&conf->device_lock);
6071                 /* '2' tells resync/reshape to pause so that all
6072                  * active stripes can drain
6073                  */
6074                 conf->quiesce = 2;
6075                 wait_event_lock_irq(conf->wait_for_stripe,
6076                                     atomic_read(&conf->active_stripes) == 0 &&
6077                                     atomic_read(&conf->active_aligned_reads) == 0,
6078                                     conf->device_lock);
6079                 conf->quiesce = 1;
6080                 spin_unlock_irq(&conf->device_lock);
6081                 /* allow reshape to continue */
6082                 wake_up(&conf->wait_for_overlap);
6083                 break;
6084
6085         case 0: /* re-enable writes */
6086                 spin_lock_irq(&conf->device_lock);
6087                 conf->quiesce = 0;
6088                 wake_up(&conf->wait_for_stripe);
6089                 wake_up(&conf->wait_for_overlap);
6090                 spin_unlock_irq(&conf->device_lock);
6091                 break;
6092         }
6093 }
6094
6095
6096 static void *raid45_takeover_raid0(struct mddev *mddev, int level)
6097 {
6098         struct r0conf *raid0_conf = mddev->private;
6099         sector_t sectors;
6100
6101         /* for raid0 takeover only one zone is supported */
6102         if (raid0_conf->nr_strip_zones > 1) {
6103                 printk(KERN_ERR "md/raid:%s: cannot takeover raid0 with more than one zone.\n",
6104                        mdname(mddev));
6105                 return ERR_PTR(-EINVAL);
6106         }
6107
6108         sectors = raid0_conf->strip_zone[0].zone_end;
6109         sector_div(sectors, raid0_conf->strip_zone[0].nb_dev);
6110         mddev->dev_sectors = sectors;
6111         mddev->new_level = level;
6112         mddev->new_layout = ALGORITHM_PARITY_N;
6113         mddev->new_chunk_sectors = mddev->chunk_sectors;
6114         mddev->raid_disks += 1;
6115         mddev->delta_disks = 1;
6116         /* make sure it will be not marked as dirty */
6117         mddev->recovery_cp = MaxSector;
6118
6119         return setup_conf(mddev);
6120 }
6121
6122
6123 static void *raid5_takeover_raid1(struct mddev *mddev)
6124 {
6125         int chunksect;
6126
6127         if (mddev->raid_disks != 2 ||
6128             mddev->degraded > 1)
6129                 return ERR_PTR(-EINVAL);
6130
6131         /* Should check if there are write-behind devices? */
6132
6133         chunksect = 64*2; /* 64K by default */
6134
6135         /* The array must be an exact multiple of chunksize */
6136         while (chunksect && (mddev->array_sectors & (chunksect-1)))
6137                 chunksect >>= 1;
6138
6139         if ((chunksect<<9) < STRIPE_SIZE)
6140                 /* array size does not allow a suitable chunk size */
6141                 return ERR_PTR(-EINVAL);
6142
6143         mddev->new_level = 5;
6144         mddev->new_layout = ALGORITHM_LEFT_SYMMETRIC;
6145         mddev->new_chunk_sectors = chunksect;
6146
6147         return setup_conf(mddev);
6148 }
6149
6150 static void *raid5_takeover_raid6(struct mddev *mddev)
6151 {
6152         int new_layout;
6153
6154         switch (mddev->layout) {
6155         case ALGORITHM_LEFT_ASYMMETRIC_6:
6156                 new_layout = ALGORITHM_LEFT_ASYMMETRIC;
6157                 break;
6158         case ALGORITHM_RIGHT_ASYMMETRIC_6:
6159                 new_layout = ALGORITHM_RIGHT_ASYMMETRIC;
6160                 break;
6161         case ALGORITHM_LEFT_SYMMETRIC_6:
6162                 new_layout = ALGORITHM_LEFT_SYMMETRIC;
6163                 break;
6164         case ALGORITHM_RIGHT_SYMMETRIC_6:
6165                 new_layout = ALGORITHM_RIGHT_SYMMETRIC;
6166                 break;
6167         case ALGORITHM_PARITY_0_6:
6168                 new_layout = ALGORITHM_PARITY_0;
6169                 break;
6170         case ALGORITHM_PARITY_N:
6171                 new_layout = ALGORITHM_PARITY_N;
6172                 break;
6173         default:
6174                 return ERR_PTR(-EINVAL);
6175         }
6176         mddev->new_level = 5;
6177         mddev->new_layout = new_layout;
6178         mddev->delta_disks = -1;
6179         mddev->raid_disks -= 1;
6180         return setup_conf(mddev);
6181 }
6182
6183
6184 static int raid5_check_reshape(struct mddev *mddev)
6185 {
6186         /* For a 2-drive array, the layout and chunk size can be changed
6187          * immediately as not restriping is needed.
6188          * For larger arrays we record the new value - after validation
6189          * to be used by a reshape pass.
6190          */
6191         struct r5conf *conf = mddev->private;
6192         int new_chunk = mddev->new_chunk_sectors;
6193
6194         if (mddev->new_layout >= 0 && !algorithm_valid_raid5(mddev->new_layout))
6195                 return -EINVAL;
6196         if (new_chunk > 0) {
6197                 if (!is_power_of_2(new_chunk))
6198                         return -EINVAL;
6199                 if (new_chunk < (PAGE_SIZE>>9))
6200                         return -EINVAL;
6201                 if (mddev->array_sectors & (new_chunk-1))
6202                         /* not factor of array size */
6203                         return -EINVAL;
6204         }
6205
6206         /* They look valid */
6207
6208         if (mddev->raid_disks == 2) {
6209                 /* can make the change immediately */
6210                 if (mddev->new_layout >= 0) {
6211                         conf->algorithm = mddev->new_layout;
6212                         mddev->layout = mddev->new_layout;
6213                 }
6214                 if (new_chunk > 0) {
6215                         conf->chunk_sectors = new_chunk ;
6216                         mddev->chunk_sectors = new_chunk;
6217                 }
6218                 set_bit(MD_CHANGE_DEVS, &mddev->flags);
6219                 md_wakeup_thread(mddev->thread);
6220         }
6221         return check_reshape(mddev);
6222 }
6223
6224 static int raid6_check_reshape(struct mddev *mddev)
6225 {
6226         int new_chunk = mddev->new_chunk_sectors;
6227
6228         if (mddev->new_layout >= 0 && !algorithm_valid_raid6(mddev->new_layout))
6229                 return -EINVAL;
6230         if (new_chunk > 0) {
6231                 if (!is_power_of_2(new_chunk))
6232                         return -EINVAL;
6233                 if (new_chunk < (PAGE_SIZE >> 9))
6234                         return -EINVAL;
6235                 if (mddev->array_sectors & (new_chunk-1))
6236                         /* not factor of array size */
6237                         return -EINVAL;
6238         }
6239
6240         /* They look valid */
6241         return check_reshape(mddev);
6242 }
6243
6244 static void *raid5_takeover(struct mddev *mddev)
6245 {
6246         /* raid5 can take over:
6247          *  raid0 - if there is only one strip zone - make it a raid4 layout
6248          *  raid1 - if there are two drives.  We need to know the chunk size
6249          *  raid4 - trivial - just use a raid4 layout.
6250          *  raid6 - Providing it is a *_6 layout
6251          */
6252         if (mddev->level == 0)
6253                 return raid45_takeover_raid0(mddev, 5);
6254         if (mddev->level == 1)
6255                 return raid5_takeover_raid1(mddev);
6256         if (mddev->level == 4) {
6257                 mddev->new_layout = ALGORITHM_PARITY_N;
6258                 mddev->new_level = 5;
6259                 return setup_conf(mddev);
6260         }
6261         if (mddev->level == 6)
6262                 return raid5_takeover_raid6(mddev);
6263
6264         return ERR_PTR(-EINVAL);
6265 }
6266
6267 static void *raid4_takeover(struct mddev *mddev)
6268 {
6269         /* raid4 can take over:
6270          *  raid0 - if there is only one strip zone
6271          *  raid5 - if layout is right
6272          */
6273         if (mddev->level == 0)
6274                 return raid45_takeover_raid0(mddev, 4);
6275         if (mddev->level == 5 &&
6276             mddev->layout == ALGORITHM_PARITY_N) {
6277                 mddev->new_layout = 0;
6278                 mddev->new_level = 4;
6279                 return setup_conf(mddev);
6280         }
6281         return ERR_PTR(-EINVAL);
6282 }
6283
6284 static struct md_personality raid5_personality;
6285
6286 static void *raid6_takeover(struct mddev *mddev)
6287 {
6288         /* Currently can only take over a raid5.  We map the
6289          * personality to an equivalent raid6 personality
6290          * with the Q block at the end.
6291          */
6292         int new_layout;
6293
6294         if (mddev->pers != &raid5_personality)
6295                 return ERR_PTR(-EINVAL);
6296         if (mddev->degraded > 1)
6297                 return ERR_PTR(-EINVAL);
6298         if (mddev->raid_disks > 253)
6299                 return ERR_PTR(-EINVAL);
6300         if (mddev->raid_disks < 3)
6301                 return ERR_PTR(-EINVAL);
6302
6303         switch (mddev->layout) {
6304         case ALGORITHM_LEFT_ASYMMETRIC:
6305                 new_layout = ALGORITHM_LEFT_ASYMMETRIC_6;
6306                 break;
6307         case ALGORITHM_RIGHT_ASYMMETRIC:
6308                 new_layout = ALGORITHM_RIGHT_ASYMMETRIC_6;
6309                 break;
6310         case ALGORITHM_LEFT_SYMMETRIC:
6311                 new_layout = ALGORITHM_LEFT_SYMMETRIC_6;
6312                 break;
6313         case ALGORITHM_RIGHT_SYMMETRIC:
6314                 new_layout = ALGORITHM_RIGHT_SYMMETRIC_6;
6315                 break;
6316         case ALGORITHM_PARITY_0:
6317                 new_layout = ALGORITHM_PARITY_0_6;
6318                 break;
6319         case ALGORITHM_PARITY_N:
6320                 new_layout = ALGORITHM_PARITY_N;
6321                 break;
6322         default:
6323                 return ERR_PTR(-EINVAL);
6324         }
6325         mddev->new_level = 6;
6326         mddev->new_layout = new_layout;
6327         mddev->delta_disks = 1;
6328         mddev->raid_disks += 1;
6329         return setup_conf(mddev);
6330 }
6331
6332
6333 static struct md_personality raid6_personality =
6334 {
6335         .name           = "raid6",
6336         .level          = 6,
6337         .owner          = THIS_MODULE,
6338         .make_request   = make_request,
6339         .run            = run,
6340         .stop           = stop,
6341         .status         = status,
6342         .error_handler  = error,
6343         .hot_add_disk   = raid5_add_disk,
6344         .hot_remove_disk= raid5_remove_disk,
6345         .spare_active   = raid5_spare_active,
6346         .sync_request   = sync_request,
6347         .resize         = raid5_resize,
6348         .size           = raid5_size,
6349         .check_reshape  = raid6_check_reshape,
6350         .start_reshape  = raid5_start_reshape,
6351         .finish_reshape = raid5_finish_reshape,
6352         .quiesce        = raid5_quiesce,
6353         .takeover       = raid6_takeover,
6354 };
6355 static struct md_personality raid5_personality =
6356 {
6357         .name           = "raid5",
6358         .level          = 5,
6359         .owner          = THIS_MODULE,
6360         .make_request   = make_request,
6361         .run            = run,
6362         .stop           = stop,
6363         .status         = status,
6364         .error_handler  = error,
6365         .hot_add_disk   = raid5_add_disk,
6366         .hot_remove_disk= raid5_remove_disk,
6367         .spare_active   = raid5_spare_active,
6368         .sync_request   = sync_request,
6369         .resize         = raid5_resize,
6370         .size           = raid5_size,
6371         .check_reshape  = raid5_check_reshape,
6372         .start_reshape  = raid5_start_reshape,
6373         .finish_reshape = raid5_finish_reshape,
6374         .quiesce        = raid5_quiesce,
6375         .takeover       = raid5_takeover,
6376 };
6377
6378 static struct md_personality raid4_personality =
6379 {
6380         .name           = "raid4",
6381         .level          = 4,
6382         .owner          = THIS_MODULE,
6383         .make_request   = make_request,
6384         .run            = run,
6385         .stop           = stop,
6386         .status         = status,
6387         .error_handler  = error,
6388         .hot_add_disk   = raid5_add_disk,
6389         .hot_remove_disk= raid5_remove_disk,
6390         .spare_active   = raid5_spare_active,
6391         .sync_request   = sync_request,
6392         .resize         = raid5_resize,
6393         .size           = raid5_size,
6394         .check_reshape  = raid5_check_reshape,
6395         .start_reshape  = raid5_start_reshape,
6396         .finish_reshape = raid5_finish_reshape,
6397         .quiesce        = raid5_quiesce,
6398         .takeover       = raid4_takeover,
6399 };
6400
6401 static int __init raid5_init(void)
6402 {
6403         register_md_personality(&raid6_personality);
6404         register_md_personality(&raid5_personality);
6405         register_md_personality(&raid4_personality);
6406         return 0;
6407 }
6408
6409 static void raid5_exit(void)
6410 {
6411         unregister_md_personality(&raid6_personality);
6412         unregister_md_personality(&raid5_personality);
6413         unregister_md_personality(&raid4_personality);
6414 }
6415
6416 module_init(raid5_init);
6417 module_exit(raid5_exit);
6418 MODULE_LICENSE("GPL");
6419 MODULE_DESCRIPTION("RAID4/5/6 (striping with parity) personality for MD");
6420 MODULE_ALIAS("md-personality-4"); /* RAID5 */
6421 MODULE_ALIAS("md-raid5");
6422 MODULE_ALIAS("md-raid4");
6423 MODULE_ALIAS("md-level-5");
6424 MODULE_ALIAS("md-level-4");
6425 MODULE_ALIAS("md-personality-8"); /* RAID6 */
6426 MODULE_ALIAS("md-raid6");
6427 MODULE_ALIAS("md-level-6");
6428
6429 /* This used to be two separate modules, they were: */
6430 MODULE_ALIAS("raid5");
6431 MODULE_ALIAS("raid6");