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