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