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