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