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