45933c1606972c007fee4393b82c05db7b24f7ec
[karo-tx-linux.git] / drivers / md / raid5.c
1 /*
2  * raid5.c : Multiple Devices driver for Linux
3  *         Copyright (C) 1996, 1997 Ingo Molnar, Miguel de Icaza, Gadi Oxman
4  *         Copyright (C) 1999, 2000 Ingo Molnar
5  *         Copyright (C) 2002, 2003 H. Peter Anvin
6  *
7  * RAID-4/5/6 management functions.
8  * Thanks to Penguin Computing for making the RAID-6 development possible
9  * by donating a test server!
10  *
11  * This program is free software; you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation; either version 2, or (at your option)
14  * any later version.
15  *
16  * You should have received a copy of the GNU General Public License
17  * (for example /usr/src/linux/COPYING); if not, write to the Free
18  * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19  */
20
21 /*
22  * BITMAP UNPLUGGING:
23  *
24  * The sequencing for updating the bitmap reliably is a little
25  * subtle (and I got it wrong the first time) so it deserves some
26  * explanation.
27  *
28  * We group bitmap updates into batches.  Each batch has a number.
29  * We may write out several batches at once, but that isn't very important.
30  * conf->seq_write is the number of the last batch successfully written.
31  * conf->seq_flush is the number of the last batch that was closed to
32  *    new additions.
33  * When we discover that we will need to write to any block in a stripe
34  * (in add_stripe_bio) we update the in-memory bitmap and record in sh->bm_seq
35  * the number of the batch it will be in. This is seq_flush+1.
36  * When we are ready to do a write, if that batch hasn't been written yet,
37  *   we plug the array and queue the stripe for later.
38  * When an unplug happens, we increment bm_flush, thus closing the current
39  *   batch.
40  * When we notice that bm_flush > bm_write, we write out all pending updates
41  * to the bitmap, and advance bm_write to where bm_flush was.
42  * This may occasionally write a bit out twice, but is sure never to
43  * miss any bits.
44  */
45
46 #include <linux/blkdev.h>
47 #include <linux/kthread.h>
48 #include <linux/raid/pq.h>
49 #include <linux/async_tx.h>
50 #include <linux/module.h>
51 #include <linux/async.h>
52 #include <linux/seq_file.h>
53 #include <linux/cpu.h>
54 #include <linux/slab.h>
55 #include <linux/ratelimit.h>
56 #include <linux/nodemask.h>
57 #include <linux/flex_array.h>
58 #include <trace/events/block.h>
59
60 #include "md.h"
61 #include "raid5.h"
62 #include "raid0.h"
63 #include "bitmap.h"
64
65 #define cpu_to_group(cpu) cpu_to_node(cpu)
66 #define ANY_GROUP NUMA_NO_NODE
67
68 static bool devices_handle_discard_safely = false;
69 module_param(devices_handle_discard_safely, bool, 0644);
70 MODULE_PARM_DESC(devices_handle_discard_safely,
71                  "Set to Y if all devices in each array reliably return zeroes on reads from discarded regions");
72 static struct workqueue_struct *raid5_wq;
73 /*
74  * Stripe cache
75  */
76
77 #define NR_STRIPES              256
78 #define STRIPE_SIZE             PAGE_SIZE
79 #define STRIPE_SHIFT            (PAGE_SHIFT - 9)
80 #define STRIPE_SECTORS          (STRIPE_SIZE>>9)
81 #define IO_THRESHOLD            1
82 #define BYPASS_THRESHOLD        1
83 #define NR_HASH                 (PAGE_SIZE / sizeof(struct hlist_head))
84 #define HASH_MASK               (NR_HASH - 1)
85 #define MAX_STRIPE_BATCH        8
86
87 static inline struct hlist_head *stripe_hash(struct r5conf *conf, sector_t sect)
88 {
89         int hash = (sect >> STRIPE_SHIFT) & HASH_MASK;
90         return &conf->stripe_hashtbl[hash];
91 }
92
93 static inline int stripe_hash_locks_hash(sector_t sect)
94 {
95         return (sect >> STRIPE_SHIFT) & STRIPE_HASH_LOCKS_MASK;
96 }
97
98 static inline void lock_device_hash_lock(struct r5conf *conf, int hash)
99 {
100         spin_lock_irq(conf->hash_locks + hash);
101         spin_lock(&conf->device_lock);
102 }
103
104 static inline void unlock_device_hash_lock(struct r5conf *conf, int hash)
105 {
106         spin_unlock(&conf->device_lock);
107         spin_unlock_irq(conf->hash_locks + hash);
108 }
109
110 static inline void lock_all_device_hash_locks_irq(struct r5conf *conf)
111 {
112         int i;
113         local_irq_disable();
114         spin_lock(conf->hash_locks);
115         for (i = 1; i < NR_STRIPE_HASH_LOCKS; i++)
116                 spin_lock_nest_lock(conf->hash_locks + i, conf->hash_locks);
117         spin_lock(&conf->device_lock);
118 }
119
120 static inline void unlock_all_device_hash_locks_irq(struct r5conf *conf)
121 {
122         int i;
123         spin_unlock(&conf->device_lock);
124         for (i = NR_STRIPE_HASH_LOCKS; i; i--)
125                 spin_unlock(conf->hash_locks + i - 1);
126         local_irq_enable();
127 }
128
129 /* bio's attached to a stripe+device for I/O are linked together in bi_sector
130  * order without overlap.  There may be several bio's per stripe+device, and
131  * a bio could span several devices.
132  * When walking this list for a particular stripe+device, we must never proceed
133  * beyond a bio that extends past this device, as the next bio might no longer
134  * be valid.
135  * This function is used to determine the 'next' bio in the list, given the sector
136  * of the current stripe+device
137  */
138 static inline struct bio *r5_next_bio(struct bio *bio, sector_t sector)
139 {
140         int sectors = bio_sectors(bio);
141         if (bio->bi_iter.bi_sector + sectors < sector + STRIPE_SECTORS)
142                 return bio->bi_next;
143         else
144                 return NULL;
145 }
146
147 /*
148  * We maintain a biased count of active stripes in the bottom 16 bits of
149  * bi_phys_segments, and a count of processed stripes in the upper 16 bits
150  */
151 static inline int raid5_bi_processed_stripes(struct bio *bio)
152 {
153         atomic_t *segments = (atomic_t *)&bio->bi_phys_segments;
154         return (atomic_read(segments) >> 16) & 0xffff;
155 }
156
157 static inline int raid5_dec_bi_active_stripes(struct bio *bio)
158 {
159         atomic_t *segments = (atomic_t *)&bio->bi_phys_segments;
160         return atomic_sub_return(1, segments) & 0xffff;
161 }
162
163 static inline void raid5_inc_bi_active_stripes(struct bio *bio)
164 {
165         atomic_t *segments = (atomic_t *)&bio->bi_phys_segments;
166         atomic_inc(segments);
167 }
168
169 static inline void raid5_set_bi_processed_stripes(struct bio *bio,
170         unsigned int cnt)
171 {
172         atomic_t *segments = (atomic_t *)&bio->bi_phys_segments;
173         int old, new;
174
175         do {
176                 old = atomic_read(segments);
177                 new = (old & 0xffff) | (cnt << 16);
178         } while (atomic_cmpxchg(segments, old, new) != old);
179 }
180
181 static inline void raid5_set_bi_stripes(struct bio *bio, unsigned int cnt)
182 {
183         atomic_t *segments = (atomic_t *)&bio->bi_phys_segments;
184         atomic_set(segments, cnt);
185 }
186
187 /* Find first data disk in a raid6 stripe */
188 static inline int raid6_d0(struct stripe_head *sh)
189 {
190         if (sh->ddf_layout)
191                 /* ddf always start from first device */
192                 return 0;
193         /* md starts just after Q block */
194         if (sh->qd_idx == sh->disks - 1)
195                 return 0;
196         else
197                 return sh->qd_idx + 1;
198 }
199 static inline int raid6_next_disk(int disk, int raid_disks)
200 {
201         disk++;
202         return (disk < raid_disks) ? disk : 0;
203 }
204
205 /* When walking through the disks in a raid5, starting at raid6_d0,
206  * We need to map each disk to a 'slot', where the data disks are slot
207  * 0 .. raid_disks-3, the parity disk is raid_disks-2 and the Q disk
208  * is raid_disks-1.  This help does that mapping.
209  */
210 static int raid6_idx_to_slot(int idx, struct stripe_head *sh,
211                              int *count, int syndrome_disks)
212 {
213         int slot = *count;
214
215         if (sh->ddf_layout)
216                 (*count)++;
217         if (idx == sh->pd_idx)
218                 return syndrome_disks;
219         if (idx == sh->qd_idx)
220                 return syndrome_disks + 1;
221         if (!sh->ddf_layout)
222                 (*count)++;
223         return slot;
224 }
225
226 static void return_io(struct bio_list *return_bi)
227 {
228         struct bio *bi;
229         while ((bi = bio_list_pop(return_bi)) != NULL) {
230                 bi->bi_iter.bi_size = 0;
231                 trace_block_bio_complete(bdev_get_queue(bi->bi_bdev),
232                                          bi, 0);
233                 bio_endio(bi);
234         }
235 }
236
237 static void print_raid5_conf (struct r5conf *conf);
238
239 static int stripe_operations_active(struct stripe_head *sh)
240 {
241         return sh->check_state || sh->reconstruct_state ||
242                test_bit(STRIPE_BIOFILL_RUN, &sh->state) ||
243                test_bit(STRIPE_COMPUTE_RUN, &sh->state);
244 }
245
246 static void raid5_wakeup_stripe_thread(struct stripe_head *sh)
247 {
248         struct r5conf *conf = sh->raid_conf;
249         struct r5worker_group *group;
250         int thread_cnt;
251         int i, cpu = sh->cpu;
252
253         if (!cpu_online(cpu)) {
254                 cpu = cpumask_any(cpu_online_mask);
255                 sh->cpu = cpu;
256         }
257
258         if (list_empty(&sh->lru)) {
259                 struct r5worker_group *group;
260                 group = conf->worker_groups + cpu_to_group(cpu);
261                 list_add_tail(&sh->lru, &group->handle_list);
262                 group->stripes_cnt++;
263                 sh->group = group;
264         }
265
266         if (conf->worker_cnt_per_group == 0) {
267                 md_wakeup_thread(conf->mddev->thread);
268                 return;
269         }
270
271         group = conf->worker_groups + cpu_to_group(sh->cpu);
272
273         group->workers[0].working = true;
274         /* at least one worker should run to avoid race */
275         queue_work_on(sh->cpu, raid5_wq, &group->workers[0].work);
276
277         thread_cnt = group->stripes_cnt / MAX_STRIPE_BATCH - 1;
278         /* wakeup more workers */
279         for (i = 1; i < conf->worker_cnt_per_group && thread_cnt > 0; i++) {
280                 if (group->workers[i].working == false) {
281                         group->workers[i].working = true;
282                         queue_work_on(sh->cpu, raid5_wq,
283                                       &group->workers[i].work);
284                         thread_cnt--;
285                 }
286         }
287 }
288
289 static void do_release_stripe(struct r5conf *conf, struct stripe_head *sh,
290                               struct list_head *temp_inactive_list)
291 {
292         BUG_ON(!list_empty(&sh->lru));
293         BUG_ON(atomic_read(&conf->active_stripes)==0);
294         if (test_bit(STRIPE_HANDLE, &sh->state)) {
295                 if (test_bit(STRIPE_DELAYED, &sh->state) &&
296                     !test_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
297                         list_add_tail(&sh->lru, &conf->delayed_list);
298                 else if (test_bit(STRIPE_BIT_DELAY, &sh->state) &&
299                            sh->bm_seq - conf->seq_write > 0)
300                         list_add_tail(&sh->lru, &conf->bitmap_list);
301                 else {
302                         clear_bit(STRIPE_DELAYED, &sh->state);
303                         clear_bit(STRIPE_BIT_DELAY, &sh->state);
304                         if (conf->worker_cnt_per_group == 0) {
305                                 list_add_tail(&sh->lru, &conf->handle_list);
306                         } else {
307                                 raid5_wakeup_stripe_thread(sh);
308                                 return;
309                         }
310                 }
311                 md_wakeup_thread(conf->mddev->thread);
312         } else {
313                 BUG_ON(stripe_operations_active(sh));
314                 if (test_and_clear_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
315                         if (atomic_dec_return(&conf->preread_active_stripes)
316                             < IO_THRESHOLD)
317                                 md_wakeup_thread(conf->mddev->thread);
318                 atomic_dec(&conf->active_stripes);
319                 if (!test_bit(STRIPE_EXPANDING, &sh->state))
320                         list_add_tail(&sh->lru, temp_inactive_list);
321         }
322 }
323
324 static void __release_stripe(struct r5conf *conf, struct stripe_head *sh,
325                              struct list_head *temp_inactive_list)
326 {
327         if (atomic_dec_and_test(&sh->count))
328                 do_release_stripe(conf, sh, temp_inactive_list);
329 }
330
331 /*
332  * @hash could be NR_STRIPE_HASH_LOCKS, then we have a list of inactive_list
333  *
334  * Be careful: Only one task can add/delete stripes from temp_inactive_list at
335  * given time. Adding stripes only takes device lock, while deleting stripes
336  * only takes hash lock.
337  */
338 static void release_inactive_stripe_list(struct r5conf *conf,
339                                          struct list_head *temp_inactive_list,
340                                          int hash)
341 {
342         int size;
343         unsigned long do_wakeup = 0;
344         int i = 0;
345         unsigned long flags;
346
347         if (hash == NR_STRIPE_HASH_LOCKS) {
348                 size = NR_STRIPE_HASH_LOCKS;
349                 hash = NR_STRIPE_HASH_LOCKS - 1;
350         } else
351                 size = 1;
352         while (size) {
353                 struct list_head *list = &temp_inactive_list[size - 1];
354
355                 /*
356                  * We don't hold any lock here yet, get_active_stripe() might
357                  * remove stripes from the list
358                  */
359                 if (!list_empty_careful(list)) {
360                         spin_lock_irqsave(conf->hash_locks + hash, flags);
361                         if (list_empty(conf->inactive_list + hash) &&
362                             !list_empty(list))
363                                 atomic_dec(&conf->empty_inactive_list_nr);
364                         list_splice_tail_init(list, conf->inactive_list + hash);
365                         do_wakeup |= 1 << hash;
366                         spin_unlock_irqrestore(conf->hash_locks + hash, flags);
367                 }
368                 size--;
369                 hash--;
370         }
371
372         for (i = 0; i < NR_STRIPE_HASH_LOCKS; i++) {
373                 if (do_wakeup & (1 << i))
374                         wake_up(&conf->wait_for_stripe[i]);
375         }
376
377         if (do_wakeup) {
378                 if (atomic_read(&conf->active_stripes) == 0)
379                         wake_up(&conf->wait_for_quiescent);
380                 if (conf->retry_read_aligned)
381                         md_wakeup_thread(conf->mddev->thread);
382         }
383 }
384
385 /* should hold conf->device_lock already */
386 static int release_stripe_list(struct r5conf *conf,
387                                struct list_head *temp_inactive_list)
388 {
389         struct stripe_head *sh;
390         int count = 0;
391         struct llist_node *head;
392
393         head = llist_del_all(&conf->released_stripes);
394         head = llist_reverse_order(head);
395         while (head) {
396                 int hash;
397
398                 sh = llist_entry(head, struct stripe_head, release_list);
399                 head = llist_next(head);
400                 /* sh could be readded after STRIPE_ON_RELEASE_LIST is cleard */
401                 smp_mb();
402                 clear_bit(STRIPE_ON_RELEASE_LIST, &sh->state);
403                 /*
404                  * Don't worry the bit is set here, because if the bit is set
405                  * again, the count is always > 1. This is true for
406                  * STRIPE_ON_UNPLUG_LIST bit too.
407                  */
408                 hash = sh->hash_lock_index;
409                 __release_stripe(conf, sh, &temp_inactive_list[hash]);
410                 count++;
411         }
412
413         return count;
414 }
415
416 static void release_stripe(struct stripe_head *sh)
417 {
418         struct r5conf *conf = sh->raid_conf;
419         unsigned long flags;
420         struct list_head list;
421         int hash;
422         bool wakeup;
423
424         /* Avoid release_list until the last reference.
425          */
426         if (atomic_add_unless(&sh->count, -1, 1))
427                 return;
428
429         if (unlikely(!conf->mddev->thread) ||
430                 test_and_set_bit(STRIPE_ON_RELEASE_LIST, &sh->state))
431                 goto slow_path;
432         wakeup = llist_add(&sh->release_list, &conf->released_stripes);
433         if (wakeup)
434                 md_wakeup_thread(conf->mddev->thread);
435         return;
436 slow_path:
437         local_irq_save(flags);
438         /* we are ok here if STRIPE_ON_RELEASE_LIST is set or not */
439         if (atomic_dec_and_lock(&sh->count, &conf->device_lock)) {
440                 INIT_LIST_HEAD(&list);
441                 hash = sh->hash_lock_index;
442                 do_release_stripe(conf, sh, &list);
443                 spin_unlock(&conf->device_lock);
444                 release_inactive_stripe_list(conf, &list, hash);
445         }
446         local_irq_restore(flags);
447 }
448
449 static inline void remove_hash(struct stripe_head *sh)
450 {
451         pr_debug("remove_hash(), stripe %llu\n",
452                 (unsigned long long)sh->sector);
453
454         hlist_del_init(&sh->hash);
455 }
456
457 static inline void insert_hash(struct r5conf *conf, struct stripe_head *sh)
458 {
459         struct hlist_head *hp = stripe_hash(conf, sh->sector);
460
461         pr_debug("insert_hash(), stripe %llu\n",
462                 (unsigned long long)sh->sector);
463
464         hlist_add_head(&sh->hash, hp);
465 }
466
467 /* find an idle stripe, make sure it is unhashed, and return it. */
468 static struct stripe_head *get_free_stripe(struct r5conf *conf, int hash)
469 {
470         struct stripe_head *sh = NULL;
471         struct list_head *first;
472
473         if (list_empty(conf->inactive_list + hash))
474                 goto out;
475         first = (conf->inactive_list + hash)->next;
476         sh = list_entry(first, struct stripe_head, lru);
477         list_del_init(first);
478         remove_hash(sh);
479         atomic_inc(&conf->active_stripes);
480         BUG_ON(hash != sh->hash_lock_index);
481         if (list_empty(conf->inactive_list + hash))
482                 atomic_inc(&conf->empty_inactive_list_nr);
483 out:
484         return sh;
485 }
486
487 static void shrink_buffers(struct stripe_head *sh)
488 {
489         struct page *p;
490         int i;
491         int num = sh->raid_conf->pool_size;
492
493         for (i = 0; i < num ; i++) {
494                 WARN_ON(sh->dev[i].page != sh->dev[i].orig_page);
495                 p = sh->dev[i].page;
496                 if (!p)
497                         continue;
498                 sh->dev[i].page = NULL;
499                 put_page(p);
500         }
501 }
502
503 static int grow_buffers(struct stripe_head *sh, gfp_t gfp)
504 {
505         int i;
506         int num = sh->raid_conf->pool_size;
507
508         for (i = 0; i < num; i++) {
509                 struct page *page;
510
511                 if (!(page = alloc_page(gfp))) {
512                         return 1;
513                 }
514                 sh->dev[i].page = page;
515                 sh->dev[i].orig_page = page;
516         }
517         return 0;
518 }
519
520 static void raid5_build_block(struct stripe_head *sh, int i, int previous);
521 static void stripe_set_idx(sector_t stripe, struct r5conf *conf, int previous,
522                             struct stripe_head *sh);
523
524 static void init_stripe(struct stripe_head *sh, sector_t sector, int previous)
525 {
526         struct r5conf *conf = sh->raid_conf;
527         int i, seq;
528
529         BUG_ON(atomic_read(&sh->count) != 0);
530         BUG_ON(test_bit(STRIPE_HANDLE, &sh->state));
531         BUG_ON(stripe_operations_active(sh));
532         BUG_ON(sh->batch_head);
533
534         pr_debug("init_stripe called, stripe %llu\n",
535                 (unsigned long long)sector);
536 retry:
537         seq = read_seqcount_begin(&conf->gen_lock);
538         sh->generation = conf->generation - previous;
539         sh->disks = previous ? conf->previous_raid_disks : conf->raid_disks;
540         sh->sector = sector;
541         stripe_set_idx(sector, conf, previous, sh);
542         sh->state = 0;
543
544         for (i = sh->disks; i--; ) {
545                 struct r5dev *dev = &sh->dev[i];
546
547                 if (dev->toread || dev->read || dev->towrite || dev->written ||
548                     test_bit(R5_LOCKED, &dev->flags)) {
549                         printk(KERN_ERR "sector=%llx i=%d %p %p %p %p %d\n",
550                                (unsigned long long)sh->sector, i, dev->toread,
551                                dev->read, dev->towrite, dev->written,
552                                test_bit(R5_LOCKED, &dev->flags));
553                         WARN_ON(1);
554                 }
555                 dev->flags = 0;
556                 raid5_build_block(sh, i, previous);
557         }
558         if (read_seqcount_retry(&conf->gen_lock, seq))
559                 goto retry;
560         sh->overwrite_disks = 0;
561         insert_hash(conf, sh);
562         sh->cpu = smp_processor_id();
563         set_bit(STRIPE_BATCH_READY, &sh->state);
564 }
565
566 static struct stripe_head *__find_stripe(struct r5conf *conf, sector_t sector,
567                                          short generation)
568 {
569         struct stripe_head *sh;
570
571         pr_debug("__find_stripe, sector %llu\n", (unsigned long long)sector);
572         hlist_for_each_entry(sh, stripe_hash(conf, sector), hash)
573                 if (sh->sector == sector && sh->generation == generation)
574                         return sh;
575         pr_debug("__stripe %llu not in cache\n", (unsigned long long)sector);
576         return NULL;
577 }
578
579 /*
580  * Need to check if array has failed when deciding whether to:
581  *  - start an array
582  *  - remove non-faulty devices
583  *  - add a spare
584  *  - allow a reshape
585  * This determination is simple when no reshape is happening.
586  * However if there is a reshape, we need to carefully check
587  * both the before and after sections.
588  * This is because some failed devices may only affect one
589  * of the two sections, and some non-in_sync devices may
590  * be insync in the section most affected by failed devices.
591  */
592 static int calc_degraded(struct r5conf *conf)
593 {
594         int degraded, degraded2;
595         int i;
596
597         rcu_read_lock();
598         degraded = 0;
599         for (i = 0; i < conf->previous_raid_disks; i++) {
600                 struct md_rdev *rdev = rcu_dereference(conf->disks[i].rdev);
601                 if (rdev && test_bit(Faulty, &rdev->flags))
602                         rdev = rcu_dereference(conf->disks[i].replacement);
603                 if (!rdev || test_bit(Faulty, &rdev->flags))
604                         degraded++;
605                 else if (test_bit(In_sync, &rdev->flags))
606                         ;
607                 else
608                         /* not in-sync or faulty.
609                          * If the reshape increases the number of devices,
610                          * this is being recovered by the reshape, so
611                          * this 'previous' section is not in_sync.
612                          * If the number of devices is being reduced however,
613                          * the device can only be part of the array if
614                          * we are reverting a reshape, so this section will
615                          * be in-sync.
616                          */
617                         if (conf->raid_disks >= conf->previous_raid_disks)
618                                 degraded++;
619         }
620         rcu_read_unlock();
621         if (conf->raid_disks == conf->previous_raid_disks)
622                 return degraded;
623         rcu_read_lock();
624         degraded2 = 0;
625         for (i = 0; i < conf->raid_disks; i++) {
626                 struct md_rdev *rdev = rcu_dereference(conf->disks[i].rdev);
627                 if (rdev && test_bit(Faulty, &rdev->flags))
628                         rdev = rcu_dereference(conf->disks[i].replacement);
629                 if (!rdev || test_bit(Faulty, &rdev->flags))
630                         degraded2++;
631                 else if (test_bit(In_sync, &rdev->flags))
632                         ;
633                 else
634                         /* not in-sync or faulty.
635                          * If reshape increases the number of devices, this
636                          * section has already been recovered, else it
637                          * almost certainly hasn't.
638                          */
639                         if (conf->raid_disks <= conf->previous_raid_disks)
640                                 degraded2++;
641         }
642         rcu_read_unlock();
643         if (degraded2 > degraded)
644                 return degraded2;
645         return degraded;
646 }
647
648 static int has_failed(struct r5conf *conf)
649 {
650         int degraded;
651
652         if (conf->mddev->reshape_position == MaxSector)
653                 return conf->mddev->degraded > conf->max_degraded;
654
655         degraded = calc_degraded(conf);
656         if (degraded > conf->max_degraded)
657                 return 1;
658         return 0;
659 }
660
661 static struct stripe_head *
662 get_active_stripe(struct r5conf *conf, sector_t sector,
663                   int previous, int noblock, int noquiesce)
664 {
665         struct stripe_head *sh;
666         int hash = stripe_hash_locks_hash(sector);
667
668         pr_debug("get_stripe, sector %llu\n", (unsigned long long)sector);
669
670         spin_lock_irq(conf->hash_locks + hash);
671
672         do {
673                 wait_event_lock_irq(conf->wait_for_quiescent,
674                                     conf->quiesce == 0 || noquiesce,
675                                     *(conf->hash_locks + hash));
676                 sh = __find_stripe(conf, sector, conf->generation - previous);
677                 if (!sh) {
678                         if (!test_bit(R5_INACTIVE_BLOCKED, &conf->cache_state)) {
679                                 sh = get_free_stripe(conf, hash);
680                                 if (!sh && !test_bit(R5_DID_ALLOC,
681                                                      &conf->cache_state))
682                                         set_bit(R5_ALLOC_MORE,
683                                                 &conf->cache_state);
684                         }
685                         if (noblock && sh == NULL)
686                                 break;
687                         if (!sh) {
688                                 set_bit(R5_INACTIVE_BLOCKED,
689                                         &conf->cache_state);
690                                 wait_event_exclusive_cmd(
691                                         conf->wait_for_stripe[hash],
692                                         !list_empty(conf->inactive_list + hash) &&
693                                         (atomic_read(&conf->active_stripes)
694                                          < (conf->max_nr_stripes * 3 / 4)
695                                          || !test_bit(R5_INACTIVE_BLOCKED,
696                                                       &conf->cache_state)),
697                                         spin_unlock_irq(conf->hash_locks + hash),
698                                         spin_lock_irq(conf->hash_locks + hash));
699                                 clear_bit(R5_INACTIVE_BLOCKED,
700                                           &conf->cache_state);
701                         } else {
702                                 init_stripe(sh, sector, previous);
703                                 atomic_inc(&sh->count);
704                         }
705                 } else if (!atomic_inc_not_zero(&sh->count)) {
706                         spin_lock(&conf->device_lock);
707                         if (!atomic_read(&sh->count)) {
708                                 if (!test_bit(STRIPE_HANDLE, &sh->state))
709                                         atomic_inc(&conf->active_stripes);
710                                 BUG_ON(list_empty(&sh->lru) &&
711                                        !test_bit(STRIPE_EXPANDING, &sh->state));
712                                 list_del_init(&sh->lru);
713                                 if (sh->group) {
714                                         sh->group->stripes_cnt--;
715                                         sh->group = NULL;
716                                 }
717                         }
718                         atomic_inc(&sh->count);
719                         spin_unlock(&conf->device_lock);
720                 }
721         } while (sh == NULL);
722
723         if (!list_empty(conf->inactive_list + hash))
724                 wake_up(&conf->wait_for_stripe[hash]);
725
726         spin_unlock_irq(conf->hash_locks + hash);
727         return sh;
728 }
729
730 static bool is_full_stripe_write(struct stripe_head *sh)
731 {
732         BUG_ON(sh->overwrite_disks > (sh->disks - sh->raid_conf->max_degraded));
733         return sh->overwrite_disks == (sh->disks - sh->raid_conf->max_degraded);
734 }
735
736 static void lock_two_stripes(struct stripe_head *sh1, struct stripe_head *sh2)
737 {
738         local_irq_disable();
739         if (sh1 > sh2) {
740                 spin_lock(&sh2->stripe_lock);
741                 spin_lock_nested(&sh1->stripe_lock, 1);
742         } else {
743                 spin_lock(&sh1->stripe_lock);
744                 spin_lock_nested(&sh2->stripe_lock, 1);
745         }
746 }
747
748 static void unlock_two_stripes(struct stripe_head *sh1, struct stripe_head *sh2)
749 {
750         spin_unlock(&sh1->stripe_lock);
751         spin_unlock(&sh2->stripe_lock);
752         local_irq_enable();
753 }
754
755 /* Only freshly new full stripe normal write stripe can be added to a batch list */
756 static bool stripe_can_batch(struct stripe_head *sh)
757 {
758         return test_bit(STRIPE_BATCH_READY, &sh->state) &&
759                 !test_bit(STRIPE_BITMAP_PENDING, &sh->state) &&
760                 is_full_stripe_write(sh);
761 }
762
763 /* we only do back search */
764 static void stripe_add_to_batch_list(struct r5conf *conf, struct stripe_head *sh)
765 {
766         struct stripe_head *head;
767         sector_t head_sector, tmp_sec;
768         int hash;
769         int dd_idx;
770
771         if (!stripe_can_batch(sh))
772                 return;
773         /* Don't cross chunks, so stripe pd_idx/qd_idx is the same */
774         tmp_sec = sh->sector;
775         if (!sector_div(tmp_sec, conf->chunk_sectors))
776                 return;
777         head_sector = sh->sector - STRIPE_SECTORS;
778
779         hash = stripe_hash_locks_hash(head_sector);
780         spin_lock_irq(conf->hash_locks + hash);
781         head = __find_stripe(conf, head_sector, conf->generation);
782         if (head && !atomic_inc_not_zero(&head->count)) {
783                 spin_lock(&conf->device_lock);
784                 if (!atomic_read(&head->count)) {
785                         if (!test_bit(STRIPE_HANDLE, &head->state))
786                                 atomic_inc(&conf->active_stripes);
787                         BUG_ON(list_empty(&head->lru) &&
788                                !test_bit(STRIPE_EXPANDING, &head->state));
789                         list_del_init(&head->lru);
790                         if (head->group) {
791                                 head->group->stripes_cnt--;
792                                 head->group = NULL;
793                         }
794                 }
795                 atomic_inc(&head->count);
796                 spin_unlock(&conf->device_lock);
797         }
798         spin_unlock_irq(conf->hash_locks + hash);
799
800         if (!head)
801                 return;
802         if (!stripe_can_batch(head))
803                 goto out;
804
805         lock_two_stripes(head, sh);
806         /* clear_batch_ready clear the flag */
807         if (!stripe_can_batch(head) || !stripe_can_batch(sh))
808                 goto unlock_out;
809
810         if (sh->batch_head)
811                 goto unlock_out;
812
813         dd_idx = 0;
814         while (dd_idx == sh->pd_idx || dd_idx == sh->qd_idx)
815                 dd_idx++;
816         if (head->dev[dd_idx].towrite->bi_rw != sh->dev[dd_idx].towrite->bi_rw)
817                 goto unlock_out;
818
819         if (head->batch_head) {
820                 spin_lock(&head->batch_head->batch_lock);
821                 /* This batch list is already running */
822                 if (!stripe_can_batch(head)) {
823                         spin_unlock(&head->batch_head->batch_lock);
824                         goto unlock_out;
825                 }
826
827                 /*
828                  * at this point, head's BATCH_READY could be cleared, but we
829                  * can still add the stripe to batch list
830                  */
831                 list_add(&sh->batch_list, &head->batch_list);
832                 spin_unlock(&head->batch_head->batch_lock);
833
834                 sh->batch_head = head->batch_head;
835         } else {
836                 head->batch_head = head;
837                 sh->batch_head = head->batch_head;
838                 spin_lock(&head->batch_lock);
839                 list_add_tail(&sh->batch_list, &head->batch_list);
840                 spin_unlock(&head->batch_lock);
841         }
842
843         if (test_and_clear_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
844                 if (atomic_dec_return(&conf->preread_active_stripes)
845                     < IO_THRESHOLD)
846                         md_wakeup_thread(conf->mddev->thread);
847
848         if (test_and_clear_bit(STRIPE_BIT_DELAY, &sh->state)) {
849                 int seq = sh->bm_seq;
850                 if (test_bit(STRIPE_BIT_DELAY, &sh->batch_head->state) &&
851                     sh->batch_head->bm_seq > seq)
852                         seq = sh->batch_head->bm_seq;
853                 set_bit(STRIPE_BIT_DELAY, &sh->batch_head->state);
854                 sh->batch_head->bm_seq = seq;
855         }
856
857         atomic_inc(&sh->count);
858 unlock_out:
859         unlock_two_stripes(head, sh);
860 out:
861         release_stripe(head);
862 }
863
864 /* Determine if 'data_offset' or 'new_data_offset' should be used
865  * in this stripe_head.
866  */
867 static int use_new_offset(struct r5conf *conf, struct stripe_head *sh)
868 {
869         sector_t progress = conf->reshape_progress;
870         /* Need a memory barrier to make sure we see the value
871          * of conf->generation, or ->data_offset that was set before
872          * reshape_progress was updated.
873          */
874         smp_rmb();
875         if (progress == MaxSector)
876                 return 0;
877         if (sh->generation == conf->generation - 1)
878                 return 0;
879         /* We are in a reshape, and this is a new-generation stripe,
880          * so use new_data_offset.
881          */
882         return 1;
883 }
884
885 static void
886 raid5_end_read_request(struct bio *bi);
887 static void
888 raid5_end_write_request(struct bio *bi);
889
890 static void ops_run_io(struct stripe_head *sh, struct stripe_head_state *s)
891 {
892         struct r5conf *conf = sh->raid_conf;
893         int i, disks = sh->disks;
894         struct stripe_head *head_sh = sh;
895
896         might_sleep();
897
898         for (i = disks; i--; ) {
899                 int rw;
900                 int replace_only = 0;
901                 struct bio *bi, *rbi;
902                 struct md_rdev *rdev, *rrdev = NULL;
903
904                 sh = head_sh;
905                 if (test_and_clear_bit(R5_Wantwrite, &sh->dev[i].flags)) {
906                         if (test_and_clear_bit(R5_WantFUA, &sh->dev[i].flags))
907                                 rw = WRITE_FUA;
908                         else
909                                 rw = WRITE;
910                         if (test_bit(R5_Discard, &sh->dev[i].flags))
911                                 rw |= REQ_DISCARD;
912                 } else if (test_and_clear_bit(R5_Wantread, &sh->dev[i].flags))
913                         rw = READ;
914                 else if (test_and_clear_bit(R5_WantReplace,
915                                             &sh->dev[i].flags)) {
916                         rw = WRITE;
917                         replace_only = 1;
918                 } else
919                         continue;
920                 if (test_and_clear_bit(R5_SyncIO, &sh->dev[i].flags))
921                         rw |= REQ_SYNC;
922
923 again:
924                 bi = &sh->dev[i].req;
925                 rbi = &sh->dev[i].rreq; /* For writing to replacement */
926
927                 rcu_read_lock();
928                 rrdev = rcu_dereference(conf->disks[i].replacement);
929                 smp_mb(); /* Ensure that if rrdev is NULL, rdev won't be */
930                 rdev = rcu_dereference(conf->disks[i].rdev);
931                 if (!rdev) {
932                         rdev = rrdev;
933                         rrdev = NULL;
934                 }
935                 if (rw & WRITE) {
936                         if (replace_only)
937                                 rdev = NULL;
938                         if (rdev == rrdev)
939                                 /* We raced and saw duplicates */
940                                 rrdev = NULL;
941                 } else {
942                         if (test_bit(R5_ReadRepl, &head_sh->dev[i].flags) && rrdev)
943                                 rdev = rrdev;
944                         rrdev = NULL;
945                 }
946
947                 if (rdev && test_bit(Faulty, &rdev->flags))
948                         rdev = NULL;
949                 if (rdev)
950                         atomic_inc(&rdev->nr_pending);
951                 if (rrdev && test_bit(Faulty, &rrdev->flags))
952                         rrdev = NULL;
953                 if (rrdev)
954                         atomic_inc(&rrdev->nr_pending);
955                 rcu_read_unlock();
956
957                 /* We have already checked bad blocks for reads.  Now
958                  * need to check for writes.  We never accept write errors
959                  * on the replacement, so we don't to check rrdev.
960                  */
961                 while ((rw & WRITE) && rdev &&
962                        test_bit(WriteErrorSeen, &rdev->flags)) {
963                         sector_t first_bad;
964                         int bad_sectors;
965                         int bad = is_badblock(rdev, sh->sector, STRIPE_SECTORS,
966                                               &first_bad, &bad_sectors);
967                         if (!bad)
968                                 break;
969
970                         if (bad < 0) {
971                                 set_bit(BlockedBadBlocks, &rdev->flags);
972                                 if (!conf->mddev->external &&
973                                     conf->mddev->flags) {
974                                         /* It is very unlikely, but we might
975                                          * still need to write out the
976                                          * bad block log - better give it
977                                          * a chance*/
978                                         md_check_recovery(conf->mddev);
979                                 }
980                                 /*
981                                  * Because md_wait_for_blocked_rdev
982                                  * will dec nr_pending, we must
983                                  * increment it first.
984                                  */
985                                 atomic_inc(&rdev->nr_pending);
986                                 md_wait_for_blocked_rdev(rdev, conf->mddev);
987                         } else {
988                                 /* Acknowledged bad block - skip the write */
989                                 rdev_dec_pending(rdev, conf->mddev);
990                                 rdev = NULL;
991                         }
992                 }
993
994                 if (rdev) {
995                         if (s->syncing || s->expanding || s->expanded
996                             || s->replacing)
997                                 md_sync_acct(rdev->bdev, STRIPE_SECTORS);
998
999                         set_bit(STRIPE_IO_STARTED, &sh->state);
1000
1001                         bio_reset(bi);
1002                         bi->bi_bdev = rdev->bdev;
1003                         bi->bi_rw = rw;
1004                         bi->bi_end_io = (rw & WRITE)
1005                                 ? raid5_end_write_request
1006                                 : raid5_end_read_request;
1007                         bi->bi_private = sh;
1008
1009                         pr_debug("%s: for %llu schedule op %ld on disc %d\n",
1010                                 __func__, (unsigned long long)sh->sector,
1011                                 bi->bi_rw, i);
1012                         atomic_inc(&sh->count);
1013                         if (sh != head_sh)
1014                                 atomic_inc(&head_sh->count);
1015                         if (use_new_offset(conf, sh))
1016                                 bi->bi_iter.bi_sector = (sh->sector
1017                                                  + rdev->new_data_offset);
1018                         else
1019                                 bi->bi_iter.bi_sector = (sh->sector
1020                                                  + rdev->data_offset);
1021                         if (test_bit(R5_ReadNoMerge, &head_sh->dev[i].flags))
1022                                 bi->bi_rw |= REQ_NOMERGE;
1023
1024                         if (test_bit(R5_SkipCopy, &sh->dev[i].flags))
1025                                 WARN_ON(test_bit(R5_UPTODATE, &sh->dev[i].flags));
1026                         sh->dev[i].vec.bv_page = sh->dev[i].page;
1027                         bi->bi_vcnt = 1;
1028                         bi->bi_io_vec[0].bv_len = STRIPE_SIZE;
1029                         bi->bi_io_vec[0].bv_offset = 0;
1030                         bi->bi_iter.bi_size = STRIPE_SIZE;
1031                         /*
1032                          * If this is discard request, set bi_vcnt 0. We don't
1033                          * want to confuse SCSI because SCSI will replace payload
1034                          */
1035                         if (rw & REQ_DISCARD)
1036                                 bi->bi_vcnt = 0;
1037                         if (rrdev)
1038                                 set_bit(R5_DOUBLE_LOCKED, &sh->dev[i].flags);
1039
1040                         if (conf->mddev->gendisk)
1041                                 trace_block_bio_remap(bdev_get_queue(bi->bi_bdev),
1042                                                       bi, disk_devt(conf->mddev->gendisk),
1043                                                       sh->dev[i].sector);
1044                         generic_make_request(bi);
1045                 }
1046                 if (rrdev) {
1047                         if (s->syncing || s->expanding || s->expanded
1048                             || s->replacing)
1049                                 md_sync_acct(rrdev->bdev, STRIPE_SECTORS);
1050
1051                         set_bit(STRIPE_IO_STARTED, &sh->state);
1052
1053                         bio_reset(rbi);
1054                         rbi->bi_bdev = rrdev->bdev;
1055                         rbi->bi_rw = rw;
1056                         BUG_ON(!(rw & WRITE));
1057                         rbi->bi_end_io = raid5_end_write_request;
1058                         rbi->bi_private = sh;
1059
1060                         pr_debug("%s: for %llu schedule op %ld on "
1061                                  "replacement disc %d\n",
1062                                 __func__, (unsigned long long)sh->sector,
1063                                 rbi->bi_rw, i);
1064                         atomic_inc(&sh->count);
1065                         if (sh != head_sh)
1066                                 atomic_inc(&head_sh->count);
1067                         if (use_new_offset(conf, sh))
1068                                 rbi->bi_iter.bi_sector = (sh->sector
1069                                                   + rrdev->new_data_offset);
1070                         else
1071                                 rbi->bi_iter.bi_sector = (sh->sector
1072                                                   + rrdev->data_offset);
1073                         if (test_bit(R5_SkipCopy, &sh->dev[i].flags))
1074                                 WARN_ON(test_bit(R5_UPTODATE, &sh->dev[i].flags));
1075                         sh->dev[i].rvec.bv_page = sh->dev[i].page;
1076                         rbi->bi_vcnt = 1;
1077                         rbi->bi_io_vec[0].bv_len = STRIPE_SIZE;
1078                         rbi->bi_io_vec[0].bv_offset = 0;
1079                         rbi->bi_iter.bi_size = STRIPE_SIZE;
1080                         /*
1081                          * If this is discard request, set bi_vcnt 0. We don't
1082                          * want to confuse SCSI because SCSI will replace payload
1083                          */
1084                         if (rw & REQ_DISCARD)
1085                                 rbi->bi_vcnt = 0;
1086                         if (conf->mddev->gendisk)
1087                                 trace_block_bio_remap(bdev_get_queue(rbi->bi_bdev),
1088                                                       rbi, disk_devt(conf->mddev->gendisk),
1089                                                       sh->dev[i].sector);
1090                         generic_make_request(rbi);
1091                 }
1092                 if (!rdev && !rrdev) {
1093                         if (rw & WRITE)
1094                                 set_bit(STRIPE_DEGRADED, &sh->state);
1095                         pr_debug("skip op %ld on disc %d for sector %llu\n",
1096                                 bi->bi_rw, i, (unsigned long long)sh->sector);
1097                         clear_bit(R5_LOCKED, &sh->dev[i].flags);
1098                         set_bit(STRIPE_HANDLE, &sh->state);
1099                 }
1100
1101                 if (!head_sh->batch_head)
1102                         continue;
1103                 sh = list_first_entry(&sh->batch_list, struct stripe_head,
1104                                       batch_list);
1105                 if (sh != head_sh)
1106                         goto again;
1107         }
1108 }
1109
1110 static struct dma_async_tx_descriptor *
1111 async_copy_data(int frombio, struct bio *bio, struct page **page,
1112         sector_t sector, struct dma_async_tx_descriptor *tx,
1113         struct stripe_head *sh)
1114 {
1115         struct bio_vec bvl;
1116         struct bvec_iter iter;
1117         struct page *bio_page;
1118         int page_offset;
1119         struct async_submit_ctl submit;
1120         enum async_tx_flags flags = 0;
1121
1122         if (bio->bi_iter.bi_sector >= sector)
1123                 page_offset = (signed)(bio->bi_iter.bi_sector - sector) * 512;
1124         else
1125                 page_offset = (signed)(sector - bio->bi_iter.bi_sector) * -512;
1126
1127         if (frombio)
1128                 flags |= ASYNC_TX_FENCE;
1129         init_async_submit(&submit, flags, tx, NULL, NULL, NULL);
1130
1131         bio_for_each_segment(bvl, bio, iter) {
1132                 int len = bvl.bv_len;
1133                 int clen;
1134                 int b_offset = 0;
1135
1136                 if (page_offset < 0) {
1137                         b_offset = -page_offset;
1138                         page_offset += b_offset;
1139                         len -= b_offset;
1140                 }
1141
1142                 if (len > 0 && page_offset + len > STRIPE_SIZE)
1143                         clen = STRIPE_SIZE - page_offset;
1144                 else
1145                         clen = len;
1146
1147                 if (clen > 0) {
1148                         b_offset += bvl.bv_offset;
1149                         bio_page = bvl.bv_page;
1150                         if (frombio) {
1151                                 if (sh->raid_conf->skip_copy &&
1152                                     b_offset == 0 && page_offset == 0 &&
1153                                     clen == STRIPE_SIZE)
1154                                         *page = bio_page;
1155                                 else
1156                                         tx = async_memcpy(*page, bio_page, page_offset,
1157                                                   b_offset, clen, &submit);
1158                         } else
1159                                 tx = async_memcpy(bio_page, *page, b_offset,
1160                                                   page_offset, clen, &submit);
1161                 }
1162                 /* chain the operations */
1163                 submit.depend_tx = tx;
1164
1165                 if (clen < len) /* hit end of page */
1166                         break;
1167                 page_offset +=  len;
1168         }
1169
1170         return tx;
1171 }
1172
1173 static void ops_complete_biofill(void *stripe_head_ref)
1174 {
1175         struct stripe_head *sh = stripe_head_ref;
1176         struct bio_list return_bi = BIO_EMPTY_LIST;
1177         int i;
1178
1179         pr_debug("%s: stripe %llu\n", __func__,
1180                 (unsigned long long)sh->sector);
1181
1182         /* clear completed biofills */
1183         for (i = sh->disks; i--; ) {
1184                 struct r5dev *dev = &sh->dev[i];
1185
1186                 /* acknowledge completion of a biofill operation */
1187                 /* and check if we need to reply to a read request,
1188                  * new R5_Wantfill requests are held off until
1189                  * !STRIPE_BIOFILL_RUN
1190                  */
1191                 if (test_and_clear_bit(R5_Wantfill, &dev->flags)) {
1192                         struct bio *rbi, *rbi2;
1193
1194                         BUG_ON(!dev->read);
1195                         rbi = dev->read;
1196                         dev->read = NULL;
1197                         while (rbi && rbi->bi_iter.bi_sector <
1198                                 dev->sector + STRIPE_SECTORS) {
1199                                 rbi2 = r5_next_bio(rbi, dev->sector);
1200                                 if (!raid5_dec_bi_active_stripes(rbi))
1201                                         bio_list_add(&return_bi, rbi);
1202                                 rbi = rbi2;
1203                         }
1204                 }
1205         }
1206         clear_bit(STRIPE_BIOFILL_RUN, &sh->state);
1207
1208         return_io(&return_bi);
1209
1210         set_bit(STRIPE_HANDLE, &sh->state);
1211         release_stripe(sh);
1212 }
1213
1214 static void ops_run_biofill(struct stripe_head *sh)
1215 {
1216         struct dma_async_tx_descriptor *tx = NULL;
1217         struct async_submit_ctl submit;
1218         int i;
1219
1220         BUG_ON(sh->batch_head);
1221         pr_debug("%s: stripe %llu\n", __func__,
1222                 (unsigned long long)sh->sector);
1223
1224         for (i = sh->disks; i--; ) {
1225                 struct r5dev *dev = &sh->dev[i];
1226                 if (test_bit(R5_Wantfill, &dev->flags)) {
1227                         struct bio *rbi;
1228                         spin_lock_irq(&sh->stripe_lock);
1229                         dev->read = rbi = dev->toread;
1230                         dev->toread = NULL;
1231                         spin_unlock_irq(&sh->stripe_lock);
1232                         while (rbi && rbi->bi_iter.bi_sector <
1233                                 dev->sector + STRIPE_SECTORS) {
1234                                 tx = async_copy_data(0, rbi, &dev->page,
1235                                         dev->sector, tx, sh);
1236                                 rbi = r5_next_bio(rbi, dev->sector);
1237                         }
1238                 }
1239         }
1240
1241         atomic_inc(&sh->count);
1242         init_async_submit(&submit, ASYNC_TX_ACK, tx, ops_complete_biofill, sh, NULL);
1243         async_trigger_callback(&submit);
1244 }
1245
1246 static void mark_target_uptodate(struct stripe_head *sh, int target)
1247 {
1248         struct r5dev *tgt;
1249
1250         if (target < 0)
1251                 return;
1252
1253         tgt = &sh->dev[target];
1254         set_bit(R5_UPTODATE, &tgt->flags);
1255         BUG_ON(!test_bit(R5_Wantcompute, &tgt->flags));
1256         clear_bit(R5_Wantcompute, &tgt->flags);
1257 }
1258
1259 static void ops_complete_compute(void *stripe_head_ref)
1260 {
1261         struct stripe_head *sh = stripe_head_ref;
1262
1263         pr_debug("%s: stripe %llu\n", __func__,
1264                 (unsigned long long)sh->sector);
1265
1266         /* mark the computed target(s) as uptodate */
1267         mark_target_uptodate(sh, sh->ops.target);
1268         mark_target_uptodate(sh, sh->ops.target2);
1269
1270         clear_bit(STRIPE_COMPUTE_RUN, &sh->state);
1271         if (sh->check_state == check_state_compute_run)
1272                 sh->check_state = check_state_compute_result;
1273         set_bit(STRIPE_HANDLE, &sh->state);
1274         release_stripe(sh);
1275 }
1276
1277 /* return a pointer to the address conversion region of the scribble buffer */
1278 static addr_conv_t *to_addr_conv(struct stripe_head *sh,
1279                                  struct raid5_percpu *percpu, int i)
1280 {
1281         void *addr;
1282
1283         addr = flex_array_get(percpu->scribble, i);
1284         return addr + sizeof(struct page *) * (sh->disks + 2);
1285 }
1286
1287 /* return a pointer to the address conversion region of the scribble buffer */
1288 static struct page **to_addr_page(struct raid5_percpu *percpu, int i)
1289 {
1290         void *addr;
1291
1292         addr = flex_array_get(percpu->scribble, i);
1293         return addr;
1294 }
1295
1296 static struct dma_async_tx_descriptor *
1297 ops_run_compute5(struct stripe_head *sh, struct raid5_percpu *percpu)
1298 {
1299         int disks = sh->disks;
1300         struct page **xor_srcs = to_addr_page(percpu, 0);
1301         int target = sh->ops.target;
1302         struct r5dev *tgt = &sh->dev[target];
1303         struct page *xor_dest = tgt->page;
1304         int count = 0;
1305         struct dma_async_tx_descriptor *tx;
1306         struct async_submit_ctl submit;
1307         int i;
1308
1309         BUG_ON(sh->batch_head);
1310
1311         pr_debug("%s: stripe %llu block: %d\n",
1312                 __func__, (unsigned long long)sh->sector, target);
1313         BUG_ON(!test_bit(R5_Wantcompute, &tgt->flags));
1314
1315         for (i = disks; i--; )
1316                 if (i != target)
1317                         xor_srcs[count++] = sh->dev[i].page;
1318
1319         atomic_inc(&sh->count);
1320
1321         init_async_submit(&submit, ASYNC_TX_FENCE|ASYNC_TX_XOR_ZERO_DST, NULL,
1322                           ops_complete_compute, sh, to_addr_conv(sh, percpu, 0));
1323         if (unlikely(count == 1))
1324                 tx = async_memcpy(xor_dest, xor_srcs[0], 0, 0, STRIPE_SIZE, &submit);
1325         else
1326                 tx = async_xor(xor_dest, xor_srcs, 0, count, STRIPE_SIZE, &submit);
1327
1328         return tx;
1329 }
1330
1331 /* set_syndrome_sources - populate source buffers for gen_syndrome
1332  * @srcs - (struct page *) array of size sh->disks
1333  * @sh - stripe_head to parse
1334  *
1335  * Populates srcs in proper layout order for the stripe and returns the
1336  * 'count' of sources to be used in a call to async_gen_syndrome.  The P
1337  * destination buffer is recorded in srcs[count] and the Q destination
1338  * is recorded in srcs[count+1]].
1339  */
1340 static int set_syndrome_sources(struct page **srcs,
1341                                 struct stripe_head *sh,
1342                                 int srctype)
1343 {
1344         int disks = sh->disks;
1345         int syndrome_disks = sh->ddf_layout ? disks : (disks - 2);
1346         int d0_idx = raid6_d0(sh);
1347         int count;
1348         int i;
1349
1350         for (i = 0; i < disks; i++)
1351                 srcs[i] = NULL;
1352
1353         count = 0;
1354         i = d0_idx;
1355         do {
1356                 int slot = raid6_idx_to_slot(i, sh, &count, syndrome_disks);
1357                 struct r5dev *dev = &sh->dev[i];
1358
1359                 if (i == sh->qd_idx || i == sh->pd_idx ||
1360                     (srctype == SYNDROME_SRC_ALL) ||
1361                     (srctype == SYNDROME_SRC_WANT_DRAIN &&
1362                      test_bit(R5_Wantdrain, &dev->flags)) ||
1363                     (srctype == SYNDROME_SRC_WRITTEN &&
1364                      dev->written))
1365                         srcs[slot] = sh->dev[i].page;
1366                 i = raid6_next_disk(i, disks);
1367         } while (i != d0_idx);
1368
1369         return syndrome_disks;
1370 }
1371
1372 static struct dma_async_tx_descriptor *
1373 ops_run_compute6_1(struct stripe_head *sh, struct raid5_percpu *percpu)
1374 {
1375         int disks = sh->disks;
1376         struct page **blocks = to_addr_page(percpu, 0);
1377         int target;
1378         int qd_idx = sh->qd_idx;
1379         struct dma_async_tx_descriptor *tx;
1380         struct async_submit_ctl submit;
1381         struct r5dev *tgt;
1382         struct page *dest;
1383         int i;
1384         int count;
1385
1386         BUG_ON(sh->batch_head);
1387         if (sh->ops.target < 0)
1388                 target = sh->ops.target2;
1389         else if (sh->ops.target2 < 0)
1390                 target = sh->ops.target;
1391         else
1392                 /* we should only have one valid target */
1393                 BUG();
1394         BUG_ON(target < 0);
1395         pr_debug("%s: stripe %llu block: %d\n",
1396                 __func__, (unsigned long long)sh->sector, target);
1397
1398         tgt = &sh->dev[target];
1399         BUG_ON(!test_bit(R5_Wantcompute, &tgt->flags));
1400         dest = tgt->page;
1401
1402         atomic_inc(&sh->count);
1403
1404         if (target == qd_idx) {
1405                 count = set_syndrome_sources(blocks, sh, SYNDROME_SRC_ALL);
1406                 blocks[count] = NULL; /* regenerating p is not necessary */
1407                 BUG_ON(blocks[count+1] != dest); /* q should already be set */
1408                 init_async_submit(&submit, ASYNC_TX_FENCE, NULL,
1409                                   ops_complete_compute, sh,
1410                                   to_addr_conv(sh, percpu, 0));
1411                 tx = async_gen_syndrome(blocks, 0, count+2, STRIPE_SIZE, &submit);
1412         } else {
1413                 /* Compute any data- or p-drive using XOR */
1414                 count = 0;
1415                 for (i = disks; i-- ; ) {
1416                         if (i == target || i == qd_idx)
1417                                 continue;
1418                         blocks[count++] = sh->dev[i].page;
1419                 }
1420
1421                 init_async_submit(&submit, ASYNC_TX_FENCE|ASYNC_TX_XOR_ZERO_DST,
1422                                   NULL, ops_complete_compute, sh,
1423                                   to_addr_conv(sh, percpu, 0));
1424                 tx = async_xor(dest, blocks, 0, count, STRIPE_SIZE, &submit);
1425         }
1426
1427         return tx;
1428 }
1429
1430 static struct dma_async_tx_descriptor *
1431 ops_run_compute6_2(struct stripe_head *sh, struct raid5_percpu *percpu)
1432 {
1433         int i, count, disks = sh->disks;
1434         int syndrome_disks = sh->ddf_layout ? disks : disks-2;
1435         int d0_idx = raid6_d0(sh);
1436         int faila = -1, failb = -1;
1437         int target = sh->ops.target;
1438         int target2 = sh->ops.target2;
1439         struct r5dev *tgt = &sh->dev[target];
1440         struct r5dev *tgt2 = &sh->dev[target2];
1441         struct dma_async_tx_descriptor *tx;
1442         struct page **blocks = to_addr_page(percpu, 0);
1443         struct async_submit_ctl submit;
1444
1445         BUG_ON(sh->batch_head);
1446         pr_debug("%s: stripe %llu block1: %d block2: %d\n",
1447                  __func__, (unsigned long long)sh->sector, target, target2);
1448         BUG_ON(target < 0 || target2 < 0);
1449         BUG_ON(!test_bit(R5_Wantcompute, &tgt->flags));
1450         BUG_ON(!test_bit(R5_Wantcompute, &tgt2->flags));
1451
1452         /* we need to open-code set_syndrome_sources to handle the
1453          * slot number conversion for 'faila' and 'failb'
1454          */
1455         for (i = 0; i < disks ; i++)
1456                 blocks[i] = NULL;
1457         count = 0;
1458         i = d0_idx;
1459         do {
1460                 int slot = raid6_idx_to_slot(i, sh, &count, syndrome_disks);
1461
1462                 blocks[slot] = sh->dev[i].page;
1463
1464                 if (i == target)
1465                         faila = slot;
1466                 if (i == target2)
1467                         failb = slot;
1468                 i = raid6_next_disk(i, disks);
1469         } while (i != d0_idx);
1470
1471         BUG_ON(faila == failb);
1472         if (failb < faila)
1473                 swap(faila, failb);
1474         pr_debug("%s: stripe: %llu faila: %d failb: %d\n",
1475                  __func__, (unsigned long long)sh->sector, faila, failb);
1476
1477         atomic_inc(&sh->count);
1478
1479         if (failb == syndrome_disks+1) {
1480                 /* Q disk is one of the missing disks */
1481                 if (faila == syndrome_disks) {
1482                         /* Missing P+Q, just recompute */
1483                         init_async_submit(&submit, ASYNC_TX_FENCE, NULL,
1484                                           ops_complete_compute, sh,
1485                                           to_addr_conv(sh, percpu, 0));
1486                         return async_gen_syndrome(blocks, 0, syndrome_disks+2,
1487                                                   STRIPE_SIZE, &submit);
1488                 } else {
1489                         struct page *dest;
1490                         int data_target;
1491                         int qd_idx = sh->qd_idx;
1492
1493                         /* Missing D+Q: recompute D from P, then recompute Q */
1494                         if (target == qd_idx)
1495                                 data_target = target2;
1496                         else
1497                                 data_target = target;
1498
1499                         count = 0;
1500                         for (i = disks; i-- ; ) {
1501                                 if (i == data_target || i == qd_idx)
1502                                         continue;
1503                                 blocks[count++] = sh->dev[i].page;
1504                         }
1505                         dest = sh->dev[data_target].page;
1506                         init_async_submit(&submit,
1507                                           ASYNC_TX_FENCE|ASYNC_TX_XOR_ZERO_DST,
1508                                           NULL, NULL, NULL,
1509                                           to_addr_conv(sh, percpu, 0));
1510                         tx = async_xor(dest, blocks, 0, count, STRIPE_SIZE,
1511                                        &submit);
1512
1513                         count = set_syndrome_sources(blocks, sh, SYNDROME_SRC_ALL);
1514                         init_async_submit(&submit, ASYNC_TX_FENCE, tx,
1515                                           ops_complete_compute, sh,
1516                                           to_addr_conv(sh, percpu, 0));
1517                         return async_gen_syndrome(blocks, 0, count+2,
1518                                                   STRIPE_SIZE, &submit);
1519                 }
1520         } else {
1521                 init_async_submit(&submit, ASYNC_TX_FENCE, NULL,
1522                                   ops_complete_compute, sh,
1523                                   to_addr_conv(sh, percpu, 0));
1524                 if (failb == syndrome_disks) {
1525                         /* We're missing D+P. */
1526                         return async_raid6_datap_recov(syndrome_disks+2,
1527                                                        STRIPE_SIZE, faila,
1528                                                        blocks, &submit);
1529                 } else {
1530                         /* We're missing D+D. */
1531                         return async_raid6_2data_recov(syndrome_disks+2,
1532                                                        STRIPE_SIZE, faila, failb,
1533                                                        blocks, &submit);
1534                 }
1535         }
1536 }
1537
1538 static void ops_complete_prexor(void *stripe_head_ref)
1539 {
1540         struct stripe_head *sh = stripe_head_ref;
1541
1542         pr_debug("%s: stripe %llu\n", __func__,
1543                 (unsigned long long)sh->sector);
1544 }
1545
1546 static struct dma_async_tx_descriptor *
1547 ops_run_prexor5(struct stripe_head *sh, struct raid5_percpu *percpu,
1548                 struct dma_async_tx_descriptor *tx)
1549 {
1550         int disks = sh->disks;
1551         struct page **xor_srcs = to_addr_page(percpu, 0);
1552         int count = 0, pd_idx = sh->pd_idx, i;
1553         struct async_submit_ctl submit;
1554
1555         /* existing parity data subtracted */
1556         struct page *xor_dest = xor_srcs[count++] = sh->dev[pd_idx].page;
1557
1558         BUG_ON(sh->batch_head);
1559         pr_debug("%s: stripe %llu\n", __func__,
1560                 (unsigned long long)sh->sector);
1561
1562         for (i = disks; i--; ) {
1563                 struct r5dev *dev = &sh->dev[i];
1564                 /* Only process blocks that are known to be uptodate */
1565                 if (test_bit(R5_Wantdrain, &dev->flags))
1566                         xor_srcs[count++] = dev->page;
1567         }
1568
1569         init_async_submit(&submit, ASYNC_TX_FENCE|ASYNC_TX_XOR_DROP_DST, tx,
1570                           ops_complete_prexor, sh, to_addr_conv(sh, percpu, 0));
1571         tx = async_xor(xor_dest, xor_srcs, 0, count, STRIPE_SIZE, &submit);
1572
1573         return tx;
1574 }
1575
1576 static struct dma_async_tx_descriptor *
1577 ops_run_prexor6(struct stripe_head *sh, struct raid5_percpu *percpu,
1578                 struct dma_async_tx_descriptor *tx)
1579 {
1580         struct page **blocks = to_addr_page(percpu, 0);
1581         int count;
1582         struct async_submit_ctl submit;
1583
1584         pr_debug("%s: stripe %llu\n", __func__,
1585                 (unsigned long long)sh->sector);
1586
1587         count = set_syndrome_sources(blocks, sh, SYNDROME_SRC_WANT_DRAIN);
1588
1589         init_async_submit(&submit, ASYNC_TX_FENCE|ASYNC_TX_PQ_XOR_DST, tx,
1590                           ops_complete_prexor, sh, to_addr_conv(sh, percpu, 0));
1591         tx = async_gen_syndrome(blocks, 0, count+2, STRIPE_SIZE,  &submit);
1592
1593         return tx;
1594 }
1595
1596 static struct dma_async_tx_descriptor *
1597 ops_run_biodrain(struct stripe_head *sh, struct dma_async_tx_descriptor *tx)
1598 {
1599         int disks = sh->disks;
1600         int i;
1601         struct stripe_head *head_sh = sh;
1602
1603         pr_debug("%s: stripe %llu\n", __func__,
1604                 (unsigned long long)sh->sector);
1605
1606         for (i = disks; i--; ) {
1607                 struct r5dev *dev;
1608                 struct bio *chosen;
1609
1610                 sh = head_sh;
1611                 if (test_and_clear_bit(R5_Wantdrain, &head_sh->dev[i].flags)) {
1612                         struct bio *wbi;
1613
1614 again:
1615                         dev = &sh->dev[i];
1616                         spin_lock_irq(&sh->stripe_lock);
1617                         chosen = dev->towrite;
1618                         dev->towrite = NULL;
1619                         sh->overwrite_disks = 0;
1620                         BUG_ON(dev->written);
1621                         wbi = dev->written = chosen;
1622                         spin_unlock_irq(&sh->stripe_lock);
1623                         WARN_ON(dev->page != dev->orig_page);
1624
1625                         while (wbi && wbi->bi_iter.bi_sector <
1626                                 dev->sector + STRIPE_SECTORS) {
1627                                 if (wbi->bi_rw & REQ_FUA)
1628                                         set_bit(R5_WantFUA, &dev->flags);
1629                                 if (wbi->bi_rw & REQ_SYNC)
1630                                         set_bit(R5_SyncIO, &dev->flags);
1631                                 if (wbi->bi_rw & REQ_DISCARD)
1632                                         set_bit(R5_Discard, &dev->flags);
1633                                 else {
1634                                         tx = async_copy_data(1, wbi, &dev->page,
1635                                                 dev->sector, tx, sh);
1636                                         if (dev->page != dev->orig_page) {
1637                                                 set_bit(R5_SkipCopy, &dev->flags);
1638                                                 clear_bit(R5_UPTODATE, &dev->flags);
1639                                                 clear_bit(R5_OVERWRITE, &dev->flags);
1640                                         }
1641                                 }
1642                                 wbi = r5_next_bio(wbi, dev->sector);
1643                         }
1644
1645                         if (head_sh->batch_head) {
1646                                 sh = list_first_entry(&sh->batch_list,
1647                                                       struct stripe_head,
1648                                                       batch_list);
1649                                 if (sh == head_sh)
1650                                         continue;
1651                                 goto again;
1652                         }
1653                 }
1654         }
1655
1656         return tx;
1657 }
1658
1659 static void ops_complete_reconstruct(void *stripe_head_ref)
1660 {
1661         struct stripe_head *sh = stripe_head_ref;
1662         int disks = sh->disks;
1663         int pd_idx = sh->pd_idx;
1664         int qd_idx = sh->qd_idx;
1665         int i;
1666         bool fua = false, sync = false, discard = false;
1667
1668         pr_debug("%s: stripe %llu\n", __func__,
1669                 (unsigned long long)sh->sector);
1670
1671         for (i = disks; i--; ) {
1672                 fua |= test_bit(R5_WantFUA, &sh->dev[i].flags);
1673                 sync |= test_bit(R5_SyncIO, &sh->dev[i].flags);
1674                 discard |= test_bit(R5_Discard, &sh->dev[i].flags);
1675         }
1676
1677         for (i = disks; i--; ) {
1678                 struct r5dev *dev = &sh->dev[i];
1679
1680                 if (dev->written || i == pd_idx || i == qd_idx) {
1681                         if (!discard && !test_bit(R5_SkipCopy, &dev->flags))
1682                                 set_bit(R5_UPTODATE, &dev->flags);
1683                         if (fua)
1684                                 set_bit(R5_WantFUA, &dev->flags);
1685                         if (sync)
1686                                 set_bit(R5_SyncIO, &dev->flags);
1687                 }
1688         }
1689
1690         if (sh->reconstruct_state == reconstruct_state_drain_run)
1691                 sh->reconstruct_state = reconstruct_state_drain_result;
1692         else if (sh->reconstruct_state == reconstruct_state_prexor_drain_run)
1693                 sh->reconstruct_state = reconstruct_state_prexor_drain_result;
1694         else {
1695                 BUG_ON(sh->reconstruct_state != reconstruct_state_run);
1696                 sh->reconstruct_state = reconstruct_state_result;
1697         }
1698
1699         set_bit(STRIPE_HANDLE, &sh->state);
1700         release_stripe(sh);
1701 }
1702
1703 static void
1704 ops_run_reconstruct5(struct stripe_head *sh, struct raid5_percpu *percpu,
1705                      struct dma_async_tx_descriptor *tx)
1706 {
1707         int disks = sh->disks;
1708         struct page **xor_srcs;
1709         struct async_submit_ctl submit;
1710         int count, pd_idx = sh->pd_idx, i;
1711         struct page *xor_dest;
1712         int prexor = 0;
1713         unsigned long flags;
1714         int j = 0;
1715         struct stripe_head *head_sh = sh;
1716         int last_stripe;
1717
1718         pr_debug("%s: stripe %llu\n", __func__,
1719                 (unsigned long long)sh->sector);
1720
1721         for (i = 0; i < sh->disks; i++) {
1722                 if (pd_idx == i)
1723                         continue;
1724                 if (!test_bit(R5_Discard, &sh->dev[i].flags))
1725                         break;
1726         }
1727         if (i >= sh->disks) {
1728                 atomic_inc(&sh->count);
1729                 set_bit(R5_Discard, &sh->dev[pd_idx].flags);
1730                 ops_complete_reconstruct(sh);
1731                 return;
1732         }
1733 again:
1734         count = 0;
1735         xor_srcs = to_addr_page(percpu, j);
1736         /* check if prexor is active which means only process blocks
1737          * that are part of a read-modify-write (written)
1738          */
1739         if (head_sh->reconstruct_state == reconstruct_state_prexor_drain_run) {
1740                 prexor = 1;
1741                 xor_dest = xor_srcs[count++] = sh->dev[pd_idx].page;
1742                 for (i = disks; i--; ) {
1743                         struct r5dev *dev = &sh->dev[i];
1744                         if (head_sh->dev[i].written)
1745                                 xor_srcs[count++] = dev->page;
1746                 }
1747         } else {
1748                 xor_dest = sh->dev[pd_idx].page;
1749                 for (i = disks; i--; ) {
1750                         struct r5dev *dev = &sh->dev[i];
1751                         if (i != pd_idx)
1752                                 xor_srcs[count++] = dev->page;
1753                 }
1754         }
1755
1756         /* 1/ if we prexor'd then the dest is reused as a source
1757          * 2/ if we did not prexor then we are redoing the parity
1758          * set ASYNC_TX_XOR_DROP_DST and ASYNC_TX_XOR_ZERO_DST
1759          * for the synchronous xor case
1760          */
1761         last_stripe = !head_sh->batch_head ||
1762                 list_first_entry(&sh->batch_list,
1763                                  struct stripe_head, batch_list) == head_sh;
1764         if (last_stripe) {
1765                 flags = ASYNC_TX_ACK |
1766                         (prexor ? ASYNC_TX_XOR_DROP_DST : ASYNC_TX_XOR_ZERO_DST);
1767
1768                 atomic_inc(&head_sh->count);
1769                 init_async_submit(&submit, flags, tx, ops_complete_reconstruct, head_sh,
1770                                   to_addr_conv(sh, percpu, j));
1771         } else {
1772                 flags = prexor ? ASYNC_TX_XOR_DROP_DST : ASYNC_TX_XOR_ZERO_DST;
1773                 init_async_submit(&submit, flags, tx, NULL, NULL,
1774                                   to_addr_conv(sh, percpu, j));
1775         }
1776
1777         if (unlikely(count == 1))
1778                 tx = async_memcpy(xor_dest, xor_srcs[0], 0, 0, STRIPE_SIZE, &submit);
1779         else
1780                 tx = async_xor(xor_dest, xor_srcs, 0, count, STRIPE_SIZE, &submit);
1781         if (!last_stripe) {
1782                 j++;
1783                 sh = list_first_entry(&sh->batch_list, struct stripe_head,
1784                                       batch_list);
1785                 goto again;
1786         }
1787 }
1788
1789 static void
1790 ops_run_reconstruct6(struct stripe_head *sh, struct raid5_percpu *percpu,
1791                      struct dma_async_tx_descriptor *tx)
1792 {
1793         struct async_submit_ctl submit;
1794         struct page **blocks;
1795         int count, i, j = 0;
1796         struct stripe_head *head_sh = sh;
1797         int last_stripe;
1798         int synflags;
1799         unsigned long txflags;
1800
1801         pr_debug("%s: stripe %llu\n", __func__, (unsigned long long)sh->sector);
1802
1803         for (i = 0; i < sh->disks; i++) {
1804                 if (sh->pd_idx == i || sh->qd_idx == i)
1805                         continue;
1806                 if (!test_bit(R5_Discard, &sh->dev[i].flags))
1807                         break;
1808         }
1809         if (i >= sh->disks) {
1810                 atomic_inc(&sh->count);
1811                 set_bit(R5_Discard, &sh->dev[sh->pd_idx].flags);
1812                 set_bit(R5_Discard, &sh->dev[sh->qd_idx].flags);
1813                 ops_complete_reconstruct(sh);
1814                 return;
1815         }
1816
1817 again:
1818         blocks = to_addr_page(percpu, j);
1819
1820         if (sh->reconstruct_state == reconstruct_state_prexor_drain_run) {
1821                 synflags = SYNDROME_SRC_WRITTEN;
1822                 txflags = ASYNC_TX_ACK | ASYNC_TX_PQ_XOR_DST;
1823         } else {
1824                 synflags = SYNDROME_SRC_ALL;
1825                 txflags = ASYNC_TX_ACK;
1826         }
1827
1828         count = set_syndrome_sources(blocks, sh, synflags);
1829         last_stripe = !head_sh->batch_head ||
1830                 list_first_entry(&sh->batch_list,
1831                                  struct stripe_head, batch_list) == head_sh;
1832
1833         if (last_stripe) {
1834                 atomic_inc(&head_sh->count);
1835                 init_async_submit(&submit, txflags, tx, ops_complete_reconstruct,
1836                                   head_sh, to_addr_conv(sh, percpu, j));
1837         } else
1838                 init_async_submit(&submit, 0, tx, NULL, NULL,
1839                                   to_addr_conv(sh, percpu, j));
1840         tx = async_gen_syndrome(blocks, 0, count+2, STRIPE_SIZE,  &submit);
1841         if (!last_stripe) {
1842                 j++;
1843                 sh = list_first_entry(&sh->batch_list, struct stripe_head,
1844                                       batch_list);
1845                 goto again;
1846         }
1847 }
1848
1849 static void ops_complete_check(void *stripe_head_ref)
1850 {
1851         struct stripe_head *sh = stripe_head_ref;
1852
1853         pr_debug("%s: stripe %llu\n", __func__,
1854                 (unsigned long long)sh->sector);
1855
1856         sh->check_state = check_state_check_result;
1857         set_bit(STRIPE_HANDLE, &sh->state);
1858         release_stripe(sh);
1859 }
1860
1861 static void ops_run_check_p(struct stripe_head *sh, struct raid5_percpu *percpu)
1862 {
1863         int disks = sh->disks;
1864         int pd_idx = sh->pd_idx;
1865         int qd_idx = sh->qd_idx;
1866         struct page *xor_dest;
1867         struct page **xor_srcs = to_addr_page(percpu, 0);
1868         struct dma_async_tx_descriptor *tx;
1869         struct async_submit_ctl submit;
1870         int count;
1871         int i;
1872
1873         pr_debug("%s: stripe %llu\n", __func__,
1874                 (unsigned long long)sh->sector);
1875
1876         BUG_ON(sh->batch_head);
1877         count = 0;
1878         xor_dest = sh->dev[pd_idx].page;
1879         xor_srcs[count++] = xor_dest;
1880         for (i = disks; i--; ) {
1881                 if (i == pd_idx || i == qd_idx)
1882                         continue;
1883                 xor_srcs[count++] = sh->dev[i].page;
1884         }
1885
1886         init_async_submit(&submit, 0, NULL, NULL, NULL,
1887                           to_addr_conv(sh, percpu, 0));
1888         tx = async_xor_val(xor_dest, xor_srcs, 0, count, STRIPE_SIZE,
1889                            &sh->ops.zero_sum_result, &submit);
1890
1891         atomic_inc(&sh->count);
1892         init_async_submit(&submit, ASYNC_TX_ACK, tx, ops_complete_check, sh, NULL);
1893         tx = async_trigger_callback(&submit);
1894 }
1895
1896 static void ops_run_check_pq(struct stripe_head *sh, struct raid5_percpu *percpu, int checkp)
1897 {
1898         struct page **srcs = to_addr_page(percpu, 0);
1899         struct async_submit_ctl submit;
1900         int count;
1901
1902         pr_debug("%s: stripe %llu checkp: %d\n", __func__,
1903                 (unsigned long long)sh->sector, checkp);
1904
1905         BUG_ON(sh->batch_head);
1906         count = set_syndrome_sources(srcs, sh, SYNDROME_SRC_ALL);
1907         if (!checkp)
1908                 srcs[count] = NULL;
1909
1910         atomic_inc(&sh->count);
1911         init_async_submit(&submit, ASYNC_TX_ACK, NULL, ops_complete_check,
1912                           sh, to_addr_conv(sh, percpu, 0));
1913         async_syndrome_val(srcs, 0, count+2, STRIPE_SIZE,
1914                            &sh->ops.zero_sum_result, percpu->spare_page, &submit);
1915 }
1916
1917 static void raid_run_ops(struct stripe_head *sh, unsigned long ops_request)
1918 {
1919         int overlap_clear = 0, i, disks = sh->disks;
1920         struct dma_async_tx_descriptor *tx = NULL;
1921         struct r5conf *conf = sh->raid_conf;
1922         int level = conf->level;
1923         struct raid5_percpu *percpu;
1924         unsigned long cpu;
1925
1926         cpu = get_cpu();
1927         percpu = per_cpu_ptr(conf->percpu, cpu);
1928         if (test_bit(STRIPE_OP_BIOFILL, &ops_request)) {
1929                 ops_run_biofill(sh);
1930                 overlap_clear++;
1931         }
1932
1933         if (test_bit(STRIPE_OP_COMPUTE_BLK, &ops_request)) {
1934                 if (level < 6)
1935                         tx = ops_run_compute5(sh, percpu);
1936                 else {
1937                         if (sh->ops.target2 < 0 || sh->ops.target < 0)
1938                                 tx = ops_run_compute6_1(sh, percpu);
1939                         else
1940                                 tx = ops_run_compute6_2(sh, percpu);
1941                 }
1942                 /* terminate the chain if reconstruct is not set to be run */
1943                 if (tx && !test_bit(STRIPE_OP_RECONSTRUCT, &ops_request))
1944                         async_tx_ack(tx);
1945         }
1946
1947         if (test_bit(STRIPE_OP_PREXOR, &ops_request)) {
1948                 if (level < 6)
1949                         tx = ops_run_prexor5(sh, percpu, tx);
1950                 else
1951                         tx = ops_run_prexor6(sh, percpu, tx);
1952         }
1953
1954         if (test_bit(STRIPE_OP_BIODRAIN, &ops_request)) {
1955                 tx = ops_run_biodrain(sh, tx);
1956                 overlap_clear++;
1957         }
1958
1959         if (test_bit(STRIPE_OP_RECONSTRUCT, &ops_request)) {
1960                 if (level < 6)
1961                         ops_run_reconstruct5(sh, percpu, tx);
1962                 else
1963                         ops_run_reconstruct6(sh, percpu, tx);
1964         }
1965
1966         if (test_bit(STRIPE_OP_CHECK, &ops_request)) {
1967                 if (sh->check_state == check_state_run)
1968                         ops_run_check_p(sh, percpu);
1969                 else if (sh->check_state == check_state_run_q)
1970                         ops_run_check_pq(sh, percpu, 0);
1971                 else if (sh->check_state == check_state_run_pq)
1972                         ops_run_check_pq(sh, percpu, 1);
1973                 else
1974                         BUG();
1975         }
1976
1977         if (overlap_clear && !sh->batch_head)
1978                 for (i = disks; i--; ) {
1979                         struct r5dev *dev = &sh->dev[i];
1980                         if (test_and_clear_bit(R5_Overlap, &dev->flags))
1981                                 wake_up(&sh->raid_conf->wait_for_overlap);
1982                 }
1983         put_cpu();
1984 }
1985
1986 static struct stripe_head *alloc_stripe(struct kmem_cache *sc, gfp_t gfp)
1987 {
1988         struct stripe_head *sh;
1989
1990         sh = kmem_cache_zalloc(sc, gfp);
1991         if (sh) {
1992                 spin_lock_init(&sh->stripe_lock);
1993                 spin_lock_init(&sh->batch_lock);
1994                 INIT_LIST_HEAD(&sh->batch_list);
1995                 INIT_LIST_HEAD(&sh->lru);
1996                 atomic_set(&sh->count, 1);
1997         }
1998         return sh;
1999 }
2000 static int grow_one_stripe(struct r5conf *conf, gfp_t gfp)
2001 {
2002         struct stripe_head *sh;
2003
2004         sh = alloc_stripe(conf->slab_cache, gfp);
2005         if (!sh)
2006                 return 0;
2007
2008         sh->raid_conf = conf;
2009
2010         if (grow_buffers(sh, gfp)) {
2011                 shrink_buffers(sh);
2012                 kmem_cache_free(conf->slab_cache, sh);
2013                 return 0;
2014         }
2015         sh->hash_lock_index =
2016                 conf->max_nr_stripes % NR_STRIPE_HASH_LOCKS;
2017         /* we just created an active stripe so... */
2018         atomic_inc(&conf->active_stripes);
2019
2020         release_stripe(sh);
2021         conf->max_nr_stripes++;
2022         return 1;
2023 }
2024
2025 static int grow_stripes(struct r5conf *conf, int num)
2026 {
2027         struct kmem_cache *sc;
2028         int devs = max(conf->raid_disks, conf->previous_raid_disks);
2029
2030         if (conf->mddev->gendisk)
2031                 sprintf(conf->cache_name[0],
2032                         "raid%d-%s", conf->level, mdname(conf->mddev));
2033         else
2034                 sprintf(conf->cache_name[0],
2035                         "raid%d-%p", conf->level, conf->mddev);
2036         sprintf(conf->cache_name[1], "%s-alt", conf->cache_name[0]);
2037
2038         conf->active_name = 0;
2039         sc = kmem_cache_create(conf->cache_name[conf->active_name],
2040                                sizeof(struct stripe_head)+(devs-1)*sizeof(struct r5dev),
2041                                0, 0, NULL);
2042         if (!sc)
2043                 return 1;
2044         conf->slab_cache = sc;
2045         conf->pool_size = devs;
2046         while (num--)
2047                 if (!grow_one_stripe(conf, GFP_KERNEL))
2048                         return 1;
2049
2050         return 0;
2051 }
2052
2053 /**
2054  * scribble_len - return the required size of the scribble region
2055  * @num - total number of disks in the array
2056  *
2057  * The size must be enough to contain:
2058  * 1/ a struct page pointer for each device in the array +2
2059  * 2/ room to convert each entry in (1) to its corresponding dma
2060  *    (dma_map_page()) or page (page_address()) address.
2061  *
2062  * Note: the +2 is for the destination buffers of the ddf/raid6 case where we
2063  * calculate over all devices (not just the data blocks), using zeros in place
2064  * of the P and Q blocks.
2065  */
2066 static struct flex_array *scribble_alloc(int num, int cnt, gfp_t flags)
2067 {
2068         struct flex_array *ret;
2069         size_t len;
2070
2071         len = sizeof(struct page *) * (num+2) + sizeof(addr_conv_t) * (num+2);
2072         ret = flex_array_alloc(len, cnt, flags);
2073         if (!ret)
2074                 return NULL;
2075         /* always prealloc all elements, so no locking is required */
2076         if (flex_array_prealloc(ret, 0, cnt, flags)) {
2077                 flex_array_free(ret);
2078                 return NULL;
2079         }
2080         return ret;
2081 }
2082
2083 static int resize_chunks(struct r5conf *conf, int new_disks, int new_sectors)
2084 {
2085         unsigned long cpu;
2086         int err = 0;
2087
2088         mddev_suspend(conf->mddev);
2089         get_online_cpus();
2090         for_each_present_cpu(cpu) {
2091                 struct raid5_percpu *percpu;
2092                 struct flex_array *scribble;
2093
2094                 percpu = per_cpu_ptr(conf->percpu, cpu);
2095                 scribble = scribble_alloc(new_disks,
2096                                           new_sectors / STRIPE_SECTORS,
2097                                           GFP_NOIO);
2098
2099                 if (scribble) {
2100                         flex_array_free(percpu->scribble);
2101                         percpu->scribble = scribble;
2102                 } else {
2103                         err = -ENOMEM;
2104                         break;
2105                 }
2106         }
2107         put_online_cpus();
2108         mddev_resume(conf->mddev);
2109         return err;
2110 }
2111
2112 static int resize_stripes(struct r5conf *conf, int newsize)
2113 {
2114         /* Make all the stripes able to hold 'newsize' devices.
2115          * New slots in each stripe get 'page' set to a new page.
2116          *
2117          * This happens in stages:
2118          * 1/ create a new kmem_cache and allocate the required number of
2119          *    stripe_heads.
2120          * 2/ gather all the old stripe_heads and transfer the pages across
2121          *    to the new stripe_heads.  This will have the side effect of
2122          *    freezing the array as once all stripe_heads have been collected,
2123          *    no IO will be possible.  Old stripe heads are freed once their
2124          *    pages have been transferred over, and the old kmem_cache is
2125          *    freed when all stripes are done.
2126          * 3/ reallocate conf->disks to be suitable bigger.  If this fails,
2127          *    we simple return a failre status - no need to clean anything up.
2128          * 4/ allocate new pages for the new slots in the new stripe_heads.
2129          *    If this fails, we don't bother trying the shrink the
2130          *    stripe_heads down again, we just leave them as they are.
2131          *    As each stripe_head is processed the new one is released into
2132          *    active service.
2133          *
2134          * Once step2 is started, we cannot afford to wait for a write,
2135          * so we use GFP_NOIO allocations.
2136          */
2137         struct stripe_head *osh, *nsh;
2138         LIST_HEAD(newstripes);
2139         struct disk_info *ndisks;
2140         int err;
2141         struct kmem_cache *sc;
2142         int i;
2143         int hash, cnt;
2144
2145         if (newsize <= conf->pool_size)
2146                 return 0; /* never bother to shrink */
2147
2148         err = md_allow_write(conf->mddev);
2149         if (err)
2150                 return err;
2151
2152         /* Step 1 */
2153         sc = kmem_cache_create(conf->cache_name[1-conf->active_name],
2154                                sizeof(struct stripe_head)+(newsize-1)*sizeof(struct r5dev),
2155                                0, 0, NULL);
2156         if (!sc)
2157                 return -ENOMEM;
2158
2159         /* Need to ensure auto-resizing doesn't interfere */
2160         mutex_lock(&conf->cache_size_mutex);
2161
2162         for (i = conf->max_nr_stripes; i; i--) {
2163                 nsh = alloc_stripe(sc, GFP_KERNEL);
2164                 if (!nsh)
2165                         break;
2166
2167                 nsh->raid_conf = conf;
2168                 list_add(&nsh->lru, &newstripes);
2169         }
2170         if (i) {
2171                 /* didn't get enough, give up */
2172                 while (!list_empty(&newstripes)) {
2173                         nsh = list_entry(newstripes.next, struct stripe_head, lru);
2174                         list_del(&nsh->lru);
2175                         kmem_cache_free(sc, nsh);
2176                 }
2177                 kmem_cache_destroy(sc);
2178                 mutex_unlock(&conf->cache_size_mutex);
2179                 return -ENOMEM;
2180         }
2181         /* Step 2 - Must use GFP_NOIO now.
2182          * OK, we have enough stripes, start collecting inactive
2183          * stripes and copying them over
2184          */
2185         hash = 0;
2186         cnt = 0;
2187         list_for_each_entry(nsh, &newstripes, lru) {
2188                 lock_device_hash_lock(conf, hash);
2189                 wait_event_exclusive_cmd(conf->wait_for_stripe[hash],
2190                                     !list_empty(conf->inactive_list + hash),
2191                                     unlock_device_hash_lock(conf, hash),
2192                                     lock_device_hash_lock(conf, hash));
2193                 osh = get_free_stripe(conf, hash);
2194                 unlock_device_hash_lock(conf, hash);
2195
2196                 for(i=0; i<conf->pool_size; i++) {
2197                         nsh->dev[i].page = osh->dev[i].page;
2198                         nsh->dev[i].orig_page = osh->dev[i].page;
2199                 }
2200                 nsh->hash_lock_index = hash;
2201                 kmem_cache_free(conf->slab_cache, osh);
2202                 cnt++;
2203                 if (cnt >= conf->max_nr_stripes / NR_STRIPE_HASH_LOCKS +
2204                     !!((conf->max_nr_stripes % NR_STRIPE_HASH_LOCKS) > hash)) {
2205                         hash++;
2206                         cnt = 0;
2207                 }
2208         }
2209         kmem_cache_destroy(conf->slab_cache);
2210
2211         /* Step 3.
2212          * At this point, we are holding all the stripes so the array
2213          * is completely stalled, so now is a good time to resize
2214          * conf->disks and the scribble region
2215          */
2216         ndisks = kzalloc(newsize * sizeof(struct disk_info), GFP_NOIO);
2217         if (ndisks) {
2218                 for (i=0; i<conf->raid_disks; i++)
2219                         ndisks[i] = conf->disks[i];
2220                 kfree(conf->disks);
2221                 conf->disks = ndisks;
2222         } else
2223                 err = -ENOMEM;
2224
2225         mutex_unlock(&conf->cache_size_mutex);
2226         /* Step 4, return new stripes to service */
2227         while(!list_empty(&newstripes)) {
2228                 nsh = list_entry(newstripes.next, struct stripe_head, lru);
2229                 list_del_init(&nsh->lru);
2230
2231                 for (i=conf->raid_disks; i < newsize; i++)
2232                         if (nsh->dev[i].page == NULL) {
2233                                 struct page *p = alloc_page(GFP_NOIO);
2234                                 nsh->dev[i].page = p;
2235                                 nsh->dev[i].orig_page = p;
2236                                 if (!p)
2237                                         err = -ENOMEM;
2238                         }
2239                 release_stripe(nsh);
2240         }
2241         /* critical section pass, GFP_NOIO no longer needed */
2242
2243         conf->slab_cache = sc;
2244         conf->active_name = 1-conf->active_name;
2245         if (!err)
2246                 conf->pool_size = newsize;
2247         return err;
2248 }
2249
2250 static int drop_one_stripe(struct r5conf *conf)
2251 {
2252         struct stripe_head *sh;
2253         int hash = (conf->max_nr_stripes - 1) & STRIPE_HASH_LOCKS_MASK;
2254
2255         spin_lock_irq(conf->hash_locks + hash);
2256         sh = get_free_stripe(conf, hash);
2257         spin_unlock_irq(conf->hash_locks + hash);
2258         if (!sh)
2259                 return 0;
2260         BUG_ON(atomic_read(&sh->count));
2261         shrink_buffers(sh);
2262         kmem_cache_free(conf->slab_cache, sh);
2263         atomic_dec(&conf->active_stripes);
2264         conf->max_nr_stripes--;
2265         return 1;
2266 }
2267
2268 static void shrink_stripes(struct r5conf *conf)
2269 {
2270         while (conf->max_nr_stripes &&
2271                drop_one_stripe(conf))
2272                 ;
2273
2274         kmem_cache_destroy(conf->slab_cache);
2275         conf->slab_cache = NULL;
2276 }
2277
2278 static void raid5_end_read_request(struct bio * bi)
2279 {
2280         struct stripe_head *sh = bi->bi_private;
2281         struct r5conf *conf = sh->raid_conf;
2282         int disks = sh->disks, i;
2283         char b[BDEVNAME_SIZE];
2284         struct md_rdev *rdev = NULL;
2285         sector_t s;
2286
2287         for (i=0 ; i<disks; i++)
2288                 if (bi == &sh->dev[i].req)
2289                         break;
2290
2291         pr_debug("end_read_request %llu/%d, count: %d, error %d.\n",
2292                 (unsigned long long)sh->sector, i, atomic_read(&sh->count),
2293                 bi->bi_error);
2294         if (i == disks) {
2295                 BUG();
2296                 return;
2297         }
2298         if (test_bit(R5_ReadRepl, &sh->dev[i].flags))
2299                 /* If replacement finished while this request was outstanding,
2300                  * 'replacement' might be NULL already.
2301                  * In that case it moved down to 'rdev'.
2302                  * rdev is not removed until all requests are finished.
2303                  */
2304                 rdev = conf->disks[i].replacement;
2305         if (!rdev)
2306                 rdev = conf->disks[i].rdev;
2307
2308         if (use_new_offset(conf, sh))
2309                 s = sh->sector + rdev->new_data_offset;
2310         else
2311                 s = sh->sector + rdev->data_offset;
2312         if (!bi->bi_error) {
2313                 set_bit(R5_UPTODATE, &sh->dev[i].flags);
2314                 if (test_bit(R5_ReadError, &sh->dev[i].flags)) {
2315                         /* Note that this cannot happen on a
2316                          * replacement device.  We just fail those on
2317                          * any error
2318                          */
2319                         printk_ratelimited(
2320                                 KERN_INFO
2321                                 "md/raid:%s: read error corrected"
2322                                 " (%lu sectors at %llu on %s)\n",
2323                                 mdname(conf->mddev), STRIPE_SECTORS,
2324                                 (unsigned long long)s,
2325                                 bdevname(rdev->bdev, b));
2326                         atomic_add(STRIPE_SECTORS, &rdev->corrected_errors);
2327                         clear_bit(R5_ReadError, &sh->dev[i].flags);
2328                         clear_bit(R5_ReWrite, &sh->dev[i].flags);
2329                 } else if (test_bit(R5_ReadNoMerge, &sh->dev[i].flags))
2330                         clear_bit(R5_ReadNoMerge, &sh->dev[i].flags);
2331
2332                 if (atomic_read(&rdev->read_errors))
2333                         atomic_set(&rdev->read_errors, 0);
2334         } else {
2335                 const char *bdn = bdevname(rdev->bdev, b);
2336                 int retry = 0;
2337                 int set_bad = 0;
2338
2339                 clear_bit(R5_UPTODATE, &sh->dev[i].flags);
2340                 atomic_inc(&rdev->read_errors);
2341                 if (test_bit(R5_ReadRepl, &sh->dev[i].flags))
2342                         printk_ratelimited(
2343                                 KERN_WARNING
2344                                 "md/raid:%s: read error on replacement device "
2345                                 "(sector %llu on %s).\n",
2346                                 mdname(conf->mddev),
2347                                 (unsigned long long)s,
2348                                 bdn);
2349                 else if (conf->mddev->degraded >= conf->max_degraded) {
2350                         set_bad = 1;
2351                         printk_ratelimited(
2352                                 KERN_WARNING
2353                                 "md/raid:%s: read error not correctable "
2354                                 "(sector %llu on %s).\n",
2355                                 mdname(conf->mddev),
2356                                 (unsigned long long)s,
2357                                 bdn);
2358                 } else if (test_bit(R5_ReWrite, &sh->dev[i].flags)) {
2359                         /* Oh, no!!! */
2360                         set_bad = 1;
2361                         printk_ratelimited(
2362                                 KERN_WARNING
2363                                 "md/raid:%s: read error NOT corrected!! "
2364                                 "(sector %llu on %s).\n",
2365                                 mdname(conf->mddev),
2366                                 (unsigned long long)s,
2367                                 bdn);
2368                 } else if (atomic_read(&rdev->read_errors)
2369                          > conf->max_nr_stripes)
2370                         printk(KERN_WARNING
2371                                "md/raid:%s: Too many read errors, failing device %s.\n",
2372                                mdname(conf->mddev), bdn);
2373                 else
2374                         retry = 1;
2375                 if (set_bad && test_bit(In_sync, &rdev->flags)
2376                     && !test_bit(R5_ReadNoMerge, &sh->dev[i].flags))
2377                         retry = 1;
2378                 if (retry)
2379                         if (test_bit(R5_ReadNoMerge, &sh->dev[i].flags)) {
2380                                 set_bit(R5_ReadError, &sh->dev[i].flags);
2381                                 clear_bit(R5_ReadNoMerge, &sh->dev[i].flags);
2382                         } else
2383                                 set_bit(R5_ReadNoMerge, &sh->dev[i].flags);
2384                 else {
2385                         clear_bit(R5_ReadError, &sh->dev[i].flags);
2386                         clear_bit(R5_ReWrite, &sh->dev[i].flags);
2387                         if (!(set_bad
2388                               && test_bit(In_sync, &rdev->flags)
2389                               && rdev_set_badblocks(
2390                                       rdev, sh->sector, STRIPE_SECTORS, 0)))
2391                                 md_error(conf->mddev, rdev);
2392                 }
2393         }
2394         rdev_dec_pending(rdev, conf->mddev);
2395         clear_bit(R5_LOCKED, &sh->dev[i].flags);
2396         set_bit(STRIPE_HANDLE, &sh->state);
2397         release_stripe(sh);
2398 }
2399
2400 static void raid5_end_write_request(struct bio *bi)
2401 {
2402         struct stripe_head *sh = bi->bi_private;
2403         struct r5conf *conf = sh->raid_conf;
2404         int disks = sh->disks, i;
2405         struct md_rdev *uninitialized_var(rdev);
2406         sector_t first_bad;
2407         int bad_sectors;
2408         int replacement = 0;
2409
2410         for (i = 0 ; i < disks; i++) {
2411                 if (bi == &sh->dev[i].req) {
2412                         rdev = conf->disks[i].rdev;
2413                         break;
2414                 }
2415                 if (bi == &sh->dev[i].rreq) {
2416                         rdev = conf->disks[i].replacement;
2417                         if (rdev)
2418                                 replacement = 1;
2419                         else
2420                                 /* rdev was removed and 'replacement'
2421                                  * replaced it.  rdev is not removed
2422                                  * until all requests are finished.
2423                                  */
2424                                 rdev = conf->disks[i].rdev;
2425                         break;
2426                 }
2427         }
2428         pr_debug("end_write_request %llu/%d, count %d, error: %d.\n",
2429                 (unsigned long long)sh->sector, i, atomic_read(&sh->count),
2430                 bi->bi_error);
2431         if (i == disks) {
2432                 BUG();
2433                 return;
2434         }
2435
2436         if (replacement) {
2437                 if (bi->bi_error)
2438                         md_error(conf->mddev, rdev);
2439                 else if (is_badblock(rdev, sh->sector,
2440                                      STRIPE_SECTORS,
2441                                      &first_bad, &bad_sectors))
2442                         set_bit(R5_MadeGoodRepl, &sh->dev[i].flags);
2443         } else {
2444                 if (bi->bi_error) {
2445                         set_bit(STRIPE_DEGRADED, &sh->state);
2446                         set_bit(WriteErrorSeen, &rdev->flags);
2447                         set_bit(R5_WriteError, &sh->dev[i].flags);
2448                         if (!test_and_set_bit(WantReplacement, &rdev->flags))
2449                                 set_bit(MD_RECOVERY_NEEDED,
2450                                         &rdev->mddev->recovery);
2451                 } else if (is_badblock(rdev, sh->sector,
2452                                        STRIPE_SECTORS,
2453                                        &first_bad, &bad_sectors)) {
2454                         set_bit(R5_MadeGood, &sh->dev[i].flags);
2455                         if (test_bit(R5_ReadError, &sh->dev[i].flags))
2456                                 /* That was a successful write so make
2457                                  * sure it looks like we already did
2458                                  * a re-write.
2459                                  */
2460                                 set_bit(R5_ReWrite, &sh->dev[i].flags);
2461                 }
2462         }
2463         rdev_dec_pending(rdev, conf->mddev);
2464
2465         if (sh->batch_head && bi->bi_error && !replacement)
2466                 set_bit(STRIPE_BATCH_ERR, &sh->batch_head->state);
2467
2468         if (!test_and_clear_bit(R5_DOUBLE_LOCKED, &sh->dev[i].flags))
2469                 clear_bit(R5_LOCKED, &sh->dev[i].flags);
2470         set_bit(STRIPE_HANDLE, &sh->state);
2471         release_stripe(sh);
2472
2473         if (sh->batch_head && sh != sh->batch_head)
2474                 release_stripe(sh->batch_head);
2475 }
2476
2477 static sector_t compute_blocknr(struct stripe_head *sh, int i, int previous);
2478
2479 static void raid5_build_block(struct stripe_head *sh, int i, int previous)
2480 {
2481         struct r5dev *dev = &sh->dev[i];
2482
2483         bio_init(&dev->req);
2484         dev->req.bi_io_vec = &dev->vec;
2485         dev->req.bi_max_vecs = 1;
2486         dev->req.bi_private = sh;
2487
2488         bio_init(&dev->rreq);
2489         dev->rreq.bi_io_vec = &dev->rvec;
2490         dev->rreq.bi_max_vecs = 1;
2491         dev->rreq.bi_private = sh;
2492
2493         dev->flags = 0;
2494         dev->sector = compute_blocknr(sh, i, previous);
2495 }
2496
2497 static void error(struct mddev *mddev, struct md_rdev *rdev)
2498 {
2499         char b[BDEVNAME_SIZE];
2500         struct r5conf *conf = mddev->private;
2501         unsigned long flags;
2502         pr_debug("raid456: error called\n");
2503
2504         spin_lock_irqsave(&conf->device_lock, flags);
2505         clear_bit(In_sync, &rdev->flags);
2506         mddev->degraded = calc_degraded(conf);
2507         spin_unlock_irqrestore(&conf->device_lock, flags);
2508         set_bit(MD_RECOVERY_INTR, &mddev->recovery);
2509
2510         set_bit(Blocked, &rdev->flags);
2511         set_bit(Faulty, &rdev->flags);
2512         set_bit(MD_CHANGE_DEVS, &mddev->flags);
2513         set_bit(MD_CHANGE_PENDING, &mddev->flags);
2514         printk(KERN_ALERT
2515                "md/raid:%s: Disk failure on %s, disabling device.\n"
2516                "md/raid:%s: Operation continuing on %d devices.\n",
2517                mdname(mddev),
2518                bdevname(rdev->bdev, b),
2519                mdname(mddev),
2520                conf->raid_disks - mddev->degraded);
2521 }
2522
2523 /*
2524  * Input: a 'big' sector number,
2525  * Output: index of the data and parity disk, and the sector # in them.
2526  */
2527 static sector_t raid5_compute_sector(struct r5conf *conf, sector_t r_sector,
2528                                      int previous, int *dd_idx,
2529                                      struct stripe_head *sh)
2530 {
2531         sector_t stripe, stripe2;
2532         sector_t chunk_number;
2533         unsigned int chunk_offset;
2534         int pd_idx, qd_idx;
2535         int ddf_layout = 0;
2536         sector_t new_sector;
2537         int algorithm = previous ? conf->prev_algo
2538                                  : conf->algorithm;
2539         int sectors_per_chunk = previous ? conf->prev_chunk_sectors
2540                                          : conf->chunk_sectors;
2541         int raid_disks = previous ? conf->previous_raid_disks
2542                                   : conf->raid_disks;
2543         int data_disks = raid_disks - conf->max_degraded;
2544
2545         /* First compute the information on this sector */
2546
2547         /*
2548          * Compute the chunk number and the sector offset inside the chunk
2549          */
2550         chunk_offset = sector_div(r_sector, sectors_per_chunk);
2551         chunk_number = r_sector;
2552
2553         /*
2554          * Compute the stripe number
2555          */
2556         stripe = chunk_number;
2557         *dd_idx = sector_div(stripe, data_disks);
2558         stripe2 = stripe;
2559         /*
2560          * Select the parity disk based on the user selected algorithm.
2561          */
2562         pd_idx = qd_idx = -1;
2563         switch(conf->level) {
2564         case 4:
2565                 pd_idx = data_disks;
2566                 break;
2567         case 5:
2568                 switch (algorithm) {
2569                 case ALGORITHM_LEFT_ASYMMETRIC:
2570                         pd_idx = data_disks - sector_div(stripe2, raid_disks);
2571                         if (*dd_idx >= pd_idx)
2572                                 (*dd_idx)++;
2573                         break;
2574                 case ALGORITHM_RIGHT_ASYMMETRIC:
2575                         pd_idx = sector_div(stripe2, raid_disks);
2576                         if (*dd_idx >= pd_idx)
2577                                 (*dd_idx)++;
2578                         break;
2579                 case ALGORITHM_LEFT_SYMMETRIC:
2580                         pd_idx = data_disks - sector_div(stripe2, raid_disks);
2581                         *dd_idx = (pd_idx + 1 + *dd_idx) % raid_disks;
2582                         break;
2583                 case ALGORITHM_RIGHT_SYMMETRIC:
2584                         pd_idx = sector_div(stripe2, raid_disks);
2585                         *dd_idx = (pd_idx + 1 + *dd_idx) % raid_disks;
2586                         break;
2587                 case ALGORITHM_PARITY_0:
2588                         pd_idx = 0;
2589                         (*dd_idx)++;
2590                         break;
2591                 case ALGORITHM_PARITY_N:
2592                         pd_idx = data_disks;
2593                         break;
2594                 default:
2595                         BUG();
2596                 }
2597                 break;
2598         case 6:
2599
2600                 switch (algorithm) {
2601                 case ALGORITHM_LEFT_ASYMMETRIC:
2602                         pd_idx = raid_disks - 1 - sector_div(stripe2, raid_disks);
2603                         qd_idx = pd_idx + 1;
2604                         if (pd_idx == raid_disks-1) {
2605                                 (*dd_idx)++;    /* Q D D D P */
2606                                 qd_idx = 0;
2607                         } else if (*dd_idx >= pd_idx)
2608                                 (*dd_idx) += 2; /* D D P Q D */
2609                         break;
2610                 case ALGORITHM_RIGHT_ASYMMETRIC:
2611                         pd_idx = sector_div(stripe2, raid_disks);
2612                         qd_idx = pd_idx + 1;
2613                         if (pd_idx == raid_disks-1) {
2614                                 (*dd_idx)++;    /* Q D D D P */
2615                                 qd_idx = 0;
2616                         } else if (*dd_idx >= pd_idx)
2617                                 (*dd_idx) += 2; /* D D P Q D */
2618                         break;
2619                 case ALGORITHM_LEFT_SYMMETRIC:
2620                         pd_idx = raid_disks - 1 - sector_div(stripe2, raid_disks);
2621                         qd_idx = (pd_idx + 1) % raid_disks;
2622                         *dd_idx = (pd_idx + 2 + *dd_idx) % raid_disks;
2623                         break;
2624                 case ALGORITHM_RIGHT_SYMMETRIC:
2625                         pd_idx = sector_div(stripe2, raid_disks);
2626                         qd_idx = (pd_idx + 1) % raid_disks;
2627                         *dd_idx = (pd_idx + 2 + *dd_idx) % raid_disks;
2628                         break;
2629
2630                 case ALGORITHM_PARITY_0:
2631                         pd_idx = 0;
2632                         qd_idx = 1;
2633                         (*dd_idx) += 2;
2634                         break;
2635                 case ALGORITHM_PARITY_N:
2636                         pd_idx = data_disks;
2637                         qd_idx = data_disks + 1;
2638                         break;
2639
2640                 case ALGORITHM_ROTATING_ZERO_RESTART:
2641                         /* Exactly the same as RIGHT_ASYMMETRIC, but or
2642                          * of blocks for computing Q is different.
2643                          */
2644                         pd_idx = sector_div(stripe2, raid_disks);
2645                         qd_idx = pd_idx + 1;
2646                         if (pd_idx == raid_disks-1) {
2647                                 (*dd_idx)++;    /* Q D D D P */
2648                                 qd_idx = 0;
2649                         } else if (*dd_idx >= pd_idx)
2650                                 (*dd_idx) += 2; /* D D P Q D */
2651                         ddf_layout = 1;
2652                         break;
2653
2654                 case ALGORITHM_ROTATING_N_RESTART:
2655                         /* Same a left_asymmetric, by first stripe is
2656                          * D D D P Q  rather than
2657                          * Q D D D P
2658                          */
2659                         stripe2 += 1;
2660                         pd_idx = raid_disks - 1 - sector_div(stripe2, raid_disks);
2661                         qd_idx = pd_idx + 1;
2662                         if (pd_idx == raid_disks-1) {
2663                                 (*dd_idx)++;    /* Q D D D P */
2664                                 qd_idx = 0;
2665                         } else if (*dd_idx >= pd_idx)
2666                                 (*dd_idx) += 2; /* D D P Q D */
2667                         ddf_layout = 1;
2668                         break;
2669
2670                 case ALGORITHM_ROTATING_N_CONTINUE:
2671                         /* Same as left_symmetric but Q is before P */
2672                         pd_idx = raid_disks - 1 - sector_div(stripe2, raid_disks);
2673                         qd_idx = (pd_idx + raid_disks - 1) % raid_disks;
2674                         *dd_idx = (pd_idx + 1 + *dd_idx) % raid_disks;
2675                         ddf_layout = 1;
2676                         break;
2677
2678                 case ALGORITHM_LEFT_ASYMMETRIC_6:
2679                         /* RAID5 left_asymmetric, with Q on last device */
2680                         pd_idx = data_disks - sector_div(stripe2, raid_disks-1);
2681                         if (*dd_idx >= pd_idx)
2682                                 (*dd_idx)++;
2683                         qd_idx = raid_disks - 1;
2684                         break;
2685
2686                 case ALGORITHM_RIGHT_ASYMMETRIC_6:
2687                         pd_idx = sector_div(stripe2, raid_disks-1);
2688                         if (*dd_idx >= pd_idx)
2689                                 (*dd_idx)++;
2690                         qd_idx = raid_disks - 1;
2691                         break;
2692
2693                 case ALGORITHM_LEFT_SYMMETRIC_6:
2694                         pd_idx = data_disks - sector_div(stripe2, raid_disks-1);
2695                         *dd_idx = (pd_idx + 1 + *dd_idx) % (raid_disks-1);
2696                         qd_idx = raid_disks - 1;
2697                         break;
2698
2699                 case ALGORITHM_RIGHT_SYMMETRIC_6:
2700                         pd_idx = sector_div(stripe2, raid_disks-1);
2701                         *dd_idx = (pd_idx + 1 + *dd_idx) % (raid_disks-1);
2702                         qd_idx = raid_disks - 1;
2703                         break;
2704
2705                 case ALGORITHM_PARITY_0_6:
2706                         pd_idx = 0;
2707                         (*dd_idx)++;
2708                         qd_idx = raid_disks - 1;
2709                         break;
2710
2711                 default:
2712                         BUG();
2713                 }
2714                 break;
2715         }
2716
2717         if (sh) {
2718                 sh->pd_idx = pd_idx;
2719                 sh->qd_idx = qd_idx;
2720                 sh->ddf_layout = ddf_layout;
2721         }
2722         /*
2723          * Finally, compute the new sector number
2724          */
2725         new_sector = (sector_t)stripe * sectors_per_chunk + chunk_offset;
2726         return new_sector;
2727 }
2728
2729 static sector_t compute_blocknr(struct stripe_head *sh, int i, int previous)
2730 {
2731         struct r5conf *conf = sh->raid_conf;
2732         int raid_disks = sh->disks;
2733         int data_disks = raid_disks - conf->max_degraded;
2734         sector_t new_sector = sh->sector, check;
2735         int sectors_per_chunk = previous ? conf->prev_chunk_sectors
2736                                          : conf->chunk_sectors;
2737         int algorithm = previous ? conf->prev_algo
2738                                  : conf->algorithm;
2739         sector_t stripe;
2740         int chunk_offset;
2741         sector_t chunk_number;
2742         int dummy1, dd_idx = i;
2743         sector_t r_sector;
2744         struct stripe_head sh2;
2745
2746         chunk_offset = sector_div(new_sector, sectors_per_chunk);
2747         stripe = new_sector;
2748
2749         if (i == sh->pd_idx)
2750                 return 0;
2751         switch(conf->level) {
2752         case 4: break;
2753         case 5:
2754                 switch (algorithm) {
2755                 case ALGORITHM_LEFT_ASYMMETRIC:
2756                 case ALGORITHM_RIGHT_ASYMMETRIC:
2757                         if (i > sh->pd_idx)
2758                                 i--;
2759                         break;
2760                 case ALGORITHM_LEFT_SYMMETRIC:
2761                 case ALGORITHM_RIGHT_SYMMETRIC:
2762                         if (i < sh->pd_idx)
2763                                 i += raid_disks;
2764                         i -= (sh->pd_idx + 1);
2765                         break;
2766                 case ALGORITHM_PARITY_0:
2767                         i -= 1;
2768                         break;
2769                 case ALGORITHM_PARITY_N:
2770                         break;
2771                 default:
2772                         BUG();
2773                 }
2774                 break;
2775         case 6:
2776                 if (i == sh->qd_idx)
2777                         return 0; /* It is the Q disk */
2778                 switch (algorithm) {
2779                 case ALGORITHM_LEFT_ASYMMETRIC:
2780                 case ALGORITHM_RIGHT_ASYMMETRIC:
2781                 case ALGORITHM_ROTATING_ZERO_RESTART:
2782                 case ALGORITHM_ROTATING_N_RESTART:
2783                         if (sh->pd_idx == raid_disks-1)
2784                                 i--;    /* Q D D D P */
2785                         else if (i > sh->pd_idx)
2786                                 i -= 2; /* D D P Q D */
2787                         break;
2788                 case ALGORITHM_LEFT_SYMMETRIC:
2789                 case ALGORITHM_RIGHT_SYMMETRIC:
2790                         if (sh->pd_idx == raid_disks-1)
2791                                 i--; /* Q D D D P */
2792                         else {
2793                                 /* D D P Q D */
2794                                 if (i < sh->pd_idx)
2795                                         i += raid_disks;
2796                                 i -= (sh->pd_idx + 2);
2797                         }
2798                         break;
2799                 case ALGORITHM_PARITY_0:
2800                         i -= 2;
2801                         break;
2802                 case ALGORITHM_PARITY_N:
2803                         break;
2804                 case ALGORITHM_ROTATING_N_CONTINUE:
2805                         /* Like left_symmetric, but P is before Q */
2806                         if (sh->pd_idx == 0)
2807                                 i--;    /* P D D D Q */
2808                         else {
2809                                 /* D D Q P D */
2810                                 if (i < sh->pd_idx)
2811                                         i += raid_disks;
2812                                 i -= (sh->pd_idx + 1);
2813                         }
2814                         break;
2815                 case ALGORITHM_LEFT_ASYMMETRIC_6:
2816                 case ALGORITHM_RIGHT_ASYMMETRIC_6:
2817                         if (i > sh->pd_idx)
2818                                 i--;
2819                         break;
2820                 case ALGORITHM_LEFT_SYMMETRIC_6:
2821                 case ALGORITHM_RIGHT_SYMMETRIC_6:
2822                         if (i < sh->pd_idx)
2823                                 i += data_disks + 1;
2824                         i -= (sh->pd_idx + 1);
2825                         break;
2826                 case ALGORITHM_PARITY_0_6:
2827                         i -= 1;
2828                         break;
2829                 default:
2830                         BUG();
2831                 }
2832                 break;
2833         }
2834
2835         chunk_number = stripe * data_disks + i;
2836         r_sector = chunk_number * sectors_per_chunk + chunk_offset;
2837
2838         check = raid5_compute_sector(conf, r_sector,
2839                                      previous, &dummy1, &sh2);
2840         if (check != sh->sector || dummy1 != dd_idx || sh2.pd_idx != sh->pd_idx
2841                 || sh2.qd_idx != sh->qd_idx) {
2842                 printk(KERN_ERR "md/raid:%s: compute_blocknr: map not correct\n",
2843                        mdname(conf->mddev));
2844                 return 0;
2845         }
2846         return r_sector;
2847 }
2848
2849 static void
2850 schedule_reconstruction(struct stripe_head *sh, struct stripe_head_state *s,
2851                          int rcw, int expand)
2852 {
2853         int i, pd_idx = sh->pd_idx, qd_idx = sh->qd_idx, disks = sh->disks;
2854         struct r5conf *conf = sh->raid_conf;
2855         int level = conf->level;
2856
2857         if (rcw) {
2858
2859                 for (i = disks; i--; ) {
2860                         struct r5dev *dev = &sh->dev[i];
2861
2862                         if (dev->towrite) {
2863                                 set_bit(R5_LOCKED, &dev->flags);
2864                                 set_bit(R5_Wantdrain, &dev->flags);
2865                                 if (!expand)
2866                                         clear_bit(R5_UPTODATE, &dev->flags);
2867                                 s->locked++;
2868                         }
2869                 }
2870                 /* if we are not expanding this is a proper write request, and
2871                  * there will be bios with new data to be drained into the
2872                  * stripe cache
2873                  */
2874                 if (!expand) {
2875                         if (!s->locked)
2876                                 /* False alarm, nothing to do */
2877                                 return;
2878                         sh->reconstruct_state = reconstruct_state_drain_run;
2879                         set_bit(STRIPE_OP_BIODRAIN, &s->ops_request);
2880                 } else
2881                         sh->reconstruct_state = reconstruct_state_run;
2882
2883                 set_bit(STRIPE_OP_RECONSTRUCT, &s->ops_request);
2884
2885                 if (s->locked + conf->max_degraded == disks)
2886                         if (!test_and_set_bit(STRIPE_FULL_WRITE, &sh->state))
2887                                 atomic_inc(&conf->pending_full_writes);
2888         } else {
2889                 BUG_ON(!(test_bit(R5_UPTODATE, &sh->dev[pd_idx].flags) ||
2890                         test_bit(R5_Wantcompute, &sh->dev[pd_idx].flags)));
2891                 BUG_ON(level == 6 &&
2892                         (!(test_bit(R5_UPTODATE, &sh->dev[qd_idx].flags) ||
2893                            test_bit(R5_Wantcompute, &sh->dev[qd_idx].flags))));
2894
2895                 for (i = disks; i--; ) {
2896                         struct r5dev *dev = &sh->dev[i];
2897                         if (i == pd_idx || i == qd_idx)
2898                                 continue;
2899
2900                         if (dev->towrite &&
2901                             (test_bit(R5_UPTODATE, &dev->flags) ||
2902                              test_bit(R5_Wantcompute, &dev->flags))) {
2903                                 set_bit(R5_Wantdrain, &dev->flags);
2904                                 set_bit(R5_LOCKED, &dev->flags);
2905                                 clear_bit(R5_UPTODATE, &dev->flags);
2906                                 s->locked++;
2907                         }
2908                 }
2909                 if (!s->locked)
2910                         /* False alarm - nothing to do */
2911                         return;
2912                 sh->reconstruct_state = reconstruct_state_prexor_drain_run;
2913                 set_bit(STRIPE_OP_PREXOR, &s->ops_request);
2914                 set_bit(STRIPE_OP_BIODRAIN, &s->ops_request);
2915                 set_bit(STRIPE_OP_RECONSTRUCT, &s->ops_request);
2916         }
2917
2918         /* keep the parity disk(s) locked while asynchronous operations
2919          * are in flight
2920          */
2921         set_bit(R5_LOCKED, &sh->dev[pd_idx].flags);
2922         clear_bit(R5_UPTODATE, &sh->dev[pd_idx].flags);
2923         s->locked++;
2924
2925         if (level == 6) {
2926                 int qd_idx = sh->qd_idx;
2927                 struct r5dev *dev = &sh->dev[qd_idx];
2928
2929                 set_bit(R5_LOCKED, &dev->flags);
2930                 clear_bit(R5_UPTODATE, &dev->flags);
2931                 s->locked++;
2932         }
2933
2934         pr_debug("%s: stripe %llu locked: %d ops_request: %lx\n",
2935                 __func__, (unsigned long long)sh->sector,
2936                 s->locked, s->ops_request);
2937 }
2938
2939 /*
2940  * Each stripe/dev can have one or more bion attached.
2941  * toread/towrite point to the first in a chain.
2942  * The bi_next chain must be in order.
2943  */
2944 static int add_stripe_bio(struct stripe_head *sh, struct bio *bi, int dd_idx,
2945                           int forwrite, int previous)
2946 {
2947         struct bio **bip;
2948         struct r5conf *conf = sh->raid_conf;
2949         int firstwrite=0;
2950
2951         pr_debug("adding bi b#%llu to stripe s#%llu\n",
2952                 (unsigned long long)bi->bi_iter.bi_sector,
2953                 (unsigned long long)sh->sector);
2954
2955         /*
2956          * If several bio share a stripe. The bio bi_phys_segments acts as a
2957          * reference count to avoid race. The reference count should already be
2958          * increased before this function is called (for example, in
2959          * make_request()), so other bio sharing this stripe will not free the
2960          * stripe. If a stripe is owned by one stripe, the stripe lock will
2961          * protect it.
2962          */
2963         spin_lock_irq(&sh->stripe_lock);
2964         /* Don't allow new IO added to stripes in batch list */
2965         if (sh->batch_head)
2966                 goto overlap;
2967         if (forwrite) {
2968                 bip = &sh->dev[dd_idx].towrite;
2969                 if (*bip == NULL)
2970                         firstwrite = 1;
2971         } else
2972                 bip = &sh->dev[dd_idx].toread;
2973         while (*bip && (*bip)->bi_iter.bi_sector < bi->bi_iter.bi_sector) {
2974                 if (bio_end_sector(*bip) > bi->bi_iter.bi_sector)
2975                         goto overlap;
2976                 bip = & (*bip)->bi_next;
2977         }
2978         if (*bip && (*bip)->bi_iter.bi_sector < bio_end_sector(bi))
2979                 goto overlap;
2980
2981         if (!forwrite || previous)
2982                 clear_bit(STRIPE_BATCH_READY, &sh->state);
2983
2984         BUG_ON(*bip && bi->bi_next && (*bip) != bi->bi_next);
2985         if (*bip)
2986                 bi->bi_next = *bip;
2987         *bip = bi;
2988         raid5_inc_bi_active_stripes(bi);
2989
2990         if (forwrite) {
2991                 /* check if page is covered */
2992                 sector_t sector = sh->dev[dd_idx].sector;
2993                 for (bi=sh->dev[dd_idx].towrite;
2994                      sector < sh->dev[dd_idx].sector + STRIPE_SECTORS &&
2995                              bi && bi->bi_iter.bi_sector <= sector;
2996                      bi = r5_next_bio(bi, sh->dev[dd_idx].sector)) {
2997                         if (bio_end_sector(bi) >= sector)
2998                                 sector = bio_end_sector(bi);
2999                 }
3000                 if (sector >= sh->dev[dd_idx].sector + STRIPE_SECTORS)
3001                         if (!test_and_set_bit(R5_OVERWRITE, &sh->dev[dd_idx].flags))
3002                                 sh->overwrite_disks++;
3003         }
3004
3005         pr_debug("added bi b#%llu to stripe s#%llu, disk %d.\n",
3006                 (unsigned long long)(*bip)->bi_iter.bi_sector,
3007                 (unsigned long long)sh->sector, dd_idx);
3008
3009         if (conf->mddev->bitmap && firstwrite) {
3010                 /* Cannot hold spinlock over bitmap_startwrite,
3011                  * but must ensure this isn't added to a batch until
3012                  * we have added to the bitmap and set bm_seq.
3013                  * So set STRIPE_BITMAP_PENDING to prevent
3014                  * batching.
3015                  * If multiple add_stripe_bio() calls race here they
3016                  * much all set STRIPE_BITMAP_PENDING.  So only the first one
3017                  * to complete "bitmap_startwrite" gets to set
3018                  * STRIPE_BIT_DELAY.  This is important as once a stripe
3019                  * is added to a batch, STRIPE_BIT_DELAY cannot be changed
3020                  * any more.
3021                  */
3022                 set_bit(STRIPE_BITMAP_PENDING, &sh->state);
3023                 spin_unlock_irq(&sh->stripe_lock);
3024                 bitmap_startwrite(conf->mddev->bitmap, sh->sector,
3025                                   STRIPE_SECTORS, 0);
3026                 spin_lock_irq(&sh->stripe_lock);
3027                 clear_bit(STRIPE_BITMAP_PENDING, &sh->state);
3028                 if (!sh->batch_head) {
3029                         sh->bm_seq = conf->seq_flush+1;
3030                         set_bit(STRIPE_BIT_DELAY, &sh->state);
3031                 }
3032         }
3033         spin_unlock_irq(&sh->stripe_lock);
3034
3035         if (stripe_can_batch(sh))
3036                 stripe_add_to_batch_list(conf, sh);
3037         return 1;
3038
3039  overlap:
3040         set_bit(R5_Overlap, &sh->dev[dd_idx].flags);
3041         spin_unlock_irq(&sh->stripe_lock);
3042         return 0;
3043 }
3044
3045 static void end_reshape(struct r5conf *conf);
3046
3047 static void stripe_set_idx(sector_t stripe, struct r5conf *conf, int previous,
3048                             struct stripe_head *sh)
3049 {
3050         int sectors_per_chunk =
3051                 previous ? conf->prev_chunk_sectors : conf->chunk_sectors;
3052         int dd_idx;
3053         int chunk_offset = sector_div(stripe, sectors_per_chunk);
3054         int disks = previous ? conf->previous_raid_disks : conf->raid_disks;
3055
3056         raid5_compute_sector(conf,
3057                              stripe * (disks - conf->max_degraded)
3058                              *sectors_per_chunk + chunk_offset,
3059                              previous,
3060                              &dd_idx, sh);
3061 }
3062
3063 static void
3064 handle_failed_stripe(struct r5conf *conf, struct stripe_head *sh,
3065                                 struct stripe_head_state *s, int disks,
3066                                 struct bio_list *return_bi)
3067 {
3068         int i;
3069         BUG_ON(sh->batch_head);
3070         for (i = disks; i--; ) {
3071                 struct bio *bi;
3072                 int bitmap_end = 0;
3073
3074                 if (test_bit(R5_ReadError, &sh->dev[i].flags)) {
3075                         struct md_rdev *rdev;
3076                         rcu_read_lock();
3077                         rdev = rcu_dereference(conf->disks[i].rdev);
3078                         if (rdev && test_bit(In_sync, &rdev->flags))
3079                                 atomic_inc(&rdev->nr_pending);
3080                         else
3081                                 rdev = NULL;
3082                         rcu_read_unlock();
3083                         if (rdev) {
3084                                 if (!rdev_set_badblocks(
3085                                             rdev,
3086                                             sh->sector,
3087                                             STRIPE_SECTORS, 0))
3088                                         md_error(conf->mddev, rdev);
3089                                 rdev_dec_pending(rdev, conf->mddev);
3090                         }
3091                 }
3092                 spin_lock_irq(&sh->stripe_lock);
3093                 /* fail all writes first */
3094                 bi = sh->dev[i].towrite;
3095                 sh->dev[i].towrite = NULL;
3096                 sh->overwrite_disks = 0;
3097                 spin_unlock_irq(&sh->stripe_lock);
3098                 if (bi)
3099                         bitmap_end = 1;
3100
3101                 if (test_and_clear_bit(R5_Overlap, &sh->dev[i].flags))
3102                         wake_up(&conf->wait_for_overlap);
3103
3104                 while (bi && bi->bi_iter.bi_sector <
3105                         sh->dev[i].sector + STRIPE_SECTORS) {
3106                         struct bio *nextbi = r5_next_bio(bi, sh->dev[i].sector);
3107
3108                         bi->bi_error = -EIO;
3109                         if (!raid5_dec_bi_active_stripes(bi)) {
3110                                 md_write_end(conf->mddev);
3111                                 bio_list_add(return_bi, bi);
3112                         }
3113                         bi = nextbi;
3114                 }
3115                 if (bitmap_end)
3116                         bitmap_endwrite(conf->mddev->bitmap, sh->sector,
3117                                 STRIPE_SECTORS, 0, 0);
3118                 bitmap_end = 0;
3119                 /* and fail all 'written' */
3120                 bi = sh->dev[i].written;
3121                 sh->dev[i].written = NULL;
3122                 if (test_and_clear_bit(R5_SkipCopy, &sh->dev[i].flags)) {
3123                         WARN_ON(test_bit(R5_UPTODATE, &sh->dev[i].flags));
3124                         sh->dev[i].page = sh->dev[i].orig_page;
3125                 }
3126
3127                 if (bi) bitmap_end = 1;
3128                 while (bi && bi->bi_iter.bi_sector <
3129                        sh->dev[i].sector + STRIPE_SECTORS) {
3130                         struct bio *bi2 = r5_next_bio(bi, sh->dev[i].sector);
3131
3132                         bi->bi_error = -EIO;
3133                         if (!raid5_dec_bi_active_stripes(bi)) {
3134                                 md_write_end(conf->mddev);
3135                                 bio_list_add(return_bi, bi);
3136                         }
3137                         bi = bi2;
3138                 }
3139
3140                 /* fail any reads if this device is non-operational and
3141                  * the data has not reached the cache yet.
3142                  */
3143                 if (!test_bit(R5_Wantfill, &sh->dev[i].flags) &&
3144                     (!test_bit(R5_Insync, &sh->dev[i].flags) ||
3145                       test_bit(R5_ReadError, &sh->dev[i].flags))) {
3146                         spin_lock_irq(&sh->stripe_lock);
3147                         bi = sh->dev[i].toread;
3148                         sh->dev[i].toread = NULL;
3149                         spin_unlock_irq(&sh->stripe_lock);
3150                         if (test_and_clear_bit(R5_Overlap, &sh->dev[i].flags))
3151                                 wake_up(&conf->wait_for_overlap);
3152                         if (bi)
3153                                 s->to_read--;
3154                         while (bi && bi->bi_iter.bi_sector <
3155                                sh->dev[i].sector + STRIPE_SECTORS) {
3156                                 struct bio *nextbi =
3157                                         r5_next_bio(bi, sh->dev[i].sector);
3158
3159                                 bi->bi_error = -EIO;
3160                                 if (!raid5_dec_bi_active_stripes(bi))
3161                                         bio_list_add(return_bi, bi);
3162                                 bi = nextbi;
3163                         }
3164                 }
3165                 if (bitmap_end)