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