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