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