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