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