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