6056ee7984ac93137326ef3d5d1546d05cb02565
[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         if (!err)
1558                 conf->pool_size = newsize;
1559         return err;
1560 }
1561
1562 static int drop_one_stripe(struct r5conf *conf)
1563 {
1564         struct stripe_head *sh;
1565
1566         spin_lock_irq(&conf->device_lock);
1567         sh = get_free_stripe(conf);
1568         spin_unlock_irq(&conf->device_lock);
1569         if (!sh)
1570                 return 0;
1571         BUG_ON(atomic_read(&sh->count));
1572         shrink_buffers(sh);
1573         kmem_cache_free(conf->slab_cache, sh);
1574         atomic_dec(&conf->active_stripes);
1575         return 1;
1576 }
1577
1578 static void shrink_stripes(struct r5conf *conf)
1579 {
1580         while (drop_one_stripe(conf))
1581                 ;
1582
1583         if (conf->slab_cache)
1584                 kmem_cache_destroy(conf->slab_cache);
1585         conf->slab_cache = NULL;
1586 }
1587
1588 static void raid5_end_read_request(struct bio * bi, int error)
1589 {
1590         struct stripe_head *sh = bi->bi_private;
1591         struct r5conf *conf = sh->raid_conf;
1592         int disks = sh->disks, i;
1593         int uptodate = test_bit(BIO_UPTODATE, &bi->bi_flags);
1594         char b[BDEVNAME_SIZE];
1595         struct md_rdev *rdev;
1596
1597
1598         for (i=0 ; i<disks; i++)
1599                 if (bi == &sh->dev[i].req)
1600                         break;
1601
1602         pr_debug("end_read_request %llu/%d, count: %d, uptodate %d.\n",
1603                 (unsigned long long)sh->sector, i, atomic_read(&sh->count),
1604                 uptodate);
1605         if (i == disks) {
1606                 BUG();
1607                 return;
1608         }
1609
1610         if (uptodate) {
1611                 set_bit(R5_UPTODATE, &sh->dev[i].flags);
1612                 if (test_bit(R5_ReadError, &sh->dev[i].flags)) {
1613                         rdev = conf->disks[i].rdev;
1614                         printk_ratelimited(
1615                                 KERN_INFO
1616                                 "md/raid:%s: read error corrected"
1617                                 " (%lu sectors at %llu on %s)\n",
1618                                 mdname(conf->mddev), STRIPE_SECTORS,
1619                                 (unsigned long long)(sh->sector
1620                                                      + rdev->data_offset),
1621                                 bdevname(rdev->bdev, b));
1622                         atomic_add(STRIPE_SECTORS, &rdev->corrected_errors);
1623                         clear_bit(R5_ReadError, &sh->dev[i].flags);
1624                         clear_bit(R5_ReWrite, &sh->dev[i].flags);
1625                 }
1626                 if (atomic_read(&conf->disks[i].rdev->read_errors))
1627                         atomic_set(&conf->disks[i].rdev->read_errors, 0);
1628         } else {
1629                 const char *bdn = bdevname(conf->disks[i].rdev->bdev, b);
1630                 int retry = 0;
1631                 rdev = conf->disks[i].rdev;
1632
1633                 clear_bit(R5_UPTODATE, &sh->dev[i].flags);
1634                 atomic_inc(&rdev->read_errors);
1635                 if (conf->mddev->degraded >= conf->max_degraded)
1636                         printk_ratelimited(
1637                                 KERN_WARNING
1638                                 "md/raid:%s: read error not correctable "
1639                                 "(sector %llu on %s).\n",
1640                                 mdname(conf->mddev),
1641                                 (unsigned long long)(sh->sector
1642                                                      + rdev->data_offset),
1643                                 bdn);
1644                 else if (test_bit(R5_ReWrite, &sh->dev[i].flags))
1645                         /* Oh, no!!! */
1646                         printk_ratelimited(
1647                                 KERN_WARNING
1648                                 "md/raid:%s: read error NOT corrected!! "
1649                                 "(sector %llu on %s).\n",
1650                                 mdname(conf->mddev),
1651                                 (unsigned long long)(sh->sector
1652                                                      + rdev->data_offset),
1653                                 bdn);
1654                 else if (atomic_read(&rdev->read_errors)
1655                          > conf->max_nr_stripes)
1656                         printk(KERN_WARNING
1657                                "md/raid:%s: Too many read errors, failing device %s.\n",
1658                                mdname(conf->mddev), bdn);
1659                 else
1660                         retry = 1;
1661                 if (retry)
1662                         set_bit(R5_ReadError, &sh->dev[i].flags);
1663                 else {
1664                         clear_bit(R5_ReadError, &sh->dev[i].flags);
1665                         clear_bit(R5_ReWrite, &sh->dev[i].flags);
1666                         md_error(conf->mddev, rdev);
1667                 }
1668         }
1669         rdev_dec_pending(conf->disks[i].rdev, conf->mddev);
1670         clear_bit(R5_LOCKED, &sh->dev[i].flags);
1671         set_bit(STRIPE_HANDLE, &sh->state);
1672         release_stripe(sh);
1673 }
1674
1675 static void raid5_end_write_request(struct bio *bi, int error)
1676 {
1677         struct stripe_head *sh = bi->bi_private;
1678         struct r5conf *conf = sh->raid_conf;
1679         int disks = sh->disks, i;
1680         int uptodate = test_bit(BIO_UPTODATE, &bi->bi_flags);
1681         sector_t first_bad;
1682         int bad_sectors;
1683
1684         for (i=0 ; i<disks; i++)
1685                 if (bi == &sh->dev[i].req)
1686                         break;
1687
1688         pr_debug("end_write_request %llu/%d, count %d, uptodate: %d.\n",
1689                 (unsigned long long)sh->sector, i, atomic_read(&sh->count),
1690                 uptodate);
1691         if (i == disks) {
1692                 BUG();
1693                 return;
1694         }
1695
1696         if (!uptodate) {
1697                 set_bit(STRIPE_DEGRADED, &sh->state);
1698                 set_bit(WriteErrorSeen, &conf->disks[i].rdev->flags);
1699                 set_bit(R5_WriteError, &sh->dev[i].flags);
1700         } else if (is_badblock(conf->disks[i].rdev, sh->sector, STRIPE_SECTORS,
1701                                &first_bad, &bad_sectors))
1702                 set_bit(R5_MadeGood, &sh->dev[i].flags);
1703
1704         rdev_dec_pending(conf->disks[i].rdev, conf->mddev);
1705         
1706         clear_bit(R5_LOCKED, &sh->dev[i].flags);
1707         set_bit(STRIPE_HANDLE, &sh->state);
1708         release_stripe(sh);
1709 }
1710
1711
1712 static sector_t compute_blocknr(struct stripe_head *sh, int i, int previous);
1713         
1714 static void raid5_build_block(struct stripe_head *sh, int i, int previous)
1715 {
1716         struct r5dev *dev = &sh->dev[i];
1717
1718         bio_init(&dev->req);
1719         dev->req.bi_io_vec = &dev->vec;
1720         dev->req.bi_vcnt++;
1721         dev->req.bi_max_vecs++;
1722         dev->vec.bv_page = dev->page;
1723         dev->vec.bv_len = STRIPE_SIZE;
1724         dev->vec.bv_offset = 0;
1725
1726         dev->req.bi_sector = sh->sector;
1727         dev->req.bi_private = sh;
1728
1729         dev->flags = 0;
1730         dev->sector = compute_blocknr(sh, i, previous);
1731 }
1732
1733 static void error(struct mddev *mddev, struct md_rdev *rdev)
1734 {
1735         char b[BDEVNAME_SIZE];
1736         struct r5conf *conf = mddev->private;
1737         pr_debug("raid456: error called\n");
1738
1739         if (test_and_clear_bit(In_sync, &rdev->flags)) {
1740                 unsigned long flags;
1741                 spin_lock_irqsave(&conf->device_lock, flags);
1742                 mddev->degraded++;
1743                 spin_unlock_irqrestore(&conf->device_lock, flags);
1744                 /*
1745                  * if recovery was running, make sure it aborts.
1746                  */
1747                 set_bit(MD_RECOVERY_INTR, &mddev->recovery);
1748         }
1749         set_bit(Blocked, &rdev->flags);
1750         set_bit(Faulty, &rdev->flags);
1751         set_bit(MD_CHANGE_DEVS, &mddev->flags);
1752         printk(KERN_ALERT
1753                "md/raid:%s: Disk failure on %s, disabling device.\n"
1754                "md/raid:%s: Operation continuing on %d devices.\n",
1755                mdname(mddev),
1756                bdevname(rdev->bdev, b),
1757                mdname(mddev),
1758                conf->raid_disks - mddev->degraded);
1759 }
1760
1761 /*
1762  * Input: a 'big' sector number,
1763  * Output: index of the data and parity disk, and the sector # in them.
1764  */
1765 static sector_t raid5_compute_sector(struct r5conf *conf, sector_t r_sector,
1766                                      int previous, int *dd_idx,
1767                                      struct stripe_head *sh)
1768 {
1769         sector_t stripe, stripe2;
1770         sector_t chunk_number;
1771         unsigned int chunk_offset;
1772         int pd_idx, qd_idx;
1773         int ddf_layout = 0;
1774         sector_t new_sector;
1775         int algorithm = previous ? conf->prev_algo
1776                                  : conf->algorithm;
1777         int sectors_per_chunk = previous ? conf->prev_chunk_sectors
1778                                          : conf->chunk_sectors;
1779         int raid_disks = previous ? conf->previous_raid_disks
1780                                   : conf->raid_disks;
1781         int data_disks = raid_disks - conf->max_degraded;
1782
1783         /* First compute the information on this sector */
1784
1785         /*
1786          * Compute the chunk number and the sector offset inside the chunk
1787          */
1788         chunk_offset = sector_div(r_sector, sectors_per_chunk);
1789         chunk_number = r_sector;
1790
1791         /*
1792          * Compute the stripe number
1793          */
1794         stripe = chunk_number;
1795         *dd_idx = sector_div(stripe, data_disks);
1796         stripe2 = stripe;
1797         /*
1798          * Select the parity disk based on the user selected algorithm.
1799          */
1800         pd_idx = qd_idx = -1;
1801         switch(conf->level) {
1802         case 4:
1803                 pd_idx = data_disks;
1804                 break;
1805         case 5:
1806                 switch (algorithm) {
1807                 case ALGORITHM_LEFT_ASYMMETRIC:
1808                         pd_idx = data_disks - sector_div(stripe2, raid_disks);
1809                         if (*dd_idx >= pd_idx)
1810                                 (*dd_idx)++;
1811                         break;
1812                 case ALGORITHM_RIGHT_ASYMMETRIC:
1813                         pd_idx = sector_div(stripe2, raid_disks);
1814                         if (*dd_idx >= pd_idx)
1815                                 (*dd_idx)++;
1816                         break;
1817                 case ALGORITHM_LEFT_SYMMETRIC:
1818                         pd_idx = data_disks - sector_div(stripe2, raid_disks);
1819                         *dd_idx = (pd_idx + 1 + *dd_idx) % raid_disks;
1820                         break;
1821                 case ALGORITHM_RIGHT_SYMMETRIC:
1822                         pd_idx = sector_div(stripe2, raid_disks);
1823                         *dd_idx = (pd_idx + 1 + *dd_idx) % raid_disks;
1824                         break;
1825                 case ALGORITHM_PARITY_0:
1826                         pd_idx = 0;
1827                         (*dd_idx)++;
1828                         break;
1829                 case ALGORITHM_PARITY_N:
1830                         pd_idx = data_disks;
1831                         break;
1832                 default:
1833                         BUG();
1834                 }
1835                 break;
1836         case 6:
1837
1838                 switch (algorithm) {
1839                 case ALGORITHM_LEFT_ASYMMETRIC:
1840                         pd_idx = raid_disks - 1 - sector_div(stripe2, raid_disks);
1841                         qd_idx = pd_idx + 1;
1842                         if (pd_idx == raid_disks-1) {
1843                                 (*dd_idx)++;    /* Q D D D P */
1844                                 qd_idx = 0;
1845                         } else if (*dd_idx >= pd_idx)
1846                                 (*dd_idx) += 2; /* D D P Q D */
1847                         break;
1848                 case ALGORITHM_RIGHT_ASYMMETRIC:
1849                         pd_idx = sector_div(stripe2, raid_disks);
1850                         qd_idx = pd_idx + 1;
1851                         if (pd_idx == raid_disks-1) {
1852                                 (*dd_idx)++;    /* Q D D D P */
1853                                 qd_idx = 0;
1854                         } else if (*dd_idx >= pd_idx)
1855                                 (*dd_idx) += 2; /* D D P Q D */
1856                         break;
1857                 case ALGORITHM_LEFT_SYMMETRIC:
1858                         pd_idx = raid_disks - 1 - sector_div(stripe2, raid_disks);
1859                         qd_idx = (pd_idx + 1) % raid_disks;
1860                         *dd_idx = (pd_idx + 2 + *dd_idx) % raid_disks;
1861                         break;
1862                 case ALGORITHM_RIGHT_SYMMETRIC:
1863                         pd_idx = sector_div(stripe2, raid_disks);
1864                         qd_idx = (pd_idx + 1) % raid_disks;
1865                         *dd_idx = (pd_idx + 2 + *dd_idx) % raid_disks;
1866                         break;
1867
1868                 case ALGORITHM_PARITY_0:
1869                         pd_idx = 0;
1870                         qd_idx = 1;
1871                         (*dd_idx) += 2;
1872                         break;
1873                 case ALGORITHM_PARITY_N:
1874                         pd_idx = data_disks;
1875                         qd_idx = data_disks + 1;
1876                         break;
1877
1878                 case ALGORITHM_ROTATING_ZERO_RESTART:
1879                         /* Exactly the same as RIGHT_ASYMMETRIC, but or
1880                          * of blocks for computing Q is different.
1881                          */
1882                         pd_idx = sector_div(stripe2, raid_disks);
1883                         qd_idx = pd_idx + 1;
1884                         if (pd_idx == raid_disks-1) {
1885                                 (*dd_idx)++;    /* Q D D D P */
1886                                 qd_idx = 0;
1887                         } else if (*dd_idx >= pd_idx)
1888                                 (*dd_idx) += 2; /* D D P Q D */
1889                         ddf_layout = 1;
1890                         break;
1891
1892                 case ALGORITHM_ROTATING_N_RESTART:
1893                         /* Same a left_asymmetric, by first stripe is
1894                          * D D D P Q  rather than
1895                          * Q D D D P
1896                          */
1897                         stripe2 += 1;
1898                         pd_idx = raid_disks - 1 - sector_div(stripe2, raid_disks);
1899                         qd_idx = pd_idx + 1;
1900                         if (pd_idx == raid_disks-1) {
1901                                 (*dd_idx)++;    /* Q D D D P */
1902                                 qd_idx = 0;
1903                         } else if (*dd_idx >= pd_idx)
1904                                 (*dd_idx) += 2; /* D D P Q D */
1905                         ddf_layout = 1;
1906                         break;
1907
1908                 case ALGORITHM_ROTATING_N_CONTINUE:
1909                         /* Same as left_symmetric but Q is before P */
1910                         pd_idx = raid_disks - 1 - sector_div(stripe2, raid_disks);
1911                         qd_idx = (pd_idx + raid_disks - 1) % raid_disks;
1912                         *dd_idx = (pd_idx + 1 + *dd_idx) % raid_disks;
1913                         ddf_layout = 1;
1914                         break;
1915
1916                 case ALGORITHM_LEFT_ASYMMETRIC_6:
1917                         /* RAID5 left_asymmetric, with Q on last device */
1918                         pd_idx = data_disks - sector_div(stripe2, raid_disks-1);
1919                         if (*dd_idx >= pd_idx)
1920                                 (*dd_idx)++;
1921                         qd_idx = raid_disks - 1;
1922                         break;
1923
1924                 case ALGORITHM_RIGHT_ASYMMETRIC_6:
1925                         pd_idx = sector_div(stripe2, raid_disks-1);
1926                         if (*dd_idx >= pd_idx)
1927                                 (*dd_idx)++;
1928                         qd_idx = raid_disks - 1;
1929                         break;
1930
1931                 case ALGORITHM_LEFT_SYMMETRIC_6:
1932                         pd_idx = data_disks - sector_div(stripe2, raid_disks-1);
1933                         *dd_idx = (pd_idx + 1 + *dd_idx) % (raid_disks-1);
1934                         qd_idx = raid_disks - 1;
1935                         break;
1936
1937                 case ALGORITHM_RIGHT_SYMMETRIC_6:
1938                         pd_idx = sector_div(stripe2, raid_disks-1);
1939                         *dd_idx = (pd_idx + 1 + *dd_idx) % (raid_disks-1);
1940                         qd_idx = raid_disks - 1;
1941                         break;
1942
1943                 case ALGORITHM_PARITY_0_6:
1944                         pd_idx = 0;
1945                         (*dd_idx)++;
1946                         qd_idx = raid_disks - 1;
1947                         break;
1948
1949                 default:
1950                         BUG();
1951                 }
1952                 break;
1953         }
1954
1955         if (sh) {
1956                 sh->pd_idx = pd_idx;
1957                 sh->qd_idx = qd_idx;
1958                 sh->ddf_layout = ddf_layout;
1959         }
1960         /*
1961          * Finally, compute the new sector number
1962          */
1963         new_sector = (sector_t)stripe * sectors_per_chunk + chunk_offset;
1964         return new_sector;
1965 }
1966
1967
1968 static sector_t compute_blocknr(struct stripe_head *sh, int i, int previous)
1969 {
1970         struct r5conf *conf = sh->raid_conf;
1971         int raid_disks = sh->disks;
1972         int data_disks = raid_disks - conf->max_degraded;
1973         sector_t new_sector = sh->sector, check;
1974         int sectors_per_chunk = previous ? conf->prev_chunk_sectors
1975                                          : conf->chunk_sectors;
1976         int algorithm = previous ? conf->prev_algo
1977                                  : conf->algorithm;
1978         sector_t stripe;
1979         int chunk_offset;
1980         sector_t chunk_number;
1981         int dummy1, dd_idx = i;
1982         sector_t r_sector;
1983         struct stripe_head sh2;
1984
1985
1986         chunk_offset = sector_div(new_sector, sectors_per_chunk);
1987         stripe = new_sector;
1988
1989         if (i == sh->pd_idx)
1990                 return 0;
1991         switch(conf->level) {
1992         case 4: break;
1993         case 5:
1994                 switch (algorithm) {
1995                 case ALGORITHM_LEFT_ASYMMETRIC:
1996                 case ALGORITHM_RIGHT_ASYMMETRIC:
1997                         if (i > sh->pd_idx)
1998                                 i--;
1999                         break;
2000                 case ALGORITHM_LEFT_SYMMETRIC:
2001                 case ALGORITHM_RIGHT_SYMMETRIC:
2002                         if (i < sh->pd_idx)
2003                                 i += raid_disks;
2004                         i -= (sh->pd_idx + 1);
2005                         break;
2006                 case ALGORITHM_PARITY_0:
2007                         i -= 1;
2008                         break;
2009                 case ALGORITHM_PARITY_N:
2010                         break;
2011                 default:
2012                         BUG();
2013                 }
2014                 break;
2015         case 6:
2016                 if (i == sh->qd_idx)
2017                         return 0; /* It is the Q disk */
2018                 switch (algorithm) {
2019                 case ALGORITHM_LEFT_ASYMMETRIC:
2020                 case ALGORITHM_RIGHT_ASYMMETRIC:
2021                 case ALGORITHM_ROTATING_ZERO_RESTART:
2022                 case ALGORITHM_ROTATING_N_RESTART:
2023                         if (sh->pd_idx == raid_disks-1)
2024                                 i--;    /* Q D D D P */
2025                         else if (i > sh->pd_idx)
2026                                 i -= 2; /* D D P Q D */
2027                         break;
2028                 case ALGORITHM_LEFT_SYMMETRIC:
2029                 case ALGORITHM_RIGHT_SYMMETRIC:
2030                         if (sh->pd_idx == raid_disks-1)
2031                                 i--; /* Q D D D P */
2032                         else {
2033                                 /* D D P Q D */
2034                                 if (i < sh->pd_idx)
2035                                         i += raid_disks;
2036                                 i -= (sh->pd_idx + 2);
2037                         }
2038                         break;
2039                 case ALGORITHM_PARITY_0:
2040                         i -= 2;
2041                         break;
2042                 case ALGORITHM_PARITY_N:
2043                         break;
2044                 case ALGORITHM_ROTATING_N_CONTINUE:
2045                         /* Like left_symmetric, but P is before Q */
2046                         if (sh->pd_idx == 0)
2047                                 i--;    /* P D D D Q */
2048                         else {
2049                                 /* D D Q P D */
2050                                 if (i < sh->pd_idx)
2051                                         i += raid_disks;
2052                                 i -= (sh->pd_idx + 1);
2053                         }
2054                         break;
2055                 case ALGORITHM_LEFT_ASYMMETRIC_6:
2056                 case ALGORITHM_RIGHT_ASYMMETRIC_6:
2057                         if (i > sh->pd_idx)
2058                                 i--;
2059                         break;
2060                 case ALGORITHM_LEFT_SYMMETRIC_6:
2061                 case ALGORITHM_RIGHT_SYMMETRIC_6:
2062                         if (i < sh->pd_idx)
2063                                 i += data_disks + 1;
2064                         i -= (sh->pd_idx + 1);
2065                         break;
2066                 case ALGORITHM_PARITY_0_6:
2067                         i -= 1;
2068                         break;
2069                 default:
2070                         BUG();
2071                 }
2072                 break;
2073         }
2074
2075         chunk_number = stripe * data_disks + i;
2076         r_sector = chunk_number * sectors_per_chunk + chunk_offset;
2077
2078         check = raid5_compute_sector(conf, r_sector,
2079                                      previous, &dummy1, &sh2);
2080         if (check != sh->sector || dummy1 != dd_idx || sh2.pd_idx != sh->pd_idx
2081                 || sh2.qd_idx != sh->qd_idx) {
2082                 printk(KERN_ERR "md/raid:%s: compute_blocknr: map not correct\n",
2083                        mdname(conf->mddev));
2084                 return 0;
2085         }
2086         return r_sector;
2087 }
2088
2089
2090 static void
2091 schedule_reconstruction(struct stripe_head *sh, struct stripe_head_state *s,
2092                          int rcw, int expand)
2093 {
2094         int i, pd_idx = sh->pd_idx, disks = sh->disks;
2095         struct r5conf *conf = sh->raid_conf;
2096         int level = conf->level;
2097
2098         if (rcw) {
2099                 /* if we are not expanding this is a proper write request, and
2100                  * there will be bios with new data to be drained into the
2101                  * stripe cache
2102                  */
2103                 if (!expand) {
2104                         sh->reconstruct_state = reconstruct_state_drain_run;
2105                         set_bit(STRIPE_OP_BIODRAIN, &s->ops_request);
2106                 } else
2107                         sh->reconstruct_state = reconstruct_state_run;
2108
2109                 set_bit(STRIPE_OP_RECONSTRUCT, &s->ops_request);
2110
2111                 for (i = disks; i--; ) {
2112                         struct r5dev *dev = &sh->dev[i];
2113
2114                         if (dev->towrite) {
2115                                 set_bit(R5_LOCKED, &dev->flags);
2116                                 set_bit(R5_Wantdrain, &dev->flags);
2117                                 if (!expand)
2118                                         clear_bit(R5_UPTODATE, &dev->flags);
2119                                 s->locked++;
2120                         }
2121                 }
2122                 if (s->locked + conf->max_degraded == disks)
2123                         if (!test_and_set_bit(STRIPE_FULL_WRITE, &sh->state))
2124                                 atomic_inc(&conf->pending_full_writes);
2125         } else {
2126                 BUG_ON(level == 6);
2127                 BUG_ON(!(test_bit(R5_UPTODATE, &sh->dev[pd_idx].flags) ||
2128                         test_bit(R5_Wantcompute, &sh->dev[pd_idx].flags)));
2129
2130                 sh->reconstruct_state = reconstruct_state_prexor_drain_run;
2131                 set_bit(STRIPE_OP_PREXOR, &s->ops_request);
2132                 set_bit(STRIPE_OP_BIODRAIN, &s->ops_request);
2133                 set_bit(STRIPE_OP_RECONSTRUCT, &s->ops_request);
2134
2135                 for (i = disks; i--; ) {
2136                         struct r5dev *dev = &sh->dev[i];
2137                         if (i == pd_idx)
2138                                 continue;
2139
2140                         if (dev->towrite &&
2141                             (test_bit(R5_UPTODATE, &dev->flags) ||
2142                              test_bit(R5_Wantcompute, &dev->flags))) {
2143                                 set_bit(R5_Wantdrain, &dev->flags);
2144                                 set_bit(R5_LOCKED, &dev->flags);
2145                                 clear_bit(R5_UPTODATE, &dev->flags);
2146                                 s->locked++;
2147                         }
2148                 }
2149         }
2150
2151         /* keep the parity disk(s) locked while asynchronous operations
2152          * are in flight
2153          */
2154         set_bit(R5_LOCKED, &sh->dev[pd_idx].flags);
2155         clear_bit(R5_UPTODATE, &sh->dev[pd_idx].flags);
2156         s->locked++;
2157
2158         if (level == 6) {
2159                 int qd_idx = sh->qd_idx;
2160                 struct r5dev *dev = &sh->dev[qd_idx];
2161
2162                 set_bit(R5_LOCKED, &dev->flags);
2163                 clear_bit(R5_UPTODATE, &dev->flags);
2164                 s->locked++;
2165         }
2166
2167         pr_debug("%s: stripe %llu locked: %d ops_request: %lx\n",
2168                 __func__, (unsigned long long)sh->sector,
2169                 s->locked, s->ops_request);
2170 }
2171
2172 /*
2173  * Each stripe/dev can have one or more bion attached.
2174  * toread/towrite point to the first in a chain.
2175  * The bi_next chain must be in order.
2176  */
2177 static int add_stripe_bio(struct stripe_head *sh, struct bio *bi, int dd_idx, int forwrite)
2178 {
2179         struct bio **bip;
2180         struct r5conf *conf = sh->raid_conf;
2181         int firstwrite=0;
2182
2183         pr_debug("adding bi b#%llu to stripe s#%llu\n",
2184                 (unsigned long long)bi->bi_sector,
2185                 (unsigned long long)sh->sector);
2186
2187
2188         spin_lock_irq(&conf->device_lock);
2189         if (forwrite) {
2190                 bip = &sh->dev[dd_idx].towrite;
2191                 if (*bip == NULL && sh->dev[dd_idx].written == NULL)
2192                         firstwrite = 1;
2193         } else
2194                 bip = &sh->dev[dd_idx].toread;
2195         while (*bip && (*bip)->bi_sector < bi->bi_sector) {
2196                 if ((*bip)->bi_sector + ((*bip)->bi_size >> 9) > bi->bi_sector)
2197                         goto overlap;
2198                 bip = & (*bip)->bi_next;
2199         }
2200         if (*bip && (*bip)->bi_sector < bi->bi_sector + ((bi->bi_size)>>9))
2201                 goto overlap;
2202
2203         BUG_ON(*bip && bi->bi_next && (*bip) != bi->bi_next);
2204         if (*bip)
2205                 bi->bi_next = *bip;
2206         *bip = bi;
2207         bi->bi_phys_segments++;
2208
2209         if (forwrite) {
2210                 /* check if page is covered */
2211                 sector_t sector = sh->dev[dd_idx].sector;
2212                 for (bi=sh->dev[dd_idx].towrite;
2213                      sector < sh->dev[dd_idx].sector + STRIPE_SECTORS &&
2214                              bi && bi->bi_sector <= sector;
2215                      bi = r5_next_bio(bi, sh->dev[dd_idx].sector)) {
2216                         if (bi->bi_sector + (bi->bi_size>>9) >= sector)
2217                                 sector = bi->bi_sector + (bi->bi_size>>9);
2218                 }
2219                 if (sector >= sh->dev[dd_idx].sector + STRIPE_SECTORS)
2220                         set_bit(R5_OVERWRITE, &sh->dev[dd_idx].flags);
2221         }
2222         spin_unlock_irq(&conf->device_lock);
2223
2224         pr_debug("added bi b#%llu to stripe s#%llu, disk %d.\n",
2225                 (unsigned long long)(*bip)->bi_sector,
2226                 (unsigned long long)sh->sector, dd_idx);
2227
2228         if (conf->mddev->bitmap && firstwrite) {
2229                 bitmap_startwrite(conf->mddev->bitmap, sh->sector,
2230                                   STRIPE_SECTORS, 0);
2231                 sh->bm_seq = conf->seq_flush+1;
2232                 set_bit(STRIPE_BIT_DELAY, &sh->state);
2233         }
2234         return 1;
2235
2236  overlap:
2237         set_bit(R5_Overlap, &sh->dev[dd_idx].flags);
2238         spin_unlock_irq(&conf->device_lock);
2239         return 0;
2240 }
2241
2242 static void end_reshape(struct r5conf *conf);
2243
2244 static void stripe_set_idx(sector_t stripe, struct r5conf *conf, int previous,
2245                             struct stripe_head *sh)
2246 {
2247         int sectors_per_chunk =
2248                 previous ? conf->prev_chunk_sectors : conf->chunk_sectors;
2249         int dd_idx;
2250         int chunk_offset = sector_div(stripe, sectors_per_chunk);
2251         int disks = previous ? conf->previous_raid_disks : conf->raid_disks;
2252
2253         raid5_compute_sector(conf,
2254                              stripe * (disks - conf->max_degraded)
2255                              *sectors_per_chunk + chunk_offset,
2256                              previous,
2257                              &dd_idx, sh);
2258 }
2259
2260 static void
2261 handle_failed_stripe(struct r5conf *conf, struct stripe_head *sh,
2262                                 struct stripe_head_state *s, int disks,
2263                                 struct bio **return_bi)
2264 {
2265         int i;
2266         for (i = disks; i--; ) {
2267                 struct bio *bi;
2268                 int bitmap_end = 0;
2269
2270                 if (test_bit(R5_ReadError, &sh->dev[i].flags)) {
2271                         struct md_rdev *rdev;
2272                         rcu_read_lock();
2273                         rdev = rcu_dereference(conf->disks[i].rdev);
2274                         if (rdev && test_bit(In_sync, &rdev->flags))
2275                                 atomic_inc(&rdev->nr_pending);
2276                         else
2277                                 rdev = NULL;
2278                         rcu_read_unlock();
2279                         if (rdev) {
2280                                 if (!rdev_set_badblocks(
2281                                             rdev,
2282                                             sh->sector,
2283                                             STRIPE_SECTORS, 0))
2284                                         md_error(conf->mddev, rdev);
2285                                 rdev_dec_pending(rdev, conf->mddev);
2286                         }
2287                 }
2288                 spin_lock_irq(&conf->device_lock);
2289                 /* fail all writes first */
2290                 bi = sh->dev[i].towrite;
2291                 sh->dev[i].towrite = NULL;
2292                 if (bi) {
2293                         s->to_write--;
2294                         bitmap_end = 1;
2295                 }
2296
2297                 if (test_and_clear_bit(R5_Overlap, &sh->dev[i].flags))
2298                         wake_up(&conf->wait_for_overlap);
2299
2300                 while (bi && bi->bi_sector <
2301                         sh->dev[i].sector + STRIPE_SECTORS) {
2302                         struct bio *nextbi = r5_next_bio(bi, sh->dev[i].sector);
2303                         clear_bit(BIO_UPTODATE, &bi->bi_flags);
2304                         if (!raid5_dec_bi_phys_segments(bi)) {
2305                                 md_write_end(conf->mddev);
2306                                 bi->bi_next = *return_bi;
2307                                 *return_bi = bi;
2308                         }
2309                         bi = nextbi;
2310                 }
2311                 /* and fail all 'written' */
2312                 bi = sh->dev[i].written;
2313                 sh->dev[i].written = NULL;
2314                 if (bi) bitmap_end = 1;
2315                 while (bi && bi->bi_sector <
2316                        sh->dev[i].sector + STRIPE_SECTORS) {
2317                         struct bio *bi2 = r5_next_bio(bi, sh->dev[i].sector);
2318                         clear_bit(BIO_UPTODATE, &bi->bi_flags);
2319                         if (!raid5_dec_bi_phys_segments(bi)) {
2320                                 md_write_end(conf->mddev);
2321                                 bi->bi_next = *return_bi;
2322                                 *return_bi = bi;
2323                         }
2324                         bi = bi2;
2325                 }
2326
2327                 /* fail any reads if this device is non-operational and
2328                  * the data has not reached the cache yet.
2329                  */
2330                 if (!test_bit(R5_Wantfill, &sh->dev[i].flags) &&
2331                     (!test_bit(R5_Insync, &sh->dev[i].flags) ||
2332                       test_bit(R5_ReadError, &sh->dev[i].flags))) {
2333                         bi = sh->dev[i].toread;
2334                         sh->dev[i].toread = NULL;
2335                         if (test_and_clear_bit(R5_Overlap, &sh->dev[i].flags))
2336                                 wake_up(&conf->wait_for_overlap);
2337                         if (bi) s->to_read--;
2338                         while (bi && bi->bi_sector <
2339                                sh->dev[i].sector + STRIPE_SECTORS) {
2340                                 struct bio *nextbi =
2341                                         r5_next_bio(bi, sh->dev[i].sector);
2342                                 clear_bit(BIO_UPTODATE, &bi->bi_flags);
2343                                 if (!raid5_dec_bi_phys_segments(bi)) {
2344                                         bi->bi_next = *return_bi;
2345                                         *return_bi = bi;
2346                                 }
2347                                 bi = nextbi;
2348                         }
2349                 }
2350                 spin_unlock_irq(&conf->device_lock);
2351                 if (bitmap_end)
2352                         bitmap_endwrite(conf->mddev->bitmap, sh->sector,
2353                                         STRIPE_SECTORS, 0, 0);
2354                 /* If we were in the middle of a write the parity block might
2355                  * still be locked - so just clear all R5_LOCKED flags
2356                  */
2357                 clear_bit(R5_LOCKED, &sh->dev[i].flags);
2358         }
2359
2360         if (test_and_clear_bit(STRIPE_FULL_WRITE, &sh->state))
2361                 if (atomic_dec_and_test(&conf->pending_full_writes))
2362                         md_wakeup_thread(conf->mddev->thread);
2363 }
2364
2365 static void
2366 handle_failed_sync(struct r5conf *conf, struct stripe_head *sh,
2367                    struct stripe_head_state *s)
2368 {
2369         int abort = 0;
2370         int i;
2371
2372         md_done_sync(conf->mddev, STRIPE_SECTORS, 0);
2373         clear_bit(STRIPE_SYNCING, &sh->state);
2374         s->syncing = 0;
2375         /* There is nothing more to do for sync/check/repair.
2376          * For recover we need to record a bad block on all
2377          * non-sync devices, or abort the recovery
2378          */
2379         if (!test_bit(MD_RECOVERY_RECOVER, &conf->mddev->recovery))
2380                 return;
2381         /* During recovery devices cannot be removed, so locking and
2382          * refcounting of rdevs is not needed
2383          */
2384         for (i = 0; i < conf->raid_disks; i++) {
2385                 struct md_rdev *rdev = conf->disks[i].rdev;
2386                 if (!rdev
2387                     || test_bit(Faulty, &rdev->flags)
2388                     || test_bit(In_sync, &rdev->flags))
2389                         continue;
2390                 if (!rdev_set_badblocks(rdev, sh->sector,
2391                                         STRIPE_SECTORS, 0))
2392                         abort = 1;
2393         }
2394         if (abort) {
2395                 conf->recovery_disabled = conf->mddev->recovery_disabled;
2396                 set_bit(MD_RECOVERY_INTR, &conf->mddev->recovery);
2397         }
2398 }
2399
2400 /* fetch_block - checks the given member device to see if its data needs
2401  * to be read or computed to satisfy a request.
2402  *
2403  * Returns 1 when no more member devices need to be checked, otherwise returns
2404  * 0 to tell the loop in handle_stripe_fill to continue
2405  */
2406 static int fetch_block(struct stripe_head *sh, struct stripe_head_state *s,
2407                        int disk_idx, int disks)
2408 {
2409         struct r5dev *dev = &sh->dev[disk_idx];
2410         struct r5dev *fdev[2] = { &sh->dev[s->failed_num[0]],
2411                                   &sh->dev[s->failed_num[1]] };
2412
2413         /* is the data in this block needed, and can we get it? */
2414         if (!test_bit(R5_LOCKED, &dev->flags) &&
2415             !test_bit(R5_UPTODATE, &dev->flags) &&
2416             (dev->toread ||
2417              (dev->towrite && !test_bit(R5_OVERWRITE, &dev->flags)) ||
2418              s->syncing || s->expanding ||
2419              (s->failed >= 1 && fdev[0]->toread) ||
2420              (s->failed >= 2 && fdev[1]->toread) ||
2421              (sh->raid_conf->level <= 5 && s->failed && fdev[0]->towrite &&
2422               !test_bit(R5_OVERWRITE, &fdev[0]->flags)) ||
2423              (sh->raid_conf->level == 6 && s->failed && s->to_write))) {
2424                 /* we would like to get this block, possibly by computing it,
2425                  * otherwise read it if the backing disk is insync
2426                  */
2427                 BUG_ON(test_bit(R5_Wantcompute, &dev->flags));
2428                 BUG_ON(test_bit(R5_Wantread, &dev->flags));
2429                 if ((s->uptodate == disks - 1) &&
2430                     (s->failed && (disk_idx == s->failed_num[0] ||
2431                                    disk_idx == s->failed_num[1]))) {
2432                         /* have disk failed, and we're requested to fetch it;
2433                          * do compute it
2434                          */
2435                         pr_debug("Computing stripe %llu block %d\n",
2436                                (unsigned long long)sh->sector, disk_idx);
2437                         set_bit(STRIPE_COMPUTE_RUN, &sh->state);
2438                         set_bit(STRIPE_OP_COMPUTE_BLK, &s->ops_request);
2439                         set_bit(R5_Wantcompute, &dev->flags);
2440                         sh->ops.target = disk_idx;
2441                         sh->ops.target2 = -1; /* no 2nd target */
2442                         s->req_compute = 1;
2443                         /* Careful: from this point on 'uptodate' is in the eye
2444                          * of raid_run_ops which services 'compute' operations
2445                          * before writes. R5_Wantcompute flags a block that will
2446                          * be R5_UPTODATE by the time it is needed for a
2447                          * subsequent operation.
2448                          */
2449                         s->uptodate++;
2450                         return 1;
2451                 } else if (s->uptodate == disks-2 && s->failed >= 2) {
2452                         /* Computing 2-failure is *very* expensive; only
2453                          * do it if failed >= 2
2454                          */
2455                         int other;
2456                         for (other = disks; other--; ) {
2457                                 if (other == disk_idx)
2458                                         continue;
2459                                 if (!test_bit(R5_UPTODATE,
2460                                       &sh->dev[other].flags))
2461                                         break;
2462                         }
2463                         BUG_ON(other < 0);
2464                         pr_debug("Computing stripe %llu blocks %d,%d\n",
2465                                (unsigned long long)sh->sector,
2466                                disk_idx, other);
2467                         set_bit(STRIPE_COMPUTE_RUN, &sh->state);
2468                         set_bit(STRIPE_OP_COMPUTE_BLK, &s->ops_request);
2469                         set_bit(R5_Wantcompute, &sh->dev[disk_idx].flags);
2470                         set_bit(R5_Wantcompute, &sh->dev[other].flags);
2471                         sh->ops.target = disk_idx;
2472                         sh->ops.target2 = other;
2473                         s->uptodate += 2;
2474                         s->req_compute = 1;
2475                         return 1;
2476                 } else if (test_bit(R5_Insync, &dev->flags)) {
2477                         set_bit(R5_LOCKED, &dev->flags);
2478                         set_bit(R5_Wantread, &dev->flags);
2479                         s->locked++;
2480                         pr_debug("Reading block %d (sync=%d)\n",
2481                                 disk_idx, s->syncing);
2482                 }
2483         }
2484
2485         return 0;
2486 }
2487
2488 /**
2489  * handle_stripe_fill - read or compute data to satisfy pending requests.
2490  */
2491 static void handle_stripe_fill(struct stripe_head *sh,
2492                                struct stripe_head_state *s,
2493                                int disks)
2494 {
2495         int i;
2496
2497         /* look for blocks to read/compute, skip this if a compute
2498          * is already in flight, or if the stripe contents are in the
2499          * midst of changing due to a write
2500          */
2501         if (!test_bit(STRIPE_COMPUTE_RUN, &sh->state) && !sh->check_state &&
2502             !sh->reconstruct_state)
2503                 for (i = disks; i--; )
2504                         if (fetch_block(sh, s, i, disks))
2505                                 break;
2506         set_bit(STRIPE_HANDLE, &sh->state);
2507 }
2508
2509
2510 /* handle_stripe_clean_event
2511  * any written block on an uptodate or failed drive can be returned.
2512  * Note that if we 'wrote' to a failed drive, it will be UPTODATE, but
2513  * never LOCKED, so we don't need to test 'failed' directly.
2514  */
2515 static void handle_stripe_clean_event(struct r5conf *conf,
2516         struct stripe_head *sh, int disks, struct bio **return_bi)
2517 {
2518         int i;
2519         struct r5dev *dev;
2520
2521         for (i = disks; i--; )
2522                 if (sh->dev[i].written) {
2523                         dev = &sh->dev[i];
2524                         if (!test_bit(R5_LOCKED, &dev->flags) &&
2525                                 test_bit(R5_UPTODATE, &dev->flags)) {
2526                                 /* We can return any write requests */
2527                                 struct bio *wbi, *wbi2;
2528                                 int bitmap_end = 0;
2529                                 pr_debug("Return write for disc %d\n", i);
2530                                 spin_lock_irq(&conf->device_lock);
2531                                 wbi = dev->written;
2532                                 dev->written = NULL;
2533                                 while (wbi && wbi->bi_sector <
2534                                         dev->sector + STRIPE_SECTORS) {
2535                                         wbi2 = r5_next_bio(wbi, dev->sector);
2536                                         if (!raid5_dec_bi_phys_segments(wbi)) {
2537                                                 md_write_end(conf->mddev);
2538                                                 wbi->bi_next = *return_bi;
2539                                                 *return_bi = wbi;
2540                                         }
2541                                         wbi = wbi2;
2542                                 }
2543                                 if (dev->towrite == NULL)
2544                                         bitmap_end = 1;
2545                                 spin_unlock_irq(&conf->device_lock);
2546                                 if (bitmap_end)
2547                                         bitmap_endwrite(conf->mddev->bitmap,
2548                                                         sh->sector,
2549                                                         STRIPE_SECTORS,
2550                                          !test_bit(STRIPE_DEGRADED, &sh->state),
2551                                                         0);
2552                         }
2553                 }
2554
2555         if (test_and_clear_bit(STRIPE_FULL_WRITE, &sh->state))
2556                 if (atomic_dec_and_test(&conf->pending_full_writes))
2557                         md_wakeup_thread(conf->mddev->thread);
2558 }
2559
2560 static void handle_stripe_dirtying(struct r5conf *conf,
2561                                    struct stripe_head *sh,
2562                                    struct stripe_head_state *s,
2563                                    int disks)
2564 {
2565         int rmw = 0, rcw = 0, i;
2566         if (conf->max_degraded == 2) {
2567                 /* RAID6 requires 'rcw' in current implementation
2568                  * Calculate the real rcw later - for now fake it
2569                  * look like rcw is cheaper
2570                  */
2571                 rcw = 1; rmw = 2;
2572         } else for (i = disks; i--; ) {
2573                 /* would I have to read this buffer for read_modify_write */
2574                 struct r5dev *dev = &sh->dev[i];
2575                 if ((dev->towrite || i == sh->pd_idx) &&
2576                     !test_bit(R5_LOCKED, &dev->flags) &&
2577                     !(test_bit(R5_UPTODATE, &dev->flags) ||
2578                       test_bit(R5_Wantcompute, &dev->flags))) {
2579                         if (test_bit(R5_Insync, &dev->flags))
2580                                 rmw++;
2581                         else
2582                                 rmw += 2*disks;  /* cannot read it */
2583                 }
2584                 /* Would I have to read this buffer for reconstruct_write */
2585                 if (!test_bit(R5_OVERWRITE, &dev->flags) && i != sh->pd_idx &&
2586                     !test_bit(R5_LOCKED, &dev->flags) &&
2587                     !(test_bit(R5_UPTODATE, &dev->flags) ||
2588                     test_bit(R5_Wantcompute, &dev->flags))) {
2589                         if (test_bit(R5_Insync, &dev->flags)) rcw++;
2590                         else
2591                                 rcw += 2*disks;
2592                 }
2593         }
2594         pr_debug("for sector %llu, rmw=%d rcw=%d\n",
2595                 (unsigned long long)sh->sector, rmw, rcw);
2596         set_bit(STRIPE_HANDLE, &sh->state);
2597         if (rmw < rcw && rmw > 0)
2598                 /* prefer read-modify-write, but need to get some data */
2599                 for (i = disks; i--; ) {
2600                         struct r5dev *dev = &sh->dev[i];
2601                         if ((dev->towrite || i == sh->pd_idx) &&
2602                             !test_bit(R5_LOCKED, &dev->flags) &&
2603                             !(test_bit(R5_UPTODATE, &dev->flags) ||
2604                             test_bit(R5_Wantcompute, &dev->flags)) &&
2605                             test_bit(R5_Insync, &dev->flags)) {
2606                                 if (
2607                                   test_bit(STRIPE_PREREAD_ACTIVE, &sh->state)) {
2608                                         pr_debug("Read_old block "
2609                                                 "%d for r-m-w\n", i);
2610                                         set_bit(R5_LOCKED, &dev->flags);
2611                                         set_bit(R5_Wantread, &dev->flags);
2612                                         s->locked++;
2613                                 } else {
2614                                         set_bit(STRIPE_DELAYED, &sh->state);
2615                                         set_bit(STRIPE_HANDLE, &sh->state);
2616                                 }
2617                         }
2618                 }
2619         if (rcw <= rmw && rcw > 0) {
2620                 /* want reconstruct write, but need to get some data */
2621                 rcw = 0;
2622                 for (i = disks; i--; ) {
2623                         struct r5dev *dev = &sh->dev[i];
2624                         if (!test_bit(R5_OVERWRITE, &dev->flags) &&
2625                             i != sh->pd_idx && i != sh->qd_idx &&
2626                             !test_bit(R5_LOCKED, &dev->flags) &&
2627                             !(test_bit(R5_UPTODATE, &dev->flags) ||
2628                               test_bit(R5_Wantcompute, &dev->flags))) {
2629                                 rcw++;
2630                                 if (!test_bit(R5_Insync, &dev->flags))
2631                                         continue; /* it's a failed drive */
2632                                 if (
2633                                   test_bit(STRIPE_PREREAD_ACTIVE, &sh->state)) {
2634                                         pr_debug("Read_old block "
2635                                                 "%d for Reconstruct\n", i);
2636                                         set_bit(R5_LOCKED, &dev->flags);
2637                                         set_bit(R5_Wantread, &dev->flags);
2638                                         s->locked++;
2639                                 } else {
2640                                         set_bit(STRIPE_DELAYED, &sh->state);
2641                                         set_bit(STRIPE_HANDLE, &sh->state);
2642                                 }
2643                         }
2644                 }
2645         }
2646         /* now if nothing is locked, and if we have enough data,
2647          * we can start a write request
2648          */
2649         /* since handle_stripe can be called at any time we need to handle the
2650          * case where a compute block operation has been submitted and then a
2651          * subsequent call wants to start a write request.  raid_run_ops only
2652          * handles the case where compute block and reconstruct are requested
2653          * simultaneously.  If this is not the case then new writes need to be
2654          * held off until the compute completes.
2655          */
2656         if ((s->req_compute || !test_bit(STRIPE_COMPUTE_RUN, &sh->state)) &&
2657             (s->locked == 0 && (rcw == 0 || rmw == 0) &&
2658             !test_bit(STRIPE_BIT_DELAY, &sh->state)))
2659                 schedule_reconstruction(sh, s, rcw == 0, 0);
2660 }
2661
2662 static void handle_parity_checks5(struct r5conf *conf, struct stripe_head *sh,
2663                                 struct stripe_head_state *s, int disks)
2664 {
2665         struct r5dev *dev = NULL;
2666
2667         set_bit(STRIPE_HANDLE, &sh->state);
2668
2669         switch (sh->check_state) {
2670         case check_state_idle:
2671                 /* start a new check operation if there are no failures */
2672                 if (s->failed == 0) {
2673                         BUG_ON(s->uptodate != disks);
2674                         sh->check_state = check_state_run;
2675                         set_bit(STRIPE_OP_CHECK, &s->ops_request);
2676                         clear_bit(R5_UPTODATE, &sh->dev[sh->pd_idx].flags);
2677                         s->uptodate--;
2678                         break;
2679                 }
2680                 dev = &sh->dev[s->failed_num[0]];
2681                 /* fall through */
2682         case check_state_compute_result:
2683                 sh->check_state = check_state_idle;
2684                 if (!dev)
2685                         dev = &sh->dev[sh->pd_idx];
2686
2687                 /* check that a write has not made the stripe insync */
2688                 if (test_bit(STRIPE_INSYNC, &sh->state))
2689                         break;
2690
2691                 /* either failed parity check, or recovery is happening */
2692                 BUG_ON(!test_bit(R5_UPTODATE, &dev->flags));
2693                 BUG_ON(s->uptodate != disks);
2694
2695                 set_bit(R5_LOCKED, &dev->flags);
2696                 s->locked++;
2697                 set_bit(R5_Wantwrite, &dev->flags);
2698
2699                 clear_bit(STRIPE_DEGRADED, &sh->state);
2700                 set_bit(STRIPE_INSYNC, &sh->state);
2701                 break;
2702         case check_state_run:
2703                 break; /* we will be called again upon completion */
2704         case check_state_check_result:
2705                 sh->check_state = check_state_idle;
2706
2707                 /* if a failure occurred during the check operation, leave
2708                  * STRIPE_INSYNC not set and let the stripe be handled again
2709                  */
2710                 if (s->failed)
2711                         break;
2712
2713                 /* handle a successful check operation, if parity is correct
2714                  * we are done.  Otherwise update the mismatch count and repair
2715                  * parity if !MD_RECOVERY_CHECK
2716                  */
2717                 if ((sh->ops.zero_sum_result & SUM_CHECK_P_RESULT) == 0)
2718                         /* parity is correct (on disc,
2719                          * not in buffer any more)
2720                          */
2721                         set_bit(STRIPE_INSYNC, &sh->state);
2722                 else {
2723                         conf->mddev->resync_mismatches += STRIPE_SECTORS;
2724                         if (test_bit(MD_RECOVERY_CHECK, &conf->mddev->recovery))
2725                                 /* don't try to repair!! */
2726                                 set_bit(STRIPE_INSYNC, &sh->state);
2727                         else {
2728                                 sh->check_state = check_state_compute_run;
2729                                 set_bit(STRIPE_COMPUTE_RUN, &sh->state);
2730                                 set_bit(STRIPE_OP_COMPUTE_BLK, &s->ops_request);
2731                                 set_bit(R5_Wantcompute,
2732                                         &sh->dev[sh->pd_idx].flags);
2733                                 sh->ops.target = sh->pd_idx;
2734                                 sh->ops.target2 = -1;
2735                                 s->uptodate++;
2736                         }
2737                 }
2738                 break;
2739         case check_state_compute_run:
2740                 break;
2741         default:
2742                 printk(KERN_ERR "%s: unknown check_state: %d sector: %llu\n",
2743                        __func__, sh->check_state,
2744                        (unsigned long long) sh->sector);
2745                 BUG();
2746         }
2747 }
2748
2749
2750 static void handle_parity_checks6(struct r5conf *conf, struct stripe_head *sh,
2751                                   struct stripe_head_state *s,
2752                                   int disks)
2753 {
2754         int pd_idx = sh->pd_idx;
2755         int qd_idx = sh->qd_idx;
2756         struct r5dev *dev;
2757
2758         set_bit(STRIPE_HANDLE, &sh->state);
2759
2760         BUG_ON(s->failed > 2);
2761
2762         /* Want to check and possibly repair P and Q.
2763          * However there could be one 'failed' device, in which
2764          * case we can only check one of them, possibly using the
2765          * other to generate missing data
2766          */
2767
2768         switch (sh->check_state) {
2769         case check_state_idle:
2770                 /* start a new check operation if there are < 2 failures */
2771                 if (s->failed == s->q_failed) {
2772                         /* The only possible failed device holds Q, so it
2773                          * makes sense to check P (If anything else were failed,
2774                          * we would have used P to recreate it).
2775                          */
2776                         sh->check_state = check_state_run;
2777                 }
2778                 if (!s->q_failed && s->failed < 2) {
2779                         /* Q is not failed, and we didn't use it to generate
2780                          * anything, so it makes sense to check it
2781                          */
2782                         if (sh->check_state == check_state_run)
2783                                 sh->check_state = check_state_run_pq;
2784                         else
2785                                 sh->check_state = check_state_run_q;
2786                 }
2787
2788                 /* discard potentially stale zero_sum_result */
2789                 sh->ops.zero_sum_result = 0;
2790
2791                 if (sh->check_state == check_state_run) {
2792                         /* async_xor_zero_sum destroys the contents of P */
2793                         clear_bit(R5_UPTODATE, &sh->dev[pd_idx].flags);
2794                         s->uptodate--;
2795                 }
2796                 if (sh->check_state >= check_state_run &&
2797                     sh->check_state <= check_state_run_pq) {
2798                         /* async_syndrome_zero_sum preserves P and Q, so
2799                          * no need to mark them !uptodate here
2800                          */
2801                         set_bit(STRIPE_OP_CHECK, &s->ops_request);
2802                         break;
2803                 }
2804
2805                 /* we have 2-disk failure */
2806                 BUG_ON(s->failed != 2);
2807                 /* fall through */
2808         case check_state_compute_result:
2809                 sh->check_state = check_state_idle;
2810
2811                 /* check that a write has not made the stripe insync */
2812                 if (test_bit(STRIPE_INSYNC, &sh->state))
2813                         break;
2814
2815                 /* now write out any block on a failed drive,
2816                  * or P or Q if they were recomputed
2817                  */
2818                 BUG_ON(s->uptodate < disks - 1); /* We don't need Q to recover */
2819                 if (s->failed == 2) {
2820                         dev = &sh->dev[s->failed_num[1]];
2821                         s->locked++;
2822                         set_bit(R5_LOCKED, &dev->flags);
2823                         set_bit(R5_Wantwrite, &dev->flags);
2824                 }
2825                 if (s->failed >= 1) {
2826                         dev = &sh->dev[s->failed_num[0]];
2827                         s->locked++;
2828                         set_bit(R5_LOCKED, &dev->flags);
2829                         set_bit(R5_Wantwrite, &dev->flags);
2830                 }
2831                 if (sh->ops.zero_sum_result & SUM_CHECK_P_RESULT) {
2832                         dev = &sh->dev[pd_idx];
2833                         s->locked++;
2834                         set_bit(R5_LOCKED, &dev->flags);
2835                         set_bit(R5_Wantwrite, &dev->flags);
2836                 }
2837                 if (sh->ops.zero_sum_result & SUM_CHECK_Q_RESULT) {
2838                         dev = &sh->dev[qd_idx];
2839                         s->locked++;
2840                         set_bit(R5_LOCKED, &dev->flags);
2841                         set_bit(R5_Wantwrite, &dev->flags);
2842                 }
2843                 clear_bit(STRIPE_DEGRADED, &sh->state);
2844
2845                 set_bit(STRIPE_INSYNC, &sh->state);
2846                 break;
2847         case check_state_run:
2848         case check_state_run_q:
2849         case check_state_run_pq:
2850                 break; /* we will be called again upon completion */
2851         case check_state_check_result:
2852                 sh->check_state = check_state_idle;
2853
2854                 /* handle a successful check operation, if parity is correct
2855                  * we are done.  Otherwise update the mismatch count and repair
2856                  * parity if !MD_RECOVERY_CHECK
2857                  */
2858                 if (sh->ops.zero_sum_result == 0) {
2859                         /* both parities are correct */
2860                         if (!s->failed)
2861                                 set_bit(STRIPE_INSYNC, &sh->state);
2862                         else {
2863                                 /* in contrast to the raid5 case we can validate
2864                                  * parity, but still have a failure to write
2865                                  * back
2866                                  */
2867                                 sh->check_state = check_state_compute_result;
2868                                 /* Returning at this point means that we may go
2869                                  * off and bring p and/or q uptodate again so
2870                                  * we make sure to check zero_sum_result again
2871                                  * to verify if p or q need writeback
2872                                  */
2873                         }
2874                 } else {
2875                         conf->mddev->resync_mismatches += STRIPE_SECTORS;
2876                         if (test_bit(MD_RECOVERY_CHECK, &conf->mddev->recovery))
2877                                 /* don't try to repair!! */
2878                                 set_bit(STRIPE_INSYNC, &sh->state);
2879                         else {
2880                                 int *target = &sh->ops.target;
2881
2882                                 sh->ops.target = -1;
2883                                 sh->ops.target2 = -1;
2884                                 sh->check_state = check_state_compute_run;
2885                                 set_bit(STRIPE_COMPUTE_RUN, &sh->state);
2886                                 set_bit(STRIPE_OP_COMPUTE_BLK, &s->ops_request);
2887                                 if (sh->ops.zero_sum_result & SUM_CHECK_P_RESULT) {
2888                                         set_bit(R5_Wantcompute,
2889                                                 &sh->dev[pd_idx].flags);
2890                                         *target = pd_idx;
2891                                         target = &sh->ops.target2;
2892                                         s->uptodate++;
2893                                 }
2894                                 if (sh->ops.zero_sum_result & SUM_CHECK_Q_RESULT) {
2895                                         set_bit(R5_Wantcompute,
2896                                                 &sh->dev[qd_idx].flags);
2897                                         *target = qd_idx;
2898                                         s->uptodate++;
2899                                 }
2900                         }
2901                 }
2902                 break;
2903         case check_state_compute_run:
2904                 break;
2905         default:
2906                 printk(KERN_ERR "%s: unknown check_state: %d sector: %llu\n",
2907                        __func__, sh->check_state,
2908                        (unsigned long long) sh->sector);
2909                 BUG();
2910         }
2911 }
2912
2913 static void handle_stripe_expansion(struct r5conf *conf, struct stripe_head *sh)
2914 {
2915         int i;
2916
2917         /* We have read all the blocks in this stripe and now we need to
2918          * copy some of them into a target stripe for expand.
2919          */
2920         struct dma_async_tx_descriptor *tx = NULL;
2921         clear_bit(STRIPE_EXPAND_SOURCE, &sh->state);
2922         for (i = 0; i < sh->disks; i++)
2923                 if (i != sh->pd_idx && i != sh->qd_idx) {
2924                         int dd_idx, j;
2925                         struct stripe_head *sh2;
2926                         struct async_submit_ctl submit;
2927
2928                         sector_t bn = compute_blocknr(sh, i, 1);
2929                         sector_t s = raid5_compute_sector(conf, bn, 0,
2930                                                           &dd_idx, NULL);
2931                         sh2 = get_active_stripe(conf, s, 0, 1, 1);
2932                         if (sh2 == NULL)
2933                                 /* so far only the early blocks of this stripe
2934                                  * have been requested.  When later blocks
2935                                  * get requested, we will try again
2936                                  */
2937                                 continue;
2938                         if (!test_bit(STRIPE_EXPANDING, &sh2->state) ||
2939                            test_bit(R5_Expanded, &sh2->dev[dd_idx].flags)) {
2940                                 /* must have already done this block */
2941                                 release_stripe(sh2);
2942                                 continue;
2943                         }
2944
2945                         /* place all the copies on one channel */
2946                         init_async_submit(&submit, 0, tx, NULL, NULL, NULL);
2947                         tx = async_memcpy(sh2->dev[dd_idx].page,
2948                                           sh->dev[i].page, 0, 0, STRIPE_SIZE,
2949                                           &submit);
2950
2951                         set_bit(R5_Expanded, &sh2->dev[dd_idx].flags);
2952                         set_bit(R5_UPTODATE, &sh2->dev[dd_idx].flags);
2953                         for (j = 0; j < conf->raid_disks; j++)
2954                                 if (j != sh2->pd_idx &&
2955                                     j != sh2->qd_idx &&
2956                                     !test_bit(R5_Expanded, &sh2->dev[j].flags))
2957                                         break;
2958                         if (j == conf->raid_disks) {
2959                                 set_bit(STRIPE_EXPAND_READY, &sh2->state);
2960                                 set_bit(STRIPE_HANDLE, &sh2->state);
2961                         }
2962                         release_stripe(sh2);
2963
2964                 }
2965         /* done submitting copies, wait for them to complete */
2966         if (tx) {
2967                 async_tx_ack(tx);
2968                 dma_wait_for_async_tx(tx);
2969         }
2970 }
2971
2972
2973 /*
2974  * handle_stripe - do things to a stripe.
2975  *
2976  * We lock the stripe and then examine the state of various bits
2977  * to see what needs to be done.
2978  * Possible results:
2979  *    return some read request which now have data
2980  *    return some write requests which are safely on disc
2981  *    schedule a read on some buffers
2982  *    schedule a write of some buffers
2983  *    return confirmation of parity correctness
2984  *
2985  * buffers are taken off read_list or write_list, and bh_cache buffers
2986  * get BH_Lock set before the stripe lock is released.
2987  *
2988  */
2989
2990 static void analyse_stripe(struct stripe_head *sh, struct stripe_head_state *s)
2991 {
2992         struct r5conf *conf = sh->raid_conf;
2993         int disks = sh->disks;
2994         struct r5dev *dev;
2995         int i;
2996
2997         memset(s, 0, sizeof(*s));
2998
2999         s->syncing = test_bit(STRIPE_SYNCING, &sh->state);
3000         s->expanding = test_bit(STRIPE_EXPAND_SOURCE, &sh->state);
3001         s->expanded = test_bit(STRIPE_EXPAND_READY, &sh->state);
3002         s->failed_num[0] = -1;
3003         s->failed_num[1] = -1;
3004
3005         /* Now to look around and see what can be done */
3006         rcu_read_lock();
3007         spin_lock_irq(&conf->device_lock);
3008         for (i=disks; i--; ) {
3009                 struct md_rdev *rdev;
3010                 sector_t first_bad;
3011                 int bad_sectors;
3012                 int is_bad = 0;
3013
3014                 dev = &sh->dev[i];
3015
3016                 pr_debug("check %d: state 0x%lx read %p write %p written %p\n",
3017                         i, dev->flags, dev->toread, dev->towrite, dev->written);
3018                 /* maybe we can reply to a read
3019                  *
3020                  * new wantfill requests are only permitted while
3021                  * ops_complete_biofill is guaranteed to be inactive
3022                  */
3023                 if (test_bit(R5_UPTODATE, &dev->flags) && dev->toread &&
3024                     !test_bit(STRIPE_BIOFILL_RUN, &sh->state))
3025                         set_bit(R5_Wantfill, &dev->flags);
3026
3027                 /* now count some things */
3028                 if (test_bit(R5_LOCKED, &dev->flags))
3029                         s->locked++;
3030                 if (test_bit(R5_UPTODATE, &dev->flags))
3031                         s->uptodate++;
3032                 if (test_bit(R5_Wantcompute, &dev->flags)) {
3033                         s->compute++;
3034                         BUG_ON(s->compute > 2);
3035                 }
3036
3037                 if (test_bit(R5_Wantfill, &dev->flags))
3038                         s->to_fill++;
3039                 else if (dev->toread)
3040                         s->to_read++;
3041                 if (dev->towrite) {
3042                         s->to_write++;
3043                         if (!test_bit(R5_OVERWRITE, &dev->flags))
3044                                 s->non_overwrite++;
3045                 }
3046                 if (dev->written)
3047                         s->written++;
3048                 rdev = rcu_dereference(conf->disks[i].rdev);
3049                 if (rdev && test_bit(Faulty, &rdev->flags))
3050                         rdev = NULL;
3051                 if (rdev) {
3052                         is_bad = is_badblock(rdev, sh->sector, STRIPE_SECTORS,
3053                                              &first_bad, &bad_sectors);
3054                         if (s->blocked_rdev == NULL
3055                             && (test_bit(Blocked, &rdev->flags)
3056                                 || is_bad < 0)) {
3057                                 if (is_bad < 0)
3058                                         set_bit(BlockedBadBlocks,
3059                                                 &rdev->flags);
3060                                 s->blocked_rdev = rdev;
3061                                 atomic_inc(&rdev->nr_pending);
3062                         }
3063                 }
3064                 clear_bit(R5_Insync, &dev->flags);
3065                 if (!rdev)
3066                         /* Not in-sync */;
3067                 else if (is_bad) {
3068                         /* also not in-sync */
3069                         if (!test_bit(WriteErrorSeen, &rdev->flags)) {
3070                                 /* treat as in-sync, but with a read error
3071                                  * which we can now try to correct
3072                                  */
3073                                 set_bit(R5_Insync, &dev->flags);
3074                                 set_bit(R5_ReadError, &dev->flags);
3075                         }
3076                 } else if (test_bit(In_sync, &rdev->flags))
3077                         set_bit(R5_Insync, &dev->flags);
3078                 else if (sh->sector + STRIPE_SECTORS <= rdev->recovery_offset)
3079                         /* in sync if before recovery_offset */
3080                         set_bit(R5_Insync, &dev->flags);
3081                 else if (test_bit(R5_UPTODATE, &dev->flags) &&
3082                          test_bit(R5_Expanded, &dev->flags))
3083                         /* If we've reshaped into here, we assume it is Insync.
3084                          * We will shortly update recovery_offset to make
3085                          * it official.
3086                          */
3087                         set_bit(R5_Insync, &dev->flags);
3088
3089                 if (test_bit(R5_WriteError, &dev->flags)) {
3090                         clear_bit(R5_Insync, &dev->flags);
3091                         if (!test_bit(Faulty, &rdev->flags)) {
3092                                 s->handle_bad_blocks = 1;
3093                                 atomic_inc(&rdev->nr_pending);
3094                         } else
3095                                 clear_bit(R5_WriteError, &dev->flags);
3096                 }
3097                 if (test_bit(R5_MadeGood, &dev->flags)) {
3098                         if (!test_bit(Faulty, &rdev->flags)) {
3099                                 s->handle_bad_blocks = 1;
3100                                 atomic_inc(&rdev->nr_pending);
3101                         } else
3102                                 clear_bit(R5_MadeGood, &dev->flags);
3103                 }
3104                 if (!test_bit(R5_Insync, &dev->flags)) {
3105                         /* The ReadError flag will just be confusing now */
3106                         clear_bit(R5_ReadError, &dev->flags);
3107                         clear_bit(R5_ReWrite, &dev->flags);
3108                 }
3109                 if (test_bit(R5_ReadError, &dev->flags))
3110                         clear_bit(R5_Insync, &dev->flags);
3111                 if (!test_bit(R5_Insync, &dev->flags)) {
3112                         if (s->failed < 2)
3113                                 s->failed_num[s->failed] = i;
3114                         s->failed++;
3115                 }
3116         }
3117         spin_unlock_irq(&conf->device_lock);
3118         rcu_read_unlock();
3119 }
3120
3121 static void handle_stripe(struct stripe_head *sh)
3122 {
3123         struct stripe_head_state s;
3124         struct r5conf *conf = sh->raid_conf;
3125         int i;
3126         int prexor;
3127         int disks = sh->disks;
3128         struct r5dev *pdev, *qdev;
3129
3130         clear_bit(STRIPE_HANDLE, &sh->state);
3131         if (test_and_set_bit_lock(STRIPE_ACTIVE, &sh->state)) {
3132                 /* already being handled, ensure it gets handled
3133                  * again when current action finishes */
3134                 set_bit(STRIPE_HANDLE, &sh->state);
3135                 return;
3136         }
3137
3138         if (test_and_clear_bit(STRIPE_SYNC_REQUESTED, &sh->state)) {
3139                 set_bit(STRIPE_SYNCING, &sh->state);
3140                 clear_bit(STRIPE_INSYNC, &sh->state);
3141         }
3142         clear_bit(STRIPE_DELAYED, &sh->state);
3143
3144         pr_debug("handling stripe %llu, state=%#lx cnt=%d, "
3145                 "pd_idx=%d, qd_idx=%d\n, check:%d, reconstruct:%d\n",
3146                (unsigned long long)sh->sector, sh->state,
3147                atomic_read(&sh->count), sh->pd_idx, sh->qd_idx,
3148                sh->check_state, sh->reconstruct_state);
3149
3150         analyse_stripe(sh, &s);
3151
3152         if (s.handle_bad_blocks) {
3153                 set_bit(STRIPE_HANDLE, &sh->state);
3154                 goto finish;
3155         }
3156
3157         if (unlikely(s.blocked_rdev)) {
3158                 if (s.syncing || s.expanding || s.expanded ||
3159                     s.to_write || s.written) {
3160                         set_bit(STRIPE_HANDLE, &sh->state);
3161                         goto finish;
3162                 }
3163                 /* There is nothing for the blocked_rdev to block */
3164                 rdev_dec_pending(s.blocked_rdev, conf->mddev);
3165                 s.blocked_rdev = NULL;
3166         }
3167
3168         if (s.to_fill && !test_bit(STRIPE_BIOFILL_RUN, &sh->state)) {
3169                 set_bit(STRIPE_OP_BIOFILL, &s.ops_request);
3170                 set_bit(STRIPE_BIOFILL_RUN, &sh->state);
3171         }
3172
3173         pr_debug("locked=%d uptodate=%d to_read=%d"
3174                " to_write=%d failed=%d failed_num=%d,%d\n",
3175                s.locked, s.uptodate, s.to_read, s.to_write, s.failed,
3176                s.failed_num[0], s.failed_num[1]);
3177         /* check if the array has lost more than max_degraded devices and,
3178          * if so, some requests might need to be failed.
3179          */
3180         if (s.failed > conf->max_degraded) {
3181                 sh->check_state = 0;
3182                 sh->reconstruct_state = 0;
3183                 if (s.to_read+s.to_write+s.written)
3184                         handle_failed_stripe(conf, sh, &s, disks, &s.return_bi);
3185                 if (s.syncing)
3186                         handle_failed_sync(conf, sh, &s);
3187         }
3188
3189         /*
3190          * might be able to return some write requests if the parity blocks
3191          * are safe, or on a failed drive
3192          */
3193         pdev = &sh->dev[sh->pd_idx];
3194         s.p_failed = (s.failed >= 1 && s.failed_num[0] == sh->pd_idx)
3195                 || (s.failed >= 2 && s.failed_num[1] == sh->pd_idx);
3196         qdev = &sh->dev[sh->qd_idx];
3197         s.q_failed = (s.failed >= 1 && s.failed_num[0] == sh->qd_idx)
3198                 || (s.failed >= 2 && s.failed_num[1] == sh->qd_idx)
3199                 || conf->level < 6;
3200
3201         if (s.written &&
3202             (s.p_failed || ((test_bit(R5_Insync, &pdev->flags)
3203                              && !test_bit(R5_LOCKED, &pdev->flags)
3204                              && test_bit(R5_UPTODATE, &pdev->flags)))) &&
3205             (s.q_failed || ((test_bit(R5_Insync, &qdev->flags)
3206                              && !test_bit(R5_LOCKED, &qdev->flags)
3207                              && test_bit(R5_UPTODATE, &qdev->flags)))))
3208                 handle_stripe_clean_event(conf, sh, disks, &s.return_bi);
3209
3210         /* Now we might consider reading some blocks, either to check/generate
3211          * parity, or to satisfy requests
3212          * or to load a block that is being partially written.
3213          */
3214         if (s.to_read || s.non_overwrite
3215             || (conf->level == 6 && s.to_write && s.failed)
3216             || (s.syncing && (s.uptodate + s.compute < disks)) || s.expanding)
3217                 handle_stripe_fill(sh, &s, disks);
3218
3219         /* Now we check to see if any write operations have recently
3220          * completed
3221          */
3222         prexor = 0;
3223         if (sh->reconstruct_state == reconstruct_state_prexor_drain_result)
3224                 prexor = 1;
3225         if (sh->reconstruct_state == reconstruct_state_drain_result ||
3226             sh->reconstruct_state == reconstruct_state_prexor_drain_result) {
3227                 sh->reconstruct_state = reconstruct_state_idle;
3228
3229                 /* All the 'written' buffers and the parity block are ready to
3230                  * be written back to disk
3231                  */
3232                 BUG_ON(!test_bit(R5_UPTODATE, &sh->dev[sh->pd_idx].flags));
3233                 BUG_ON(sh->qd_idx >= 0 &&
3234                        !test_bit(R5_UPTODATE, &sh->dev[sh->qd_idx].flags));
3235                 for (i = disks; i--; ) {
3236                         struct r5dev *dev = &sh->dev[i];
3237                         if (test_bit(R5_LOCKED, &dev->flags) &&
3238                                 (i == sh->pd_idx || i == sh->qd_idx ||
3239                                  dev->written)) {
3240                                 pr_debug("Writing block %d\n", i);
3241                                 set_bit(R5_Wantwrite, &dev->flags);
3242                                 if (prexor)
3243                                         continue;
3244                                 if (s.failed > 1)
3245                                         continue;
3246                                 if (!test_bit(R5_Insync, &dev->flags) ||
3247                                     ((i == sh->pd_idx || i == sh->qd_idx)  &&
3248                                      s.failed == 0))
3249                                         set_bit(STRIPE_INSYNC, &sh->state);
3250                         }
3251                 }
3252                 if (test_and_clear_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
3253                         s.dec_preread_active = 1;
3254         }
3255
3256         /* Now to consider new write requests and what else, if anything
3257          * should be read.  We do not handle new writes when:
3258          * 1/ A 'write' operation (copy+xor) is already in flight.
3259          * 2/ A 'check' operation is in flight, as it may clobber the parity
3260          *    block.
3261          */
3262         if (s.to_write && !sh->reconstruct_state && !sh->check_state)
3263                 handle_stripe_dirtying(conf, sh, &s, disks);
3264
3265         /* maybe we need to check and possibly fix the parity for this stripe
3266          * Any reads will already have been scheduled, so we just see if enough
3267          * data is available.  The parity check is held off while parity
3268          * dependent operations are in flight.
3269          */
3270         if (sh->check_state ||
3271             (s.syncing && s.locked == 0 &&
3272              !test_bit(STRIPE_COMPUTE_RUN, &sh->state) &&
3273              !test_bit(STRIPE_INSYNC, &sh->state))) {
3274                 if (conf->level == 6)
3275                         handle_parity_checks6(conf, sh, &s, disks);
3276                 else
3277                         handle_parity_checks5(conf, sh, &s, disks);
3278         }
3279
3280         if (s.syncing && s.locked == 0 && test_bit(STRIPE_INSYNC, &sh->state)) {
3281                 md_done_sync(conf->mddev, STRIPE_SECTORS, 1);
3282                 clear_bit(STRIPE_SYNCING, &sh->state);
3283         }
3284
3285         /* If the failed drives are just a ReadError, then we might need
3286          * to progress the repair/check process
3287          */
3288         if (s.failed <= conf->max_degraded && !conf->mddev->ro)
3289                 for (i = 0; i < s.failed; i++) {
3290                         struct r5dev *dev = &sh->dev[s.failed_num[i]];
3291                         if (test_bit(R5_ReadError, &dev->flags)
3292                             && !test_bit(R5_LOCKED, &dev->flags)
3293                             && test_bit(R5_UPTODATE, &dev->flags)
3294                                 ) {
3295                                 if (!test_bit(R5_ReWrite, &dev->flags)) {
3296                                         set_bit(R5_Wantwrite, &dev->flags);
3297                                         set_bit(R5_ReWrite, &dev->flags);
3298                                         set_bit(R5_LOCKED, &dev->flags);
3299                                         s.locked++;
3300                                 } else {
3301                                         /* let's read it back */
3302                                         set_bit(R5_Wantread, &dev->flags);
3303                                         set_bit(R5_LOCKED, &dev->flags);
3304                                         s.locked++;
3305                                 }
3306                         }
3307                 }
3308
3309
3310         /* Finish reconstruct operations initiated by the expansion process */
3311         if (sh->reconstruct_state == reconstruct_state_result) {
3312                 struct stripe_head *sh_src
3313                         = get_active_stripe(conf, sh->sector, 1, 1, 1);
3314                 if (sh_src && test_bit(STRIPE_EXPAND_SOURCE, &sh_src->state)) {
3315                         /* sh cannot be written until sh_src has been read.
3316                          * so arrange for sh to be delayed a little
3317                          */
3318                         set_bit(STRIPE_DELAYED, &sh->state);
3319                         set_bit(STRIPE_HANDLE, &sh->state);
3320                         if (!test_and_set_bit(STRIPE_PREREAD_ACTIVE,
3321                                               &sh_src->state))
3322                                 atomic_inc(&conf->preread_active_stripes);
3323                         release_stripe(sh_src);
3324                         goto finish;
3325                 }
3326                 if (sh_src)
3327                         release_stripe(sh_src);
3328
3329                 sh->reconstruct_state = reconstruct_state_idle;
3330                 clear_bit(STRIPE_EXPANDING, &sh->state);
3331                 for (i = conf->raid_disks; i--; ) {
3332                         set_bit(R5_Wantwrite, &sh->dev[i].flags);
3333                         set_bit(R5_LOCKED, &sh->dev[i].flags);
3334                         s.locked++;
3335                 }
3336         }
3337
3338         if (s.expanded && test_bit(STRIPE_EXPANDING, &sh->state) &&
3339             !sh->reconstruct_state) {
3340                 /* Need to write out all blocks after computing parity */
3341                 sh->disks = conf->raid_disks;
3342                 stripe_set_idx(sh->sector, conf, 0, sh);
3343                 schedule_reconstruction(sh, &s, 1, 1);
3344         } else if (s.expanded && !sh->reconstruct_state && s.locked == 0) {
3345                 clear_bit(STRIPE_EXPAND_READY, &sh->state);
3346                 atomic_dec(&conf->reshape_stripes);
3347                 wake_up(&conf->wait_for_overlap);
3348                 md_done_sync(conf->mddev, STRIPE_SECTORS, 1);
3349         }
3350
3351         if (s.expanding && s.locked == 0 &&
3352             !test_bit(STRIPE_COMPUTE_RUN, &sh->state))
3353                 handle_stripe_expansion(conf, sh);
3354
3355 finish:
3356         /* wait for this device to become unblocked */
3357         if (conf->mddev->external && unlikely(s.blocked_rdev))
3358                 md_wait_for_blocked_rdev(s.blocked_rdev, conf->mddev);
3359
3360         if (s.handle_bad_blocks)
3361                 for (i = disks; i--; ) {
3362                         struct md_rdev *rdev;
3363                         struct r5dev *dev = &sh->dev[i];
3364                         if (test_and_clear_bit(R5_WriteError, &dev->flags)) {
3365                                 /* We own a safe reference to the rdev */
3366                                 rdev = conf->disks[i].rdev;
3367                                 if (!rdev_set_badblocks(rdev, sh->sector,
3368                                                         STRIPE_SECTORS, 0))
3369                                         md_error(conf->mddev, rdev);
3370                                 rdev_dec_pending(rdev, conf->mddev);
3371                         }
3372                         if (test_and_clear_bit(R5_MadeGood, &dev->flags)) {
3373                                 rdev = conf->disks[i].rdev;
3374                                 rdev_clear_badblocks(rdev, sh->sector,
3375                                                      STRIPE_SECTORS);
3376                                 rdev_dec_pending(rdev, conf->mddev);
3377                         }
3378                 }
3379
3380         if (s.ops_request)
3381                 raid_run_ops(sh, s.ops_request);
3382
3383         ops_run_io(sh, &s);
3384
3385         if (s.dec_preread_active) {
3386                 /* We delay this until after ops_run_io so that if make_request
3387                  * is waiting on a flush, it won't continue until the writes
3388                  * have actually been submitted.
3389                  */
3390                 atomic_dec(&conf->preread_active_stripes);
3391                 if (atomic_read(&conf->preread_active_stripes) <
3392                     IO_THRESHOLD)
3393                         md_wakeup_thread(conf->mddev->thread);
3394         }
3395
3396         return_io(s.return_bi);
3397
3398         clear_bit_unlock(STRIPE_ACTIVE, &sh->state);
3399 }
3400
3401 static void raid5_activate_delayed(struct r5conf *conf)
3402 {
3403         if (atomic_read(&conf->preread_active_stripes) < IO_THRESHOLD) {
3404                 while (!list_empty(&conf->delayed_list)) {
3405                         struct list_head *l = conf->delayed_list.next;
3406                         struct stripe_head *sh;
3407                         sh = list_entry(l, struct stripe_head, lru);
3408                         list_del_init(l);
3409                         clear_bit(STRIPE_DELAYED, &sh->state);
3410                         if (!test_and_set_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
3411                                 atomic_inc(&conf->preread_active_stripes);
3412                         list_add_tail(&sh->lru, &conf->hold_list);
3413                 }
3414         }
3415 }
3416
3417 static void activate_bit_delay(struct r5conf *conf)
3418 {
3419         /* device_lock is held */
3420         struct list_head head;
3421         list_add(&head, &conf->bitmap_list);
3422         list_del_init(&conf->bitmap_list);
3423         while (!list_empty(&head)) {
3424                 struct stripe_head *sh = list_entry(head.next, struct stripe_head, lru);
3425                 list_del_init(&sh->lru);
3426                 atomic_inc(&sh->count);
3427                 __release_stripe(conf, sh);
3428         }
3429 }
3430
3431 int md_raid5_congested(struct mddev *mddev, int bits)
3432 {
3433         struct r5conf *conf = mddev->private;
3434
3435         /* No difference between reads and writes.  Just check
3436          * how busy the stripe_cache is
3437          */
3438
3439         if (conf->inactive_blocked)
3440                 return 1;
3441         if (conf->quiesce)
3442                 return 1;
3443         if (list_empty_careful(&conf->inactive_list))
3444                 return 1;
3445
3446         return 0;
3447 }
3448 EXPORT_SYMBOL_GPL(md_raid5_congested);
3449
3450 static int raid5_congested(void *data, int bits)
3451 {
3452         struct mddev *mddev = data;
3453
3454         return mddev_congested(mddev, bits) ||
3455                 md_raid5_congested(mddev, bits);
3456 }
3457
3458 /* We want read requests to align with chunks where possible,
3459  * but write requests don't need to.
3460  */
3461 static int raid5_mergeable_bvec(struct request_queue *q,
3462                                 struct bvec_merge_data *bvm,
3463                                 struct bio_vec *biovec)
3464 {
3465         struct mddev *mddev = q->queuedata;
3466         sector_t sector = bvm->bi_sector + get_start_sect(bvm->bi_bdev);
3467         int max;
3468         unsigned int chunk_sectors = mddev->chunk_sectors;
3469         unsigned int bio_sectors = bvm->bi_size >> 9;
3470
3471         if ((bvm->bi_rw & 1) == WRITE)
3472                 return biovec->bv_len; /* always allow writes to be mergeable */
3473
3474         if (mddev->new_chunk_sectors < mddev->chunk_sectors)
3475                 chunk_sectors = mddev->new_chunk_sectors;
3476         max =  (chunk_sectors - ((sector & (chunk_sectors - 1)) + bio_sectors)) << 9;
3477         if (max < 0) max = 0;
3478         if (max <= biovec->bv_len && bio_sectors == 0)
3479                 return biovec->bv_len;
3480         else
3481                 return max;
3482 }
3483
3484
3485 static int in_chunk_boundary(struct mddev *mddev, struct bio *bio)
3486 {
3487         sector_t sector = bio->bi_sector + get_start_sect(bio->bi_bdev);
3488         unsigned int chunk_sectors = mddev->chunk_sectors;
3489         unsigned int bio_sectors = bio->bi_size >> 9;
3490
3491         if (mddev->new_chunk_sectors < mddev->chunk_sectors)
3492                 chunk_sectors = mddev->new_chunk_sectors;
3493         return  chunk_sectors >=
3494                 ((sector & (chunk_sectors - 1)) + bio_sectors);
3495 }
3496
3497 /*
3498  *  add bio to the retry LIFO  ( in O(1) ... we are in interrupt )
3499  *  later sampled by raid5d.
3500  */
3501 static void add_bio_to_retry(struct bio *bi,struct r5conf *conf)
3502 {
3503         unsigned long flags;
3504
3505         spin_lock_irqsave(&conf->device_lock, flags);
3506
3507         bi->bi_next = conf->retry_read_aligned_list;
3508         conf->retry_read_aligned_list = bi;
3509
3510         spin_unlock_irqrestore(&conf->device_lock, flags);
3511         md_wakeup_thread(conf->mddev->thread);
3512 }
3513
3514
3515 static struct bio *remove_bio_from_retry(struct r5conf *conf)
3516 {
3517         struct bio *bi;
3518
3519         bi = conf->retry_read_aligned;
3520         if (bi) {
3521                 conf->retry_read_aligned = NULL;
3522                 return bi;
3523         }
3524         bi = conf->retry_read_aligned_list;
3525         if(bi) {
3526                 conf->retry_read_aligned_list = bi->bi_next;
3527                 bi->bi_next = NULL;
3528                 /*
3529                  * this sets the active strip count to 1 and the processed
3530                  * strip count to zero (upper 8 bits)
3531                  */
3532                 bi->bi_phys_segments = 1; /* biased count of active stripes */
3533         }
3534
3535         return bi;
3536 }
3537
3538
3539 /*
3540  *  The "raid5_align_endio" should check if the read succeeded and if it
3541  *  did, call bio_endio on the original bio (having bio_put the new bio
3542  *  first).
3543  *  If the read failed..
3544  */
3545 static void raid5_align_endio(struct bio *bi, int error)
3546 {
3547         struct bio* raid_bi  = bi->bi_private;
3548         struct mddev *mddev;
3549         struct r5conf *conf;
3550         int uptodate = test_bit(BIO_UPTODATE, &bi->bi_flags);
3551         struct md_rdev *rdev;
3552
3553         bio_put(bi);
3554
3555         rdev = (void*)raid_bi->bi_next;
3556         raid_bi->bi_next = NULL;
3557         mddev = rdev->mddev;
3558         conf = mddev->private;
3559
3560         rdev_dec_pending(rdev, conf->mddev);
3561
3562         if (!error && uptodate) {
3563                 bio_endio(raid_bi, 0);
3564                 if (atomic_dec_and_test(&conf->active_aligned_reads))
3565                         wake_up(&conf->wait_for_stripe);
3566                 return;
3567         }
3568
3569
3570         pr_debug("raid5_align_endio : io error...handing IO for a retry\n");
3571
3572         add_bio_to_retry(raid_bi, conf);
3573 }
3574
3575 static int bio_fits_rdev(struct bio *bi)
3576 {
3577         struct request_queue *q = bdev_get_queue(bi->bi_bdev);
3578
3579         if ((bi->bi_size>>9) > queue_max_sectors(q))
3580                 return 0;
3581         blk_recount_segments(q, bi);
3582         if (bi->bi_phys_segments > queue_max_segments(q))
3583                 return 0;
3584
3585         if (q->merge_bvec_fn)
3586                 /* it's too hard to apply the merge_bvec_fn at this stage,
3587                  * just just give up
3588                  */
3589                 return 0;
3590
3591         return 1;
3592 }
3593
3594
3595 static int chunk_aligned_read(struct mddev *mddev, struct bio * raid_bio)
3596 {
3597         struct r5conf *conf = mddev->private;
3598         int dd_idx;
3599         struct bio* align_bi;
3600         struct md_rdev *rdev;
3601
3602         if (!in_chunk_boundary(mddev, raid_bio)) {
3603                 pr_debug("chunk_aligned_read : non aligned\n");
3604                 return 0;
3605         }
3606         /*
3607          * use bio_clone_mddev to make a copy of the bio
3608          */
3609         align_bi = bio_clone_mddev(raid_bio, GFP_NOIO, mddev);
3610         if (!align_bi)
3611                 return 0;
3612         /*
3613          *   set bi_end_io to a new function, and set bi_private to the
3614          *     original bio.
3615          */
3616         align_bi->bi_end_io  = raid5_align_endio;
3617         align_bi->bi_private = raid_bio;
3618         /*
3619          *      compute position
3620          */
3621         align_bi->bi_sector =  raid5_compute_sector(conf, raid_bio->bi_sector,
3622                                                     0,
3623                                                     &dd_idx, NULL);
3624
3625         rcu_read_lock();
3626         rdev = rcu_dereference(conf->disks[dd_idx].rdev);
3627         if (rdev && test_bit(In_sync, &rdev->flags)) {
3628                 sector_t first_bad;
3629                 int bad_sectors;
3630
3631                 atomic_inc(&rdev->nr_pending);
3632                 rcu_read_unlock();
3633                 raid_bio->bi_next = (void*)rdev;
3634                 align_bi->bi_bdev =  rdev->bdev;
3635                 align_bi->bi_flags &= ~(1 << BIO_SEG_VALID);
3636
3637                 if (!bio_fits_rdev(align_bi) ||
3638                     is_badblock(rdev, align_bi->bi_sector, align_bi->bi_size>>9,
3639                                 &first_bad, &bad_sectors)) {
3640                         /* too big in some way, or has a known bad block */
3641                         bio_put(align_bi);
3642                         rdev_dec_pending(rdev, mddev);
3643                         return 0;
3644                 }
3645
3646                 /* No reshape active, so we can trust rdev->data_offset */
3647                 align_bi->bi_sector += rdev->data_offset;
3648
3649                 spin_lock_irq(&conf->device_lock);
3650                 wait_event_lock_irq(conf->wait_for_stripe,
3651                                     conf->quiesce == 0,
3652                                     conf->device_lock, /* nothing */);
3653                 atomic_inc(&conf->active_aligned_reads);
3654                 spin_unlock_irq(&conf->device_lock);
3655
3656                 generic_make_request(align_bi);
3657                 return 1;
3658         } else {
3659                 rcu_read_unlock();
3660                 bio_put(align_bi);
3661                 return 0;
3662         }
3663 }
3664
3665 /* __get_priority_stripe - get the next stripe to process
3666  *
3667  * Full stripe writes are allowed to pass preread active stripes up until
3668  * the bypass_threshold is exceeded.  In general the bypass_count
3669  * increments when the handle_list is handled before the hold_list; however, it
3670  * will not be incremented when STRIPE_IO_STARTED is sampled set signifying a
3671  * stripe with in flight i/o.  The bypass_count will be reset when the
3672  * head of the hold_list has changed, i.e. the head was promoted to the
3673  * handle_list.
3674  */
3675 static struct stripe_head *__get_priority_stripe(struct r5conf *conf)
3676 {
3677         struct stripe_head *sh;
3678
3679         pr_debug("%s: handle: %s hold: %s full_writes: %d bypass_count: %d\n",
3680                   __func__,
3681                   list_empty(&conf->handle_list) ? "empty" : "busy",
3682                   list_empty(&conf->hold_list) ? "empty" : "busy",
3683                   atomic_read(&conf->pending_full_writes), conf->bypass_count);
3684
3685         if (!list_empty(&conf->handle_list)) {
3686                 sh = list_entry(conf->handle_list.next, typeof(*sh), lru);
3687
3688                 if (list_empty(&conf->hold_list))
3689                         conf->bypass_count = 0;
3690                 else if (!test_bit(STRIPE_IO_STARTED, &sh->state)) {
3691                         if (conf->hold_list.next == conf->last_hold)
3692                                 conf->bypass_count++;
3693                         else {
3694                                 conf->last_hold = conf->hold_list.next;
3695                                 conf->bypass_count -= conf->bypass_threshold;
3696                                 if (conf->bypass_count < 0)
3697                                         conf->bypass_count = 0;
3698                         }
3699                 }
3700         } else if (!list_empty(&conf->hold_list) &&
3701                    ((conf->bypass_threshold &&
3702                      conf->bypass_count > conf->bypass_threshold) ||
3703                     atomic_read(&conf->pending_full_writes) == 0)) {
3704                 sh = list_entry(conf->hold_list.next,
3705                                 typeof(*sh), lru);
3706                 conf->bypass_count -= conf->bypass_threshold;
3707                 if (conf->bypass_count < 0)
3708                         conf->bypass_count = 0;
3709         } else
3710                 return NULL;
3711
3712         list_del_init(&sh->lru);
3713         atomic_inc(&sh->count);
3714         BUG_ON(atomic_read(&sh->count) != 1);
3715         return sh;
3716 }
3717
3718 static void make_request(struct mddev *mddev, struct bio * bi)
3719 {
3720         struct r5conf *conf = mddev->private;
3721         int dd_idx;
3722         sector_t new_sector;
3723         sector_t logical_sector, last_sector;
3724         struct stripe_head *sh;
3725         const int rw = bio_data_dir(bi);
3726         int remaining;
3727         int plugged;
3728
3729         if (unlikely(bi->bi_rw & REQ_FLUSH)) {
3730                 md_flush_request(mddev, bi);
3731                 return;
3732         }
3733
3734         md_write_start(mddev, bi);
3735
3736         if (rw == READ &&
3737              mddev->reshape_position == MaxSector &&
3738              chunk_aligned_read(mddev,bi))
3739                 return;
3740
3741         logical_sector = bi->bi_sector & ~((sector_t)STRIPE_SECTORS-1);
3742         last_sector = bi->bi_sector + (bi->bi_size>>9);
3743         bi->bi_next = NULL;
3744         bi->bi_phys_segments = 1;       /* over-loaded to count active stripes */
3745
3746         plugged = mddev_check_plugged(mddev);
3747         for (;logical_sector < last_sector; logical_sector += STRIPE_SECTORS) {
3748                 DEFINE_WAIT(w);
3749                 int disks, data_disks;
3750                 int previous;
3751
3752         retry:
3753                 previous = 0;
3754                 disks = conf->raid_disks;
3755                 prepare_to_wait(&conf->wait_for_overlap, &w, TASK_UNINTERRUPTIBLE);
3756                 if (unlikely(conf->reshape_progress != MaxSector)) {
3757                         /* spinlock is needed as reshape_progress may be
3758                          * 64bit on a 32bit platform, and so it might be
3759                          * possible to see a half-updated value
3760                          * Of course reshape_progress could change after
3761                          * the lock is dropped, so once we get a reference
3762                          * to the stripe that we think it is, we will have
3763                          * to check again.
3764                          */
3765                         spin_lock_irq(&conf->device_lock);
3766                         if (mddev->delta_disks < 0
3767                             ? logical_sector < conf->reshape_progress
3768                             : logical_sector >= conf->reshape_progress) {
3769                                 disks = conf->previous_raid_disks;
3770                                 previous = 1;
3771                         } else {
3772                                 if (mddev->delta_disks < 0
3773                                     ? logical_sector < conf->reshape_safe
3774                                     : logical_sector >= conf->reshape_safe) {
3775                                         spin_unlock_irq(&conf->device_lock);
3776                                         schedule();
3777                                         goto retry;
3778                                 }
3779                         }
3780                         spin_unlock_irq(&conf->device_lock);
3781                 }
3782                 data_disks = disks - conf->max_degraded;
3783
3784                 new_sector = raid5_compute_sector(conf, logical_sector,
3785                                                   previous,
3786                                                   &dd_idx, NULL);
3787                 pr_debug("raid456: make_request, sector %llu logical %llu\n",
3788                         (unsigned long long)new_sector, 
3789                         (unsigned long long)logical_sector);
3790
3791                 sh = get_active_stripe(conf, new_sector, previous,
3792                                        (bi->bi_rw&RWA_MASK), 0);
3793                 if (sh) {
3794                         if (unlikely(previous)) {
3795                                 /* expansion might have moved on while waiting for a
3796                                  * stripe, so we must do the range check again.
3797                                  * Expansion could still move past after this
3798                                  * test, but as we are holding a reference to
3799                                  * 'sh', we know that if that happens,
3800                                  *  STRIPE_EXPANDING will get set and the expansion
3801                                  * won't proceed until we finish with the stripe.
3802                                  */
3803                                 int must_retry = 0;
3804                                 spin_lock_irq(&conf->device_lock);
3805                                 if (mddev->delta_disks < 0
3806                                     ? logical_sector >= conf->reshape_progress
3807                                     : logical_sector < conf->reshape_progress)
3808                                         /* mismatch, need to try again */
3809                                         must_retry = 1;
3810                                 spin_unlock_irq(&conf->device_lock);
3811                                 if (must_retry) {
3812                                         release_stripe(sh);
3813                                         schedule();
3814                                         goto retry;
3815                                 }
3816                         }
3817
3818                         if (rw == WRITE &&
3819                             logical_sector >= mddev->suspend_lo &&
3820                             logical_sector < mddev->suspend_hi) {
3821                                 release_stripe(sh);
3822                                 /* As the suspend_* range is controlled by
3823                                  * userspace, we want an interruptible
3824                                  * wait.
3825                                  */
3826                                 flush_signals(current);
3827                                 prepare_to_wait(&conf->wait_for_overlap,
3828                                                 &w, TASK_INTERRUPTIBLE);
3829                                 if (logical_sector >= mddev->suspend_lo &&
3830                                     logical_sector < mddev->suspend_hi)
3831                                         schedule();
3832                                 goto retry;
3833                         }
3834
3835                         if (test_bit(STRIPE_EXPANDING, &sh->state) ||
3836                             !add_stripe_bio(sh, bi, dd_idx, rw)) {
3837                                 /* Stripe is busy expanding or
3838                                  * add failed due to overlap.  Flush everything
3839                                  * and wait a while
3840                                  */
3841                                 md_wakeup_thread(mddev->thread);
3842                                 release_stripe(sh);
3843                                 schedule();
3844                                 goto retry;
3845                         }
3846                         finish_wait(&conf->wait_for_overlap, &w);
3847                         set_bit(STRIPE_HANDLE, &sh->state);
3848                         clear_bit(STRIPE_DELAYED, &sh->state);
3849                         if ((bi->bi_rw & REQ_SYNC) &&
3850                             !test_and_set_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
3851                                 atomic_inc(&conf->preread_active_stripes);
3852                         release_stripe(sh);
3853                 } else {
3854                         /* cannot get stripe for read-ahead, just give-up */
3855                         clear_bit(BIO_UPTODATE, &bi->bi_flags);
3856                         finish_wait(&conf->wait_for_overlap, &w);
3857                         break;
3858                 }
3859                         
3860         }
3861         if (!plugged)
3862                 md_wakeup_thread(mddev->thread);
3863
3864         spin_lock_irq(&conf->device_lock);
3865         remaining = raid5_dec_bi_phys_segments(bi);
3866         spin_unlock_irq(&conf->device_lock);
3867         if (remaining == 0) {
3868
3869                 if ( rw == WRITE )
3870                         md_write_end(mddev);
3871
3872                 bio_endio(bi, 0);
3873         }
3874 }
3875
3876 static sector_t raid5_size(struct mddev *mddev, sector_t sectors, int raid_disks);
3877
3878 static sector_t reshape_request(struct mddev *mddev, sector_t sector_nr, int *skipped)
3879 {
3880         /* reshaping is quite different to recovery/resync so it is
3881          * handled quite separately ... here.
3882          *
3883          * On each call to sync_request, we gather one chunk worth of
3884          * destination stripes and flag them as expanding.
3885          * Then we find all the source stripes and request reads.
3886          * As the reads complete, handle_stripe will copy the data
3887          * into the destination stripe and release that stripe.
3888          */
3889         struct r5conf *conf = mddev->private;
3890         struct stripe_head *sh;
3891         sector_t first_sector, last_sector;
3892         int raid_disks = conf->previous_raid_disks;
3893         int data_disks = raid_disks - conf->max_degraded;
3894         int new_data_disks = conf->raid_disks - conf->max_degraded;
3895         int i;
3896         int dd_idx;
3897         sector_t writepos, readpos, safepos;
3898         sector_t stripe_addr;
3899         int reshape_sectors;
3900         struct list_head stripes;
3901
3902         if (sector_nr == 0) {
3903                 /* If restarting in the middle, skip the initial sectors */
3904                 if (mddev->delta_disks < 0 &&
3905                     conf->reshape_progress < raid5_size(mddev, 0, 0)) {
3906                         sector_nr = raid5_size(mddev, 0, 0)
3907                                 - conf->reshape_progress;
3908                 } else if (mddev->delta_disks >= 0 &&
3909                            conf->reshape_progress > 0)
3910                         sector_nr = conf->reshape_progress;
3911                 sector_div(sector_nr, new_data_disks);
3912                 if (sector_nr) {
3913                         mddev->curr_resync_completed = sector_nr;
3914                         sysfs_notify(&mddev->kobj, NULL, "sync_completed");
3915                         *skipped = 1;
3916                         return sector_nr;
3917                 }
3918         }
3919
3920         /* We need to process a full chunk at a time.
3921          * If old and new chunk sizes differ, we need to process the
3922          * largest of these
3923          */
3924         if (mddev->new_chunk_sectors > mddev->chunk_sectors)
3925                 reshape_sectors = mddev->new_chunk_sectors;
3926         else
3927                 reshape_sectors = mddev->chunk_sectors;
3928
3929         /* we update the metadata when there is more than 3Meg
3930          * in the block range (that is rather arbitrary, should
3931          * probably be time based) or when the data about to be
3932          * copied would over-write the source of the data at
3933          * the front of the range.
3934          * i.e. one new_stripe along from reshape_progress new_maps
3935          * to after where reshape_safe old_maps to
3936          */
3937         writepos = conf->reshape_progress;
3938         sector_div(writepos, new_data_disks);
3939         readpos = conf->reshape_progress;
3940         sector_div(readpos, data_disks);
3941         safepos = conf->reshape_safe;
3942         sector_div(safepos, data_disks);
3943         if (mddev->delta_disks < 0) {
3944                 writepos -= min_t(sector_t, reshape_sectors, writepos);
3945                 readpos += reshape_sectors;
3946                 safepos += reshape_sectors;
3947         } else {
3948                 writepos += reshape_sectors;
3949                 readpos -= min_t(sector_t, reshape_sectors, readpos);
3950                 safepos -= min_t(sector_t, reshape_sectors, safepos);
3951         }
3952
3953         /* 'writepos' is the most advanced device address we might write.
3954          * 'readpos' is the least advanced device address we might read.
3955          * 'safepos' is the least address recorded in the metadata as having
3956          *     been reshaped.
3957          * If 'readpos' is behind 'writepos', then there is no way that we can
3958          * ensure safety in the face of a crash - that must be done by userspace
3959          * making a backup of the data.  So in that case there is no particular
3960          * rush to update metadata.
3961          * Otherwise if 'safepos' is behind 'writepos', then we really need to
3962          * update the metadata to advance 'safepos' to match 'readpos' so that
3963          * we can be safe in the event of a crash.
3964          * So we insist on updating metadata if safepos is behind writepos and
3965          * readpos is beyond writepos.
3966          * In any case, update the metadata every 10 seconds.
3967          * Maybe that number should be configurable, but I'm not sure it is
3968          * worth it.... maybe it could be a multiple of safemode_delay???
3969          */
3970         if ((mddev->delta_disks < 0
3971              ? (safepos > writepos && readpos < writepos)
3972              : (safepos < writepos && readpos > writepos)) ||
3973             time_after(jiffies, conf->reshape_checkpoint + 10*HZ)) {
3974                 /* Cannot proceed until we've updated the superblock... */
3975                 wait_event(conf->wait_for_overlap,
3976                            atomic_read(&conf->reshape_stripes)==0);
3977                 mddev->reshape_position = conf->reshape_progress;
3978                 mddev->curr_resync_completed = sector_nr;
3979                 conf->reshape_checkpoint = jiffies;
3980                 set_bit(MD_CHANGE_DEVS, &mddev->flags);
3981                 md_wakeup_thread(mddev->thread);
3982                 wait_event(mddev->sb_wait, mddev->flags == 0 ||
3983                            kthread_should_stop());
3984                 spin_lock_irq(&conf->device_lock);
3985                 conf->reshape_safe = mddev->reshape_position;
3986                 spin_unlock_irq(&conf->device_lock);
3987                 wake_up(&conf->wait_for_overlap);
3988                 sysfs_notify(&mddev->kobj, NULL, "sync_completed");
3989         }
3990
3991         if (mddev->delta_disks < 0) {
3992                 BUG_ON(conf->reshape_progress == 0);
3993                 stripe_addr = writepos;
3994                 BUG_ON((mddev->dev_sectors &
3995                         ~((sector_t)reshape_sectors - 1))
3996                        - reshape_sectors - stripe_addr
3997                        != sector_nr);
3998         } else {
3999                 BUG_ON(writepos != sector_nr + reshape_sectors);
4000                 stripe_addr = sector_nr;
4001         }
4002         INIT_LIST_HEAD(&stripes);
4003         for (i = 0; i < reshape_sectors; i += STRIPE_SECTORS) {
4004                 int j;
4005                 int skipped_disk = 0;
4006                 sh = get_active_stripe(conf, stripe_addr+i, 0, 0, 1);
4007                 set_bit(STRIPE_EXPANDING, &sh->state);
4008                 atomic_inc(&conf->reshape_stripes);
4009                 /* If any of this stripe is beyond the end of the old
4010                  * array, then we need to zero those blocks
4011                  */
4012                 for (j=sh->disks; j--;) {
4013                         sector_t s;
4014                         if (j == sh->pd_idx)
4015                                 continue;
4016                         if (conf->level == 6 &&
4017                             j == sh->qd_idx)
4018                                 continue;
4019                         s = compute_blocknr(sh, j, 0);
4020                         if (s < raid5_size(mddev, 0, 0)) {
4021                                 skipped_disk = 1;
4022                                 continue;
4023                         }
4024                         memset(page_address(sh->dev[j].page), 0, STRIPE_SIZE);
4025                         set_bit(R5_Expanded, &sh->dev[j].flags);
4026                         set_bit(R5_UPTODATE, &sh->dev[j].flags);
4027                 }
4028                 if (!skipped_disk) {
4029                         set_bit(STRIPE_EXPAND_READY, &sh->state);
4030                         set_bit(STRIPE_HANDLE, &sh->state);
4031                 }
4032                 list_add(&sh->lru, &stripes);
4033         }
4034         spin_lock_irq(&conf->device_lock);
4035         if (mddev->delta_disks < 0)
4036                 conf->reshape_progress -= reshape_sectors * new_data_disks;
4037         else
4038                 conf->reshape_progress += reshape_sectors * new_data_disks;
4039         spin_unlock_irq(&conf->device_lock);
4040         /* Ok, those stripe are ready. We can start scheduling
4041          * reads on the source stripes.
4042          * The source stripes are determined by mapping the first and last
4043          * block on the destination stripes.
4044          */
4045         first_sector =
4046                 raid5_compute_sector(conf, stripe_addr*(new_data_disks),
4047                                      1, &dd_idx, NULL);
4048         last_sector =
4049                 raid5_compute_sector(conf, ((stripe_addr+reshape_sectors)
4050                                             * new_data_disks - 1),
4051                                      1, &dd_idx, NULL);
4052         if (last_sector >= mddev->dev_sectors)
4053                 last_sector = mddev->dev_sectors - 1;
4054         while (first_sector <= last_sector) {
4055                 sh = get_active_stripe(conf, first_sector, 1, 0, 1);
4056                 set_bit(STRIPE_EXPAND_SOURCE, &sh->state);
4057                 set_bit(STRIPE_HANDLE, &sh->state);
4058                 release_stripe(sh);
4059                 first_sector += STRIPE_SECTORS;
4060         }
4061         /* Now that the sources are clearly marked, we can release
4062          * the destination stripes
4063          */
4064         while (!list_empty(&stripes)) {
4065                 sh = list_entry(stripes.next, struct stripe_head, lru);
4066                 list_del_init(&sh->lru);
4067                 release_stripe(sh);
4068         }
4069         /* If this takes us to the resync_max point where we have to pause,
4070          * then we need to write out the superblock.
4071          */
4072         sector_nr += reshape_sectors;
4073         if ((sector_nr - mddev->curr_resync_completed) * 2
4074             >= mddev->resync_max - mddev->curr_resync_completed) {
4075                 /* Cannot proceed until we've updated the superblock... */
4076                 wait_event(conf->wait_for_overlap,
4077                            atomic_read(&conf->reshape_stripes) == 0);
4078                 mddev->reshape_position = conf->reshape_progress;
4079                 mddev->curr_resync_completed = sector_nr;
4080                 conf->reshape_checkpoint = jiffies;
4081                 set_bit(MD_CHANGE_DEVS, &mddev->flags);
4082                 md_wakeup_thread(mddev->thread);
4083                 wait_event(mddev->sb_wait,
4084                            !test_bit(MD_CHANGE_DEVS, &mddev->flags)
4085                            || kthread_should_stop());
4086                 spin_lock_irq(&conf->device_lock);
4087                 conf->reshape_safe = mddev->reshape_position;
4088                 spin_unlock_irq(&conf->device_lock);
4089                 wake_up(&conf->wait_for_overlap);
4090                 sysfs_notify(&mddev->kobj, NULL, "sync_completed");
4091         }
4092         return reshape_sectors;
4093 }
4094
4095 /* FIXME go_faster isn't used */
4096 static inline sector_t sync_request(struct mddev *mddev, sector_t sector_nr, int *skipped, int go_faster)
4097 {
4098         struct r5conf *conf = mddev->private;
4099         struct stripe_head *sh;
4100         sector_t max_sector = mddev->dev_sectors;
4101         sector_t sync_blocks;
4102         int still_degraded = 0;
4103         int i;
4104
4105         if (sector_nr >= max_sector) {
4106                 /* just being told to finish up .. nothing much to do */
4107
4108                 if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery)) {
4109                         end_reshape(conf);
4110                         return 0;
4111                 }
4112
4113                 if (mddev->curr_resync < max_sector) /* aborted */
4114                         bitmap_end_sync(mddev->bitmap, mddev->curr_resync,
4115                                         &sync_blocks, 1);
4116                 else /* completed sync */
4117                         conf->fullsync = 0;
4118                 bitmap_close_sync(mddev->bitmap);
4119
4120                 return 0;
4121         }
4122
4123         /* Allow raid5_quiesce to complete */
4124         wait_event(conf->wait_for_overlap, conf->quiesce != 2);
4125
4126         if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery))
4127                 return reshape_request(mddev, sector_nr, skipped);
4128
4129         /* No need to check resync_max as we never do more than one
4130          * stripe, and as resync_max will always be on a chunk boundary,
4131          * if the check in md_do_sync didn't fire, there is no chance
4132          * of overstepping resync_max here
4133          */
4134
4135         /* if there is too many failed drives and we are trying
4136          * to resync, then assert that we are finished, because there is
4137          * nothing we can do.
4138          */
4139         if (mddev->degraded >= conf->max_degraded &&
4140             test_bit(MD_RECOVERY_SYNC, &mddev->recovery)) {
4141                 sector_t rv = mddev->dev_sectors - sector_nr;
4142                 *skipped = 1;
4143                 return rv;
4144         }
4145         if (!bitmap_start_sync(mddev->bitmap, sector_nr, &sync_blocks, 1) &&
4146             !test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery) &&
4147             !conf->fullsync && sync_blocks >= STRIPE_SECTORS) {
4148                 /* we can skip this block, and probably more */
4149                 sync_blocks /= STRIPE_SECTORS;
4150                 *skipped = 1;
4151                 return sync_blocks * STRIPE_SECTORS; /* keep things rounded to whole stripes */
4152         }
4153
4154
4155         bitmap_cond_end_sync(mddev->bitmap, sector_nr);
4156
4157         sh = get_active_stripe(conf, sector_nr, 0, 1, 0);
4158         if (sh == NULL) {
4159                 sh = get_active_stripe(conf, sector_nr, 0, 0, 0);
4160                 /* make sure we don't swamp the stripe cache if someone else
4161                  * is trying to get access
4162                  */
4163                 schedule_timeout_uninterruptible(1);
4164         }
4165         /* Need to check if array will still be degraded after recovery/resync
4166          * We don't need to check the 'failed' flag as when that gets set,
4167          * recovery aborts.
4168          */
4169         for (i = 0; i < conf->raid_disks; i++)
4170                 if (conf->disks[i].rdev == NULL)
4171                         still_degraded = 1;
4172
4173         bitmap_start_sync(mddev->bitmap, sector_nr, &sync_blocks, still_degraded);
4174
4175         set_bit(STRIPE_SYNC_REQUESTED, &sh->state);
4176
4177         handle_stripe(sh);
4178         release_stripe(sh);
4179
4180         return STRIPE_SECTORS;
4181 }
4182
4183 static int  retry_aligned_read(struct r5conf *conf, struct bio *raid_bio)
4184 {
4185         /* We may not be able to submit a whole bio at once as there
4186          * may not be enough stripe_heads available.
4187          * We cannot pre-allocate enough stripe_heads as we may need
4188          * more than exist in the cache (if we allow ever large chunks).
4189          * So we do one stripe head at a time and record in
4190          * ->bi_hw_segments how many have been done.
4191          *
4192          * We *know* that this entire raid_bio is in one chunk, so
4193          * it will be only one 'dd_idx' and only need one call to raid5_compute_sector.
4194          */
4195         struct stripe_head *sh;
4196         int dd_idx;
4197         sector_t sector, logical_sector, last_sector;
4198         int scnt = 0;
4199         int remaining;
4200         int handled = 0;
4201
4202         logical_sector = raid_bio->bi_sector & ~((sector_t)STRIPE_SECTORS-1);
4203         sector = raid5_compute_sector(conf, logical_sector,
4204                                       0, &dd_idx, NULL);
4205         last_sector = raid_bio->bi_sector + (raid_bio->bi_size>>9);
4206
4207         for (; logical_sector < last_sector;
4208              logical_sector += STRIPE_SECTORS,
4209                      sector += STRIPE_SECTORS,
4210                      scnt++) {
4211
4212                 if (scnt < raid5_bi_hw_segments(raid_bio))
4213                         /* already done this stripe */
4214                         continue;
4215
4216                 sh = get_active_stripe(conf, sector, 0, 1, 0);
4217
4218                 if (!sh) {
4219                         /* failed to get a stripe - must wait */
4220                         raid5_set_bi_hw_segments(raid_bio, scnt);
4221                         conf->retry_read_aligned = raid_bio;
4222                         return handled;
4223                 }
4224
4225                 set_bit(R5_ReadError, &sh->dev[dd_idx].flags);
4226                 if (!add_stripe_bio(sh, raid_bio, dd_idx, 0)) {
4227                         release_stripe(sh);
4228                         raid5_set_bi_hw_segments(raid_bio, scnt);
4229                         conf->retry_read_aligned = raid_bio;
4230                         return handled;
4231                 }
4232
4233                 handle_stripe(sh);
4234                 release_stripe(sh);
4235                 handled++;
4236         }
4237         spin_lock_irq(&conf->device_lock);
4238         remaining = raid5_dec_bi_phys_segments(raid_bio);
4239         spin_unlock_irq(&conf->device_lock);
4240         if (remaining == 0)
4241                 bio_endio(raid_bio, 0);
4242         if (atomic_dec_and_test(&conf->active_aligned_reads))
4243                 wake_up(&conf->wait_for_stripe);
4244         return handled;
4245 }
4246
4247
4248 /*
4249  * This is our raid5 kernel thread.
4250  *
4251  * We scan the hash table for stripes which can be handled now.
4252  * During the scan, completed stripes are saved for us by the interrupt
4253  * handler, so that they will not have to wait for our next wakeup.
4254  */
4255 static void raid5d(struct mddev *mddev)
4256 {
4257         struct stripe_head *sh;
4258         struct r5conf *conf = mddev->private;
4259         int handled;
4260         struct blk_plug plug;
4261
4262         pr_debug("+++ raid5d active\n");
4263
4264         md_check_recovery(mddev);
4265
4266         blk_start_plug(&plug);
4267         handled = 0;
4268         spin_lock_irq(&conf->device_lock);
4269         while (1) {
4270                 struct bio *bio;
4271
4272                 if (atomic_read(&mddev->plug_cnt) == 0 &&
4273                     !list_empty(&conf->bitmap_list)) {
4274                         /* Now is a good time to flush some bitmap updates */
4275                         conf->seq_flush++;
4276                         spin_unlock_irq(&conf->device_lock);
4277                         bitmap_unplug(mddev->bitmap);
4278                         spin_lock_irq(&conf->device_lock);
4279                         conf->seq_write = conf->seq_flush;
4280                         activate_bit_delay(conf);
4281                 }
4282                 if (atomic_read(&mddev->plug_cnt) == 0)
4283                         raid5_activate_delayed(conf);
4284
4285                 while ((bio = remove_bio_from_retry(conf))) {
4286                         int ok;
4287                         spin_unlock_irq(&conf->device_lock);
4288                         ok = retry_aligned_read(conf, bio);
4289                         spin_lock_irq(&conf->device_lock);
4290                         if (!ok)
4291                                 break;
4292                         handled++;
4293                 }
4294
4295                 sh = __get_priority_stripe(conf);
4296
4297                 if (!sh)
4298                         break;
4299                 spin_unlock_irq(&conf->device_lock);
4300                 
4301                 handled++;
4302                 handle_stripe(sh);
4303                 release_stripe(sh);
4304                 cond_resched();
4305
4306                 if (mddev->flags & ~(1<<MD_CHANGE_PENDING))
4307                         md_check_recovery(mddev);
4308
4309                 spin_lock_irq(&conf->device_lock);
4310         }
4311         pr_debug("%d stripes handled\n", handled);
4312
4313         spin_unlock_irq(&conf->device_lock);
4314
4315         async_tx_issue_pending_all();
4316         blk_finish_plug(&plug);
4317
4318         pr_debug("--- raid5d inactive\n");
4319 }
4320
4321 static ssize_t
4322 raid5_show_stripe_cache_size(struct mddev *mddev, char *page)
4323 {
4324         struct r5conf *conf = mddev->private;
4325         if (conf)
4326                 return sprintf(page, "%d\n", conf->max_nr_stripes);
4327         else
4328                 return 0;
4329 }
4330
4331 int
4332 raid5_set_cache_size(struct mddev *mddev, int size)
4333 {
4334         struct r5conf *conf = mddev->private;
4335         int err;
4336
4337         if (size <= 16 || size > 32768)
4338                 return -EINVAL;
4339         while (size < conf->max_nr_stripes) {
4340                 if (drop_one_stripe(conf))
4341                         conf->max_nr_stripes--;
4342                 else
4343                         break;
4344         }
4345         err = md_allow_write(mddev);
4346         if (err)
4347                 return err;
4348         while (size > conf->max_nr_stripes) {
4349                 if (grow_one_stripe(conf))
4350                         conf->max_nr_stripes++;
4351                 else break;
4352         }
4353         return 0;
4354 }
4355 EXPORT_SYMBOL(raid5_set_cache_size);
4356
4357 static ssize_t
4358 raid5_store_stripe_cache_size(struct mddev *mddev, const char *page, size_t len)
4359 {
4360         struct r5conf *conf = mddev->private;
4361         unsigned long new;
4362         int err;
4363
4364         if (len >= PAGE_SIZE)
4365                 return -EINVAL;
4366         if (!conf)
4367                 return -ENODEV;
4368
4369         if (strict_strtoul(page, 10, &new))
4370                 return -EINVAL;
4371         err = raid5_set_cache_size(mddev, new);
4372         if (err)
4373                 return err;
4374         return len;
4375 }
4376
4377 static struct md_sysfs_entry
4378 raid5_stripecache_size = __ATTR(stripe_cache_size, S_IRUGO | S_IWUSR,
4379                                 raid5_show_stripe_cache_size,
4380                                 raid5_store_stripe_cache_size);
4381
4382 static ssize_t
4383 raid5_show_preread_threshold(struct mddev *mddev, char *page)
4384 {
4385         struct r5conf *conf = mddev->private;
4386         if (conf)
4387                 return sprintf(page, "%d\n", conf->bypass_threshold);
4388         else
4389                 return 0;
4390 }
4391
4392 static ssize_t
4393 raid5_store_preread_threshold(struct mddev *mddev, const char *page, size_t len)
4394 {
4395         struct r5conf *conf = mddev->private;
4396         unsigned long new;
4397         if (len >= PAGE_SIZE)
4398                 return -EINVAL;
4399         if (!conf)
4400                 return -ENODEV;
4401
4402         if (strict_strtoul(page, 10, &new))
4403                 return -EINVAL;
4404         if (new > conf->max_nr_stripes)
4405                 return -EINVAL;
4406         conf->bypass_threshold = new;
4407         return len;
4408 }
4409
4410 static struct md_sysfs_entry
4411 raid5_preread_bypass_threshold = __ATTR(preread_bypass_threshold,
4412                                         S_IRUGO | S_IWUSR,
4413                                         raid5_show_preread_threshold,
4414                                         raid5_store_preread_threshold);
4415
4416 static ssize_t
4417 stripe_cache_active_show(struct mddev *mddev, char *page)
4418 {
4419         struct r5conf *conf = mddev->private;
4420         if (conf)
4421                 return sprintf(page, "%d\n", atomic_read(&conf->active_stripes));
4422         else
4423                 return 0;
4424 }
4425
4426 static struct md_sysfs_entry
4427 raid5_stripecache_active = __ATTR_RO(stripe_cache_active);
4428
4429 static struct attribute *raid5_attrs[] =  {
4430         &raid5_stripecache_size.attr,
4431         &raid5_stripecache_active.attr,
4432         &raid5_preread_bypass_threshold.attr,
4433         NULL,
4434 };
4435 static struct attribute_group raid5_attrs_group = {
4436         .name = NULL,
4437         .attrs = raid5_attrs,
4438 };
4439
4440 static sector_t
4441 raid5_size(struct mddev *mddev, sector_t sectors, int raid_disks)
4442 {
4443         struct r5conf *conf = mddev->private;
4444
4445         if (!sectors)
4446                 sectors = mddev->dev_sectors;
4447         if (!raid_disks)
4448                 /* size is defined by the smallest of previous and new size */
4449                 raid_disks = min(conf->raid_disks, conf->previous_raid_disks);
4450
4451         sectors &= ~((sector_t)mddev->chunk_sectors - 1);
4452         sectors &= ~((sector_t)mddev->new_chunk_sectors - 1);
4453         return sectors * (raid_disks - conf->max_degraded);
4454 }
4455
4456 static void free_scratch_buffer(struct r5conf *conf, struct raid5_percpu *percpu)
4457 {
4458         safe_put_page(percpu->spare_page);
4459         kfree(percpu->scribble);
4460         percpu->spare_page = NULL;
4461         percpu->scribble = NULL;
4462 }
4463
4464 static int alloc_scratch_buffer(struct r5conf *conf, struct raid5_percpu *percpu)
4465 {
4466         if (conf->level == 6 && !percpu->spare_page)
4467                 percpu->spare_page = alloc_page(GFP_KERNEL);
4468         if (!percpu->scribble)
4469                 percpu->scribble = kmalloc(conf->scribble_len, GFP_KERNEL);
4470
4471         if (!percpu->scribble || (conf->level == 6 && !percpu->spare_page)) {
4472                 free_scratch_buffer(conf, percpu);
4473                 return -ENOMEM;
4474         }
4475
4476         return 0;
4477 }
4478
4479 static void raid5_free_percpu(struct r5conf *conf)
4480 {
4481         unsigned long cpu;
4482
4483         if (!conf->percpu)
4484                 return;
4485
4486 #ifdef CONFIG_HOTPLUG_CPU
4487         unregister_cpu_notifier(&conf->cpu_notify);
4488 #endif
4489
4490         get_online_cpus();
4491         for_each_possible_cpu(cpu)
4492                 free_scratch_buffer(conf, per_cpu_ptr(conf->percpu, cpu));
4493         put_online_cpus();
4494
4495         free_percpu(conf->percpu);
4496 }
4497
4498 static void free_conf(struct r5conf *conf)
4499 {
4500         shrink_stripes(conf);
4501         raid5_free_percpu(conf);
4502         kfree(conf->disks);
4503         kfree(conf->stripe_hashtbl);
4504         kfree(conf);
4505 }
4506
4507 #ifdef CONFIG_HOTPLUG_CPU
4508 static int raid456_cpu_notify(struct notifier_block *nfb, unsigned long action,
4509                               void *hcpu)
4510 {
4511         struct r5conf *conf = container_of(nfb, struct r5conf, cpu_notify);
4512         long cpu = (long)hcpu;
4513         struct raid5_percpu *percpu = per_cpu_ptr(conf->percpu, cpu);
4514
4515         switch (action) {
4516         case CPU_UP_PREPARE:
4517         case CPU_UP_PREPARE_FROZEN:
4518                 if (alloc_scratch_buffer(conf, percpu)) {
4519                         pr_err("%s: failed memory allocation for cpu%ld\n",
4520                                __func__, cpu);
4521                         return notifier_from_errno(-ENOMEM);
4522                 }
4523                 break;
4524         case CPU_DEAD:
4525         case CPU_DEAD_FROZEN:
4526                 free_scratch_buffer(conf, per_cpu_ptr(conf->percpu, cpu));
4527                 break;
4528         default:
4529                 break;
4530         }
4531         return NOTIFY_OK;
4532 }
4533 #endif
4534
4535 static int raid5_alloc_percpu(struct r5conf *conf)
4536 {
4537         unsigned long cpu;
4538         int err = 0;
4539
4540         conf->percpu = alloc_percpu(struct raid5_percpu);
4541         if (!conf->percpu)
4542                 return -ENOMEM;
4543
4544 #ifdef CONFIG_HOTPLUG_CPU
4545         conf->cpu_notify.notifier_call = raid456_cpu_notify;
4546         conf->cpu_notify.priority = 0;
4547         err = register_cpu_notifier(&conf->cpu_notify);
4548         if (err)
4549                 return err;
4550 #endif
4551
4552         get_online_cpus();
4553         for_each_present_cpu(cpu) {
4554                 err = alloc_scratch_buffer(conf, per_cpu_ptr(conf->percpu, cpu));
4555                 if (err) {
4556                         pr_err("%s: failed memory allocation for cpu%ld\n",
4557                                __func__, cpu);
4558                         break;
4559                 }
4560         }
4561         put_online_cpus();
4562
4563         return err;
4564 }
4565
4566 static struct r5conf *setup_conf(struct mddev *mddev)
4567 {
4568         struct r5conf *conf;
4569         int raid_disk, memory, max_disks;
4570         struct md_rdev *rdev;
4571         struct disk_info *disk;
4572
4573         if (mddev->new_level != 5
4574             && mddev->new_level != 4
4575             && mddev->new_level != 6) {
4576                 printk(KERN_ERR "md/raid:%s: raid level not set to 4/5/6 (%d)\n",
4577                        mdname(mddev), mddev->new_level);
4578                 return ERR_PTR(-EIO);
4579         }
4580         if ((mddev->new_level == 5
4581              && !algorithm_valid_raid5(mddev->new_layout)) ||
4582             (mddev->new_level == 6
4583              && !algorithm_valid_raid6(mddev->new_layout))) {
4584                 printk(KERN_ERR "md/raid:%s: layout %d not supported\n",
4585                        mdname(mddev), mddev->new_layout);
4586                 return ERR_PTR(-EIO);
4587         }
4588         if (mddev->new_level == 6 && mddev->raid_disks < 4) {
4589                 printk(KERN_ERR "md/raid:%s: not enough configured devices (%d, minimum 4)\n",
4590                        mdname(mddev), mddev->raid_disks);
4591                 return ERR_PTR(-EINVAL);
4592         }
4593
4594         if (!mddev->new_chunk_sectors ||
4595             (mddev->new_chunk_sectors << 9) % PAGE_SIZE ||
4596             !is_power_of_2(mddev->new_chunk_sectors)) {
4597                 printk(KERN_ERR "md/raid:%s: invalid chunk size %d\n",
4598                        mdname(mddev), mddev->new_chunk_sectors << 9);
4599                 return ERR_PTR(-EINVAL);
4600         }
4601
4602         conf = kzalloc(sizeof(struct r5conf), GFP_KERNEL);
4603         if (conf == NULL)
4604                 goto abort;
4605         spin_lock_init(&conf->device_lock);
4606         init_waitqueue_head(&conf->wait_for_stripe);
4607         init_waitqueue_head(&conf->wait_for_overlap);
4608         INIT_LIST_HEAD(&conf->handle_list);
4609         INIT_LIST_HEAD(&conf->hold_list);
4610         INIT_LIST_HEAD(&conf->delayed_list);
4611         INIT_LIST_HEAD(&conf->bitmap_list);
4612         INIT_LIST_HEAD(&conf->inactive_list);
4613         atomic_set(&conf->active_stripes, 0);
4614         atomic_set(&conf->preread_active_stripes, 0);
4615         atomic_set(&conf->active_aligned_reads, 0);
4616         conf->bypass_threshold = BYPASS_THRESHOLD;
4617         conf->recovery_disabled = mddev->recovery_disabled - 1;
4618
4619         conf->raid_disks = mddev->raid_disks;
4620         if (mddev->reshape_position == MaxSector)
4621                 conf->previous_raid_disks = mddev->raid_disks;
4622         else
4623                 conf->previous_raid_disks = mddev->raid_disks - mddev->delta_disks;
4624         max_disks = max(conf->raid_disks, conf->previous_raid_disks);
4625         conf->scribble_len = scribble_len(max_disks);
4626
4627         conf->disks = kzalloc(max_disks * sizeof(struct disk_info),
4628                               GFP_KERNEL);
4629         if (!conf->disks)
4630                 goto abort;
4631
4632         conf->mddev = mddev;
4633
4634         if ((conf->stripe_hashtbl = kzalloc(PAGE_SIZE, GFP_KERNEL)) == NULL)
4635                 goto abort;
4636
4637         conf->level = mddev->new_level;
4638         if (raid5_alloc_percpu(conf) != 0)
4639                 goto abort;
4640
4641         pr_debug("raid456: run(%s) called.\n", mdname(mddev));
4642
4643         list_for_each_entry(rdev, &mddev->disks, same_set) {
4644                 raid_disk = rdev->raid_disk;
4645                 if (raid_disk >= max_disks
4646                     || raid_disk < 0)
4647                         continue;
4648                 disk = conf->disks + raid_disk;
4649
4650                 disk->rdev = rdev;
4651
4652                 if (test_bit(In_sync, &rdev->flags)) {
4653                         char b[BDEVNAME_SIZE];
4654                         printk(KERN_INFO "md/raid:%s: device %s operational as raid"
4655                                " disk %d\n",
4656                                mdname(mddev), bdevname(rdev->bdev, b), raid_disk);
4657                 } else if (rdev->saved_raid_disk != raid_disk)
4658                         /* Cannot rely on bitmap to complete recovery */
4659                         conf->fullsync = 1;
4660         }
4661
4662         conf->chunk_sectors = mddev->new_chunk_sectors;
4663         conf->level = mddev->new_level;
4664         if (conf->level == 6)
4665                 conf->max_degraded = 2;
4666         else
4667                 conf->max_degraded = 1;
4668         conf->algorithm = mddev->new_layout;
4669         conf->max_nr_stripes = NR_STRIPES;
4670         conf->reshape_progress = mddev->reshape_position;
4671         if (conf->reshape_progress != MaxSector) {
4672                 conf->prev_chunk_sectors = mddev->chunk_sectors;
4673                 conf->prev_algo = mddev->layout;
4674         }
4675
4676         memory = conf->max_nr_stripes * (sizeof(struct stripe_head) +
4677                  max_disks * ((sizeof(struct bio) + PAGE_SIZE))) / 1024;
4678         if (grow_stripes(conf, conf->max_nr_stripes)) {
4679                 printk(KERN_ERR
4680                        "md/raid:%s: couldn't allocate %dkB for buffers\n",
4681                        mdname(mddev), memory);
4682                 goto abort;
4683         } else
4684                 printk(KERN_INFO "md/raid:%s: allocated %dkB\n",
4685                        mdname(mddev), memory);
4686
4687         conf->thread = md_register_thread(raid5d, mddev, NULL);
4688         if (!conf->thread) {
4689                 printk(KERN_ERR
4690                        "md/raid:%s: couldn't allocate thread.\n",
4691                        mdname(mddev));
4692                 goto abort;
4693         }
4694
4695         return conf;
4696
4697  abort:
4698         if (conf) {
4699                 free_conf(conf);
4700                 return ERR_PTR(-EIO);
4701         } else
4702                 return ERR_PTR(-ENOMEM);
4703 }
4704
4705
4706 static int only_parity(int raid_disk, int algo, int raid_disks, int max_degraded)
4707 {
4708         switch (algo) {
4709         case ALGORITHM_PARITY_0:
4710                 if (raid_disk < max_degraded)
4711                         return 1;
4712                 break;
4713         case ALGORITHM_PARITY_N:
4714                 if (raid_disk >= raid_disks - max_degraded)
4715                         return 1;
4716                 break;
4717         case ALGORITHM_PARITY_0_6:
4718                 if (raid_disk == 0 || 
4719                     raid_disk == raid_disks - 1)
4720                         return 1;
4721                 break;
4722         case ALGORITHM_LEFT_ASYMMETRIC_6:
4723         case ALGORITHM_RIGHT_ASYMMETRIC_6:
4724         case ALGORITHM_LEFT_SYMMETRIC_6:
4725         case ALGORITHM_RIGHT_SYMMETRIC_6:
4726                 if (raid_disk == raid_disks - 1)
4727                         return 1;
4728         }
4729         return 0;
4730 }
4731
4732 static int run(struct mddev *mddev)
4733 {
4734         struct r5conf *conf;
4735         int working_disks = 0;
4736         int dirty_parity_disks = 0;
4737         struct md_rdev *rdev;
4738         sector_t reshape_offset = 0;
4739
4740         if (mddev->recovery_cp != MaxSector)
4741                 printk(KERN_NOTICE "md/raid:%s: not clean"
4742                        " -- starting background reconstruction\n",
4743                        mdname(mddev));
4744         if (mddev->reshape_position != MaxSector) {
4745                 /* Check that we can continue the reshape.
4746                  * Currently only disks can change, it must
4747                  * increase, and we must be past the point where
4748                  * a stripe over-writes itself
4749                  */
4750                 sector_t here_new, here_old;
4751                 int old_disks;
4752                 int max_degraded = (mddev->level == 6 ? 2 : 1);
4753
4754                 if (mddev->new_level != mddev->level) {
4755                         printk(KERN_ERR "md/raid:%s: unsupported reshape "
4756                                "required - aborting.\n",
4757                                mdname(mddev));
4758                         return -EINVAL;
4759                 }
4760                 old_disks = mddev->raid_disks - mddev->delta_disks;
4761                 /* reshape_position must be on a new-stripe boundary, and one
4762                  * further up in new geometry must map after here in old
4763                  * geometry.
4764                  */
4765                 here_new = mddev->reshape_position;
4766                 if (sector_div(here_new, mddev->new_chunk_sectors *
4767                                (mddev->raid_disks - max_degraded))) {
4768                         printk(KERN_ERR "md/raid:%s: reshape_position not "
4769                                "on a stripe boundary\n", mdname(mddev));
4770                         return -EINVAL;
4771                 }
4772                 reshape_offset = here_new * mddev->new_chunk_sectors;
4773                 /* here_new is the stripe we will write to */
4774                 here_old = mddev->reshape_position;
4775                 sector_div(here_old, mddev->chunk_sectors *
4776                            (old_disks-max_degraded));
4777                 /* here_old is the first stripe that we might need to read
4778                  * from */
4779                 if (mddev->delta_disks == 0) {
4780                         /* We cannot be sure it is safe to start an in-place
4781                          * reshape.  It is only safe if user-space if monitoring
4782                          * and taking constant backups.
4783                          * mdadm always starts a situation like this in
4784                          * readonly mode so it can take control before
4785                          * allowing any writes.  So just check for that.
4786                          */
4787                         if ((here_new * mddev->new_chunk_sectors != 
4788                              here_old * mddev->chunk_sectors) ||
4789                             mddev->ro == 0) {
4790                                 printk(KERN_ERR "md/raid:%s: in-place reshape must be started"
4791                                        " in read-only mode - aborting\n",
4792                                        mdname(mddev));
4793                                 return -EINVAL;
4794                         }
4795                 } else if (mddev->delta_disks < 0
4796                     ? (here_new * mddev->new_chunk_sectors <=
4797                        here_old * mddev->chunk_sectors)
4798                     : (here_new * mddev->new_chunk_sectors >=
4799                        here_old * mddev->chunk_sectors)) {
4800                         /* Reading from the same stripe as writing to - bad */
4801                         printk(KERN_ERR "md/raid:%s: reshape_position too early for "
4802                                "auto-recovery - aborting.\n",
4803                                mdname(mddev));
4804                         return -EINVAL;
4805                 }
4806                 printk(KERN_INFO "md/raid:%s: reshape will continue\n",
4807                        mdname(mddev));
4808                 /* OK, we should be able to continue; */
4809         } else {
4810                 BUG_ON(mddev->level != mddev->new_level);
4811                 BUG_ON(mddev->layout != mddev->new_layout);
4812                 BUG_ON(mddev->chunk_sectors != mddev->new_chunk_sectors);
4813                 BUG_ON(mddev->delta_disks != 0);
4814         }
4815
4816         if (mddev->private == NULL)
4817                 conf = setup_conf(mddev);
4818         else
4819                 conf = mddev->private;
4820
4821         if (IS_ERR(conf))
4822                 return PTR_ERR(conf);
4823
4824         mddev->thread = conf->thread;
4825         conf->thread = NULL;
4826         mddev->private = conf;
4827
4828         /*
4829          * 0 for a fully functional array, 1 or 2 for a degraded array.
4830          */
4831         list_for_each_entry(rdev, &mddev->disks, same_set) {
4832                 if (rdev->raid_disk < 0)
4833                         continue;
4834                 if (test_bit(In_sync, &rdev->flags)) {
4835                         working_disks++;
4836                         continue;
4837                 }
4838                 /* This disc is not fully in-sync.  However if it
4839                  * just stored parity (beyond the recovery_offset),
4840                  * when we don't need to be concerned about the
4841                  * array being dirty.
4842                  * When reshape goes 'backwards', we never have
4843                  * partially completed devices, so we only need
4844                  * to worry about reshape going forwards.
4845                  */
4846                 /* Hack because v0.91 doesn't store recovery_offset properly. */
4847                 if (mddev->major_version == 0 &&
4848                     mddev->minor_version > 90)
4849                         rdev->recovery_offset = reshape_offset;
4850                         
4851                 if (rdev->recovery_offset < reshape_offset) {
4852                         /* We need to check old and new layout */
4853                         if (!only_parity(rdev->raid_disk,
4854                                          conf->algorithm,
4855                                          conf->raid_disks,
4856                                          conf->max_degraded))
4857                                 continue;
4858                 }
4859                 if (!only_parity(rdev->raid_disk,
4860                                  conf->prev_algo,
4861                                  conf->previous_raid_disks,
4862                                  conf->max_degraded))
4863                         continue;
4864                 dirty_parity_disks++;
4865         }
4866
4867         mddev->degraded = (max(conf->raid_disks, conf->previous_raid_disks)
4868                            - working_disks);
4869
4870         if (has_failed(conf)) {
4871                 printk(KERN_ERR "md/raid:%s: not enough operational devices"
4872                         " (%d/%d failed)\n",
4873                         mdname(mddev), mddev->degraded, conf->raid_disks);
4874                 goto abort;
4875         }
4876
4877         /* device size must be a multiple of chunk size */
4878         mddev->dev_sectors &= ~(mddev->chunk_sectors - 1);
4879         mddev->resync_max_sectors = mddev->dev_sectors;
4880
4881         if (mddev->degraded > dirty_parity_disks &&
4882             mddev->recovery_cp != MaxSector) {
4883                 if (mddev->ok_start_degraded)
4884                         printk(KERN_WARNING
4885                                "md/raid:%s: starting dirty degraded array"
4886                                " - data corruption possible.\n",
4887                                mdname(mddev));
4888                 else {
4889                         printk(KERN_ERR
4890                                "md/raid:%s: cannot start dirty degraded array.\n",
4891                                mdname(mddev));
4892                         goto abort;
4893                 }
4894         }
4895
4896         if (mddev->degraded == 0)
4897                 printk(KERN_INFO "md/raid:%s: raid level %d active with %d out of %d"
4898                        " devices, algorithm %d\n", mdname(mddev), conf->level,
4899                        mddev->raid_disks-mddev->degraded, mddev->raid_disks,
4900                        mddev->new_layout);
4901         else
4902                 printk(KERN_ALERT "md/raid:%s: raid level %d active with %d"
4903                        " out of %d devices, algorithm %d\n",
4904                        mdname(mddev), conf->level,
4905                        mddev->raid_disks - mddev->degraded,
4906                        mddev->raid_disks, mddev->new_layout);
4907
4908         print_raid5_conf(conf);
4909
4910         if (conf->reshape_progress != MaxSector) {
4911                 conf->reshape_safe = conf->reshape_progress;
4912                 atomic_set(&conf->reshape_stripes, 0);
4913                 clear_bit(MD_RECOVERY_SYNC, &mddev->recovery);
4914                 clear_bit(MD_RECOVERY_CHECK, &mddev->recovery);
4915                 set_bit(MD_RECOVERY_RESHAPE, &mddev->recovery);
4916                 set_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
4917                 mddev->sync_thread = md_register_thread(md_do_sync, mddev,
4918                                                         "reshape");
4919         }
4920
4921
4922         /* Ok, everything is just fine now */
4923         if (mddev->to_remove == &raid5_attrs_group)
4924                 mddev->to_remove = NULL;
4925         else if (mddev->kobj.sd &&
4926             sysfs_create_group(&mddev->kobj, &raid5_attrs_group))
4927                 printk(KERN_WARNING
4928                        "raid5: failed to create sysfs attributes for %s\n",
4929                        mdname(mddev));
4930         md_set_array_sectors(mddev, raid5_size(mddev, 0, 0));
4931
4932         if (mddev->queue) {
4933                 int chunk_size;
4934                 /* read-ahead size must cover two whole stripes, which
4935                  * is 2 * (datadisks) * chunksize where 'n' is the
4936                  * number of raid devices
4937                  */
4938                 int data_disks = conf->previous_raid_disks - conf->max_degraded;
4939                 int stripe = data_disks *
4940                         ((mddev->chunk_sectors << 9) / PAGE_SIZE);
4941                 if (mddev->queue->backing_dev_info.ra_pages < 2 * stripe)
4942                         mddev->queue->backing_dev_info.ra_pages = 2 * stripe;
4943
4944                 blk_queue_merge_bvec(mddev->queue, raid5_mergeable_bvec);
4945
4946                 mddev->queue->backing_dev_info.congested_data = mddev;
4947                 mddev->queue->backing_dev_info.congested_fn = raid5_congested;
4948
4949                 chunk_size = mddev->chunk_sectors << 9;
4950                 blk_queue_io_min(mddev->queue, chunk_size);
4951                 blk_queue_io_opt(mddev->queue, chunk_size *
4952                                  (conf->raid_disks - conf->max_degraded));
4953
4954                 list_for_each_entry(rdev, &mddev->disks, same_set)
4955                         disk_stack_limits(mddev->gendisk, rdev->bdev,
4956                                           rdev->data_offset << 9);
4957         }
4958
4959         return 0;
4960 abort:
4961         md_unregister_thread(&mddev->thread);
4962         print_raid5_conf(conf);
4963         free_conf(conf);
4964         mddev->private = NULL;
4965         printk(KERN_ALERT "md/raid:%s: failed to run raid set.\n", mdname(mddev));
4966         return -EIO;
4967 }
4968
4969 static int stop(struct mddev *mddev)
4970 {
4971         struct r5conf *conf = mddev->private;
4972
4973         md_unregister_thread(&mddev->thread);
4974         if (mddev->queue)
4975                 mddev->queue->backing_dev_info.congested_fn = NULL;
4976         free_conf(conf);
4977         mddev->private = NULL;
4978         mddev->to_remove = &raid5_attrs_group;
4979         return 0;
4980 }
4981
4982 static void status(struct seq_file *seq, struct mddev *mddev)
4983 {
4984         struct r5conf *conf = mddev->private;
4985         int i;
4986
4987         seq_printf(seq, " level %d, %dk chunk, algorithm %d", mddev->level,
4988                 mddev->chunk_sectors / 2, mddev->layout);
4989         seq_printf (seq, " [%d/%d] [", conf->raid_disks, conf->raid_disks - mddev->degraded);
4990         for (i = 0; i < conf->raid_disks; i++)
4991                 seq_printf (seq, "%s",
4992                                conf->disks[i].rdev &&
4993                                test_bit(In_sync, &conf->disks[i].rdev->flags) ? "U" : "_");
4994         seq_printf (seq, "]");
4995 }
4996
4997 static void print_raid5_conf (struct r5conf *conf)
4998 {
4999         int i;
5000         struct disk_info *tmp;
5001
5002         printk(KERN_DEBUG "RAID conf printout:\n");
5003         if (!conf) {
5004                 printk("(conf==NULL)\n");
5005                 return;
5006         }
5007         printk(KERN_DEBUG " --- level:%d rd:%d wd:%d\n", conf->level,
5008                conf->raid_disks,
5009                conf->raid_disks - conf->mddev->degraded);
5010
5011         for (i = 0; i < conf->raid_disks; i++) {
5012                 char b[BDEVNAME_SIZE];
5013                 tmp = conf->disks + i;
5014                 if (tmp->rdev)
5015                         printk(KERN_DEBUG " disk %d, o:%d, dev:%s\n",
5016                                i, !test_bit(Faulty, &tmp->rdev->flags),
5017                                bdevname(tmp->rdev->bdev, b));
5018         }
5019 }
5020
5021 static int raid5_spare_active(struct mddev *mddev)
5022 {
5023         int i;
5024         struct r5conf *conf = mddev->private;
5025         struct disk_info *tmp;
5026         int count = 0;
5027         unsigned long flags;
5028
5029         for (i = 0; i < conf->raid_disks; i++) {
5030                 tmp = conf->disks + i;
5031                 if (tmp->rdev
5032                     && tmp->rdev->recovery_offset == MaxSector
5033                     && !test_bit(Faulty, &tmp->rdev->flags)
5034                     && !test_and_set_bit(In_sync, &tmp->rdev->flags)) {
5035                         count++;
5036                         sysfs_notify_dirent_safe(tmp->rdev->sysfs_state);
5037                 }
5038         }
5039         spin_lock_irqsave(&conf->device_lock, flags);
5040         mddev->degraded -= count;
5041         spin_unlock_irqrestore(&conf->device_lock, flags);
5042         print_raid5_conf(conf);
5043         return count;
5044 }
5045
5046 static int raid5_remove_disk(struct mddev *mddev, int number)
5047 {
5048         struct r5conf *conf = mddev->private;
5049         int err = 0;
5050         struct md_rdev *rdev;
5051         struct disk_info *p = conf->disks + number;
5052
5053         print_raid5_conf(conf);
5054         rdev = p->rdev;
5055         if (rdev) {
5056                 if (number >= conf->raid_disks &&
5057                     conf->reshape_progress == MaxSector)
5058                         clear_bit(In_sync, &rdev->flags);
5059
5060                 if (test_bit(In_sync, &rdev->flags) ||
5061                     atomic_read(&rdev->nr_pending)) {
5062                         err = -EBUSY;
5063                         goto abort;
5064                 }
5065                 /* Only remove non-faulty devices if recovery
5066                  * isn't possible.
5067                  */
5068                 if (!test_bit(Faulty, &rdev->flags) &&
5069                     mddev->recovery_disabled != conf->recovery_disabled &&
5070                     !has_failed(conf) &&
5071                     number < conf->raid_disks) {
5072                         err = -EBUSY;
5073                         goto abort;
5074                 }
5075                 p->rdev = NULL;
5076                 synchronize_rcu();
5077                 if (atomic_read(&rdev->nr_pending)) {
5078                         /* lost the race, try later */
5079                         err = -EBUSY;
5080                         p->rdev = rdev;
5081                 }
5082         }
5083 abort:
5084
5085         print_raid5_conf(conf);
5086         return err;
5087 }
5088
5089 static int raid5_add_disk(struct mddev *mddev, struct md_rdev *rdev)
5090 {
5091         struct r5conf *conf = mddev->private;
5092         int err = -EEXIST;
5093         int disk;
5094         struct disk_info *p;
5095         int first = 0;
5096         int last = conf->raid_disks - 1;
5097
5098         if (mddev->recovery_disabled == conf->recovery_disabled)
5099                 return -EBUSY;
5100
5101         if (has_failed(conf))
5102                 /* no point adding a device */
5103                 return -EINVAL;
5104
5105         if (rdev->raid_disk >= 0)
5106                 first = last = rdev->raid_disk;
5107
5108         /*
5109          * find the disk ... but prefer rdev->saved_raid_disk
5110          * if possible.
5111          */
5112         if (rdev->saved_raid_disk >= 0 &&
5113             rdev->saved_raid_disk >= first &&
5114             conf->disks[rdev->saved_raid_disk].rdev == NULL)
5115                 disk = rdev->saved_raid_disk;
5116         else
5117                 disk = first;
5118         for ( ; disk <= last ; disk++)
5119                 if ((p=conf->disks + disk)->rdev == NULL) {
5120                         clear_bit(In_sync, &rdev->flags);
5121                         rdev->raid_disk = disk;
5122                         err = 0;
5123                         if (rdev->saved_raid_disk != disk)
5124                                 conf->fullsync = 1;
5125                         rcu_assign_pointer(p->rdev, rdev);
5126                         break;
5127                 }
5128         print_raid5_conf(conf);
5129         return err;
5130 }
5131
5132 static int raid5_resize(struct mddev *mddev, sector_t sectors)
5133 {
5134         /* no resync is happening, and there is enough space
5135          * on all devices, so we can resize.
5136          * We need to make sure resync covers any new space.
5137          * If the array is shrinking we should possibly wait until
5138          * any io in the removed space completes, but it hardly seems
5139          * worth it.
5140          */
5141         sectors &= ~((sector_t)mddev->chunk_sectors - 1);
5142         md_set_array_sectors(mddev, raid5_size(mddev, sectors,
5143                                                mddev->raid_disks));
5144         if (mddev->array_sectors >
5145             raid5_size(mddev, sectors, mddev->raid_disks))
5146                 return -EINVAL;
5147         set_capacity(mddev->gendisk, mddev->array_sectors);
5148         revalidate_disk(mddev->gendisk);
5149         if (sectors > mddev->dev_sectors &&
5150             mddev->recovery_cp > mddev->dev_sectors) {
5151                 mddev->recovery_cp = mddev->dev_sectors;
5152                 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
5153         }
5154         mddev->dev_sectors = sectors;
5155         mddev->resync_max_sectors = sectors;
5156         return 0;
5157 }
5158
5159 static int check_stripe_cache(struct mddev *mddev)
5160 {
5161         /* Can only proceed if there are plenty of stripe_heads.
5162          * We need a minimum of one full stripe,, and for sensible progress
5163          * it is best to have about 4 times that.
5164          * If we require 4 times, then the default 256 4K stripe_heads will
5165          * allow for chunk sizes up to 256K, which is probably OK.
5166          * If the chunk size is greater, user-space should request more
5167          * stripe_heads first.
5168          */
5169         struct r5conf *conf = mddev->private;
5170         if (((mddev->chunk_sectors << 9) / STRIPE_SIZE) * 4
5171             > conf->max_nr_stripes ||
5172             ((mddev->new_chunk_sectors << 9) / STRIPE_SIZE) * 4
5173             > conf->max_nr_stripes) {
5174                 printk(KERN_WARNING "md/raid:%s: reshape: not enough stripes.  Needed %lu\n",
5175                        mdname(mddev),
5176                        ((max(mddev->chunk_sectors, mddev->new_chunk_sectors) << 9)
5177                         / STRIPE_SIZE)*4);
5178                 return 0;
5179         }
5180         return 1;
5181 }
5182
5183 static int check_reshape(struct mddev *mddev)
5184 {
5185         struct r5conf *conf = mddev->private;
5186
5187         if (mddev->delta_disks == 0 &&
5188             mddev->new_layout == mddev->layout &&
5189             mddev->new_chunk_sectors == mddev->chunk_sectors)
5190                 return 0; /* nothing to do */
5191         if (mddev->bitmap)
5192                 /* Cannot grow a bitmap yet */
5193                 return -EBUSY;
5194         if (has_failed(conf))
5195                 return -EINVAL;
5196         if (mddev->delta_disks < 0) {
5197                 /* We might be able to shrink, but the devices must
5198                  * be made bigger first.
5199                  * For raid6, 4 is the minimum size.
5200                  * Otherwise 2 is the minimum
5201                  */
5202                 int min = 2;
5203                 if (mddev->level == 6)
5204                         min = 4;
5205                 if (mddev->raid_disks + mddev->delta_disks < min)
5206                         return -EINVAL;
5207         }
5208
5209         if (!check_stripe_cache(mddev))
5210                 return -ENOSPC;
5211
5212         return resize_stripes(conf, conf->raid_disks + mddev->delta_disks);
5213 }
5214
5215 static int raid5_start_reshape(struct mddev *mddev)
5216 {
5217         struct r5conf *conf = mddev->private;
5218         struct md_rdev *rdev;
5219         int spares = 0;
5220         unsigned long flags;
5221
5222         if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
5223                 return -EBUSY;
5224
5225         if (!check_stripe_cache(mddev))
5226                 return -ENOSPC;
5227
5228         list_for_each_entry(rdev, &mddev->disks, same_set)
5229                 if (!test_bit(In_sync, &rdev->flags)
5230                     && !test_bit(Faulty, &rdev->flags))
5231                         spares++;
5232
5233         if (spares - mddev->degraded < mddev->delta_disks - conf->max_degraded)
5234                 /* Not enough devices even to make a degraded array
5235                  * of that size
5236                  */
5237                 return -EINVAL;
5238
5239         /* Refuse to reduce size of the array.  Any reductions in
5240          * array size must be through explicit setting of array_size
5241          * attribute.
5242          */
5243         if (raid5_size(mddev, 0, conf->raid_disks + mddev->delta_disks)
5244             < mddev->array_sectors) {
5245                 printk(KERN_ERR "md/raid:%s: array size must be reduced "
5246                        "before number of disks\n", mdname(mddev));
5247                 return -EINVAL;
5248         }
5249
5250         atomic_set(&conf->reshape_stripes, 0);
5251         spin_lock_irq(&conf->device_lock);
5252         conf->previous_raid_disks = conf->raid_disks;
5253         conf->raid_disks += mddev->delta_disks;
5254         conf->prev_chunk_sectors = conf->chunk_sectors;
5255         conf->chunk_sectors = mddev->new_chunk_sectors;
5256         conf->prev_algo = conf->algorithm;
5257         conf->algorithm = mddev->new_layout;
5258         if (mddev->delta_disks < 0)
5259                 conf->reshape_progress = raid5_size(mddev, 0, 0);
5260         else
5261                 conf->reshape_progress = 0;
5262         conf->reshape_safe = conf->reshape_progress;
5263         conf->generation++;
5264         spin_unlock_irq(&conf->device_lock);
5265
5266         /* Add some new drives, as many as will fit.
5267          * We know there are enough to make the newly sized array work.
5268          * Don't add devices if we are reducing the number of
5269          * devices in the array.  This is because it is not possible
5270          * to correctly record the "partially reconstructed" state of
5271          * such devices during the reshape and confusion could result.
5272          */
5273         if (mddev->delta_disks >= 0) {
5274                 int added_devices = 0;
5275                 list_for_each_entry(rdev, &mddev->disks, same_set)
5276                         if (rdev->raid_disk < 0 &&
5277                             !test_bit(Faulty, &rdev->flags)) {
5278                                 if (raid5_add_disk(mddev, rdev) == 0) {
5279                                         if (rdev->raid_disk
5280                                             >= conf->previous_raid_disks) {
5281                                                 set_bit(In_sync, &rdev->flags);
5282                                                 added_devices++;
5283                                         } else
5284                                                 rdev->recovery_offset = 0;
5285
5286                                         if (sysfs_link_rdev(mddev, rdev))
5287                                                 /* Failure here is OK */;
5288                                 }
5289                         } else if (rdev->raid_disk >= conf->previous_raid_disks
5290                                    && !test_bit(Faulty, &rdev->flags)) {
5291                                 /* This is a spare that was manually added */
5292                                 set_bit(In_sync, &rdev->flags);
5293                                 added_devices++;
5294                         }
5295
5296                 /* When a reshape changes the number of devices,
5297                  * ->degraded is measured against the larger of the
5298                  * pre and post number of devices.
5299                  */
5300                 spin_lock_irqsave(&conf->device_lock, flags);
5301                 mddev->degraded += (conf->raid_disks - conf->previous_raid_disks)
5302                         - added_devices;
5303                 spin_unlock_irqrestore(&conf->device_lock, flags);
5304         }
5305         mddev->raid_disks = conf->raid_disks;
5306         mddev->reshape_position = conf->reshape_progress;
5307         set_bit(MD_CHANGE_DEVS, &mddev->flags);
5308
5309         clear_bit(MD_RECOVERY_SYNC, &mddev->recovery);
5310         clear_bit(MD_RECOVERY_CHECK, &mddev->recovery);
5311         set_bit(MD_RECOVERY_RESHAPE, &mddev->recovery);
5312         set_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
5313         mddev->sync_thread = md_register_thread(md_do_sync, mddev,
5314                                                 "reshape");
5315         if (!mddev->sync_thread) {
5316                 mddev->recovery = 0;
5317                 spin_lock_irq(&conf->device_lock);
5318                 mddev->raid_disks = conf->raid_disks = conf->previous_raid_disks;
5319                 conf->reshape_progress = MaxSector;
5320                 spin_unlock_irq(&conf->device_lock);
5321                 return -EAGAIN;
5322         }
5323         conf->reshape_checkpoint = jiffies;
5324         md_wakeup_thread(mddev->sync_thread);
5325         md_new_event(mddev);
5326         return 0;
5327 }
5328
5329 /* This is called from the reshape thread and should make any
5330  * changes needed in 'conf'
5331  */
5332 static void end_reshape(struct r5conf *conf)
5333 {
5334
5335         if (!test_bit(MD_RECOVERY_INTR, &conf->mddev->recovery)) {
5336
5337                 spin_lock_irq(&conf->device_lock);
5338                 conf->previous_raid_disks = conf->raid_disks;
5339                 conf->reshape_progress = MaxSector;
5340                 spin_unlock_irq(&conf->device_lock);
5341                 wake_up(&conf->wait_for_overlap);
5342
5343                 /* read-ahead size must cover two whole stripes, which is
5344                  * 2 * (datadisks) * chunksize where 'n' is the number of raid devices
5345                  */
5346                 if (conf->mddev->queue) {
5347                         int data_disks = conf->raid_disks - conf->max_degraded;
5348                         int stripe = data_disks * ((conf->chunk_sectors << 9)
5349                                                    / PAGE_SIZE);
5350                         if (conf->mddev->queue->backing_dev_info.ra_pages < 2 * stripe)
5351                                 conf->mddev->queue->backing_dev_info.ra_pages = 2 * stripe;
5352                 }
5353         }
5354 }
5355
5356 /* This is called from the raid5d thread with mddev_lock held.
5357  * It makes config changes to the device.
5358  */
5359 static void raid5_finish_reshape(struct mddev *mddev)
5360 {
5361         struct r5conf *conf = mddev->private;
5362
5363         if (!test_bit(MD_RECOVERY_INTR, &mddev->recovery)) {
5364
5365                 if (mddev->delta_disks > 0) {
5366                         md_set_array_sectors(mddev, raid5_size(mddev, 0, 0));
5367                         set_capacity(mddev->gendisk, mddev->array_sectors);
5368                         revalidate_disk(mddev->gendisk);
5369                 } else {
5370                         int d;
5371                         mddev->degraded = conf->raid_disks;
5372                         for (d = 0; d < conf->raid_disks ; d++)
5373                                 if (conf->disks[d].rdev &&
5374                                     test_bit(In_sync,
5375                                              &conf->disks[d].rdev->flags))
5376                                         mddev->degraded--;
5377                         for (d = conf->raid_disks ;
5378                              d < conf->raid_disks - mddev->delta_disks;
5379                              d++) {
5380                                 struct md_rdev *rdev = conf->disks[d].rdev;
5381                                 if (rdev && raid5_remove_disk(mddev, d) == 0) {
5382                                         sysfs_unlink_rdev(mddev, rdev);
5383                                         rdev->raid_disk = -1;
5384                                 }
5385                         }
5386                 }
5387                 mddev->layout = conf->algorithm;
5388                 mddev->chunk_sectors = conf->chunk_sectors;
5389                 mddev->reshape_position = MaxSector;
5390                 mddev->delta_disks = 0;
5391         }
5392 }
5393
5394 static void raid5_quiesce(struct mddev *mddev, int state)
5395 {
5396         struct r5conf *conf = mddev->private;
5397
5398         switch(state) {
5399         case 2: /* resume for a suspend */
5400                 wake_up(&conf->wait_for_overlap);
5401                 break;
5402
5403         case 1: /* stop all writes */
5404                 spin_lock_irq(&conf->device_lock);
5405                 /* '2' tells resync/reshape to pause so that all
5406                  * active stripes can drain
5407                  */
5408                 conf->quiesce = 2;
5409                 wait_event_lock_irq(conf->wait_for_stripe,
5410                                     atomic_read(&conf->active_stripes) == 0 &&
5411                                     atomic_read(&conf->active_aligned_reads) == 0,
5412                                     conf->device_lock, /* nothing */);
5413                 conf->quiesce = 1;
5414                 spin_unlock_irq(&conf->device_lock);
5415                 /* allow reshape to continue */
5416                 wake_up(&conf->wait_for_overlap);
5417                 break;
5418
5419         case 0: /* re-enable writes */
5420                 spin_lock_irq(&conf->device_lock);
5421                 conf->quiesce = 0;
5422                 wake_up(&conf->wait_for_stripe);
5423                 wake_up(&conf->wait_for_overlap);
5424                 spin_unlock_irq(&conf->device_lock);
5425                 break;
5426         }
5427 }
5428
5429
5430 static void *raid45_takeover_raid0(struct mddev *mddev, int level)
5431 {
5432         struct r0conf *raid0_conf = mddev->private;
5433         sector_t sectors;
5434
5435         /* for raid0 takeover only one zone is supported */
5436         if (raid0_conf->nr_strip_zones > 1) {
5437                 printk(KERN_ERR "md/raid:%s: cannot takeover raid0 with more than one zone.\n",
5438                        mdname(mddev));
5439                 return ERR_PTR(-EINVAL);
5440         }
5441
5442         sectors = raid0_conf->strip_zone[0].zone_end;
5443         sector_div(sectors, raid0_conf->strip_zone[0].nb_dev);
5444         mddev->dev_sectors = sectors;
5445         mddev->new_level = level;
5446         mddev->new_layout = ALGORITHM_PARITY_N;
5447         mddev->new_chunk_sectors = mddev->chunk_sectors;
5448         mddev->raid_disks += 1;
5449         mddev->delta_disks = 1;
5450         /* make sure it will be not marked as dirty */
5451         mddev->recovery_cp = MaxSector;
5452
5453         return setup_conf(mddev);
5454 }
5455
5456
5457 static void *raid5_takeover_raid1(struct mddev *mddev)
5458 {
5459         int chunksect;
5460
5461         if (mddev->raid_disks != 2 ||
5462             mddev->degraded > 1)
5463                 return ERR_PTR(-EINVAL);
5464
5465         /* Should check if there are write-behind devices? */
5466
5467         chunksect = 64*2; /* 64K by default */
5468
5469         /* The array must be an exact multiple of chunksize */
5470         while (chunksect && (mddev->array_sectors & (chunksect-1)))
5471                 chunksect >>= 1;
5472
5473         if ((chunksect<<9) < STRIPE_SIZE)
5474                 /* array size does not allow a suitable chunk size */
5475                 return ERR_PTR(-EINVAL);
5476
5477         mddev->new_level = 5;
5478         mddev->new_layout = ALGORITHM_LEFT_SYMMETRIC;
5479         mddev->new_chunk_sectors = chunksect;
5480
5481         return setup_conf(mddev);
5482 }
5483
5484 static void *raid5_takeover_raid6(struct mddev *mddev)
5485 {
5486         int new_layout;
5487
5488         switch (mddev->layout) {
5489         case ALGORITHM_LEFT_ASYMMETRIC_6:
5490                 new_layout = ALGORITHM_LEFT_ASYMMETRIC;
5491                 break;
5492         case ALGORITHM_RIGHT_ASYMMETRIC_6:
5493                 new_layout = ALGORITHM_RIGHT_ASYMMETRIC;
5494                 break;
5495         case ALGORITHM_LEFT_SYMMETRIC_6:
5496                 new_layout = ALGORITHM_LEFT_SYMMETRIC;
5497                 break;
5498         case ALGORITHM_RIGHT_SYMMETRIC_6:
5499                 new_layout = ALGORITHM_RIGHT_SYMMETRIC;
5500                 break;
5501         case ALGORITHM_PARITY_0_6:
5502                 new_layout = ALGORITHM_PARITY_0;
5503                 break;
5504         case ALGORITHM_PARITY_N:
5505                 new_layout = ALGORITHM_PARITY_N;
5506                 break;
5507         default:
5508                 return ERR_PTR(-EINVAL);
5509         }
5510         mddev->new_level = 5;
5511         mddev->new_layout = new_layout;
5512         mddev->delta_disks = -1;
5513         mddev->raid_disks -= 1;
5514         return setup_conf(mddev);
5515 }
5516
5517
5518 static int raid5_check_reshape(struct mddev *mddev)
5519 {
5520         /* For a 2-drive array, the layout and chunk size can be changed
5521          * immediately as not restriping is needed.
5522          * For larger arrays we record the new value - after validation
5523          * to be used by a reshape pass.
5524          */
5525         struct r5conf *conf = mddev->private;
5526         int new_chunk = mddev->new_chunk_sectors;
5527
5528         if (mddev->new_layout >= 0 && !algorithm_valid_raid5(mddev->new_layout))
5529                 return -EINVAL;
5530         if (new_chunk > 0) {
5531                 if (!is_power_of_2(new_chunk))
5532                         return -EINVAL;
5533                 if (new_chunk < (PAGE_SIZE>>9))
5534                         return -EINVAL;
5535                 if (mddev->array_sectors & (new_chunk-1))
5536                         /* not factor of array size */
5537                         return -EINVAL;
5538         }
5539
5540         /* They look valid */
5541
5542         if (mddev->raid_disks == 2) {
5543                 /* can make the change immediately */
5544                 if (mddev->new_layout >= 0) {
5545                         conf->algorithm = mddev->new_layout;
5546                         mddev->layout = mddev->new_layout;
5547                 }
5548                 if (new_chunk > 0) {
5549                         conf->chunk_sectors = new_chunk ;
5550                         mddev->chunk_sectors = new_chunk;
5551                 }
5552                 set_bit(MD_CHANGE_DEVS, &mddev->flags);
5553                 md_wakeup_thread(mddev->thread);
5554         }
5555         return check_reshape(mddev);
5556 }
5557
5558 static int raid6_check_reshape(struct mddev *mddev)
5559 {
5560         int new_chunk = mddev->new_chunk_sectors;
5561
5562         if (mddev->new_layout >= 0 && !algorithm_valid_raid6(mddev->new_layout))
5563                 return -EINVAL;
5564         if (new_chunk > 0) {
5565                 if (!is_power_of_2(new_chunk))
5566                         return -EINVAL;
5567                 if (new_chunk < (PAGE_SIZE >> 9))
5568                         return -EINVAL;
5569                 if (mddev->array_sectors & (new_chunk-1))
5570                         /* not factor of array size */
5571                         return -EINVAL;
5572         }
5573
5574         /* They look valid */
5575         return check_reshape(mddev);
5576 }
5577
5578 static void *raid5_takeover(struct mddev *mddev)
5579 {
5580         /* raid5 can take over:
5581          *  raid0 - if there is only one strip zone - make it a raid4 layout
5582          *  raid1 - if there are two drives.  We need to know the chunk size
5583          *  raid4 - trivial - just use a raid4 layout.
5584          *  raid6 - Providing it is a *_6 layout
5585          */
5586         if (mddev->level == 0)
5587                 return raid45_takeover_raid0(mddev, 5);
5588         if (mddev->level == 1)
5589                 return raid5_takeover_raid1(mddev);
5590         if (mddev->level == 4) {
5591                 mddev->new_layout = ALGORITHM_PARITY_N;
5592                 mddev->new_level = 5;
5593                 return setup_conf(mddev);
5594         }
5595         if (mddev->level == 6)
5596                 return raid5_takeover_raid6(mddev);
5597
5598         return ERR_PTR(-EINVAL);
5599 }
5600
5601 static void *raid4_takeover(struct mddev *mddev)
5602 {
5603         /* raid4 can take over:
5604          *  raid0 - if there is only one strip zone
5605          *  raid5 - if layout is right
5606          */
5607         if (mddev->level == 0)
5608                 return raid45_takeover_raid0(mddev, 4);
5609         if (mddev->level == 5 &&
5610             mddev->layout == ALGORITHM_PARITY_N) {
5611                 mddev->new_layout = 0;
5612                 mddev->new_level = 4;
5613                 return setup_conf(mddev);
5614         }
5615         return ERR_PTR(-EINVAL);
5616 }
5617
5618 static struct md_personality raid5_personality;
5619
5620 static void *raid6_takeover(struct mddev *mddev)
5621 {
5622         /* Currently can only take over a raid5.  We map the
5623          * personality to an equivalent raid6 personality
5624          * with the Q block at the end.
5625          */
5626         int new_layout;
5627
5628         if (mddev->pers != &raid5_personality)
5629                 return ERR_PTR(-EINVAL);
5630         if (mddev->degraded > 1)
5631                 return ERR_PTR(-EINVAL);
5632         if (mddev->raid_disks > 253)
5633                 return ERR_PTR(-EINVAL);
5634         if (mddev->raid_disks < 3)
5635                 return ERR_PTR(-EINVAL);
5636
5637         switch (mddev->layout) {
5638         case ALGORITHM_LEFT_ASYMMETRIC:
5639                 new_layout = ALGORITHM_LEFT_ASYMMETRIC_6;
5640                 break;
5641         case ALGORITHM_RIGHT_ASYMMETRIC:
5642                 new_layout = ALGORITHM_RIGHT_ASYMMETRIC_6;
5643                 break;
5644         case ALGORITHM_LEFT_SYMMETRIC:
5645                 new_layout = ALGORITHM_LEFT_SYMMETRIC_6;
5646                 break;
5647         case ALGORITHM_RIGHT_SYMMETRIC:
5648                 new_layout = ALGORITHM_RIGHT_SYMMETRIC_6;
5649                 break;
5650         case ALGORITHM_PARITY_0:
5651                 new_layout = ALGORITHM_PARITY_0_6;
5652                 break;
5653         case ALGORITHM_PARITY_N:
5654                 new_layout = ALGORITHM_PARITY_N;
5655                 break;
5656         default:
5657                 return ERR_PTR(-EINVAL);
5658         }
5659         mddev->new_level = 6;
5660         mddev->new_layout = new_layout;
5661         mddev->delta_disks = 1;
5662         mddev->raid_disks += 1;
5663         return setup_conf(mddev);
5664 }
5665
5666
5667 static struct md_personality raid6_personality =
5668 {
5669         .name           = "raid6",
5670         .level          = 6,
5671         .owner          = THIS_MODULE,
5672         .make_request   = make_request,
5673         .run            = run,
5674         .stop           = stop,
5675         .status         = status,
5676         .error_handler  = error,
5677         .hot_add_disk   = raid5_add_disk,
5678         .hot_remove_disk= raid5_remove_disk,
5679         .spare_active   = raid5_spare_active,
5680         .sync_request   = sync_request,
5681         .resize         = raid5_resize,
5682         .size           = raid5_size,
5683         .check_reshape  = raid6_check_reshape,
5684         .start_reshape  = raid5_start_reshape,
5685         .finish_reshape = raid5_finish_reshape,
5686         .quiesce        = raid5_quiesce,
5687         .takeover       = raid6_takeover,
5688 };
5689 static struct md_personality raid5_personality =
5690 {
5691         .name           = "raid5",
5692         .level          = 5,
5693         .owner          = THIS_MODULE,
5694         .make_request   = make_request,
5695         .run            = run,
5696         .stop           = stop,
5697         .status         = status,
5698         .error_handler  = error,
5699         .hot_add_disk   = raid5_add_disk,
5700         .hot_remove_disk= raid5_remove_disk,
5701         .spare_active   = raid5_spare_active,
5702         .sync_request   = sync_request,
5703         .resize         = raid5_resize,
5704         .size           = raid5_size,
5705         .check_reshape  = raid5_check_reshape,
5706         .start_reshape  = raid5_start_reshape,
5707         .finish_reshape = raid5_finish_reshape,
5708         .quiesce        = raid5_quiesce,
5709         .takeover       = raid5_takeover,
5710 };
5711
5712 static struct md_personality raid4_personality =
5713 {
5714         .name           = "raid4",
5715         .level          = 4,
5716         .owner          = THIS_MODULE,
5717         .make_request   = make_request,
5718         .run            = run,
5719         .stop           = stop,
5720         .status         = status,
5721         .error_handler  = error,
5722         .hot_add_disk   = raid5_add_disk,
5723         .hot_remove_disk= raid5_remove_disk,
5724         .spare_active   = raid5_spare_active,
5725         .sync_request   = sync_request,
5726         .resize         = raid5_resize,
5727         .size           = raid5_size,
5728         .check_reshape  = raid5_check_reshape,
5729         .start_reshape  = raid5_start_reshape,
5730         .finish_reshape = raid5_finish_reshape,
5731         .quiesce        = raid5_quiesce,
5732         .takeover       = raid4_takeover,
5733 };
5734
5735 static int __init raid5_init(void)
5736 {
5737         register_md_personality(&raid6_personality);
5738         register_md_personality(&raid5_personality);
5739         register_md_personality(&raid4_personality);
5740         return 0;
5741 }
5742
5743 static void raid5_exit(void)
5744 {
5745         unregister_md_personality(&raid6_personality);
5746         unregister_md_personality(&raid5_personality);
5747         unregister_md_personality(&raid4_personality);
5748 }
5749
5750 module_init(raid5_init);
5751 module_exit(raid5_exit);
5752 MODULE_LICENSE("GPL");
5753 MODULE_DESCRIPTION("RAID4/5/6 (striping with parity) personality for MD");
5754 MODULE_ALIAS("md-personality-4"); /* RAID5 */
5755 MODULE_ALIAS("md-raid5");
5756 MODULE_ALIAS("md-raid4");
5757 MODULE_ALIAS("md-level-5");
5758 MODULE_ALIAS("md-level-4");
5759 MODULE_ALIAS("md-personality-8"); /* RAID6 */
5760 MODULE_ALIAS("md-raid6");
5761 MODULE_ALIAS("md-level-6");
5762
5763 /* This used to be two separate modules, they were: */
5764 MODULE_ALIAS("raid5");
5765 MODULE_ALIAS("raid6");