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