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