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