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