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